Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex e6d856b93e Add subagent work units across providers
Co-authored-by: codex <[email protected]>
2026-03-18 15:54:55 -07:00
Julius Marminge ef843d400e maybe fix codex subturns 2026-03-18 15:47:34 -07:00
Julius Marminge 654ca0da91 Backfill missing app settings defaults during decode
- add decoding defaults in `AppSettingsSchema` so older persisted settings load safely
- export shared `Schema.Literals` types for `EnvMode` and `TimestampFormat`
- add a regression test covering pre-new-key settings hydration
2026-03-18 14:17:23 -07:00
Julius Marminge aa66e08034 update adapter 2026-03-18 13:26:12 -07:00
Julius Marmingeandcodex 268d4f7cf8 Merge main and use source proposed plans in the sidebar
Co-authored-by: codex <[email protected]>
2026-03-18 13:25:17 -07:00
Utkarsh Patil 0de5742b04 fix: consume plans on implementation (#1133) 2026-03-18 13:09:57 -07:00
Julius Marminge 321251907a refactor storage 2026-03-18 11:00:07 -07:00
Julius Marminge d5c86c9af6 Merge branch 'main' into split-stack/claude-sibling 2026-03-18 10:18:13 -07:00
Utkarsh Patil b500a36a94 fix: implement button overflow (#1193) 2026-03-18 09:46:09 -07:00
Julius Marminge a75a9b427f Split Codex and Claude traits handling by model capabilities
- Add dedicated Claude traits picker with model-aware effort, thinking, and fast mode controls
- Treat Claude Ultrathink as a prompt keyword instead of session effort
- Normalize provider model options in composer flow and adapter, with tests for unsupported effort/thinking cases
2026-03-17 16:56:59 -07:00
MaskandJulius Marminge 1310045629 Give Agents access to Terminal output (#1032)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-17 15:56:51 -07:00
Seif Almotaz BellahandJulius Marminge 579a69eb77 feat: add configurable model for git text generation (#1171)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-17 15:33:36 -07:00
Guilherme Vieira 9ee8c4f543 fix(web): fix sidebar project drag clipping with variable-height items (#1176) 2026-03-17 15:31:25 -07:00
Julius Marminge 55560f5116 Use GitHub App token when checking out main in release workflow (#1175) 2026-03-17 14:55:27 -07:00
Julius Marminge f98679d217 Add Claude fast mode support across adapter and composer controls
- support `claudeAgent.fastMode` in shared/contracts, provider dispatch, and Claude adapter SDK settings
- gate fast mode to supported Claude models and restart/forward options in orchestration
- unify draft/UI fast mode state (not Codex-only) and add browser/server tests plus SDK probe
2026-03-17 14:36:35 -07:00
Julius Marminge 5c9cfcd4c3 Remove Ultrathink pill from composer header
- keep Ultrathink frame styling without extra wrapper padding toggles
- drop the inline Ultrathink badge row in ChatView
- clean up stray whitespace in ProviderService test
2026-03-17 14:11:26 -07:00
JustYanniccandClaude Opus 4.6 e6254a8451 feat: claude effort controls, ultrathink UI, and adapter robustness (#1146)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
2026-03-17 13:23:07 -07:00
Utkarsh Patil 3710ddb611 fix: fix menu copy (#1063) 2026-03-17 10:57:31 -07:00
0x1f99d 3fce14bbcf fix(web): restore pointer cursors for sidebar actions (#894) 2026-03-17 08:46:06 -07:00
James d430a0624b Add copy workspace path button to thread action menu (#1128) 2026-03-16 22:34:24 -07:00
Julius Marminge b04132d8c8 Use provider default model in orchestration integration seed
- derive `defaultModel` from `DEFAULT_MODEL_BY_PROVIDER` using harness provider
- replace hardcoded `gpt-5-codex` in seeded project and thread setup
2026-03-16 17:36:56 -07:00
Julius Marminge b577cb5326 Fix locked-thread model selection and provider fallback
- Use thread provider as the preferred provider during command handling
- Update `ProviderModelPicker` to show direct model choices when provider is locked
- Add browser tests for locked/unlocked picker behavior and widen browser test glob
2026-03-16 17:26:50 -07:00
Julius Marminge fc9660f238 Enforce provider-model consistency for thread turn starts
- Reject turn starts that request a provider switch from the thread-bound provider
- Reject models that do not belong to the thread provider and log start failures
- Add shared `inferProviderForModel` helper and tests; reuse it in web store inference
2026-03-16 17:09:38 -07:00
Julius Marminge b403ca3183 dont provide generated orchestration ids to native providerRefs 2026-03-16 16:09:50 -07:00
Julius Marminge f34dd0a91f Schema.is 2026-03-16 15:48:28 -07:00
Julius Marminge 33791cdfe5 align branding guide lines 2026-03-16 15:41:12 -07:00
Julius Marminge fdcb05d3f6 replace ad-hoc union for contract type 2026-03-16 12:16:24 -07:00
Julius Marmingeandcodex 2121682546 Improve Claude adapter tool streaming and health checks
- Map Claude reasoning deltas, streamed tool input JSON, and tool results into runtime item/content events
- Classify Agent/read-only Claude tools for correct approval request types
- Add Claude CLI provider health checks and auth-status parsing coverage

Co-authored-by: codex <[email protected]>
2026-03-16 12:14:27 -07:00
Julius Marminge d2b00e6550 Show Claude Code in provider picker and add Cursor placeholder
- Include Claude Code in available provider options in the picker
- Add Cursor as a disabled placeholder provider with icon mapping
- Update session-logic tests to assert provider availability and ordering
2026-03-16 11:11:57 -07:00
Julius Marminge e0facb03bd fix circular import 2026-03-16 11:06:26 -07:00
Julius Marminge 73152abe81 fmt 2026-03-16 11:03:31 -07:00
Julius Marminge c5bfff1583 unify start option union 2026-03-16 10:41:05 -07:00
132 changed files with 13700 additions and 2666 deletions

No files matched your search

+22 -2
View File
@@ -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"
+1
View File
@@ -17,3 +17,4 @@ release/
apps/web/.playwright
apps/web/playwright-report
apps/web/src/components/__screenshots__
.vitest-*
@@ -88,8 +88,8 @@ Update/add tests in `packages/contracts/src/*.test.ts` for:
Create:
1. `apps/server/src/provider/Services/ClaudeCodeAdapter.ts`
2. `apps/server/src/provider/Layers/ClaudeCodeAdapter.ts`
1. `apps/server/src/provider/Services/ClaudeAdapter.ts`
2. `apps/server/src/provider/Layers/ClaudeAdapter.ts`
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
@@ -279,7 +279,7 @@ Map orchestration stop/interrupt expectations onto SDK controls:
Update provider registry layer to include Claude:
1. add `claudeCode` -> `ClaudeCodeAdapter`
1. add `claudeCode` -> `ClaudeAdapter`
2. ensure `ProviderService.listProviderStatuses()` reports Claude availability
### 3.2 Persist provider binding
@@ -384,7 +384,7 @@ Cover:
### 6.2 Adapter layer tests
Add `ClaudeCodeAdapter.test.ts` covering:
Add `ClaudeAdapter.test.ts` covering:
1. session start
2. event mapping
+1 -1
View File
@@ -7,7 +7,7 @@
## Project Snapshot
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
+1 -1
View File
@@ -1,6 +1,6 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
## How to use
@@ -6,6 +6,7 @@ import { execFileSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ApprovalRequestId,
ProviderKind,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
@@ -205,7 +206,7 @@ export interface OrchestrationIntegrationHarness {
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: "codex" | "claudeCode";
readonly provider?: ProviderKind;
readonly realCodex?: boolean;
}
@@ -10,6 +10,7 @@ import {
ProviderTurnStartResult,
ThreadId,
TurnId,
ProviderKind,
} from "@t3tools/contracts";
import { Effect, Queue, Stream } from "effect";
@@ -35,7 +36,7 @@ export interface TestTurnResponse {
export type FixtureProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex" | "claudeCode";
readonly provider: ProviderKind;
readonly createdAt: string;
readonly threadId: string;
readonly turnId?: string | undefined;
@@ -177,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly provider: "codex" | "claudeCode";
readonly provider: ProviderKind;
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
@@ -197,7 +198,7 @@ export interface TestProviderAdapterHarness {
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: "codex" | "claudeCode";
readonly provider?: ProviderKind;
}
function nowIso(): string {
@@ -205,7 +206,7 @@ function nowIso(): string {
}
function sessionNotFound(
provider: "codex" | "claudeCode",
provider: ProviderKind,
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
@@ -215,7 +216,7 @@ function sessionNotFound(
}
function missingSessionEffect(
provider: "codex" | "claudeCode",
provider: ProviderKind,
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
@@ -5,9 +5,11 @@ import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
MessageId,
ProjectId,
ProviderKind,
ThreadId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
@@ -36,7 +38,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 = "codex" | "claudeCode";
type IntegrationProvider = ProviderKind;
function nowIso() {
return new Date().toISOString();
@@ -105,6 +107,8 @@ function withRealCodexHarness<A, E>(
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
Effect.gen(function* () {
const createdAt = nowIso();
const provider = harness.adapterHarness?.provider ?? "codex";
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
yield* harness.engine.dispatch({
type: "project.create",
@@ -112,7 +116,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModel: "gpt-5-codex",
defaultModel,
createdAt,
});
@@ -122,7 +126,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
model: "gpt-5-codex",
model: defaultModel,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -883,7 +887,7 @@ it.live(
),
);
it.live("starts a claudeCode session on first turn when provider is requested", () =>
it.live("starts a claudeAgent session on first turn when provider is requested", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
@@ -893,20 +897,20 @@ it.live("starts a claudeCode session on first turn when provider is requested",
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeCode"),
...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", "claudeCode"),
...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", "claudeCode"),
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -919,25 +923,25 @@ it.live("starts a claudeCode session on first turn when provider is requested",
commandId: "cmd-turn-start-claude-initial",
messageId: "msg-user-claude-initial",
text: "Use Claude",
provider: "claudeCode",
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeCode" &&
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, "claudeCode");
assert.equal(thread.session?.providerName, "claudeAgent");
}),
"claudeCode",
"claudeAgent",
),
);
it.live("recovers claudeCode sessions after provider stopAll using persisted resume state", () =>
it.live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
@@ -947,20 +951,20 @@ it.live("recovers claudeCode sessions after provider stopAll using persisted res
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeCode"),
...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", "claudeCode"),
...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", "claudeCode"),
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -973,7 +977,7 @@ it.live("recovers claudeCode sessions after provider stopAll using persisted res
commandId: "cmd-turn-start-claude-recover-1",
messageId: "msg-user-claude-recover-1",
text: "Before restart",
provider: "claudeCode",
provider: "claudeAgent",
});
yield* harness.waitForThread(
@@ -993,20 +997,20 @@ it.live("recovers claudeCode sessions after provider stopAll using persisted res
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeCode"),
...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", "claudeCode"),
...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", "claudeCode"),
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1029,20 +1033,20 @@ it.live("recovers claudeCode sessions after provider stopAll using persisted res
const recoveredThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeCode" &&
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, "claudeCode");
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
assert.equal(recoveredThread.session?.threadId, "thread-1");
}),
"claudeCode",
"claudeAgent",
),
);
it.live("forwards claudeCode approval responses to the provider session", () =>
it.live("forwards claudeAgent approval responses to the provider session", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
@@ -1052,13 +1056,13 @@ it.live("forwards claudeCode approval responses to the provider session", () =>
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeCode"),
...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", "claudeCode"),
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
@@ -1067,7 +1071,7 @@ it.live("forwards claudeCode approval responses to the provider session", () =>
},
{
type: "turn.completed",
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeCode"),
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1080,7 +1084,7 @@ it.live("forwards claudeCode approval responses to the provider session", () =>
commandId: "cmd-turn-start-claude-approval",
messageId: "msg-user-claude-approval",
text: "Need approval",
provider: "claudeCode",
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
@@ -1109,11 +1113,11 @@ it.live("forwards claudeCode approval responses to the provider session", () =>
);
assert.equal(approvalResponses[0]?.decision, "accept");
}),
"claudeCode",
"claudeAgent",
),
);
it.live("forwards thread.turn.interrupt to claudeCode provider sessions", () =>
it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
@@ -1123,20 +1127,20 @@ it.live("forwards thread.turn.interrupt to claudeCode provider sessions", () =>
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeCode"),
...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", "claudeCode"),
...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", "claudeCode"),
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1149,7 +1153,7 @@ it.live("forwards thread.turn.interrupt to claudeCode provider sessions", () =>
commandId: "cmd-turn-start-claude-interrupt",
messageId: "msg-user-claude-interrupt",
text: "Start long turn",
provider: "claudeCode",
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(
@@ -1175,11 +1179,11 @@ it.live("forwards thread.turn.interrupt to claudeCode provider sessions", () =>
);
assert.equal(interruptCalls.length, 1);
}),
"claudeCode",
"claudeAgent",
),
);
it.live("reverts claudeCode turns and rolls back provider conversation state", () =>
it.live("reverts claudeAgent turns and rolls back provider conversation state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
@@ -1189,20 +1193,20 @@ it.live("reverts claudeCode turns and rolls back provider conversation state", (
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeCode"),
...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", "claudeCode"),
...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", "claudeCode"),
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1219,7 +1223,7 @@ it.live("reverts claudeCode turns and rolls back provider conversation state", (
commandId: "cmd-turn-start-claude-revert-1",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
provider: "claudeCode",
provider: "claudeAgent",
});
yield* harness.waitForThread(
@@ -1232,20 +1236,20 @@ it.live("reverts claudeCode turns and rolls back provider conversation state", (
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeCode"),
...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", "claudeCode"),
...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", "claudeCode"),
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1269,7 +1273,7 @@ it.live("reverts claudeCode turns and rolls back provider conversation state", (
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.session?.providerName === "claudeCode",
entry.session?.providerName === "claudeAgent",
);
yield* harness.engine.dispatch({
@@ -1296,6 +1300,6 @@ it.live("reverts claudeCode turns and rolls back provider conversation state", (
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
"claudeCode",
"claudeAgent",
),
);
+1 -1
View File
@@ -22,7 +22,7 @@
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.76",
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@pierre/diffs": "^1.1.0-beta.16",
@@ -62,6 +62,7 @@ function makeSnapshot(input: {
messages: [],
activities: [],
proposedPlans: [],
workUnits: [],
checkpoints: [
{
turnId: TurnId.makeUnsafe("turn-1"),
@@ -37,6 +37,8 @@ function createSendTurnHarness() {
planType: null,
sparkEnabled: true,
},
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
};
const requireSession = vi
@@ -75,6 +77,8 @@ function createThreadControlHarness() {
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
};
const requireSession = vi
@@ -117,6 +121,8 @@ function createPendingUserInputHarness() {
},
],
]),
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
};
const requireSession = vi
@@ -135,6 +141,44 @@ function createPendingUserInputHarness() {
return { manager, context, requireSession, writeMessage, emitEvent };
}
function createCollabNotificationHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
provider: "codex",
status: "running",
threadId: asThreadId("thread_1"),
runtimeMode: "full-access",
model: "gpt-5.3-codex",
activeTurnId: "turn_parent",
resumeCursor: { threadId: "provider_parent" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
account: {
type: "unknown",
planType: null,
sparkEnabled: true,
},
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map<string, string>(),
collabReceiverItems: new Map<string, string>(),
nextRequestId: 1,
stopping: false,
};
const emitEvent = vi
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
.mockImplementation(() => {});
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, emitEvent, updateSession };
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
@@ -721,6 +765,8 @@ describe("respondToUserInput", () => {
},
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
};
type ApprovalRequestContext = {
session: typeof context.session;
@@ -748,6 +794,197 @@ describe("respondToUserInput", () => {
});
});
describe("collab child conversation routing", () => {
it("rewrites child notification turn ids onto the parent turn", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/agentMessage/delta",
params: {
threadId: "child_provider_1",
turnId: "turn_child_1",
itemId: "msg_child_1",
delta: "working",
},
});
expect(emitEvent).toHaveBeenLastCalledWith(
expect.objectContaining({
method: "item/agentMessage/delta",
turnId: "turn_parent",
itemId: "msg_child_1",
}),
);
});
it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => {
const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
updateSession.mockClear();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "turn/started",
params: {
threadId: "child_provider_1",
turn: { id: "turn_child_1" },
},
});
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "turn/completed",
params: {
threadId: "child_provider_1",
turn: { id: "turn_child_1", status: "completed" },
},
});
expect(emitEvent).not.toHaveBeenCalled();
expect(updateSession).not.toHaveBeenCalled();
});
it("rewrites child approval requests onto the parent turn", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
(
manager as unknown as {
handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
}
).handleServerRequest(context, {
id: 42,
method: "item/commandExecution/requestApproval",
params: {
threadId: "child_provider_1",
turnId: "turn_child_1",
itemId: "call_child_1",
command: "bun install",
},
});
expect(Array.from(context.pendingApprovals.values())[0]).toEqual(
expect.objectContaining({
turnId: "turn_parent",
itemId: "call_child_1",
}),
);
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
method: "item/commandExecution/requestApproval",
turnId: "turn_parent",
itemId: "call_child_1",
}),
);
});
it("rewrites child task notifications onto the parent collab item when no child item id exists", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "codex/event/task_started",
params: {
threadId: "child_provider_1",
msg: {
type: "task_started",
turn_id: "turn_child_1",
},
},
});
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
method: "codex/event/task_started",
turnId: "turn_parent",
itemId: "call_collab_1",
}),
);
});
});
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
it("keeps prior thread history when resuming with a changed runtime mode", async () => {
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
+117 -10
View File
@@ -70,6 +70,8 @@ interface CodexSessionContext {
pending: Map<PendingRequestKey, PendingRequest>;
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
collabReceiverTurns: Map<string, TurnId>;
collabReceiverItems: Map<string, ProviderItemId>;
nextRequestId: number;
stopping: boolean;
}
@@ -571,6 +573,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
nextRequestId: 1,
stopping: false,
};
@@ -732,6 +736,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
const context = this.requireSession(input.threadId);
context.collabReceiverTurns.clear();
context.collabReceiverItems.clear();
const turnInput: Array<
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
@@ -1121,7 +1127,18 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
context: CodexSessionContext,
notification: JsonRpcNotification,
): void {
const route = this.readRouteFields(notification.params);
const rawRoute = this.readRouteFields(notification.params);
this.rememberCollabReceiverTurns(context, notification.params, rawRoute.turnId);
const childParentTurnId = this.readChildParentTurnId(context, notification.params);
const childParentItemId = this.readChildParentItemId(context, notification.params);
const isChildConversation = childParentTurnId !== undefined;
const effectiveItemId = rawRoute.itemId ?? childParentItemId;
if (
isChildConversation &&
this.shouldSuppressChildConversationNotification(notification.method)
) {
return;
}
const textDelta =
notification.method === "item/agentMessage/delta"
? this.readString(notification.params, "delta")
@@ -1134,8 +1151,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: notification.method,
turnId: route.turnId,
itemId: route.itemId,
...((childParentTurnId ?? rawRoute.turnId)
? { turnId: childParentTurnId ?? rawRoute.turnId }
: {}),
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
textDelta,
payload: notification.params,
});
@@ -1151,6 +1170,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "turn/started") {
if (isChildConversation) {
return;
}
const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
this.updateSession(context, {
status: "running",
@@ -1160,6 +1182,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "turn/completed") {
if (isChildConversation) {
return;
}
context.collabReceiverTurns.clear();
context.collabReceiverItems.clear();
const turn = this.readObject(notification.params, "turn");
const status = this.readString(turn, "status");
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
@@ -1172,6 +1199,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "error") {
if (isChildConversation) {
return;
}
const message = this.readString(this.readObject(notification.params)?.error, "message");
const willRetry = this.readBoolean(notification.params, "willRetry");
@@ -1183,7 +1213,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
const route = this.readRouteFields(request.params);
const rawRoute = this.readRouteFields(request.params);
const childParentTurnId = this.readChildParentTurnId(context, request.params);
const childParentItemId = this.readChildParentItemId(context, request.params);
const effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
const effectiveItemId = rawRoute.itemId ?? childParentItemId;
const requestKind = this.requestKindForMethod(request.method);
let requestId: ApprovalRequestId | undefined;
if (requestKind) {
@@ -1199,8 +1233,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
: "item/fileChange/requestApproval",
requestKind,
threadId: context.session.threadId,
...(route.turnId ? { turnId: route.turnId } : {}),
...(route.itemId ? { itemId: route.itemId } : {}),
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
};
context.pendingApprovals.set(requestId, pendingRequest);
}
@@ -1211,8 +1245,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
requestId,
jsonRpcId: request.id,
threadId: context.session.threadId,
...(route.turnId ? { turnId: route.turnId } : {}),
...(route.itemId ? { itemId: route.itemId } : {}),
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
});
}
@@ -1223,8 +1257,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: request.method,
turnId: route.turnId,
itemId: route.itemId,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
requestId,
requestKind,
payload: request.params,
@@ -1451,6 +1485,79 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return route;
}
private readProviderConversationId(params: unknown): string | undefined {
return (
this.readString(params, "threadId") ??
this.readString(this.readObject(params, "thread"), "id") ??
this.readString(params, "conversationId")
);
}
private readChildParentTurnId(context: CodexSessionContext, params: unknown): TurnId | undefined {
const providerConversationId = this.readProviderConversationId(params);
if (!providerConversationId) {
return undefined;
}
return context.collabReceiverTurns.get(providerConversationId);
}
private readChildParentItemId(
context: CodexSessionContext,
params: unknown,
): ProviderItemId | undefined {
const providerConversationId = this.readProviderConversationId(params);
if (!providerConversationId) {
return undefined;
}
return context.collabReceiverItems.get(providerConversationId);
}
private rememberCollabReceiverTurns(
context: CodexSessionContext,
params: unknown,
parentTurnId: TurnId | undefined,
): void {
if (!parentTurnId) {
return;
}
const payload = this.readObject(params);
const item = this.readObject(payload, "item") ?? payload;
const itemType = this.readString(item, "type") ?? this.readString(item, "kind");
if (itemType !== "collabAgentToolCall") {
return;
}
const parentItemId = toProviderItemId(this.readString(item, "id"));
const receiverThreadIds =
this.readArray(item, "receiverThreadIds")
?.map((value) => (typeof value === "string" ? value : null))
.filter((value): value is string => value !== null) ?? [];
for (const receiverThreadId of receiverThreadIds) {
context.collabReceiverTurns.set(receiverThreadId, parentTurnId);
if (parentItemId) {
context.collabReceiverItems.set(receiverThreadId, parentItemId);
}
}
}
private shouldSuppressChildConversationNotification(method: string): boolean {
return (
method === "thread/started" ||
method === "thread/status/changed" ||
method === "thread/archived" ||
method === "thread/unarchived" ||
method === "thread/closed" ||
method === "thread/compacted" ||
method === "thread/name/updated" ||
method === "thread/tokenUsage/updated" ||
method === "turn/started" ||
method === "turn/completed" ||
method === "turn/aborted" ||
method === "turn/plan/updated" ||
method === "item/plan/delta"
);
}
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
const target =
key === undefined
@@ -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 {
+11 -2
View File
@@ -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 {
@@ -3,7 +3,7 @@ import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import type { ProviderKind, 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: "codex" | "claudeCode";
readonly provider: ProviderKind;
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -235,7 +235,7 @@ describe("CheckpointReactor", () => {
readonly projectWorkspaceRoot?: string;
readonly threadWorktreePath?: string | null;
readonly providerSessionCwd?: string;
readonly providerName?: "codex" | "claudeCode";
readonly providerName?: ProviderKind;
}) {
const cwd = createGitRepository();
tempDirs.push(cwd);
@@ -478,10 +478,10 @@ describe("CheckpointReactor", () => {
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
});
it("captures pre-turn and completion checkpoints for claudeCode runtime events", async () => {
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
providerName: "claudeCode",
providerName: "claudeAgent",
});
const createdAt = new Date().toISOString();
@@ -493,7 +493,7 @@ describe("CheckpointReactor", () => {
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeCode",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
@@ -506,7 +506,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
provider: "claudeCode",
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
@@ -520,7 +520,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"),
provider: "claudeCode",
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
@@ -854,8 +854,8 @@ describe("CheckpointReactor", () => {
).toBe(false);
});
it("executes provider revert and emits thread.reverted for claudeCode sessions", async () => {
const harness = await createHarness({ providerName: "claudeCode" });
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(
@@ -866,7 +866,7 @@ describe("CheckpointReactor", () => {
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeCode",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
@@ -89,6 +89,7 @@ const make = Effect.gen(function* () {
detail: input.detail,
},
turnId: null,
workUnitId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
@@ -113,6 +114,7 @@ const make = Effect.gen(function* () {
detail: input.detail,
},
turnId: input.turnId,
workUnitId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
@@ -313,6 +315,7 @@ const make = Effect.gen(function* () {
status: input.status,
},
turnId: input.turnId,
workUnitId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
@@ -7,6 +7,7 @@ import {
ProjectId,
ThreadId,
TurnId,
WorkUnitId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
@@ -175,6 +176,138 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("projects work units and activity work-unit links", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = new Date().toISOString();
yield* eventStore.append({
type: "thread.created",
eventId: EventId.makeUnsafe("evt-work-unit-thread"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-work-unit"),
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-work-unit-thread"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-work-unit-thread"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-work-unit"),
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread work unit",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
yield* eventStore.append({
type: "thread.work-unit-upserted",
eventId: EventId.makeUnsafe("evt-work-unit-upsert"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-work-unit"),
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-work-unit-upsert"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-work-unit-upsert"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-work-unit"),
workUnit: {
id: WorkUnitId.makeUnsafe("wu:thread-work-unit:turn:turn-1:root"),
turnId: TurnId.makeUnsafe("turn-1"),
parentWorkUnitId: null,
kind: "primary_agent",
state: "running",
title: "Primary agent",
detail: null,
spawnedByActivityId: null,
providerRefs: {
providerTurnId: "provider-turn-1",
},
startedAt: now,
updatedAt: now,
completedAt: null,
},
},
});
yield* eventStore.append({
type: "thread.activity-appended",
eventId: EventId.makeUnsafe("evt-work-unit-activity"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-work-unit"),
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-work-unit-activity"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-work-unit-activity"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-work-unit"),
activity: {
id: EventId.makeUnsafe("activity-work-unit"),
tone: "info",
kind: "task.progress",
summary: "Reasoning update",
payload: {
detail: "Looking around",
},
turnId: TurnId.makeUnsafe("turn-1"),
workUnitId: WorkUnitId.makeUnsafe("wu:thread-work-unit:turn:turn-1:root"),
createdAt: now,
},
},
});
yield* projectionPipeline.bootstrap;
const workUnitRows = yield* sql<{
readonly workUnitId: string;
readonly turnId: string;
readonly state: string;
readonly providerRefsJson: string | null;
}>`
SELECT
work_unit_id AS "workUnitId",
turn_id AS "turnId",
state,
provider_refs_json AS "providerRefsJson"
FROM projection_thread_work_units
WHERE thread_id = 'thread-work-unit'
`;
assert.deepEqual(workUnitRows, [
{
workUnitId: "wu:thread-work-unit:turn:turn-1:root",
turnId: "turn-1",
state: "running",
providerRefsJson: '{"providerTurnId":"provider-turn-1"}',
},
]);
const activityRows = yield* sql<{
readonly activityId: string;
readonly workUnitId: string | null;
}>`
SELECT
activity_id AS "activityId",
work_unit_id AS "workUnitId"
FROM projection_thread_activities
WHERE thread_id = 'thread-work-unit'
`;
assert.deepEqual(activityRows, [
{
activityId: "activity-work-unit",
workUnitId: "wu:thread-work-unit:turn:turn-1:root",
},
]);
}),
);
it.effect("stores message attachment references without mutating payloads", () =>
Effect.sync(() => fs.mkdtempSync(path.join(os.tmpdir(), "t3-projection-attachments-"))).pipe(
Effect.flatMap((stateDir) =>
@@ -1729,6 +1862,8 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
const threadId = ThreadId.makeUnsafe("thread-restart");
const turnId = TurnId.makeUnsafe("turn-restart");
const messageId = MessageId.makeUnsafe("message-restart");
const sourcePlanThreadId = ThreadId.makeUnsafe("thread-plan-source");
const sourcePlanId = "plan-source";
const turnStartedAt = "2026-02-26T14:00:00.000Z";
const sessionSetAt = "2026-02-26T14:00:05.000Z";
@@ -1749,6 +1884,10 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
payload: {
threadId,
messageId,
sourceProposedPlan: {
threadId: sourcePlanThreadId,
planId: sourcePlanId,
},
runtimeMode: "approval-required",
createdAt: turnStartedAt,
},
@@ -1800,11 +1939,15 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
return yield* sql<{
readonly turnId: string;
readonly userMessageId: string | null;
readonly sourceProposedPlanThreadId: string | null;
readonly sourceProposedPlanId: string | null;
readonly startedAt: string;
}>`
SELECT
turn_id AS "turnId",
pending_message_id AS "userMessageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId",
started_at AS "startedAt"
FROM projection_turns
WHERE turn_id = ${turnId}
@@ -1815,6 +1958,8 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
{
turnId: "turn-restart",
userMessageId: "message-restart",
sourceProposedPlanThreadId: "thread-plan-source",
sourceProposedPlanId: "plan-source",
startedAt: turnStartedAt,
},
]);
@@ -22,6 +22,10 @@ import {
type ProjectionThreadProposedPlan,
ProjectionThreadProposedPlanRepository,
} from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
import {
type ProjectionThreadWorkUnit,
ProjectionThreadWorkUnitRepository,
} from "../../persistence/Services/ProjectionThreadWorkUnits.ts";
import { ProjectionThreadSessionRepository } from "../../persistence/Services/ProjectionThreadSessions.ts";
import {
type ProjectionTurn,
@@ -34,6 +38,7 @@ import { ProjectionStateRepositoryLive } from "../../persistence/Layers/Projecti
import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts";
import { ProjectionThreadWorkUnitRepositoryLive } from "../../persistence/Layers/ProjectionThreadWorkUnits.ts";
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
@@ -55,6 +60,7 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
threadMessages: "projection.thread-messages",
threadProposedPlans: "projection.thread-proposed-plans",
threadActivities: "projection.thread-activities",
threadWorkUnits: "projection.thread-work-units",
threadSessions: "projection.thread-sessions",
threadTurns: "projection.thread-turns",
checkpoints: "projection.checkpoints",
@@ -214,6 +220,28 @@ function retainProjectionProposedPlansAfterRevert(
);
}
function retainProjectionWorkUnitsAfterRevert(
workUnits: ReadonlyArray<ProjectionThreadWorkUnit>,
turns: ReadonlyArray<ProjectionTurn>,
turnCount: number,
): ReadonlyArray<ProjectionThreadWorkUnit> {
const retainedTurnIds = new Set<string>(
turns
.filter(
(turn) =>
turn.turnId !== null &&
turn.checkpointTurnCount !== null &&
turn.checkpointTurnCount <= turnCount,
)
.flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])),
);
const retained = workUnits.filter((workUnit) => retainedTurnIds.has(workUnit.turnId));
const retainedIds = new Set(retained.map((workUnit) => workUnit.workUnitId));
return retained.filter(
(workUnit) => workUnit.parentWorkUnitId === null || retainedIds.has(workUnit.parentWorkUnitId),
);
}
function collectThreadAttachmentRelativePaths(
threadId: string,
messages: ReadonlyArray<ProjectionThreadMessage>,
@@ -346,6 +374,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
const projectionThreadWorkUnitRepository = yield* ProjectionThreadWorkUnitRepository;
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
@@ -653,6 +682,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
threadId: event.payload.threadId,
turnId: event.payload.proposedPlan.turnId,
planMarkdown: event.payload.proposedPlan.planMarkdown,
implementedAt: event.payload.proposedPlan.implementedAt,
implementationThreadId: event.payload.proposedPlan.implementationThreadId,
createdAt: event.payload.proposedPlan.createdAt,
updatedAt: event.payload.proposedPlan.updatedAt,
});
@@ -703,6 +734,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
activityId: event.payload.activity.id,
threadId: event.payload.threadId,
turnId: event.payload.activity.turnId,
workUnitId: event.payload.activity.workUnitId,
tone: event.payload.activity.tone,
kind: event.payload.activity.kind,
summary: event.payload.activity.summary,
@@ -746,6 +778,64 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
});
const applyThreadWorkUnitsProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
) =>
Effect.gen(function* () {
switch (event.type) {
case "thread.work-unit-upserted":
yield* projectionThreadWorkUnitRepository.upsert({
workUnitId: event.payload.workUnit.id,
threadId: event.payload.threadId,
turnId: event.payload.workUnit.turnId,
parentWorkUnitId: event.payload.workUnit.parentWorkUnitId,
kind: event.payload.workUnit.kind,
state: event.payload.workUnit.state,
title: event.payload.workUnit.title,
detail: event.payload.workUnit.detail,
spawnedByActivityId: event.payload.workUnit.spawnedByActivityId,
...(event.payload.workUnit.providerRefs !== undefined
? { providerRefs: event.payload.workUnit.providerRefs }
: {}),
startedAt: event.payload.workUnit.startedAt,
updatedAt: event.payload.workUnit.updatedAt,
completedAt: event.payload.workUnit.completedAt,
});
return;
case "thread.reverted": {
const existingRows = yield* projectionThreadWorkUnitRepository.listByThreadId({
threadId: event.payload.threadId,
});
if (existingRows.length === 0) {
return;
}
const existingTurns = yield* projectionTurnRepository.listByThreadId({
threadId: event.payload.threadId,
});
const keptRows = retainProjectionWorkUnitsAfterRevert(
existingRows,
existingTurns,
event.payload.turnCount,
);
if (keptRows.length === existingRows.length) {
return;
}
yield* projectionThreadWorkUnitRepository.deleteByThreadId({
threadId: event.payload.threadId,
});
yield* Effect.forEach(keptRows, projectionThreadWorkUnitRepository.upsert, {
concurrency: 1,
}).pipe(Effect.asVoid);
return;
}
default:
return;
}
});
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
@@ -775,6 +865,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
yield* projectionTurnRepository.replacePendingTurnStart({
threadId: event.payload.threadId,
messageId: event.payload.messageId,
sourceProposedPlanThreadId: event.payload.sourceProposedPlan?.threadId ?? null,
sourceProposedPlanId: event.payload.sourceProposedPlan?.planId ?? null,
requestedAt: event.payload.createdAt,
});
return;
@@ -804,6 +896,16 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
pendingMessageId:
existingTurn.value.pendingMessageId ??
(Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null),
sourceProposedPlanThreadId:
existingTurn.value.sourceProposedPlanThreadId ??
(Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanThreadId
: null),
sourceProposedPlanId:
existingTurn.value.sourceProposedPlanId ??
(Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanId
: null),
startedAt:
existingTurn.value.startedAt ??
(Option.isSome(pendingTurnStart)
@@ -822,6 +924,12 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
pendingMessageId: Option.isSome(pendingTurnStart)
? pendingTurnStart.value.messageId
: null,
sourceProposedPlanThreadId: Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanThreadId
: null,
sourceProposedPlanId: Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanId
: null,
assistantMessageId: null,
state: "running",
requestedAt: Option.isSome(pendingTurnStart)
@@ -875,6 +983,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
turnId: event.payload.turnId,
threadId: event.payload.threadId,
pendingMessageId: null,
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.messageId,
state: event.payload.streaming ? "running" : "completed",
requestedAt: event.payload.createdAt,
@@ -910,6 +1020,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
turnId: event.payload.turnId,
threadId: event.payload.threadId,
pendingMessageId: null,
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: null,
state: "interrupted",
requestedAt: event.payload.createdAt,
@@ -954,6 +1066,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
turnId: event.payload.turnId,
threadId: event.payload.threadId,
pendingMessageId: null,
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.assistantMessageId,
state: nextState,
requestedAt: event.payload.completedAt,
@@ -1108,6 +1222,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
apply: applyThreadActivitiesProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadWorkUnits,
apply: applyThreadWorkUnitsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
apply: applyThreadSessionsProjection,
@@ -1225,6 +1343,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),
Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
Layer.provideMerge(ProjectionThreadWorkUnitRepositoryLive),
Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
Layer.provideMerge(ProjectionTurnRepositoryLive),
Layer.provideMerge(ProjectionPendingApprovalRepositoryLive),
@@ -1,4 +1,12 @@
import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import {
CheckpointRef,
EventId,
MessageId,
ProjectId,
ThreadId,
TurnId,
WorkUnitId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -13,6 +21,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
const asWorkUnitId = (value: string): WorkUnitId => WorkUnitId.makeUnsafe(value);
const projectionSnapshotLayer = it.layer(
OrchestrationProjectionSnapshotQueryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
@@ -26,6 +35,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_state`;
yield* sql`DELETE FROM projection_thread_proposed_plans`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`
@@ -101,11 +111,35 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
)
`;
yield* sql`
INSERT INTO projection_thread_proposed_plans (
plan_id,
thread_id,
turn_id,
plan_markdown,
implemented_at,
implementation_thread_id,
created_at,
updated_at
)
VALUES (
'plan-1',
'thread-1',
'turn-1',
'# Ship it',
'2026-02-24T00:00:05.500Z',
'thread-2',
'2026-02-24T00:00:05.000Z',
'2026-02-24T00:00:05.500Z'
)
`;
yield* sql`
INSERT INTO projection_thread_activities (
activity_id,
thread_id,
turn_id,
work_unit_id,
tone,
kind,
summary,
@@ -116,6 +150,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'activity-1',
'thread-1',
'turn-1',
'wu:thread-1:turn:turn-1:root',
'info',
'runtime.note',
'provider started',
@@ -124,6 +159,39 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
)
`;
yield* sql`
INSERT INTO projection_thread_work_units (
work_unit_id,
thread_id,
turn_id,
parent_work_unit_id,
kind,
state,
title,
detail,
spawned_by_activity_id,
provider_refs_json,
started_at,
updated_at,
completed_at
)
VALUES (
'wu:thread-1:turn:turn-1:root',
'thread-1',
'turn-1',
NULL,
'primary_agent',
'completed',
'Primary agent',
NULL,
NULL,
'{"providerTurnId":"provider-turn-1"}',
'2026-02-24T00:00:08.000Z',
'2026-02-24T00:00:08.000Z',
'2026-02-24T00:00:08.000Z'
)
`;
yield* sql`
INSERT INTO projection_thread_sessions (
thread_id,
@@ -154,6 +222,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
@@ -168,6 +238,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'thread-1',
'turn-1',
NULL,
'thread-1',
'plan-1',
'message-1',
'completed',
'2026-02-24T00:00:08.000Z',
@@ -238,6 +310,10 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
startedAt: "2026-02-24T00:00:08.000Z",
completedAt: "2026-02-24T00:00:08.000Z",
assistantMessageId: asMessageId("message-1"),
sourceProposedPlan: {
threadId: ThreadId.makeUnsafe("thread-1"),
planId: "plan-1",
},
},
createdAt: "2026-02-24T00:00:02.000Z",
updatedAt: "2026-02-24T00:00:03.000Z",
@@ -253,7 +329,17 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
updatedAt: "2026-02-24T00:00:05.000Z",
},
],
proposedPlans: [],
proposedPlans: [
{
id: "plan-1",
turnId: asTurnId("turn-1"),
planMarkdown: "# Ship it",
implementedAt: "2026-02-24T00:00:05.500Z",
implementationThreadId: ThreadId.makeUnsafe("thread-2"),
createdAt: "2026-02-24T00:00:05.000Z",
updatedAt: "2026-02-24T00:00:05.500Z",
},
],
activities: [
{
id: asEventId("activity-1"),
@@ -262,9 +348,28 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
summary: "provider started",
payload: { stage: "start" },
turnId: asTurnId("turn-1"),
workUnitId: asWorkUnitId("wu:thread-1:turn:turn-1:root"),
createdAt: "2026-02-24T00:00:06.000Z",
},
],
workUnits: [
{
id: asWorkUnitId("wu:thread-1:turn:turn-1:root"),
turnId: asTurnId("turn-1"),
parentWorkUnitId: null,
kind: "primary_agent",
state: "completed",
title: "Primary agent",
detail: null,
spawnedByActivityId: null,
providerRefs: {
providerTurnId: "provider-turn-1",
},
startedAt: "2026-02-24T00:00:08.000Z",
updatedAt: "2026-02-24T00:00:08.000Z",
completedAt: "2026-02-24T00:00:08.000Z",
},
],
checkpoints: [
{
turnId: asTurnId("turn-1"),
@@ -4,8 +4,10 @@ import {
MessageId,
NonNegativeInt,
OrchestrationCheckpointFile,
OrchestrationProposedPlanId,
OrchestrationReadModel,
ProjectScript,
ThreadId,
TurnId,
type OrchestrationCheckpointSummary,
type OrchestrationLatestTurn,
@@ -15,6 +17,7 @@ import {
type OrchestrationSession,
type OrchestrationThread,
type OrchestrationThreadActivity,
type OrchestrationWorkUnit,
} from "@t3tools/contracts";
import { Effect, Layer, Schema, Struct } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -32,6 +35,7 @@ import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionThreadMessages.ts";
import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
import { ProjectionThreadWorkUnit } from "../../persistence/Services/ProjectionThreadWorkUnits.ts";
import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
@@ -60,6 +64,13 @@ const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
sequence: Schema.NullOr(NonNegativeInt),
}),
);
const ProjectionThreadWorkUnitDbRowSchema = ProjectionThreadWorkUnit.mapFields(
Struct.assign({
providerRefs: Schema.NullOr(
Schema.fromJsonString(ProjectionThreadWorkUnit.fields.providerRefs),
),
}),
);
const ProjectionThreadSessionDbRowSchema = ProjectionThreadSession;
const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
Struct.assign({
@@ -74,6 +85,8 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
startedAt: Schema.NullOr(IsoDateTime),
completedAt: Schema.NullOr(IsoDateTime),
assistantMessageId: Schema.NullOr(MessageId),
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
});
const ProjectionStateDbRowSchema = ProjectionState;
@@ -83,6 +96,7 @@ const REQUIRED_SNAPSHOT_PROJECTORS = [
ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
ORCHESTRATION_PROJECTOR_NAMES.threadWorkUnits,
ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
] as const;
@@ -200,6 +214,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
plan_markdown AS "planMarkdown",
implemented_at AS "implementedAt",
implementation_thread_id AS "implementationThreadId",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projection_thread_proposed_plans
@@ -216,6 +232,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
work_unit_id AS "workUnitId",
tone,
kind,
summary,
@@ -232,6 +249,30 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listThreadWorkUnitRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadWorkUnitDbRowSchema,
execute: () =>
sql`
SELECT
work_unit_id AS "workUnitId",
thread_id AS "threadId",
turn_id AS "turnId",
parent_work_unit_id AS "parentWorkUnitId",
kind,
state,
title,
detail,
spawned_by_activity_id AS "spawnedByActivityId",
provider_refs_json AS "providerRefs",
started_at AS "startedAt",
updated_at AS "updatedAt",
completed_at AS "completedAt"
FROM projection_thread_work_units
ORDER BY thread_id ASC, started_at ASC, work_unit_id ASC
`,
});
const listThreadSessionRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadSessionDbRowSchema,
@@ -284,7 +325,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
requested_at AS "requestedAt",
started_at AS "startedAt",
completed_at AS "completedAt",
assistant_message_id AS "assistantMessageId"
assistant_message_id AS "assistantMessageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId"
FROM projection_turns
WHERE turn_id IS NOT NULL
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
@@ -314,6 +357,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
messageRows,
proposedPlanRows,
activityRows,
workUnitRows,
sessionRows,
checkpointRows,
latestTurnRows,
@@ -359,6 +403,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listThreadWorkUnitRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getSnapshot:listThreadWorkUnits:query",
"ProjectionSnapshotQuery.getSnapshot:listThreadWorkUnits:decodeRows",
),
),
),
listThreadSessionRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -396,6 +448,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
const workUnitsByThread = new Map<string, Array<OrchestrationWorkUnit>>();
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
const sessionsByThread = new Map<string, OrchestrationSession>();
const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
@@ -435,6 +488,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
id: row.planId,
turnId: row.turnId,
planMarkdown: row.planMarkdown,
implementedAt: row.implementedAt,
implementationThreadId: row.implementationThreadId,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
});
@@ -451,12 +506,33 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
workUnitId: row.workUnitId,
...(row.sequence !== null ? { sequence: row.sequence } : {}),
createdAt: row.createdAt,
});
activitiesByThread.set(row.threadId, threadActivities);
}
for (const row of workUnitRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
const threadWorkUnits = workUnitsByThread.get(row.threadId) ?? [];
threadWorkUnits.push({
id: row.workUnitId,
turnId: row.turnId,
parentWorkUnitId: row.parentWorkUnitId,
kind: row.kind,
state: row.state,
title: row.title,
detail: row.detail,
spawnedByActivityId: row.spawnedByActivityId,
...(row.providerRefs !== null ? { providerRefs: row.providerRefs } : {}),
startedAt: row.startedAt,
updatedAt: row.updatedAt,
completedAt: row.completedAt,
});
workUnitsByThread.set(row.threadId, threadWorkUnits);
}
for (const row of checkpointRows) {
updatedAt = maxIso(updatedAt, row.completedAt);
const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? [];
@@ -497,6 +573,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
startedAt: row.startedAt,
completedAt: row.completedAt,
assistantMessageId: row.assistantMessageId,
...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null
? {
sourceProposedPlan: {
threadId: row.sourceProposedPlanThreadId,
planId: row.sourceProposedPlanId,
},
}
: {}),
});
}
@@ -540,6 +624,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
workUnits: workUnitsByThread.get(row.threadId) ?? [],
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
}));
@@ -83,9 +83,13 @@ describe("ProviderCommandReactor", () => {
createdStateDirs.clear();
});
async function createHarness(input?: { readonly stateDir?: string }) {
async function createHarness(input?: {
readonly stateDir?: string;
readonly threadModel?: string;
}) {
const now = new Date().toISOString();
const stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
const threadModel = input?.threadModel ?? "gpt-5-codex";
createdStateDirs.add(stateDir);
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
let nextSessionIndex = 1;
@@ -96,7 +100,7 @@ describe("ProviderCommandReactor", () => {
typeof input === "object" &&
input !== null &&
"provider" in input &&
(input.provider === "codex" || input.provider === "claudeCode")
(input.provider === "codex" || input.provider === "claudeAgent")
? input.provider
: "codex";
const resumeCursor =
@@ -228,7 +232,7 @@ describe("ProviderCommandReactor", () => {
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot: "/tmp/provider-project",
defaultModel: "gpt-5-codex",
defaultModel: threadModel,
createdAt: now,
}),
);
@@ -239,7 +243,7 @@ describe("ProviderCommandReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
model: threadModel,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -351,6 +355,106 @@ describe("ProviderCommandReactor", () => {
});
});
it("forwards claude effort options through session start and turn send", async () => {
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort"),
role: "user",
text: "hello with effort",
attachments: [],
},
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
});
});
it("forwards claude fast mode options through session start and turn send", async () => {
const harness = await createHarness({ threadModel: "claude-opus-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-fast-mode"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-fast-mode"),
role: "user",
text: "hello with fast mode",
attachments: [],
},
provider: "claudeAgent",
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "claudeAgent",
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
});
});
it("forwards plan interaction mode to the provider turn request", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -389,7 +493,7 @@ describe("ProviderCommandReactor", () => {
});
});
it("starts first turn with requested provider when provider is specified", async () => {
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -404,26 +508,85 @@ describe("ProviderCommandReactor", () => {
text: "hello claude",
attachments: [],
},
provider: "claudeCode",
provider: "claudeAgent",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "claudeCode",
cwd: "/tmp/provider-project",
model: "gpt-5-codex",
runtimeMode: "approval-required",
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?.providerName).toBe("claudeCode");
expect(thread?.session?.threadId).toBe("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 () => {
@@ -472,6 +635,73 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("restarts claude sessions when claude effort changes", async () => {
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort-1"),
role: "user",
text: "first claude turn",
attachments: [],
},
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "medium",
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort-2"),
role: "user",
text: "second claude turn",
attachments: [],
},
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
provider: "claudeAgent",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
});
});
it("restarts the provider session when runtime mode is updated on the thread", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -559,7 +789,7 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("switches provider by restarting the session when turn request provider changes", async () => {
it("rejects provider changes after a thread is already bound to a session provider", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -594,29 +824,40 @@ describe("ProviderCommandReactor", () => {
text: "second",
attachments: [],
},
provider: "claudeCode",
provider: "claudeAgent",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
provider: "claudeCode",
runtimeMode: "approval-required",
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[1]?.[1]).not.toHaveProperty("resumeCursor");
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("claudeCode");
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 () => {
@@ -856,6 +1097,7 @@ describe("ProviderCommandReactor", () => {
requestKind: "command",
},
turnId: null,
workUnitId: null,
createdAt: now,
},
createdAt: now,
@@ -1,10 +1,11 @@
import {
type ChatAttachment,
CommandId,
DEFAULT_GIT_TEXT_GENERATION_MODEL,
EventId,
type OrchestrationEvent,
type ProviderModelOptions,
type ProviderKind,
ProviderKind,
type ProviderStartOptions,
type OrchestrationSession,
ThreadId,
@@ -25,6 +26,7 @@ import {
ProviderCommandReactor,
type ProviderCommandReactorShape,
} from "../Services/ProviderCommandReactor.ts";
import { inferProviderForModel } from "@t3tools/shared/model";
type ProviderIntentEvent = Extract<
OrchestrationEvent,
@@ -74,6 +76,11 @@ const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
const WORKTREE_BRANCH_PREFIX = "t3code";
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
const sameModelOptions = (
left: ProviderModelOptions | undefined,
right: ProviderModelOptions | undefined,
): boolean => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
@@ -136,6 +143,7 @@ const make = Effect.gen(function* () {
);
const threadProviderOptions = new Map<string, ProviderStartOptions>();
const threadModelOptions = new Map<string, ProviderModelOptions>();
const appendProviderFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -165,6 +173,7 @@ const make = Effect.gen(function* () {
...(input.requestId ? { requestId: input.requestId } : {}),
},
turnId: input.turnId,
workUnitId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
@@ -205,11 +214,30 @@ const make = Effect.gen(function* () {
}
const desiredRuntimeMode = thread.runtimeMode;
const currentProvider: ProviderKind | undefined =
thread.session?.providerName === "codex" || thread.session?.providerName === "claudeCode"
? thread.session.providerName
: undefined;
const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
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 desiredModel = options?.model ?? thread.model;
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
@@ -269,13 +297,23 @@ const make = Effect.gen(function* () {
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
const previousModelOptions = threadModelOptions.get(threadId);
const shouldRestartForModelOptionsChange =
currentProvider === "claudeAgent" &&
options?.modelOptions !== undefined &&
!sameModelOptions(previousModelOptions, options.modelOptions);
if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {
if (
!runtimeModeChanged &&
!providerChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelOptionsChange
) {
return existingSessionThreadId;
}
const resumeCursor =
providerChanged || shouldRestartForModelChange
providerChanged || shouldRestartForModelChange || shouldRestartForModelOptionsChange
? undefined
: (activeSession?.resumeCursor ?? undefined);
yield* Effect.logInfo("provider command reactor restarting provider session", {
@@ -289,6 +327,7 @@ const make = Effect.gen(function* () {
providerChanged,
modelChanged,
shouldRestartForModelChange,
shouldRestartForModelOptionsChange,
hasResumeCursor: resumeCursor !== undefined,
});
const restartedSession = yield* startProviderSession({
@@ -328,15 +367,18 @@ const make = Effect.gen(function* () {
if (!thread) {
return;
}
if (input.providerOptions !== undefined) {
threadProviderOptions.set(input.threadId, input.providerOptions);
}
yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.provider !== undefined ? { provider: input.provider } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
});
if (input.providerOptions !== undefined) {
threadProviderOptions.set(input.threadId, input.providerOptions);
}
if (input.modelOptions !== undefined) {
threadModelOptions.set(input.threadId, input.modelOptions);
}
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
const activeSession = yield* providerService
@@ -393,6 +435,7 @@ const make = Effect.gen(function* () {
cwd,
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
})
.pipe(
Effect.catch((error) =>
@@ -477,7 +520,18 @@ const make = Effect.gen(function* () {
: {}),
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
});
}).pipe(
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
}),
),
);
});
const processTurnInterruptRequested = Effect.fnUntraced(function* (
@@ -626,13 +680,13 @@ const make = Effect.gen(function* () {
return;
}
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
yield* ensureSessionForThread(
event.payload.threadId,
event.occurredAt,
cachedProviderOptions !== undefined
const cachedModelOptions = threadModelOptions.get(event.payload.threadId);
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
...(cachedProviderOptions !== undefined
? { providerOptions: cachedProviderOptions }
: undefined,
);
: {}),
...(cachedModelOptions !== undefined ? { modelOptions: cachedModelOptions } : {}),
});
return;
}
case "thread.turn-start-requested":
@@ -2,7 +2,12 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { OrchestrationReadModel, ProviderRuntimeEvent } from "@t3tools/contracts";
import type {
OrchestrationReadModel,
ProviderKind,
ProviderRuntimeEvent,
ProviderSession,
} from "@t3tools/contracts";
import {
ApprovalRequestId,
CommandId,
@@ -45,7 +50,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex" | "claudeCode";
readonly provider: ProviderKind;
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -57,6 +62,7 @@ type LegacyProviderRuntimeEvent = {
function createProviderServiceHarness() {
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
const runtimeSessions: ProviderSession[] = [];
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
const service: ProviderServiceShape = {
@@ -66,12 +72,21 @@ function createProviderServiceHarness() {
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession: () => unsupported(),
listSessions: () => Effect.succeed([]),
listSessions: () => Effect.succeed([...runtimeSessions]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation: () => unsupported(),
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
};
const setSession = (session: ProviderSession): void => {
const existingIndex = runtimeSessions.findIndex((entry) => entry.threadId === session.threadId);
if (existingIndex >= 0) {
runtimeSessions[existingIndex] = session;
return;
}
runtimeSessions.push(session);
};
const emit = (event: LegacyProviderRuntimeEvent): void => {
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
};
@@ -79,6 +94,7 @@ function createProviderServiceHarness() {
return {
service,
emit,
setSession,
};
}
@@ -86,11 +102,12 @@ async function waitForThread(
engine: OrchestrationEngineShape,
predicate: (thread: ProviderRuntimeTestThread) => boolean,
timeoutMs = 2000,
threadId: ThreadId = asThreadId("thread-1"),
) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<ProviderRuntimeTestThread> => {
const readModel = await Effect.runPromise(engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === threadId);
if (thread && predicate(thread)) {
return thread;
}
@@ -108,6 +125,7 @@ type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number]
type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number];
type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number];
type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number];
type ProviderRuntimeTestWorkUnit = ProviderRuntimeTestThread["workUnits"][number];
type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number];
describe("ProviderRuntimeIngestion", () => {
@@ -150,6 +168,7 @@ describe("ProviderRuntimeIngestion", () => {
);
const layer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
@@ -205,10 +224,19 @@ describe("ProviderRuntimeIngestion", () => {
createdAt,
}),
);
provider.setSession({
provider: "codex",
status: "ready",
runtimeMode: "approval-required",
threadId: ThreadId.makeUnsafe("thread-1"),
createdAt,
updatedAt: createdAt,
});
return {
engine,
emit: provider.emit,
setProviderSession: provider.setSession,
drain,
};
}
@@ -414,7 +442,7 @@ describe("ProviderRuntimeIngestion", () => {
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeCode",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: seededAt,
@@ -427,7 +455,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-claude-placeholder"),
provider: "claudeCode",
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
@@ -443,7 +471,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-claude-placeholder"),
provider: "claudeCode",
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
@@ -682,6 +710,496 @@ describe("ProviderRuntimeIngestion", () => {
);
});
it("marks the source proposed plan implemented only after the target turn starts", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
const targetThreadId = asThreadId("thread-implement");
const sourceTurnId = asTurnId("turn-plan-source");
const targetTurnId = asTurnId("turn-plan-implement");
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target"),
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-target"),
threadId: targetThreadId,
session: {
threadId: targetThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
harness.setProviderSession({
provider: "codex",
status: "ready",
runtimeMode: "approval-required",
threadId: targetThreadId,
createdAt,
updatedAt: createdAt,
activeTurnId: targetTurnId,
});
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed"),
provider: "codex",
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
payload: {
planMarkdown: "# Source plan",
},
});
const sourceThreadWithPlan = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
proposedPlan.implementedAt === null,
),
2_000,
sourceThreadId,
);
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) =>
entry.id === "plan:thread-plan:turn:turn-plan-source",
);
expect(sourcePlan).toBeDefined();
if (!sourcePlan) {
throw new Error("Expected source plan to exist.");
}
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target"),
threadId: targetThreadId,
message: {
messageId: asMessageId("msg-plan-target"),
role: "user",
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
attachments: [],
},
sourceProposedPlan: {
threadId: sourceThreadId,
planId: sourcePlan.id,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
}),
);
const sourceThreadBeforeStart = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === sourcePlan.id && proposedPlan.implementedAt === null,
),
2_000,
sourceThreadId,
);
expect(
sourceThreadBeforeStart.proposedPlans.find((entry) => entry.id === sourcePlan.id),
).toMatchObject({
implementedAt: null,
implementationThreadId: null,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-plan-target-started"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: targetTurnId,
});
const sourceThreadAfterStart = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === sourcePlan.id &&
proposedPlan.implementedAt !== null &&
proposedPlan.implementationThreadId === targetThreadId,
),
2_000,
sourceThreadId,
);
expect(
sourceThreadAfterStart.proposedPlans.find((entry) => entry.id === sourcePlan.id),
).toMatchObject({
implementationThreadId: "thread-implement",
});
});
it("does not mark the source proposed plan implemented for a rejected turn.started event", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
const targetThreadId = asThreadId("thread-1");
const sourceTurnId = asTurnId("turn-plan-source");
const activeTurnId = asTurnId("turn-already-running");
const staleTurnId = asTurnId("turn-stale-start");
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-guarded"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-guarded"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
harness.setProviderSession({
provider: "codex",
status: "running",
runtimeMode: "approval-required",
threadId: targetThreadId,
createdAt,
updatedAt: createdAt,
activeTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-already-running"),
provider: "codex",
createdAt,
threadId: targetThreadId,
turnId: activeTurnId,
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === activeTurnId,
2_000,
targetThreadId,
);
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed-guarded"),
provider: "codex",
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
payload: {
planMarkdown: "# Source plan",
},
});
const sourceThreadWithPlan = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
proposedPlan.implementedAt === null,
),
2_000,
sourceThreadId,
);
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) =>
entry.id === "plan:thread-plan:turn:turn-plan-source",
);
expect(sourcePlan).toBeDefined();
if (!sourcePlan) {
throw new Error("Expected source plan to exist.");
}
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-guarded"),
threadId: targetThreadId,
message: {
messageId: asMessageId("msg-plan-target-guarded"),
role: "user",
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
attachments: [],
},
sourceProposedPlan: {
threadId: sourceThreadId,
planId: sourcePlan.id,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
}),
);
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-stale-plan-implementation"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: staleTurnId,
});
await harness.drain();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const sourceThreadAfterRejectedStart = readModel.threads.find(
(entry) => entry.id === sourceThreadId,
);
expect(
sourceThreadAfterRejectedStart?.proposedPlans.find((entry) => entry.id === sourcePlan.id),
).toMatchObject({
implementedAt: null,
implementationThreadId: null,
});
const targetThreadAfterRejectedStart = readModel.threads.find(
(entry) => entry.id === targetThreadId,
);
expect(targetThreadAfterRejectedStart?.session?.status).toBe("running");
expect(targetThreadAfterRejectedStart?.session?.activeTurnId).toBe(activeTurnId);
});
it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
const targetThreadId = asThreadId("thread-implement");
const sourceTurnId = asTurnId("turn-plan-source");
const expectedTurnId = asTurnId("turn-plan-implement");
const replayedTurnId = asTurnId("turn-replayed");
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-unrelated"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-unrelated"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target-unrelated"),
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-plan-target-unrelated"),
threadId: targetThreadId,
session: {
threadId: targetThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed-unrelated"),
provider: "codex",
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
payload: {
planMarkdown: "# Source plan",
},
});
const sourceThreadWithPlan = await waitForThread(
harness.engine,
(thread) =>
thread.proposedPlans.some(
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
proposedPlan.implementedAt === null,
),
2_000,
sourceThreadId,
);
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) =>
entry.id === "plan:thread-plan:turn:turn-plan-source",
);
expect(sourcePlan).toBeDefined();
if (!sourcePlan) {
throw new Error("Expected source plan to exist.");
}
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-unrelated"),
threadId: targetThreadId,
message: {
messageId: asMessageId("msg-plan-target-unrelated"),
role: "user",
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
attachments: [],
},
sourceProposedPlan: {
threadId: sourceThreadId,
planId: sourcePlan.id,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
}),
);
harness.setProviderSession({
provider: "codex",
status: "running",
runtimeMode: "approval-required",
threadId: targetThreadId,
createdAt,
updatedAt: createdAt,
activeTurnId: expectedTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-unrelated-plan-implementation"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: replayedTurnId,
});
await harness.drain();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const sourceThreadAfterUnrelatedStart = readModel.threads.find(
(entry) => entry.id === sourceThreadId,
);
expect(
sourceThreadAfterUnrelatedStart?.proposedPlans.find((entry) => entry.id === sourcePlan.id),
).toMatchObject({
implementedAt: null,
implementationThreadId: null,
});
});
it("finalizes buffered proposed-plan deltas into a first-class proposed plan on turn completion", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1392,6 +1910,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
itemId: "call-collab-1",
payload: {
taskId: "turn-task-1",
taskType: "plan",
@@ -1405,9 +1924,11 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
itemId: "call-collab-1",
payload: {
taskId: "turn-task-1",
description: "Comparing the desktop rollout chunks to the app-server stream.",
summary: "Code reviewer is validating the desktop rollout chunks.",
},
});
@@ -1418,6 +1939,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
itemId: "call-collab-1",
payload: {
taskId: "turn-task-1",
status: "completed",
@@ -1470,11 +1992,44 @@ describe("ProviderRuntimeIngestion", () => {
expect(started?.kind).toBe("task.started");
expect(started?.summary).toBe("Plan task started");
expect(progress?.kind).toBe("task.progress");
expect(progressPayload?.detail).toBe(
"Comparing the desktop rollout chunks to the app-server stream.",
expect(progressPayload?.detail).toBe("Code reviewer is validating the desktop rollout chunks.");
expect(progressPayload?.summary).toBe(
"Code reviewer is validating the desktop rollout chunks.",
);
expect(completed?.kind).toBe("task.completed");
expect(completedPayload?.detail).toBe("<proposed_plan>\n# Plan title\n</proposed_plan>");
expect(started?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
expect(progress?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
expect(completed?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
expect(
thread.workUnits.find(
(entry: ProviderRuntimeTestWorkUnit) => entry.id === "wu:thread-1:turn:turn-task-1:root",
),
).toMatchObject({
id: "wu:thread-1:turn:turn-task-1:root",
turnId: "turn-task-1",
parentWorkUnitId: null,
kind: "primary_agent",
state: "running",
title: "Primary agent",
});
expect(
thread.workUnits.find(
(entry: ProviderRuntimeTestWorkUnit) =>
entry.id === "wu:thread-1:turn:turn-task-1:task:turn-task-1",
),
).toMatchObject({
id: "wu:thread-1:turn:turn-task-1:task:turn-task-1",
turnId: "turn-task-1",
parentWorkUnitId: "wu:thread-1:turn:turn-task-1:root",
kind: "delegated_agent",
state: "completed",
title: "<proposed_plan>\n# Plan title\n</proposed_plan>",
providerRefs: {
runtimeTaskId: "turn-task-1",
runtimeItemId: "call-collab-1",
},
});
expect(
thread.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-task-1",
@@ -4,10 +4,14 @@ import {
CommandId,
MessageId,
type OrchestrationEvent,
type OrchestrationProposedPlanId,
CheckpointRef,
isToolLifecycleItemType,
RuntimeTaskId,
ThreadId,
TurnId,
WorkUnitId,
type OrchestrationThread,
type OrchestrationThreadActivity,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
@@ -15,6 +19,8 @@ import { Cache, Cause, Duration, Effect, Layer, Option, Ref, Stream } from "effe
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { isGitRepository } from "../../git/isRepo.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
@@ -26,6 +32,10 @@ import {
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
const rootWorkUnitIdForTurn = (threadId: ThreadId, turnId: TurnId): WorkUnitId =>
WorkUnitId.makeUnsafe(`wu:${threadId}:turn:${turnId}:root`);
const taskWorkUnitIdForTurn = (threadId: ThreadId, turnId: TurnId, taskId: string): WorkUnitId =>
WorkUnitId.makeUnsafe(`wu:${threadId}:turn:${turnId}:task:${taskId}`);
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
@@ -174,6 +184,57 @@ function requestKindFromCanonicalRequestType(
}
}
function workUnitIdForRuntimeEvent(event: ProviderRuntimeEvent): WorkUnitId | null {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return null;
}
if (
event.type === "task.started" ||
event.type === "task.progress" ||
event.type === "task.completed"
) {
return taskWorkUnitIdForTurn(event.threadId, turnId, String(event.payload.taskId));
}
return rootWorkUnitIdForTurn(event.threadId, turnId);
}
function runtimeTurnStateToWorkUnitState(
state: "completed" | "failed" | "interrupted" | "cancelled",
): "completed" | "failed" | "stopped" | "cancelled" {
switch (state) {
case "failed":
return "failed";
case "interrupted":
return "stopped";
case "cancelled":
return "cancelled";
case "completed":
return "completed";
}
}
function runtimeTaskStateToWorkUnitState(
state: "completed" | "failed" | "stopped",
): "completed" | "failed" | "stopped" {
switch (state) {
case "failed":
return "failed";
case "stopped":
return "stopped";
case "completed":
return "completed";
}
}
function providerTurnWorkUnitRefs(
event: ProviderRuntimeEvent,
): NonNullable<OrchestrationThread["workUnits"][number]["providerRefs"]> | undefined {
return event.providerRefs?.providerTurnId !== undefined
? { providerTurnId: event.providerRefs.providerTurnId }
: undefined;
}
function runtimeEventToActivities(
event: ProviderRuntimeEvent,
): ReadonlyArray<OrchestrationThreadActivity> {
@@ -183,6 +244,7 @@ function runtimeEventToActivities(
? { sequence: eventWithSequence.sessionSequence }
: {};
})();
const maybeWorkUnit = { workUnitId: workUnitIdForRuntimeEvent(event) };
switch (event.type) {
case "request.opened": {
if (event.payload.requestType === "tool_user_input") {
@@ -210,6 +272,7 @@ function runtimeEventToActivities(
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -234,6 +297,7 @@ function runtimeEventToActivities(
...(event.payload.decision ? { decision: event.payload.decision } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -255,6 +319,7 @@ function runtimeEventToActivities(
message: truncateDetail(message),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -273,6 +338,7 @@ function runtimeEventToActivities(
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -293,6 +359,7 @@ function runtimeEventToActivities(
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -311,6 +378,7 @@ function runtimeEventToActivities(
questions: event.payload.questions,
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -329,6 +397,7 @@ function runtimeEventToActivities(
answers: event.payload.answers,
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -355,6 +424,7 @@ function runtimeEventToActivities(
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -370,11 +440,13 @@ function runtimeEventToActivities(
summary: "Reasoning update",
payload: {
taskId: event.payload.taskId,
detail: truncateDetail(event.payload.description),
detail: truncateDetail(event.payload.summary ?? event.payload.description),
...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}),
...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -400,6 +472,7 @@ function runtimeEventToActivities(
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -423,6 +496,7 @@ function runtimeEventToActivities(
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -444,6 +518,7 @@ function runtimeEventToActivities(
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -465,6 +540,7 @@ function runtimeEventToActivities(
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -480,6 +556,7 @@ function runtimeEventToActivities(
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const assistantDeliveryModeRef = yield* Ref.make<AssistantDeliveryMode>(
DEFAULT_ASSISTANT_DELIVERY_MODE,
@@ -671,6 +748,8 @@ const make = Effect.gen(function* () {
threadProposedPlans: ReadonlyArray<{
id: string;
createdAt: string;
implementedAt: string | null;
implementationThreadId: ThreadId | null;
}>;
planId: string;
turnId?: TurnId;
@@ -693,6 +772,8 @@ const make = Effect.gen(function* () {
id: input.planId,
turnId: input.turnId ?? null,
planMarkdown,
implementedAt: existingPlan?.implementedAt ?? null,
implementationThreadId: existingPlan?.implementationThreadId ?? null,
createdAt: existingPlan?.createdAt ?? input.createdAt,
updatedAt: input.updatedAt,
},
@@ -706,6 +787,8 @@ const make = Effect.gen(function* () {
threadProposedPlans: ReadonlyArray<{
id: string;
createdAt: string;
implementedAt: string | null;
implementationThreadId: ThreadId | null;
}>;
planId: string;
turnId?: TurnId;
@@ -772,6 +855,147 @@ const make = Effect.gen(function* () {
).pipe(Effect.asVoid);
});
const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fnUntraced(function* (
threadId: ThreadId,
) {
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId,
});
if (Option.isNone(pendingTurnStart)) {
return null;
}
const sourceThreadId = pendingTurnStart.value.sourceProposedPlanThreadId;
const sourcePlanId = pendingTurnStart.value.sourceProposedPlanId;
if (sourceThreadId === null || sourcePlanId === null) {
return null;
}
return {
sourceThreadId,
sourcePlanId,
} as const;
});
const getExpectedProviderTurnIdForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const sessions = yield* providerService.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
return session?.activeTurnId;
});
const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fnUntraced(function* (
threadId: ThreadId,
eventTurnId: TurnId | undefined,
) {
if (eventTurnId === undefined) {
return null;
}
const expectedTurnId = yield* getExpectedProviderTurnIdForThread(threadId);
if (!sameId(expectedTurnId, eventTurnId)) {
return null;
}
return yield* getSourceProposedPlanReferenceForPendingTurnStart(threadId);
});
const markSourceProposedPlanImplemented = Effect.fnUntraced(function* (
sourceThreadId: ThreadId,
sourcePlanId: OrchestrationProposedPlanId,
implementationThreadId: ThreadId,
implementedAt: string,
) {
const readModel = yield* orchestrationEngine.getReadModel();
const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
return;
}
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: CommandId.makeUnsafe(
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
),
threadId: sourceThread.id,
proposedPlan: {
...sourcePlan,
implementedAt,
implementationThreadId,
updatedAt: implementedAt,
},
createdAt: implementedAt,
});
});
const upsertWorkUnit = Effect.fnUntraced(function* (input: {
thread: OrchestrationThread;
event: ProviderRuntimeEvent;
workUnitId: WorkUnitId;
turnId: TurnId;
kind: "primary_agent" | "delegated_agent";
state: "queued" | "running" | "completed" | "failed" | "stopped" | "cancelled";
title: string;
updatedAt: string;
parentWorkUnitId?: WorkUnitId | null;
detail?: string | null;
startedAt?: string;
completedAt?: string | null;
providerRefs?: NonNullable<OrchestrationThread["workUnits"][number]["providerRefs"]>;
}) {
const existing = input.thread.workUnits.find((entry) => sameId(entry.id, input.workUnitId));
const providerRefs =
input.providerRefs !== undefined || existing?.providerRefs !== undefined
? {
...existing?.providerRefs,
...input.providerRefs,
}
: undefined;
yield* orchestrationEngine.dispatch({
type: "thread.work-unit.upsert",
commandId: providerCommandId(input.event, "thread-work-unit-upsert"),
threadId: input.thread.id,
workUnit: {
id: input.workUnitId,
turnId: input.turnId,
parentWorkUnitId: input.parentWorkUnitId ?? existing?.parentWorkUnitId ?? null,
kind: input.kind,
state: input.state,
title: input.title.trim().length > 0 ? input.title : (existing?.title ?? "Work unit"),
detail: input.detail !== undefined ? input.detail : (existing?.detail ?? null),
spawnedByActivityId: existing?.spawnedByActivityId ?? null,
...(providerRefs !== undefined ? { providerRefs } : {}),
startedAt: existing?.startedAt ?? input.startedAt ?? input.updatedAt,
updatedAt: input.updatedAt,
completedAt:
input.completedAt !== undefined ? input.completedAt : (existing?.completedAt ?? null),
},
createdAt: input.updatedAt,
});
});
const ensureRootWorkUnit = Effect.fnUntraced(function* (
thread: OrchestrationThread,
event: ProviderRuntimeEvent,
turnId: TurnId,
updatedAt: string,
) {
const providerRefs = providerTurnWorkUnitRefs(event);
yield* upsertWorkUnit({
thread,
event,
workUnitId: rootWorkUnitIdForTurn(thread.id, turnId),
turnId,
kind: "primary_agent",
state: "running",
title: "Primary agent",
updatedAt,
startedAt: updatedAt,
...(providerRefs ? { providerRefs } : {}),
});
});
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel();
@@ -812,6 +1036,10 @@ const make = Effect.gen(function* () {
return true;
}
})();
const acceptedTurnStartedSourcePlan =
event.type === "turn.started" && shouldApplyThreadLifecycle
? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId)
: null;
if (
event.type === "session.started" ||
@@ -854,6 +1082,26 @@ const make = Effect.gen(function* () {
: (thread.session?.lastError ?? null);
if (shouldApplyThreadLifecycle) {
if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) {
yield* markSourceProposedPlanImplemented(
acceptedTurnStartedSourcePlan.sourceThreadId,
acceptedTurnStartedSourcePlan.sourcePlanId,
thread.id,
now,
).pipe(
Effect.catchCause((cause) =>
Effect.logWarning(
"provider runtime ingestion failed to mark source proposed plan",
{
eventId: event.eventId,
eventType: event.type,
cause: Cause.pretty(cause),
},
),
),
);
}
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "thread-session-set"),
@@ -872,6 +1120,89 @@ const make = Effect.gen(function* () {
}
}
if (eventTurnId !== undefined) {
yield* ensureRootWorkUnit(thread, event, eventTurnId, now);
}
if (event.type === "turn.started" && eventTurnId !== undefined) {
const providerRefs = providerTurnWorkUnitRefs(event);
yield* upsertWorkUnit({
thread,
event,
workUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
turnId: eventTurnId,
kind: "primary_agent",
state: "running",
title: "Primary agent",
updatedAt: now,
startedAt: now,
...(providerRefs ? { providerRefs } : {}),
});
}
if (event.type === "turn.completed" && eventTurnId !== undefined) {
const providerRefs = providerTurnWorkUnitRefs(event);
yield* upsertWorkUnit({
thread,
event,
workUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
turnId: eventTurnId,
kind: "primary_agent",
state: runtimeTurnStateToWorkUnitState(runtimeTurnState(event)),
title: "Primary agent",
updatedAt: now,
completedAt: now,
...(providerRefs ? { providerRefs } : {}),
});
}
if (
(event.type === "task.started" ||
event.type === "task.progress" ||
event.type === "task.completed") &&
eventTurnId !== undefined
) {
const taskId = String(event.payload.taskId);
const workUnitId = taskWorkUnitIdForTurn(thread.id, eventTurnId, taskId);
const taskState =
event.type === "task.completed"
? runtimeTaskStateToWorkUnitState(event.payload.status)
: "running";
const taskTitle =
event.type === "task.started"
? (event.payload.description ?? event.payload.taskType ?? "Delegated task")
: event.type === "task.completed"
? (event.payload.summary ?? "Delegated task")
: (event.payload.summary ?? event.payload.description);
const taskDetail =
event.type === "task.started"
? (event.payload.description ?? null)
: event.type === "task.completed"
? (event.payload.summary ?? null)
: (event.payload.summary ?? event.payload.description);
yield* upsertWorkUnit({
thread,
event,
workUnitId,
turnId: eventTurnId,
parentWorkUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
kind: "delegated_agent",
state: taskState,
title: taskTitle,
detail: taskDetail,
updatedAt: now,
...(event.type === "task.started" ? { startedAt: now } : {}),
...(event.type === "task.completed" ? { completedAt: now } : {}),
providerRefs: {
runtimeTaskId: RuntimeTaskId.makeUnsafe(taskId),
...(event.itemId ? { runtimeItemId: event.itemId } : {}),
...(event.providerRefs?.providerTurnId !== undefined
? { providerTurnId: event.providerRefs.providerTurnId }
: {}),
},
});
}
const assistantDelta =
event.type === "content.delta" && event.payload.streamKind === "assistant_text"
? event.payload.delta
@@ -1144,4 +1475,7 @@ const make = Effect.gen(function* () {
} satisfies ProviderRuntimeIngestionShape;
});
export const ProviderRuntimeIngestionLive = Layer.effect(ProviderRuntimeIngestionService, make);
export const ProviderRuntimeIngestionLive = Layer.effect(
ProviderRuntimeIngestionService,
make,
).pipe(Layer.provide(ProjectionTurnRepositoryLive));
+2
View File
@@ -13,6 +13,7 @@ import {
ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema,
ThreadRevertedPayload as ContractsThreadRevertedPayloadSchema,
ThreadActivityAppendedPayload as ContractsThreadActivityAppendedPayloadSchema,
ThreadWorkUnitUpsertedPayload as ContractsThreadWorkUnitUpsertedPayloadSchema,
ThreadTurnStartRequestedPayload as ContractsThreadTurnStartRequestedPayloadSchema,
ThreadTurnInterruptRequestedPayload as ContractsThreadTurnInterruptRequestedPayloadSchema,
ThreadApprovalResponseRequestedPayload as ContractsThreadApprovalResponseRequestedPayloadSchema,
@@ -37,6 +38,7 @@ export const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema;
export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema;
export const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema;
export const ThreadActivityAppendedPayload = ContractsThreadActivityAppendedPayloadSchema;
export const ThreadWorkUnitUpsertedPayload = ContractsThreadWorkUnitUpsertedPayloadSchema;
export const ThreadTurnStartRequestedPayload = ContractsThreadTurnStartRequestedPayloadSchema;
export const ThreadTurnInterruptRequestedPayload =
@@ -62,6 +62,7 @@ const readModel: OrchestrationReadModel = {
session: null,
activities: [],
proposedPlans: [],
workUnits: [],
checkpoints: [],
deletedAt: null,
},
@@ -81,6 +82,7 @@ const readModel: OrchestrationReadModel = {
session: null,
activities: [],
proposedPlans: [],
workUnits: [],
checkpoints: [],
deletedAt: null,
},
+49 -7
View File
@@ -262,11 +262,35 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}
case "thread.turn.start": {
yield* requireThread({
const targetThread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const sourceProposedPlan = command.sourceProposedPlan;
const sourceThread = sourceProposedPlan
? yield* requireThread({
readModel,
command,
threadId: sourceProposedPlan.threadId,
})
: null;
const sourcePlan =
sourceProposedPlan && sourceThread
? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)
: null;
if (sourceProposedPlan && !sourcePlan) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,
});
}
if (sourceThread && sourceThread.projectId !== targetThread.projectId) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
});
}
const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
...withEventBase({
aggregateKind: "thread",
@@ -306,12 +330,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
? { providerOptions: command.providerOptions }
: {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
runtimeMode:
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
command.runtimeMode,
interactionMode:
readModel.threads.find((entry) => entry.id === command.threadId)?.interactionMode ??
command.interactionMode,
runtimeMode: targetThread.runtimeMode,
interactionMode: targetThread.interactionMode,
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
createdAt: command.createdAt,
},
};
@@ -610,6 +631,27 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.work-unit.upsert": {
yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
return {
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
type: "thread.work-unit-upserted",
payload: {
threadId: command.threadId,
workUnit: command.workUnit,
},
};
}
default: {
command satisfies never;
const fallback = command as never as { type: string };
@@ -85,6 +85,7 @@ describe("orchestration projector", () => {
messages: [],
proposedPlans: [],
activities: [],
workUnits: [],
checkpoints: [],
session: null,
},
@@ -122,6 +123,88 @@ describe("orchestration projector", () => {
).rejects.toBeDefined();
});
it("applies thread.work-unit-upserted events", async () => {
const now = new Date().toISOString();
const model = createEmptyReadModel(now);
const afterCreate = await Effect.runPromise(
projectEvent(
model,
makeEvent({
sequence: 1,
type: "thread.created",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: now,
commandId: "cmd-thread-create",
payload: {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
),
);
const next = await Effect.runPromise(
projectEvent(
afterCreate,
makeEvent({
sequence: 2,
type: "thread.work-unit-upserted",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: now,
commandId: "cmd-work-unit-upsert",
payload: {
threadId: "thread-1",
workUnit: {
id: "wu:thread-1:turn:turn-1:root",
turnId: "turn-1",
parentWorkUnitId: null,
kind: "primary_agent",
state: "running",
title: "Primary agent",
detail: null,
spawnedByActivityId: null,
providerRefs: {
providerTurnId: "provider-turn-1",
},
startedAt: now,
updatedAt: now,
completedAt: null,
},
},
}),
),
);
expect(next.threads[0]?.workUnits).toEqual([
{
id: "wu:thread-1:turn:turn-1:root",
turnId: "turn-1",
parentWorkUnitId: null,
kind: "primary_agent",
state: "running",
title: "Primary agent",
detail: null,
spawnedByActivityId: null,
providerRefs: {
providerTurnId: "provider-turn-1",
},
startedAt: now,
updatedAt: now,
completedAt: null,
},
]);
});
it("keeps projector forward-compatible for unhandled event types", async () => {
const now = new Date().toISOString();
const model = createEmptyReadModel(now);
@@ -453,6 +536,7 @@ describe("orchestration projector", () => {
summary: "Edit file started",
payload: { toolKind: "command" },
turnId: "turn-1",
workUnitId: null,
createdAt: "2026-02-23T10:00:02.750Z",
},
},
@@ -527,6 +611,7 @@ describe("orchestration projector", () => {
summary: "Edit file complete",
payload: { toolKind: "command" },
turnId: "turn-2",
workUnitId: null,
createdAt: "2026-02-23T10:00:04.750Z",
},
},
@@ -23,6 +23,7 @@ import {
ThreadRevertedPayload,
ThreadSessionSetPayload,
ThreadTurnDiffCompletedPayload,
ThreadWorkUnitUpsertedPayload,
} from "./Schemas.ts";
type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
@@ -136,6 +137,17 @@ function retainThreadProposedPlansAfterRevert(
);
}
function retainThreadWorkUnitsAfterRevert(
workUnits: ReadonlyArray<OrchestrationThread["workUnits"][number]>,
retainedTurnIds: ReadonlySet<string>,
): ReadonlyArray<OrchestrationThread["workUnits"][number]> {
const retained = workUnits.filter((workUnit) => retainedTurnIds.has(workUnit.turnId));
const retainedIds = new Set(retained.map((workUnit) => workUnit.id));
return retained.filter(
(workUnit) => workUnit.parentWorkUnitId === null || retainedIds.has(workUnit.parentWorkUnitId),
);
}
function compareThreadActivities(
left: OrchestrationThread["activities"][number],
right: OrchestrationThread["activities"][number],
@@ -262,7 +274,9 @@ export function projectEvent(
updatedAt: payload.updatedAt,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
workUnits: [],
checkpoints: [],
session: null,
},
@@ -563,6 +577,7 @@ export function projectEvent(
retainedTurnIds,
).slice(-200);
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
const workUnits = retainThreadWorkUnitsAfterRevert(thread.workUnits, retainedTurnIds);
const latestCheckpoint = checkpoints.at(-1) ?? null;
const latestTurn =
@@ -584,6 +599,7 @@ export function projectEvent(
messages,
proposedPlans,
activities,
workUnits,
latestTurn,
updatedAt: event.occurredAt,
}),
@@ -621,6 +637,37 @@ export function projectEvent(
}),
);
case "thread.work-unit-upserted":
return decodeForEvent(
ThreadWorkUnitUpsertedPayload,
event.payload,
event.type,
"payload",
).pipe(
Effect.map((payload) => {
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
if (!thread) {
return nextBase;
}
const workUnits = [
...thread.workUnits.filter((entry) => entry.id !== payload.workUnit.id),
payload.workUnit,
].toSorted(
(left, right) =>
left.startedAt.localeCompare(right.startedAt) || left.id.localeCompare(right.id),
);
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
workUnits,
updatedAt: event.occurredAt,
}),
};
}),
);
default:
return Effect.succeed(nextBase);
}
@@ -38,6 +38,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
activity_id,
thread_id,
turn_id,
work_unit_id,
tone,
kind,
summary,
@@ -49,6 +50,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
${row.activityId},
${row.threadId},
${row.turnId},
${row.workUnitId},
${row.tone},
${row.kind},
${row.summary},
@@ -60,6 +62,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
DO UPDATE SET
thread_id = excluded.thread_id,
turn_id = excluded.turn_id,
work_unit_id = excluded.work_unit_id,
tone = excluded.tone,
kind = excluded.kind,
summary = excluded.summary,
@@ -78,6 +81,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
work_unit_id AS "workUnitId",
tone,
kind,
summary,
@@ -126,6 +130,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
activityId: row.activityId,
threadId: row.threadId,
turnId: row.turnId,
workUnitId: row.workUnitId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
@@ -22,6 +22,8 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
thread_id,
turn_id,
plan_markdown,
implemented_at,
implementation_thread_id,
created_at,
updated_at
)
@@ -30,6 +32,8 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
${row.threadId},
${row.turnId},
${row.planMarkdown},
${row.implementedAt},
${row.implementationThreadId},
${row.createdAt},
${row.updatedAt}
)
@@ -38,6 +42,8 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
thread_id = excluded.thread_id,
turn_id = excluded.turn_id,
plan_markdown = excluded.plan_markdown,
implemented_at = excluded.implemented_at,
implementation_thread_id = excluded.implementation_thread_id,
created_at = excluded.created_at,
updated_at = excluded.updated_at
`,
@@ -52,6 +58,8 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
plan_markdown AS "planMarkdown",
implemented_at AS "implementedAt",
implementation_thread_id AS "implementationThreadId",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projection_thread_proposed_plans
@@ -0,0 +1,163 @@
import { Effect, Layer, Schema, Struct } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
import {
DeleteProjectionThreadWorkUnitsInput,
ListProjectionThreadWorkUnitsInput,
ProjectionThreadWorkUnit,
ProjectionThreadWorkUnitRepository,
type ProjectionThreadWorkUnitRepositoryShape,
} from "../Services/ProjectionThreadWorkUnits.ts";
const ProjectionThreadWorkUnitDbRowSchema = ProjectionThreadWorkUnit.mapFields(
Struct.assign({
providerRefs: Schema.NullOr(
Schema.fromJsonString(ProjectionThreadWorkUnit.fields.providerRefs),
),
}),
);
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown) =>
Schema.isSchemaError(cause)
? toPersistenceDecodeError(decodeOperation)(cause)
: toPersistenceSqlError(sqlOperation)(cause);
}
const makeProjectionThreadWorkUnitRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const upsertProjectionThreadWorkUnitRow = SqlSchema.void({
Request: ProjectionThreadWorkUnit,
execute: (row) => sql`
INSERT INTO projection_thread_work_units (
work_unit_id,
thread_id,
turn_id,
parent_work_unit_id,
kind,
state,
title,
detail,
spawned_by_activity_id,
provider_refs_json,
started_at,
updated_at,
completed_at
)
VALUES (
${row.workUnitId},
${row.threadId},
${row.turnId},
${row.parentWorkUnitId},
${row.kind},
${row.state},
${row.title},
${row.detail},
${row.spawnedByActivityId},
${row.providerRefs ? JSON.stringify(row.providerRefs) : null},
${row.startedAt},
${row.updatedAt},
${row.completedAt}
)
ON CONFLICT (work_unit_id)
DO UPDATE SET
thread_id = excluded.thread_id,
turn_id = excluded.turn_id,
parent_work_unit_id = excluded.parent_work_unit_id,
kind = excluded.kind,
state = excluded.state,
title = excluded.title,
detail = excluded.detail,
spawned_by_activity_id = excluded.spawned_by_activity_id,
provider_refs_json = excluded.provider_refs_json,
started_at = excluded.started_at,
updated_at = excluded.updated_at,
completed_at = excluded.completed_at
`,
});
const listProjectionThreadWorkUnitRows = SqlSchema.findAll({
Request: ListProjectionThreadWorkUnitsInput,
Result: ProjectionThreadWorkUnitDbRowSchema,
execute: ({ threadId }) => sql`
SELECT
work_unit_id AS "workUnitId",
thread_id AS "threadId",
turn_id AS "turnId",
parent_work_unit_id AS "parentWorkUnitId",
kind,
state,
title,
detail,
spawned_by_activity_id AS "spawnedByActivityId",
provider_refs_json AS "providerRefs",
started_at AS "startedAt",
updated_at AS "updatedAt",
completed_at AS "completedAt"
FROM projection_thread_work_units
WHERE thread_id = ${threadId}
ORDER BY started_at ASC, work_unit_id ASC
`,
});
const deleteProjectionThreadWorkUnitRows = SqlSchema.void({
Request: DeleteProjectionThreadWorkUnitsInput,
execute: ({ threadId }) => sql`
DELETE FROM projection_thread_work_units
WHERE thread_id = ${threadId}
`,
});
const upsert: ProjectionThreadWorkUnitRepositoryShape["upsert"] = (row) =>
upsertProjectionThreadWorkUnitRow(row).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionThreadWorkUnitRepository.upsert:query")),
);
const listByThreadId: ProjectionThreadWorkUnitRepositoryShape["listByThreadId"] = (input) =>
listProjectionThreadWorkUnitRows(input).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionThreadWorkUnitRepository.listByThreadId:query",
"ProjectionThreadWorkUnitRepository.listByThreadId:decodeRows",
),
),
Effect.map((rows) =>
rows.map((row) => ({
workUnitId: row.workUnitId,
threadId: row.threadId,
turnId: row.turnId,
parentWorkUnitId: row.parentWorkUnitId,
kind: row.kind,
state: row.state,
title: row.title,
detail: row.detail,
spawnedByActivityId: row.spawnedByActivityId,
...(row.providerRefs !== null ? { providerRefs: row.providerRefs } : {}),
startedAt: row.startedAt,
updatedAt: row.updatedAt,
completedAt: row.completedAt,
})),
),
);
const deleteByThreadId: ProjectionThreadWorkUnitRepositoryShape["deleteByThreadId"] = (input) =>
deleteProjectionThreadWorkUnitRows(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadWorkUnitRepository.deleteByThreadId:query"),
),
);
return {
upsert,
listByThreadId,
deleteByThreadId,
} satisfies ProjectionThreadWorkUnitRepositoryShape;
});
export const ProjectionThreadWorkUnitRepositoryLive = Layer.effect(
ProjectionThreadWorkUnitRepository,
makeProjectionThreadWorkUnitRepository,
);
@@ -47,6 +47,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
@@ -61,6 +63,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
${row.threadId},
${row.turnId},
${row.pendingMessageId},
${row.sourceProposedPlanThreadId},
${row.sourceProposedPlanId},
${row.assistantMessageId},
${row.state},
${row.requestedAt},
@@ -74,6 +78,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
ON CONFLICT (thread_id, turn_id)
DO UPDATE SET
pending_message_id = excluded.pending_message_id,
source_proposed_plan_thread_id = excluded.source_proposed_plan_thread_id,
source_proposed_plan_id = excluded.source_proposed_plan_id,
assistant_message_id = excluded.assistant_message_id,
state = excluded.state,
requested_at = excluded.requested_at,
@@ -106,6 +112,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
@@ -120,6 +128,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
${row.threadId},
NULL,
${row.messageId},
${row.sourceProposedPlanThreadId},
${row.sourceProposedPlanId},
NULL,
'pending',
${row.requestedAt},
@@ -141,6 +151,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
pending_message_id AS "messageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId",
requested_at AS "requestedAt"
FROM projection_turns
WHERE thread_id = ${threadId}
@@ -162,6 +174,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
pending_message_id AS "pendingMessageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId",
assistant_message_id AS "assistantMessageId",
state,
requested_at AS "requestedAt",
@@ -193,6 +207,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
pending_message_id AS "pendingMessageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId",
assistant_message_id AS "assistantMessageId",
state,
requested_at AS "requestedAt",
@@ -25,6 +25,9 @@ import Migration0010 from "./Migrations/010_ProjectionThreadsRuntimeMode.ts";
import Migration0011 from "./Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts";
import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts";
import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
import Migration0016 from "./Migrations/016_ProjectionThreadWorkUnits.ts";
import { Effect } from "effect";
/**
@@ -51,6 +54,9 @@ const loader = Migrator.fromRecord({
"11_OrchestrationThreadCreatedRuntimeMode": Migration0011,
"12_ProjectionThreadsInteractionMode": Migration0012,
"13_ProjectionThreadProposedPlans": Migration0013,
"14_ProjectionThreadProposedPlanImplementation": Migration0014,
"15_ProjectionTurnsSourceProposedPlan": Migration0015,
"16_ProjectionThreadWorkUnits": Migration0016,
});
/**
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_thread_proposed_plans
ADD COLUMN implemented_at TEXT
`;
yield* sql`
ALTER TABLE projection_thread_proposed_plans
ADD COLUMN implementation_thread_id TEXT
`;
});
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_turns
ADD COLUMN source_proposed_plan_thread_id TEXT
`;
yield* sql`
ALTER TABLE projection_turns
ADD COLUMN source_proposed_plan_id TEXT
`;
});
@@ -0,0 +1,88 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_thread_activities
ADD COLUMN work_unit_id TEXT
`;
yield* sql`
CREATE TABLE IF NOT EXISTS projection_thread_work_units (
work_unit_id TEXT PRIMARY KEY,
thread_id TEXT NOT NULL,
turn_id TEXT NOT NULL,
parent_work_unit_id TEXT,
kind TEXT NOT NULL,
state TEXT NOT NULL,
title TEXT NOT NULL,
detail TEXT,
spawned_by_activity_id TEXT,
provider_refs_json TEXT,
started_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
completed_at TEXT
)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_thread_work_units_thread_turn
ON projection_thread_work_units(thread_id, turn_id, started_at)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_thread_work_units_thread_parent
ON projection_thread_work_units(thread_id, parent_work_unit_id, started_at)
`;
yield* sql`
INSERT INTO projection_thread_work_units (
work_unit_id,
thread_id,
turn_id,
parent_work_unit_id,
kind,
state,
title,
detail,
spawned_by_activity_id,
provider_refs_json,
started_at,
updated_at,
completed_at
)
SELECT
'wu:' || thread_id || ':turn:' || turn_id || ':root',
thread_id,
turn_id,
NULL,
'primary_agent',
CASE state
WHEN 'completed' THEN 'completed'
WHEN 'error' THEN 'failed'
WHEN 'interrupted' THEN 'stopped'
ELSE 'running'
END,
'Primary agent',
NULL,
NULL,
NULL,
COALESCE(started_at, requested_at),
COALESCE(completed_at, started_at, requested_at),
CASE
WHEN state IN ('completed', 'error', 'interrupted') THEN COALESCE(completed_at, started_at, requested_at)
ELSE NULL
END
FROM projection_turns
WHERE turn_id IS NOT NULL
`;
yield* sql`
UPDATE projection_thread_activities
SET work_unit_id = 'wu:' || thread_id || ':turn:' || turn_id || ':root'
WHERE turn_id IS NOT NULL
AND work_unit_id IS NULL
`;
});
@@ -13,6 +13,7 @@ import {
OrchestrationThreadActivityTone,
ThreadId,
TurnId,
WorkUnitId,
} from "@t3tools/contracts";
import { Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
@@ -23,6 +24,7 @@ export const ProjectionThreadActivity = Schema.Struct({
activityId: EventId,
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
workUnitId: Schema.NullOr(WorkUnitId),
tone: OrchestrationThreadActivityTone,
kind: Schema.String,
summary: Schema.String,
@@ -15,6 +15,8 @@ export const ProjectionThreadProposedPlan = Schema.Struct({
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
planMarkdown: TrimmedNonEmptyString,
implementedAt: Schema.NullOr(IsoDateTime),
implementationThreadId: Schema.NullOr(ThreadId),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
});
@@ -0,0 +1,59 @@
import {
EventId,
IsoDateTime,
OrchestrationWorkUnitKind,
OrchestrationWorkUnitProviderRefs,
OrchestrationWorkUnitState,
ThreadId,
TurnId,
TrimmedNonEmptyString,
WorkUnitId,
} from "@t3tools/contracts";
import { Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
export const ProjectionThreadWorkUnit = Schema.Struct({
workUnitId: WorkUnitId,
threadId: ThreadId,
turnId: TurnId,
parentWorkUnitId: Schema.NullOr(WorkUnitId),
kind: OrchestrationWorkUnitKind,
state: OrchestrationWorkUnitState,
title: TrimmedNonEmptyString,
detail: Schema.NullOr(TrimmedNonEmptyString),
spawnedByActivityId: Schema.NullOr(EventId),
providerRefs: Schema.optional(OrchestrationWorkUnitProviderRefs),
startedAt: IsoDateTime,
updatedAt: IsoDateTime,
completedAt: Schema.NullOr(IsoDateTime),
});
export type ProjectionThreadWorkUnit = typeof ProjectionThreadWorkUnit.Type;
export const ListProjectionThreadWorkUnitsInput = Schema.Struct({
threadId: ThreadId,
});
export type ListProjectionThreadWorkUnitsInput = typeof ListProjectionThreadWorkUnitsInput.Type;
export const DeleteProjectionThreadWorkUnitsInput = Schema.Struct({
threadId: ThreadId,
});
export type DeleteProjectionThreadWorkUnitsInput = typeof DeleteProjectionThreadWorkUnitsInput.Type;
export interface ProjectionThreadWorkUnitRepositoryShape {
readonly upsert: (
workUnit: ProjectionThreadWorkUnit,
) => Effect.Effect<void, ProjectionRepositoryError>;
readonly listByThreadId: (
input: ListProjectionThreadWorkUnitsInput,
) => Effect.Effect<ReadonlyArray<ProjectionThreadWorkUnit>, ProjectionRepositoryError>;
readonly deleteByThreadId: (
input: DeleteProjectionThreadWorkUnitsInput,
) => Effect.Effect<void, ProjectionRepositoryError>;
}
export class ProjectionThreadWorkUnitRepository extends ServiceMap.Service<
ProjectionThreadWorkUnitRepository,
ProjectionThreadWorkUnitRepositoryShape
>()("t3/persistence/Services/ProjectionThreadWorkUnits/ProjectionThreadWorkUnitRepository") {}
@@ -11,6 +11,7 @@ import {
IsoDateTime,
MessageId,
NonNegativeInt,
OrchestrationProposedPlanId,
OrchestrationCheckpointFile,
OrchestrationCheckpointStatus,
ThreadId,
@@ -34,6 +35,8 @@ export const ProjectionTurn = Schema.Struct({
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
pendingMessageId: Schema.NullOr(MessageId),
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
assistantMessageId: Schema.NullOr(MessageId),
state: ProjectionTurnState,
requestedAt: IsoDateTime,
@@ -50,6 +53,8 @@ export const ProjectionTurnById = Schema.Struct({
threadId: ThreadId,
turnId: TurnId,
pendingMessageId: Schema.NullOr(MessageId),
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
assistantMessageId: Schema.NullOr(MessageId),
state: ProjectionTurnState,
requestedAt: IsoDateTime,
@@ -65,6 +70,8 @@ export type ProjectionTurnById = typeof ProjectionTurnById.Type;
export const ProjectionPendingTurnStart = Schema.Struct({
threadId: ThreadId,
messageId: MessageId,
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
requestedAt: IsoDateTime,
});
export type ProjectionPendingTurnStart = typeof ProjectionPendingTurnStart.Type;
File diff suppressed because it is too large. Load diff
@@ -1,947 +0,0 @@
import type {
Options as ClaudeQueryOptions,
PermissionMode,
PermissionResult,
SDKMessage,
SDKUserMessage,
} from "@anthropic-ai/claude-agent-sdk";
import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import { Effect, Fiber, Random, Stream } from "effect";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { ClaudeCodeAdapter } from "../Services/ClaudeCodeAdapter.ts";
import {
makeClaudeCodeAdapterLive,
type ClaudeCodeAdapterLiveOptions,
} from "./ClaudeCodeAdapter.ts";
class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
private readonly queue: Array<SDKMessage> = [];
private readonly resolvers: Array<(value: IteratorResult<SDKMessage>) => void> = [];
private done = false;
public readonly interruptCalls: Array<void> = [];
public readonly setModelCalls: Array<string | undefined> = [];
public readonly setPermissionModeCalls: Array<string> = [];
public readonly setMaxThinkingTokensCalls: Array<number | null> = [];
public closeCalls = 0;
emit(message: SDKMessage): void {
if (this.done) {
return;
}
const resolver = this.resolvers.shift();
if (resolver) {
resolver({ done: false, value: message });
return;
}
this.queue.push(message);
}
finish(): void {
if (this.done) {
return;
}
this.done = true;
for (const resolver of this.resolvers.splice(0)) {
resolver({ done: true, value: undefined });
}
}
readonly interrupt = async (): Promise<void> => {
this.interruptCalls.push(undefined);
};
readonly setModel = async (model?: string): Promise<void> => {
this.setModelCalls.push(model);
};
readonly setPermissionMode = async (mode: PermissionMode): Promise<void> => {
this.setPermissionModeCalls.push(mode);
};
readonly setMaxThinkingTokens = async (maxThinkingTokens: number | null): Promise<void> => {
this.setMaxThinkingTokensCalls.push(maxThinkingTokens);
};
readonly close = (): void => {
this.closeCalls += 1;
this.finish();
};
[Symbol.asyncIterator](): AsyncIterator<SDKMessage> {
return {
next: () => {
if (this.queue.length > 0) {
const value = this.queue.shift();
if (value) {
return Promise.resolve({
done: false,
value,
});
}
}
if (this.done) {
return Promise.resolve({
done: true,
value: undefined,
});
}
return new Promise((resolve) => {
this.resolvers.push(resolve);
});
},
};
}
}
interface Harness {
readonly layer: ReturnType<typeof makeClaudeCodeAdapterLive>;
readonly query: FakeClaudeQuery;
readonly getLastCreateQueryInput: () =>
| {
readonly prompt: AsyncIterable<SDKUserMessage>;
readonly options: ClaudeQueryOptions;
}
| undefined;
}
function makeHarness(config?: {
readonly nativeEventLogPath?: string;
readonly nativeEventLogger?: ClaudeCodeAdapterLiveOptions["nativeEventLogger"];
}): Harness {
const query = new FakeClaudeQuery();
let createInput:
| {
readonly prompt: AsyncIterable<SDKUserMessage>;
readonly options: ClaudeQueryOptions;
}
| undefined;
const adapterOptions: ClaudeCodeAdapterLiveOptions = {
createQuery: (input) => {
createInput = input;
return query;
},
...(config?.nativeEventLogger
? {
nativeEventLogger: config.nativeEventLogger,
}
: {}),
...(config?.nativeEventLogPath
? {
nativeEventLogPath: config.nativeEventLogPath,
}
: {}),
};
return {
layer: makeClaudeCodeAdapterLive(adapterOptions),
query,
getLastCreateQueryInput: () => createInput,
};
}
function makeDeterministicRandomService(seed = 0x1234_5678): {
nextIntUnsafe: () => number;
nextDoubleUnsafe: () => number;
} {
let state = seed >>> 0;
const nextIntUnsafe = (): number => {
state = (Math.imul(1_664_525, state) + 1_013_904_223) >>> 0;
return state;
};
return {
nextIntUnsafe,
nextDoubleUnsafe: () => nextIntUnsafe() / 0x1_0000_0000,
};
}
const THREAD_ID = ThreadId.makeUnsafe("thread-claude-1");
const RESUME_THREAD_ID = ThreadId.makeUnsafe("thread-claude-resume");
describe("ClaudeCodeAdapterLive", () => {
it.effect("returns validation error for non-claudeCode provider on startSession", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const result = yield* adapter
.startSession({ threadId: THREAD_ID, provider: "codex", runtimeMode: "full-access" })
.pipe(Effect.result);
assert.equal(result._tag, "Failure");
if (result._tag !== "Failure") {
return;
}
assert.deepEqual(
result.failure,
new ProviderAdapterValidationError({
provider: "claudeCode",
operation: "startSession",
issue: "Expected provider 'claudeCode' but received 'codex'.",
}),
);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("derives bypass permission mode from full-access runtime policy", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.permissionMode, "bypassPermissions");
assert.equal(createInput?.options.allowDangerouslySkipPermissions, true);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("keeps explicit claude permission mode over runtime-derived defaults", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
providerOptions: {
claudeCode: {
permissionMode: "plan",
},
},
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.permissionMode, "plan");
assert.equal(createInput?.options.allowDangerouslySkipPermissions, undefined);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("maps Claude stream/runtime messages to canonical provider runtime events", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 11).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
model: "claude-sonnet-4-5",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-1",
uuid: "stream-1",
parent_tool_use_id: null,
event: {
type: "content_block_delta",
index: 0,
delta: {
type: "text_delta",
text: "Hi",
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-1",
uuid: "stream-2",
parent_tool_use_id: null,
event: {
type: "content_block_start",
index: 1,
content_block: {
type: "tool_use",
id: "tool-1",
name: "Bash",
input: {
command: "ls",
},
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-1",
uuid: "stream-3",
parent_tool_use_id: null,
event: {
type: "content_block_stop",
index: 1,
},
} as unknown as SDKMessage);
harness.query.emit({
type: "assistant",
session_id: "sdk-session-1",
uuid: "assistant-1",
parent_tool_use_id: null,
message: {
id: "assistant-message-1",
content: [{ type: "text", text: "Hi" }],
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-1",
uuid: "result-1",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"turn.started",
"thread.started",
"content.delta",
"item.started",
"item.completed",
"item.updated",
"item.completed",
"turn.completed",
],
);
const turnStarted = runtimeEvents[3];
assert.equal(turnStarted?.type, "turn.started");
if (turnStarted?.type === "turn.started") {
assert.equal(String(turnStarted.turnId), String(turn.turnId));
}
const deltaEvent = runtimeEvents.find((event) => event.type === "content.delta");
assert.equal(deltaEvent?.type, "content.delta");
if (deltaEvent?.type === "content.delta") {
assert.equal(deltaEvent.payload.delta, "Hi");
assert.equal(String(deltaEvent.turnId), String(turn.turnId));
}
const toolStarted = runtimeEvents.find((event) => event.type === "item.started");
assert.equal(toolStarted?.type, "item.started");
if (toolStarted?.type === "item.started") {
assert.equal(toolStarted.payload.itemType, "command_execution");
}
const turnCompleted = runtimeEvents[runtimeEvents.length - 1];
assert.equal(turnCompleted?.type, "turn.completed");
if (turnCompleted?.type === "turn.completed") {
assert.equal(String(turnCompleted.turnId), String(turn.turnId));
assert.equal(turnCompleted.payload.state, "completed");
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect(
"emits completion only after turn result when assistant frames arrive before deltas",
() => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
harness.query.emit({
type: "assistant",
session_id: "sdk-session-early-assistant",
uuid: "assistant-early",
parent_tool_use_id: null,
message: {
id: "assistant-message-early",
content: [
{ type: "tool_use", id: "tool-early", name: "Read", input: { path: "a.ts" } },
],
},
} as unknown as SDKMessage);
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-early-assistant",
uuid: "stream-early",
parent_tool_use_id: null,
event: {
type: "content_block_delta",
index: 0,
delta: {
type: "text_delta",
text: "Late text",
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-early-assistant",
uuid: "result-early",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"turn.started",
"thread.started",
"item.updated",
"content.delta",
"item.completed",
"turn.completed",
],
);
const deltaIndex = runtimeEvents.findIndex((event) => event.type === "content.delta");
const completedIndex = runtimeEvents.findIndex((event) => event.type === "item.completed");
assert.equal(deltaIndex >= 0 && completedIndex >= 0 && deltaIndex < completedIndex, true);
const deltaEvent = runtimeEvents[deltaIndex];
assert.equal(deltaEvent?.type, "content.delta");
if (deltaEvent?.type === "content.delta") {
assert.equal(deltaEvent.payload.delta, "Late text");
assert.equal(String(deltaEvent.turnId), String(turn.turnId));
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
},
);
it.effect("falls back to assistant payload text when stream deltas are absent", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
harness.query.emit({
type: "assistant",
session_id: "sdk-session-fallback-text",
uuid: "assistant-fallback",
parent_tool_use_id: null,
message: {
id: "assistant-message-fallback",
content: [{ type: "text", text: "Fallback hello" }],
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-fallback-text",
uuid: "result-fallback",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"turn.started",
"thread.started",
"item.updated",
"content.delta",
"item.completed",
"turn.completed",
],
);
const deltaEvent = runtimeEvents.find((event) => event.type === "content.delta");
assert.equal(deltaEvent?.type, "content.delta");
if (deltaEvent?.type === "content.delta") {
assert.equal(deltaEvent.payload.delta, "Fallback hello");
assert.equal(String(deltaEvent.turnId), String(turn.turnId));
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("does not fabricate provider thread ids before first SDK session_id", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 5).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
assert.equal(session.threadId, THREAD_ID);
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
assert.equal(turn.threadId, THREAD_ID);
harness.query.emit({
type: "stream_event",
session_id: "sdk-thread-real",
uuid: "stream-thread-real",
parent_tool_use_id: null,
event: {
type: "message_start",
message: {
id: "msg-thread-real",
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-thread-real",
uuid: "result-thread-real",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"turn.started",
"thread.started",
],
);
const sessionStarted = runtimeEvents[0];
assert.equal(sessionStarted?.type, "session.started");
if (sessionStarted?.type === "session.started") {
assert.equal(sessionStarted.threadId, THREAD_ID);
}
const threadStarted = runtimeEvents[4];
assert.equal(threadStarted?.type, "thread.started");
if (threadStarted?.type === "thread.started") {
assert.equal(threadStarted.threadId, THREAD_ID);
assert.deepEqual(threadStarted.payload, {
providerThreadId: "sdk-thread-real",
});
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("bridges approval request/response lifecycle through canUseTool", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "approval-required",
});
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
const createInput = harness.getLastCreateQueryInput();
const canUseTool = createInput?.options.canUseTool;
assert.equal(typeof canUseTool, "function");
if (!canUseTool) {
return;
}
const permissionPromise = canUseTool(
"Bash",
{ command: "pwd" },
{
signal: new AbortController().signal,
suggestions: [
{
type: "setMode",
mode: "default",
destination: "session",
},
],
toolUseID: "tool-use-1",
},
);
const requested = yield* Stream.runHead(adapter.streamEvents);
assert.equal(requested._tag, "Some");
if (requested._tag !== "Some") {
return;
}
assert.equal(requested.value.type, "request.opened");
if (requested.value.type !== "request.opened") {
return;
}
const runtimeRequestId = requested.value.requestId;
assert.equal(typeof runtimeRequestId, "string");
if (runtimeRequestId === undefined) {
return;
}
yield* adapter.respondToRequest(
session.threadId,
ApprovalRequestId.makeUnsafe(runtimeRequestId),
"accept",
);
const resolved = yield* Stream.runHead(adapter.streamEvents);
assert.equal(resolved._tag, "Some");
if (resolved._tag !== "Some") {
return;
}
assert.equal(resolved.value.type, "request.resolved");
if (resolved.value.type !== "request.resolved") {
return;
}
assert.equal(resolved.value.requestId, requested.value.requestId);
assert.equal(resolved.value.payload.decision, "accept");
const permissionResult = yield* Effect.promise(() => permissionPromise);
assert.equal((permissionResult as PermissionResult).behavior, "allow");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("passes parsed resume cursor values to Claude query options", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const session = yield* adapter.startSession({
threadId: RESUME_THREAD_ID,
provider: "claudeCode",
resumeCursor: {
threadId: "resume-thread-1",
resume: "550e8400-e29b-41d4-a716-446655440000",
resumeSessionAt: "assistant-99",
turnCount: 3,
},
runtimeMode: "full-access",
});
assert.equal(session.threadId, RESUME_THREAD_ID);
assert.deepEqual(session.resumeCursor, {
threadId: RESUME_THREAD_ID,
resume: "550e8400-e29b-41d4-a716-446655440000",
resumeSessionAt: "assistant-99",
turnCount: 3,
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.resume, "550e8400-e29b-41d4-a716-446655440000");
assert.equal(createInput?.options.resumeSessionAt, "assistant-99");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("does not synthesize resume session id from generated thread ids", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
assert.equal("resume" in (session.resumeCursor as Record<string, unknown>), false);
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.resume, undefined);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect(
"supports rollbackThread by trimming in-memory turns and preserving earlier turns",
() => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
const firstTurn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "first",
attachments: [],
});
const firstCompletedFiber = yield* Stream.filter(
adapter.streamEvents,
(event) => event.type === "turn.completed",
).pipe(Stream.runHead, Effect.forkChild);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-rollback",
uuid: "result-first",
} as unknown as SDKMessage);
const firstCompleted = yield* Fiber.join(firstCompletedFiber);
assert.equal(firstCompleted._tag, "Some");
if (firstCompleted._tag === "Some" && firstCompleted.value.type === "turn.completed") {
assert.equal(String(firstCompleted.value.turnId), String(firstTurn.turnId));
}
const secondTurn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "second",
attachments: [],
});
const secondCompletedFiber = yield* Stream.filter(
adapter.streamEvents,
(event) => event.type === "turn.completed",
).pipe(Stream.runHead, Effect.forkChild);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-rollback",
uuid: "result-second",
} as unknown as SDKMessage);
const secondCompleted = yield* Fiber.join(secondCompletedFiber);
assert.equal(secondCompleted._tag, "Some");
if (secondCompleted._tag === "Some" && secondCompleted.value.type === "turn.completed") {
assert.equal(String(secondCompleted.value.turnId), String(secondTurn.turnId));
}
const threadBeforeRollback = yield* adapter.readThread(session.threadId);
assert.equal(threadBeforeRollback.turns.length, 2);
const rolledBack = yield* adapter.rollbackThread(session.threadId, 1);
assert.equal(rolledBack.turns.length, 1);
assert.equal(rolledBack.turns[0]?.id, firstTurn.turnId);
const threadAfterRollback = yield* adapter.readThread(session.threadId);
assert.equal(threadAfterRollback.turns.length, 1);
assert.equal(threadAfterRollback.turns[0]?.id, firstTurn.turnId);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
},
);
it.effect("updates model on sendTurn when model override is provided", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
model: "claude-opus-4-6",
attachments: [],
});
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6"]);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("writes provider-native observability records when enabled", () => {
const nativeEvents: Array<{
event?: {
provider?: string;
method?: string;
threadId?: string;
turnId?: string;
};
}> = [];
const harness = makeHarness({
nativeEventLogger: {
filePath: "memory://claude-native-events",
write: (event) => {
nativeEvents.push(event as (typeof nativeEvents)[number]);
return Effect.void;
},
close: () => Effect.void,
},
});
return Effect.gen(function* () {
const adapter = yield* ClaudeCodeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeCode",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
const turnCompletedFiber = yield* Stream.filter(
adapter.streamEvents,
(event) => event.type === "turn.completed",
).pipe(Stream.runHead, Effect.forkChild);
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-native-log",
uuid: "stream-native-log",
parent_tool_use_id: null,
event: {
type: "content_block_delta",
index: 0,
delta: {
type: "text_delta",
text: "hi",
},
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-native-log",
uuid: "result-native-log",
} as unknown as SDKMessage);
const turnCompleted = yield* Fiber.join(turnCompletedFiber);
assert.equal(turnCompleted._tag, "Some");
assert.equal(nativeEvents.length > 0, true);
assert.equal(
nativeEvents.some((record) => record.event?.provider === "claudeCode"),
true,
);
assert.equal(
nativeEvents.some(
(record) =>
String(
(record.event as { readonly providerThreadId?: string } | undefined)
?.providerThreadId,
) === "sdk-session-native-log",
),
true,
);
assert.equal(
nativeEvents.some((record) => String(record.event?.turnId) === String(turn.turnId)),
true,
);
assert.equal(
nativeEvents.some(
(record) => record.event?.method === "claude/stream_event/content_block_delta/text_delta",
),
true,
);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
});
@@ -0,0 +1,149 @@
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import { query, type SpawnOptions, type SpawnedProcess } from "@anthropic-ai/claude-agent-sdk";
import { afterEach, describe, expect, it } from "vitest";
async function* emptyPrompt(): AsyncGenerator<never, void, void> {}
class FakeClaudeCodeProcess implements SpawnedProcess {
readonly stdin = new PassThrough();
readonly stdout = new PassThrough();
killed = false;
exitCode: number | null = null;
private readonly events = new EventEmitter();
private bufferedInput = "";
constructor(
private readonly onMessage: (
message: Record<string, unknown>,
process: FakeClaudeCodeProcess,
) => void,
) {
this.stdin.setEncoding("utf8");
this.stdin.on("data", (chunk: string) => {
this.bufferedInput += chunk;
this.drainInput();
});
}
emitJson(message: unknown): void {
this.stdout.write(`${JSON.stringify(message)}\n`);
}
kill(_signal: NodeJS.Signals): boolean {
this.killed = true;
this.exitCode = 0;
this.stdout.end();
this.events.emit("exit", 0, null);
return true;
}
on(
event: "exit" | "error",
listener:
| ((code: number | null, signal: NodeJS.Signals | null) => void)
| ((error: Error) => void),
): void {
this.events.on(event, listener);
}
once(
event: "exit" | "error",
listener:
| ((code: number | null, signal: NodeJS.Signals | null) => void)
| ((error: Error) => void),
): void {
this.events.once(event, listener);
}
off(
event: "exit" | "error",
listener:
| ((code: number | null, signal: NodeJS.Signals | null) => void)
| ((error: Error) => void),
): void {
this.events.off(event, listener);
}
private drainInput(): void {
while (true) {
const newlineIndex = this.bufferedInput.indexOf("\n");
if (newlineIndex === -1) {
return;
}
const line = this.bufferedInput.slice(0, newlineIndex).trim();
this.bufferedInput = this.bufferedInput.slice(newlineIndex + 1);
if (line.length === 0) {
continue;
}
this.onMessage(JSON.parse(line) as Record<string, unknown>, this);
}
}
}
describe("Claude SDK fast mode probe", () => {
let activeQuery: ReturnType<typeof query> | null = null;
afterEach(() => {
activeQuery?.close();
activeQuery = null;
});
it("passes fast mode through the SDK settings flag", async () => {
let spawnOptions: SpawnOptions | undefined;
activeQuery = query({
prompt: emptyPrompt(),
options: {
persistSession: false,
settings: {
fastMode: true,
},
spawnClaudeCodeProcess: (options): SpawnedProcess => {
spawnOptions = options;
return new FakeClaudeCodeProcess((message, process) => {
if (
message.type !== "control_request" ||
typeof message.request_id !== "string" ||
!message.request ||
typeof message.request !== "object" ||
(message.request as { subtype?: unknown }).subtype !== "initialize"
) {
return;
}
process.emitJson({
type: "control_response",
response: {
subtype: "success",
request_id: message.request_id,
response: {
commands: [],
agents: [],
output_style: "default",
available_output_styles: ["default"],
models: [],
account: {
subscriptionType: "max",
},
fast_mode_state: "on",
},
},
});
});
},
},
});
const initialization = await activeQuery.initializationResult();
expect(initialization.fast_mode_state).toBe("on");
expect(spawnOptions).toBeDefined();
const settingsFlagIndex = spawnOptions?.args.indexOf("--settings") ?? -1;
expect(settingsFlagIndex).toBeGreaterThan(-1);
expect(JSON.parse(spawnOptions?.args[settingsFlagIndex + 1] ?? "")).toEqual({
fastMode: true,
});
});
});
@@ -162,7 +162,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
const adapter = yield* CodexAdapter;
const result = yield* adapter
.startSession({
provider: "claudeCode",
provider: "claudeAgent",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
})
@@ -174,7 +174,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
new ProviderAdapterValidationError({
provider: "codex",
operation: "startSession",
issue: "Expected provider 'codex' but received 'claudeCode'.",
issue: "Expected provider 'codex' but received 'claudeAgent'.",
}),
);
assert.equal(validationManager.startSessionImpl.mock.calls.length, 0);
@@ -800,6 +800,48 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}
}),
);
it.effect("prefers manager-assigned turn ids for Codex task events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-task-started-parent-turn"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-parent"),
itemId: asItemId("call-collab-1"),
createdAt: new Date().toISOString(),
method: "codex/event/task_started",
payload: {
id: "turn-child",
msg: {
type: "task_started",
turn_id: "turn-child",
collaboration_mode_kind: "default",
},
conversationId: "child-provider-thread",
},
} satisfies ProviderEvent);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "task.started");
if (firstEvent.value.type !== "task.started") {
return;
}
assert.equal(firstEvent.value.turnId, "turn-parent");
assert.equal(firstEvent.value.itemId, "call-collab-1");
assert.equal(firstEvent.value.providerRefs?.providerTurnId, "turn-parent");
assert.equal(firstEvent.value.providerRefs?.providerItemId, "call-collab-1");
assert.equal(firstEvent.value.payload.taskId, "turn-child");
}),
);
});
afterAll(() => {
@@ -109,6 +109,14 @@ function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function toTurnId(value: string | undefined): TurnId | undefined {
return value?.trim() ? TurnId.makeUnsafe(value) : undefined;
}
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
return value?.trim() ? ProviderItemId.makeUnsafe(value) : undefined;
}
function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "interrupted" {
switch (value) {
case "completed":
@@ -415,27 +423,27 @@ function codexEventBase(
): Omit<ProviderRuntimeEvent, "type" | "payload"> {
const payload = asObject(event.payload);
const msg = codexEventMessage(payload);
const turnId = asString(msg?.turn_id) ?? asString(msg?.turnId);
const itemId = asString(msg?.item_id) ?? asString(msg?.itemId);
const turnId = event.turnId ?? toTurnId(asString(msg?.turn_id) ?? asString(msg?.turnId));
const itemId = event.itemId ?? toProviderItemId(asString(msg?.item_id) ?? asString(msg?.itemId));
const requestId = asString(msg?.request_id) ?? asString(msg?.requestId);
const base = runtimeEventBase(event, canonicalThreadId);
const providerRefs = base.providerRefs
? {
...base.providerRefs,
...(turnId ? { providerTurnId: turnId } : {}),
...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
...(itemId ? { providerItemId: itemId } : {}),
...(requestId ? { providerRequestId: requestId } : {}),
}
: {
...(turnId ? { providerTurnId: turnId } : {}),
...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
...(itemId ? { providerItemId: itemId } : {}),
...(requestId ? { providerRequestId: requestId } : {}),
};
return {
...base,
...(turnId ? { turnId: TurnId.makeUnsafe(turnId) } : {}),
...(itemId ? { itemId: asRuntimeItemId(ProviderItemId.makeUnsafe(itemId)) } : {}),
...(turnId ? { turnId } : {}),
...(itemId ? { itemId: asRuntimeItemId(itemId) } : {}),
...(requestId ? { requestId: asRuntimeRequestId(requestId) } : {}),
...(Object.keys(providerRefs).length > 0 ? { providerRefs } : {}),
};
@@ -4,7 +4,7 @@ import { assertFailure } from "@effect/vitest/utils";
import { Effect, Layer, Stream } from "effect";
import { ClaudeCodeAdapter, ClaudeCodeAdapterShape } from "../Services/ClaudeCodeAdapter.ts";
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,8 +28,8 @@ const fakeCodexAdapter: CodexAdapterShape = {
streamEvents: Stream.empty,
};
const fakeClaudeAdapter: ClaudeCodeAdapterShape = {
provider: "claudeCode",
const fakeClaudeAdapter: ClaudeAdapterShape = {
provider: "claudeAgent",
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
@@ -51,7 +51,7 @@ const layer = it.layer(
ProviderAdapterRegistryLive,
Layer.mergeAll(
Layer.succeed(CodexAdapter, fakeCodexAdapter),
Layer.succeed(ClaudeCodeAdapter, fakeClaudeAdapter),
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
),
),
NodeServices.layer,
@@ -63,12 +63,12 @@ layer("ProviderAdapterRegistryLive", (it) => {
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry;
const codex = yield* registry.getByProvider("codex");
const claude = yield* registry.getByProvider("claudeCode");
const claude = yield* registry.getByProvider("claudeAgent");
assert.equal(codex, fakeCodexAdapter);
assert.equal(claude, fakeClaudeAdapter);
const providers = yield* registry.listProviders();
assert.deepEqual(providers, ["codex", "claudeCode"]);
assert.deepEqual(providers, ["codex", "claudeAgent"]);
}),
);
@@ -1,7 +1,7 @@
/**
* ProviderAdapterRegistryLive - In-memory provider adapter lookup layer.
*
* Binds provider kinds (codex/claudeCode/...) to concrete adapter services.
* Binds provider kinds (codex/claudeAgent/...) 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,7 @@ import {
ProviderAdapterRegistry,
type ProviderAdapterRegistryShape,
} from "../Services/ProviderAdapterRegistry.ts";
import { ClaudeCodeAdapter } from "../Services/ClaudeCodeAdapter.ts";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
export interface ProviderAdapterRegistryLiveOptions {
@@ -27,7 +27,7 @@ const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOption
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter, yield* ClaudeCodeAdapter];
: [yield* CodexAdapter, yield* ClaudeAdapter];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
@@ -5,9 +5,11 @@ import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
checkClaudeProviderStatus,
checkCodexProviderStatus,
hasCustomModelProvider,
parseAuthStatusFromOutput,
parseClaudeAuthStatusFromOutput,
readCodexConfigModelProvider,
} from "./ProviderHealth";
@@ -464,4 +466,175 @@ 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");
});
});
});
+207 -11
View File
@@ -26,6 +26,7 @@ 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 ────────────────────────────────────────────────────
@@ -44,12 +45,7 @@ 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("command not found: codex") ||
lower.includes("spawn codex enoent") ||
lower.includes("enoent") ||
lower.includes("notfound")
);
return lower.includes("enoent") || lower.includes("notfound");
}
function detailFromResult(
@@ -264,6 +260,27 @@ 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<
@@ -390,18 +407,197 @@ 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 codexStatusFiber = yield* checkCodexProviderStatus.pipe(
Effect.map(Array.of),
Effect.forkScoped,
);
const statusesFiber = yield* Effect.all([checkCodexProviderStatus, checkClaudeProviderStatus], {
concurrency: "unbounded",
}).pipe(Effect.forkScoped);
return {
getStatuses: Fiber.join(codexStatusFiber),
getStatuses: Fiber.join(statusesFiber),
} satisfies ProviderHealthShape;
}),
);
@@ -52,7 +52,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex" | "claudeCode";
readonly provider: ProviderKind;
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -217,15 +217,15 @@ const sleep = (ms: number) =>
function makeProviderServiceLayer() {
const codex = makeFakeCodexAdapter();
const claude = makeFakeCodexAdapter("claudeCode");
const claude = makeFakeCodexAdapter("claudeAgent");
const registry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(codex.adapter)
: provider === "claudeCode"
: provider === "claudeAgent"
? Effect.succeed(claude.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex", "claudeCode"]),
listProviders: () => Effect.succeed(["codex", "claudeAgent"]),
};
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
@@ -537,24 +537,24 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("routes explicit claudeCode provider session starts to the claude adapter", () =>
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: "claudeCode",
provider: "claudeAgent",
threadId: asThreadId("thread-claude"),
cwd: "/tmp/project-claude",
runtimeMode: "full-access",
});
assert.equal(session.provider, "claudeCode");
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, "claudeCode");
assert.equal(startPayload.provider, "claudeAgent");
assert.equal(startPayload.cwd, "/tmp/project-claude");
}
}),
@@ -600,6 +600,57 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("recovers stale claudeAgent sessions for sendTurn using persisted cwd", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const initial = yield* provider.startSession(asThreadId("thread-claude-send-turn"), {
provider: "claudeAgent",
threadId: asThreadId("thread-claude-send-turn"),
cwd: "/tmp/project-claude-send-turn",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
runtimeMode: "full-access",
});
yield* routing.claude.stopAll();
routing.claude.startSession.mockClear();
routing.claude.sendTurn.mockClear();
yield* provider.sendTurn({
threadId: initial.threadId,
input: "resume with claude",
attachments: [],
});
assert.equal(routing.claude.startSession.mock.calls.length, 1);
const resumedStartInput = routing.claude.startSession.mock.calls[0]?.[0];
assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true);
if (resumedStartInput && typeof resumedStartInput === "object") {
const startPayload = resumedStartInput as {
provider?: string;
cwd?: string;
modelOptions?: unknown;
resumeCursor?: unknown;
threadId?: string;
};
assert.equal(startPayload.provider, "claudeAgent");
assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn");
assert.deepEqual(startPayload.modelOptions, {
claudeAgent: {
effort: "max",
},
});
assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);
assert.equal(startPayload.threadId, initial.threadId);
}
assert.equal(routing.claude.sendTurn.mock.calls.length, 1);
}),
);
it.effect("lists no sessions after adapter runtime clears", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -88,17 +88,29 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
function toRuntimePayloadFromSession(
session: ProviderSession,
extra?: { readonly providerOptions?: unknown },
extra?: { readonly modelOptions?: unknown; readonly providerOptions?: unknown },
): Record<string, unknown> {
return {
cwd: session.cwd ?? null,
model: session.model ?? null,
activeTurnId: session.activeTurnId ?? null,
lastError: session.lastError ?? null,
...(extra?.modelOptions !== undefined ? { modelOptions: extra.modelOptions } : {}),
...(extra?.providerOptions !== undefined ? { providerOptions: extra.providerOptions } : {}),
};
}
function readPersistedModelOptions(
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): Record<string, unknown> | undefined {
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
return undefined;
}
const raw = "modelOptions" in runtimePayload ? runtimePayload.modelOptions : undefined;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
return raw as Record<string, unknown>;
}
function readPersistedProviderOptions(
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): Record<string, unknown> | undefined {
@@ -150,7 +162,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const upsertSessionBinding = (
session: ProviderSession,
threadId: ThreadId,
extra?: { readonly providerOptions?: unknown },
extra?: { readonly modelOptions?: unknown; readonly providerOptions?: unknown },
) =>
directory.upsert({
threadId,
@@ -213,12 +225,14 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelOptions = readPersistedModelOptions(input.binding.runtimePayload);
const persistedProviderOptions = readPersistedProviderOptions(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelOptions ? { modelOptions: persistedModelOptions } : {}),
...(persistedProviderOptions ? { providerOptions: persistedProviderOptions } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
@@ -292,6 +306,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
yield* upsertSessionBinding(session, threadId, {
modelOptions: input.modelOptions,
providerOptions: input.providerOptions,
});
yield* analytics.record("provider.session.started", {
@@ -141,8 +141,8 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
yield* runtimeRepository.upsert({
threadId,
providerName: "claudeCode",
adapterKey: "claudeCode",
providerName: "claudeAgent",
adapterKey: "claudeAgent",
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 === "claudeCode") {
if (providerName === "codex" || providerName === "claudeAgent") {
return Effect.succeed(providerName);
}
return Effect.fail(
@@ -0,0 +1,30 @@
/**
* ClaudeAdapter - Claude Agent implementation of the generic provider adapter contract.
*
* This service owns Claude runtime/session semantics and emits canonical
* provider runtime events. It does not perform cross-provider routing, shared
* event fan-out, or checkpoint orchestration.
*
* Uses Effect `ServiceMap.Service` for dependency injection and returns the
* shared provider-adapter error channel with `provider: "claudeAgent"` context.
*
* @module ClaudeAdapter
*/
import { ServiceMap } from "effect";
import type { ProviderAdapterError } from "../Errors.ts";
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
/**
* ClaudeAdapterShape - Service API for the Claude Agent provider adapter.
*/
export interface ClaudeAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
readonly provider: "claudeAgent";
}
/**
* ClaudeAdapter - Service tag for Claude Agent provider adapter operations.
*/
export class ClaudeAdapter extends ServiceMap.Service<ClaudeAdapter, ClaudeAdapterShape>()(
"t3/provider/Services/ClaudeAdapter",
) {}
@@ -1,31 +0,0 @@
/**
* ClaudeCodeAdapter - Claude Code 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: "claudeCode"` context.
*
* @module ClaudeCodeAdapter
*/
import { ServiceMap } from "effect";
import type { ProviderAdapterError } from "../Errors.ts";
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
/**
* ClaudeCodeAdapterShape - Service API for the Claude Code provider adapter.
*/
export interface ClaudeCodeAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
readonly provider: "claudeCode";
}
/**
* ClaudeCodeAdapter - Service tag for Claude Code provider adapter operations.
*/
export class ClaudeCodeAdapter extends ServiceMap.Service<
ClaudeCodeAdapter,
ClaudeCodeAdapterShape
>()("t3/provider/Services/ClaudeCodeAdapter") {}
@@ -1,8 +1,8 @@
/**
* ProviderHealth - Provider readiness snapshot service.
*
* Owns startup-time provider health checks (install/auth reachability) and
* exposes the cached results to transport layers.
* Owns provider health checks (install/auth reachability) and exposes the
* latest results to transport layers.
*
* @module ProviderHealth
*/
@@ -12,7 +12,7 @@ import type { Effect } from "effect";
export interface ProviderHealthShape {
/**
* Read provider health statuses computed at server startup.
* Read the latest provider health statuses.
*/
readonly getStatuses: Effect.Effect<ReadonlyArray<ServerProviderStatus>>;
}
+2 -2
View File
@@ -19,7 +19,7 @@ import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus";
import { ProviderUnsupportedError } from "./provider/Errors";
import { makeClaudeCodeAdapterLive } from "./provider/Layers/ClaudeCodeAdapter";
import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter";
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
@@ -59,7 +59,7 @@ export function makeServerProviderLayer(): Layer.Layer<
const codexAdapterLayer = makeCodexAdapterLive(
nativeEventLogger ? { nativeEventLogger } : undefined,
);
const claudeAdapterLayer = makeClaudeCodeAdapterLive(
const claudeAdapterLayer = makeClaudeAdapterLive(
nativeEventLogger ? { nativeEventLogger } : undefined,
);
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
+1 -1
View File
@@ -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()
+31 -4
View File
@@ -1,6 +1,8 @@
import { Schema } from "effect";
import { describe, expect, it } from "vitest";
import {
AppSettingsSchema,
DEFAULT_TIMESTAMP_FORMAT,
getAppModelOptions,
normalizeCustomModelSlugs,
@@ -22,8 +24,8 @@ describe("normalizeCustomModelSlugs", () => {
});
it("normalizes provider-specific aliases for claude", () => {
expect(normalizeCustomModelSlugs(["sonnet"], "claudeCode")).toEqual([]);
expect(normalizeCustomModelSlugs(["claude/custom-sonnet"], "claudeCode")).toEqual([
expect(normalizeCustomModelSlugs(["sonnet"], "claudeAgent")).toEqual([]);
expect(normalizeCustomModelSlugs(["claude/custom-sonnet"], "claudeAgent")).toEqual([
"claude/custom-sonnet",
]);
});
@@ -35,6 +37,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",
@@ -53,7 +56,7 @@ describe("getAppModelOptions", () => {
});
});
it("keeps a saved custom provider model available as an exact slug option", () => {
const options = getAppModelOptions("claudeCode", ["claude/custom-opus"], "claude/custom-opus");
const options = getAppModelOptions("claudeAgent", ["claude/custom-opus"], "claude/custom-opus");
expect(options.some((option) => option.slug === "claude/custom-opus" && option.isCustom)).toBe(
true,
@@ -81,8 +84,32 @@ describe("timestamp format defaults", () => {
describe("provider-specific custom models", () => {
it("includes provider-specific custom slugs in non-codex model lists", () => {
const claudeOptions = getAppModelOptions("claudeCode", ["claude/custom-opus"]);
const claudeOptions = getAppModelOptions("claudeAgent", ["claude/custom-opus"]);
expect(claudeOptions.some((option) => option.slug === "claude/custom-opus")).toBe(true);
});
});
describe("AppSettingsSchema", () => {
it("fills decoding defaults for persisted settings that predate newer keys", () => {
const decode = Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema));
expect(
decode(
JSON.stringify({
codexBinaryPath: "/usr/local/bin/codex",
confirmThreadDelete: false,
}),
),
).toMatchObject({
codexBinaryPath: "/usr/local/bin/codex",
codexHomePath: "",
defaultThreadEnvMode: "local",
confirmThreadDelete: false,
enableAssistantStreaming: false,
timestampFormat: DEFAULT_TIMESTAMP_FORMAT,
customCodexModels: [],
customClaudeModels: [],
});
});
});
+31 -28
View File
@@ -1,43 +1,46 @@
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";
import { EnvMode } from "./components/BranchToolbar.logic";
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
const MAX_CUSTOM_MODEL_COUNT = 32;
export const MAX_CUSTOM_MODEL_LENGTH = 256;
export const TIMESTAMP_FORMAT_OPTIONS = ["locale", "12-hour", "24-hour"] as const;
export type TimestampFormat = (typeof TIMESTAMP_FORMAT_OPTIONS)[number];
export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
export type TimestampFormat = typeof TimestampFormat.Type;
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)),
claudeCode: new Set(getModelOptions("claudeCode").map((option) => option.slug)),
claudeAgent: new Set(getModelOptions("claudeAgent").map((option) => option.slug)),
};
const AppSettingsSchema = Schema.Struct({
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
Schema.withConstructorDefault(() => Option.some("")),
),
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
Schema.withConstructorDefault(() => Option.some("")),
),
defaultThreadEnvMode: Schema.Literals(["local", "worktree"]).pipe(
Schema.withConstructorDefault(() => Option.some("local")),
),
confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))),
enableAssistantStreaming: Schema.Boolean.pipe(
Schema.withConstructorDefault(() => Option.some(false)),
),
timestampFormat: Schema.Literals(["locale", "12-hour", "24-hour"]).pipe(
Schema.withConstructorDefault(() => Option.some(DEFAULT_TIMESTAMP_FORMAT)),
),
customCodexModels: Schema.Array(Schema.String).pipe(
Schema.withConstructorDefault(() => Option.some([])),
),
customClaudeModels: Schema.Array(Schema.String).pipe(
Schema.withConstructorDefault(() => Option.some([])),
),
const withDefaults =
<
S extends Schema.Top & Schema.WithoutConstructorDefault,
D extends S["~type.make.in"] & S["Encoded"],
>(
fallback: () => D,
) =>
(schema: S) =>
schema.pipe(
Schema.withConstructorDefault(() => Option.some(fallback())),
Schema.withDecodingDefault(() => fallback()),
);
export const AppSettingsSchema = Schema.Struct({
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
defaultThreadEnvMode: EnvMode.pipe(withDefaults(() => "local" as const satisfies EnvMode)),
confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),
enableAssistantStreaming: Schema.Boolean.pipe(withDefaults(() => false)),
timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),
customCodexModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
customClaudeModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
textGenerationModel: Schema.optional(TrimmedNonEmptyString),
});
export type AppSettings = typeof AppSettingsSchema.Type;
export interface AppModelOption {
@@ -81,7 +84,7 @@ function normalizeAppSettings(settings: AppSettings): AppSettings {
return {
...settings,
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeCode"),
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeAgent"),
};
}
export function getAppModelOptions(
@@ -1,6 +1,8 @@
import type { GitBranch } from "@t3tools/contracts";
import { Schema } from "effect";
export type EnvMode = "local" | "worktree";
export const EnvMode = Schema.Literals(["local", "worktree"]);
export type EnvMode = typeof EnvMode.Type;
export function resolveEffectiveEnvMode(input: {
activeWorktreePath: string | null;
@@ -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";
@@ -150,6 +154,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;
@@ -221,6 +244,7 @@ function createSnapshotForTargetUser(options: {
messages,
activities: [],
proposedPlans: [],
workUnits: [],
checkpoints: [],
session: {
threadId: THREAD_ID,
@@ -275,6 +299,7 @@ function addThreadToSnapshot(
messages: [],
activities: [],
proposedPlans: [],
workUnits: [],
checkpoints: [],
session: {
threadId,
@@ -345,6 +370,8 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
id: "plan-browser-test",
turnId: null,
planMarkdown,
implementedAt: null,
implementationThreadId: null,
createdAt: isoAt(1_000),
updatedAt: isoAt(1_001),
},
@@ -531,6 +558,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 +1045,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.",
});
});
});
+47 -1
View File
@@ -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";
@@ -122,6 +127,47 @@ export function getCustomModelOptionsByProvider(settings: {
}): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
return {
codex: getAppModelOptions("codex", settings.customCodexModels),
claudeCode: getAppModelOptions("claudeCode", settings.customClaudeModels),
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.",
};
}
File diff suppressed because it is too large. Load diff
+330 -98
View File
@@ -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 }));
+1 -1
View File
@@ -146,7 +146,7 @@ export const OpenAI: Icon = (props) => (
export const ClaudeAI: Icon = (props) => (
<svg {...props} preserveAspectRatio="xMidYMid" viewBox="0 0 256 257">
<path
fill="#D97757"
fill="currentColor"
d="m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0 82.05 1.426l4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999-.064.065Z"
/>
</svg>
@@ -98,6 +98,7 @@ function createMinimalSnapshot(): OrchestrationReadModel {
],
activities: [],
proposedPlans: [],
workUnits: [],
checkpoints: [],
session: {
threadId: THREAD_ID,
@@ -141,6 +141,8 @@ describe("resolveThreadStatusPill", () => {
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
planMarkdown: "# Plan",
implementedAt: null,
implementationThreadId: null,
},
],
session: {
@@ -155,6 +157,35 @@ describe("resolveThreadStatusPill", () => {
).toMatchObject({ label: "Plan Ready", pulse: false });
});
it("does not show plan ready after the proposed plan was implemented elsewhere", () => {
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
latestTurn: makeLatestTurn(),
proposedPlans: [
{
id: "plan-1" as never,
turnId: "turn-1" as never,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
planMarkdown: "# Plan",
implementedAt: "2026-03-09T10:06:00.000Z",
implementationThreadId: "thread-implement" as never,
},
],
session: {
...baseThread.session,
status: "ready",
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Completed", pulse: false });
});
it("shows completed when there is an unseen completion and no active blocker", () => {
expect(
resolveThreadStatusPill({
+9 -3
View File
@@ -1,6 +1,10 @@
import type { Thread } from "../types";
import { cn } from "../lib/utils";
import { findLatestProposedPlan, isLatestTurnSettled } from "../session-logic";
import {
findLatestProposedPlan,
hasActionableProposedPlan,
isLatestTurnSettled,
} from "../session-logic";
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
export type SidebarNewThreadEnvMode = "local" | "worktree";
@@ -51,7 +55,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(
@@ -124,7 +128,9 @@ export function resolveThreadStatusPill(input: {
!hasPendingUserInput &&
thread.interactionMode === "plan" &&
isLatestTurnSettled(thread.latestTurn, thread.session) &&
findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? null) !== null;
hasActionableProposedPlan(
findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? null),
);
if (hasPlanReadyPrompt) {
return {
label: "Plan Ready",
+46 -8
View File
@@ -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,176 @@
import "../../index.css";
import { ThreadId } from "@t3tools/contracts";
import { page } from "vitest/browser";
import { afterEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
import { ClaudeTraitsPicker } from "./ClaudeTraitsPicker";
import { useComposerDraftStore } from "../../composerDraftStore";
async function mountPicker(props?: {
model?: string;
prompt?: string;
effort?: "low" | "medium" | "high" | "max" | "ultrathink" | null;
thinkingEnabled?: boolean | null;
fastModeEnabled?: boolean;
}) {
const threadId = ThreadId.makeUnsafe("thread-claude-traits");
const draftsByThreadId = {} as ReturnType<
typeof useComposerDraftStore.getState
>["draftsByThreadId"];
draftsByThreadId[threadId] = {
prompt: props?.prompt ?? "",
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
terminalContexts: [],
provider: "claudeAgent",
model: props?.model ?? "claude-opus-4-6",
modelOptions: {
claudeAgent: {
...(props?.effort ? { effort: props.effort } : {}),
...(props?.thinkingEnabled === false ? { thinking: false } : {}),
...(props?.fastModeEnabled ? { fastMode: true } : {}),
},
},
runtimeMode: null,
interactionMode: null,
};
useComposerDraftStore.setState({
draftsByThreadId,
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
const host = document.createElement("div");
document.body.append(host);
const onPromptChange = vi.fn();
const screen = await render(
<ClaudeTraitsPicker
threadId={threadId}
model={props?.model ?? "claude-opus-4-6"}
onPromptChange={onPromptChange}
/>,
{ container: host },
);
return {
onPromptChange,
cleanup: async () => {
await screen.unmount();
host.remove();
},
};
}
describe("ClaudeTraitsPicker", () => {
afterEach(() => {
document.body.innerHTML = "";
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
});
it("shows fast mode controls for Opus", async () => {
const mounted = await mountPicker();
try {
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Fast Mode");
expect(text).toContain("off");
expect(text).toContain("on");
});
} finally {
await mounted.cleanup();
}
});
it("hides fast mode controls for non-Opus models", async () => {
const mounted = await mountPicker({ model: "claude-sonnet-4-6" });
try {
await page.getByRole("button").click();
await vi.waitFor(() => {
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
});
} finally {
await mounted.cleanup();
}
});
it("shows only the provided effort options", async () => {
const mounted = await mountPicker({
model: "claude-sonnet-4-6",
});
try {
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Low");
expect(text).toContain("Medium");
expect(text).toContain("High");
expect(text).not.toContain("Max");
expect(text).toContain("Ultrathink");
});
} finally {
await mounted.cleanup();
}
});
it("shows a thinking on/off dropdown for Haiku", async () => {
const mounted = await mountPicker({
model: "claude-haiku-4-5",
thinkingEnabled: true,
});
try {
await vi.waitFor(() => {
expect(document.body.textContent ?? "").toContain("Thinking On");
});
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Thinking");
expect(text).toContain("On (default)");
expect(text).toContain("Off");
});
} finally {
await mounted.cleanup();
}
});
it("shows prompt-controlled Ultrathink state with disabled effort controls", async () => {
const mounted = await mountPicker({
effort: "high",
model: "claude-opus-4-6",
prompt: "Ultrathink:\nInvestigate this",
fastModeEnabled: false,
});
try {
await vi.waitFor(() => {
expect(document.body.textContent ?? "").toContain("Ultrathink");
expect(document.body.textContent ?? "").not.toContain("Ultrathink · Prompt");
});
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Effort");
expect(text).toContain("Remove Ultrathink from the prompt to change effort.");
expect(text).not.toContain("Fallback Effort");
});
} finally {
await mounted.cleanup();
}
});
});
@@ -0,0 +1,257 @@
import {
type ClaudeCodeEffort,
type ClaudeModelOptions,
type ProviderModelOptions,
type ThreadId,
} from "@t3tools/contracts";
import {
applyClaudePromptEffortPrefix,
getDefaultReasoningEffort,
getReasoningEffortOptions,
normalizeClaudeModelOptions,
resolveReasoningEffortForProvider,
supportsClaudeFastMode,
supportsClaudeThinkingToggle,
supportsClaudeUltrathinkKeyword,
isClaudeUltrathinkPrompt,
} from "@t3tools/shared/model";
import { memo, useState } from "react";
import { ChevronDownIcon } from "lucide-react";
import { Button } from "../ui/button";
import {
Menu,
MenuGroup,
MenuPopup,
MenuRadioGroup,
MenuRadioItem,
MenuSeparator as MenuDivider,
MenuTrigger,
} from "../ui/menu";
import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore";
const CLAUDE_EFFORT_LABELS: Record<ClaudeCodeEffort, string> = {
low: "Low",
medium: "Medium",
high: "High",
max: "Max",
ultrathink: "Ultrathink",
};
const ULTRATHINK_PROMPT_PREFIX = "Ultrathink:\n";
function getSelectedClaudeTraits(
model: string | null | undefined,
prompt: string,
modelOptions: ClaudeModelOptions | null | undefined,
): {
effort: Exclude<ClaudeCodeEffort, "ultrathink"> | null;
thinkingEnabled: boolean | null;
fastModeEnabled: boolean;
options: ReadonlyArray<ClaudeCodeEffort>;
ultrathinkPromptControlled: boolean;
supportsFastMode: boolean;
} {
const options = getReasoningEffortOptions("claudeAgent", model);
const defaultReasoningEffort = getDefaultReasoningEffort("claudeAgent") as Exclude<
ClaudeCodeEffort,
"ultrathink"
>;
const resolvedEffort = resolveReasoningEffortForProvider("claudeAgent", modelOptions?.effort);
const effort =
resolvedEffort && resolvedEffort !== "ultrathink" && options.includes(resolvedEffort)
? resolvedEffort
: options.includes(defaultReasoningEffort)
? defaultReasoningEffort
: null;
const thinkingEnabled = supportsClaudeThinkingToggle(model)
? (modelOptions?.thinking ?? true)
: null;
const supportsFastMode = supportsClaudeFastMode(model);
return {
effort,
thinkingEnabled,
fastModeEnabled: supportsFastMode && modelOptions?.fastMode === true,
options,
ultrathinkPromptControlled:
supportsClaudeUltrathinkKeyword(model) && isClaudeUltrathinkPrompt(prompt),
supportsFastMode,
};
}
function ClaudeTraitsMenuContentImpl(props: {
threadId: ThreadId;
model: string | null | undefined;
onPromptChange: (prompt: string) => void;
}) {
const draft = useComposerThreadDraft(props.threadId);
const prompt = draft.prompt;
const modelOptions = draft.modelOptions?.claudeAgent;
const setModelOptions = useComposerDraftStore((store) => store.setModelOptions);
const {
effort,
thinkingEnabled,
fastModeEnabled,
options,
ultrathinkPromptControlled,
supportsFastMode,
} = getSelectedClaudeTraits(props.model, prompt, modelOptions);
const defaultReasoningEffort = getDefaultReasoningEffort("claudeAgent");
const setClaudeModelOptions = (nextClaudeModelOptions: ClaudeModelOptions | undefined) => {
const { claudeAgent: _discardedClaude, ...otherProviderModelOptions } =
draft.modelOptions ?? {};
const nextProviderModelOptions: ProviderModelOptions | undefined = nextClaudeModelOptions
? { ...otherProviderModelOptions, claudeAgent: nextClaudeModelOptions }
: Object.keys(otherProviderModelOptions).length > 0
? otherProviderModelOptions
: undefined;
setModelOptions(props.threadId, nextProviderModelOptions);
};
if (effort === null && thinkingEnabled === null) {
return null;
}
return (
<>
{effort ? (
<>
<MenuGroup>
<div className="px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs">Effort</div>
{ultrathinkPromptControlled ? (
<div className="px-2 pb-1.5 text-muted-foreground/80 text-xs">
Remove Ultrathink from the prompt to change effort.
</div>
) : null}
<MenuRadioGroup
value={effort}
onValueChange={(value) => {
if (ultrathinkPromptControlled) return;
if (!value) return;
const nextEffort = options.find((option) => option === value);
if (!nextEffort) return;
if (nextEffort === "ultrathink") {
const nextPrompt =
prompt.trim().length === 0
? ULTRATHINK_PROMPT_PREFIX
: applyClaudePromptEffortPrefix(prompt, "ultrathink");
props.onPromptChange(nextPrompt);
return;
}
setClaudeModelOptions(
normalizeClaudeModelOptions(props.model, {
...modelOptions,
effort: nextEffort,
}),
);
}}
>
{options.map((option) => (
<MenuRadioItem key={option} value={option} disabled={ultrathinkPromptControlled}>
{CLAUDE_EFFORT_LABELS[option]}
{option === defaultReasoningEffort ? " (default)" : ""}
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuGroup>
</>
) : thinkingEnabled !== null ? (
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Thinking</div>
<MenuRadioGroup
value={thinkingEnabled ? "on" : "off"}
onValueChange={(value) => {
setClaudeModelOptions(
normalizeClaudeModelOptions(props.model, {
...modelOptions,
thinking: value === "on",
}),
);
}}
>
<MenuRadioItem value="on">On (default)</MenuRadioItem>
<MenuRadioItem value="off">Off</MenuRadioItem>
</MenuRadioGroup>
</MenuGroup>
) : null}
{supportsFastMode ? (
<>
<MenuDivider />
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
<MenuRadioGroup
value={fastModeEnabled ? "on" : "off"}
onValueChange={(value) => {
setClaudeModelOptions(
normalizeClaudeModelOptions(props.model, {
...modelOptions,
fastMode: value === "on",
}),
);
}}
>
<MenuRadioItem value="off">off</MenuRadioItem>
<MenuRadioItem value="on">on</MenuRadioItem>
</MenuRadioGroup>
</MenuGroup>
</>
) : null}
</>
);
}
export const ClaudeTraitsMenuContent = memo(ClaudeTraitsMenuContentImpl);
export const ClaudeTraitsPicker = memo(function ClaudeTraitsPicker(props: {
threadId: ThreadId;
model: string | null | undefined;
onPromptChange: (prompt: string) => void;
}) {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const draft = useComposerThreadDraft(props.threadId);
const prompt = draft.prompt;
const modelOptions = draft.modelOptions?.claudeAgent;
const { effort, thinkingEnabled, fastModeEnabled, ultrathinkPromptControlled, supportsFastMode } =
getSelectedClaudeTraits(props.model, prompt, modelOptions);
const triggerLabel = [
ultrathinkPromptControlled
? "Ultrathink"
: effort
? CLAUDE_EFFORT_LABELS[effort]
: thinkingEnabled === null
? null
: `Thinking ${thinkingEnabled ? "On" : "Off"}`,
...(supportsFastMode && fastModeEnabled ? ["Fast"] : []),
]
.filter(Boolean)
.join(" · ");
return (
<Menu
open={isMenuOpen}
onOpenChange={(open) => {
setIsMenuOpen(open);
}}
>
<MenuTrigger
render={
<Button
size="sm"
variant="ghost"
className="shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
/>
}
>
<span>{triggerLabel}</span>
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
</MenuTrigger>
<MenuPopup align="start">
<ClaudeTraitsMenuContent
threadId={props.threadId}
model={props.model}
onPromptChange={props.onPromptChange}
/>
</MenuPopup>
</Menu>
);
});
@@ -0,0 +1,169 @@
import "../../index.css";
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { page } from "vitest/browser";
import { afterEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
import { CodexTraitsPicker } from "./CodexTraitsPicker";
import { COMPOSER_DRAFT_STORAGE_KEY, useComposerDraftStore } from "../../composerDraftStore";
async function mountPicker(props: {
reasoningEffort?: "low" | "medium" | "high" | "xhigh";
fastModeEnabled: boolean;
}) {
const threadId = ThreadId.makeUnsafe("thread-codex-traits");
const draftsByThreadId = {} as ReturnType<
typeof useComposerDraftStore.getState
>["draftsByThreadId"];
draftsByThreadId[threadId] = {
prompt: "",
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
terminalContexts: [],
provider: "codex",
model: null,
modelOptions: {
codex: {
...(props.reasoningEffort ? { reasoningEffort: props.reasoningEffort } : {}),
...(props.fastModeEnabled ? { fastMode: true } : {}),
},
},
runtimeMode: null,
interactionMode: null,
};
useComposerDraftStore.setState({
draftsByThreadId,
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {
[ProjectId.makeUnsafe("project-codex-traits")]: threadId,
},
});
const host = document.createElement("div");
document.body.append(host);
const screen = await render(<CodexTraitsPicker threadId={threadId} />, { container: host });
return {
cleanup: async () => {
await screen.unmount();
host.remove();
},
};
}
describe("CodexTraitsPicker", () => {
afterEach(() => {
document.body.innerHTML = "";
localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY);
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
});
it("shows fast mode controls", async () => {
const mounted = await mountPicker({
fastModeEnabled: false,
});
try {
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Fast Mode");
expect(text).toContain("off");
expect(text).toContain("on");
});
} finally {
await mounted.cleanup();
}
});
it("shows Fast in the trigger label when fast mode is active", async () => {
const mounted = await mountPicker({
fastModeEnabled: true,
});
try {
await vi.waitFor(() => {
expect(document.body.textContent ?? "").toContain("High · Fast");
});
} finally {
await mounted.cleanup();
}
});
it("shows only the provided effort options", async () => {
const mounted = await mountPicker({
fastModeEnabled: false,
});
try {
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Low");
expect(text).toContain("Medium");
expect(text).toContain("High");
expect(text).toContain("Extra High");
});
} finally {
await mounted.cleanup();
}
});
it("hydrates legacy codex persisted state into modelOptions through the picker", async () => {
const threadId = ThreadId.makeUnsafe("thread-codex-legacy");
localStorage.setItem(
COMPOSER_DRAFT_STORAGE_KEY,
JSON.stringify({
state: {
draftsByThreadId: {
[threadId]: {
prompt: "",
attachments: [],
provider: "codex",
model: "gpt-5.3-codex",
effort: "xhigh",
codexFastMode: true,
serviceTier: "fast",
},
},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
},
version: 1,
}),
);
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
const host = document.createElement("div");
document.body.append(host);
const screen = await render(<CodexTraitsPicker threadId={threadId} />, { container: host });
try {
await useComposerDraftStore.persist.rehydrate();
await vi.waitFor(() => {
expect(document.body.textContent ?? "").toContain("Extra High · Fast");
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
codex: {
reasoningEffort: "xhigh",
fastMode: true,
},
});
});
} finally {
await screen.unmount();
host.remove();
}
});
});
@@ -1,7 +1,18 @@
import { type CodexReasoningEffort } from "@t3tools/contracts";
import { getDefaultReasoningEffort } from "@t3tools/shared/model";
import type {
CodexModelOptions,
CodexReasoningEffort,
ProviderModelOptions,
ThreadId,
} from "@t3tools/contracts";
import {
getDefaultReasoningEffort,
getReasoningEffortOptions,
normalizeCodexModelOptions,
resolveReasoningEffortForProvider,
} from "@t3tools/shared/model";
import { memo, useState } from "react";
import { ChevronDownIcon } from "lucide-react";
import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore";
import { Button } from "../ui/button";
import {
Menu,
@@ -13,25 +24,99 @@ import {
MenuTrigger,
} from "../ui/menu";
export const CodexTraitsPicker = memo(function CodexTraitsPicker(props: {
const CODEX_REASONING_LABELS: Record<CodexReasoningEffort, string> = {
low: "Low",
medium: "Medium",
high: "High",
xhigh: "Extra High",
};
function getSelectedCodexTraits(modelOptions: CodexModelOptions | null | undefined): {
effort: CodexReasoningEffort;
fastModeEnabled: boolean;
options: ReadonlyArray<CodexReasoningEffort>;
onEffortChange: (effort: CodexReasoningEffort) => void;
onFastModeChange: (enabled: boolean) => void;
}) {
const [isMenuOpen, setIsMenuOpen] = useState(false);
} {
const defaultReasoningEffort = getDefaultReasoningEffort("codex");
const reasoningLabelByOption: Record<CodexReasoningEffort, string> = {
low: "Low",
medium: "Medium",
high: "High",
xhigh: "Extra High",
return {
effort:
resolveReasoningEffortForProvider("codex", modelOptions?.reasoningEffort) ??
defaultReasoningEffort,
fastModeEnabled: modelOptions?.fastMode === true,
};
const triggerLabel = [
reasoningLabelByOption[props.effort],
...(props.fastModeEnabled ? ["Fast"] : []),
]
}
function CodexTraitsMenuContentImpl(props: { threadId: ThreadId }) {
const draft = useComposerThreadDraft(props.threadId);
const modelOptions = draft.modelOptions?.codex;
const setModelOptions = useComposerDraftStore((store) => store.setModelOptions);
const options = getReasoningEffortOptions("codex");
const defaultReasoningEffort = getDefaultReasoningEffort("codex");
const { effort, fastModeEnabled } = getSelectedCodexTraits(modelOptions);
const setCodexModelOptions = (nextCodexModelOptions: CodexModelOptions | undefined) => {
const { codex: _discardedCodex, ...otherProviderModelOptions } = draft.modelOptions ?? {};
const nextProviderModelOptions: ProviderModelOptions | undefined = nextCodexModelOptions
? { ...otherProviderModelOptions, codex: nextCodexModelOptions }
: Object.keys(otherProviderModelOptions).length > 0
? otherProviderModelOptions
: undefined;
setModelOptions(props.threadId, nextProviderModelOptions);
};
return (
<>
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Reasoning</div>
<MenuRadioGroup
value={effort}
onValueChange={(value) => {
if (!value) return;
const nextEffort = options.find((option) => option === value);
if (!nextEffort) return;
setCodexModelOptions(
normalizeCodexModelOptions({
...modelOptions,
reasoningEffort: nextEffort,
}),
);
}}
>
{options.map((option) => (
<MenuRadioItem key={option} value={option}>
{CODEX_REASONING_LABELS[option]}
{option === defaultReasoningEffort ? " (default)" : ""}
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuGroup>
<MenuDivider />
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
<MenuRadioGroup
value={fastModeEnabled ? "on" : "off"}
onValueChange={(value) => {
setCodexModelOptions(
normalizeCodexModelOptions({
...modelOptions,
fastMode: value === "on",
}),
);
}}
>
<MenuRadioItem value="off">off</MenuRadioItem>
<MenuRadioItem value="on">on</MenuRadioItem>
</MenuRadioGroup>
</MenuGroup>
</>
);
}
export const CodexTraitsMenuContent = memo(CodexTraitsMenuContentImpl);
export const CodexTraitsPicker = memo(function CodexTraitsPicker(props: { threadId: ThreadId }) {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const modelOptions = useComposerThreadDraft(props.threadId).modelOptions?.codex;
const { effort, fastModeEnabled } = getSelectedCodexTraits(modelOptions);
const triggerLabel = [CODEX_REASONING_LABELS[effort], ...(fastModeEnabled ? ["Fast"] : [])]
.filter(Boolean)
.join(" · ");
@@ -47,46 +132,17 @@ export const CodexTraitsPicker = memo(function CodexTraitsPicker(props: {
<Button
size="sm"
variant="ghost"
className="shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
className="min-w-0 max-w-40 shrink justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:max-w-48 sm:px-3 [&_svg]:mx-0"
/>
}
>
<span>{triggerLabel}</span>
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
{triggerLabel}
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
</span>
</MenuTrigger>
<MenuPopup align="start">
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Reasoning</div>
<MenuRadioGroup
value={props.effort}
onValueChange={(value) => {
if (!value) return;
const nextEffort = props.options.find((option) => option === value);
if (!nextEffort) return;
props.onEffortChange(nextEffort);
}}
>
{props.options.map((effort) => (
<MenuRadioItem key={effort} value={effort}>
{reasoningLabelByOption[effort]}
{effort === defaultReasoningEffort ? " (default)" : ""}
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuGroup>
<MenuDivider />
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
<MenuRadioGroup
value={props.fastModeEnabled ? "on" : "off"}
onValueChange={(value) => {
props.onFastModeChange(value === "on");
}}
>
<MenuRadioItem value="off">off</MenuRadioItem>
<MenuRadioItem value="on">on</MenuRadioItem>
</MenuRadioGroup>
</MenuGroup>
<CodexTraitsMenuContent threadId={props.threadId} />
</MenuPopup>
</Menu>
);
@@ -0,0 +1,186 @@
import { type ProviderModelOptions, ThreadId } from "@t3tools/contracts";
import "../../index.css";
import { page } from "vitest/browser";
import { afterEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
import { ClaudeTraitsMenuContent } from "./ClaudeTraitsPicker";
import { CodexTraitsMenuContent } from "./CodexTraitsPicker";
import { useComposerDraftStore } from "../../composerDraftStore";
async function mountMenu(props?: {
model?: string;
prompt?: string;
provider?: "codex" | "claudeAgent";
modelOptions?: ProviderModelOptions | null;
}) {
const threadId = ThreadId.makeUnsafe("thread-compact-menu");
const provider = props?.provider ?? "claudeAgent";
const draftsByThreadId = {} as ReturnType<
typeof useComposerDraftStore.getState
>["draftsByThreadId"];
draftsByThreadId[threadId] = {
prompt: props?.prompt ?? "",
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
terminalContexts: [],
provider,
model: props?.model ?? "claude-opus-4-6",
modelOptions: props?.modelOptions ?? null,
runtimeMode: null,
interactionMode: null,
};
useComposerDraftStore.setState({
draftsByThreadId,
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
const host = document.createElement("div");
document.body.append(host);
const onPromptChange = vi.fn();
const screen = await render(
<CompactComposerControlsMenu
activePlan={false}
interactionMode="default"
planSidebarOpen={false}
runtimeMode="approval-required"
traitsMenuContent={
provider === "codex" ? (
<CodexTraitsMenuContent threadId={threadId} />
) : (
<ClaudeTraitsMenuContent
threadId={threadId}
model={props?.model ?? "claude-opus-4-6"}
onPromptChange={onPromptChange}
/>
)
}
onToggleInteractionMode={vi.fn()}
onTogglePlanSidebar={vi.fn()}
onToggleRuntimeMode={vi.fn()}
/>,
{ container: host },
);
return {
cleanup: async () => {
await screen.unmount();
host.remove();
},
};
}
describe("CompactComposerControlsMenu", () => {
afterEach(() => {
document.body.innerHTML = "";
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
});
it("shows fast mode controls for Opus", async () => {
const mounted = await mountMenu();
try {
await page.getByLabelText("More composer controls").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Fast Mode");
expect(text).toContain("off");
expect(text).toContain("on");
});
} finally {
await mounted.cleanup();
}
});
it("hides fast mode controls for non-Opus Claude models", async () => {
const mounted = await mountMenu({ model: "claude-sonnet-4-6" });
try {
await page.getByLabelText("More composer controls").click();
await vi.waitFor(() => {
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
});
} finally {
await mounted.cleanup();
}
});
it("shows only the provided effort options", async () => {
const mounted = await mountMenu({
model: "claude-sonnet-4-6",
});
try {
await page.getByLabelText("More composer controls").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Low");
expect(text).toContain("Medium");
expect(text).toContain("High");
expect(text).not.toContain("Max");
expect(text).toContain("Ultrathink");
});
} finally {
await mounted.cleanup();
}
});
it("shows a Claude thinking on/off section for Haiku", async () => {
const mounted = await mountMenu({
model: "claude-haiku-4-5",
modelOptions: {
claudeAgent: {
thinking: true,
},
},
});
try {
await page.getByLabelText("More composer controls").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Thinking");
expect(text).toContain("On (default)");
expect(text).toContain("Off");
});
} finally {
await mounted.cleanup();
}
});
it("shows prompt-controlled Ultrathink messaging with disabled effort controls", async () => {
const mounted = await mountMenu({
model: "claude-opus-4-6",
prompt: "Ultrathink:\nInvestigate this",
modelOptions: {
claudeAgent: {
effort: "high",
},
},
});
try {
await page.getByLabelText("More composer controls").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Effort");
expect(text).toContain("Remove Ultrathink from the prompt to change effort.");
expect(text).not.toContain("Fallback Effort");
});
} finally {
await mounted.cleanup();
}
});
});
@@ -1,16 +1,9 @@
import {
type CodexReasoningEffort,
type ProviderKind,
RuntimeMode,
ProviderInteractionMode,
} from "@t3tools/contracts";
import { getDefaultReasoningEffort } from "@t3tools/shared/model";
import { memo } from "react";
import { ProviderInteractionMode, RuntimeMode } from "@t3tools/contracts";
import { memo, type ReactNode } from "react";
import { EllipsisIcon, ListTodoIcon } from "lucide-react";
import { Button } from "../ui/button";
import {
Menu,
MenuGroup,
MenuItem,
MenuPopup,
MenuRadioGroup,
@@ -24,24 +17,11 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls
interactionMode: ProviderInteractionMode;
planSidebarOpen: boolean;
runtimeMode: RuntimeMode;
selectedEffort: CodexReasoningEffort | null;
selectedProvider: ProviderKind;
selectedCodexFastModeEnabled: boolean;
reasoningOptions: ReadonlyArray<CodexReasoningEffort>;
onEffortSelect: (effort: CodexReasoningEffort) => void;
onCodexFastModeChange: (enabled: boolean) => void;
traitsMenuContent?: ReactNode;
onToggleInteractionMode: () => void;
onTogglePlanSidebar: () => void;
onToggleRuntimeMode: () => void;
}) {
const defaultReasoningEffort = getDefaultReasoningEffort("codex");
const reasoningLabelByOption: Record<CodexReasoningEffort, string> = {
low: "Low",
medium: "Medium",
high: "High",
xhigh: "Extra High",
};
return (
<Menu>
<MenuTrigger
@@ -57,70 +37,35 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls
<EllipsisIcon aria-hidden="true" className="size-4" />
</MenuTrigger>
<MenuPopup align="start">
{props.selectedProvider === "codex" && props.selectedEffort != null ? (
{props.traitsMenuContent ? (
<>
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Reasoning</div>
<MenuRadioGroup
value={props.selectedEffort}
onValueChange={(value) => {
if (!value) return;
const nextEffort = props.reasoningOptions.find((option) => option === value);
if (!nextEffort) return;
props.onEffortSelect(nextEffort);
}}
>
{props.reasoningOptions.map((effort) => (
<MenuRadioItem key={effort} value={effort}>
{reasoningLabelByOption[effort]}
{effort === defaultReasoningEffort ? " (default)" : ""}
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuGroup>
<MenuDivider />
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
<MenuRadioGroup
value={props.selectedCodexFastModeEnabled ? "on" : "off"}
onValueChange={(value) => {
props.onCodexFastModeChange(value === "on");
}}
>
<MenuRadioItem value="off">off</MenuRadioItem>
<MenuRadioItem value="on">on</MenuRadioItem>
</MenuRadioGroup>
</MenuGroup>
{props.traitsMenuContent}
<MenuDivider />
</>
) : null}
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Mode</div>
<MenuRadioGroup
value={props.interactionMode}
onValueChange={(value) => {
if (!value || value === props.interactionMode) return;
props.onToggleInteractionMode();
}}
>
<MenuRadioItem value="default">Chat</MenuRadioItem>
<MenuRadioItem value="plan">Plan</MenuRadioItem>
</MenuRadioGroup>
</MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Mode</div>
<MenuRadioGroup
value={props.interactionMode}
onValueChange={(value) => {
if (!value || value === props.interactionMode) return;
props.onToggleInteractionMode();
}}
>
<MenuRadioItem value="default">Chat</MenuRadioItem>
<MenuRadioItem value="plan">Plan</MenuRadioItem>
</MenuRadioGroup>
<MenuDivider />
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Access</div>
<MenuRadioGroup
value={props.runtimeMode}
onValueChange={(value) => {
if (!value || value === props.runtimeMode) return;
props.onToggleRuntimeMode();
}}
>
<MenuRadioItem value="approval-required">Supervised</MenuRadioItem>
<MenuRadioItem value="full-access">Full access</MenuRadioItem>
</MenuRadioGroup>
</MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Access</div>
<MenuRadioGroup
value={props.runtimeMode}
onValueChange={(value) => {
if (!value || value === props.runtimeMode) return;
props.onToggleRuntimeMode();
}}
>
<MenuRadioItem value="approval-required">Supervised</MenuRadioItem>
<MenuRadioItem value="full-access">Full access</MenuRadioItem>
</MenuRadioGroup>
{props.activePlan ? (
<>
<MenuDivider />
@@ -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&#x27;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;
@@ -12,18 +12,23 @@ export const ProviderHealthBanner = memo(function ProviderHealthBanner({
return null;
}
const providerLabel =
status.provider === "codex"
? "Codex"
: status.provider === "claudeAgent"
? "Claude"
: status.provider;
const defaultMessage =
status.status === "error"
? `${status.provider} provider is unavailable.`
: `${status.provider} provider has limited availability.`;
? `${providerLabel} provider is unavailable.`
: `${providerLabel} provider has limited availability.`;
const title = providerLabel === "Codex" ? "Codex provider status" : `${providerLabel} status`;
return (
<div className="pt-3 mx-auto max-w-3xl">
<Alert variant={status.status === "error" ? "error" : "warning"}>
<CircleAlertIcon />
<AlertTitle>
{status.provider === "codex" ? "Codex provider status" : `${status.provider} status`}
</AlertTitle>
<AlertTitle>{title}</AlertTitle>
<AlertDescription className="line-clamp-3" title={status.message ?? defaultMessage}>
{status.message ?? defaultMessage}
</AlertDescription>
@@ -0,0 +1,94 @@
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();
}
});
});
@@ -17,7 +17,7 @@ import {
MenuSubTrigger,
MenuTrigger,
} from "../ui/menu";
import { ClaudeAI, Gemini, Icon, OpenAI, OpenCodeIcon } from "../Icons";
import { ClaudeAI, CursorIcon, Gemini, Icon, OpenAI, OpenCodeIcon } from "../Icons";
import { cn } from "~/lib/utils";
function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is {
@@ -63,7 +63,8 @@ function resolveModelForProviderPicker(
const PROVIDER_ICON_BY_PROVIDER: Record<ProviderPickerKind, Icon> = {
codex: OpenAI,
claudeCode: ClaudeAI,
claudeAgent: ClaudeAI,
cursor: CursorIcon,
};
export const AVAILABLE_PROVIDER_OPTIONS = PROVIDER_OPTIONS.filter(isAvailableProviderOption);
@@ -73,20 +74,41 @@ const COMING_SOON_PROVIDER_OPTIONS = [
{ id: "gemini", label: "Gemini", icon: Gemini },
] as const;
function providerIconClassName(
provider: ProviderKind | ProviderPickerKind,
fallbackClassName: string,
): string {
return provider === "claudeAgent" ? "text-[#d97757]" : fallbackClassName;
}
export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
provider: ProviderKind;
model: ModelSlug;
lockedProvider: ProviderKind | null;
modelOptionsByProvider: Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>>;
ultrathinkActive?: boolean;
compact?: boolean;
disabled?: boolean;
onProviderModelChange: (provider: ProviderKind, model: ModelSlug) => void;
}) {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const selectedProviderOptions = props.modelOptionsByProvider[props.provider];
const activeProvider = props.lockedProvider ?? props.provider;
const selectedProviderOptions = props.modelOptionsByProvider[activeProvider];
const selectedModelLabel =
selectedProviderOptions.find((option) => option.slug === props.model)?.name ?? props.model;
const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[props.provider];
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);
};
return (
<Menu
@@ -105,100 +127,119 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
size="sm"
variant="ghost"
className={cn(
"min-w-0 shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80",
props.compact ? "max-w-42" : "sm:px-3",
"min-w-0 justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 [&_svg]:mx-0",
props.compact ? "max-w-42 shrink-0" : "max-w-48 shrink sm:max-w-56 sm:px-3",
)}
disabled={props.disabled}
/>
}
>
<span
className={cn("flex min-w-0 items-center gap-2", props.compact ? "max-w-36" : undefined)}
className={cn(
"flex min-w-0 w-full items-center gap-2 overflow-hidden",
props.compact ? "max-w-36" : undefined,
)}
>
<ProviderIcon aria-hidden="true" className="size-4 shrink-0 text-muted-foreground/70" />
<span className="truncate">{selectedModelLabel}</span>
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
<ProviderIcon
aria-hidden="true"
className={cn(
"size-4 shrink-0",
providerIconClassName(activeProvider, "text-muted-foreground/70"),
activeProvider === "claudeAgent" && props.ultrathinkActive
? "ultrathink-chroma"
: undefined,
)}
/>
<span className="min-w-0 flex-1 truncate">{selectedModelLabel}</span>
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
</span>
</MenuTrigger>
<MenuPopup align="start">
{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.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={cn(
"size-4 shrink-0",
providerIconClassName(option.value, "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)}
>
{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>
);
})}
{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>
);
})}
</>
)}
</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,
+14 -1
View File
@@ -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");
});
});
+3 -3
View File
@@ -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" },
]);
});
});
+51 -7
View File
@@ -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;
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more