Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db02da69ba | ||
|
|
ca37b7bafe | ||
|
|
e11fb6e778 | ||
|
|
d415558915 | ||
|
|
843d6d8678 | ||
|
|
754cded24a | ||
|
|
2b6640af1e | ||
|
|
9e29c9d728 | ||
|
|
ef2569196f | ||
|
|
34cef6202b | ||
|
|
25c7003226 | ||
|
|
46e63b3612 | ||
|
|
d373389703 | ||
|
|
bc12421736 | ||
|
|
8f11ea44a7 | ||
|
|
56660b04e9 | ||
|
|
2a237c2001 | ||
|
|
77716b4ccb | ||
|
|
fb18b2de16 |
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.
|
||||
|
||||
@@ -312,7 +312,7 @@ jobs:
|
||||
name: Mint release app token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ vars.RELEASE_APP_ID }}
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
|
||||
+2
-1
@@ -17,4 +17,5 @@ release/
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
.vitest-*
|
||||
__screenshots__/
|
||||
@@ -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,6 +1,3 @@
|
||||
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";
|
||||
@@ -13,9 +10,11 @@ import {
|
||||
import {
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
Option,
|
||||
Path,
|
||||
Ref,
|
||||
Schedule,
|
||||
Schema,
|
||||
@@ -25,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";
|
||||
@@ -66,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, {
|
||||
@@ -76,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 {
|
||||
@@ -214,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
|
||||
@@ -231,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(
|
||||
@@ -262,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),
|
||||
);
|
||||
@@ -278,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,
|
||||
);
|
||||
@@ -312,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),
|
||||
);
|
||||
|
||||
@@ -352,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,
|
||||
@@ -469,13 +477,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
}
|
||||
});
|
||||
|
||||
yield* shutdown.pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
fs.rmSync(rootDir, { recursive: true, force: true });
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* shutdown;
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -27,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);
|
||||
@@ -51,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,
|
||||
@@ -70,7 +69,7 @@ function waitForSync<A>(
|
||||
if (Date.now() >= deadline) {
|
||||
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
|
||||
}
|
||||
yield* sleep(10);
|
||||
yield* Effect.sleep(10);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -91,7 +90,7 @@ function withHarness<A, E>(
|
||||
makeOrchestrationIntegrationHarness({ provider }),
|
||||
use,
|
||||
(harness) => harness.dispose,
|
||||
);
|
||||
).pipe(Effect.provide(NodeServices.layer));
|
||||
}
|
||||
|
||||
function withRealCodexHarness<A, E>(
|
||||
@@ -101,7 +100,7 @@ function withRealCodexHarness<A, E>(
|
||||
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
|
||||
use,
|
||||
(harness) => harness.dispose,
|
||||
);
|
||||
).pipe(Effect.provide(NodeServices.layer));
|
||||
}
|
||||
|
||||
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -163,7 +163,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const resolvedPath = resolveAttachmentPath({
|
||||
stateDir: serverConfig.stateDir,
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||
|
||||
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", () =>
|
||||
|
||||
@@ -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",
|
||||
) {}
|
||||
@@ -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,
|
||||
|
||||
@@ -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";
|
||||
@@ -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),
|
||||
);
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,16 +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;
|
||||
readonly baseDir?: string;
|
||||
readonly threadModel?: string;
|
||||
}) {
|
||||
const now = new Date().toISOString();
|
||||
const stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
||||
const threadModel = input?.threadModel ?? "gpt-5-codex";
|
||||
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> = [];
|
||||
@@ -214,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);
|
||||
@@ -694,6 +704,7 @@ describe("ProviderCommandReactor", () => {
|
||||
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",
|
||||
@@ -1135,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(
|
||||
@@ -1147,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();
|
||||
|
||||
@@ -97,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());
|
||||
}
|
||||
@@ -312,7 +327,7 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const resumeCursor =
|
||||
providerChanged || shouldRestartForModelChange || shouldRestartForModelOptionsChange
|
||||
providerChanged || shouldRestartForModelChange
|
||||
? undefined
|
||||
: (activeSession?.resumeCursor ?? undefined);
|
||||
yield* Effect.logInfo("provider command reactor restarting provider session", {
|
||||
@@ -589,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,
|
||||
@@ -633,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,
|
||||
|
||||
@@ -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()));
|
||||
});
|
||||
@@ -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)),
|
||||
);
|
||||
@@ -1,3 +1,8 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type {
|
||||
Options as ClaudeQueryOptions,
|
||||
PermissionMode,
|
||||
@@ -5,18 +10,29 @@ import type {
|
||||
SDKMessage,
|
||||
SDKUserMessage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { ApprovalRequestId, ProviderItemId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
ProviderItemId,
|
||||
ProviderRuntimeEvent,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect, Fiber, Random, Stream } from "effect";
|
||||
import { Effect, Fiber, Layer, Random, Stream } from "effect";
|
||||
|
||||
import { attachmentRelativePath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
|
||||
import { makeClaudeAdapterLive, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts";
|
||||
|
||||
class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
|
||||
private readonly queue: Array<SDKMessage> = [];
|
||||
private readonly resolvers: Array<(value: IteratorResult<SDKMessage>) => void> = [];
|
||||
private readonly waiters: Array<{
|
||||
readonly resolve: (value: IteratorResult<SDKMessage>) => void;
|
||||
readonly reject: (reason: unknown) => void;
|
||||
}> = [];
|
||||
private done = false;
|
||||
private failure: unknown | undefined;
|
||||
|
||||
public readonly interruptCalls: Array<void> = [];
|
||||
public readonly setModelCalls: Array<string | undefined> = [];
|
||||
@@ -28,21 +44,33 @@ class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
|
||||
if (this.done) {
|
||||
return;
|
||||
}
|
||||
const resolver = this.resolvers.shift();
|
||||
if (resolver) {
|
||||
resolver({ done: false, value: message });
|
||||
const waiter = this.waiters.shift();
|
||||
if (waiter) {
|
||||
waiter.resolve({ done: false, value: message });
|
||||
return;
|
||||
}
|
||||
this.queue.push(message);
|
||||
}
|
||||
|
||||
fail(cause: unknown): void {
|
||||
if (this.done) {
|
||||
return;
|
||||
}
|
||||
this.done = true;
|
||||
this.failure = cause;
|
||||
for (const waiter of this.waiters.splice(0)) {
|
||||
waiter.reject(cause);
|
||||
}
|
||||
}
|
||||
|
||||
finish(): void {
|
||||
if (this.done) {
|
||||
return;
|
||||
}
|
||||
this.done = true;
|
||||
for (const resolver of this.resolvers.splice(0)) {
|
||||
resolver({ done: true, value: undefined });
|
||||
this.failure = undefined;
|
||||
for (const waiter of this.waiters.splice(0)) {
|
||||
waiter.resolve({ done: true, value: undefined });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,35 +107,34 @@ class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
|
||||
});
|
||||
}
|
||||
}
|
||||
if (this.failure !== undefined) {
|
||||
const failure = this.failure;
|
||||
this.failure = undefined;
|
||||
return Promise.reject(failure);
|
||||
}
|
||||
if (this.done) {
|
||||
return Promise.resolve({
|
||||
done: true,
|
||||
value: undefined,
|
||||
});
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
this.resolvers.push(resolve);
|
||||
return new Promise((resolve, reject) => {
|
||||
this.waiters.push({
|
||||
resolve,
|
||||
reject,
|
||||
});
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
interface Harness {
|
||||
readonly layer: ReturnType<typeof makeClaudeAdapterLive>;
|
||||
readonly query: FakeClaudeQuery;
|
||||
readonly getLastCreateQueryInput: () =>
|
||||
| {
|
||||
readonly prompt: AsyncIterable<SDKUserMessage>;
|
||||
readonly options: ClaudeQueryOptions;
|
||||
}
|
||||
| undefined;
|
||||
}
|
||||
|
||||
function makeHarness(config?: {
|
||||
readonly nativeEventLogPath?: string;
|
||||
readonly nativeEventLogger?: ClaudeAdapterLiveOptions["nativeEventLogger"];
|
||||
}): Harness {
|
||||
readonly cwd?: string;
|
||||
readonly baseDir?: string;
|
||||
}) {
|
||||
const query = new FakeClaudeQuery();
|
||||
let createInput:
|
||||
| {
|
||||
@@ -134,7 +161,15 @@ function makeHarness(config?: {
|
||||
};
|
||||
|
||||
return {
|
||||
layer: makeClaudeAdapterLive(adapterOptions),
|
||||
layer: makeClaudeAdapterLive(adapterOptions).pipe(
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(
|
||||
config?.cwd ?? "/tmp/claude-adapter-test",
|
||||
config?.baseDir ?? "/tmp",
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
query,
|
||||
getLastCreateQueryInput: () => createInput,
|
||||
};
|
||||
@@ -178,6 +213,24 @@ async function readFirstPromptText(
|
||||
return content.text;
|
||||
}
|
||||
|
||||
async function readFirstPromptMessage(
|
||||
input:
|
||||
| {
|
||||
readonly prompt: AsyncIterable<SDKUserMessage>;
|
||||
}
|
||||
| undefined,
|
||||
): Promise<SDKUserMessage | undefined> {
|
||||
const iterator = input?.prompt[Symbol.asyncIterator]();
|
||||
if (!iterator) {
|
||||
return undefined;
|
||||
}
|
||||
const next = await iterator.next();
|
||||
if (next.done) {
|
||||
return undefined;
|
||||
}
|
||||
return next.value;
|
||||
}
|
||||
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-claude-1");
|
||||
const RESUME_THREAD_ID = ThreadId.makeUnsafe("thread-claude-resume");
|
||||
|
||||
@@ -219,6 +272,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.deepEqual(createInput?.options.settingSources, ["user", "project", "local"]);
|
||||
assert.equal(createInput?.options.permissionMode, "bypassPermissions");
|
||||
assert.equal(createInput?.options.allowDangerouslySkipPermissions, true);
|
||||
}).pipe(
|
||||
@@ -227,6 +281,26 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("loads Claude filesystem settings sources for SDK sessions", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.deepEqual(createInput?.options.settingSources, ["user", "project", "local"]);
|
||||
assert.equal(createInput?.options.permissionMode, undefined);
|
||||
assert.equal(createInput?.options.allowDangerouslySkipPermissions, undefined);
|
||||
}).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* () {
|
||||
@@ -461,6 +535,71 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("embeds image attachments in Claude user messages", () => {
|
||||
const baseDir = mkdtempSync(path.join(os.tmpdir(), "claude-attachments-"));
|
||||
const harness = makeHarness({
|
||||
cwd: "/tmp/project-claude-attachments",
|
||||
baseDir,
|
||||
});
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() =>
|
||||
rmSync(baseDir, {
|
||||
recursive: true,
|
||||
force: true,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
const { attachmentsDir } = yield* ServerConfig;
|
||||
|
||||
const attachment = {
|
||||
type: "image" as const,
|
||||
id: "thread-claude-attachment-12345678-1234-1234-1234-123456789abc",
|
||||
name: "diagram.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4,
|
||||
};
|
||||
const attachmentPath = path.join(attachmentsDir, attachmentRelativePath(attachment));
|
||||
mkdirSync(path.dirname(attachmentPath), { recursive: true });
|
||||
writeFileSync(attachmentPath, Uint8Array.from([1, 2, 3, 4]));
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "What's in this image?",
|
||||
attachments: [attachment],
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
const promptMessage = yield* Effect.promise(() => readFirstPromptMessage(createInput));
|
||||
assert.isDefined(promptMessage);
|
||||
assert.deepEqual(promptMessage?.message.content, [
|
||||
{
|
||||
type: "text",
|
||||
text: "What's in this image?",
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
source: {
|
||||
type: "base64",
|
||||
media_type: "image/png",
|
||||
data: "AQIDBA==",
|
||||
},
|
||||
},
|
||||
]);
|
||||
}).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* () {
|
||||
@@ -890,6 +1029,130 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("treats user-aborted Claude results as interrupted without a runtime error", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "error_during_execution",
|
||||
is_error: false,
|
||||
errors: ["Error: Request was aborted."],
|
||||
stop_reason: "tool_use",
|
||||
session_id: "sdk-session-abort",
|
||||
uuid: "result-abort",
|
||||
} 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",
|
||||
"turn.completed",
|
||||
],
|
||||
);
|
||||
|
||||
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, "interrupted");
|
||||
assert.equal(turnCompleted.payload.errorMessage, "Error: Request was aborted.");
|
||||
assert.equal(turnCompleted.payload.stopReason, "tool_use");
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("closes the session when the Claude stream aborts after a turn starts", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
|
||||
|
||||
const runtimeEventsFiber = Effect.runFork(
|
||||
Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId: THREAD_ID,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.fail(new Error("All fibers interrupted without error"));
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
runtimeEventsFiber.interruptUnsafe();
|
||||
assert.deepEqual(
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"turn.completed",
|
||||
"session.exited",
|
||||
],
|
||||
);
|
||||
|
||||
const turnCompleted = runtimeEvents[4];
|
||||
assert.equal(turnCompleted?.type, "turn.completed");
|
||||
if (turnCompleted?.type === "turn.completed") {
|
||||
assert.equal(String(turnCompleted.turnId), String(turn.turnId));
|
||||
assert.equal(turnCompleted.payload.state, "interrupted");
|
||||
assert.equal(turnCompleted.payload.errorMessage, "Claude runtime interrupted.");
|
||||
}
|
||||
|
||||
const sessionExited = runtimeEvents[5];
|
||||
assert.equal(sessionExited?.type, "session.exited");
|
||||
|
||||
assert.equal(yield* adapter.hasSession(THREAD_ID), false);
|
||||
const sessions = yield* adapter.listSessions();
|
||||
assert.equal(sessions.length, 0);
|
||||
assert.equal(harness.query.closeCalls, 1);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("forwards Claude task progress summaries for subagent updates", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
@@ -1030,6 +1293,172 @@ describe("ClaudeAdapterLive", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("creates a fresh assistant message when Claude reuses a text block index", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-reused-text-index",
|
||||
uuid: "stream-reused-start-1",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_start",
|
||||
index: 0,
|
||||
content_block: {
|
||||
type: "text",
|
||||
text: "",
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-reused-text-index",
|
||||
uuid: "stream-reused-delta-1",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_delta",
|
||||
index: 0,
|
||||
delta: {
|
||||
type: "text_delta",
|
||||
text: "First",
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-reused-text-index",
|
||||
uuid: "stream-reused-stop-1",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_stop",
|
||||
index: 0,
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-reused-text-index",
|
||||
uuid: "stream-reused-start-2",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_start",
|
||||
index: 0,
|
||||
content_block: {
|
||||
type: "text",
|
||||
text: "",
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-reused-text-index",
|
||||
uuid: "stream-reused-delta-2",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_delta",
|
||||
index: 0,
|
||||
delta: {
|
||||
type: "text_delta",
|
||||
text: "Second",
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-reused-text-index",
|
||||
uuid: "stream-reused-stop-2",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_stop",
|
||||
index: 0,
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
errors: [],
|
||||
session_id: "sdk-session-reused-text-index",
|
||||
uuid: "result-reused-text-index",
|
||||
} 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.completed",
|
||||
"content.delta",
|
||||
"item.completed",
|
||||
],
|
||||
);
|
||||
|
||||
const assistantDeltas = runtimeEvents.filter(
|
||||
(event) => event.type === "content.delta" && event.payload.streamKind === "assistant_text",
|
||||
);
|
||||
assert.equal(assistantDeltas.length, 2);
|
||||
if (assistantDeltas.length !== 2) {
|
||||
return;
|
||||
}
|
||||
const [firstAssistantDelta, secondAssistantDelta] = assistantDeltas;
|
||||
assert.equal(firstAssistantDelta?.type, "content.delta");
|
||||
assert.equal(secondAssistantDelta?.type, "content.delta");
|
||||
if (
|
||||
firstAssistantDelta?.type !== "content.delta" ||
|
||||
secondAssistantDelta?.type !== "content.delta"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstAssistantDelta.payload.delta, "First");
|
||||
assert.equal(secondAssistantDelta.payload.delta, "Second");
|
||||
assert.notEqual(firstAssistantDelta.itemId, secondAssistantDelta.itemId);
|
||||
|
||||
const assistantCompletions = runtimeEvents.filter(
|
||||
(event) =>
|
||||
event.type === "item.completed" && event.payload.itemType === "assistant_message",
|
||||
);
|
||||
assert.equal(assistantCompletions.length, 2);
|
||||
assert.equal(String(assistantCompletions[0]?.itemId), String(firstAssistantDelta.itemId));
|
||||
assert.equal(String(assistantCompletions[1]?.itemId), String(secondAssistantDelta.itemId));
|
||||
assert.notEqual(
|
||||
String(assistantCompletions[0]?.itemId),
|
||||
String(assistantCompletions[1]?.itemId),
|
||||
);
|
||||
}).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* () {
|
||||
@@ -1581,7 +2010,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("passes parsed resume cursor values to Claude query options", () => {
|
||||
it.effect("passes Claude resume ids without pinning a stale assistant checkpoint", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
@@ -1608,14 +2037,15 @@ describe("ClaudeAdapterLive", () => {
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.resume, "550e8400-e29b-41d4-a716-446655440000");
|
||||
assert.equal(createInput?.options.resumeSessionAt, "assistant-99");
|
||||
assert.equal(createInput?.options.sessionId, undefined);
|
||||
assert.equal(createInput?.options.resumeSessionAt, undefined);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("does not synthesize resume session id from generated thread ids", () => {
|
||||
it.effect("uses an app-generated Claude session id for fresh sessions", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
@@ -1626,10 +2056,21 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
assert.equal("resume" in (session.resumeCursor as Record<string, unknown>), false);
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
const sessionResumeCursor = session.resumeCursor as {
|
||||
threadId?: string;
|
||||
resume?: string;
|
||||
turnCount?: number;
|
||||
};
|
||||
assert.equal(sessionResumeCursor.threadId, THREAD_ID);
|
||||
assert.equal(typeof sessionResumeCursor.resume, "string");
|
||||
assert.equal(sessionResumeCursor.turnCount, 0);
|
||||
assert.match(
|
||||
sessionResumeCursor.resume ?? "",
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
|
||||
);
|
||||
assert.equal(createInput?.options.resume, undefined);
|
||||
assert.equal(createInput?.options.sessionId, sessionResumeCursor.resume);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -1841,6 +2282,143 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("captures ExitPlanMode as a proposed plan and denies auto-exit", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "plan this",
|
||||
interactionMode: "plan",
|
||||
attachments: [],
|
||||
});
|
||||
yield* Stream.take(adapter.streamEvents, 1).pipe(Stream.runDrain);
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
const canUseTool = createInput?.options.canUseTool;
|
||||
assert.equal(typeof canUseTool, "function");
|
||||
if (!canUseTool) {
|
||||
return;
|
||||
}
|
||||
|
||||
const permissionPromise = canUseTool(
|
||||
"ExitPlanMode",
|
||||
{
|
||||
plan: "# Ship it\n\n- one\n- two",
|
||||
allowedPrompts: [{ tool: "Bash", prompt: "run tests" }],
|
||||
},
|
||||
{
|
||||
signal: new AbortController().signal,
|
||||
toolUseID: "tool-exit-1",
|
||||
},
|
||||
);
|
||||
|
||||
const proposedEvent = yield* Stream.runHead(adapter.streamEvents);
|
||||
assert.equal(proposedEvent._tag, "Some");
|
||||
if (proposedEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(proposedEvent.value.type, "turn.proposed.completed");
|
||||
if (proposedEvent.value.type !== "turn.proposed.completed") {
|
||||
return;
|
||||
}
|
||||
assert.equal(proposedEvent.value.payload.planMarkdown, "# Ship it\n\n- one\n- two");
|
||||
assert.deepEqual(proposedEvent.value.providerRefs, {
|
||||
providerItemId: ProviderItemId.makeUnsafe("tool-exit-1"),
|
||||
});
|
||||
|
||||
const permissionResult = yield* Effect.promise(() => permissionPromise);
|
||||
assert.equal((permissionResult as PermissionResult).behavior, "deny");
|
||||
const deniedResult = permissionResult as PermissionResult & {
|
||||
message?: string;
|
||||
};
|
||||
assert.equal(deniedResult.message?.includes("captured your proposed plan"), true);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("extracts proposed plans from assistant ExitPlanMode snapshots", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "plan this",
|
||||
interactionMode: "plan",
|
||||
attachments: [],
|
||||
});
|
||||
yield* Stream.take(adapter.streamEvents, 1).pipe(Stream.runDrain);
|
||||
|
||||
const proposedEventFiber = yield* Stream.filter(
|
||||
adapter.streamEvents,
|
||||
(event) => event.type === "turn.proposed.completed",
|
||||
).pipe(Stream.runHead, Effect.forkChild);
|
||||
|
||||
harness.query.emit({
|
||||
type: "assistant",
|
||||
session_id: "sdk-session-exit-plan",
|
||||
uuid: "assistant-exit-plan",
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
model: "claude-opus-4-6",
|
||||
id: "msg-exit-plan",
|
||||
type: "message",
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "tool-exit-2",
|
||||
name: "ExitPlanMode",
|
||||
input: {
|
||||
plan: "# Final plan\n\n- capture it",
|
||||
},
|
||||
},
|
||||
],
|
||||
stop_reason: null,
|
||||
stop_sequence: null,
|
||||
usage: {},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const proposedEvent = yield* Fiber.join(proposedEventFiber);
|
||||
assert.equal(proposedEvent._tag, "Some");
|
||||
if (proposedEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(proposedEvent.value.type, "turn.proposed.completed");
|
||||
if (proposedEvent.value.type !== "turn.proposed.completed") {
|
||||
return;
|
||||
}
|
||||
assert.equal(proposedEvent.value.payload.planMarkdown, "# Final plan\n\n- capture it");
|
||||
assert.deepEqual(proposedEvent.value.providerRefs, {
|
||||
providerItemId: ProviderItemId.makeUnsafe("tool-exit-2"),
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("handles AskUserQuestion via user-input.requested/resolved lifecycle", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
@@ -2035,6 +2613,74 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("denies AskUserQuestion when the waiting turn is aborted", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
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 controller = new AbortController();
|
||||
const permissionPromise = canUseTool(
|
||||
"AskUserQuestion",
|
||||
{
|
||||
questions: [
|
||||
{
|
||||
question: "Continue?",
|
||||
header: "Continue",
|
||||
options: [{ label: "Yes", description: "Proceed" }],
|
||||
multiSelect: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
signal: controller.signal,
|
||||
toolUseID: "tool-ask-abort",
|
||||
},
|
||||
);
|
||||
|
||||
const requestedEvent = yield* Stream.runHead(adapter.streamEvents);
|
||||
assert.equal(requestedEvent._tag, "Some");
|
||||
if (requestedEvent._tag !== "Some" || requestedEvent.value.type !== "user-input.requested") {
|
||||
assert.fail("Expected user-input.requested event");
|
||||
return;
|
||||
}
|
||||
assert.equal(requestedEvent.value.threadId, session.threadId);
|
||||
|
||||
controller.abort();
|
||||
|
||||
const resolvedEvent = yield* Stream.runHead(adapter.streamEvents);
|
||||
assert.equal(resolvedEvent._tag, "Some");
|
||||
if (resolvedEvent._tag !== "Some" || resolvedEvent.value.type !== "user-input.resolved") {
|
||||
assert.fail("Expected user-input.resolved event");
|
||||
return;
|
||||
}
|
||||
assert.deepEqual(resolvedEvent.value.payload.answers, {});
|
||||
|
||||
const permissionResult = yield* Effect.promise(() => permissionPromise);
|
||||
assert.deepEqual(permissionResult, {
|
||||
behavior: "deny",
|
||||
message: "User cancelled tool execution.",
|
||||
} satisfies PermissionResult);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("writes provider-native observability records when enabled", () => {
|
||||
const nativeEvents: Array<{
|
||||
event?: {
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
type PermissionUpdate,
|
||||
type SDKMessage,
|
||||
type SDKResultMessage,
|
||||
type SettingSource,
|
||||
type SDKUserMessage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
@@ -46,8 +47,23 @@ import {
|
||||
supportsClaudeThinkingToggle,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
} from "@t3tools/shared/model";
|
||||
import { Cause, DateTime, Deferred, Effect, Layer, Queue, Random, Ref, Stream } from "effect";
|
||||
import {
|
||||
Cause,
|
||||
DateTime,
|
||||
Deferred,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Fiber,
|
||||
Layer,
|
||||
Queue,
|
||||
Random,
|
||||
Ref,
|
||||
Stream,
|
||||
} from "effect";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
ProviderAdapterRequestError,
|
||||
@@ -87,12 +103,14 @@ interface ClaudeTurnState {
|
||||
readonly startedAt: string;
|
||||
readonly items: Array<unknown>;
|
||||
readonly assistantTextBlocks: Map<number, AssistantTextBlockState>;
|
||||
readonly assistantTextBlockOrder: Array<number>;
|
||||
readonly assistantTextBlockOrder: Array<AssistantTextBlockState>;
|
||||
readonly capturedProposedPlanKeys: Set<string>;
|
||||
nextSyntheticAssistantBlockIndex: number;
|
||||
}
|
||||
|
||||
interface AssistantTextBlockState {
|
||||
readonly itemId: string;
|
||||
readonly blockIndex: number;
|
||||
emittedTextDelta: boolean;
|
||||
fallbackText: string;
|
||||
streamClosed: boolean;
|
||||
@@ -126,6 +144,7 @@ interface ClaudeSessionContext {
|
||||
session: ProviderSession;
|
||||
readonly promptQueue: Queue.Queue<PromptQueueItem>;
|
||||
readonly query: ClaudeQueryRuntime;
|
||||
streamFiber: Fiber.Fiber<void, Error> | undefined;
|
||||
readonly startedAt: string;
|
||||
readonly basePermissionMode: PermissionMode | undefined;
|
||||
resumeSessionId: string | undefined;
|
||||
@@ -174,6 +193,68 @@ function toMessage(cause: unknown, fallback: string): string {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function toError(cause: unknown, fallback: string): Error {
|
||||
return cause instanceof Error ? cause : new Error(toMessage(cause, fallback));
|
||||
}
|
||||
|
||||
function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray<string> {
|
||||
const errors = Cause.prettyErrors(cause)
|
||||
.map((error) => error.message.trim())
|
||||
.filter((message) => message.length > 0);
|
||||
if (errors.length > 0) {
|
||||
return errors;
|
||||
}
|
||||
|
||||
const squashed = toMessage(Cause.squash(cause), "").trim();
|
||||
return squashed.length > 0 ? [squashed] : [];
|
||||
}
|
||||
|
||||
function isClaudeInterruptedMessage(message: string): boolean {
|
||||
const normalized = message.toLowerCase();
|
||||
return (
|
||||
normalized.includes("all fibers interrupted without error") ||
|
||||
normalized.includes("request was aborted") ||
|
||||
normalized.includes("interrupted by user")
|
||||
);
|
||||
}
|
||||
|
||||
function isClaudeInterruptedCause(cause: Cause.Cause<Error>): boolean {
|
||||
return (
|
||||
Cause.hasInterruptsOnly(cause) ||
|
||||
normalizeClaudeStreamMessages(cause).some(isClaudeInterruptedMessage)
|
||||
);
|
||||
}
|
||||
|
||||
function messageFromClaudeStreamCause(cause: Cause.Cause<Error>, fallback: string): string {
|
||||
return normalizeClaudeStreamMessages(cause)[0] ?? fallback;
|
||||
}
|
||||
|
||||
function interruptionMessageFromClaudeCause(cause: Cause.Cause<Error>): string {
|
||||
const message = messageFromClaudeStreamCause(cause, "Claude runtime interrupted.");
|
||||
return isClaudeInterruptedMessage(message) ? "Claude runtime interrupted." : message;
|
||||
}
|
||||
|
||||
function resultErrorsText(result: SDKResultMessage): string {
|
||||
return "errors" in result && Array.isArray(result.errors)
|
||||
? result.errors.join(" ").toLowerCase()
|
||||
: "";
|
||||
}
|
||||
|
||||
function isInterruptedResult(result: SDKResultMessage): boolean {
|
||||
const errors = resultErrorsText(result);
|
||||
if (errors.includes("interrupt")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
result.subtype === "error_during_execution" &&
|
||||
result.is_error === false &&
|
||||
(errors.includes("request was aborted") ||
|
||||
errors.includes("interrupted by user") ||
|
||||
errors.includes("aborted"))
|
||||
);
|
||||
}
|
||||
|
||||
function asRuntimeItemId(value: string): RuntimeItemId {
|
||||
return RuntimeItemId.makeUnsafe(value);
|
||||
}
|
||||
@@ -340,21 +421,19 @@ function titleForTool(itemType: CanonicalItemType): string {
|
||||
}
|
||||
}
|
||||
|
||||
function buildUserMessage(input: ProviderSendTurnInput): SDKUserMessage {
|
||||
const fragments: string[] = [];
|
||||
|
||||
if (input.input && input.input.trim().length > 0) {
|
||||
fragments.push(input.input.trim());
|
||||
}
|
||||
|
||||
for (const attachment of input.attachments ?? []) {
|
||||
if (attachment.type === "image") {
|
||||
fragments.push(
|
||||
`Attached image: ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes).`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const SUPPORTED_CLAUDE_IMAGE_MIME_TYPES = new Set([
|
||||
"image/gif",
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/webp",
|
||||
]);
|
||||
const CLAUDE_SETTING_SOURCES = [
|
||||
"user",
|
||||
"project",
|
||||
"local",
|
||||
] as const satisfies ReadonlyArray<SettingSource>;
|
||||
|
||||
function buildPromptText(input: ProviderSendTurnInput): string {
|
||||
const requestedEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
input.modelOptions?.claudeAgent?.effort ?? null,
|
||||
@@ -366,26 +445,108 @@ function buildUserMessage(input: ProviderSendTurnInput): SDKUserMessage {
|
||||
: requestedEffort && supportedEffortOptions.includes(requestedEffort)
|
||||
? requestedEffort
|
||||
: null;
|
||||
const text = applyClaudePromptEffortPrefix(fragments.join("\n\n"), promptEffort);
|
||||
return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort);
|
||||
}
|
||||
|
||||
function buildUserMessage(input: {
|
||||
readonly sdkContent: Array<Record<string, unknown>>;
|
||||
}): SDKUserMessage {
|
||||
return {
|
||||
type: "user",
|
||||
session_id: "",
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
role: "user",
|
||||
content: [{ type: "text", text }],
|
||||
content: input.sdkContent,
|
||||
},
|
||||
} as SDKUserMessage;
|
||||
}
|
||||
|
||||
function buildClaudeImageContentBlock(input: {
|
||||
readonly mimeType: string;
|
||||
readonly bytes: Uint8Array;
|
||||
}): Record<string, unknown> {
|
||||
return {
|
||||
type: "image",
|
||||
source: {
|
||||
type: "base64",
|
||||
media_type: input.mimeType,
|
||||
data: Buffer.from(input.bytes).toString("base64"),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildUserMessageEffect(
|
||||
input: ProviderSendTurnInput,
|
||||
dependencies: {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly attachmentsDir: string;
|
||||
},
|
||||
): Effect.Effect<SDKUserMessage, ProviderAdapterRequestError> {
|
||||
return Effect.gen(function* () {
|
||||
const text = buildPromptText(input);
|
||||
const sdkContent: Array<Record<string, unknown>> = [];
|
||||
|
||||
if (text.length > 0) {
|
||||
sdkContent.push({ type: "text", text });
|
||||
}
|
||||
|
||||
for (const attachment of input.attachments ?? []) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!SUPPORTED_CLAUDE_IMAGE_MIME_TYPES.has(attachment.mimeType)) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "turn/start",
|
||||
detail: `Unsupported Claude image attachment type '${attachment.mimeType}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: dependencies.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "turn/start",
|
||||
detail: `Invalid attachment id '${attachment.id}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const bytes = yield* dependencies.fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "turn/start",
|
||||
detail: toMessage(cause, "Failed to read attachment file."),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
sdkContent.push(
|
||||
buildClaudeImageContentBlock({
|
||||
mimeType: attachment.mimeType,
|
||||
bytes,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return buildUserMessage({ sdkContent });
|
||||
});
|
||||
}
|
||||
|
||||
function turnStatusFromResult(result: SDKResultMessage): ProviderRuntimeTurnStatus {
|
||||
if (result.subtype === "success") {
|
||||
return "completed";
|
||||
}
|
||||
|
||||
const errors = result.errors.join(" ").toLowerCase();
|
||||
if (errors.includes("interrupt")) {
|
||||
const errors = resultErrorsText(result);
|
||||
if (isInterruptedResult(result)) {
|
||||
return "interrupted";
|
||||
}
|
||||
if (errors.includes("cancel")) {
|
||||
@@ -474,6 +635,28 @@ function extractTextContent(value: unknown): string {
|
||||
return extractTextContent(record.content);
|
||||
}
|
||||
|
||||
function extractExitPlanModePlan(value: unknown): string | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const record = value as {
|
||||
plan?: unknown;
|
||||
};
|
||||
return typeof record.plan === "string" && record.plan.trim().length > 0
|
||||
? record.plan.trim()
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function exitPlanCaptureKey(input: {
|
||||
readonly toolUseId?: string | undefined;
|
||||
readonly planMarkdown: string;
|
||||
}): string {
|
||||
return input.toolUseId && input.toolUseId.length > 0
|
||||
? `tool:${input.toolUseId}`
|
||||
: `plan:${input.planMarkdown}`;
|
||||
}
|
||||
|
||||
function tryParseJsonRecord(value: string): Record<string, unknown> | undefined {
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
@@ -654,6 +837,8 @@ function sdkNativeItemId(message: SDKMessage): string | undefined {
|
||||
|
||||
function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
@@ -785,7 +970,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
}
|
||||
|
||||
const existing = turnState.assistantTextBlocks.get(blockIndex);
|
||||
if (existing) {
|
||||
if (existing && !existing.completionEmitted) {
|
||||
if (existing.fallbackText.length === 0 && options?.fallbackText) {
|
||||
existing.fallbackText = options.fallbackText;
|
||||
}
|
||||
@@ -797,13 +982,14 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
|
||||
const block: AssistantTextBlockState = {
|
||||
itemId: yield* Random.nextUUIDv4,
|
||||
blockIndex,
|
||||
emittedTextDelta: false,
|
||||
fallbackText: options?.fallbackText ?? "",
|
||||
streamClosed: options?.streamClosed ?? false,
|
||||
completionEmitted: false,
|
||||
};
|
||||
turnState.assistantTextBlocks.set(blockIndex, block);
|
||||
turnState.assistantTextBlockOrder.push(blockIndex);
|
||||
turnState.assistantTextBlockOrder.push(block);
|
||||
return { blockIndex, block };
|
||||
});
|
||||
|
||||
@@ -833,7 +1019,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
|
||||
const completeAssistantTextBlock = (
|
||||
context: ClaudeSessionContext,
|
||||
blockIndex: number,
|
||||
block: AssistantTextBlockState,
|
||||
options?: {
|
||||
readonly force?: boolean;
|
||||
readonly rawMethod?: string;
|
||||
@@ -842,8 +1028,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
const turnState = context.turnState;
|
||||
const block = turnState?.assistantTextBlocks.get(blockIndex);
|
||||
if (!turnState || !block || block.completionEmitted) {
|
||||
if (!turnState || block.completionEmitted) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -879,6 +1064,9 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
}
|
||||
|
||||
block.completionEmitted = true;
|
||||
if (turnState.assistantTextBlocks.get(block.blockIndex) === block) {
|
||||
turnState.assistantTextBlocks.delete(block.blockIndex);
|
||||
}
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
@@ -923,19 +1111,10 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
return;
|
||||
}
|
||||
|
||||
const orderedBlocks = turnState.assistantTextBlockOrder
|
||||
.map((blockIndex) => ({
|
||||
blockIndex,
|
||||
block: turnState.assistantTextBlocks.get(blockIndex),
|
||||
}))
|
||||
.filter(
|
||||
(
|
||||
entry,
|
||||
): entry is {
|
||||
readonly blockIndex: number;
|
||||
readonly block: AssistantTextBlockState;
|
||||
} => entry.block !== undefined,
|
||||
);
|
||||
const orderedBlocks = turnState.assistantTextBlockOrder.map((block) => ({
|
||||
blockIndex: block.blockIndex,
|
||||
block,
|
||||
}));
|
||||
|
||||
for (const [position, text] of snapshotTextBlocks.entries()) {
|
||||
const existingEntry = orderedBlocks[position];
|
||||
@@ -959,7 +1138,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
}
|
||||
|
||||
if (entry.block.streamClosed && !entry.block.completionEmitted) {
|
||||
yield* completeAssistantTextBlock(context, entry.blockIndex, {
|
||||
yield* completeAssistantTextBlock(context, entry.block, {
|
||||
rawMethod: "claude/assistant",
|
||||
rawPayload: message,
|
||||
});
|
||||
@@ -1053,6 +1232,54 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
});
|
||||
});
|
||||
|
||||
const emitProposedPlanCompleted = (
|
||||
context: ClaudeSessionContext,
|
||||
input: {
|
||||
readonly planMarkdown: string;
|
||||
readonly toolUseId?: string | undefined;
|
||||
readonly rawSource: "claude.sdk.message" | "claude.sdk.permission";
|
||||
readonly rawMethod: string;
|
||||
readonly rawPayload: unknown;
|
||||
},
|
||||
): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
const turnState = context.turnState;
|
||||
const planMarkdown = input.planMarkdown.trim();
|
||||
if (!turnState || planMarkdown.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const captureKey = exitPlanCaptureKey({
|
||||
toolUseId: input.toolUseId,
|
||||
planMarkdown,
|
||||
});
|
||||
if (turnState.capturedProposedPlanKeys.has(captureKey)) {
|
||||
return;
|
||||
}
|
||||
turnState.capturedProposedPlanKeys.add(captureKey);
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.proposed.completed",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: stamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
turnId: turnState.turnId,
|
||||
payload: {
|
||||
planMarkdown,
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, {
|
||||
providerItemId: input.toolUseId,
|
||||
}),
|
||||
raw: {
|
||||
source: input.rawSource,
|
||||
method: input.rawMethod,
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const completeTurn = (
|
||||
context: ClaudeSessionContext,
|
||||
status: ProviderRuntimeTurnStatus,
|
||||
@@ -1116,8 +1343,8 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
// Clear any remaining stale entries (e.g. from interrupted content blocks)
|
||||
context.inFlightTools.clear();
|
||||
|
||||
for (const blockIndex of turnState.assistantTextBlockOrder) {
|
||||
yield* completeAssistantTextBlock(context, blockIndex, {
|
||||
for (const block of turnState.assistantTextBlockOrder) {
|
||||
yield* completeAssistantTextBlock(context, block, {
|
||||
force: true,
|
||||
rawMethod: "claude/result",
|
||||
rawPayload: result ?? { status },
|
||||
@@ -1368,7 +1595,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
const assistantBlock = context.turnState?.assistantTextBlocks.get(index);
|
||||
if (assistantBlock) {
|
||||
assistantBlock.streamClosed = true;
|
||||
yield* completeAssistantTextBlock(context, index, {
|
||||
yield* completeAssistantTextBlock(context, assistantBlock, {
|
||||
rawMethod: "claude/stream_event/content_block_stop",
|
||||
rawPayload: message,
|
||||
});
|
||||
@@ -1506,6 +1733,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
items: [],
|
||||
assistantTextBlocks: new Map(),
|
||||
assistantTextBlockOrder: [],
|
||||
capturedProposedPlanKeys: new Set(),
|
||||
nextSyntheticAssistantBlockIndex: -1,
|
||||
};
|
||||
context.session = {
|
||||
@@ -1535,6 +1763,35 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
});
|
||||
}
|
||||
|
||||
const content = message.message?.content;
|
||||
if (Array.isArray(content)) {
|
||||
for (const block of content) {
|
||||
if (!block || typeof block !== "object") {
|
||||
continue;
|
||||
}
|
||||
const toolUse = block as {
|
||||
type?: unknown;
|
||||
id?: unknown;
|
||||
name?: unknown;
|
||||
input?: unknown;
|
||||
};
|
||||
if (toolUse.type !== "tool_use" || toolUse.name !== "ExitPlanMode") {
|
||||
continue;
|
||||
}
|
||||
const planMarkdown = extractExitPlanModePlan(toolUse.input);
|
||||
if (!planMarkdown) {
|
||||
continue;
|
||||
}
|
||||
yield* emitProposedPlanCompleted(context, {
|
||||
planMarkdown,
|
||||
toolUseId: typeof toolUse.id === "string" ? toolUse.id : undefined,
|
||||
rawSource: "claude.sdk.message",
|
||||
rawMethod: "claude/assistant",
|
||||
rawPayload: message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (context.turnState) {
|
||||
context.turnState.items.push(message.message);
|
||||
yield* backfillAssistantTextBlocksFromSnapshot(context, message);
|
||||
@@ -1838,22 +2095,49 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
}
|
||||
});
|
||||
|
||||
const runSdkStream = (context: ClaudeSessionContext): Effect.Effect<void> =>
|
||||
Stream.fromAsyncIterable(context.query, (cause) => cause).pipe(
|
||||
const runSdkStream = (context: ClaudeSessionContext): Effect.Effect<void, Error> =>
|
||||
Stream.fromAsyncIterable(context.query, (cause) =>
|
||||
toError(cause, "Claude runtime stream failed."),
|
||||
).pipe(
|
||||
Stream.takeWhile(() => !context.stopped),
|
||||
Stream.runForEach((message) => handleSdkMessage(context, message)),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.gen(function* () {
|
||||
if (Cause.hasInterruptsOnly(cause) || context.stopped) {
|
||||
return;
|
||||
}
|
||||
const message = toMessage(Cause.squash(cause), "Claude runtime stream failed.");
|
||||
yield* emitRuntimeError(context, message, cause);
|
||||
yield* completeTurn(context, "failed", message);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const handleStreamExit = (
|
||||
context: ClaudeSessionContext,
|
||||
exit: Exit.Exit<void, Error>,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
if (context.stopped) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Exit.isFailure(exit)) {
|
||||
if (isClaudeInterruptedCause(exit.cause)) {
|
||||
if (context.turnState) {
|
||||
yield* completeTurn(
|
||||
context,
|
||||
"interrupted",
|
||||
interruptionMessageFromClaudeCause(exit.cause),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const message = messageFromClaudeStreamCause(
|
||||
exit.cause,
|
||||
"Claude runtime stream failed.",
|
||||
);
|
||||
yield* emitRuntimeError(context, message, Cause.pretty(exit.cause));
|
||||
yield* completeTurn(context, "failed", message);
|
||||
}
|
||||
} else if (context.turnState) {
|
||||
yield* completeTurn(context, "interrupted", "Claude runtime stream ended.");
|
||||
}
|
||||
|
||||
yield* stopSessionInternal(context, {
|
||||
emitExitEvent: true,
|
||||
});
|
||||
});
|
||||
|
||||
const stopSessionInternal = (
|
||||
context: ClaudeSessionContext,
|
||||
options?: { readonly emitExitEvent?: boolean },
|
||||
@@ -1889,7 +2173,18 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
|
||||
yield* Queue.shutdown(context.promptQueue);
|
||||
|
||||
context.query.close();
|
||||
const streamFiber = context.streamFiber;
|
||||
context.streamFiber = undefined;
|
||||
if (streamFiber && streamFiber.pollUnsafe() === undefined) {
|
||||
yield* Fiber.interrupt(streamFiber);
|
||||
}
|
||||
|
||||
// @effect-diagnostics-next-line tryCatchInEffectGen:off
|
||||
try {
|
||||
context.query.close();
|
||||
} catch (cause) {
|
||||
yield* emitRuntimeError(context, "Failed to close Claude runtime query.", cause);
|
||||
}
|
||||
|
||||
const updatedAt = yield* nowIso;
|
||||
context.session = {
|
||||
@@ -1954,6 +2249,10 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
const startedAt = yield* nowIso;
|
||||
const resumeState = readClaudeResumeState(input.resumeCursor);
|
||||
const threadId = input.threadId;
|
||||
const existingResumeSessionId = resumeState?.resume;
|
||||
const newSessionId =
|
||||
existingResumeSessionId === undefined ? yield* Random.nextUUIDv4 : undefined;
|
||||
const sessionId = existingResumeSessionId ?? newSessionId;
|
||||
|
||||
const promptQueue = yield* Queue.unbounded<PromptQueueItem>();
|
||||
const prompt = Stream.fromQueue(promptQueue).pipe(
|
||||
@@ -1998,6 +2297,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
);
|
||||
|
||||
const answersDeferred = yield* Deferred.make<ProviderUserInputAnswers>();
|
||||
let aborted = false;
|
||||
const pendingInput: PendingUserInput = {
|
||||
questions,
|
||||
answers: answersDeferred,
|
||||
@@ -2031,6 +2331,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
if (!pendingUserInputs.has(requestId)) {
|
||||
return;
|
||||
}
|
||||
aborted = true;
|
||||
pendingUserInputs.delete(requestId);
|
||||
Effect.runFork(Deferred.succeed(answersDeferred, {} as ProviderUserInputAnswers));
|
||||
};
|
||||
@@ -2061,6 +2362,13 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
},
|
||||
});
|
||||
|
||||
if (aborted) {
|
||||
return {
|
||||
behavior: "deny",
|
||||
message: "User cancelled tool execution.",
|
||||
} satisfies PermissionResult;
|
||||
}
|
||||
|
||||
// Return the answers to the SDK in the expected format:
|
||||
// { questions: [...], answers: { questionText: selectedLabel } }
|
||||
return {
|
||||
@@ -2090,6 +2398,28 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
return yield* handleAskUserQuestion(context, toolInput, callbackOptions);
|
||||
}
|
||||
|
||||
if (toolName === "ExitPlanMode") {
|
||||
const planMarkdown = extractExitPlanModePlan(toolInput);
|
||||
if (planMarkdown) {
|
||||
yield* emitProposedPlanCompleted(context, {
|
||||
planMarkdown,
|
||||
toolUseId: callbackOptions.toolUseID,
|
||||
rawSource: "claude.sdk.permission",
|
||||
rawMethod: "canUseTool/ExitPlanMode",
|
||||
rawPayload: {
|
||||
toolName,
|
||||
input: toolInput,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
behavior: "deny",
|
||||
message:
|
||||
"The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.",
|
||||
} satisfies PermissionResult;
|
||||
}
|
||||
|
||||
const runtimeMode = input.runtimeMode ?? "full-access";
|
||||
if (runtimeMode === "full-access") {
|
||||
return {
|
||||
@@ -2237,9 +2567,8 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
const queryOptions: ClaudeQueryOptions = {
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
...(providerOptions?.binaryPath
|
||||
? { pathToClaudeCodeExecutable: providerOptions.binaryPath }
|
||||
: {}),
|
||||
pathToClaudeCodeExecutable: providerOptions?.binaryPath ?? "claude",
|
||||
settingSources: [...CLAUDE_SETTING_SOURCES],
|
||||
...(effectiveEffort ? { effort: effectiveEffort } : {}),
|
||||
...(permissionMode ? { permissionMode } : {}),
|
||||
...(permissionMode === "bypassPermissions"
|
||||
@@ -2249,8 +2578,8 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
? { maxThinkingTokens: providerOptions.maxThinkingTokens }
|
||||
: {}),
|
||||
...(Object.keys(settings).length > 0 ? { settings } : {}),
|
||||
...(resumeState?.resume ? { resume: resumeState.resume } : {}),
|
||||
...(resumeState?.resumeSessionAt ? { resumeSessionAt: resumeState.resumeSessionAt } : {}),
|
||||
...(existingResumeSessionId ? { resume: existingResumeSessionId } : {}),
|
||||
...(newSessionId ? { sessionId: newSessionId } : {}),
|
||||
includePartialMessages: true,
|
||||
canUseTool,
|
||||
env: process.env,
|
||||
@@ -2282,7 +2611,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
...(threadId ? { threadId } : {}),
|
||||
resumeCursor: {
|
||||
...(threadId ? { threadId } : {}),
|
||||
...(resumeState?.resume ? { resume: resumeState.resume } : {}),
|
||||
...(sessionId ? { resume: sessionId } : {}),
|
||||
...(resumeState?.resumeSessionAt
|
||||
? { resumeSessionAt: resumeState.resumeSessionAt }
|
||||
: {}),
|
||||
@@ -2296,9 +2625,10 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
session,
|
||||
promptQueue,
|
||||
query: queryRuntime,
|
||||
streamFiber: undefined,
|
||||
startedAt,
|
||||
basePermissionMode: permissionMode,
|
||||
resumeSessionId: resumeState?.resume,
|
||||
resumeSessionId: sessionId,
|
||||
pendingApprovals,
|
||||
pendingUserInputs,
|
||||
turns: [],
|
||||
@@ -2357,7 +2687,17 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
providerRefs: {},
|
||||
});
|
||||
|
||||
Effect.runFork(runSdkStream(context));
|
||||
const streamFiber = Effect.runFork(runSdkStream(context));
|
||||
context.streamFiber = streamFiber;
|
||||
streamFiber.addObserver((exit) => {
|
||||
if (context.stopped) {
|
||||
return;
|
||||
}
|
||||
if (context.streamFiber === streamFiber) {
|
||||
context.streamFiber = undefined;
|
||||
}
|
||||
Effect.runFork(handleStreamExit(context, exit));
|
||||
});
|
||||
|
||||
return {
|
||||
...session,
|
||||
@@ -2405,6 +2745,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
items: [],
|
||||
assistantTextBlocks: new Map(),
|
||||
assistantTextBlockOrder: [],
|
||||
capturedProposedPlanKeys: new Set(),
|
||||
nextSyntheticAssistantBlockIndex: -1,
|
||||
};
|
||||
|
||||
@@ -2429,7 +2770,10 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
providerRefs: {},
|
||||
});
|
||||
|
||||
const message = buildUserMessage(input);
|
||||
const message = yield* buildUserMessageEffect(input, {
|
||||
fileSystem,
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
});
|
||||
|
||||
yield* Queue.offer(context.promptQueue, {
|
||||
type: "message",
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { PassThrough } from "node:stream";
|
||||
import { query, type SpawnOptions, type SpawnedProcess } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
async function* emptyPrompt(): AsyncGenerator<never, void, void> {}
|
||||
|
||||
class FakeClaudeCodeProcess implements SpawnedProcess {
|
||||
readonly stdin = new PassThrough();
|
||||
readonly stdout = new PassThrough();
|
||||
killed = false;
|
||||
exitCode: number | null = null;
|
||||
|
||||
private readonly events = new EventEmitter();
|
||||
private bufferedInput = "";
|
||||
|
||||
constructor(
|
||||
private readonly onMessage: (
|
||||
message: Record<string, unknown>,
|
||||
process: FakeClaudeCodeProcess,
|
||||
) => void,
|
||||
) {
|
||||
this.stdin.setEncoding("utf8");
|
||||
this.stdin.on("data", (chunk: string) => {
|
||||
this.bufferedInput += chunk;
|
||||
this.drainInput();
|
||||
});
|
||||
}
|
||||
|
||||
emitJson(message: unknown): void {
|
||||
this.stdout.write(`${JSON.stringify(message)}\n`);
|
||||
}
|
||||
|
||||
kill(_signal: NodeJS.Signals): boolean {
|
||||
this.killed = true;
|
||||
this.exitCode = 0;
|
||||
this.stdout.end();
|
||||
this.events.emit("exit", 0, null);
|
||||
return true;
|
||||
}
|
||||
|
||||
on(
|
||||
event: "exit" | "error",
|
||||
listener:
|
||||
| ((code: number | null, signal: NodeJS.Signals | null) => void)
|
||||
| ((error: Error) => void),
|
||||
): void {
|
||||
this.events.on(event, listener);
|
||||
}
|
||||
|
||||
once(
|
||||
event: "exit" | "error",
|
||||
listener:
|
||||
| ((code: number | null, signal: NodeJS.Signals | null) => void)
|
||||
| ((error: Error) => void),
|
||||
): void {
|
||||
this.events.once(event, listener);
|
||||
}
|
||||
|
||||
off(
|
||||
event: "exit" | "error",
|
||||
listener:
|
||||
| ((code: number | null, signal: NodeJS.Signals | null) => void)
|
||||
| ((error: Error) => void),
|
||||
): void {
|
||||
this.events.off(event, listener);
|
||||
}
|
||||
|
||||
private drainInput(): void {
|
||||
while (true) {
|
||||
const newlineIndex = this.bufferedInput.indexOf("\n");
|
||||
if (newlineIndex === -1) {
|
||||
return;
|
||||
}
|
||||
const line = this.bufferedInput.slice(0, newlineIndex).trim();
|
||||
this.bufferedInput = this.bufferedInput.slice(newlineIndex + 1);
|
||||
if (line.length === 0) {
|
||||
continue;
|
||||
}
|
||||
this.onMessage(JSON.parse(line) as Record<string, unknown>, this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe("Claude SDK fast mode probe", () => {
|
||||
let activeQuery: ReturnType<typeof query> | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
activeQuery?.close();
|
||||
activeQuery = null;
|
||||
});
|
||||
|
||||
it("passes fast mode through the SDK settings flag", async () => {
|
||||
let spawnOptions: SpawnOptions | undefined;
|
||||
|
||||
activeQuery = query({
|
||||
prompt: emptyPrompt(),
|
||||
options: {
|
||||
persistSession: false,
|
||||
settings: {
|
||||
fastMode: true,
|
||||
},
|
||||
spawnClaudeCodeProcess: (options): SpawnedProcess => {
|
||||
spawnOptions = options;
|
||||
return new FakeClaudeCodeProcess((message, process) => {
|
||||
if (
|
||||
message.type !== "control_request" ||
|
||||
typeof message.request_id !== "string" ||
|
||||
!message.request ||
|
||||
typeof message.request !== "object" ||
|
||||
(message.request as { subtype?: unknown }).subtype !== "initialize"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.emitJson({
|
||||
type: "control_response",
|
||||
response: {
|
||||
subtype: "success",
|
||||
request_id: message.request_id,
|
||||
response: {
|
||||
commands: [],
|
||||
agents: [],
|
||||
output_style: "default",
|
||||
available_output_styles: ["default"],
|
||||
models: [],
|
||||
account: {
|
||||
subscriptionType: "max",
|
||||
},
|
||||
fast_mode_state: "on",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const initialization = await activeQuery.initializationResult();
|
||||
expect(initialization.fast_mode_state).toBe("on");
|
||||
|
||||
expect(spawnOptions).toBeDefined();
|
||||
const settingsFlagIndex = spawnOptions?.args.indexOf("--settings") ?? -1;
|
||||
expect(settingsFlagIndex).toBeGreaterThan(-1);
|
||||
expect(JSON.parse(spawnOptions?.args[settingsFlagIndex + 1] ?? "")).toEqual({
|
||||
fastMode: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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) {
|
||||
|
||||
@@ -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,
|
||||
@@ -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);
|
||||
@@ -716,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();
|
||||
@@ -733,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",
|
||||
@@ -746,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);
|
||||
@@ -772,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",
|
||||
@@ -836,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,7 +88,12 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
|
||||
|
||||
function toRuntimePayloadFromSession(
|
||||
session: ProviderSession,
|
||||
extra?: { readonly modelOptions?: unknown; readonly providerOptions?: unknown },
|
||||
extra?: {
|
||||
readonly modelOptions?: unknown;
|
||||
readonly providerOptions?: unknown;
|
||||
readonly lastRuntimeEvent?: string;
|
||||
readonly lastRuntimeEventAt?: string;
|
||||
},
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
cwd: session.cwd ?? null,
|
||||
@@ -97,6 +102,10 @@ function toRuntimePayloadFromSession(
|
||||
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 }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -162,7 +171,12 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const upsertSessionBinding = (
|
||||
session: ProviderSession,
|
||||
threadId: ThreadId,
|
||||
extra?: { readonly modelOptions?: unknown; readonly providerOptions?: unknown },
|
||||
extra?: {
|
||||
readonly modelOptions?: unknown;
|
||||
readonly providerOptions?: unknown;
|
||||
readonly lastRuntimeEvent?: string;
|
||||
readonly lastRuntimeEventAt?: string;
|
||||
},
|
||||
) =>
|
||||
directory.upsert({
|
||||
threadId,
|
||||
@@ -177,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);
|
||||
|
||||
@@ -295,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(
|
||||
@@ -513,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(
|
||||
|
||||
@@ -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";
|
||||
@@ -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",
|
||||
});
|
||||
@@ -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.10'
|
||||
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";
|
||||
|
||||
@@ -64,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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -87,3 +117,107 @@ describe("provider-specific custom models", () => {
|
||||
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: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
+120
-52
@@ -1,43 +1,61 @@
|
||||
import { useCallback } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { TrimmedNonEmptyString, type ProviderKind } from "@t3tools/contracts";
|
||||
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
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";
|
||||
type CustomModelSettingsKey = "customCodexModels" | "customClaudeModels";
|
||||
export type ProviderCustomModelConfig = {
|
||||
provider: ProviderKind;
|
||||
settingsKey: CustomModelSettingsKey;
|
||||
defaultSettingsKey: CustomModelSettingsKey;
|
||||
title: string;
|
||||
description: string;
|
||||
placeholder: string;
|
||||
example: string;
|
||||
};
|
||||
|
||||
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
|
||||
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
|
||||
claudeAgent: new Set(getModelOptions("claudeAgent").map((option) => option.slug)),
|
||||
};
|
||||
|
||||
const AppSettingsSchema = Schema.Struct({
|
||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some("")),
|
||||
),
|
||||
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some("")),
|
||||
),
|
||||
defaultThreadEnvMode: Schema.Literals(["local", "worktree"]).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some("local")),
|
||||
),
|
||||
confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))),
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(false)),
|
||||
),
|
||||
timestampFormat: Schema.Literals(["locale", "12-hour", "24-hour"]).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(DEFAULT_TIMESTAMP_FORMAT)),
|
||||
),
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
customClaudeModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
const withDefaults =
|
||||
<
|
||||
S extends Schema.Top & Schema.WithoutConstructorDefault,
|
||||
D extends S["~type.make.in"] & S["Encoded"],
|
||||
>(
|
||||
fallback: () => D,
|
||||
) =>
|
||||
(schema: S) =>
|
||||
schema.pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(fallback())),
|
||||
Schema.withDecodingDefault(() => fallback()),
|
||||
);
|
||||
|
||||
export const AppSettingsSchema = Schema.Struct({
|
||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
|
||||
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
|
||||
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;
|
||||
@@ -48,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>,
|
||||
@@ -85,6 +124,39 @@ function normalizeAppSettings(settings: AppSettings): AppSettings {
|
||||
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[],
|
||||
@@ -96,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)) {
|
||||
@@ -111,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,
|
||||
@@ -124,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;
|
||||
|
||||
@@ -752,6 +752,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModel: null,
|
||||
stickyModelOptions: {},
|
||||
});
|
||||
useStore.setState({
|
||||
projects: [],
|
||||
@@ -1279,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,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
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 {
|
||||
@@ -121,16 +120,6 @@ export function cloneComposerImageForRetry(
|
||||
}
|
||||
}
|
||||
|
||||
export function getCustomModelOptionsByProvider(settings: {
|
||||
customCodexModels: readonly string[];
|
||||
customClaudeModels: readonly string[];
|
||||
}): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
|
||||
return {
|
||||
codex: getAppModelOptions("codex", settings.customCodexModels),
|
||||
claudeAgent: getAppModelOptions("claudeAgent", settings.customClaudeModels),
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveComposerSendState(options: {
|
||||
prompt: string;
|
||||
imageCount: number;
|
||||
|
||||
@@ -24,15 +24,8 @@ import {
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getDefaultModel,
|
||||
getDefaultReasoningEffort,
|
||||
getReasoningEffortOptions,
|
||||
isClaudeUltrathinkPrompt,
|
||||
normalizeClaudeModelOptions,
|
||||
normalizeCodexModelOptions,
|
||||
normalizeModelSlug,
|
||||
resolveReasoningEffortForProvider,
|
||||
resolveModelSlugForProvider,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
} from "@t3tools/shared/model";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
@@ -126,7 +119,12 @@ import {
|
||||
import { SidebarTrigger } from "./ui/sidebar";
|
||||
import { newCommandId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
import { resolveAppModelSelection, useAppSettings } from "../appSettings";
|
||||
import {
|
||||
getCustomModelOptionsByProvider,
|
||||
getCustomModelsByProvider,
|
||||
resolveAppModelSelection,
|
||||
useAppSettings,
|
||||
} from "../appSettings";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import {
|
||||
type ComposerImageAttachment,
|
||||
@@ -153,12 +151,15 @@ import { buildExpandedImagePreview, ExpandedImagePreview } from "./chat/Expanded
|
||||
import { AVAILABLE_PROVIDER_OPTIONS, ProviderModelPicker } from "./chat/ProviderModelPicker";
|
||||
import { ComposerCommandItem, ComposerCommandMenu } from "./chat/ComposerCommandMenu";
|
||||
import { ComposerPendingApprovalActions } from "./chat/ComposerPendingApprovalActions";
|
||||
import { ClaudeTraitsMenuContent, ClaudeTraitsPicker } from "./chat/ClaudeTraitsPicker";
|
||||
import { CodexTraitsMenuContent, CodexTraitsPicker } from "./chat/CodexTraitsPicker";
|
||||
import { CompactComposerControlsMenu } from "./chat/CompactComposerControlsMenu";
|
||||
import { ComposerPendingApprovalPanel } from "./chat/ComposerPendingApprovalPanel";
|
||||
import { ComposerPendingUserInputPanel } from "./chat/ComposerPendingUserInputPanel";
|
||||
import { ComposerPlanFollowUpBanner } from "./chat/ComposerPlanFollowUpBanner";
|
||||
import {
|
||||
getComposerProviderState,
|
||||
renderProviderTraitsMenuContent,
|
||||
renderProviderTraitsPicker,
|
||||
} from "./chat/composerProviderRegistry";
|
||||
import { ProviderHealthBanner } from "./chat/ProviderHealthBanner";
|
||||
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
|
||||
import {
|
||||
@@ -168,7 +169,6 @@ import {
|
||||
cloneComposerImageForRetry,
|
||||
collectUserMessageBlobPreviewUrls,
|
||||
deriveComposerSendState,
|
||||
getCustomModelOptionsByProvider,
|
||||
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
|
||||
LastInvokedScriptByProjectSchema,
|
||||
PullRequestDialogState,
|
||||
@@ -244,6 +244,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const setStoreThreadError = useStore((store) => store.setError);
|
||||
const setStoreThreadBranch = useStore((store) => store.setThreadBranch);
|
||||
const { settings } = useAppSettings();
|
||||
const setStickyComposerModel = useComposerDraftStore((store) => store.setStickyModel);
|
||||
const timestampFormat = settings.timestampFormat;
|
||||
const navigate = useNavigate();
|
||||
const rawSearch = useSearch({
|
||||
@@ -596,72 +597,27 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
selectedProvider,
|
||||
activeThread?.model ?? activeProject?.model ?? getDefaultModel(selectedProvider),
|
||||
);
|
||||
const customModelsByProvider = useMemo(
|
||||
() => ({
|
||||
codex: settings.customCodexModels,
|
||||
claudeAgent: settings.customClaudeModels,
|
||||
}),
|
||||
[settings.customClaudeModels, settings.customCodexModels],
|
||||
);
|
||||
const customModelsForSelectedProvider = customModelsByProvider[selectedProvider];
|
||||
const customModelsByProvider = useMemo(() => getCustomModelsByProvider(settings), [settings]);
|
||||
const selectedModel = useMemo(() => {
|
||||
const draftModel = composerDraft.model;
|
||||
if (!draftModel) {
|
||||
return baseThreadModel;
|
||||
}
|
||||
return resolveAppModelSelection(
|
||||
selectedProvider,
|
||||
customModelsForSelectedProvider,
|
||||
draftModel,
|
||||
) as ModelSlug;
|
||||
}, [baseThreadModel, composerDraft.model, customModelsForSelectedProvider, selectedProvider]);
|
||||
return resolveAppModelSelection(selectedProvider, customModelsByProvider, draftModel);
|
||||
}, [baseThreadModel, composerDraft.model, customModelsByProvider, selectedProvider]);
|
||||
const draftModelOptions = composerDraft.modelOptions;
|
||||
const selectedCodexEffort =
|
||||
selectedProvider === "codex"
|
||||
? (resolveReasoningEffortForProvider("codex", draftModelOptions?.codex?.reasoningEffort) ??
|
||||
getDefaultReasoningEffort("codex"))
|
||||
: null;
|
||||
const selectedClaudeReasoningOptions =
|
||||
selectedProvider === "claudeAgent"
|
||||
? getReasoningEffortOptions("claudeAgent", selectedModel)
|
||||
: ([] as const);
|
||||
const selectedClaudeBaseEffort =
|
||||
selectedProvider === "claudeAgent" && selectedClaudeReasoningOptions.length > 0
|
||||
? (() => {
|
||||
const draftEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
draftModelOptions?.claudeAgent?.effort,
|
||||
);
|
||||
if (
|
||||
draftEffort &&
|
||||
draftEffort !== "ultrathink" &&
|
||||
selectedClaudeReasoningOptions.includes(draftEffort)
|
||||
) {
|
||||
return draftEffort;
|
||||
}
|
||||
const defaultEffort = getDefaultReasoningEffort("claudeAgent");
|
||||
return selectedClaudeReasoningOptions.includes(defaultEffort) ? defaultEffort : null;
|
||||
})()
|
||||
: null;
|
||||
const isClaudeUltrathink =
|
||||
selectedProvider === "claudeAgent" &&
|
||||
supportsClaudeUltrathinkKeyword(selectedModel) &&
|
||||
isClaudeUltrathinkPrompt(prompt);
|
||||
const selectedPromptEffort = selectedCodexEffort ?? selectedClaudeBaseEffort;
|
||||
const selectedModelOptionsForDispatch = useMemo(() => {
|
||||
if (selectedProvider === "codex") {
|
||||
const codexOptions = normalizeCodexModelOptions(draftModelOptions?.codex);
|
||||
return codexOptions ? { codex: codexOptions } : undefined;
|
||||
}
|
||||
if (selectedProvider === "claudeAgent") {
|
||||
const claudeOptions = normalizeClaudeModelOptions(
|
||||
selectedModel,
|
||||
draftModelOptions?.claudeAgent,
|
||||
);
|
||||
return claudeOptions ? { claudeAgent: claudeOptions } : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}, [draftModelOptions, selectedModel, selectedProvider]);
|
||||
const composerProviderState = useMemo(
|
||||
() =>
|
||||
getComposerProviderState({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
prompt,
|
||||
modelOptions: draftModelOptions,
|
||||
}),
|
||||
[draftModelOptions, prompt, selectedModel, selectedProvider],
|
||||
);
|
||||
const selectedPromptEffort = composerProviderState.promptEffort;
|
||||
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
|
||||
const providerOptionsForDispatch = useMemo(() => {
|
||||
if (!settings.codexBinaryPath && !settings.codexHomePath) {
|
||||
return undefined;
|
||||
@@ -1149,10 +1105,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
|
||||
const availableEditors = serverConfigQuery.data?.availableEditors ?? EMPTY_AVAILABLE_EDITORS;
|
||||
const providerStatuses = serverConfigQuery.data?.providers ?? EMPTY_PROVIDER_STATUSES;
|
||||
const activeProvider = activeThread?.session?.provider ?? "codex";
|
||||
const activeProviderStatus = useMemo(
|
||||
() => providerStatuses.find((status) => status.provider === activeProvider) ?? null,
|
||||
[activeProvider, providerStatuses],
|
||||
() => providerStatuses.find((status) => status.provider === selectedProvider) ?? null,
|
||||
[selectedProvider, providerStatuses],
|
||||
);
|
||||
const activeProjectCwd = activeProject?.cwd ?? null;
|
||||
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
|
||||
@@ -3141,20 +3096,20 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
const resolvedModel = resolveAppModelSelection(provider, customModelsByProvider, model);
|
||||
setComposerDraftProvider(activeThread.id, provider);
|
||||
setComposerDraftModel(
|
||||
activeThread.id,
|
||||
resolveAppModelSelection(provider, customModelsByProvider[provider], model),
|
||||
);
|
||||
setComposerDraftModel(activeThread.id, resolvedModel);
|
||||
setStickyComposerModel(resolvedModel);
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
customModelsByProvider,
|
||||
lockedProvider,
|
||||
scheduleComposerFocus,
|
||||
setComposerDraftModel,
|
||||
setComposerDraftProvider,
|
||||
setStickyComposerModel,
|
||||
customModelsByProvider,
|
||||
],
|
||||
);
|
||||
const setPromptFromTraits = useCallback(
|
||||
@@ -3173,6 +3128,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
},
|
||||
[scheduleComposerFocus, setPrompt],
|
||||
);
|
||||
const providerTraitsMenuContent = renderProviderTraitsMenuContent({
|
||||
provider: selectedProvider,
|
||||
threadId,
|
||||
model: selectedModel,
|
||||
onPromptChange: setPromptFromTraits,
|
||||
});
|
||||
const providerTraitsPicker = renderProviderTraitsPicker({
|
||||
provider: selectedProvider,
|
||||
threadId,
|
||||
model: selectedModel,
|
||||
onPromptChange: setPromptFromTraits,
|
||||
});
|
||||
const onEnvModeChange = useCallback(
|
||||
(mode: DraftThreadEnvMode) => {
|
||||
if (isLocalDraftThread) {
|
||||
@@ -3586,7 +3553,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => scrollMessagesToBottom("smooth")}
|
||||
className="pointer-events-auto flex items-center gap-1.5 rounded-full border border-border/60 bg-card px-3 py-1 text-muted-foreground text-xs shadow-sm transition-colors hover:bg-accent hover:text-accent-foreground"
|
||||
className="pointer-events-auto flex items-center gap-1.5 rounded-full border border-border/60 bg-card px-3 py-1 text-muted-foreground text-xs shadow-sm transition-colors hover:border-border hover:text-foreground hover:cursor-pointer"
|
||||
>
|
||||
<ChevronDownIcon className="size-3.5" />
|
||||
Scroll to bottom
|
||||
@@ -3606,7 +3573,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
<div
|
||||
className={cn(
|
||||
"group rounded-[22px] p-px transition-colors duration-200",
|
||||
isClaudeUltrathink ? "ultrathink-frame" : undefined,
|
||||
composerProviderState.composerFrameClassName,
|
||||
)}
|
||||
onDragEnter={onComposerDragEnter}
|
||||
onDragOver={onComposerDragOver}
|
||||
@@ -3617,7 +3584,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
className={cn(
|
||||
"rounded-[20px] border bg-card transition-colors duration-200 focus-within:border-ring/45",
|
||||
isDragOverComposer ? "border-primary/70 bg-accent/30" : "border-border",
|
||||
isClaudeUltrathink ? "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]" : "",
|
||||
composerProviderState.composerSurfaceClassName,
|
||||
)}
|
||||
>
|
||||
{activePendingApproval ? (
|
||||
@@ -3806,7 +3773,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
model={selectedModelForPickerWithCustomFallback}
|
||||
lockedProvider={lockedProvider}
|
||||
modelOptionsByProvider={modelOptionsByProvider}
|
||||
ultrathinkActive={isClaudeUltrathink}
|
||||
{...(composerProviderState.modelPickerIconClassName
|
||||
? {
|
||||
activeProviderIconClassName:
|
||||
composerProviderState.modelPickerIconClassName,
|
||||
}
|
||||
: {})}
|
||||
onProviderModelChange={onProviderModelSelect}
|
||||
/>
|
||||
|
||||
@@ -3818,42 +3790,20 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
interactionMode={interactionMode}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
traitsMenuContent={
|
||||
selectedProvider === "codex" ? (
|
||||
<CodexTraitsMenuContent threadId={threadId} />
|
||||
) : selectedProvider === "claudeAgent" ? (
|
||||
<ClaudeTraitsMenuContent
|
||||
threadId={threadId}
|
||||
model={selectedModel}
|
||||
onPromptChange={setPromptFromTraits}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
traitsMenuContent={providerTraitsMenuContent}
|
||||
onToggleInteractionMode={toggleInteractionMode}
|
||||
onTogglePlanSidebar={togglePlanSidebar}
|
||||
onToggleRuntimeMode={toggleRuntimeMode}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{selectedProvider === "codex" ? (
|
||||
{providerTraitsPicker ? (
|
||||
<>
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="mx-0.5 hidden h-4 sm:block"
|
||||
/>
|
||||
<CodexTraitsPicker threadId={threadId} />
|
||||
</>
|
||||
) : selectedProvider === "claudeAgent" ? (
|
||||
<>
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="mx-0.5 hidden h-4 sm:block"
|
||||
/>
|
||||
<ClaudeTraitsPicker
|
||||
threadId={threadId}
|
||||
model={selectedModel}
|
||||
onPromptChange={setPromptFromTraits}
|
||||
/>
|
||||
{providerTraitsPicker}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
hasUnseenCompletion,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
@@ -230,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" });
|
||||
});
|
||||
});
|
||||
@@ -22,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"
|
||||
@@ -151,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,
|
||||
@@ -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;
|
||||
@@ -1230,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 && (
|
||||
@@ -1339,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}>
|
||||
@@ -1368,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}
|
||||
@@ -1672,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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -173,4 +173,25 @@ describe("ClaudeTraitsPicker", () => {
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
ProviderKind,
|
||||
type ClaudeCodeEffort,
|
||||
type ClaudeModelOptions,
|
||||
type ProviderModelOptions,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
isClaudeUltrathinkPrompt,
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useState } from "react";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
@@ -29,6 +29,8 @@ import {
|
||||
} 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",
|
||||
@@ -51,12 +53,12 @@ function getSelectedClaudeTraits(
|
||||
ultrathinkPromptControlled: boolean;
|
||||
supportsFastMode: boolean;
|
||||
} {
|
||||
const options = getReasoningEffortOptions("claudeAgent", model);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("claudeAgent") as Exclude<
|
||||
const options = getReasoningEffortOptions(PROVIDER, model);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER) as Exclude<
|
||||
ClaudeCodeEffort,
|
||||
"ultrathink"
|
||||
>;
|
||||
const resolvedEffort = resolveReasoningEffortForProvider("claudeAgent", modelOptions?.effort);
|
||||
const resolvedEffort = resolveReasoningEffortForProvider(PROVIDER, modelOptions?.effort);
|
||||
const effort =
|
||||
resolvedEffort && resolvedEffort !== "ultrathink" && options.includes(resolvedEffort)
|
||||
? resolvedEffort
|
||||
@@ -78,15 +80,21 @@ function getSelectedClaudeTraits(
|
||||
};
|
||||
}
|
||||
|
||||
function ClaudeTraitsMenuContentImpl(props: {
|
||||
interface ClaudeTraitsMenuContentProps {
|
||||
threadId: ThreadId;
|
||||
model: string | null | undefined;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}) {
|
||||
const draft = useComposerThreadDraft(props.threadId);
|
||||
}
|
||||
|
||||
export const ClaudeTraitsMenuContent = memo(function ClaudeTraitsMenuContentImpl({
|
||||
threadId,
|
||||
model,
|
||||
onPromptChange,
|
||||
}: ClaudeTraitsMenuContentProps) {
|
||||
const draft = useComposerThreadDraft(threadId);
|
||||
const prompt = draft.prompt;
|
||||
const modelOptions = draft.modelOptions?.claudeAgent;
|
||||
const setModelOptions = useComposerDraftStore((store) => store.setModelOptions);
|
||||
const modelOptions = draft.modelOptions?.[PROVIDER];
|
||||
const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
|
||||
const {
|
||||
effort,
|
||||
thinkingEnabled,
|
||||
@@ -94,19 +102,44 @@ function ClaudeTraitsMenuContentImpl(props: {
|
||||
options,
|
||||
ultrathinkPromptControlled,
|
||||
supportsFastMode,
|
||||
} = getSelectedClaudeTraits(props.model, prompt, modelOptions);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("claudeAgent");
|
||||
} = getSelectedClaudeTraits(model, prompt, modelOptions);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER);
|
||||
|
||||
const setClaudeModelOptions = (nextClaudeModelOptions: ClaudeModelOptions | undefined) => {
|
||||
const { claudeAgent: _discardedClaude, ...otherProviderModelOptions } =
|
||||
draft.modelOptions ?? {};
|
||||
const nextProviderModelOptions: ProviderModelOptions | undefined = nextClaudeModelOptions
|
||||
? { ...otherProviderModelOptions, claudeAgent: nextClaudeModelOptions }
|
||||
: Object.keys(otherProviderModelOptions).length > 0
|
||||
? otherProviderModelOptions
|
||||
: undefined;
|
||||
setModelOptions(props.threadId, nextProviderModelOptions);
|
||||
};
|
||||
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;
|
||||
@@ -123,29 +156,7 @@ function ClaudeTraitsMenuContentImpl(props: {
|
||||
Remove Ultrathink from the prompt to change effort.
|
||||
</div>
|
||||
) : null}
|
||||
<MenuRadioGroup
|
||||
value={effort}
|
||||
onValueChange={(value) => {
|
||||
if (ultrathinkPromptControlled) return;
|
||||
if (!value) return;
|
||||
const nextEffort = options.find((option) => option === value);
|
||||
if (!nextEffort) return;
|
||||
if (nextEffort === "ultrathink") {
|
||||
const nextPrompt =
|
||||
prompt.trim().length === 0
|
||||
? ULTRATHINK_PROMPT_PREFIX
|
||||
: applyClaudePromptEffortPrefix(prompt, "ultrathink");
|
||||
props.onPromptChange(nextPrompt);
|
||||
return;
|
||||
}
|
||||
setClaudeModelOptions(
|
||||
normalizeClaudeModelOptions(props.model, {
|
||||
...modelOptions,
|
||||
effort: nextEffort,
|
||||
}),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioGroup value={effort} onValueChange={handleEffortChange}>
|
||||
{options.map((option) => (
|
||||
<MenuRadioItem key={option} value={option} disabled={ultrathinkPromptControlled}>
|
||||
{CLAUDE_EFFORT_LABELS[option]}
|
||||
@@ -161,11 +172,14 @@ function ClaudeTraitsMenuContentImpl(props: {
|
||||
<MenuRadioGroup
|
||||
value={thinkingEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
setClaudeModelOptions(
|
||||
normalizeClaudeModelOptions(props.model, {
|
||||
setProviderModelOptions(
|
||||
threadId,
|
||||
PROVIDER,
|
||||
normalizeClaudeModelOptions(model, {
|
||||
...modelOptions,
|
||||
thinking: value === "on",
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -182,11 +196,14 @@ function ClaudeTraitsMenuContentImpl(props: {
|
||||
<MenuRadioGroup
|
||||
value={fastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
setClaudeModelOptions(
|
||||
normalizeClaudeModelOptions(props.model, {
|
||||
setProviderModelOptions(
|
||||
threadId,
|
||||
PROVIDER,
|
||||
normalizeClaudeModelOptions(model, {
|
||||
...modelOptions,
|
||||
fastMode: value === "on",
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -198,21 +215,19 @@ function ClaudeTraitsMenuContentImpl(props: {
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
export const ClaudeTraitsMenuContent = memo(ClaudeTraitsMenuContentImpl);
|
||||
|
||||
export const ClaudeTraitsPicker = memo(function ClaudeTraitsPicker(props: {
|
||||
threadId: ThreadId;
|
||||
model: string | null | undefined;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}) {
|
||||
export const ClaudeTraitsPicker = memo(function ClaudeTraitsPicker({
|
||||
threadId,
|
||||
model,
|
||||
onPromptChange,
|
||||
}: ClaudeTraitsMenuContentProps) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const draft = useComposerThreadDraft(props.threadId);
|
||||
const draft = useComposerThreadDraft(threadId);
|
||||
const prompt = draft.prompt;
|
||||
const modelOptions = draft.modelOptions?.claudeAgent;
|
||||
const modelOptions = draft.modelOptions?.[PROVIDER];
|
||||
const { effort, thinkingEnabled, fastModeEnabled, ultrathinkPromptControlled, supportsFastMode } =
|
||||
getSelectedClaudeTraits(props.model, prompt, modelOptions);
|
||||
getSelectedClaudeTraits(model, prompt, modelOptions);
|
||||
const triggerLabel = [
|
||||
ultrathinkPromptControlled
|
||||
? "Ultrathink"
|
||||
@@ -247,9 +262,9 @@ export const ClaudeTraitsPicker = memo(function ClaudeTraitsPicker(props: {
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
<ClaudeTraitsMenuContent
|
||||
threadId={props.threadId}
|
||||
model={props.model}
|
||||
onPromptChange={props.onPromptChange}
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
|
||||
@@ -116,6 +116,25 @@ describe("CodexTraitsPicker", () => {
|
||||
}
|
||||
});
|
||||
|
||||
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(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type {
|
||||
CodexModelOptions,
|
||||
CodexReasoningEffort,
|
||||
ProviderModelOptions,
|
||||
ProviderKind,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -24,6 +24,8 @@ import {
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
|
||||
const PROVIDER = "codex" as const satisfies ProviderKind;
|
||||
|
||||
const CODEX_REASONING_LABELS: Record<CodexReasoningEffort, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
@@ -35,10 +37,10 @@ function getSelectedCodexTraits(modelOptions: CodexModelOptions | null | undefin
|
||||
effort: CodexReasoningEffort;
|
||||
fastModeEnabled: boolean;
|
||||
} {
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("codex");
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER);
|
||||
return {
|
||||
effort:
|
||||
resolveReasoningEffortForProvider("codex", modelOptions?.reasoningEffort) ??
|
||||
resolveReasoningEffortForProvider(PROVIDER, modelOptions?.reasoningEffort) ??
|
||||
defaultReasoningEffort,
|
||||
fastModeEnabled: modelOptions?.fastMode === true,
|
||||
};
|
||||
@@ -46,22 +48,12 @@ function getSelectedCodexTraits(modelOptions: CodexModelOptions | null | undefin
|
||||
|
||||
function CodexTraitsMenuContentImpl(props: { threadId: ThreadId }) {
|
||||
const draft = useComposerThreadDraft(props.threadId);
|
||||
const modelOptions = draft.modelOptions?.codex;
|
||||
const setModelOptions = useComposerDraftStore((store) => store.setModelOptions);
|
||||
const options = getReasoningEffortOptions("codex");
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("codex");
|
||||
const modelOptions = draft.modelOptions?.[PROVIDER];
|
||||
const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
|
||||
const options = getReasoningEffortOptions(PROVIDER);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER);
|
||||
const { effort, fastModeEnabled } = getSelectedCodexTraits(modelOptions);
|
||||
|
||||
const setCodexModelOptions = (nextCodexModelOptions: CodexModelOptions | undefined) => {
|
||||
const { codex: _discardedCodex, ...otherProviderModelOptions } = draft.modelOptions ?? {};
|
||||
const nextProviderModelOptions: ProviderModelOptions | undefined = nextCodexModelOptions
|
||||
? { ...otherProviderModelOptions, codex: nextCodexModelOptions }
|
||||
: Object.keys(otherProviderModelOptions).length > 0
|
||||
? otherProviderModelOptions
|
||||
: undefined;
|
||||
setModelOptions(props.threadId, nextProviderModelOptions);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<MenuGroup>
|
||||
@@ -72,11 +64,14 @@ function CodexTraitsMenuContentImpl(props: { threadId: ThreadId }) {
|
||||
if (!value) return;
|
||||
const nextEffort = options.find((option) => option === value);
|
||||
if (!nextEffort) return;
|
||||
setCodexModelOptions(
|
||||
setProviderModelOptions(
|
||||
props.threadId,
|
||||
PROVIDER,
|
||||
normalizeCodexModelOptions({
|
||||
...modelOptions,
|
||||
reasoningEffort: nextEffort,
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -94,11 +89,14 @@ function CodexTraitsMenuContentImpl(props: { threadId: ThreadId }) {
|
||||
<MenuRadioGroup
|
||||
value={fastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
setCodexModelOptions(
|
||||
setProviderModelOptions(
|
||||
props.threadId,
|
||||
PROVIDER,
|
||||
normalizeCodexModelOptions({
|
||||
...modelOptions,
|
||||
fastMode: value === "on",
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -22,7 +22,7 @@ export const ProviderHealthBanner = memo(function ProviderHealthBanner({
|
||||
status.status === "error"
|
||||
? `${providerLabel} provider is unavailable.`
|
||||
: `${providerLabel} provider has limited availability.`;
|
||||
const title = providerLabel === "Codex" ? "Codex provider status" : `${providerLabel} status`;
|
||||
const title = `${providerLabel} provider status`;
|
||||
|
||||
return (
|
||||
<div className="pt-3 mx-auto max-w-3xl">
|
||||
|
||||
@@ -91,4 +91,24 @@ describe("ProviderModelPicker", () => {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("dispatches the canonical slug when a model is selected", async () => {
|
||||
const mounted = await mountPicker({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
lockedProvider: "claudeAgent",
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitemradio", { name: "Claude Sonnet 4.6" }).click();
|
||||
|
||||
expect(mounted.onProviderModelChange).toHaveBeenCalledWith(
|
||||
"claudeAgent",
|
||||
"claude-sonnet-4-6",
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { type ModelSlug, type ProviderKind } from "@t3tools/contracts";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { resolveSelectableModel } from "@t3tools/shared/model";
|
||||
import { memo, useState } from "react";
|
||||
import { type ProviderPickerKind, PROVIDER_OPTIONS } from "../../session-logic";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
@@ -28,39 +28,6 @@ function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): o
|
||||
return option.available;
|
||||
}
|
||||
|
||||
function resolveModelForProviderPicker(
|
||||
provider: ProviderKind,
|
||||
value: string,
|
||||
options: ReadonlyArray<{ slug: string; name: string }>,
|
||||
): ModelSlug | null {
|
||||
const trimmedValue = value.trim();
|
||||
if (!trimmedValue) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const direct = options.find((option) => option.slug === trimmedValue);
|
||||
if (direct) {
|
||||
return direct.slug;
|
||||
}
|
||||
|
||||
const byName = options.find((option) => option.name.toLowerCase() === trimmedValue.toLowerCase());
|
||||
if (byName) {
|
||||
return byName.slug;
|
||||
}
|
||||
|
||||
const normalized = normalizeModelSlug(trimmedValue, provider);
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const resolved = options.find((option) => option.slug === normalized);
|
||||
if (resolved) {
|
||||
return resolved.slug;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
const PROVIDER_ICON_BY_PROVIDER: Record<ProviderPickerKind, Icon> = {
|
||||
codex: OpenAI,
|
||||
claudeAgent: ClaudeAI,
|
||||
@@ -86,7 +53,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
model: ModelSlug;
|
||||
lockedProvider: ProviderKind | null;
|
||||
modelOptionsByProvider: Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>>;
|
||||
ultrathinkActive?: boolean;
|
||||
activeProviderIconClassName?: string;
|
||||
compact?: boolean;
|
||||
disabled?: boolean;
|
||||
onProviderModelChange: (provider: ProviderKind, model: ModelSlug) => void;
|
||||
@@ -100,7 +67,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
const handleModelChange = (provider: ProviderKind, value: string) => {
|
||||
if (props.disabled) return;
|
||||
if (!value) return;
|
||||
const resolvedModel = resolveModelForProviderPicker(
|
||||
const resolvedModel = resolveSelectableModel(
|
||||
provider,
|
||||
value,
|
||||
props.modelOptionsByProvider[provider],
|
||||
@@ -145,9 +112,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
providerIconClassName(activeProvider, "text-muted-foreground/70"),
|
||||
activeProvider === "claudeAgent" && props.ultrathinkActive
|
||||
? "ultrathink-chroma"
|
||||
: undefined,
|
||||
props.activeProviderIconClassName,
|
||||
)}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate">{selectedModelLabel}</span>
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getComposerProviderState } from "./composerProviderRegistry";
|
||||
|
||||
describe("getComposerProviderState", () => {
|
||||
it("returns codex defaults when no codex draft options exist", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
prompt: "",
|
||||
modelOptions: undefined,
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes codex dispatch options while preserving the selected effort", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "low",
|
||||
modelOptionsForDispatch: {
|
||||
codex: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("returns Claude defaults for effort-capable models", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
prompt: "",
|
||||
modelOptions: undefined,
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("tracks Claude ultrathink from the prompt without changing dispatch effort", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
prompt: "Ultrathink:\nInvestigate this failure",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "medium",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "medium",
|
||||
modelOptionsForDispatch: {
|
||||
claudeAgent: {
|
||||
effort: "medium",
|
||||
},
|
||||
},
|
||||
composerFrameClassName: "ultrathink-frame",
|
||||
composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]",
|
||||
modelPickerIconClassName: "ultrathink-chroma",
|
||||
});
|
||||
});
|
||||
|
||||
it("drops unsupported Claude effort options for models without effort controls", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
thinking: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "claudeAgent",
|
||||
promptEffort: null,
|
||||
modelOptionsForDispatch: {
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores codex options while resolving Claude state", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores Claude options while resolving codex state", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
prompt: "Ultrathink:\nThis should not matter",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import {
|
||||
type ModelSlug,
|
||||
type ProviderKind,
|
||||
type ProviderModelOptions,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getDefaultReasoningEffort,
|
||||
getReasoningEffortOptions,
|
||||
isClaudeUltrathinkPrompt,
|
||||
normalizeClaudeModelOptions,
|
||||
normalizeCodexModelOptions,
|
||||
resolveReasoningEffortForProvider,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
} from "@t3tools/shared/model";
|
||||
import type { ReactNode } from "react";
|
||||
import { ClaudeTraitsMenuContent, ClaudeTraitsPicker } from "./ClaudeTraitsPicker";
|
||||
import { CodexTraitsMenuContent, CodexTraitsPicker } from "./CodexTraitsPicker";
|
||||
|
||||
export type ComposerProviderStateInput = {
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
prompt: string;
|
||||
modelOptions: ProviderModelOptions | null | undefined;
|
||||
};
|
||||
|
||||
export type ComposerProviderState = {
|
||||
provider: ProviderKind;
|
||||
promptEffort: string | null;
|
||||
modelOptionsForDispatch: ProviderModelOptions | undefined;
|
||||
composerFrameClassName?: string;
|
||||
composerSurfaceClassName?: string;
|
||||
modelPickerIconClassName?: string;
|
||||
};
|
||||
|
||||
type ProviderRegistryEntry = {
|
||||
getState: (input: ComposerProviderStateInput) => ComposerProviderState;
|
||||
renderTraitsMenuContent: (input: {
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}) => ReactNode;
|
||||
renderTraitsPicker: (input: {
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}) => ReactNode;
|
||||
};
|
||||
|
||||
const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
|
||||
codex: {
|
||||
getState: ({ modelOptions }) => {
|
||||
const promptEffort =
|
||||
resolveReasoningEffortForProvider("codex", modelOptions?.codex?.reasoningEffort) ??
|
||||
getDefaultReasoningEffort("codex");
|
||||
const normalizedCodexOptions = normalizeCodexModelOptions(modelOptions?.codex);
|
||||
|
||||
return {
|
||||
provider: "codex",
|
||||
promptEffort,
|
||||
modelOptionsForDispatch: normalizedCodexOptions
|
||||
? { codex: normalizedCodexOptions }
|
||||
: undefined,
|
||||
};
|
||||
},
|
||||
renderTraitsMenuContent: ({ threadId }) => <CodexTraitsMenuContent threadId={threadId} />,
|
||||
renderTraitsPicker: ({ threadId }) => <CodexTraitsPicker threadId={threadId} />,
|
||||
},
|
||||
claudeAgent: {
|
||||
getState: ({ model, prompt, modelOptions }) => {
|
||||
const reasoningOptions = getReasoningEffortOptions("claudeAgent", model);
|
||||
const draftEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
modelOptions?.claudeAgent?.effort,
|
||||
);
|
||||
const defaultEffort = getDefaultReasoningEffort("claudeAgent");
|
||||
const promptEffort =
|
||||
draftEffort && draftEffort !== "ultrathink" && reasoningOptions.includes(draftEffort)
|
||||
? draftEffort
|
||||
: reasoningOptions.includes(defaultEffort)
|
||||
? defaultEffort
|
||||
: null;
|
||||
const normalizedClaudeOptions = normalizeClaudeModelOptions(model, modelOptions?.claudeAgent);
|
||||
const ultrathinkActive =
|
||||
supportsClaudeUltrathinkKeyword(model) && isClaudeUltrathinkPrompt(prompt);
|
||||
|
||||
return {
|
||||
provider: "claudeAgent",
|
||||
promptEffort,
|
||||
modelOptionsForDispatch: normalizedClaudeOptions
|
||||
? { claudeAgent: normalizedClaudeOptions }
|
||||
: undefined,
|
||||
...(ultrathinkActive ? { composerFrameClassName: "ultrathink-frame" } : {}),
|
||||
...(ultrathinkActive
|
||||
? { composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]" }
|
||||
: {}),
|
||||
...(ultrathinkActive ? { modelPickerIconClassName: "ultrathink-chroma" } : {}),
|
||||
};
|
||||
},
|
||||
renderTraitsMenuContent: ({ threadId, model, onPromptChange }) => (
|
||||
<ClaudeTraitsMenuContent threadId={threadId} model={model} onPromptChange={onPromptChange} />
|
||||
),
|
||||
renderTraitsPicker: ({ threadId, model, onPromptChange }) => (
|
||||
<ClaudeTraitsPicker threadId={threadId} model={model} onPromptChange={onPromptChange} />
|
||||
),
|
||||
},
|
||||
};
|
||||
|
||||
export function getComposerProviderState(input: ComposerProviderStateInput): ComposerProviderState {
|
||||
return composerProviderRegistry[input.provider].getState(input);
|
||||
}
|
||||
|
||||
export function renderProviderTraitsMenuContent(input: {
|
||||
provider: ProviderKind;
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}): ReactNode {
|
||||
return composerProviderRegistry[input.provider].renderTraitsMenuContent({
|
||||
threadId: input.threadId,
|
||||
model: input.model,
|
||||
onPromptChange: input.onPromptChange,
|
||||
});
|
||||
}
|
||||
|
||||
export function renderProviderTraitsPicker(input: {
|
||||
provider: ProviderKind;
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}): ReactNode {
|
||||
return composerProviderRegistry[input.provider].renderTraitsPicker({
|
||||
threadId: input.threadId,
|
||||
model: input.model,
|
||||
onPromptChange: input.onPromptChange,
|
||||
});
|
||||
}
|
||||
@@ -62,17 +62,23 @@ function makeTerminalContext(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function resetComposerDraftStore() {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModel: null,
|
||||
stickyModelOptions: {},
|
||||
});
|
||||
}
|
||||
|
||||
describe("composerDraftStore addImages", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-dedupe");
|
||||
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
|
||||
let revokeSpy: ReturnType<typeof vi.fn<(url: string) => void>>;
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
resetComposerDraftStore();
|
||||
originalRevokeObjectUrl = URL.revokeObjectURL;
|
||||
revokeSpy = vi.fn();
|
||||
URL.revokeObjectURL = revokeSpy;
|
||||
@@ -157,11 +163,7 @@ describe("composerDraftStore clearComposerContent", () => {
|
||||
let revokeSpy: ReturnType<typeof vi.fn<(url: string) => void>>;
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
resetComposerDraftStore();
|
||||
originalRevokeObjectUrl = URL.revokeObjectURL;
|
||||
revokeSpy = vi.fn();
|
||||
URL.revokeObjectURL = revokeSpy;
|
||||
@@ -423,11 +425,7 @@ describe("composerDraftStore project draft thread mapping", () => {
|
||||
const otherThreadId = ThreadId.makeUnsafe("thread-b");
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("stores and reads project draft thread ids via actions", () => {
|
||||
@@ -599,11 +597,7 @@ describe("composerDraftStore modelOptions", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-model-options");
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("stores provider-scoped model options in the draft", () => {
|
||||
@@ -642,17 +636,165 @@ describe("composerDraftStore modelOptions", () => {
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("replaces only the targeted provider model options", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
|
||||
store.setProviderModelOptions(
|
||||
threadId,
|
||||
"claudeAgent",
|
||||
{
|
||||
thinking: false,
|
||||
},
|
||||
{ persistSticky: true },
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("removes only the targeted provider entry when next options normalize empty", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
|
||||
store.setProviderModelOptions(threadId, "claudeAgent", {
|
||||
thinking: true,
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
});
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({});
|
||||
});
|
||||
|
||||
it("removes model options entirely when the last provider entry normalizes empty", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
|
||||
store.setProviderModelOptions(threadId, "codex", {
|
||||
reasoningEffort: "high",
|
||||
fastMode: false,
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("updates only the draft when sticky persistence is omitted", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setStickyModelOptions({
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
|
||||
store.setProviderModelOptions(threadId, "claudeAgent", {
|
||||
thinking: false,
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("updates only the draft when sticky persistence is disabled", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setStickyModelOptions({
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
store.setModelOptions(threadId, {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
|
||||
store.setProviderModelOptions(
|
||||
threadId,
|
||||
"claudeAgent",
|
||||
{
|
||||
thinking: false,
|
||||
},
|
||||
{ persistSticky: false },
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore setModel", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-model");
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("keeps explicit DEFAULT_MODEL overrides instead of coercing to null", () => {
|
||||
@@ -666,15 +808,51 @@ describe("composerDraftStore setModel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore sticky composer settings", () => {
|
||||
beforeEach(() => {
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("stores sticky model and codex model options", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setStickyModel("gpt-5.3-codex");
|
||||
store.setStickyModelOptions({
|
||||
codex: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState()).toMatchObject({
|
||||
stickyModel: "gpt-5.3-codex",
|
||||
stickyModelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes empty sticky model options", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setStickyModelOptions({
|
||||
codex: {
|
||||
fastMode: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore setProvider", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-provider");
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("persists provider-only selection even when prompt/model are empty", () => {
|
||||
@@ -699,11 +877,7 @@ describe("composerDraftStore runtime and interaction settings", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-settings");
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("stores runtime mode overrides in the composer draft", () => {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Equal from "effect/Equal";
|
||||
import { DeepMutable } from "effect/Types";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { getLocalStorageItem } from "./hooks/useLocalStorage";
|
||||
@@ -104,6 +105,8 @@ const PersistedComposerDraftStoreState = Schema.Struct({
|
||||
draftsByThreadId: Schema.Record(ThreadId, PersistedComposerThreadDraftState),
|
||||
draftThreadsByThreadId: Schema.Record(ThreadId, PersistedDraftThreadState),
|
||||
projectDraftThreadIdByProjectId: Schema.Record(ProjectId, ThreadId),
|
||||
stickyModel: Schema.NullOr(Schema.String),
|
||||
stickyModelOptions: ProviderModelOptions,
|
||||
});
|
||||
type PersistedComposerDraftStoreState = typeof PersistedComposerDraftStoreState.Type;
|
||||
|
||||
@@ -143,6 +146,8 @@ interface ComposerDraftStoreState {
|
||||
draftsByThreadId: Record<ThreadId, ComposerThreadDraftState>;
|
||||
draftThreadsByThreadId: Record<ThreadId, DraftThreadState>;
|
||||
projectDraftThreadIdByProjectId: Record<ProjectId, ThreadId>;
|
||||
stickyModel: string | null;
|
||||
stickyModelOptions: ProviderModelOptions;
|
||||
getDraftThreadByProjectId: (projectId: ProjectId) => ProjectDraftThread | null;
|
||||
getDraftThread: (threadId: ThreadId) => DraftThreadState | null;
|
||||
setProjectDraftThreadId: (
|
||||
@@ -172,6 +177,8 @@ interface ComposerDraftStoreState {
|
||||
clearProjectDraftThreadId: (projectId: ProjectId) => void;
|
||||
clearProjectDraftThreadById: (projectId: ProjectId, threadId: ThreadId) => void;
|
||||
clearDraftThread: (threadId: ThreadId) => void;
|
||||
setStickyModel: (model: string | null | undefined) => void;
|
||||
setStickyModelOptions: (modelOptions: ProviderModelOptions | null | undefined) => void;
|
||||
setPrompt: (threadId: ThreadId, prompt: string) => void;
|
||||
setTerminalContexts: (threadId: ThreadId, contexts: TerminalContextDraft[]) => void;
|
||||
setProvider: (threadId: ThreadId, provider: ProviderKind | null | undefined) => void;
|
||||
@@ -180,6 +187,14 @@ interface ComposerDraftStoreState {
|
||||
threadId: ThreadId,
|
||||
modelOptions: ProviderModelOptions | null | undefined,
|
||||
) => void;
|
||||
setProviderModelOptions: (
|
||||
threadId: ThreadId,
|
||||
provider: ProviderKind,
|
||||
nextProviderOptions: ProviderModelOptions[ProviderKind] | null | undefined,
|
||||
options?: {
|
||||
persistSticky?: boolean;
|
||||
},
|
||||
) => void;
|
||||
setRuntimeMode: (threadId: ThreadId, runtimeMode: RuntimeMode | null | undefined) => void;
|
||||
setInteractionMode: (
|
||||
threadId: ThreadId,
|
||||
@@ -207,11 +222,15 @@ interface ComposerDraftStoreState {
|
||||
clearThreadDraft: (threadId: ThreadId) => void;
|
||||
}
|
||||
|
||||
const EMPTY_PERSISTED_DRAFT_STORE_STATE: PersistedComposerDraftStoreState = {
|
||||
const EMPTY_PROVIDER_MODEL_OPTIONS = Object.freeze<ProviderModelOptions>({});
|
||||
|
||||
const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftStoreState>({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
};
|
||||
stickyModel: null,
|
||||
stickyModelOptions: EMPTY_PROVIDER_MODEL_OPTIONS,
|
||||
});
|
||||
|
||||
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
|
||||
const EMPTY_IDS: string[] = [];
|
||||
@@ -397,6 +416,24 @@ function normalizeProviderModelOptions(
|
||||
};
|
||||
}
|
||||
|
||||
function replaceProviderModelOptions(
|
||||
currentModelOptions: ProviderModelOptions | null | undefined,
|
||||
provider: ProviderKind,
|
||||
nextProviderOptions: ProviderModelOptions[ProviderKind] | null | undefined,
|
||||
): ProviderModelOptions | null {
|
||||
const { [provider]: _discardedProviderModelOptions, ...otherProviderModelOptions } =
|
||||
currentModelOptions ?? {};
|
||||
const normalizedNextProviderOptions = normalizeProviderModelOptions(
|
||||
{ [provider]: nextProviderOptions },
|
||||
provider,
|
||||
);
|
||||
|
||||
return normalizeProviderModelOptions({
|
||||
...otherProviderModelOptions,
|
||||
...(normalizedNextProviderOptions ? normalizedNextProviderOptions : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function revokeObjectPreviewUrl(previewUrl: string): void {
|
||||
if (typeof URL === "undefined") {
|
||||
return;
|
||||
@@ -674,6 +711,12 @@ function migratePersistedComposerDraftStoreState(
|
||||
const rawDraftMap = candidate.draftsByThreadId;
|
||||
const rawDraftThreadsByThreadId = candidate.draftThreadsByThreadId;
|
||||
const rawProjectDraftThreadIdByProjectId = candidate.projectDraftThreadIdByProjectId;
|
||||
const stickyModel =
|
||||
typeof candidate.stickyModel === "string"
|
||||
? (normalizeModelSlug(candidate.stickyModel, "codex") ?? null)
|
||||
: null;
|
||||
const stickyModelOptions =
|
||||
normalizeProviderModelOptions(candidate.stickyModelOptions) ?? EMPTY_PROVIDER_MODEL_OPTIONS;
|
||||
const { draftThreadsByThreadId, projectDraftThreadIdByProjectId } =
|
||||
normalizePersistedDraftThreads(rawDraftThreadsByThreadId, rawProjectDraftThreadIdByProjectId);
|
||||
const draftsByThreadId = normalizePersistedDraftsByThreadId(
|
||||
@@ -691,6 +734,8 @@ function migratePersistedComposerDraftStoreState(
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId,
|
||||
stickyModel,
|
||||
stickyModelOptions,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -744,6 +789,8 @@ function partializeComposerDraftStoreState(
|
||||
draftsByThreadId: persistedDraftsByThreadId,
|
||||
draftThreadsByThreadId: state.draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: state.projectDraftThreadIdByProjectId,
|
||||
stickyModel: state.stickyModel,
|
||||
stickyModelOptions: state.stickyModelOptions,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -759,6 +806,13 @@ function normalizeCurrentPersistedComposerDraftStoreState(
|
||||
normalizedPersistedState.draftThreadsByThreadId,
|
||||
normalizedPersistedState.projectDraftThreadIdByProjectId,
|
||||
);
|
||||
const stickyModel =
|
||||
typeof normalizedPersistedState.stickyModel === "string"
|
||||
? (normalizeModelSlug(normalizedPersistedState.stickyModel, "codex") ?? null)
|
||||
: null;
|
||||
const stickyModelOptions =
|
||||
normalizeProviderModelOptions(normalizedPersistedState.stickyModelOptions) ??
|
||||
EMPTY_PROVIDER_MODEL_OPTIONS;
|
||||
return {
|
||||
draftsByThreadId: normalizePersistedDraftsByThreadId(
|
||||
normalizedPersistedState.draftsByThreadId,
|
||||
@@ -767,6 +821,8 @@ function normalizeCurrentPersistedComposerDraftStoreState(
|
||||
),
|
||||
draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId,
|
||||
stickyModel,
|
||||
stickyModelOptions,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -790,6 +846,53 @@ function readPersistedAttachmentIdsFromStorage(threadId: ThreadId): string[] {
|
||||
}
|
||||
}
|
||||
|
||||
function verifyPersistedAttachments(
|
||||
threadId: ThreadId,
|
||||
attachments: PersistedComposerImageAttachment[],
|
||||
set: (
|
||||
partial:
|
||||
| ComposerDraftStoreState
|
||||
| Partial<ComposerDraftStoreState>
|
||||
| ((
|
||||
state: ComposerDraftStoreState,
|
||||
) => ComposerDraftStoreState | Partial<ComposerDraftStoreState>),
|
||||
replace?: false,
|
||||
) => void,
|
||||
): void {
|
||||
let persistedIdSet = new Set<string>();
|
||||
try {
|
||||
composerDebouncedStorage.flush();
|
||||
persistedIdSet = new Set(readPersistedAttachmentIdsFromStorage(threadId));
|
||||
} catch {
|
||||
persistedIdSet = new Set();
|
||||
}
|
||||
set((state) => {
|
||||
const current = state.draftsByThreadId[threadId];
|
||||
if (!current) {
|
||||
return state;
|
||||
}
|
||||
const imageIdSet = new Set(current.images.map((image) => image.id));
|
||||
const persistedAttachments = attachments.filter(
|
||||
(attachment) => imageIdSet.has(attachment.id) && persistedIdSet.has(attachment.id),
|
||||
);
|
||||
const nonPersistedImageIds = current.images
|
||||
.map((image) => image.id)
|
||||
.filter((imageId) => !persistedIdSet.has(imageId));
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...current,
|
||||
persistedAttachments,
|
||||
nonPersistedImageIds,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
}
|
||||
|
||||
function hydreatePersistedComposerImageAttachment(
|
||||
attachment: PersistedComposerImageAttachment,
|
||||
): File | null {
|
||||
@@ -870,6 +973,8 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModel: null,
|
||||
stickyModelOptions: EMPTY_PROVIDER_MODEL_OPTIONS,
|
||||
getDraftThreadByProjectId: (projectId) => {
|
||||
if (projectId.length === 0) {
|
||||
return null;
|
||||
@@ -1105,6 +1210,29 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
};
|
||||
});
|
||||
},
|
||||
setStickyModel: (model) => {
|
||||
const normalizedModel = normalizeModelSlug(model, "codex") ?? null;
|
||||
set((state) => {
|
||||
if (state.stickyModel === normalizedModel) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
stickyModel: normalizedModel,
|
||||
};
|
||||
});
|
||||
},
|
||||
setStickyModelOptions: (modelOptions) => {
|
||||
const normalizedModelOptions =
|
||||
normalizeProviderModelOptions(modelOptions) ?? EMPTY_PROVIDER_MODEL_OPTIONS;
|
||||
set((state) => {
|
||||
if (Equal.equals(state.stickyModelOptions, normalizedModelOptions)) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
stickyModelOptions: normalizedModelOptions,
|
||||
};
|
||||
});
|
||||
},
|
||||
setPrompt: (threadId, prompt) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
@@ -1214,7 +1342,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
if (JSON.stringify(base.modelOptions) === JSON.stringify(nextModelOptions)) {
|
||||
if (Equal.equals(base.modelOptions, nextModelOptions)) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
@@ -1230,6 +1358,53 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setProviderModelOptions: (threadId, provider, nextProviderOptions, options) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const normalizedProvider = normalizeProviderKind(provider);
|
||||
if (normalizedProvider === null) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
const nextModelOptions = replaceProviderModelOptions(
|
||||
base.modelOptions,
|
||||
normalizedProvider,
|
||||
nextProviderOptions,
|
||||
);
|
||||
const nextStickyModelOptions =
|
||||
options?.persistSticky === true
|
||||
? (nextModelOptions ?? EMPTY_PROVIDER_MODEL_OPTIONS)
|
||||
: state.stickyModelOptions;
|
||||
|
||||
if (
|
||||
Equal.equals(base.modelOptions, nextModelOptions) &&
|
||||
Equal.equals(state.stickyModelOptions, nextStickyModelOptions)
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelOptions: nextModelOptions,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
|
||||
return {
|
||||
draftsByThreadId: nextDraftsByThreadId,
|
||||
...(options?.persistSticky === true
|
||||
? { stickyModelOptions: nextStickyModelOptions }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
},
|
||||
setRuntimeMode: (threadId, runtimeMode) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
@@ -1534,32 +1709,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
Promise.resolve().then(() => {
|
||||
const persistedIdSet = new Set(readPersistedAttachmentIdsFromStorage(threadId));
|
||||
set((state) => {
|
||||
const current = state.draftsByThreadId[threadId];
|
||||
if (!current) {
|
||||
return state;
|
||||
}
|
||||
const imageIdSet = new Set(current.images.map((image) => image.id));
|
||||
const persistedAttachments = attachments.filter(
|
||||
(attachment) => imageIdSet.has(attachment.id) && persistedIdSet.has(attachment.id),
|
||||
);
|
||||
const nonPersistedImageIds = current.images
|
||||
.map((image) => image.id)
|
||||
.filter((imageId) => !persistedIdSet.has(imageId));
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...current,
|
||||
persistedAttachments,
|
||||
nonPersistedImageIds,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
verifyPersistedAttachments(threadId, attachments, set);
|
||||
});
|
||||
},
|
||||
clearComposerContent: (threadId) => {
|
||||
@@ -1644,6 +1794,8 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: normalizedPersisted.draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: normalizedPersisted.projectDraftThreadIdByProjectId,
|
||||
stickyModel: normalizedPersisted.stickyModel,
|
||||
stickyModelOptions: normalizedPersisted.stickyModelOptions,
|
||||
};
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { DEFAULT_RUNTIME_MODE, type ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useCallback } from "react";
|
||||
import { inferProviderForModel } from "@t3tools/shared/model";
|
||||
import {
|
||||
type DraftThreadEnvMode,
|
||||
type DraftThreadState,
|
||||
@@ -12,6 +13,8 @@ import { useStore } from "../store";
|
||||
export function useHandleNewThread() {
|
||||
const projects = useStore((store) => store.projects);
|
||||
const threads = useStore((store) => store.threads);
|
||||
const stickyModel = useComposerDraftStore((store) => store.stickyModel);
|
||||
const stickyModelOptions = useComposerDraftStore((store) => store.stickyModelOptions);
|
||||
const navigate = useNavigate();
|
||||
const routeThreadId = useParams({
|
||||
strict: false,
|
||||
@@ -38,6 +41,9 @@ export function useHandleNewThread() {
|
||||
clearProjectDraftThreadId,
|
||||
getDraftThread,
|
||||
getDraftThreadByProjectId,
|
||||
setModel,
|
||||
setModelOptions,
|
||||
setProvider,
|
||||
setDraftThreadContext,
|
||||
setProjectDraftThreadId,
|
||||
} = useComposerDraftStore.getState();
|
||||
@@ -96,6 +102,13 @@ export function useHandleNewThread() {
|
||||
envMode: options?.envMode ?? "local",
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
});
|
||||
if (stickyModel) {
|
||||
setProvider(threadId, inferProviderForModel(stickyModel));
|
||||
setModel(threadId, stickyModel);
|
||||
}
|
||||
if (Object.keys(stickyModelOptions).length > 0) {
|
||||
setModelOptions(threadId, stickyModelOptions);
|
||||
}
|
||||
|
||||
await navigate({
|
||||
to: "/$threadId",
|
||||
@@ -103,7 +116,7 @@ export function useHandleNewThread() {
|
||||
});
|
||||
})();
|
||||
},
|
||||
[navigate, routeThreadId],
|
||||
[navigate, routeThreadId, stickyModel, stickyModelOptions],
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -16,6 +16,10 @@ export function isWindowsPlatform(platform: string): boolean {
|
||||
return /^win(dows)?/i.test(platform);
|
||||
}
|
||||
|
||||
export function isLinuxPlatform(platform: string): boolean {
|
||||
return /linux/i.test(platform);
|
||||
}
|
||||
|
||||
export function randomUUID(): string {
|
||||
if (typeof crypto.randomUUID === "function") {
|
||||
return crypto.randomUUID();
|
||||
|
||||
@@ -3,13 +3,30 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import { useCallback, useState } from "react";
|
||||
import { type ProviderKind, DEFAULT_GIT_TEXT_GENERATION_MODEL } from "@t3tools/contracts";
|
||||
import { getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { getAppModelOptions, MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
|
||||
import {
|
||||
getAppModelOptions,
|
||||
getCustomModelsForProvider,
|
||||
getDefaultCustomModelsForProvider,
|
||||
MAX_CUSTOM_MODEL_LENGTH,
|
||||
MODEL_PROVIDER_SETTINGS,
|
||||
patchCustomModels,
|
||||
useAppSettings,
|
||||
} from "../appSettings";
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { ensureNativeApi } from "../nativeApi";
|
||||
import { Button } from "../components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "../components/ui/dialog";
|
||||
import { Input } from "../components/ui/input";
|
||||
import {
|
||||
Select,
|
||||
@@ -40,77 +57,21 @@ const THEME_OPTIONS = [
|
||||
},
|
||||
] as const;
|
||||
|
||||
const MODEL_PROVIDER_SETTINGS: Array<{
|
||||
provider: ProviderKind;
|
||||
title: string;
|
||||
description: string;
|
||||
placeholder: string;
|
||||
example: string;
|
||||
}> = [
|
||||
{
|
||||
provider: "codex",
|
||||
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",
|
||||
},
|
||||
{
|
||||
provider: "claudeAgent",
|
||||
title: "Claude",
|
||||
description: "Save additional Claude model slugs for the picker and `/model` command.",
|
||||
placeholder: "your-claude-model-slug",
|
||||
example: "claude-sonnet-5-0",
|
||||
},
|
||||
] as const;
|
||||
|
||||
const TIMESTAMP_FORMAT_LABELS = {
|
||||
locale: "System default",
|
||||
"12-hour": "12-hour",
|
||||
"24-hour": "24-hour",
|
||||
} as const;
|
||||
|
||||
function getCustomModelsForProvider(
|
||||
settings: ReturnType<typeof useAppSettings>["settings"],
|
||||
provider: ProviderKind,
|
||||
) {
|
||||
switch (provider) {
|
||||
case "claudeAgent":
|
||||
return settings.customClaudeModels;
|
||||
case "codex":
|
||||
default:
|
||||
return settings.customCodexModels;
|
||||
}
|
||||
}
|
||||
|
||||
function getDefaultCustomModelsForProvider(
|
||||
defaults: ReturnType<typeof useAppSettings>["defaults"],
|
||||
provider: ProviderKind,
|
||||
) {
|
||||
switch (provider) {
|
||||
case "claudeAgent":
|
||||
return defaults.customClaudeModels;
|
||||
case "codex":
|
||||
default:
|
||||
return defaults.customCodexModels;
|
||||
}
|
||||
}
|
||||
|
||||
function patchCustomModels(provider: ProviderKind, models: string[]) {
|
||||
switch (provider) {
|
||||
case "claudeAgent":
|
||||
return { customClaudeModels: models };
|
||||
case "codex":
|
||||
default:
|
||||
return { customCodexModels: models };
|
||||
}
|
||||
}
|
||||
|
||||
function SettingsRouteView() {
|
||||
const { theme, setTheme, resolvedTheme } = useTheme();
|
||||
const { settings, defaults, updateSettings } = useAppSettings();
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
||||
const [isProjectBasePathDialogOpen, setIsProjectBasePathDialogOpen] = useState(false);
|
||||
const [isPickingProjectBasePath, setIsPickingProjectBasePath] = useState(false);
|
||||
const [projectBasePathDraft, setProjectBasePathDraft] = useState("");
|
||||
const [customModelInputByProvider, setCustomModelInputByProvider] = useState<
|
||||
Record<ProviderKind, string>
|
||||
>({
|
||||
@@ -123,6 +84,7 @@ function SettingsRouteView() {
|
||||
|
||||
const codexBinaryPath = settings.codexBinaryPath;
|
||||
const codexHomePath = settings.codexHomePath;
|
||||
const newProjectBasePath = settings.newProjectBasePath;
|
||||
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
||||
const availableEditors = serverConfigQuery.data?.availableEditors;
|
||||
|
||||
@@ -224,6 +186,43 @@ function SettingsRouteView() {
|
||||
[settings, updateSettings],
|
||||
);
|
||||
|
||||
const openProjectBasePathDialog = useCallback(() => {
|
||||
setProjectBasePathDraft(settings.newProjectBasePath);
|
||||
setIsProjectBasePathDialogOpen(true);
|
||||
}, [settings.newProjectBasePath]);
|
||||
|
||||
const closeProjectBasePathDialog = useCallback((open: boolean) => {
|
||||
setIsProjectBasePathDialogOpen(open);
|
||||
if (!open) {
|
||||
setIsPickingProjectBasePath(false);
|
||||
setProjectBasePathDraft("");
|
||||
}
|
||||
}, []);
|
||||
|
||||
const saveProjectBasePath = useCallback(() => {
|
||||
const normalizedPath = projectBasePathDraft.trim();
|
||||
updateSettings({
|
||||
newProjectBasePath: normalizedPath,
|
||||
});
|
||||
setProjectBasePathDraft(normalizedPath);
|
||||
setIsProjectBasePathDialogOpen(false);
|
||||
}, [projectBasePathDraft, updateSettings]);
|
||||
|
||||
const pickProjectBasePath = useCallback(async () => {
|
||||
if (isPickingProjectBasePath) return;
|
||||
|
||||
setIsPickingProjectBasePath(true);
|
||||
try {
|
||||
const api = ensureNativeApi();
|
||||
const pickedPath = await api.dialogs.pickFolder();
|
||||
if (!pickedPath) return;
|
||||
|
||||
setProjectBasePathDraft(pickedPath);
|
||||
} finally {
|
||||
setIsPickingProjectBasePath(false);
|
||||
}
|
||||
}, [isPickingProjectBasePath]);
|
||||
|
||||
return (
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
|
||||
@@ -333,6 +332,48 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Projects</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Optionally choose where newly created empty project folders should live by
|
||||
default. If unset, the create-project dialog starts in your Documents folder.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between gap-3 rounded-lg border border-border bg-background px-3 py-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
New project directory base path
|
||||
</p>
|
||||
<p className="mt-1 break-all font-mono text-[11px] text-muted-foreground">
|
||||
{newProjectBasePath || "Not set"}
|
||||
</p>
|
||||
</div>
|
||||
<Button size="xs" variant="outline" onClick={openProjectBasePathDialog}>
|
||||
{newProjectBasePath ? "Edit path" : "Set path"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{newProjectBasePath ? (
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
newProjectBasePath: defaults.newProjectBasePath,
|
||||
})
|
||||
}
|
||||
>
|
||||
Restore default
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Codex App Server</h2>
|
||||
@@ -771,6 +812,57 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Dialog open={isProjectBasePathDialogOpen} onOpenChange={closeProjectBasePathDialog}>
|
||||
<DialogPopup>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Default new project path</DialogTitle>
|
||||
<DialogDescription>
|
||||
Enter the full base path where new empty project folders should be created.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="space-y-4 pt-0" scrollFade={false}>
|
||||
<label htmlFor="new-project-base-path" className="block space-y-2">
|
||||
<span className="text-xs font-medium text-foreground">Full path</span>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="new-project-base-path"
|
||||
value={projectBasePathDraft}
|
||||
onChange={(event) => setProjectBasePathDraft(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter") return;
|
||||
event.preventDefault();
|
||||
saveProjectBasePath();
|
||||
}}
|
||||
placeholder="/Users/you/Developer/sandboxes"
|
||||
spellCheck={false}
|
||||
autoFocus
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => void pickProjectBasePath()}
|
||||
disabled={isPickingProjectBasePath}
|
||||
>
|
||||
{isPickingProjectBasePath ? "Selecting..." : "Select"}
|
||||
</Button>
|
||||
</div>
|
||||
</label>
|
||||
</DialogPanel>
|
||||
<DialogFooter variant="bare" className="pt-0">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => closeProjectBasePathDialog(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="button" onClick={saveProjectBasePath}>
|
||||
Save path
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
</SidebarInset>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -142,6 +142,36 @@ describe("derivePendingApprovals", () => {
|
||||
|
||||
expect(derivePendingApprovals(activities)).toEqual([]);
|
||||
});
|
||||
|
||||
it("clears stale pending approvals when the backend marks them stale after restart", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "approval-open-stale-restart",
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
tone: "approval",
|
||||
payload: {
|
||||
requestId: "req-stale-restart-1",
|
||||
requestKind: "command",
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: "approval-failed-stale-restart",
|
||||
createdAt: "2026-02-23T00:00:02.000Z",
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
tone: "error",
|
||||
payload: {
|
||||
requestId: "req-stale-restart-1",
|
||||
detail:
|
||||
"Stale pending approval request: req-stale-restart-1. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.",
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
expect(derivePendingApprovals(activities)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("derivePendingUserInputs", () => {
|
||||
@@ -228,6 +258,48 @@ describe("derivePendingUserInputs", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("clears stale pending user-input prompts when the provider reports an orphaned request", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "user-input-open-stale",
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
kind: "user-input.requested",
|
||||
summary: "User input requested",
|
||||
tone: "info",
|
||||
payload: {
|
||||
requestId: "req-user-input-stale-1",
|
||||
questions: [
|
||||
{
|
||||
id: "sandbox_mode",
|
||||
header: "Sandbox",
|
||||
question: "Which mode should be used?",
|
||||
options: [
|
||||
{
|
||||
label: "workspace-write",
|
||||
description: "Allow workspace writes only",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: "user-input-failed-stale",
|
||||
createdAt: "2026-02-23T00:00:02.000Z",
|
||||
kind: "provider.user-input.respond.failed",
|
||||
summary: "Provider user input response failed",
|
||||
tone: "error",
|
||||
payload: {
|
||||
requestId: "req-user-input-stale-1",
|
||||
detail:
|
||||
"Stale pending user-input request: req-user-input-stale-1. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.",
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
expect(derivePendingUserInputs(activities)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveActivePlanState", () => {
|
||||
@@ -695,6 +767,158 @@ describe("deriveWorkLogEntries", () => {
|
||||
"apps/web/src/session-logic.ts",
|
||||
]);
|
||||
});
|
||||
|
||||
it("collapses repeated lifecycle updates for the same tool call into one entry", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "tool-update-1",
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
kind: "tool.updated",
|
||||
summary: "Tool call",
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Tool call",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: "tool-update-2",
|
||||
createdAt: "2026-02-23T00:00:02.000Z",
|
||||
kind: "tool.updated",
|
||||
summary: "Tool call",
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Tool call",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
data: {
|
||||
item: {
|
||||
command: ["sed", "-n", "1,40p", "/tmp/app.ts"],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: "tool-complete",
|
||||
createdAt: "2026-02-23T00:00:03.000Z",
|
||||
kind: "tool.completed",
|
||||
summary: "Tool call completed",
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Tool call",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]).toMatchObject({
|
||||
id: "tool-complete",
|
||||
createdAt: "2026-02-23T00:00:03.000Z",
|
||||
label: "Tool call completed",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
command: "sed -n 1,40p /tmp/app.ts",
|
||||
itemType: "dynamic_tool_call",
|
||||
toolTitle: "Tool call",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps separate tool entries when an identical call starts after the prior one completed", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "tool-1-update",
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
kind: "tool.updated",
|
||||
summary: "Tool call",
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Tool call",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: "tool-1-complete",
|
||||
createdAt: "2026-02-23T00:00:02.000Z",
|
||||
kind: "tool.completed",
|
||||
summary: "Tool call completed",
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Tool call",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: "tool-2-update",
|
||||
createdAt: "2026-02-23T00:00:03.000Z",
|
||||
kind: "tool.updated",
|
||||
summary: "Tool call",
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Tool call",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: "tool-2-complete",
|
||||
createdAt: "2026-02-23T00:00:04.000Z",
|
||||
kind: "tool.completed",
|
||||
summary: "Tool call completed",
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Tool call",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["tool-1-complete", "tool-2-complete"]);
|
||||
});
|
||||
|
||||
it("collapses same-timestamp lifecycle rows even when completed sorts before updated by id", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "z-update-earlier",
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
kind: "tool.updated",
|
||||
summary: "Tool call",
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Tool call",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: "a-complete-same-timestamp",
|
||||
createdAt: "2026-02-23T00:00:02.000Z",
|
||||
kind: "tool.completed",
|
||||
summary: "Tool call",
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Tool call",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: "z-update-same-timestamp",
|
||||
createdAt: "2026-02-23T00:00:02.000Z",
|
||||
kind: "tool.updated",
|
||||
summary: "Tool call",
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Tool call",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.id).toBe("a-complete-same-timestamp");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveTimelineEntries", () => {
|
||||
|
||||
+188
-42
@@ -45,6 +45,11 @@ export interface WorkLogEntry {
|
||||
requestKind?: PendingApproval["requestKind"];
|
||||
}
|
||||
|
||||
interface DerivedWorkLogEntry extends WorkLogEntry {
|
||||
activityKind: OrchestrationThreadActivity["kind"];
|
||||
collapseKey?: string;
|
||||
}
|
||||
|
||||
export interface PendingApproval {
|
||||
requestId: ApprovalRequestId;
|
||||
requestKind: "command" | "file-read" | "file-change";
|
||||
@@ -160,6 +165,20 @@ function requestKindFromRequestType(requestType: unknown): PendingApproval["requ
|
||||
}
|
||||
}
|
||||
|
||||
function isStalePendingRequestFailureDetail(detail: string | undefined): boolean {
|
||||
const normalized = detail?.toLowerCase();
|
||||
if (!normalized) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
normalized.includes("stale pending approval request") ||
|
||||
normalized.includes("stale pending user-input request") ||
|
||||
normalized.includes("unknown pending approval request") ||
|
||||
normalized.includes("unknown pending permission request") ||
|
||||
normalized.includes("unknown pending user-input request")
|
||||
);
|
||||
}
|
||||
|
||||
export function derivePendingApprovals(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): PendingApproval[] {
|
||||
@@ -204,7 +223,7 @@ export function derivePendingApprovals(
|
||||
if (
|
||||
activity.kind === "provider.approval.respond.failed" &&
|
||||
requestId &&
|
||||
detail?.includes("Unknown pending permission request")
|
||||
isStalePendingRequestFailureDetail(detail)
|
||||
) {
|
||||
openByRequestId.delete(requestId);
|
||||
continue;
|
||||
@@ -280,6 +299,7 @@ export function derivePendingUserInputs(
|
||||
payload && typeof payload.requestId === "string"
|
||||
? ApprovalRequestId.makeUnsafe(payload.requestId)
|
||||
: null;
|
||||
const detail = payload && typeof payload.detail === "string" ? payload.detail : undefined;
|
||||
|
||||
if (activity.kind === "user-input.requested" && requestId) {
|
||||
const questions = parseUserInputQuestions(payload);
|
||||
@@ -296,6 +316,15 @@ export function derivePendingUserInputs(
|
||||
|
||||
if (activity.kind === "user-input.resolved" && requestId) {
|
||||
openByRequestId.delete(requestId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
activity.kind === "provider.user-input.respond.failed" &&
|
||||
requestId &&
|
||||
isStalePendingRequestFailureDetail(detail)
|
||||
) {
|
||||
openByRequestId.delete(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -430,51 +459,16 @@ export function deriveWorkLogEntries(
|
||||
latestTurnId: TurnId | undefined,
|
||||
): WorkLogEntry[] {
|
||||
const ordered = [...activities].toSorted(compareActivitiesByOrder);
|
||||
return ordered
|
||||
const entries = ordered
|
||||
.filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true))
|
||||
.filter((activity) => activity.kind !== "tool.started")
|
||||
.filter((activity) => activity.kind !== "task.started" && activity.kind !== "task.completed")
|
||||
.filter((activity) => activity.summary !== "Checkpoint captured")
|
||||
.filter((activity) => !isPlanBoundaryToolActivity(activity))
|
||||
.map((activity) => {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const command = extractToolCommand(payload);
|
||||
const changedFiles = extractChangedFiles(payload);
|
||||
const title = extractToolTitle(payload);
|
||||
const entry: WorkLogEntry = {
|
||||
id: activity.id,
|
||||
createdAt: activity.createdAt,
|
||||
label: activity.summary,
|
||||
tone: activity.tone === "approval" ? "info" : activity.tone,
|
||||
};
|
||||
const itemType = extractWorkLogItemType(payload);
|
||||
const requestKind = extractWorkLogRequestKind(payload);
|
||||
if (payload && typeof payload.detail === "string" && payload.detail.length > 0) {
|
||||
const detail = stripTrailingExitCode(payload.detail).output;
|
||||
if (detail) {
|
||||
entry.detail = detail;
|
||||
}
|
||||
}
|
||||
if (command) {
|
||||
entry.command = command;
|
||||
}
|
||||
if (changedFiles.length > 0) {
|
||||
entry.changedFiles = changedFiles;
|
||||
}
|
||||
if (title) {
|
||||
entry.toolTitle = title;
|
||||
}
|
||||
if (itemType) {
|
||||
entry.itemType = itemType;
|
||||
}
|
||||
if (requestKind) {
|
||||
entry.requestKind = requestKind;
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
.map(toDerivedWorkLogEntry);
|
||||
return collapseDerivedWorkLogEntries(entries).map(
|
||||
({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry,
|
||||
);
|
||||
}
|
||||
|
||||
function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean {
|
||||
@@ -489,6 +483,134 @@ function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): bool
|
||||
return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:");
|
||||
}
|
||||
|
||||
function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const command = extractToolCommand(payload);
|
||||
const changedFiles = extractChangedFiles(payload);
|
||||
const title = extractToolTitle(payload);
|
||||
const entry: DerivedWorkLogEntry = {
|
||||
id: activity.id,
|
||||
createdAt: activity.createdAt,
|
||||
label: activity.summary,
|
||||
tone: activity.tone === "approval" ? "info" : activity.tone,
|
||||
activityKind: activity.kind,
|
||||
};
|
||||
const itemType = extractWorkLogItemType(payload);
|
||||
const requestKind = extractWorkLogRequestKind(payload);
|
||||
if (payload && typeof payload.detail === "string" && payload.detail.length > 0) {
|
||||
const detail = stripTrailingExitCode(payload.detail).output;
|
||||
if (detail) {
|
||||
entry.detail = detail;
|
||||
}
|
||||
}
|
||||
if (command) {
|
||||
entry.command = command;
|
||||
}
|
||||
if (changedFiles.length > 0) {
|
||||
entry.changedFiles = changedFiles;
|
||||
}
|
||||
if (title) {
|
||||
entry.toolTitle = title;
|
||||
}
|
||||
if (itemType) {
|
||||
entry.itemType = itemType;
|
||||
}
|
||||
if (requestKind) {
|
||||
entry.requestKind = requestKind;
|
||||
}
|
||||
const collapseKey = deriveToolLifecycleCollapseKey(entry);
|
||||
if (collapseKey) {
|
||||
entry.collapseKey = collapseKey;
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
function collapseDerivedWorkLogEntries(
|
||||
entries: ReadonlyArray<DerivedWorkLogEntry>,
|
||||
): DerivedWorkLogEntry[] {
|
||||
const collapsed: DerivedWorkLogEntry[] = [];
|
||||
for (const entry of entries) {
|
||||
const previous = collapsed.at(-1);
|
||||
if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {
|
||||
collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);
|
||||
continue;
|
||||
}
|
||||
collapsed.push(entry);
|
||||
}
|
||||
return collapsed;
|
||||
}
|
||||
|
||||
function shouldCollapseToolLifecycleEntries(
|
||||
previous: DerivedWorkLogEntry,
|
||||
next: DerivedWorkLogEntry,
|
||||
): boolean {
|
||||
if (previous.activityKind !== "tool.updated" && previous.activityKind !== "tool.completed") {
|
||||
return false;
|
||||
}
|
||||
if (next.activityKind !== "tool.updated" && next.activityKind !== "tool.completed") {
|
||||
return false;
|
||||
}
|
||||
if (previous.activityKind === "tool.completed") {
|
||||
return false;
|
||||
}
|
||||
return previous.collapseKey !== undefined && previous.collapseKey === next.collapseKey;
|
||||
}
|
||||
|
||||
function mergeDerivedWorkLogEntries(
|
||||
previous: DerivedWorkLogEntry,
|
||||
next: DerivedWorkLogEntry,
|
||||
): DerivedWorkLogEntry {
|
||||
const changedFiles = mergeChangedFiles(previous.changedFiles, next.changedFiles);
|
||||
const detail = next.detail ?? previous.detail;
|
||||
const command = next.command ?? previous.command;
|
||||
const toolTitle = next.toolTitle ?? previous.toolTitle;
|
||||
const itemType = next.itemType ?? previous.itemType;
|
||||
const requestKind = next.requestKind ?? previous.requestKind;
|
||||
const collapseKey = next.collapseKey ?? previous.collapseKey;
|
||||
return {
|
||||
...previous,
|
||||
...next,
|
||||
...(detail ? { detail } : {}),
|
||||
...(command ? { command } : {}),
|
||||
...(changedFiles.length > 0 ? { changedFiles } : {}),
|
||||
...(toolTitle ? { toolTitle } : {}),
|
||||
...(itemType ? { itemType } : {}),
|
||||
...(requestKind ? { requestKind } : {}),
|
||||
...(collapseKey ? { collapseKey } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function mergeChangedFiles(
|
||||
previous: ReadonlyArray<string> | undefined,
|
||||
next: ReadonlyArray<string> | undefined,
|
||||
): string[] {
|
||||
const merged = [...(previous ?? []), ...(next ?? [])];
|
||||
if (merged.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return [...new Set(merged)];
|
||||
}
|
||||
|
||||
function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | undefined {
|
||||
if (entry.activityKind !== "tool.updated" && entry.activityKind !== "tool.completed") {
|
||||
return undefined;
|
||||
}
|
||||
const normalizedLabel = normalizeCompactToolLabel(entry.toolTitle ?? entry.label);
|
||||
const detail = entry.detail?.trim() ?? "";
|
||||
const itemType = entry.itemType ?? "";
|
||||
if (normalizedLabel.length === 0 && detail.length === 0 && itemType.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return [itemType, normalizedLabel, detail].join("\u001f");
|
||||
}
|
||||
|
||||
function normalizeCompactToolLabel(value: string): string {
|
||||
return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
|
||||
}
|
||||
|
||||
function toLatestProposedPlanState(proposedPlan: ProposedPlan): LatestProposedPlanState {
|
||||
return {
|
||||
id: proposedPlan.id,
|
||||
@@ -666,7 +788,31 @@ function compareActivitiesByOrder(
|
||||
return -1;
|
||||
}
|
||||
|
||||
return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
|
||||
const createdAtComparison = left.createdAt.localeCompare(right.createdAt);
|
||||
if (createdAtComparison !== 0) {
|
||||
return createdAtComparison;
|
||||
}
|
||||
|
||||
const lifecycleRankComparison =
|
||||
compareActivityLifecycleRank(left.kind) - compareActivityLifecycleRank(right.kind);
|
||||
if (lifecycleRankComparison !== 0) {
|
||||
return lifecycleRankComparison;
|
||||
}
|
||||
|
||||
return left.id.localeCompare(right.id);
|
||||
}
|
||||
|
||||
function compareActivityLifecycleRank(kind: string): number {
|
||||
if (kind.endsWith(".started") || kind === "tool.started") {
|
||||
return 0;
|
||||
}
|
||||
if (kind.endsWith(".progress") || kind.endsWith(".updated")) {
|
||||
return 1;
|
||||
}
|
||||
if (kind.endsWith(".completed") || kind.endsWith(".resolved")) {
|
||||
return 2;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
export function hasToolActivityForTurn(
|
||||
|
||||
@@ -320,6 +320,42 @@ describe("wsNativeApi", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards workspace directory creation to the websocket project method", async () => {
|
||||
requestMock.mockResolvedValue({
|
||||
relativePath: "sandbox",
|
||||
absolutePath: "/tmp/project/sandbox",
|
||||
});
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
const api = createWsNativeApi();
|
||||
await api.projects.createDirectory({
|
||||
cwd: "/tmp/project",
|
||||
relativePath: "sandbox",
|
||||
});
|
||||
|
||||
expect(requestMock).toHaveBeenCalledWith(WS_METHODS.projectsCreateDirectory, {
|
||||
cwd: "/tmp/project",
|
||||
relativePath: "sandbox",
|
||||
});
|
||||
});
|
||||
|
||||
it("reads the desktop documents path when the bridge is available", async () => {
|
||||
const getDocumentsPath = vi.fn().mockResolvedValue("/Users/davis/Documents");
|
||||
Object.defineProperty(getWindowForTest(), "desktopBridge", {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: {
|
||||
getDocumentsPath,
|
||||
},
|
||||
});
|
||||
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
const api = createWsNativeApi();
|
||||
|
||||
await expect(api.dialogs.getDocumentsPath()).resolves.toBe("/Users/davis/Documents");
|
||||
expect(getDocumentsPath).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("forwards full-thread diff requests to the orchestration websocket method", async () => {
|
||||
requestMock.mockResolvedValue({ diff: "patch" });
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
@@ -94,6 +94,10 @@ export function createWsNativeApi(): NativeApi {
|
||||
if (!window.desktopBridge) return null;
|
||||
return window.desktopBridge.pickFolder();
|
||||
},
|
||||
getDocumentsPath: async () => {
|
||||
if (!window.desktopBridge) return null;
|
||||
return window.desktopBridge.getDocumentsPath();
|
||||
},
|
||||
confirm: async (message) => {
|
||||
if (window.desktopBridge) {
|
||||
return window.desktopBridge.confirm(message);
|
||||
@@ -114,6 +118,7 @@ export function createWsNativeApi(): NativeApi {
|
||||
projects: {
|
||||
searchEntries: (input) => transport.request(WS_METHODS.projectsSearchEntries, input),
|
||||
writeFile: (input) => transport.request(WS_METHODS.projectsWriteFile, input),
|
||||
createDirectory: (input) => transport.request(WS_METHODS.projectsCreateDirectory, input),
|
||||
},
|
||||
shell: {
|
||||
openInEditor: (cwd, editor) =>
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
},
|
||||
"apps/desktop": {
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.10",
|
||||
"version": "0.0.13",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
"electron": "40.6.0",
|
||||
@@ -43,7 +43,7 @@
|
||||
},
|
||||
"apps/server": {
|
||||
"name": "t3",
|
||||
"version": "0.0.10",
|
||||
"version": "0.0.13",
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
@@ -73,7 +73,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.10",
|
||||
"version": "0.0.13",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
@@ -112,7 +112,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:",
|
||||
@@ -123,7 +123,7 @@
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.10",
|
||||
"version": "0.0.13",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.10",
|
||||
"version": "0.0.13",
|
||||
"private": true,
|
||||
"files": [
|
||||
"dist"
|
||||
|
||||
@@ -19,6 +19,8 @@ import type {
|
||||
GitStatusResult,
|
||||
} from "./git";
|
||||
import type {
|
||||
ProjectCreateDirectoryInput,
|
||||
ProjectCreateDirectoryResult,
|
||||
ProjectSearchEntriesInput,
|
||||
ProjectSearchEntriesResult,
|
||||
ProjectWriteFileInput,
|
||||
@@ -97,6 +99,7 @@ export interface DesktopUpdateActionResult {
|
||||
export interface DesktopBridge {
|
||||
getWsUrl: () => string | null;
|
||||
pickFolder: () => Promise<string | null>;
|
||||
getDocumentsPath: () => Promise<string | null>;
|
||||
confirm: (message: string) => Promise<boolean>;
|
||||
setTheme: (theme: DesktopTheme) => Promise<void>;
|
||||
showContextMenu: <T extends string>(
|
||||
@@ -114,6 +117,7 @@ export interface DesktopBridge {
|
||||
export interface NativeApi {
|
||||
dialogs: {
|
||||
pickFolder: () => Promise<string | null>;
|
||||
getDocumentsPath: () => Promise<string | null>;
|
||||
confirm: (message: string) => Promise<boolean>;
|
||||
};
|
||||
terminal: {
|
||||
@@ -128,6 +132,7 @@ export interface NativeApi {
|
||||
projects: {
|
||||
searchEntries: (input: ProjectSearchEntriesInput) => Promise<ProjectSearchEntriesResult>;
|
||||
writeFile: (input: ProjectWriteFileInput) => Promise<ProjectWriteFileResult>;
|
||||
createDirectory: (input: ProjectCreateDirectoryInput) => Promise<ProjectCreateDirectoryResult>;
|
||||
};
|
||||
shell: {
|
||||
openInEditor: (cwd: string, editor: EditorId) => Promise<void>;
|
||||
|
||||
@@ -37,3 +37,15 @@ export const ProjectWriteFileResult = Schema.Struct({
|
||||
relativePath: TrimmedNonEmptyString,
|
||||
});
|
||||
export type ProjectWriteFileResult = typeof ProjectWriteFileResult.Type;
|
||||
|
||||
export const ProjectCreateDirectoryInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
relativePath: TrimmedNonEmptyString.check(Schema.isMaxLength(PROJECT_WRITE_FILE_PATH_MAX_LENGTH)),
|
||||
});
|
||||
export type ProjectCreateDirectoryInput = typeof ProjectCreateDirectoryInput.Type;
|
||||
|
||||
export const ProjectCreateDirectoryResult = Schema.Struct({
|
||||
relativePath: TrimmedNonEmptyString,
|
||||
absolutePath: TrimmedNonEmptyString,
|
||||
});
|
||||
export type ProjectCreateDirectoryResult = typeof ProjectCreateDirectoryResult.Type;
|
||||
@@ -34,7 +34,11 @@ import {
|
||||
TerminalWriteInput,
|
||||
} from "./terminal";
|
||||
import { KeybindingRule } from "./keybindings";
|
||||
import { ProjectSearchEntriesInput, ProjectWriteFileInput } from "./project";
|
||||
import {
|
||||
ProjectCreateDirectoryInput,
|
||||
ProjectSearchEntriesInput,
|
||||
ProjectWriteFileInput,
|
||||
} from "./project";
|
||||
import { OpenInEditorInput } from "./editor";
|
||||
import { ServerConfigUpdatedPayload } from "./server";
|
||||
|
||||
@@ -47,6 +51,7 @@ export const WS_METHODS = {
|
||||
projectsRemove: "projects.remove",
|
||||
projectsSearchEntries: "projects.searchEntries",
|
||||
projectsWriteFile: "projects.writeFile",
|
||||
projectsCreateDirectory: "projects.createDirectory",
|
||||
|
||||
// Shell methods
|
||||
shellOpenInEditor: "shell.openInEditor",
|
||||
@@ -111,6 +116,7 @@ const WebSocketRequestBody = Schema.Union([
|
||||
// Project Search
|
||||
tagRequestBody(WS_METHODS.projectsSearchEntries, ProjectSearchEntriesInput),
|
||||
tagRequestBody(WS_METHODS.projectsWriteFile, ProjectWriteFileInput),
|
||||
tagRequestBody(WS_METHODS.projectsCreateDirectory, ProjectCreateDirectoryInput),
|
||||
|
||||
// Shell methods
|
||||
tagRequestBody(WS_METHODS.shellOpenInEditor, OpenInEditorInput),
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
normalizeCodexModelOptions,
|
||||
normalizeModelSlug,
|
||||
resolveReasoningEffortForProvider,
|
||||
resolveSelectableModel,
|
||||
resolveModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
supportsClaudeAdaptiveReasoning,
|
||||
@@ -94,6 +95,70 @@ describe("resolveModelSlug", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSelectableModel", () => {
|
||||
it("resolves exact slug matches", () => {
|
||||
expect(
|
||||
resolveSelectableModel("codex", "gpt-5.3-codex", [
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4" },
|
||||
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
|
||||
]),
|
||||
).toBe("gpt-5.3-codex");
|
||||
});
|
||||
|
||||
it("resolves case-insensitive display-name matches", () => {
|
||||
expect(
|
||||
resolveSelectableModel("codex", "gpt-5.3 codex", [
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4" },
|
||||
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
|
||||
]),
|
||||
).toBe("gpt-5.3-codex");
|
||||
});
|
||||
|
||||
it("resolves provider-specific aliases after normalization", () => {
|
||||
expect(
|
||||
resolveSelectableModel("claudeAgent", "sonnet", [
|
||||
{ slug: "claude-opus-4-6", name: "Claude Opus 4.6" },
|
||||
{ slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
|
||||
]),
|
||||
).toBe("claude-sonnet-4-6");
|
||||
});
|
||||
|
||||
it("returns null for empty input", () => {
|
||||
expect(resolveSelectableModel("codex", "", [{ slug: "gpt-5.4", name: "GPT-5.4" }])).toBeNull();
|
||||
expect(
|
||||
resolveSelectableModel("codex", " ", [{ slug: "gpt-5.4", name: "GPT-5.4" }]),
|
||||
).toBeNull();
|
||||
expect(
|
||||
resolveSelectableModel("codex", null, [{ slug: "gpt-5.4", name: "GPT-5.4" }]),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for unknown values that are not present in options", () => {
|
||||
expect(
|
||||
resolveSelectableModel("codex", "gpt-4.1", [{ slug: "gpt-5.4", name: "GPT-5.4" }]),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("does not accept normalized custom-looking slugs unless they exist in options", () => {
|
||||
expect(
|
||||
resolveSelectableModel("codex", "custom/internal-model", [
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4" },
|
||||
]),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("respects provider boundaries", () => {
|
||||
expect(
|
||||
resolveSelectableModel("codex", "sonnet", [{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" }]),
|
||||
).toBeNull();
|
||||
expect(
|
||||
resolveSelectableModel("claudeAgent", "5.3", [
|
||||
{ slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
|
||||
]),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getReasoningEffortOptions", () => {
|
||||
it("returns codex reasoning options for codex", () => {
|
||||
expect(getReasoningEffortOptions("codex")).toEqual(REASONING_EFFORT_OPTIONS_BY_PROVIDER.codex);
|
||||
|
||||
@@ -24,6 +24,11 @@ const CLAUDE_OPUS_4_6_MODEL = "claude-opus-4-6";
|
||||
const CLAUDE_SONNET_4_6_MODEL = "claude-sonnet-4-6";
|
||||
const CLAUDE_HAIKU_4_5_MODEL = "claude-haiku-4-5";
|
||||
|
||||
export interface SelectableModelOption {
|
||||
slug: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export function getModelOptions(provider: ProviderKind = "codex") {
|
||||
return MODEL_OPTIONS_BY_PROVIDER[provider];
|
||||
}
|
||||
@@ -77,6 +82,39 @@ export function normalizeModelSlug(
|
||||
return typeof aliased === "string" ? aliased : (trimmed as ModelSlug);
|
||||
}
|
||||
|
||||
export function resolveSelectableModel(
|
||||
provider: ProviderKind,
|
||||
value: string | null | undefined,
|
||||
options: ReadonlyArray<SelectableModelOption>,
|
||||
): ModelSlug | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const direct = options.find((option) => option.slug === trimmed);
|
||||
if (direct) {
|
||||
return direct.slug;
|
||||
}
|
||||
|
||||
const byName = options.find((option) => option.name.toLowerCase() === trimmed.toLowerCase());
|
||||
if (byName) {
|
||||
return byName.slug;
|
||||
}
|
||||
|
||||
const normalized = normalizeModelSlug(trimmed, provider);
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const resolved = options.find((option) => option.slug === normalized);
|
||||
return resolved ? resolved.slug : null;
|
||||
}
|
||||
|
||||
export function resolveModelSlug(
|
||||
model: string | null | undefined,
|
||||
provider: ProviderKind = "codex",
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
import { query, type SDKMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
type ProbeMode = "off" | "on";
|
||||
|
||||
async function* emptyPrompt(): AsyncGenerator<never, void, void> {}
|
||||
|
||||
function parseArgs(argv: ReadonlyArray<string>): {
|
||||
readonly mode: ProbeMode | "both";
|
||||
readonly model?: string;
|
||||
readonly cwd?: string;
|
||||
readonly prompt?: string;
|
||||
} {
|
||||
let mode: ProbeMode | "both" = "both";
|
||||
let model: string | undefined;
|
||||
let cwd: string | undefined;
|
||||
let prompt: string | undefined;
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const value = argv[index];
|
||||
if (!value) {
|
||||
continue;
|
||||
}
|
||||
if (value === "--mode") {
|
||||
const next = argv[index + 1];
|
||||
if (next === "off" || next === "on" || next === "both") {
|
||||
mode = next;
|
||||
index += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (value === "--model") {
|
||||
model = argv[index + 1];
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (value === "--cwd") {
|
||||
cwd = argv[index + 1];
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (value === "--prompt") {
|
||||
prompt = argv[index + 1] ?? prompt;
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
mode,
|
||||
...(model ? { model } : {}),
|
||||
...(cwd ? { cwd } : {}),
|
||||
...(prompt ? { prompt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function runProbe(input: {
|
||||
readonly mode: ProbeMode;
|
||||
readonly model?: string;
|
||||
readonly cwd?: string;
|
||||
readonly prompt?: string;
|
||||
}): Promise<void> {
|
||||
const messages = query({
|
||||
prompt: input.prompt ?? emptyPrompt(),
|
||||
options: {
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
persistSession: false,
|
||||
tools: [],
|
||||
permissionMode: "plan",
|
||||
includePartialMessages: true,
|
||||
...(input.mode === "on" ? { settings: { fastMode: true } } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
const summary = {
|
||||
mode: input.mode,
|
||||
initFastModeState: null as string | null,
|
||||
resultFastModeState: null as string | null,
|
||||
resultSubtype: null as string | null,
|
||||
resultText: null as string | null,
|
||||
};
|
||||
|
||||
const initialization = await messages.initializationResult();
|
||||
summary.initFastModeState = initialization.fast_mode_state ?? null;
|
||||
|
||||
if (!input.prompt) {
|
||||
messages.close();
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
for await (const message of messages) {
|
||||
handleProbeMessage(message, summary);
|
||||
}
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
}
|
||||
|
||||
function handleProbeMessage(
|
||||
message: SDKMessage,
|
||||
summary: {
|
||||
mode: ProbeMode;
|
||||
initFastModeState: string | null;
|
||||
resultFastModeState: string | null;
|
||||
resultSubtype: string | null;
|
||||
resultText: string | null;
|
||||
},
|
||||
): void {
|
||||
if (message.type !== "result") {
|
||||
return;
|
||||
}
|
||||
summary.resultSubtype = message.subtype;
|
||||
summary.resultFastModeState = message.fast_mode_state ?? null;
|
||||
summary.resultText = message.subtype === "success" ? message.result : message.errors.join("\n");
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
const modes = args.mode === "both" ? (["off", "on"] as const) : [args.mode];
|
||||
|
||||
for (const mode of modes) {
|
||||
await runProbe({
|
||||
mode,
|
||||
...(args.model ? { model: args.model } : {}),
|
||||
...(args.cwd ? { cwd: args.cwd } : {}),
|
||||
...(args.prompt ? { prompt: args.prompt } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await main();
|
||||
@@ -1,261 +0,0 @@
|
||||
import { query, type SDKMessage, type ThinkingConfig } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
type ProbeCase =
|
||||
| "default"
|
||||
| "effort-low"
|
||||
| "effort-high"
|
||||
| "settings-off"
|
||||
| "settings-on"
|
||||
| "thinking-disabled"
|
||||
| "thinking-enabled";
|
||||
|
||||
function parseArgs(argv: ReadonlyArray<string>): {
|
||||
readonly model: string;
|
||||
readonly cwd?: string;
|
||||
readonly prompt: string;
|
||||
readonly cases: ReadonlyArray<ProbeCase>;
|
||||
} {
|
||||
let model = "claude-haiku-4-5";
|
||||
let cwd: string | undefined;
|
||||
let prompt =
|
||||
"Think step by step about this before answering: what is 27 multiplied by 43? Return the final number only.";
|
||||
let cases: ReadonlyArray<ProbeCase> = [
|
||||
"default",
|
||||
"effort-low",
|
||||
"effort-high",
|
||||
"settings-off",
|
||||
"settings-on",
|
||||
"thinking-disabled",
|
||||
"thinking-enabled",
|
||||
];
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const value = argv[index];
|
||||
if (!value) {
|
||||
continue;
|
||||
}
|
||||
if (value === "--model") {
|
||||
model = argv[index + 1] ?? model;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (value === "--cwd") {
|
||||
cwd = argv[index + 1] ?? cwd;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (value === "--prompt") {
|
||||
prompt = argv[index + 1] ?? prompt;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (value === "--cases") {
|
||||
const next = argv[index + 1];
|
||||
if (next) {
|
||||
const requested = next
|
||||
.split(",")
|
||||
.map((entry) => entry.trim())
|
||||
.filter(
|
||||
(entry): entry is ProbeCase =>
|
||||
entry === "default" ||
|
||||
entry === "effort-low" ||
|
||||
entry === "effort-high" ||
|
||||
entry === "settings-off" ||
|
||||
entry === "settings-on" ||
|
||||
entry === "thinking-disabled" ||
|
||||
entry === "thinking-enabled",
|
||||
);
|
||||
if (requested.length > 0) {
|
||||
cases = requested;
|
||||
}
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
model,
|
||||
prompt,
|
||||
...(cwd ? { cwd } : {}),
|
||||
cases,
|
||||
};
|
||||
}
|
||||
|
||||
function caseOptions(caseName: ProbeCase): {
|
||||
readonly label: ProbeCase;
|
||||
readonly effort?: "low" | "high";
|
||||
readonly settings?: { alwaysThinkingEnabled: boolean };
|
||||
readonly thinking?: ThinkingConfig;
|
||||
} {
|
||||
switch (caseName) {
|
||||
case "effort-low":
|
||||
return {
|
||||
label: caseName,
|
||||
effort: "low",
|
||||
};
|
||||
case "effort-high":
|
||||
return {
|
||||
label: caseName,
|
||||
effort: "high",
|
||||
};
|
||||
case "settings-off":
|
||||
return {
|
||||
label: caseName,
|
||||
settings: {
|
||||
alwaysThinkingEnabled: false,
|
||||
},
|
||||
};
|
||||
case "settings-on":
|
||||
return {
|
||||
label: caseName,
|
||||
settings: {
|
||||
alwaysThinkingEnabled: true,
|
||||
},
|
||||
};
|
||||
case "thinking-disabled":
|
||||
return {
|
||||
label: caseName,
|
||||
thinking: {
|
||||
type: "disabled",
|
||||
},
|
||||
};
|
||||
case "thinking-enabled":
|
||||
return {
|
||||
label: caseName,
|
||||
thinking: {
|
||||
type: "enabled",
|
||||
budgetTokens: 1024,
|
||||
},
|
||||
};
|
||||
default:
|
||||
return {
|
||||
label: caseName,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
type ProbeSummary = {
|
||||
readonly case: ProbeCase;
|
||||
readonly model: string;
|
||||
initModelInfo: {
|
||||
value: string | null;
|
||||
supportsEffort: boolean | null;
|
||||
supportsAdaptiveThinking: boolean | null;
|
||||
supportedEffortLevels: ReadonlyArray<string> | null;
|
||||
} | null;
|
||||
resultSubtype: string | null;
|
||||
resultText: string | null;
|
||||
assistantThinkingBlockCount: number;
|
||||
streamThinkingEventTypes: Record<string, number>;
|
||||
error: string | null;
|
||||
};
|
||||
|
||||
async function runCase(input: {
|
||||
readonly caseName: ProbeCase;
|
||||
readonly model: string;
|
||||
readonly cwd?: string;
|
||||
readonly prompt: string;
|
||||
}): Promise<ProbeSummary> {
|
||||
const caseConfig = caseOptions(input.caseName);
|
||||
const summary: ProbeSummary = {
|
||||
case: input.caseName,
|
||||
model: input.model,
|
||||
initModelInfo: null,
|
||||
resultSubtype: null,
|
||||
resultText: null,
|
||||
assistantThinkingBlockCount: 0,
|
||||
streamThinkingEventTypes: {},
|
||||
error: null,
|
||||
};
|
||||
|
||||
try {
|
||||
const messages = query({
|
||||
prompt: input.prompt,
|
||||
options: {
|
||||
model: input.model,
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
persistSession: false,
|
||||
tools: [],
|
||||
permissionMode: "bypassPermissions",
|
||||
includePartialMessages: true,
|
||||
maxTurns: 1,
|
||||
...(caseConfig.effort ? { effort: caseConfig.effort } : {}),
|
||||
...(caseConfig.settings ? { settings: caseConfig.settings } : {}),
|
||||
...(caseConfig.thinking ? { thinking: caseConfig.thinking } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
const initialization = await messages.initializationResult();
|
||||
const initModel =
|
||||
initialization.models.find((candidate) => candidate.value === input.model) ??
|
||||
initialization.models.find((candidate) => candidate.value.includes("haiku")) ??
|
||||
null;
|
||||
summary.initModelInfo = initModel
|
||||
? {
|
||||
value: initModel.value,
|
||||
supportsEffort: initModel.supportsEffort ?? null,
|
||||
supportsAdaptiveThinking: initModel.supportsAdaptiveThinking ?? null,
|
||||
supportedEffortLevels: initModel.supportedEffortLevels ?? null,
|
||||
}
|
||||
: null;
|
||||
|
||||
for await (const message of messages) {
|
||||
handleMessage(summary, message);
|
||||
}
|
||||
} catch (error) {
|
||||
summary.error = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
return summary;
|
||||
}
|
||||
|
||||
function handleMessage(summary: ProbeSummary, message: SDKMessage): void {
|
||||
if (message.type === "stream_event") {
|
||||
const event = message.event as {
|
||||
type?: string;
|
||||
delta?: {
|
||||
type?: string;
|
||||
};
|
||||
};
|
||||
const eventType = event.delta?.type ?? event.type;
|
||||
if (typeof eventType === "string" && eventType.includes("thinking")) {
|
||||
summary.streamThinkingEventTypes[eventType] =
|
||||
(summary.streamThinkingEventTypes[eventType] ?? 0) + 1;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "assistant") {
|
||||
for (const block of message.message.content) {
|
||||
if (typeof block?.type === "string" && block.type.includes("thinking")) {
|
||||
summary.assistantThinkingBlockCount += 1;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "result") {
|
||||
summary.resultSubtype = message.subtype;
|
||||
summary.resultText = message.subtype === "success" ? message.result : message.errors.join("\n");
|
||||
}
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
const results: ProbeSummary[] = [];
|
||||
|
||||
for (const caseName of args.cases) {
|
||||
results.push(
|
||||
await runCase({
|
||||
caseName,
|
||||
model: args.model,
|
||||
...(args.cwd ? { cwd: args.cwd } : {}),
|
||||
prompt: args.prompt,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
console.log(JSON.stringify(results, null, 2));
|
||||
}
|
||||
|
||||
await main();
|
||||
+42
-24
@@ -1,10 +1,10 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { homedir } from "node:os";
|
||||
import { resolve } from "node:path";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import {
|
||||
DEFAULT_DEV_STATE_DIR,
|
||||
createDevRunnerEnv,
|
||||
findFirstAvailableOffset,
|
||||
resolveModePortOffsets,
|
||||
@@ -46,27 +46,24 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
});
|
||||
|
||||
describe("createDevRunnerEnv", () => {
|
||||
it.effect("defaults state dir to ~/.t3/dev when not provided", () =>
|
||||
it.effect("defaults T3CODE_HOME to ~/.t3 when not provided", () =>
|
||||
Effect.gen(function* () {
|
||||
const [env, defaultStateDir] = yield* Effect.all([
|
||||
createDevRunnerEnv({
|
||||
mode: "dev",
|
||||
baseEnv: {},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
stateDir: undefined,
|
||||
authToken: undefined,
|
||||
noBrowser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
}),
|
||||
DEFAULT_DEV_STATE_DIR,
|
||||
]);
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev",
|
||||
baseEnv: {},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: undefined,
|
||||
authToken: undefined,
|
||||
noBrowser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.T3CODE_STATE_DIR, defaultStateDir);
|
||||
assert.equal(env.T3CODE_HOME, resolve(homedir(), ".t3"));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -77,7 +74,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
baseEnv: {},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
stateDir: "/tmp/override-state",
|
||||
t3Home: "/tmp/custom-t3",
|
||||
authToken: "secret",
|
||||
noBrowser: true,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
@@ -87,7 +84,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
devUrl: new URL("http://localhost:7331"),
|
||||
});
|
||||
|
||||
assert.equal(env.T3CODE_STATE_DIR, resolve("/tmp/override-state"));
|
||||
assert.equal(env.T3CODE_HOME, resolve("/tmp/custom-t3"));
|
||||
assert.equal(env.T3CODE_PORT, "4222");
|
||||
assert.equal(env.VITE_WS_URL, "ws://localhost:4222");
|
||||
assert.equal(env.T3CODE_NO_BROWSER, "1");
|
||||
@@ -107,7 +104,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
stateDir: undefined,
|
||||
t3Home: undefined,
|
||||
authToken: undefined,
|
||||
noBrowser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
@@ -129,7 +126,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
baseEnv: {},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
stateDir: undefined,
|
||||
t3Home: undefined,
|
||||
authToken: undefined,
|
||||
noBrowser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
@@ -142,6 +139,27 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
assert.equal(env.T3CODE_LOG_WS_EVENTS, "0");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses custom t3Home when provided", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev",
|
||||
baseEnv: {},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: "/tmp/my-t3",
|
||||
authToken: undefined,
|
||||
noBrowser: undefined,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: undefined,
|
||||
port: undefined,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.T3CODE_HOME, resolve("/tmp/my-t3"));
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("findFirstAvailableOffset", () => {
|
||||
|
||||
+15
-16
@@ -14,8 +14,8 @@ const BASE_WEB_PORT = 5733;
|
||||
const MAX_HASH_OFFSET = 3000;
|
||||
const MAX_PORT = 65535;
|
||||
|
||||
export const DEFAULT_DEV_STATE_DIR = Effect.map(Effect.service(Path.Path), (path) =>
|
||||
path.join(homedir(), ".t3", "dev"),
|
||||
export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
|
||||
path.join(homedir(), ".t3"),
|
||||
);
|
||||
|
||||
const MODE_ARGS = {
|
||||
@@ -101,17 +101,16 @@ export function resolveOffset(config: {
|
||||
return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
|
||||
}
|
||||
|
||||
function resolveStateDir(stateDir: string | undefined): Effect.Effect<string, never, Path.Path> {
|
||||
function resolveBaseDir(baseDir: string | undefined): Effect.Effect<string, never, Path.Path> {
|
||||
return Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const configured = stateDir?.trim();
|
||||
const configured = baseDir?.trim();
|
||||
|
||||
if (configured) {
|
||||
// Resolve relative paths against cwd (monorepo root) before turbo changes directories.
|
||||
return path.resolve(configured);
|
||||
}
|
||||
|
||||
return yield* DEFAULT_DEV_STATE_DIR;
|
||||
return yield* DEFAULT_T3_HOME;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -120,7 +119,7 @@ interface CreateDevRunnerEnvInput {
|
||||
readonly baseEnv: NodeJS.ProcessEnv;
|
||||
readonly serverOffset: number;
|
||||
readonly webOffset: number;
|
||||
readonly stateDir: string | undefined;
|
||||
readonly t3Home: string | undefined;
|
||||
readonly authToken: string | undefined;
|
||||
readonly noBrowser: boolean | undefined;
|
||||
readonly autoBootstrapProjectFromCwd: boolean | undefined;
|
||||
@@ -135,7 +134,7 @@ export function createDevRunnerEnv({
|
||||
baseEnv,
|
||||
serverOffset,
|
||||
webOffset,
|
||||
stateDir,
|
||||
t3Home,
|
||||
authToken,
|
||||
noBrowser,
|
||||
autoBootstrapProjectFromCwd,
|
||||
@@ -147,7 +146,7 @@ export function createDevRunnerEnv({
|
||||
return Effect.gen(function* () {
|
||||
const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
|
||||
const webPort = BASE_WEB_PORT + webOffset;
|
||||
const resolvedStateDir = yield* resolveStateDir(stateDir);
|
||||
const resolvedBaseDir = yield* resolveBaseDir(t3Home);
|
||||
|
||||
const output: NodeJS.ProcessEnv = {
|
||||
...baseEnv,
|
||||
@@ -156,7 +155,7 @@ export function createDevRunnerEnv({
|
||||
ELECTRON_RENDERER_PORT: String(webPort),
|
||||
VITE_WS_URL: `ws://localhost:${serverPort}`,
|
||||
VITE_DEV_SERVER_URL: devUrl?.toString() ?? `http://localhost:${webPort}`,
|
||||
T3CODE_STATE_DIR: resolvedStateDir,
|
||||
T3CODE_HOME: resolvedBaseDir,
|
||||
};
|
||||
|
||||
if (host !== undefined) {
|
||||
@@ -335,7 +334,7 @@ export function resolveModePortOffsets<R = NetService>({
|
||||
|
||||
interface DevRunnerCliInput {
|
||||
readonly mode: DevMode;
|
||||
readonly stateDir: string | undefined;
|
||||
readonly t3Home: string | undefined;
|
||||
readonly authToken: string | undefined;
|
||||
readonly noBrowser: boolean | undefined;
|
||||
readonly autoBootstrapProjectFromCwd: boolean | undefined;
|
||||
@@ -415,7 +414,7 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
|
||||
baseEnv: process.env,
|
||||
serverOffset,
|
||||
webOffset,
|
||||
stateDir: input.stateDir,
|
||||
t3Home: input.t3Home,
|
||||
authToken: input.authToken,
|
||||
noBrowser: resolveOptionalBooleanOverride(input.noBrowser, envOverrides.noBrowser),
|
||||
autoBootstrapProjectFromCwd: resolveOptionalBooleanOverride(
|
||||
@@ -437,7 +436,7 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
|
||||
: "";
|
||||
|
||||
yield* Effect.logInfo(
|
||||
`[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} stateDir=${String(env.T3CODE_STATE_DIR)}`,
|
||||
`[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${String(env.T3CODE_HOME)}`,
|
||||
);
|
||||
|
||||
if (input.dryRun) {
|
||||
@@ -485,9 +484,9 @@ const devRunnerCli = Command.make("dev-runner", {
|
||||
mode: Argument.choice("mode", DEV_RUNNER_MODES).pipe(
|
||||
Argument.withDescription("Development mode to run."),
|
||||
),
|
||||
stateDir: Flag.string("state-dir").pipe(
|
||||
Flag.withDescription("State directory path (forwards to T3CODE_STATE_DIR)."),
|
||||
Flag.withFallbackConfig(optionalStringConfig("T3CODE_STATE_DIR")),
|
||||
t3Home: Flag.string("home-dir").pipe(
|
||||
Flag.withDescription("Base directory for all T3 Code data (equivalent to T3CODE_HOME)."),
|
||||
Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOME")),
|
||||
),
|
||||
authToken: Flag.string("auth-token").pipe(
|
||||
Flag.withDescription("Auth token (forwards to T3CODE_AUTH_TOKEN)."),
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@
|
||||
"T3CODE_MODE",
|
||||
"T3CODE_PORT",
|
||||
"T3CODE_NO_BROWSER",
|
||||
"T3CODE_STATE_DIR",
|
||||
"T3CODE_HOME",
|
||||
"T3CODE_AUTH_TOKEN",
|
||||
"T3CODE_DESKTOP_WS_URL"
|
||||
],
|
||||
|
||||
Reference in new issue
Block a user