Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db02da69ba | ||
|
|
ca37b7bafe | ||
|
|
e11fb6e778 | ||
|
|
d415558915 | ||
|
|
843d6d8678 | ||
|
|
754cded24a | ||
|
|
2b6640af1e | ||
|
|
9e29c9d728 | ||
|
|
ef2569196f | ||
|
|
34cef6202b | ||
|
|
25c7003226 | ||
|
|
46e63b3612 | ||
|
|
d373389703 | ||
|
|
bc12421736 | ||
|
|
8f11ea44a7 | ||
|
|
56660b04e9 | ||
|
|
2a237c2001 | ||
|
|
77716b4ccb | ||
|
|
fb18b2de16 | ||
|
|
0de5742b04 | ||
|
|
b500a36a94 | ||
|
|
1310045629 | ||
|
|
579a69eb77 | ||
|
|
9ee8c4f543 | ||
|
|
55560f5116 | ||
|
|
3710ddb611 | ||
|
|
3fce14bbcf | ||
|
|
d430a0624b |
No files matched your search
+1
-1
@@ -5,7 +5,7 @@
|
||||
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
||||
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
||||
`bun run dev -- --state-dir ~/.t3/another-dev-state`
|
||||
`bun run dev -- --base-dir ~/.t3-2`
|
||||
- `bun run start` — Runs the production server (serves built web app as static files).
|
||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||
|
||||
@@ -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: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
persist-credentials: true
|
||||
|
||||
- id: app_bot
|
||||
name: Resolve GitHub App bot identity
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app_token.outputs.token }}
|
||||
APP_SLUG: ${{ steps.app_token.outputs.app-slug }}
|
||||
run: |
|
||||
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
|
||||
echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT"
|
||||
echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
@@ -349,8 +369,8 @@ jobs:
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git config user.name "${{ steps.app_bot.outputs.name }}"
|
||||
git config user.email "${{ steps.app_bot.outputs.email }}"
|
||||
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
|
||||
git commit -m "chore(release): prepare $RELEASE_TAG"
|
||||
|
||||
@@ -17,3 +17,5 @@ release/
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
__screenshots__/
|
||||
@@ -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
|
||||
@@ -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,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
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ The T3 Code CLI accepts the following configuration options, available either as
|
||||
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
|
||||
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
|
||||
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
|
||||
| `--state-dir <path>` | `T3CODE_STATE_DIR` | State directory. |
|
||||
| `--base-dir <path>` | `T3CODE_HOME` | Base directory. |
|
||||
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
|
||||
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
|
||||
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.10",
|
||||
"version": "0.0.13",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -47,6 +47,7 @@ import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runti
|
||||
syncShellEnvironment();
|
||||
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const GET_DOCUMENTS_PATH_CHANNEL = "desktop:get-documents-path";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
@@ -56,8 +57,8 @@ const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const STATE_DIR =
|
||||
process.env.T3CODE_STATE_DIR?.trim() || Path.join(OS.homedir(), ".t3", "userdata");
|
||||
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
|
||||
const STATE_DIR = Path.join(BASE_DIR, "userdata");
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
@@ -924,7 +925,7 @@ function backendEnv(): NodeJS.ProcessEnv {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_NO_BROWSER: "1",
|
||||
T3CODE_PORT: String(backendPort),
|
||||
T3CODE_STATE_DIR: STATE_DIR,
|
||||
T3CODE_HOME: BASE_DIR,
|
||||
T3CODE_AUTH_TOKEN: backendAuthToken,
|
||||
};
|
||||
}
|
||||
@@ -1086,6 +1087,16 @@ function registerIpcHandlers(): void {
|
||||
return result.filePaths[0] ?? null;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(GET_DOCUMENTS_PATH_CHANNEL);
|
||||
ipcMain.handle(GET_DOCUMENTS_PATH_CHANNEL, async () => {
|
||||
try {
|
||||
const documentsPath = app.getPath("documents");
|
||||
return typeof documentsPath === "string" && documentsPath.length > 0 ? documentsPath : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(CONFIRM_CHANNEL);
|
||||
ipcMain.handle(CONFIRM_CHANNEL, async (_event, message: unknown) => {
|
||||
if (typeof message !== "string") {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { contextBridge, ipcRenderer } from "electron";
|
||||
import type { DesktopBridge } from "@t3tools/contracts";
|
||||
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const GET_DOCUMENTS_PATH_CHANNEL = "desktop:get-documents-path";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
@@ -16,6 +17,7 @@ const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getWsUrl: () => wsUrl,
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||
getDocumentsPath: () => ipcRenderer.invoke(GET_DOCUMENTS_PATH_CHANNEL),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
ProviderKind,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
Option,
|
||||
Path,
|
||||
Ref,
|
||||
Schedule,
|
||||
Schema,
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
|
||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
|
||||
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
@@ -65,7 +66,7 @@ import {
|
||||
makeTestProviderAdapterHarness,
|
||||
type TestProviderAdapterHarness,
|
||||
} from "./TestProviderAdapter.integration.ts";
|
||||
import { ServerConfig } from "../src/config.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
@@ -75,14 +76,16 @@ function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
});
|
||||
}
|
||||
|
||||
function initializeGitWorkspace(cwd: string) {
|
||||
const initializeGitWorkspace = Effect.fn(function* (cwd: string) {
|
||||
runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const { join } = yield* Path.Path;
|
||||
yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
|
||||
runGit(cwd, ["add", "."]);
|
||||
runGit(cwd, ["commit", "-m", "Initial"]);
|
||||
}
|
||||
});
|
||||
|
||||
export function gitRefExists(cwd: string, ref: string): boolean {
|
||||
try {
|
||||
@@ -205,7 +208,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: "codex" | "claudeCode";
|
||||
readonly provider?: ProviderKind;
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
|
||||
@@ -213,7 +216,9 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
options?: MakeOrchestrationIntegrationHarnessOptions,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const sleep = (ms: number) => Effect.sleep(ms);
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const provider = options?.provider ?? "codex";
|
||||
const useRealCodex = options?.realCodex === true;
|
||||
const adapterHarness = useRealCodex
|
||||
@@ -230,13 +235,16 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
||||
} as typeof ProviderAdapterRegistry.Service)
|
||||
: null;
|
||||
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
|
||||
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-orchestration-integration-",
|
||||
});
|
||||
const workspaceDir = path.join(rootDir, "workspace");
|
||||
const stateDir = path.join(rootDir, "state");
|
||||
const dbPath = path.join(stateDir, "state.sqlite");
|
||||
fs.mkdirSync(workspaceDir, { recursive: true });
|
||||
fs.mkdirSync(stateDir, { recursive: true });
|
||||
initializeGitWorkspace(workspaceDir);
|
||||
const { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
yield* fileSystem.makeDirectory(workspaceDir, { recursive: true });
|
||||
yield* fileSystem.makeDirectory(stateDir, { recursive: true });
|
||||
yield* initializeGitWorkspace(workspaceDir);
|
||||
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
@@ -261,7 +269,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(makeCodexAdapterLive()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
@@ -277,12 +285,13 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
CheckpointStoreLive,
|
||||
checkpointStoreLayer,
|
||||
providerLayer,
|
||||
RuntimeReceiptBusLive,
|
||||
);
|
||||
@@ -311,7 +320,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
);
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -351,7 +360,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
|
||||
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
|
||||
).pipe(Effect.forkIn(scope));
|
||||
yield* sleep(10);
|
||||
yield* Effect.sleep(10);
|
||||
|
||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||
threadId,
|
||||
@@ -468,13 +477,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
}
|
||||
});
|
||||
|
||||
yield* shutdown.pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
fs.rmSync(rootDir, { recursive: true, force: true });
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* shutdown;
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -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";
|
||||
@@ -25,6 +27,7 @@ import type {
|
||||
CheckpointDiffFinalizedReceipt,
|
||||
TurnProcessingQuiescedReceipt,
|
||||
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
@@ -36,7 +39,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();
|
||||
@@ -49,8 +52,6 @@ class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWai
|
||||
},
|
||||
) {}
|
||||
|
||||
const sleep = (ms: number) => Effect.sleep(ms);
|
||||
|
||||
function waitForSync<A>(
|
||||
read: () => A,
|
||||
predicate: (value: A) => boolean,
|
||||
@@ -68,7 +69,7 @@ function waitForSync<A>(
|
||||
if (Date.now() >= deadline) {
|
||||
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
|
||||
}
|
||||
yield* sleep(10);
|
||||
yield* Effect.sleep(10);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -89,7 +90,7 @@ function withHarness<A, E>(
|
||||
makeOrchestrationIntegrationHarness({ provider }),
|
||||
use,
|
||||
(harness) => harness.dispose,
|
||||
);
|
||||
).pipe(Effect.provide(NodeServices.layer));
|
||||
}
|
||||
|
||||
function withRealCodexHarness<A, E>(
|
||||
@@ -99,12 +100,14 @@ function withRealCodexHarness<A, E>(
|
||||
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
|
||||
use,
|
||||
(harness) => harness.dispose,
|
||||
);
|
||||
).pipe(Effect.provide(NodeServices.layer));
|
||||
}
|
||||
|
||||
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 +115,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModel,
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -122,7 +125,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 +886,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 +896,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 +922,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 +950,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 +976,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 +996,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 +1032,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 +1055,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 +1070,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 +1083,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 +1112,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 +1126,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 +1152,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 +1178,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 +1192,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 +1222,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 +1235,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 +1272,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 +1299,6 @@ it.live("reverts claudeCode turns and rolls back provider conversation state", (
|
||||
);
|
||||
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
|
||||
}),
|
||||
"claudeCode",
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.10",
|
||||
"version": "0.0.13",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/pingdotgg/t3code",
|
||||
@@ -22,7 +23,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",
|
||||
|
||||
@@ -11,7 +11,7 @@ export function normalizeAttachmentRelativePath(rawRelativePath: string): string
|
||||
}
|
||||
|
||||
export function resolveAttachmentRelativePath(input: {
|
||||
readonly stateDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly relativePath: string;
|
||||
}): string | null {
|
||||
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
|
||||
@@ -19,7 +19,7 @@ export function resolveAttachmentRelativePath(input: {
|
||||
return null;
|
||||
}
|
||||
|
||||
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
|
||||
const attachmentsRoot = path.resolve(input.attachmentsDir);
|
||||
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
||||
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
||||
return null;
|
||||
|
||||
@@ -44,34 +44,32 @@ describe("attachmentStore", () => {
|
||||
});
|
||||
|
||||
it("resolves attachment path by id using the extension that exists on disk", () => {
|
||||
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||
try {
|
||||
const attachmentId = "thread-1-attachment";
|
||||
const attachmentsDir = path.join(stateDir, "attachments");
|
||||
fs.mkdirSync(attachmentsDir, { recursive: true });
|
||||
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||
fs.writeFileSync(pngPath, Buffer.from("hello"));
|
||||
|
||||
const resolved = resolveAttachmentPathById({
|
||||
stateDir,
|
||||
attachmentsDir,
|
||||
attachmentId,
|
||||
});
|
||||
expect(resolved).toBe(pngPath);
|
||||
} finally {
|
||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||
fs.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns null when no attachment file exists for the id", () => {
|
||||
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||
try {
|
||||
const resolved = resolveAttachmentPathById({
|
||||
stateDir,
|
||||
attachmentsDir,
|
||||
attachmentId: "thread-1-missing",
|
||||
});
|
||||
expect(resolved).toBeNull();
|
||||
} finally {
|
||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||
fs.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -66,17 +66,17 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
|
||||
}
|
||||
|
||||
export function resolveAttachmentPath(input: {
|
||||
readonly stateDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly attachment: ChatAttachment;
|
||||
}): string | null {
|
||||
return resolveAttachmentRelativePath({
|
||||
stateDir: input.stateDir,
|
||||
attachmentsDir: input.attachmentsDir,
|
||||
relativePath: attachmentRelativePath(input.attachment),
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveAttachmentPathById(input: {
|
||||
readonly stateDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly attachmentId: string;
|
||||
}): string | null {
|
||||
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
|
||||
@@ -85,7 +85,7 @@ export function resolveAttachmentPathById(input: {
|
||||
}
|
||||
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
|
||||
const maybePath = resolveAttachmentRelativePath({
|
||||
stateDir: input.stateDir,
|
||||
attachmentsDir: input.attachmentsDir,
|
||||
relativePath: `${normalizedId}${extension}`,
|
||||
});
|
||||
if (maybePath && existsSync(maybePath)) {
|
||||
|
||||
@@ -15,15 +15,14 @@ import { Effect, Layer, FileSystem, Path } from "effect";
|
||||
|
||||
import { CheckpointInvariantError } from "../Errors.ts";
|
||||
import { GitCommandError } from "../../git/Errors.ts";
|
||||
import { GitServiceLive } from "../../git/Layers/GitService.ts";
|
||||
import { GitService } from "../../git/Services/GitService.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||
import { CheckpointRef } from "@t3tools/contracts";
|
||||
|
||||
const makeCheckpointStore = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const git = yield* GitService;
|
||||
const git = yield* GitCore;
|
||||
|
||||
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
||||
git
|
||||
@@ -277,6 +276,4 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
} satisfies CheckpointStoreShape;
|
||||
});
|
||||
|
||||
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore).pipe(
|
||||
Layer.provideMerge(GitServiceLive),
|
||||
);
|
||||
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore);
|
||||
@@ -37,6 +37,7 @@ function createSendTurnHarness() {
|
||||
planType: null,
|
||||
sparkEnabled: true,
|
||||
},
|
||||
collabReceiverTurns: new Map(),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
@@ -75,6 +76,7 @@ function createThreadControlHarness() {
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
collabReceiverTurns: new Map(),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
@@ -117,6 +119,7 @@ function createPendingUserInputHarness() {
|
||||
},
|
||||
],
|
||||
]),
|
||||
collabReceiverTurns: new Map(),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
@@ -135,6 +138,43 @@ 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>(),
|
||||
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 +761,7 @@ describe("respondToUserInput", () => {
|
||||
},
|
||||
pendingApprovals: new Map(),
|
||||
pendingUserInputs: new Map(),
|
||||
collabReceiverTurns: new Map(),
|
||||
};
|
||||
type ApprovalRequestContext = {
|
||||
session: typeof context.session;
|
||||
@@ -748,6 +789,152 @@ 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",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
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-"));
|
||||
|
||||
@@ -70,6 +70,7 @@ interface CodexSessionContext {
|
||||
pending: Map<PendingRequestKey, PendingRequest>;
|
||||
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
||||
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
|
||||
collabReceiverTurns: Map<string, TurnId>;
|
||||
nextRequestId: number;
|
||||
stopping: boolean;
|
||||
}
|
||||
@@ -571,6 +572,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
pendingUserInputs: new Map(),
|
||||
collabReceiverTurns: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
@@ -732,6 +734,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||
const context = this.requireSession(input.threadId);
|
||||
context.collabReceiverTurns.clear();
|
||||
|
||||
const turnInput: Array<
|
||||
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
|
||||
@@ -1121,7 +1124,16 @@ 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 isChildConversation = childParentTurnId !== undefined;
|
||||
if (
|
||||
isChildConversation &&
|
||||
this.shouldSuppressChildConversationNotification(notification.method)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const textDelta =
|
||||
notification.method === "item/agentMessage/delta"
|
||||
? this.readString(notification.params, "delta")
|
||||
@@ -1134,8 +1146,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 }
|
||||
: {}),
|
||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
||||
textDelta,
|
||||
payload: notification.params,
|
||||
});
|
||||
@@ -1151,6 +1165,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 +1177,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (notification.method === "turn/completed") {
|
||||
if (isChildConversation) {
|
||||
return;
|
||||
}
|
||||
context.collabReceiverTurns.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 +1193,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 +1207,9 @@ 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 effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
|
||||
const requestKind = this.requestKindForMethod(request.method);
|
||||
let requestId: ApprovalRequestId | undefined;
|
||||
if (requestKind) {
|
||||
@@ -1199,8 +1225,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 } : {}),
|
||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
||||
};
|
||||
context.pendingApprovals.set(requestId, pendingRequest);
|
||||
}
|
||||
@@ -1211,8 +1237,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 } : {}),
|
||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1223,8 +1249,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 } : {}),
|
||||
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
||||
requestId,
|
||||
requestKind,
|
||||
payload: request.params,
|
||||
@@ -1451,6 +1477,64 @@ 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 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 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);
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -12,16 +12,32 @@ export const DEFAULT_PORT = 3773;
|
||||
|
||||
export type RuntimeMode = "web" | "desktop";
|
||||
|
||||
/**
|
||||
* ServerDerivedPaths - Derived paths from the base directory.
|
||||
*/
|
||||
export interface ServerDerivedPaths {
|
||||
readonly stateDir: string;
|
||||
readonly dbPath: string;
|
||||
readonly keybindingsConfigPath: string;
|
||||
readonly worktreesDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly logsDir: string;
|
||||
readonly serverLogPath: string;
|
||||
readonly providerLogsDir: string;
|
||||
readonly providerEventLogPath: string;
|
||||
readonly terminalLogsDir: string;
|
||||
readonly anonymousIdPath: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* ServerConfigShape - Process/runtime configuration required by the server.
|
||||
*/
|
||||
export interface ServerConfigShape {
|
||||
export interface ServerConfigShape extends ServerDerivedPaths {
|
||||
readonly mode: RuntimeMode;
|
||||
readonly port: number;
|
||||
readonly host: string | undefined;
|
||||
readonly cwd: string;
|
||||
readonly keybindingsConfigPath: string;
|
||||
readonly stateDir: string;
|
||||
readonly baseDir: string;
|
||||
readonly staticDir: string | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
readonly noBrowser: boolean;
|
||||
@@ -30,31 +46,68 @@ export interface ServerConfigShape {
|
||||
readonly logWebSocketEvents: boolean;
|
||||
}
|
||||
|
||||
export const deriveServerPaths = Effect.fn(function* (
|
||||
baseDir: ServerConfigShape["baseDir"],
|
||||
devUrl: ServerConfigShape["devUrl"],
|
||||
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
|
||||
const { join } = yield* Path.Path;
|
||||
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata");
|
||||
const dbPath = join(stateDir, "state.sqlite");
|
||||
const attachmentsDir = join(stateDir, "attachments");
|
||||
const logsDir = join(stateDir, "logs");
|
||||
const providerLogsDir = join(logsDir, "provider");
|
||||
return {
|
||||
stateDir,
|
||||
dbPath,
|
||||
keybindingsConfigPath: join(stateDir, "keybindings.json"),
|
||||
worktreesDir: join(baseDir, "worktrees"),
|
||||
attachmentsDir,
|
||||
logsDir,
|
||||
serverLogPath: join(logsDir, "server.log"),
|
||||
providerLogsDir,
|
||||
providerEventLogPath: join(providerLogsDir, "events.log"),
|
||||
terminalLogsDir: join(logsDir, "terminals"),
|
||||
anonymousIdPath: join(stateDir, "anonymous-id"),
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* ServerConfig - Service tag for server runtime configuration.
|
||||
*/
|
||||
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
||||
"t3/config/ServerConfig",
|
||||
) {
|
||||
static readonly layerTest = (cwd: string, statedir: string) =>
|
||||
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const devUrl = undefined;
|
||||
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const baseDir =
|
||||
typeof baseDirOrPrefix === "string"
|
||||
? baseDirOrPrefix
|
||||
: yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
|
||||
yield* fs.makeDirectory(derivedPaths.stateDir, { recursive: true });
|
||||
yield* fs.makeDirectory(derivedPaths.logsDir, { recursive: true });
|
||||
yield* fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true });
|
||||
|
||||
return {
|
||||
cwd,
|
||||
stateDir: statedir,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
mode: "web",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
port: 0,
|
||||
host: undefined,
|
||||
authToken: undefined,
|
||||
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
devUrl,
|
||||
noBrowser: false,
|
||||
};
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,11 +8,14 @@ import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
|
||||
const makeCodexTextGenerationTestLayer = (stateDir: string) =>
|
||||
CodexTextGenerationLive.pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-codex-text-generation-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
function makeFakeCodexBinary(dir: string) {
|
||||
return Effect.gen(function* () {
|
||||
@@ -186,8 +189,6 @@ function withFakeCodexEnv<A, E, R>(
|
||||
);
|
||||
}
|
||||
|
||||
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
|
||||
|
||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
it.effect("generates and sanitizes commit messages without branch by default", () =>
|
||||
withFakeCodexEnv(
|
||||
@@ -325,9 +326,10 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const { attachmentsDir } = yield* ServerConfig;
|
||||
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const attachmentPath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
||||
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
@@ -363,9 +365,10 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const { attachmentsDir } = yield* ServerConfig;
|
||||
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
||||
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
@@ -410,8 +413,9 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const { attachmentsDir } = yield* ServerConfig;
|
||||
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
|
||||
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
|
||||
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -163,7 +163,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const resolvedPath = resolveAttachmentPath({
|
||||
stateDir: serverConfig.stateDir,
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||
@@ -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 {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+1243
-1101
File diff suppressed because it is too large.
Load diff
@@ -15,10 +15,10 @@ import {
|
||||
GitHubCli,
|
||||
} from "../Services/GitHubCli.ts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { GitServiceLive } from "./GitService.ts";
|
||||
import { GitService } from "../Services/GitService.ts";
|
||||
import { GitCoreLive } from "./GitCore.ts";
|
||||
import { GitCore } from "../Services/GitCore.ts";
|
||||
import { makeGitManager } from "./GitManager.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
|
||||
interface FakeGhScenario {
|
||||
prListSequence?: string[];
|
||||
@@ -106,11 +106,11 @@ function runGit(
|
||||
): Effect.Effect<
|
||||
{ readonly code: number; readonly stdout: string; readonly stderr: string },
|
||||
GitCommandError,
|
||||
GitService
|
||||
GitCore
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const gitService = yield* GitService;
|
||||
return yield* gitService.execute({
|
||||
const gitCore = yield* GitCore;
|
||||
return yield* gitCore.execute({
|
||||
operation: "GitManager.test.runGit",
|
||||
cwd,
|
||||
args,
|
||||
@@ -124,7 +124,7 @@ function initRepo(
|
||||
): Effect.Effect<
|
||||
void,
|
||||
PlatformError.PlatformError | GitCommandError,
|
||||
FileSystem.FileSystem | Scope.Scope | GitService
|
||||
FileSystem.FileSystem | Scope.Scope | GitCore
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
@@ -140,7 +140,7 @@ function initRepo(
|
||||
function createBareRemote(): Effect.Effect<
|
||||
string,
|
||||
PlatformError.PlatformError | GitCommandError,
|
||||
FileSystem.FileSystem | Scope.Scope | GitService
|
||||
FileSystem.FileSystem | Scope.Scope | GitCore
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const remoteDir = yield* makeTempDir("t3code-git-remote-");
|
||||
@@ -474,18 +474,20 @@ function makeManager(input?: {
|
||||
}) {
|
||||
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
|
||||
const textGeneration = createTextGeneration(input?.textGeneration);
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-git-manager-test-",
|
||||
});
|
||||
|
||||
const gitCoreLayer = GitCoreLive.pipe(
|
||||
Layer.provideMerge(GitServiceLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
);
|
||||
|
||||
const managerLayer = Layer.mergeAll(
|
||||
Layer.succeed(GitHubCli, gitHubCli),
|
||||
Layer.succeed(TextGeneration, textGeneration),
|
||||
gitCoreLayer,
|
||||
NodeServices.layer,
|
||||
);
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
return makeGitManager.pipe(
|
||||
Effect.provide(managerLayer),
|
||||
@@ -493,7 +495,10 @@ function makeManager(input?: {
|
||||
);
|
||||
}
|
||||
|
||||
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
|
||||
const GitManagerTestLayer = GitCoreLive.pipe(
|
||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
it.effect("status includes PR metadata when branch already has an open PR", () =>
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import { GitServiceLive } from "./GitService.ts";
|
||||
import { GitService } from "../Services/GitService.ts";
|
||||
|
||||
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
|
||||
|
||||
layer("GitServiceLive", (it) => {
|
||||
it.effect("runGit executes successful git commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const gitService = yield* GitService;
|
||||
const result = yield* gitService.execute({
|
||||
operation: "GitProcess.test.version",
|
||||
cwd: process.cwd(),
|
||||
args: ["--version"],
|
||||
});
|
||||
|
||||
assert.equal(result.code, 0);
|
||||
assert.ok(result.stdout.toLowerCase().includes("git version"));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("runGit can return non-zero exit codes when allowed", () =>
|
||||
Effect.gen(function* () {
|
||||
const gitService = yield* GitService;
|
||||
const result = yield* gitService.execute({
|
||||
operation: "GitProcess.test.allowNonZero",
|
||||
cwd: process.cwd(),
|
||||
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
|
||||
assert.notEqual(result.code, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("runGit fails with GitCommandError when non-zero exits are not allowed", () =>
|
||||
Effect.gen(function* () {
|
||||
const gitService = yield* GitService;
|
||||
const result = yield* Effect.result(
|
||||
gitService.execute({
|
||||
operation: "GitProcess.test.failOnNonZero",
|
||||
cwd: process.cwd(),
|
||||
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(result._tag, "Failure");
|
||||
if (result._tag === "Failure") {
|
||||
assert.ok(Schema.is(GitCommandError)(result.failure));
|
||||
assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero");
|
||||
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,144 +0,0 @@
|
||||
/**
|
||||
* Git process helpers - Effect-native git execution with typed errors.
|
||||
*
|
||||
* Centralizes child-process git invocation for server modules. This module
|
||||
* only executes git commands and reports structured failures.
|
||||
*
|
||||
* @module GitServiceLive
|
||||
*/
|
||||
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import {
|
||||
ExecuteGitInput,
|
||||
ExecuteGitResult,
|
||||
GitService,
|
||||
GitServiceShape,
|
||||
} from "../Services/GitService.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
|
||||
function quoteGitCommand(args: ReadonlyArray<string>): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function toGitCommandError(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
detail: string,
|
||||
) {
|
||||
return (cause: unknown) =>
|
||||
Schema.is(GitCommandError)(cause)
|
||||
? cause
|
||||
: new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: quoteGitCommand(input.args),
|
||||
cwd: input.cwd,
|
||||
detail: `${cause instanceof Error && cause.message.length > 0 ? cause.message : "Unknown error"} - ${detail}`,
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
const collectOutput = Effect.fn(function* <E>(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
maxOutputBytes: number,
|
||||
): Effect.fn.Return<string, GitCommandError> {
|
||||
const decoder = new TextDecoder();
|
||||
let bytes = 0;
|
||||
let text = "";
|
||||
|
||||
yield* Stream.runForEach(stream, (chunk) =>
|
||||
Effect.gen(function* () {
|
||||
bytes += chunk.byteLength;
|
||||
if (bytes > maxOutputBytes) {
|
||||
return yield* new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: quoteGitCommand(input.args),
|
||||
cwd: input.cwd,
|
||||
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
|
||||
});
|
||||
}
|
||||
text += decoder.decode(chunk, { stream: true });
|
||||
}),
|
||||
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
|
||||
|
||||
text += decoder.decode();
|
||||
return text;
|
||||
});
|
||||
|
||||
const makeGitService = Effect.gen(function* () {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
|
||||
const commandInput = {
|
||||
...input,
|
||||
args: [...input.args],
|
||||
} as const;
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
|
||||
const commandEffect = Effect.gen(function* () {
|
||||
const child = yield* commandSpawner
|
||||
.spawn(
|
||||
ChildProcess.make("git", commandInput.args, {
|
||||
cwd: commandInput.cwd,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectOutput(commandInput, child.stdout, maxOutputBytes),
|
||||
collectOutput(commandInput, child.stderr, maxOutputBytes),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = stderr.trim();
|
||||
return yield* new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail:
|
||||
trimmedStderr.length > 0
|
||||
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
|
||||
});
|
||||
|
||||
return yield* commandEffect.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(timeoutMs),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
execute,
|
||||
} satisfies GitServiceShape;
|
||||
});
|
||||
|
||||
export const GitServiceLive = Layer.effect(GitService, makeGitService);
|
||||
@@ -24,6 +24,22 @@ import type {
|
||||
|
||||
import type { GitCommandError } from "../Errors.ts";
|
||||
|
||||
export interface ExecuteGitInput {
|
||||
readonly operation: string;
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
}
|
||||
|
||||
export interface ExecuteGitResult {
|
||||
readonly code: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
}
|
||||
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
||||
upstreamRef: string | null;
|
||||
}
|
||||
@@ -86,6 +102,11 @@ export interface GitSetBranchUpstreamInput {
|
||||
* GitCoreShape - Service API for low-level Git repository interactions.
|
||||
*/
|
||||
export interface GitCoreShape {
|
||||
/**
|
||||
* Execute a raw Git command.
|
||||
*/
|
||||
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Read Git status for a repository.
|
||||
*/
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
/**
|
||||
* GitService - Service for Git command execution.
|
||||
*
|
||||
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
|
||||
* domain errors for Git command execution.
|
||||
*
|
||||
* @module GitService
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { GitCommandError } from "../Errors.ts";
|
||||
|
||||
export interface ExecuteGitInput {
|
||||
readonly operation: string;
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
}
|
||||
|
||||
export interface ExecuteGitResult {
|
||||
readonly code: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitServiceShape - Service API for Git command execution.
|
||||
*/
|
||||
export interface GitServiceShape {
|
||||
/**
|
||||
* Execute a Git command.
|
||||
*/
|
||||
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitService - Service for Git command execution.
|
||||
*/
|
||||
export class GitService extends ServiceMap.Service<GitService, GitServiceShape>()(
|
||||
"t3/git/Services/GitService",
|
||||
) {}
|
||||
@@ -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 * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { assertFailure } from "@effect/vitest/utils";
|
||||
import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
|
||||
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { ServerConfig } from "./config";
|
||||
|
||||
import {
|
||||
DEFAULT_KEYBINDINGS,
|
||||
@@ -17,21 +17,17 @@ import {
|
||||
} from "./keybindings";
|
||||
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
const makeKeybindingsLayer = () =>
|
||||
KeybindingsLive.pipe(
|
||||
const makeKeybindingsLayer = () => {
|
||||
return KeybindingsLive.pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { join } = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-server-config-test-" });
|
||||
const configPath = join(dir, "keybindings.json");
|
||||
return { keybindingsConfigPath: configPath } as ServerConfigShape;
|
||||
Layer.fresh(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-keybindings-test-",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
|
||||
effect.pipe(
|
||||
@@ -42,7 +38,9 @@ const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R
|
||||
const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRule[]) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const encoded = yield* Schema.encodeEffect(KeybindingsConfigJson)(rules);
|
||||
yield* fileSystem.makeDirectory(path.dirname(configPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(configPath, encoded);
|
||||
});
|
||||
|
||||
|
||||
@@ -60,13 +60,11 @@ const runCli = (
|
||||
args: ReadonlyArray<string>,
|
||||
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
|
||||
) => {
|
||||
const uniqueStateDir = `/tmp/t3-cli-state-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
|
||||
Effect.provide(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_STATE_DIR: uniqueStateDir,
|
||||
...env,
|
||||
},
|
||||
}),
|
||||
@@ -93,8 +91,8 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
"4010",
|
||||
"--host",
|
||||
"0.0.0.0",
|
||||
"--state-dir",
|
||||
"/tmp/t3-cli-state",
|
||||
"--home-dir",
|
||||
"/tmp/t3-cli-home",
|
||||
"--dev-url",
|
||||
"http://127.0.0.1:5173",
|
||||
"--no-browser",
|
||||
@@ -106,7 +104,8 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.port, 4010);
|
||||
assert.equal(resolvedConfig?.host, "0.0.0.0");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-state");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-cli-home");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-home/dev");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "auth-secret");
|
||||
@@ -131,7 +130,7 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_PORT: "4999",
|
||||
T3CODE_HOST: "100.88.10.4",
|
||||
T3CODE_STATE_DIR: "/tmp/t3-env-state",
|
||||
T3CODE_HOME: "/tmp/t3-env-home",
|
||||
VITE_DEV_SERVER_URL: "http://localhost:5173",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTH_TOKEN: "env-token",
|
||||
@@ -141,7 +140,8 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.port, 4999);
|
||||
assert.equal(resolvedConfig?.host, "100.88.10.4");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-state");
|
||||
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-home/dev");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://localhost:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "env-token");
|
||||
|
||||
+12
-16
@@ -11,12 +11,13 @@ import { Command, Flag } from "effect/unstable/cli";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
deriveServerPaths,
|
||||
resolveStaticDir,
|
||||
ServerConfig,
|
||||
type RuntimeMode,
|
||||
type ServerConfigShape,
|
||||
} from "./config";
|
||||
import { fixPath, resolveStateDir } from "./os-jank";
|
||||
import { fixPath, resolveBaseDir } from "./os-jank";
|
||||
import { Open } from "./open";
|
||||
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
@@ -36,7 +37,7 @@ interface CliInput {
|
||||
readonly mode: Option.Option<RuntimeMode>;
|
||||
readonly port: Option.Option<number>;
|
||||
readonly host: Option.Option<string>;
|
||||
readonly stateDir: Option.Option<string>;
|
||||
readonly t3Home: Option.Option<string>;
|
||||
readonly devUrl: Option.Option<URL>;
|
||||
readonly noBrowser: Option.Option<boolean>;
|
||||
readonly authToken: Option.Option<string>;
|
||||
@@ -99,10 +100,7 @@ const CliEnvConfig = Config.all({
|
||||
),
|
||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
stateDir: Config.string("T3CODE_STATE_DIR").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||
Config.option,
|
||||
@@ -152,10 +150,10 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
},
|
||||
});
|
||||
const stateDir = yield* resolveStateDir(
|
||||
Option.getOrUndefined(input.stateDir) ?? env.stateDir,
|
||||
);
|
||||
|
||||
const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
|
||||
const baseDir = yield* resolveBaseDir(Option.getOrUndefined(input.t3Home) ?? env.t3Home);
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
const noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
|
||||
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
|
||||
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
|
||||
@@ -167,8 +165,6 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
env.logWebSocketEvents ?? Boolean(devUrl),
|
||||
);
|
||||
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
|
||||
const { join } = yield* Path.Path;
|
||||
const keybindingsConfigPath = join(stateDir, "keybindings.json");
|
||||
const host =
|
||||
Option.getOrUndefined(input.host) ??
|
||||
env.host ??
|
||||
@@ -178,9 +174,9 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
mode,
|
||||
port,
|
||||
cwd: cliConfig.cwd,
|
||||
keybindingsConfigPath,
|
||||
host,
|
||||
stateDir,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
staticDir,
|
||||
devUrl,
|
||||
noBrowser,
|
||||
@@ -299,8 +295,8 @@ const hostFlag = Flag.string("host").pipe(
|
||||
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const stateDirFlag = Flag.string("state-dir").pipe(
|
||||
Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."),
|
||||
const t3HomeFlag = Flag.string("home-dir").pipe(
|
||||
Flag.withDescription("Base directory for all T3 Code data (equivalent to T3CODE_HOME)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const devUrlFlag = Flag.string("dev-url").pipe(
|
||||
@@ -335,7 +331,7 @@ export const t3Cli = Command.make("t3", {
|
||||
mode: modeFlag,
|
||||
port: portFlag,
|
||||
host: hostFlag,
|
||||
stateDir: stateDirFlag,
|
||||
t3Home: t3HomeFlag,
|
||||
devUrl: devUrlFlag,
|
||||
noBrowser: noBrowserFlag,
|
||||
authToken: authTokenFlag,
|
||||
|
||||
@@ -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,
|
||||
@@ -19,6 +19,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||
@@ -44,7 +45,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 +236,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);
|
||||
@@ -252,12 +253,16 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-checkpoint-reactor-test-",
|
||||
});
|
||||
|
||||
const layer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(GitCoreLive))),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -478,10 +483,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 +498,7 @@ describe("CheckpointReactor", () => {
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeCode",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
@@ -506,7 +511,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 +525,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 +859,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 +871,7 @@ describe("CheckpointReactor", () => {
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeCode",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
|
||||
@@ -35,12 +35,15 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
|
||||
|
||||
async function createOrchestrationSystem() {
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-orchestration-engine-test-",
|
||||
});
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(orchestrationLayer);
|
||||
@@ -317,13 +320,17 @@ describe("OrchestrationEngine", () => {
|
||||
},
|
||||
};
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-orchestration-engine-test-",
|
||||
});
|
||||
|
||||
const runtime = ManagedRuntime.make(
|
||||
OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -243,7 +243,7 @@ const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSid
|
||||
const fileSystem = yield* Effect.service(FileSystem.FileSystem);
|
||||
const path = yield* Effect.service(Path.Path);
|
||||
|
||||
const attachmentsRootDir = path.join(serverConfig.stateDir, "attachments");
|
||||
const attachmentsRootDir = serverConfig.attachmentsDir;
|
||||
|
||||
yield* Effect.forEach(
|
||||
sideEffects.deletedThreadIds,
|
||||
@@ -653,6 +653,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,
|
||||
});
|
||||
@@ -775,6 +777,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 +808,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 +836,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 +895,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 +932,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 +978,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,
|
||||
|
||||
@@ -26,6 +26,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,6 +102,29 @@ 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,
|
||||
@@ -154,6 +178,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 +194,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
NULL,
|
||||
'thread-1',
|
||||
'plan-1',
|
||||
'message-1',
|
||||
'completed',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
@@ -238,6 +266,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 +285,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"),
|
||||
|
||||
@@ -4,8 +4,10 @@ import {
|
||||
MessageId,
|
||||
NonNegativeInt,
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationProposedPlanId,
|
||||
OrchestrationReadModel,
|
||||
ProjectScript,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationLatestTurn,
|
||||
@@ -74,6 +76,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;
|
||||
|
||||
@@ -200,6 +204,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
|
||||
@@ -284,7 +290,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
|
||||
@@ -435,6 +443,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,
|
||||
});
|
||||
@@ -497,6 +507,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,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../../git/Errors.ts";
|
||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
@@ -41,6 +41,9 @@ const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
|
||||
const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>
|
||||
Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)));
|
||||
|
||||
async function waitFor(
|
||||
predicate: () => boolean | Promise<boolean>,
|
||||
timeoutMs = 2000,
|
||||
@@ -67,6 +70,7 @@ describe("ProviderCommandReactor", () => {
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
const createdStateDirs = new Set<string>();
|
||||
const createdBaseDirs = new Set<string>();
|
||||
|
||||
afterEach(async () => {
|
||||
if (scope) {
|
||||
@@ -81,12 +85,22 @@ describe("ProviderCommandReactor", () => {
|
||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||
}
|
||||
createdStateDirs.clear();
|
||||
for (const baseDir of createdBaseDirs) {
|
||||
fs.rmSync(baseDir, { recursive: true, force: true });
|
||||
}
|
||||
createdBaseDirs.clear();
|
||||
});
|
||||
|
||||
async function createHarness(input?: { readonly stateDir?: string }) {
|
||||
async function createHarness(input?: {
|
||||
readonly baseDir?: string;
|
||||
readonly threadModel?: string;
|
||||
}) {
|
||||
const now = new Date().toISOString();
|
||||
const stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
||||
const baseDir = input?.baseDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
||||
createdBaseDirs.add(baseDir);
|
||||
const { stateDir } = deriveServerPathsSync(baseDir, undefined);
|
||||
createdStateDirs.add(stateDir);
|
||||
const threadModel = input?.threadModel ?? "gpt-5-codex";
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
let nextSessionIndex = 1;
|
||||
const runtimeSessions: Array<ProviderSession> = [];
|
||||
@@ -96,7 +110,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 =
|
||||
@@ -210,7 +224,7 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
|
||||
),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
@@ -228,7 +242,7 @@ describe("ProviderCommandReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot: "/tmp/provider-project",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModel: threadModel,
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -239,7 +253,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 +365,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 +503,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 +518,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 +645,74 @@ 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",
|
||||
resumeCursor: { opaque: "resume-1" },
|
||||
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 +800,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 +835,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 () => {
|
||||
@@ -894,6 +1146,7 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(failureActivity).toBeDefined();
|
||||
expect(failureActivity?.payload).toMatchObject({
|
||||
requestId: "approval-request-1",
|
||||
detail: expect.stringContaining("Stale pending approval request: approval-request-1"),
|
||||
});
|
||||
|
||||
const resolvedActivity = thread?.activities.find(
|
||||
@@ -906,6 +1159,117 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(resolvedActivity).toBeUndefined();
|
||||
});
|
||||
|
||||
it("surfaces stale provider user-input failures without faking user-input resolution", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
harness.respondToUserInput.mockImplementation(() =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: "claudeAgent",
|
||||
method: "item/tool/respondToUserInput",
|
||||
detail: "Unknown pending user-input request: user-input-request-1",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input-error"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: CommandId.makeUnsafe("cmd-user-input-requested"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
activity: {
|
||||
id: EventId.makeUnsafe("activity-user-input-requested"),
|
||||
tone: "info",
|
||||
kind: "user-input.requested",
|
||||
summary: "User input requested",
|
||||
payload: {
|
||||
requestId: "user-input-request-1",
|
||||
questions: [
|
||||
{
|
||||
id: "sandbox_mode",
|
||||
header: "Sandbox",
|
||||
question: "Which mode should be used?",
|
||||
options: [
|
||||
{
|
||||
label: "workspace-write",
|
||||
description: "Allow workspace writes only",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.user-input.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-user-input-respond-stale"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
requestId: asApprovalRequestId("user-input-request-1"),
|
||||
answers: {
|
||||
sandbox_mode: "workspace-write",
|
||||
},
|
||||
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"),
|
||||
);
|
||||
if (!thread) return false;
|
||||
return thread.activities.some(
|
||||
(activity) => activity.kind === "provider.user-input.respond.failed",
|
||||
);
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread).toBeDefined();
|
||||
|
||||
const failureActivity = thread?.activities.find(
|
||||
(activity) => activity.kind === "provider.user-input.respond.failed",
|
||||
);
|
||||
expect(failureActivity).toBeDefined();
|
||||
expect(failureActivity?.payload).toMatchObject({
|
||||
requestId: "user-input-request-1",
|
||||
detail: expect.stringContaining("Stale pending user-input request: user-input-request-1"),
|
||||
});
|
||||
|
||||
const resolvedActivity = thread?.activities.find(
|
||||
(activity) =>
|
||||
activity.kind === "user-input.resolved" &&
|
||||
typeof activity.payload === "object" &&
|
||||
activity.payload !== null &&
|
||||
(activity.payload as Record<string, unknown>).requestId === "user-input-request-1",
|
||||
);
|
||||
expect(resolvedActivity).toBeUndefined();
|
||||
});
|
||||
|
||||
it("reacts to thread.session.stop by stopping provider session and clearing thread session state", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import {
|
||||
type ChatAttachment,
|
||||
CommandId,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
EventId,
|
||||
type OrchestrationEvent,
|
||||
type ProviderModelOptions,
|
||||
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)) {
|
||||
@@ -90,6 +97,21 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
|
||||
);
|
||||
}
|
||||
|
||||
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||
const error = Cause.squash(cause);
|
||||
if (Schema.is(ProviderAdapterRequestError)(error)) {
|
||||
return error.detail.toLowerCase().includes("unknown pending user-input request");
|
||||
}
|
||||
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
|
||||
}
|
||||
|
||||
function stalePendingRequestDetail(
|
||||
requestKind: "approval" | "user-input",
|
||||
requestId: string,
|
||||
): string {
|
||||
return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`;
|
||||
}
|
||||
|
||||
function isTemporaryWorktreeBranch(branch: string): boolean {
|
||||
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
|
||||
}
|
||||
@@ -136,6 +158,7 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const threadProviderOptions = new Map<string, ProviderStartOptions>();
|
||||
const threadModelOptions = new Map<string, ProviderModelOptions>();
|
||||
|
||||
const appendProviderFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -205,11 +228,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,8 +311,18 @@ 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;
|
||||
}
|
||||
|
||||
@@ -289,6 +341,7 @@ const make = Effect.gen(function* () {
|
||||
providerChanged,
|
||||
modelChanged,
|
||||
shouldRestartForModelChange,
|
||||
shouldRestartForModelOptionsChange,
|
||||
hasResumeCursor: resumeCursor !== undefined,
|
||||
});
|
||||
const restartedSession = yield* startProviderSession({
|
||||
@@ -328,15 +381,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 +449,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 +534,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* (
|
||||
@@ -536,7 +604,9 @@ const make = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
detail: Cause.pretty(cause),
|
||||
detail: isUnknownPendingApprovalRequestError(cause)
|
||||
? stalePendingRequestDetail("approval", event.payload.requestId)
|
||||
: Cause.pretty(cause),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
@@ -580,7 +650,9 @@ const make = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.user-input.respond.failed",
|
||||
summary: "Provider user input response failed",
|
||||
detail: Cause.pretty(cause),
|
||||
detail: isUnknownPendingUserInputRequestError(cause)
|
||||
? stalePendingRequestDetail("user-input", event.payload.requestId)
|
||||
: Cause.pretty(cause),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
@@ -626,13 +698,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;
|
||||
}
|
||||
@@ -150,6 +167,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 +223,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 +441,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeCode",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: seededAt,
|
||||
@@ -427,7 +454,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 +470,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 +709,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();
|
||||
@@ -1408,6 +1925,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
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.",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1470,8 +1988,9 @@ 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>");
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationProposedPlanId,
|
||||
CheckpointRef,
|
||||
isToolLifecycleItemType,
|
||||
ThreadId,
|
||||
@@ -15,6 +16,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";
|
||||
@@ -370,7 +373,8 @@ 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 } : {}),
|
||||
},
|
||||
@@ -480,6 +484,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 +676,8 @@ const make = Effect.gen(function* () {
|
||||
threadProposedPlans: ReadonlyArray<{
|
||||
id: string;
|
||||
createdAt: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
}>;
|
||||
planId: string;
|
||||
turnId?: TurnId;
|
||||
@@ -693,6 +700,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 +715,8 @@ const make = Effect.gen(function* () {
|
||||
threadProposedPlans: ReadonlyArray<{
|
||||
id: string;
|
||||
createdAt: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
}>;
|
||||
planId: string;
|
||||
turnId?: TurnId;
|
||||
@@ -772,6 +783,79 @@ 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 processRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
@@ -812,6 +896,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 +942,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"),
|
||||
@@ -1144,4 +1252,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));
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -27,10 +27,10 @@ export const expandHomePath = Effect.fn(function* (input: string) {
|
||||
return input;
|
||||
});
|
||||
|
||||
export const resolveStateDir = Effect.fn(function* (raw: string | undefined) {
|
||||
export const resolveBaseDir = Effect.fn(function* (raw: string | undefined) {
|
||||
const { join, resolve } = yield* Path.Path;
|
||||
if (!raw || raw.trim().length === 0) {
|
||||
return join(OS.homedir(), ".t3", "userdata");
|
||||
return join(OS.homedir(), ".t3");
|
||||
}
|
||||
return resolve(yield* expandHomePath(raw.trim()));
|
||||
});
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -49,9 +49,6 @@ export const SqlitePersistenceMemory = Layer.provideMerge(
|
||||
makeRuntimeSqliteLayer({ filename: ":memory:" }),
|
||||
);
|
||||
|
||||
export const layerConfig = Effect.gen(function* () {
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
const { join } = yield* Path.Path;
|
||||
const dbPath = join(stateDir, "state.sqlite");
|
||||
return makeSqlitePersistenceLive(dbPath);
|
||||
}).pipe(Layer.unwrap);
|
||||
export const layerConfig = Layer.unwrap(
|
||||
Effect.map(Effect.service(ServerConfig), ({ dbPath }) => makeSqlitePersistenceLive(dbPath)),
|
||||
);
|
||||
@@ -25,6 +25,8 @@ 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 { Effect } from "effect";
|
||||
|
||||
/**
|
||||
@@ -51,6 +53,8 @@ const loader = Migrator.fromRecord({
|
||||
"11_OrchestrationThreadCreatedRuntimeMode": Migration0011,
|
||||
"12_ProjectionThreadsInteractionMode": Migration0012,
|
||||
"13_ProjectionThreadProposedPlans": Migration0013,
|
||||
"14_ProjectionThreadProposedPlanImplementation": Migration0014,
|
||||
"15_ProjectionTurnsSourceProposedPlan": Migration0015,
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
+16
@@ -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
|
||||
`;
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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
+1295
-239
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),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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,45 @@ 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"),
|
||||
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.providerRefs?.providerTurnId, "turn-parent");
|
||||
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 } : {}),
|
||||
};
|
||||
@@ -1328,7 +1336,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
stateDir: serverConfig.stateDir,
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
@@ -195,9 +195,21 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
|
||||
};
|
||||
|
||||
const updateSession = (
|
||||
threadId: ThreadId,
|
||||
update: (session: ProviderSession) => ProviderSession,
|
||||
): void => {
|
||||
const existing = sessions.get(threadId);
|
||||
if (!existing) {
|
||||
return;
|
||||
}
|
||||
sessions.set(threadId, update(existing));
|
||||
};
|
||||
|
||||
return {
|
||||
adapter,
|
||||
emit,
|
||||
updateSession,
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
@@ -217,15 +229,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);
|
||||
@@ -348,16 +360,29 @@ it.effect(
|
||||
Layer.provide(firstDirectoryLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
const updatedResumeCursor = {
|
||||
threadId: asThreadId("thread-1"),
|
||||
resume: "resume-session-1",
|
||||
resumeSessionAt: "assistant-message-1",
|
||||
turnCount: 1,
|
||||
};
|
||||
|
||||
const startedSession = yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const threadId = asThreadId("thread-1");
|
||||
return yield* provider.startSession(threadId, {
|
||||
const session = yield* provider.startSession(threadId, {
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project",
|
||||
runtimeMode: "full-access",
|
||||
threadId,
|
||||
});
|
||||
firstCodex.updateSession(threadId, (existing) => ({
|
||||
...existing,
|
||||
status: "ready",
|
||||
resumeCursor: updatedResumeCursor,
|
||||
updatedAt: new Date(Date.now() + 1_000).toISOString(),
|
||||
}));
|
||||
return session;
|
||||
}).pipe(Effect.provide(firstProviderLayer));
|
||||
|
||||
const persistedAfterStopAll = yield* Effect.gen(function* () {
|
||||
@@ -367,7 +392,7 @@ it.effect(
|
||||
assert.equal(Option.isSome(persistedAfterStopAll), true);
|
||||
if (Option.isSome(persistedAfterStopAll)) {
|
||||
assert.equal(persistedAfterStopAll.value.status, "stopped");
|
||||
assert.deepEqual(persistedAfterStopAll.value.resumeCursor, startedSession.resumeCursor);
|
||||
assert.deepEqual(persistedAfterStopAll.value.resumeCursor, updatedResumeCursor);
|
||||
}
|
||||
|
||||
const secondCodex = makeFakeCodexAdapter();
|
||||
@@ -410,7 +435,7 @@ it.effect(
|
||||
};
|
||||
assert.equal(startPayload.provider, "codex");
|
||||
assert.equal(startPayload.cwd, "/tmp/project");
|
||||
assert.deepEqual(startPayload.resumeCursor, startedSession.resumeCursor);
|
||||
assert.deepEqual(startPayload.resumeCursor, updatedResumeCursor);
|
||||
assert.equal(startPayload.threadId, startedSession.threadId);
|
||||
}
|
||||
assert.equal(secondCodex.rollbackThread.mock.calls.length, 1);
|
||||
@@ -537,24 +562,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 +625,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;
|
||||
@@ -665,6 +741,96 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reuses persisted resume cursor when startSession is called after a restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-service-start-"));
|
||||
const dbPath = path.join(tempDir, "orchestration.sqlite");
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
);
|
||||
|
||||
const firstClaude = makeFakeCodexAdapter("claudeAgent");
|
||||
const firstRegistry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "claudeAgent"
|
||||
? Effect.succeed(firstClaude.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["claudeAgent"]),
|
||||
};
|
||||
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const firstProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
|
||||
Layer.provide(firstDirectoryLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
|
||||
const initial = yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
return yield* provider.startSession(asThreadId("thread-claude-start"), {
|
||||
provider: "claudeAgent",
|
||||
threadId: asThreadId("thread-claude-start"),
|
||||
cwd: "/tmp/project-claude-start",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
}).pipe(Effect.provide(firstProviderLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
yield* provider.listSessions();
|
||||
}).pipe(Effect.provide(firstProviderLayer));
|
||||
|
||||
const secondClaude = makeFakeCodexAdapter("claudeAgent");
|
||||
const secondRegistry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "claudeAgent"
|
||||
? Effect.succeed(secondClaude.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["claudeAgent"]),
|
||||
};
|
||||
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const secondProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
|
||||
Layer.provide(secondDirectoryLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
|
||||
secondClaude.startSession.mockClear();
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
yield* provider.startSession(initial.threadId, {
|
||||
provider: "claudeAgent",
|
||||
threadId: initial.threadId,
|
||||
cwd: "/tmp/project-claude-start",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
}).pipe(Effect.provide(secondProviderLayer));
|
||||
|
||||
assert.equal(secondClaude.startSession.mock.calls.length, 1);
|
||||
const resumedStartInput = secondClaude.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;
|
||||
resumeCursor?: unknown;
|
||||
threadId?: string;
|
||||
};
|
||||
assert.equal(startPayload.provider, "claudeAgent");
|
||||
assert.equal(startPayload.cwd, "/tmp/project-claude-start");
|
||||
assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);
|
||||
assert.equal(startPayload.threadId, initial.threadId);
|
||||
}
|
||||
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
|
||||
const fanout = makeProviderServiceLayer();
|
||||
@@ -682,7 +848,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
const consumer = yield* Stream.runForEach(provider.streamEvents, (event) =>
|
||||
Ref.update(eventsRef, (current) => [...current, event]),
|
||||
).pipe(Effect.forkChild);
|
||||
yield* sleep(20);
|
||||
yield* sleep(50);
|
||||
|
||||
const completedEvent: LegacyProviderRuntimeEvent = {
|
||||
type: "turn.completed",
|
||||
@@ -695,7 +861,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
};
|
||||
|
||||
fanout.codex.emit(completedEvent);
|
||||
yield* sleep(20);
|
||||
yield* sleep(50);
|
||||
|
||||
const events = yield* Ref.get(eventsRef);
|
||||
yield* Fiber.interrupt(consumer);
|
||||
@@ -721,7 +887,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
Stream.runForEach((event) => Ref.update(receivedRef, (current) => [...current, event])),
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* sleep(20);
|
||||
yield* sleep(50);
|
||||
|
||||
fanout.codex.emit({
|
||||
type: "tool.started",
|
||||
@@ -785,7 +951,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
Stream.runForEach(() => Effect.fail("listener crash")),
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* sleep(20);
|
||||
yield* sleep(50);
|
||||
|
||||
const events: ReadonlyArray<LegacyProviderRuntimeEvent> = [
|
||||
{
|
||||
|
||||
@@ -88,17 +88,38 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
|
||||
|
||||
function toRuntimePayloadFromSession(
|
||||
session: ProviderSession,
|
||||
extra?: { readonly providerOptions?: unknown },
|
||||
extra?: {
|
||||
readonly modelOptions?: unknown;
|
||||
readonly providerOptions?: unknown;
|
||||
readonly lastRuntimeEvent?: string;
|
||||
readonly lastRuntimeEventAt?: string;
|
||||
},
|
||||
): 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 } : {}),
|
||||
...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}),
|
||||
...(extra?.lastRuntimeEventAt !== undefined
|
||||
? { lastRuntimeEventAt: extra.lastRuntimeEventAt }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
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 +171,12 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const upsertSessionBinding = (
|
||||
session: ProviderSession,
|
||||
threadId: ThreadId,
|
||||
extra?: { readonly providerOptions?: unknown },
|
||||
extra?: {
|
||||
readonly modelOptions?: unknown;
|
||||
readonly providerOptions?: unknown;
|
||||
readonly lastRuntimeEvent?: string;
|
||||
readonly lastRuntimeEventAt?: string;
|
||||
},
|
||||
) =>
|
||||
directory.upsert({
|
||||
threadId,
|
||||
@@ -165,7 +191,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const adapters = yield* Effect.forEach(providers, (provider) =>
|
||||
registry.getByProvider(provider),
|
||||
);
|
||||
|
||||
const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
publishRuntimeEvent(event);
|
||||
|
||||
@@ -213,12 +238,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",
|
||||
@@ -281,8 +308,17 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
threadId,
|
||||
provider: parsed.provider ?? "codex",
|
||||
};
|
||||
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
|
||||
const effectiveResumeCursor =
|
||||
input.resumeCursor ??
|
||||
(persistedBinding?.provider === input.provider
|
||||
? persistedBinding.resumeCursor
|
||||
: undefined);
|
||||
const adapter = yield* registry.getByProvider(input.provider);
|
||||
const session = yield* adapter.startSession(input);
|
||||
const session = yield* adapter.startSession({
|
||||
...input,
|
||||
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
|
||||
});
|
||||
|
||||
if (session.provider !== adapter.provider) {
|
||||
return yield* toValidationError(
|
||||
@@ -292,6 +328,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(session, threadId, {
|
||||
modelOptions: input.modelOptions,
|
||||
providerOptions: input.providerOptions,
|
||||
});
|
||||
yield* analytics.record("provider.session.started", {
|
||||
@@ -498,6 +535,17 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const runStopAll = () =>
|
||||
Effect.gen(function* () {
|
||||
const threadIds = yield* directory.listThreadIds();
|
||||
const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
|
||||
adapter.listSessions(),
|
||||
).pipe(
|
||||
Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)),
|
||||
);
|
||||
yield* Effect.forEach(activeSessions, (session) =>
|
||||
upsertSessionBinding(session, session.threadId, {
|
||||
lastRuntimeEvent: "provider.stopAll",
|
||||
lastRuntimeEventAt: new Date().toISOString(),
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
|
||||
yield* Effect.forEach(threadIds, (threadId) =>
|
||||
directory.getProvider(threadId).pipe(
|
||||
|
||||
@@ -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>>;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, FileSystem, Layer } from "effect";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
|
||||
@@ -19,7 +17,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";
|
||||
@@ -33,20 +31,33 @@ import { GitManagerLive } from "./git/Layers/GitManager";
|
||||
import { GitCoreLive } from "./git/Layers/GitCore";
|
||||
import { GitHubCliLive } from "./git/Layers/GitHubCli";
|
||||
import { CodexTextGenerationLive } from "./git/Layers/CodexTextGeneration";
|
||||
import { GitServiceLive } from "./git/Layers/GitService";
|
||||
import { BunPtyAdapterLive } from "./terminal/Layers/BunPTY";
|
||||
import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
|
||||
import { PtyAdapter } from "./terminal/Services/PTY";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
|
||||
type RuntimePtyAdapterLoader = {
|
||||
layer: Layer.Layer<PtyAdapter, never, FileSystem.FileSystem | Path.Path>;
|
||||
};
|
||||
|
||||
const runtimePtyAdapterLoaders = {
|
||||
bun: () => import("./terminal/Layers/BunPTY"),
|
||||
node: () => import("./terminal/Layers/NodePTY"),
|
||||
} satisfies Record<string, () => Promise<RuntimePtyAdapterLoader>>;
|
||||
|
||||
const makeRuntimePtyAdapterLayer = () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = process.versions.bun !== undefined ? "bun" : "node";
|
||||
const loader = runtimePtyAdapterLoaders[runtime];
|
||||
const ptyAdapterModule = yield* Effect.promise<RuntimePtyAdapterLoader>(loader);
|
||||
return ptyAdapterModule.layer;
|
||||
}).pipe(Layer.unwrap);
|
||||
|
||||
export function makeServerProviderLayer(): Layer.Layer<
|
||||
ProviderService,
|
||||
ProviderUnsupportedError,
|
||||
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem | AnalyticsService
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
const providerLogsDir = path.join(stateDir, "logs", "provider");
|
||||
const providerEventLogPath = path.join(providerLogsDir, "events.log");
|
||||
const { providerEventLogPath } = yield* ServerConfig;
|
||||
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "native",
|
||||
});
|
||||
@@ -59,7 +70,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(
|
||||
@@ -74,8 +85,8 @@ export function makeServerProviderLayer(): Layer.Layer<
|
||||
}
|
||||
|
||||
export function makeServerRuntimeServicesLayer() {
|
||||
const gitCoreLayer = GitCoreLive.pipe(Layer.provideMerge(GitServiceLive));
|
||||
const textGenerationLayer = CodexTextGenerationLive;
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
@@ -85,13 +96,13 @@ export function makeServerRuntimeServicesLayer() {
|
||||
|
||||
const checkpointDiffQueryLayer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
Layer.provideMerge(checkpointStoreLayer),
|
||||
);
|
||||
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
CheckpointStoreLive,
|
||||
checkpointStoreLayer,
|
||||
checkpointDiffQueryLayer,
|
||||
RuntimeReceiptBusLive,
|
||||
);
|
||||
@@ -100,7 +111,7 @@ export function makeServerRuntimeServicesLayer() {
|
||||
);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
@@ -112,23 +123,17 @@ export function makeServerRuntimeServicesLayer() {
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
);
|
||||
|
||||
const terminalLayer = TerminalManagerLive.pipe(
|
||||
Layer.provide(
|
||||
typeof Bun !== "undefined" && process.platform !== "win32"
|
||||
? BunPtyAdapterLive
|
||||
: NodePtyAdapterLive,
|
||||
),
|
||||
);
|
||||
const terminalLayer = TerminalManagerLive.pipe(Layer.provide(makeRuntimePtyAdapterLayer()));
|
||||
|
||||
const gitManagerLayer = GitManagerLive.pipe(
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provideMerge(GitHubCliLive),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
|
||||
return Layer.mergeAll(
|
||||
orchestrationReactorLayer,
|
||||
gitCoreLayer,
|
||||
GitCoreLive,
|
||||
gitManagerLayer,
|
||||
terminalLayer,
|
||||
KeybindingsLive,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { Effect, Logger } from "effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -7,16 +6,13 @@ import * as Layer from "effect/Layer";
|
||||
import { ServerConfig } from "./config";
|
||||
|
||||
export const ServerLoggerLive = Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
|
||||
const logDir = path.join(config.stateDir, "logs");
|
||||
const logPath = path.join(logDir, "server.log");
|
||||
const { logsDir, serverLogPath } = yield* ServerConfig;
|
||||
|
||||
yield* Effect.sync(() => {
|
||||
fs.mkdirSync(logDir, { recursive: true });
|
||||
fs.mkdirSync(logsDir, { recursive: true });
|
||||
});
|
||||
|
||||
const fileLogger = Logger.formatSimple.pipe(Logger.toFile(logPath));
|
||||
const fileLogger = Logger.formatSimple.pipe(Logger.toFile(serverLogPath));
|
||||
|
||||
return Logger.layer([Logger.defaultLogger, fileLogger], {
|
||||
mergeWithExisting: false,
|
||||
|
||||
@@ -9,6 +9,10 @@ const CodexAuthJsonSchema = Schema.Struct({
|
||||
}),
|
||||
});
|
||||
|
||||
const ClaudeJsonSchema = Schema.Struct({
|
||||
userID: Schema.String,
|
||||
});
|
||||
|
||||
class IdentifyUserError extends Schema.TaggedErrorClass<IdentifyUserError>()("IdentifyUserError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
@@ -37,12 +41,23 @@ const getCodexAccountId = Effect.gen(function* () {
|
||||
return authJson.tokens.account_id;
|
||||
});
|
||||
|
||||
const upsertAnonymousId = Effect.gen(function* () {
|
||||
const getClaudeUserId = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
|
||||
const anonymousIdPath = path.join(serverConfig.stateDir, "anonymous-id");
|
||||
const claudeJsonPath = path.join(homedir(), ".claude.json");
|
||||
const claudeJson = yield* Effect.flatMap(
|
||||
fileSystem.readFileString(claudeJsonPath),
|
||||
Schema.decodeEffect(Schema.fromJsonString(ClaudeJsonSchema)),
|
||||
);
|
||||
|
||||
return claudeJson.userID;
|
||||
});
|
||||
|
||||
const upsertAnonymousId = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const { anonymousIdPath } = yield* ServerConfig;
|
||||
|
||||
const anonymousId = yield* fileSystem.readFileString(anonymousIdPath).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -59,7 +74,8 @@ const upsertAnonymousId = Effect.gen(function* () {
|
||||
/**
|
||||
* getTelemetryIdentifier - Users are "identified" by finding the first match of the following, then hashing the value.
|
||||
* 1. ~/.codex/auth.json tokens.account_id
|
||||
* 2. ~/.t3/telemetry/anonymous-id
|
||||
* 2. ~/.claude.json userID
|
||||
* 3. ~/.t3/telemetry/anonymous-id
|
||||
*/
|
||||
export const getTelemetryIdentifier = Effect.gen(function* () {
|
||||
const codexAccountId = yield* Effect.result(getCodexAccountId);
|
||||
@@ -67,6 +83,11 @@ export const getTelemetryIdentifier = Effect.gen(function* () {
|
||||
return yield* hash(codexAccountId.success);
|
||||
}
|
||||
|
||||
const claudeUserId = yield* Effect.result(getClaudeUserId);
|
||||
if (claudeUserId._tag === "Success") {
|
||||
return yield* hash(claudeUserId.success);
|
||||
}
|
||||
|
||||
const anonymousId = yield* Effect.result(upsertAnonymousId);
|
||||
if (anonymousId._tag === "Success") {
|
||||
return yield* hash(anonymousId.success);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { ConfigProvider, Effect, FileSystem, Layer } from "effect";
|
||||
import { ConfigProvider, Effect, Layer } from "effect";
|
||||
import * as HttpServer from "effect/unstable/http/HttpServer";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
@@ -37,13 +37,10 @@ interface RecordedBatchBody {
|
||||
it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
|
||||
it.effect("flush drains all buffered events across multiple batches", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const stateDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-telemetry-flush-",
|
||||
});
|
||||
|
||||
const capturedRequests: Array<RecordedBatchRequest> = [];
|
||||
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), stateDir);
|
||||
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-telemetry-base-",
|
||||
});
|
||||
|
||||
const telemetryLayer = AnalyticsServiceLayerLive.pipe(Layer.provideMerge(serverConfigLayer));
|
||||
const configLayer = ConfigProvider.layer(
|
||||
|
||||
@@ -86,11 +86,13 @@ class BunPtyProcess implements PtyProcess {
|
||||
}
|
||||
}
|
||||
|
||||
export const BunPtyAdapterLive = Layer.effect(
|
||||
export const layer = Layer.effect(
|
||||
PtyAdapter,
|
||||
Effect.gen(function* () {
|
||||
if (process.platform === "win32") {
|
||||
return yield* Effect.die("Bun PTY terminal support is unavailable on Windows.");
|
||||
return yield* Effect.die(
|
||||
"Bun PTY terminal support is unavailable on Windows. Please use Node.js (e.g. by running `npx t3`) instead.",
|
||||
);
|
||||
}
|
||||
return {
|
||||
spawn: (input) =>
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
type TerminalEvent,
|
||||
type TerminalSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Encoding, Layer, Path, Schema } from "effect";
|
||||
import { Effect, Encoding, Layer, Schema } from "effect";
|
||||
|
||||
import { createLogger } from "../../logger";
|
||||
import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "../Services/PTY";
|
||||
@@ -1172,13 +1172,11 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
export const TerminalManagerLive = Layer.effect(
|
||||
TerminalManager,
|
||||
Effect.gen(function* () {
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
const { join } = yield* Path.Path;
|
||||
const logsDir = join(stateDir, "logs", "terminals");
|
||||
const { terminalLogsDir } = yield* ServerConfig;
|
||||
|
||||
const ptyAdapter = yield* PtyAdapter;
|
||||
const runtime = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter })),
|
||||
Effect.sync(() => new TerminalManagerRuntime({ logsDir: terminalLogsDir, ptyAdapter })),
|
||||
(r) => Effect.sync(() => r.dispose()),
|
||||
);
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ class NodePtyProcess implements PtyProcess {
|
||||
}
|
||||
}
|
||||
|
||||
export const NodePtyAdapterLive = Layer.effect(
|
||||
export const layer = Layer.effect(
|
||||
PtyAdapter,
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effec
|
||||
import { describe, expect, it, afterEach, vi } from "vitest";
|
||||
import { createServer } from "./wsServer";
|
||||
import WebSocket from "ws";
|
||||
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
|
||||
import {
|
||||
@@ -451,6 +451,16 @@ function expectAvailableEditors(value: unknown): void {
|
||||
}
|
||||
}
|
||||
|
||||
function ensureParentDir(filePath: string): void {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
}
|
||||
|
||||
function deriveServerPathsSync(baseDir: string, devUrl: URL | undefined) {
|
||||
return Effect.runSync(
|
||||
deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
}
|
||||
|
||||
describe("WebSocket Server", () => {
|
||||
let server: Http.Server | null = null;
|
||||
let serverScope: Scope.Closeable | null = null;
|
||||
@@ -474,7 +484,7 @@ describe("WebSocket Server", () => {
|
||||
logWebSocketEvents?: boolean;
|
||||
devUrl?: string;
|
||||
authToken?: string;
|
||||
stateDir?: string;
|
||||
baseDir?: string;
|
||||
staticDir?: string;
|
||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
||||
providerHealth?: ProviderHealthShape;
|
||||
@@ -488,7 +498,9 @@ describe("WebSocket Server", () => {
|
||||
throw new Error("Test server is already running");
|
||||
}
|
||||
|
||||
const stateDir = options.stateDir ?? makeTempDir("t3code-ws-state-");
|
||||
const baseDir = options.baseDir ?? makeTempDir("t3code-ws-base-");
|
||||
const devUrl = options.devUrl ? new URL(options.devUrl) : undefined;
|
||||
const derivedPaths = deriveServerPathsSync(baseDir, devUrl);
|
||||
const scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory;
|
||||
const providerLayer = options.providerLayer ?? makeServerProviderLayer();
|
||||
@@ -502,10 +514,10 @@ describe("WebSocket Server", () => {
|
||||
port: 0,
|
||||
host: undefined,
|
||||
cwd: options.cwd ?? "/test/project",
|
||||
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
|
||||
stateDir,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
staticDir: options.staticDir,
|
||||
devUrl: options.devUrl ? new URL(options.devUrl) : undefined,
|
||||
devUrl,
|
||||
noBrowser: true,
|
||||
authToken: options.authToken,
|
||||
autoBootstrapProjectFromCwd: options.autoBootstrapProjectFromCwd ?? false,
|
||||
@@ -590,12 +602,13 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
|
||||
it("serves persisted attachments from stateDir", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-attachments-");
|
||||
const attachmentPath = path.join(stateDir, "attachments", "thread-a", "message-a", "0.png");
|
||||
const baseDir = makeTempDir("t3code-state-attachments-");
|
||||
const { attachmentsDir } = deriveServerPathsSync(baseDir, undefined);
|
||||
const attachmentPath = path.join(attachmentsDir, "thread-a", "message-a", "0.png");
|
||||
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
|
||||
fs.writeFileSync(attachmentPath, Buffer.from("hello-attachment"));
|
||||
|
||||
server = await createTestServer({ cwd: "/test/project", stateDir });
|
||||
server = await createTestServer({ cwd: "/test/project", baseDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
@@ -608,10 +621,10 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
|
||||
it("serves persisted attachments for URL-encoded paths", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-attachments-encoded-");
|
||||
const baseDir = makeTempDir("t3code-state-attachments-encoded-");
|
||||
const { attachmentsDir } = deriveServerPathsSync(baseDir, undefined);
|
||||
const attachmentPath = path.join(
|
||||
stateDir,
|
||||
"attachments",
|
||||
attachmentsDir,
|
||||
"thread%20folder",
|
||||
"message%20folder",
|
||||
"file%20name.png",
|
||||
@@ -619,7 +632,7 @@ describe("WebSocket Server", () => {
|
||||
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
|
||||
fs.writeFileSync(attachmentPath, Buffer.from("hello-encoded-attachment"));
|
||||
|
||||
server = await createTestServer({ cwd: "/test/project", stateDir });
|
||||
server = await createTestServer({ cwd: "/test/project", baseDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
@@ -634,11 +647,11 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
|
||||
it("serves static index for root path", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-static-root-");
|
||||
const baseDir = makeTempDir("t3code-state-static-root-");
|
||||
const staticDir = makeTempDir("t3code-static-root-");
|
||||
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>static-root</h1>", "utf8");
|
||||
|
||||
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
|
||||
server = await createTestServer({ cwd: "/test/project", baseDir, staticDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
@@ -649,11 +662,11 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
|
||||
it("rejects static path traversal attempts", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-static-traversal-");
|
||||
const baseDir = makeTempDir("t3code-state-static-traversal-");
|
||||
const staticDir = makeTempDir("t3code-static-traversal-");
|
||||
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>safe</h1>", "utf8");
|
||||
|
||||
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
|
||||
server = await createTestServer({ cwd: "/test/project", baseDir, staticDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
@@ -731,15 +744,16 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
|
||||
it("includes bootstrap ids in welcome when cwd project and thread already exist", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-bootstrap-existing-");
|
||||
const persistenceLayer = makeSqlitePersistenceLive(path.join(stateDir, "state.sqlite")).pipe(
|
||||
const baseDir = makeTempDir("t3code-state-bootstrap-existing-");
|
||||
const { dbPath } = deriveServerPathsSync(baseDir, undefined);
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath).pipe(
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
const cwd = "/test/bootstrap-existing";
|
||||
|
||||
server = await createTestServer({
|
||||
cwd,
|
||||
stateDir,
|
||||
baseDir,
|
||||
persistenceLayer,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
});
|
||||
@@ -762,7 +776,7 @@ describe("WebSocket Server", () => {
|
||||
|
||||
server = await createTestServer({
|
||||
cwd,
|
||||
stateDir,
|
||||
baseDir,
|
||||
persistenceLayer,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
});
|
||||
@@ -811,11 +825,12 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
|
||||
it("responds to server.getConfig", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-get-config-");
|
||||
const keybindingsPath = path.join(stateDir, "keybindings.json");
|
||||
const baseDir = makeTempDir("t3code-state-get-config-");
|
||||
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
|
||||
ensureParentDir(keybindingsPath);
|
||||
fs.writeFileSync(keybindingsPath, "[]", "utf8");
|
||||
|
||||
server = await createTestServer({ cwd: "/my/workspace", stateDir });
|
||||
server = await createTestServer({ cwd: "/my/workspace", baseDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
@@ -836,11 +851,11 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
|
||||
it("bootstraps default keybindings file when missing", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-bootstrap-keybindings-");
|
||||
const keybindingsPath = path.join(stateDir, "keybindings.json");
|
||||
const baseDir = makeTempDir("t3code-state-bootstrap-keybindings-");
|
||||
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
|
||||
expect(fs.existsSync(keybindingsPath)).toBe(false);
|
||||
|
||||
server = await createTestServer({ cwd: "/my/workspace", stateDir });
|
||||
server = await createTestServer({ cwd: "/my/workspace", baseDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
@@ -866,11 +881,12 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
|
||||
it("falls back to defaults and reports malformed keybindings config issues", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-malformed-keybindings-");
|
||||
const keybindingsPath = path.join(stateDir, "keybindings.json");
|
||||
const baseDir = makeTempDir("t3code-state-malformed-keybindings-");
|
||||
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
|
||||
ensureParentDir(keybindingsPath);
|
||||
fs.writeFileSync(keybindingsPath, "{ not-json", "utf8");
|
||||
|
||||
server = await createTestServer({ cwd: "/my/workspace", stateDir });
|
||||
server = await createTestServer({ cwd: "/my/workspace", baseDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
@@ -897,8 +913,9 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
|
||||
it("ignores invalid keybinding entries but keeps valid entries and reports issues", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-partial-invalid-keybindings-");
|
||||
const keybindingsPath = path.join(stateDir, "keybindings.json");
|
||||
const baseDir = makeTempDir("t3code-state-partial-invalid-keybindings-");
|
||||
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
|
||||
ensureParentDir(keybindingsPath);
|
||||
fs.writeFileSync(
|
||||
keybindingsPath,
|
||||
JSON.stringify([
|
||||
@@ -909,7 +926,7 @@ describe("WebSocket Server", () => {
|
||||
"utf8",
|
||||
);
|
||||
|
||||
server = await createTestServer({ cwd: "/my/workspace", stateDir });
|
||||
server = await createTestServer({ cwd: "/my/workspace", baseDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
@@ -948,11 +965,12 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
|
||||
it("pushes server.configUpdated issues when keybindings file changes", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-keybindings-watch-");
|
||||
const keybindingsPath = path.join(stateDir, "keybindings.json");
|
||||
const baseDir = makeTempDir("t3code-state-keybindings-watch-");
|
||||
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
|
||||
ensureParentDir(keybindingsPath);
|
||||
fs.writeFileSync(keybindingsPath, "[]", "utf8");
|
||||
|
||||
server = await createTestServer({ cwd: "/my/workspace", stateDir });
|
||||
server = await createTestServer({ cwd: "/my/workspace", baseDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
@@ -1008,8 +1026,9 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
|
||||
it("reads keybindings from the configured state directory", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-keybindings-");
|
||||
const keybindingsPath = path.join(stateDir, "keybindings.json");
|
||||
const baseDir = makeTempDir("t3code-state-keybindings-");
|
||||
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
|
||||
ensureParentDir(keybindingsPath);
|
||||
fs.writeFileSync(
|
||||
keybindingsPath,
|
||||
JSON.stringify([
|
||||
@@ -1019,7 +1038,7 @@ describe("WebSocket Server", () => {
|
||||
]),
|
||||
"utf8",
|
||||
);
|
||||
server = await createTestServer({ cwd: "/my/workspace", stateDir });
|
||||
server = await createTestServer({ cwd: "/my/workspace", baseDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
@@ -1043,15 +1062,16 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
|
||||
it("upserts keybinding rules and updates cached server config", async () => {
|
||||
const stateDir = makeTempDir("t3code-state-upsert-keybinding-");
|
||||
const keybindingsPath = path.join(stateDir, "keybindings.json");
|
||||
const baseDir = makeTempDir("t3code-state-upsert-keybinding-");
|
||||
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
|
||||
ensureParentDir(keybindingsPath);
|
||||
fs.writeFileSync(
|
||||
keybindingsPath,
|
||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
server = await createTestServer({ cwd: "/my/workspace", stateDir });
|
||||
server = await createTestServer({ cwd: "/my/workspace", baseDir });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
@@ -1621,6 +1641,49 @@ describe("WebSocket Server", () => {
|
||||
expect(fs.existsSync(path.join(workspace, "..", "escape.md"))).toBe(false);
|
||||
});
|
||||
|
||||
it("supports projects.createDirectory within the workspace root", async () => {
|
||||
const workspace = makeTempDir("t3code-ws-create-directory-");
|
||||
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const [ws] = await connectAndAwaitWelcome(port);
|
||||
connections.push(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.projectsCreateDirectory, {
|
||||
cwd: workspace,
|
||||
relativePath: "sandboxes/fresh-room",
|
||||
});
|
||||
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
relativePath: "sandboxes/fresh-room",
|
||||
absolutePath: path.join(workspace, "sandboxes", "fresh-room"),
|
||||
});
|
||||
expect(fs.existsSync(path.join(workspace, "sandboxes", "fresh-room"))).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects projects.createDirectory when the target already exists", async () => {
|
||||
const workspace = makeTempDir("t3code-ws-create-directory-existing-");
|
||||
fs.mkdirSync(path.join(workspace, "existing"), { recursive: true });
|
||||
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const [ws] = await connectAndAwaitWelcome(port);
|
||||
connections.push(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.projectsCreateDirectory, {
|
||||
cwd: workspace,
|
||||
relativePath: "existing",
|
||||
});
|
||||
|
||||
expect(response.result).toBeUndefined();
|
||||
expect(response.error?.message).toContain("Workspace directory already exists");
|
||||
});
|
||||
|
||||
it("routes git core methods over websocket", async () => {
|
||||
const listBranches = vi.fn(() =>
|
||||
Effect.succeed({
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
FileSystem,
|
||||
Layer,
|
||||
Path,
|
||||
PlatformError,
|
||||
Ref,
|
||||
Result,
|
||||
Schema,
|
||||
@@ -370,7 +371,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
};
|
||||
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
stateDir: serverConfig.stateDir,
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment: persistedAttachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
@@ -440,11 +441,11 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
|
||||
const filePath = isIdLookup
|
||||
? resolveAttachmentPathById({
|
||||
stateDir: serverConfig.stateDir,
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachmentId: normalizedRelativePath,
|
||||
})
|
||||
: resolveAttachmentRelativePath({
|
||||
stateDir: serverConfig.stateDir,
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
relativePath: normalizedRelativePath,
|
||||
});
|
||||
if (!filePath) {
|
||||
@@ -776,6 +777,58 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
return { relativePath: target.relativePath };
|
||||
}
|
||||
|
||||
case WS_METHODS.projectsCreateDirectory: {
|
||||
const body = stripRequestTag(request.body);
|
||||
const target = yield* resolveWorkspaceWritePath({
|
||||
workspaceRoot: body.cwd,
|
||||
relativePath: body.relativePath,
|
||||
path,
|
||||
});
|
||||
|
||||
const existingEntry = yield* Effect.result(fileSystem.stat(target.absolutePath));
|
||||
if (Result.isSuccess(existingEntry)) {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Workspace directory already exists: ${target.relativePath}`,
|
||||
});
|
||||
}
|
||||
if (
|
||||
!(
|
||||
existingEntry.failure instanceof PlatformError.PlatformError &&
|
||||
existingEntry.failure.reason instanceof PlatformError.SystemError &&
|
||||
existingEntry.failure.reason._tag === "NotFound"
|
||||
)
|
||||
) {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Failed to inspect workspace directory: ${String(existingEntry.failure)}`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem
|
||||
.makeDirectory(path.dirname(target.absolutePath), { recursive: true })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to prepare workspace directory path: ${String(cause)}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* fileSystem.makeDirectory(target.absolutePath, { recursive: false }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to create workspace directory: ${String(cause)}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
relativePath: target.relativePath,
|
||||
absolutePath: target.absolutePath,
|
||||
};
|
||||
}
|
||||
|
||||
case WS_METHODS.shellOpenInEditor: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* openInEditor(body);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.10",
|
||||
"version": "0.0.13",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -51,7 +51,7 @@
|
||||
"@vitejs/plugin-react": "^6.0.0",
|
||||
"@vitest/browser-playwright": "^4.0.18",
|
||||
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
||||
"msw": "^2.12.10",
|
||||
"msw": "2.12.11",
|
||||
"playwright": "^1.58.2",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "catalog:",
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* - Please do NOT modify this file.
|
||||
*/
|
||||
|
||||
const PACKAGE_VERSION = '2.12.9'
|
||||
const PACKAGE_VERSION = '2.12.11'
|
||||
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
|
||||
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
|
||||
const activeClientIds = new Set()
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import { Schema } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AppSettingsSchema,
|
||||
DEFAULT_TIMESTAMP_FORMAT,
|
||||
getAppModelOptions,
|
||||
getCustomModelOptionsByProvider,
|
||||
getCustomModelsByProvider,
|
||||
getCustomModelsForProvider,
|
||||
getDefaultCustomModelsForProvider,
|
||||
MODEL_PROVIDER_SETTINGS,
|
||||
normalizeCustomModelSlugs,
|
||||
patchCustomModels,
|
||||
resolveAppModelSelection,
|
||||
} from "./appSettings";
|
||||
|
||||
@@ -22,8 +30,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 +43,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 +62,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,
|
||||
@@ -63,13 +72,35 @@ describe("getAppModelOptions", () => {
|
||||
|
||||
describe("resolveAppModelSelection", () => {
|
||||
it("preserves saved custom model slugs instead of falling back to the default", () => {
|
||||
expect(resolveAppModelSelection("codex", ["galapagos-alpha"], "galapagos-alpha")).toBe(
|
||||
"galapagos-alpha",
|
||||
);
|
||||
expect(
|
||||
resolveAppModelSelection(
|
||||
"codex",
|
||||
{ codex: ["galapagos-alpha"], claudeAgent: [] },
|
||||
"galapagos-alpha",
|
||||
),
|
||||
).toBe("galapagos-alpha");
|
||||
});
|
||||
|
||||
it("falls back to the provider default when no model is selected", () => {
|
||||
expect(resolveAppModelSelection("codex", [], "")).toBe("gpt-5.4");
|
||||
expect(resolveAppModelSelection("codex", { codex: [], claudeAgent: [] }, "")).toBe("gpt-5.4");
|
||||
});
|
||||
|
||||
it("resolves display names through the shared resolver", () => {
|
||||
expect(resolveAppModelSelection("codex", { codex: [], claudeAgent: [] }, "GPT-5.3 Codex")).toBe(
|
||||
"gpt-5.3-codex",
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves aliases through the shared resolver", () => {
|
||||
expect(resolveAppModelSelection("claudeAgent", { codex: [], claudeAgent: [] }, "sonnet")).toBe(
|
||||
"claude-sonnet-4-6",
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves transient selected custom models included in app model options", () => {
|
||||
expect(
|
||||
resolveAppModelSelection("codex", { codex: [], claudeAgent: [] }, "custom/selected-model"),
|
||||
).toBe("custom/selected-model");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -81,8 +112,112 @@ 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("provider-indexed custom model settings", () => {
|
||||
const settings = {
|
||||
customCodexModels: ["custom/codex-model"],
|
||||
customClaudeModels: ["claude/custom-opus"],
|
||||
} as const;
|
||||
|
||||
it("exports one provider config per provider", () => {
|
||||
expect(MODEL_PROVIDER_SETTINGS.map((config) => config.provider)).toEqual([
|
||||
"codex",
|
||||
"claudeAgent",
|
||||
]);
|
||||
});
|
||||
|
||||
it("reads custom models for each provider", () => {
|
||||
expect(getCustomModelsForProvider(settings, "codex")).toEqual(["custom/codex-model"]);
|
||||
expect(getCustomModelsForProvider(settings, "claudeAgent")).toEqual(["claude/custom-opus"]);
|
||||
});
|
||||
|
||||
it("reads default custom models for each provider", () => {
|
||||
const defaults = {
|
||||
customCodexModels: ["default/codex-model"],
|
||||
customClaudeModels: ["claude/default-opus"],
|
||||
} as const;
|
||||
|
||||
expect(getDefaultCustomModelsForProvider(defaults, "codex")).toEqual(["default/codex-model"]);
|
||||
expect(getDefaultCustomModelsForProvider(defaults, "claudeAgent")).toEqual([
|
||||
"claude/default-opus",
|
||||
]);
|
||||
});
|
||||
|
||||
it("patches custom models for codex", () => {
|
||||
expect(patchCustomModels("codex", ["custom/codex-model"])).toEqual({
|
||||
customCodexModels: ["custom/codex-model"],
|
||||
});
|
||||
});
|
||||
|
||||
it("patches custom models for claude", () => {
|
||||
expect(patchCustomModels("claudeAgent", ["claude/custom-opus"])).toEqual({
|
||||
customClaudeModels: ["claude/custom-opus"],
|
||||
});
|
||||
});
|
||||
|
||||
it("builds a complete provider-indexed custom model record", () => {
|
||||
expect(getCustomModelsByProvider(settings)).toEqual({
|
||||
codex: ["custom/codex-model"],
|
||||
claudeAgent: ["claude/custom-opus"],
|
||||
});
|
||||
});
|
||||
|
||||
it("builds provider-indexed model options including custom models", () => {
|
||||
const modelOptionsByProvider = getCustomModelOptionsByProvider(settings);
|
||||
|
||||
expect(
|
||||
modelOptionsByProvider.codex.some((option) => option.slug === "custom/codex-model"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
modelOptionsByProvider.claudeAgent.some((option) => option.slug === "claude/custom-opus"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("normalizes and deduplicates custom model options per provider", () => {
|
||||
const modelOptionsByProvider = getCustomModelOptionsByProvider({
|
||||
customCodexModels: [" custom/codex-model ", "gpt-5.4", "custom/codex-model"],
|
||||
customClaudeModels: [" sonnet ", "claude/custom-opus", "claude/custom-opus"],
|
||||
});
|
||||
|
||||
expect(
|
||||
modelOptionsByProvider.codex.filter((option) => option.slug === "custom/codex-model"),
|
||||
).toHaveLength(1);
|
||||
expect(modelOptionsByProvider.codex.some((option) => option.slug === "gpt-5.4")).toBe(true);
|
||||
expect(
|
||||
modelOptionsByProvider.claudeAgent.filter((option) => option.slug === "claude/custom-opus"),
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
modelOptionsByProvider.claudeAgent.some((option) => option.slug === "claude-sonnet-4-6"),
|
||||
).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: "",
|
||||
newProjectBasePath: "",
|
||||
defaultThreadEnvMode: "local",
|
||||
confirmThreadDelete: false,
|
||||
enableAssistantStreaming: false,
|
||||
timestampFormat: DEFAULT_TIMESTAMP_FORMAT,
|
||||
customCodexModels: [],
|
||||
customClaudeModels: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
+126
-57
@@ -1,43 +1,62 @@
|
||||
import { useCallback } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { type ProviderKind } from "@t3tools/contracts";
|
||||
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { TrimmedNonEmptyString, type ProviderKind } from "@t3tools/contracts";
|
||||
import {
|
||||
getDefaultModel,
|
||||
getModelOptions,
|
||||
normalizeModelSlug,
|
||||
resolveSelectableModel,
|
||||
} 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)),
|
||||
type CustomModelSettingsKey = "customCodexModels" | "customClaudeModels";
|
||||
export type ProviderCustomModelConfig = {
|
||||
provider: ProviderKind;
|
||||
settingsKey: CustomModelSettingsKey;
|
||||
defaultSettingsKey: CustomModelSettingsKey;
|
||||
title: string;
|
||||
description: string;
|
||||
placeholder: string;
|
||||
example: string;
|
||||
};
|
||||
|
||||
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 BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
|
||||
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
|
||||
claudeAgent: new Set(getModelOptions("claudeAgent").map((option) => option.slug)),
|
||||
};
|
||||
|
||||
const 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(() => "")),
|
||||
newProjectBasePath: 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 {
|
||||
@@ -47,6 +66,27 @@ export interface AppModelOption {
|
||||
}
|
||||
|
||||
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
|
||||
const PROVIDER_CUSTOM_MODEL_CONFIG: Record<ProviderKind, ProviderCustomModelConfig> = {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
settingsKey: "customCodexModels",
|
||||
defaultSettingsKey: "customCodexModels",
|
||||
title: "Codex",
|
||||
description: "Save additional Codex model slugs for the picker and `/model` command.",
|
||||
placeholder: "your-codex-model-slug",
|
||||
example: "gpt-6.7-codex-ultra-preview",
|
||||
},
|
||||
claudeAgent: {
|
||||
provider: "claudeAgent",
|
||||
settingsKey: "customClaudeModels",
|
||||
defaultSettingsKey: "customClaudeModels",
|
||||
title: "Claude",
|
||||
description: "Save additional Claude model slugs for the picker and `/model` command.",
|
||||
placeholder: "your-claude-model-slug",
|
||||
example: "claude-sonnet-5-0",
|
||||
},
|
||||
};
|
||||
export const MODEL_PROVIDER_SETTINGS = Object.values(PROVIDER_CUSTOM_MODEL_CONFIG);
|
||||
|
||||
export function normalizeCustomModelSlugs(
|
||||
models: Iterable<string | null | undefined>,
|
||||
@@ -81,9 +121,42 @@ function normalizeAppSettings(settings: AppSettings): AppSettings {
|
||||
return {
|
||||
...settings,
|
||||
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
|
||||
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeCode"),
|
||||
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeAgent"),
|
||||
};
|
||||
}
|
||||
|
||||
export function getCustomModelsForProvider(
|
||||
settings: Pick<AppSettings, CustomModelSettingsKey>,
|
||||
provider: ProviderKind,
|
||||
): readonly string[] {
|
||||
return settings[PROVIDER_CUSTOM_MODEL_CONFIG[provider].settingsKey];
|
||||
}
|
||||
|
||||
export function getDefaultCustomModelsForProvider(
|
||||
defaults: Pick<AppSettings, CustomModelSettingsKey>,
|
||||
provider: ProviderKind,
|
||||
): readonly string[] {
|
||||
return defaults[PROVIDER_CUSTOM_MODEL_CONFIG[provider].defaultSettingsKey];
|
||||
}
|
||||
|
||||
export function patchCustomModels(
|
||||
provider: ProviderKind,
|
||||
models: string[],
|
||||
): Partial<Pick<AppSettings, CustomModelSettingsKey>> {
|
||||
return {
|
||||
[PROVIDER_CUSTOM_MODEL_CONFIG[provider].settingsKey]: models,
|
||||
};
|
||||
}
|
||||
|
||||
export function getCustomModelsByProvider(
|
||||
settings: Pick<AppSettings, CustomModelSettingsKey>,
|
||||
): Record<ProviderKind, readonly string[]> {
|
||||
return {
|
||||
codex: getCustomModelsForProvider(settings, "codex"),
|
||||
claudeAgent: getCustomModelsForProvider(settings, "claudeAgent"),
|
||||
};
|
||||
}
|
||||
|
||||
export function getAppModelOptions(
|
||||
provider: ProviderKind,
|
||||
customModels: readonly string[],
|
||||
@@ -95,6 +168,7 @@ export function getAppModelOptions(
|
||||
isCustom: false,
|
||||
}));
|
||||
const seen = new Set(options.map((option) => option.slug));
|
||||
const trimmedSelectedModel = selectedModel?.trim().toLowerCase();
|
||||
|
||||
for (const slug of normalizeCustomModelSlugs(customModels, provider)) {
|
||||
if (seen.has(slug)) {
|
||||
@@ -110,7 +184,14 @@ export function getAppModelOptions(
|
||||
}
|
||||
|
||||
const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
|
||||
if (normalizedSelectedModel && !seen.has(normalizedSelectedModel)) {
|
||||
const selectedModelMatchesExistingName =
|
||||
typeof trimmedSelectedModel === "string" &&
|
||||
options.some((option) => option.name.toLowerCase() === trimmedSelectedModel);
|
||||
if (
|
||||
normalizedSelectedModel &&
|
||||
!seen.has(normalizedSelectedModel) &&
|
||||
!selectedModelMatchesExistingName
|
||||
) {
|
||||
options.push({
|
||||
slug: normalizedSelectedModel,
|
||||
name: normalizedSelectedModel,
|
||||
@@ -123,34 +204,22 @@ export function getAppModelOptions(
|
||||
|
||||
export function resolveAppModelSelection(
|
||||
provider: ProviderKind,
|
||||
customModels: readonly string[],
|
||||
customModels: Record<ProviderKind, readonly string[]>,
|
||||
selectedModel: string | null | undefined,
|
||||
): string {
|
||||
const options = getAppModelOptions(provider, customModels, selectedModel);
|
||||
const trimmedSelectedModel = selectedModel?.trim();
|
||||
if (trimmedSelectedModel) {
|
||||
const direct = options.find((option) => option.slug === trimmedSelectedModel);
|
||||
if (direct) {
|
||||
return direct.slug;
|
||||
}
|
||||
const customModelsForProvider = customModels[provider];
|
||||
const options = getAppModelOptions(provider, customModelsForProvider, selectedModel);
|
||||
return resolveSelectableModel(provider, selectedModel, options) ?? getDefaultModel(provider);
|
||||
}
|
||||
|
||||
const byName = options.find(
|
||||
(option) => option.name.toLowerCase() === trimmedSelectedModel.toLowerCase(),
|
||||
);
|
||||
if (byName) {
|
||||
return byName.slug;
|
||||
}
|
||||
}
|
||||
|
||||
const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
|
||||
if (!normalizedSelectedModel) {
|
||||
return getDefaultModel(provider);
|
||||
}
|
||||
|
||||
return (
|
||||
options.find((option) => option.slug === normalizedSelectedModel)?.slug ??
|
||||
getDefaultModel(provider)
|
||||
);
|
||||
export function getCustomModelOptionsByProvider(
|
||||
settings: Pick<AppSettings, CustomModelSettingsKey>,
|
||||
): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
|
||||
const customModelsByProvider = getCustomModelsByProvider(settings);
|
||||
return {
|
||||
codex: getAppModelOptions("codex", customModelsByProvider.codex),
|
||||
claudeAgent: getAppModelOptions("claudeAgent", customModelsByProvider.claudeAgent),
|
||||
};
|
||||
}
|
||||
|
||||
export function useAppSettings() {
|
||||
|
||||
@@ -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;
|
||||
@@ -345,6 +368,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 +556,13 @@ async function waitForComposerEditor(): Promise<HTMLElement> {
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForSendButton(): Promise<HTMLButtonElement> {
|
||||
return waitForElement(
|
||||
() => document.querySelector<HTMLButtonElement>('button[aria-label="Send message"]'),
|
||||
"Unable to find send button.",
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForInteractionModeButton(
|
||||
expectedLabel: "Chat" | "Plan",
|
||||
): Promise<HTMLButtonElement> {
|
||||
@@ -720,6 +752,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModel: null,
|
||||
stickyModelOptions: {},
|
||||
});
|
||||
useStore.setState({
|
||||
projects: [],
|
||||
@@ -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,
|
||||
@@ -1087,6 +1281,198 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("snapshots sticky codex settings into a new draft thread", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModel: "gpt-5.3-codex",
|
||||
stickyModelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-sticky-codex-traits-test" as MessageId,
|
||||
targetText: "sticky codex traits test",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
|
||||
await newThreadButton.click();
|
||||
|
||||
const newThreadPath = await waitForURL(
|
||||
mounted.router,
|
||||
(path) => UUID_ROUTE_RE.test(path),
|
||||
"Route should have changed to a new draft thread UUID.",
|
||||
);
|
||||
const newThreadId = newThreadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
|
||||
model: "gpt-5.3-codex",
|
||||
provider: "codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("hydrates the provider alongside a sticky claude model", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModel: "claude-opus-4-6",
|
||||
stickyModelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-sticky-claude-model-test" as MessageId,
|
||||
targetText: "sticky claude model test",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
|
||||
await newThreadButton.click();
|
||||
|
||||
const newThreadPath = await waitForURL(
|
||||
mounted.router,
|
||||
(path) => UUID_ROUTE_RE.test(path),
|
||||
"Route should have changed to a new sticky claude draft thread UUID.",
|
||||
);
|
||||
const newThreadId = newThreadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
await expect.element(page.getByText("Claude Opus 4.6")).toBeInTheDocument();
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to defaults when no sticky composer settings exist", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-default-codex-traits-test" as MessageId,
|
||||
targetText: "default codex traits test",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
|
||||
await newThreadButton.click();
|
||||
|
||||
const newThreadPath = await waitForURL(
|
||||
mounted.router,
|
||||
(path) => UUID_ROUTE_RE.test(path),
|
||||
"Route should have changed to a new draft thread UUID.",
|
||||
);
|
||||
const newThreadId = newThreadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toBeUndefined();
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("prefers draft state over sticky composer settings and defaults", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModel: "gpt-5.3-codex",
|
||||
stickyModelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-draft-codex-traits-precedence-test" as MessageId,
|
||||
targetText: "draft codex traits precedence test",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
|
||||
await newThreadButton.click();
|
||||
|
||||
const threadPath = await waitForURL(
|
||||
mounted.router,
|
||||
(path) => UUID_ROUTE_RE.test(path),
|
||||
"Route should have changed to a sticky draft thread UUID.",
|
||||
);
|
||||
const threadId = threadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
useComposerDraftStore.getState().setModel(threadId, "gpt-5.4");
|
||||
useComposerDraftStore.getState().setModelOptions(threadId, {
|
||||
codex: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
|
||||
await newThreadButton.click();
|
||||
|
||||
await waitForURL(
|
||||
mounted.router,
|
||||
(path) => path === threadPath,
|
||||
"New-thread should reuse the existing project draft thread.",
|
||||
);
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
|
||||
model: "gpt-5.4",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("creates a new thread from the global chat.new shortcut", 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.",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,13 @@
|
||||
import { ProjectId, type ProviderKind, type ThreadId } from "@t3tools/contracts";
|
||||
import { ProjectId, type ThreadId } from "@t3tools/contracts";
|
||||
import { type ChatMessage, type Thread } from "../types";
|
||||
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";
|
||||
@@ -116,12 +120,43 @@ export function cloneComposerImageForRetry(
|
||||
}
|
||||
}
|
||||
|
||||
export function getCustomModelOptionsByProvider(settings: {
|
||||
customCodexModels: readonly string[];
|
||||
customClaudeModels: readonly string[];
|
||||
}): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
|
||||
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 {
|
||||
codex: getAppModelOptions("codex", settings.customCodexModels),
|
||||
claudeCode: getAppModelOptions("claudeCode", settings.customClaudeModels),
|
||||
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
@@ -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 }));
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
hasUnseenCompletion,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
@@ -141,6 +142,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 +158,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({
|
||||
@@ -199,3 +231,53 @@ describe("resolveThreadRowClassName", () => {
|
||||
expect(className).toContain("hover:bg-accent");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveProjectStatusIndicator", () => {
|
||||
it("returns null when no threads have a notable status", () => {
|
||||
expect(resolveProjectStatusIndicator([null, null])).toBeNull();
|
||||
});
|
||||
|
||||
it("surfaces the highest-priority actionable state across project threads", () => {
|
||||
expect(
|
||||
resolveProjectStatusIndicator([
|
||||
{
|
||||
label: "Completed",
|
||||
colorClass: "text-emerald-600",
|
||||
dotClass: "bg-emerald-500",
|
||||
pulse: false,
|
||||
},
|
||||
{
|
||||
label: "Pending Approval",
|
||||
colorClass: "text-amber-600",
|
||||
dotClass: "bg-amber-500",
|
||||
pulse: false,
|
||||
},
|
||||
{
|
||||
label: "Working",
|
||||
colorClass: "text-sky-600",
|
||||
dotClass: "bg-sky-500",
|
||||
pulse: true,
|
||||
},
|
||||
]),
|
||||
).toMatchObject({ label: "Pending Approval", dotClass: "bg-amber-500" });
|
||||
});
|
||||
|
||||
it("prefers plan-ready over completed when no stronger action is needed", () => {
|
||||
expect(
|
||||
resolveProjectStatusIndicator([
|
||||
{
|
||||
label: "Completed",
|
||||
colorClass: "text-emerald-600",
|
||||
dotClass: "bg-emerald-500",
|
||||
pulse: false,
|
||||
},
|
||||
{
|
||||
label: "Plan Ready",
|
||||
colorClass: "text-violet-600",
|
||||
dotClass: "bg-violet-500",
|
||||
pulse: false,
|
||||
},
|
||||
]),
|
||||
).toMatchObject({ label: "Plan Ready", dotClass: "bg-violet-500" });
|
||||
});
|
||||
});
|
||||
@@ -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";
|
||||
@@ -18,6 +22,15 @@ export interface ThreadStatusPill {
|
||||
pulse: boolean;
|
||||
}
|
||||
|
||||
const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
|
||||
"Pending Approval": 5,
|
||||
"Awaiting Input": 4,
|
||||
Working: 3,
|
||||
Connecting: 3,
|
||||
"Plan Ready": 2,
|
||||
Completed: 1,
|
||||
};
|
||||
|
||||
type ThreadStatusInput = Pick<
|
||||
Thread,
|
||||
"interactionMode" | "latestTurn" | "lastVisitedAt" | "proposedPlans" | "session"
|
||||
@@ -51,7 +64,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 +137,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",
|
||||
@@ -145,3 +160,21 @@ export function resolveThreadStatusPill(input: {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveProjectStatusIndicator(
|
||||
statuses: ReadonlyArray<ThreadStatusPill | null>,
|
||||
): ThreadStatusPill | null {
|
||||
let highestPriorityStatus: ThreadStatusPill | null = null;
|
||||
|
||||
for (const status of statuses) {
|
||||
if (status === null) continue;
|
||||
if (
|
||||
highestPriorityStatus === null ||
|
||||
THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
|
||||
) {
|
||||
highestPriorityStatus = status;
|
||||
}
|
||||
}
|
||||
|
||||
return highestPriorityStatus;
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import {
|
||||
ArrowLeftIcon,
|
||||
ChevronRightIcon,
|
||||
FolderIcon,
|
||||
FolderOpenIcon,
|
||||
FolderPlusIcon,
|
||||
GitPullRequestIcon,
|
||||
PlusIcon,
|
||||
RocketIcon,
|
||||
@@ -24,7 +26,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,
|
||||
@@ -39,7 +41,7 @@ import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { isElectron } from "../env";
|
||||
import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
|
||||
import { isMacPlatform, newCommandId, newProjectId } from "../lib/utils";
|
||||
import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../lib/utils";
|
||||
import { useStore } from "../store";
|
||||
import { shortcutLabelForCommand } from "../keybindings";
|
||||
import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic";
|
||||
@@ -64,6 +66,17 @@ import {
|
||||
import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
|
||||
import { Button } from "./ui/button";
|
||||
import { Collapsible, CollapsibleContent } from "./ui/collapsible";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "./ui/dialog";
|
||||
import { Input } from "./ui/input";
|
||||
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import {
|
||||
SidebarContent,
|
||||
@@ -84,6 +97,7 @@ import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
import { isNonEmpty as isNonEmptyString } from "effect/String";
|
||||
import {
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
@@ -271,7 +285,7 @@ export default function Sidebar() {
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
const isOnSettings = useLocation({ select: (loc) => loc.pathname === "/settings" });
|
||||
const { settings: appSettings } = useAppSettings();
|
||||
const { settings: appSettings, updateSettings } = useAppSettings();
|
||||
const { handleNewThread } = useHandleNewThread();
|
||||
const routeThreadId = useParams({
|
||||
strict: false,
|
||||
@@ -284,11 +298,22 @@ export default function Sidebar() {
|
||||
const queryClient = useQueryClient();
|
||||
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
|
||||
const [addingProject, setAddingProject] = useState(false);
|
||||
const [isAddProjectMenuOpen, setIsAddProjectMenuOpen] = useState(false);
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||
const [isAddingProject, setIsAddingProject] = useState(false);
|
||||
const [addProjectError, setAddProjectError] = useState<string | null>(null);
|
||||
const addProjectInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const addProjectMenuCloseTimerRef = useRef<number | null>(null);
|
||||
const [isCreateProjectDialogOpen, setIsCreateProjectDialogOpen] = useState(false);
|
||||
const [createProjectDirectoryPath, setCreateProjectDirectoryPath] = useState("");
|
||||
const [newProjectDirectoryName, setNewProjectDirectoryName] = useState("");
|
||||
const [isCreatingProjectDirectory, setIsCreatingProjectDirectory] = useState(false);
|
||||
const [isPickingCreateProjectDirectoryPath, setIsPickingCreateProjectDirectoryPath] =
|
||||
useState(false);
|
||||
const [createProjectDirectoryError, setCreateProjectDirectoryError] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
|
||||
const [renamingTitle, setRenamingTitle] = useState("");
|
||||
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
|
||||
@@ -305,7 +330,8 @@ export default function Sidebar() {
|
||||
const clearSelection = useThreadSelectionStore((s) => s.clearSelection);
|
||||
const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection);
|
||||
const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);
|
||||
const shouldBrowseForProjectImmediately = isElectron;
|
||||
const isLinuxDesktop = isElectron && isLinuxPlatform(navigator.platform);
|
||||
const shouldBrowseForProjectImmediately = isElectron && !isLinuxDesktop;
|
||||
const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately;
|
||||
const projectCwdById = useMemo(
|
||||
() => new Map(projects.map((project) => [project.id, project.cwd] as const)),
|
||||
@@ -401,11 +427,11 @@ export default function Sidebar() {
|
||||
);
|
||||
|
||||
const addProjectFromPath = useCallback(
|
||||
async (rawCwd: string) => {
|
||||
async (rawCwd: string): Promise<{ ok: boolean; error?: string }> => {
|
||||
const cwd = rawCwd.trim();
|
||||
if (!cwd || isAddingProject) return;
|
||||
if (!cwd || isAddingProject) return { ok: false };
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
if (!api) return { ok: false, error: "Native API not available." };
|
||||
|
||||
setIsAddingProject(true);
|
||||
const finishAddingProject = () => {
|
||||
@@ -419,7 +445,7 @@ export default function Sidebar() {
|
||||
if (existing) {
|
||||
focusMostRecentThreadForProject(existing.id);
|
||||
finishAddingProject();
|
||||
return;
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
const projectId = newProjectId();
|
||||
@@ -451,9 +477,10 @@ export default function Sidebar() {
|
||||
} else {
|
||||
setAddProjectError(description);
|
||||
}
|
||||
return;
|
||||
return { ok: false, error: description };
|
||||
}
|
||||
finishAddingProject();
|
||||
return { ok: true };
|
||||
},
|
||||
[
|
||||
focusMostRecentThreadForProject,
|
||||
@@ -470,6 +497,26 @@ export default function Sidebar() {
|
||||
};
|
||||
|
||||
const canAddProject = newCwd.trim().length > 0 && !isAddingProject;
|
||||
const newProjectBasePath = appSettings.newProjectBasePath.trim();
|
||||
|
||||
const cancelAddProjectMenuClose = useCallback(() => {
|
||||
if (addProjectMenuCloseTimerRef.current === null) return;
|
||||
window.clearTimeout(addProjectMenuCloseTimerRef.current);
|
||||
addProjectMenuCloseTimerRef.current = null;
|
||||
}, []);
|
||||
|
||||
const openAddProjectMenu = useCallback(() => {
|
||||
cancelAddProjectMenuClose();
|
||||
setIsAddProjectMenuOpen(true);
|
||||
}, [cancelAddProjectMenuClose]);
|
||||
|
||||
const scheduleAddProjectMenuClose = useCallback(() => {
|
||||
cancelAddProjectMenuClose();
|
||||
addProjectMenuCloseTimerRef.current = window.setTimeout(() => {
|
||||
setIsAddProjectMenuOpen(false);
|
||||
addProjectMenuCloseTimerRef.current = null;
|
||||
}, 120);
|
||||
}, [cancelAddProjectMenuClose]);
|
||||
|
||||
const handlePickFolder = async () => {
|
||||
const api = readNativeApi();
|
||||
@@ -490,6 +537,7 @@ export default function Sidebar() {
|
||||
};
|
||||
|
||||
const handleStartAddProject = () => {
|
||||
setIsAddProjectMenuOpen(false);
|
||||
setAddProjectError(null);
|
||||
if (shouldBrowseForProjectImmediately) {
|
||||
void handlePickFolder();
|
||||
@@ -498,6 +546,110 @@ export default function Sidebar() {
|
||||
setAddingProject((prev) => !prev);
|
||||
};
|
||||
|
||||
const closeCreateProjectDialog = useCallback((open: boolean) => {
|
||||
setIsCreateProjectDialogOpen(open);
|
||||
if (!open) {
|
||||
setCreateProjectDirectoryPath("");
|
||||
setNewProjectDirectoryName("");
|
||||
setCreateProjectDirectoryError(null);
|
||||
setIsCreatingProjectDirectory(false);
|
||||
setIsPickingCreateProjectDirectoryPath(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleStartCreateProjectDirectory = useCallback(() => {
|
||||
setIsAddProjectMenuOpen(false);
|
||||
setAddProjectError(null);
|
||||
setCreateProjectDirectoryPath(newProjectBasePath);
|
||||
setNewProjectDirectoryName("");
|
||||
setCreateProjectDirectoryError(null);
|
||||
setIsCreateProjectDialogOpen(true);
|
||||
|
||||
if (newProjectBasePath) {
|
||||
return;
|
||||
}
|
||||
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
return;
|
||||
}
|
||||
|
||||
void api.dialogs.getDocumentsPath().then((documentsPath) => {
|
||||
if (!documentsPath) return;
|
||||
setCreateProjectDirectoryPath((current) =>
|
||||
current.trim().length > 0 ? current : documentsPath,
|
||||
);
|
||||
});
|
||||
}, [newProjectBasePath]);
|
||||
|
||||
const handlePickCreateProjectDirectoryPath = useCallback(async () => {
|
||||
const api = readNativeApi();
|
||||
if (!api || isPickingCreateProjectDirectoryPath) return;
|
||||
|
||||
setIsPickingCreateProjectDirectoryPath(true);
|
||||
try {
|
||||
const pickedPath = await api.dialogs.pickFolder();
|
||||
if (pickedPath) {
|
||||
setCreateProjectDirectoryPath(pickedPath);
|
||||
setCreateProjectDirectoryError(null);
|
||||
}
|
||||
} finally {
|
||||
setIsPickingCreateProjectDirectoryPath(false);
|
||||
}
|
||||
}, [isPickingCreateProjectDirectoryPath]);
|
||||
|
||||
const handleCreateProjectDirectory = useCallback(async () => {
|
||||
const basePath = createProjectDirectoryPath.trim();
|
||||
const relativePath = newProjectDirectoryName.trim();
|
||||
if (!basePath || !relativePath || isCreatingProjectDirectory || isAddingProject) {
|
||||
if (!basePath) {
|
||||
setCreateProjectDirectoryError("Enter a directory path.");
|
||||
}
|
||||
if (!relativePath) {
|
||||
setCreateProjectDirectoryError("Enter a directory name.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
|
||||
setIsCreatingProjectDirectory(true);
|
||||
setCreateProjectDirectoryError(null);
|
||||
|
||||
try {
|
||||
const result = await api.projects.createDirectory({
|
||||
cwd: basePath,
|
||||
relativePath,
|
||||
});
|
||||
const addedProject = await addProjectFromPath(result.absolutePath);
|
||||
if (!addedProject.ok) {
|
||||
setCreateProjectDirectoryError(addedProject.error ?? "Unable to open the new project.");
|
||||
setIsCreatingProjectDirectory(false);
|
||||
return;
|
||||
}
|
||||
closeCreateProjectDialog(false);
|
||||
} catch (error) {
|
||||
setCreateProjectDirectoryError(
|
||||
error instanceof Error ? error.message : "Unable to create the directory.",
|
||||
);
|
||||
setIsCreatingProjectDirectory(false);
|
||||
}
|
||||
}, [
|
||||
addProjectFromPath,
|
||||
closeCreateProjectDialog,
|
||||
createProjectDirectoryPath,
|
||||
isAddingProject,
|
||||
isCreatingProjectDirectory,
|
||||
newProjectDirectoryName,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
cancelAddProjectMenuClose();
|
||||
};
|
||||
}, [cancelAddProjectMenuClose]);
|
||||
|
||||
const cancelRename = useCallback(() => {
|
||||
setRenamingThreadId(null);
|
||||
renamingInputRef.current = null;
|
||||
@@ -561,7 +713,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 +816,7 @@ export default function Sidebar() {
|
||||
],
|
||||
);
|
||||
|
||||
const { copyToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
|
||||
const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
|
||||
onCopy: (ctx) => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
@@ -681,21 +832,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 +878,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 +908,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(
|
||||
@@ -1192,26 +1382,59 @@ export default function Sidebar() {
|
||||
<span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/60">
|
||||
Projects
|
||||
</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Add project"
|
||||
aria-pressed={shouldShowProjectPathEntry}
|
||||
className="inline-flex size-5 items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"
|
||||
onClick={handleStartAddProject}
|
||||
<div onMouseEnter={openAddProjectMenu} onMouseLeave={scheduleAddProjectMenuClose}>
|
||||
<Menu open={isAddProjectMenuOpen} onOpenChange={setIsAddProjectMenuOpen}>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Add project"
|
||||
aria-expanded={isAddProjectMenuOpen}
|
||||
className="inline-flex size-5 cursor-pointer items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"
|
||||
onClick={() => setIsAddProjectMenuOpen((open) => !open)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<PlusIcon
|
||||
className={`size-3.5 transition-transform duration-150 ${
|
||||
isAddProjectMenuOpen || shouldShowProjectPathEntry ? "rotate-90" : "rotate-0"
|
||||
}`}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<PlusIcon
|
||||
className={`size-3.5 transition-transform duration-150 ${
|
||||
shouldShowProjectPathEntry ? "rotate-45" : "rotate-0"
|
||||
}`}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="right">Add project</TooltipPopup>
|
||||
</Tooltip>
|
||||
</MenuTrigger>
|
||||
<MenuPopup
|
||||
align="end"
|
||||
className="w-64"
|
||||
onMouseEnter={openAddProjectMenu}
|
||||
onMouseLeave={scheduleAddProjectMenuClose}
|
||||
>
|
||||
<MenuItem className="items-start py-2.5" onClick={handleStartAddProject}>
|
||||
<FolderOpenIcon className="mt-0.5 size-4" />
|
||||
<span className="flex flex-col gap-0.5">
|
||||
<span className="text-sm font-medium text-foreground">
|
||||
Open existing directory
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Add a project from a folder you already have.
|
||||
</span>
|
||||
</span>
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
className="items-start py-2.5"
|
||||
onClick={handleStartCreateProjectDirectory}
|
||||
>
|
||||
<FolderPlusIcon className="mt-0.5 size-4" />
|
||||
<span className="flex flex-col gap-0.5">
|
||||
<span className="text-sm font-medium text-foreground">
|
||||
Create new empty directory
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Make a fresh folder inside your default project path.
|
||||
</span>
|
||||
</span>
|
||||
</MenuItem>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{shouldShowProjectPathEntry && (
|
||||
@@ -1282,7 +1505,7 @@ export default function Sidebar() {
|
||||
<DndContext
|
||||
sensors={projectDnDSensors}
|
||||
collisionDetection={projectCollisionDetection}
|
||||
modifiers={[restrictToVerticalAxis, restrictToParentElement]}
|
||||
modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]}
|
||||
onDragStart={handleProjectDragStart}
|
||||
onDragEnd={handleProjectDragEnd}
|
||||
onDragCancel={handleProjectDragCancel}
|
||||
@@ -1301,13 +1524,22 @@ export default function Sidebar() {
|
||||
if (byDate !== 0) return byDate;
|
||||
return b.id.localeCompare(a.id);
|
||||
});
|
||||
const projectStatus = resolveProjectStatusIndicator(
|
||||
projectThreads.map((thread) =>
|
||||
resolveThreadStatusPill({
|
||||
thread,
|
||||
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
|
||||
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const isThreadListExpanded = expandedThreadListsByProject.has(project.id);
|
||||
const hasHiddenThreads = projectThreads.length > THREAD_PREVIEW_LIMIT;
|
||||
const visibleThreads =
|
||||
hasHiddenThreads && !isThreadListExpanded
|
||||
? projectThreads.slice(0, THREAD_PREVIEW_LIMIT)
|
||||
: projectThreads;
|
||||
const orderedProjectThreadIds = projectThreads.map((t) => t.id);
|
||||
const orderedProjectThreadIds = projectThreads.map((thread) => thread.id);
|
||||
|
||||
return (
|
||||
<SortableProjectItem key={project.id} projectId={project.id}>
|
||||
@@ -1330,11 +1562,28 @@ export default function Sidebar() {
|
||||
});
|
||||
}}
|
||||
>
|
||||
<ChevronRightIcon
|
||||
className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${
|
||||
project.expanded ? "rotate-90" : ""
|
||||
}`}
|
||||
/>
|
||||
{!project.expanded && projectStatus ? (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
title={projectStatus.label}
|
||||
className={`-ml-0.5 relative inline-flex size-3.5 shrink-0 items-center justify-center ${projectStatus.colorClass}`}
|
||||
>
|
||||
<span className="absolute inset-0 flex items-center justify-center transition-opacity duration-150 group-hover/project-header:opacity-0">
|
||||
<span
|
||||
className={`size-[9px] rounded-full ${projectStatus.dotClass} ${
|
||||
projectStatus.pulse ? "animate-pulse" : ""
|
||||
}`}
|
||||
/>
|
||||
</span>
|
||||
<ChevronRightIcon className="absolute inset-0 m-auto size-3.5 text-muted-foreground/70 opacity-0 transition-opacity duration-150 group-hover/project-header:opacity-100" />
|
||||
</span>
|
||||
) : (
|
||||
<ChevronRightIcon
|
||||
className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${
|
||||
project.expanded ? "rotate-90" : ""
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
<ProjectFavicon cwd={project.cwd} />
|
||||
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
|
||||
{project.name}
|
||||
@@ -1634,6 +1883,102 @@ export default function Sidebar() {
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarFooter>
|
||||
<Dialog open={isCreateProjectDialogOpen} onOpenChange={closeCreateProjectDialog}>
|
||||
<DialogPopup>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create new empty directory</DialogTitle>
|
||||
<DialogDescription>
|
||||
Choose where the new folder should live, then name the project and T3 Code will open
|
||||
it right away.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="space-y-5 pt-0" scrollFade={false}>
|
||||
<div className="space-y-2">
|
||||
<span className="text-xs font-medium text-foreground">Directory path</span>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={createProjectDirectoryPath}
|
||||
onChange={(event) => {
|
||||
setCreateProjectDirectoryPath(event.target.value);
|
||||
if (createProjectDirectoryError) {
|
||||
setCreateProjectDirectoryError(null);
|
||||
}
|
||||
}}
|
||||
placeholder="/Users/you/Documents"
|
||||
spellCheck={false}
|
||||
autoFocus
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => void handlePickCreateProjectDirectoryPath()}
|
||||
disabled={isPickingCreateProjectDirectoryPath}
|
||||
>
|
||||
{isPickingCreateProjectDirectoryPath ? "Selecting..." : "Select"}
|
||||
</Button>
|
||||
</div>
|
||||
{!newProjectBasePath && createProjectDirectoryPath.trim() ? (
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
newProjectBasePath: createProjectDirectoryPath.trim(),
|
||||
})
|
||||
}
|
||||
>
|
||||
Set as default
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<label htmlFor="new-project-directory-name" className="block space-y-2">
|
||||
<span className="text-xs font-medium text-foreground">Project name</span>
|
||||
<Input
|
||||
id="new-project-directory-name"
|
||||
value={newProjectDirectoryName}
|
||||
onChange={(event) => {
|
||||
setNewProjectDirectoryName(event.target.value);
|
||||
if (createProjectDirectoryError) {
|
||||
setCreateProjectDirectoryError(null);
|
||||
}
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter") return;
|
||||
event.preventDefault();
|
||||
void handleCreateProjectDirectory();
|
||||
}}
|
||||
placeholder="my-new-project"
|
||||
spellCheck={false}
|
||||
/>
|
||||
</label>
|
||||
|
||||
{createProjectDirectoryError ? (
|
||||
<p className="text-xs text-destructive">{createProjectDirectoryError}</p>
|
||||
) : null}
|
||||
</DialogPanel>
|
||||
<DialogFooter variant="bare" className="pt-0">
|
||||
<Button type="button" variant="outline" onClick={() => closeCreateProjectDialog(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => void handleCreateProjectDirectory()}
|
||||
disabled={
|
||||
!createProjectDirectoryPath.trim() ||
|
||||
!newProjectDirectoryName.trim() ||
|
||||
isCreatingProjectDirectory ||
|
||||
isAddingProject
|
||||
}
|
||||
>
|
||||
{isCreatingProjectDirectory || isAddingProject ? "Creating..." : "OK"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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,197 @@
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
it("persists sticky claude model options when traits change", async () => {
|
||||
const mounted = await mountPicker({
|
||||
model: "claude-opus-4-6",
|
||||
effort: "medium",
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitemradio", { name: "Max" }).click();
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toMatchObject({
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,272 @@
|
||||
import {
|
||||
ProviderKind,
|
||||
type ClaudeCodeEffort,
|
||||
type ClaudeModelOptions,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getDefaultReasoningEffort,
|
||||
getReasoningEffortOptions,
|
||||
normalizeClaudeModelOptions,
|
||||
resolveReasoningEffortForProvider,
|
||||
supportsClaudeFastMode,
|
||||
supportsClaudeThinkingToggle,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
isClaudeUltrathinkPrompt,
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, 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 PROVIDER = "claudeAgent" as const satisfies ProviderKind;
|
||||
|
||||
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(PROVIDER, model);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER) as Exclude<
|
||||
ClaudeCodeEffort,
|
||||
"ultrathink"
|
||||
>;
|
||||
const resolvedEffort = resolveReasoningEffortForProvider(PROVIDER, 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,
|
||||
};
|
||||
}
|
||||
|
||||
interface ClaudeTraitsMenuContentProps {
|
||||
threadId: ThreadId;
|
||||
model: string | null | undefined;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}
|
||||
|
||||
export const ClaudeTraitsMenuContent = memo(function ClaudeTraitsMenuContentImpl({
|
||||
threadId,
|
||||
model,
|
||||
onPromptChange,
|
||||
}: ClaudeTraitsMenuContentProps) {
|
||||
const draft = useComposerThreadDraft(threadId);
|
||||
const prompt = draft.prompt;
|
||||
const modelOptions = draft.modelOptions?.[PROVIDER];
|
||||
const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
|
||||
const {
|
||||
effort,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
options,
|
||||
ultrathinkPromptControlled,
|
||||
supportsFastMode,
|
||||
} = getSelectedClaudeTraits(model, prompt, modelOptions);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER);
|
||||
|
||||
const handleEffortChange = useCallback(
|
||||
(value: ClaudeCodeEffort) => {
|
||||
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");
|
||||
onPromptChange(nextPrompt);
|
||||
return;
|
||||
}
|
||||
setProviderModelOptions(
|
||||
threadId,
|
||||
PROVIDER,
|
||||
normalizeClaudeModelOptions(model, {
|
||||
...modelOptions,
|
||||
effort: nextEffort,
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
},
|
||||
[
|
||||
ultrathinkPromptControlled,
|
||||
model,
|
||||
modelOptions,
|
||||
onPromptChange,
|
||||
threadId,
|
||||
setProviderModelOptions,
|
||||
options,
|
||||
prompt,
|
||||
],
|
||||
);
|
||||
|
||||
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={handleEffortChange}>
|
||||
{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) => {
|
||||
setProviderModelOptions(
|
||||
threadId,
|
||||
PROVIDER,
|
||||
normalizeClaudeModelOptions(model, {
|
||||
...modelOptions,
|
||||
thinking: value === "on",
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<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) => {
|
||||
setProviderModelOptions(
|
||||
threadId,
|
||||
PROVIDER,
|
||||
normalizeClaudeModelOptions(model, {
|
||||
...modelOptions,
|
||||
fastMode: value === "on",
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
export const ClaudeTraitsPicker = memo(function ClaudeTraitsPicker({
|
||||
threadId,
|
||||
model,
|
||||
onPromptChange,
|
||||
}: ClaudeTraitsMenuContentProps) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const draft = useComposerThreadDraft(threadId);
|
||||
const prompt = draft.prompt;
|
||||
const modelOptions = draft.modelOptions?.[PROVIDER];
|
||||
const { effort, thinkingEnabled, fastModeEnabled, ultrathinkPromptControlled, supportsFastMode } =
|
||||
getSelectedClaudeTraits(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={threadId}
|
||||
model={model}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
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("persists sticky codex model options when traits change", async () => {
|
||||
const mounted = await mountPicker({
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitemradio", { name: "on" }).click();
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toMatchObject({
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
} 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();
|
||||
}
|
||||
});
|
||||
});
|
||||
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user