Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
14070d6c45 | ||
|
|
8cad01a57b | ||
|
|
340634eeee | ||
|
|
fa0a1c1567 | ||
|
|
01358d1006 | ||
|
|
529315b4c8 | ||
|
|
0a503d0cde | ||
|
|
d4a7e1ac0b | ||
|
|
be1abc88fd | ||
|
|
384f35084e | ||
|
|
1371ce2cce | ||
|
|
d6408a2949 | ||
|
|
e823f8f14e | ||
|
|
2b08d86696 | ||
|
|
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.
|
||||
|
||||
@@ -24,32 +24,32 @@ jobs:
|
||||
{
|
||||
name: "size:XS",
|
||||
color: "0e8a16",
|
||||
description: "0-9 changed lines (additions + deletions).",
|
||||
description: "0-9 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:S",
|
||||
color: "5ebd3e",
|
||||
description: "10-29 changed lines (additions + deletions).",
|
||||
description: "10-29 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:M",
|
||||
color: "fbca04",
|
||||
description: "30-99 changed lines (additions + deletions).",
|
||||
description: "30-99 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:L",
|
||||
color: "fe7d37",
|
||||
description: "100-499 changed lines (additions + deletions).",
|
||||
description: "100-499 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:XL",
|
||||
color: "d93f0b",
|
||||
description: "500-999 changed lines (additions + deletions).",
|
||||
description: "500-999 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:XXL",
|
||||
color: "b60205",
|
||||
description: "1,000+ changed lines (additions + deletions).",
|
||||
description: "1,000+ effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -131,12 +131,18 @@ jobs:
|
||||
with:
|
||||
script: |
|
||||
const issueNumber = context.payload.pull_request.number;
|
||||
const additions = context.payload.pull_request.additions ?? 0;
|
||||
const deletions = context.payload.pull_request.deletions ?? 0;
|
||||
const changedLines = additions + deletions;
|
||||
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
|
||||
|
||||
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
||||
// Keep this aligned with the repo's test entrypoints and test-only support files.
|
||||
const testFilePatterns = [
|
||||
/(^|\/)__tests__(\/|$)/,
|
||||
/(^|\/)tests?(\/|$)/,
|
||||
/^apps\/server\/integration\//,
|
||||
/\.(test|spec|browser|integration)\.[^.\/]+$/,
|
||||
];
|
||||
|
||||
const isTestFile = (filename) =>
|
||||
testFilePatterns.some((pattern) => pattern.test(filename));
|
||||
|
||||
const resolveSizeLabel = (totalChangedLines) => {
|
||||
if (totalChangedLines < 10) {
|
||||
@@ -162,6 +168,42 @@ jobs:
|
||||
return "size:XXL";
|
||||
};
|
||||
|
||||
const files = await github.paginate(
|
||||
github.rest.pulls.listFiles,
|
||||
{
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: issueNumber,
|
||||
per_page: 100,
|
||||
},
|
||||
(response) => response.data,
|
||||
);
|
||||
|
||||
if (files.length >= 3000) {
|
||||
core.warning(
|
||||
"The GitHub pull request files API may truncate results at 3,000 files; PR size may be undercounted.",
|
||||
);
|
||||
}
|
||||
|
||||
let testChangedLines = 0;
|
||||
let nonTestChangedLines = 0;
|
||||
|
||||
for (const file of files) {
|
||||
const changedLinesForFile = (file.additions ?? 0) + (file.deletions ?? 0);
|
||||
|
||||
if (changedLinesForFile === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isTestFile(file.filename)) {
|
||||
testChangedLines += changedLinesForFile;
|
||||
continue;
|
||||
}
|
||||
|
||||
nonTestChangedLines += changedLinesForFile;
|
||||
}
|
||||
|
||||
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
|
||||
const nextLabelName = resolveSizeLabel(changedLines);
|
||||
|
||||
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||
@@ -199,4 +241,15 @@ jobs:
|
||||
});
|
||||
}
|
||||
|
||||
core.info(`PR #${issueNumber}: ${changedLines} changed lines -> ${nextLabelName}`);
|
||||
const classification =
|
||||
nonTestChangedLines === 0
|
||||
? testChangedLines > 0
|
||||
? "test-only PR"
|
||||
: "no line changes"
|
||||
: testChangedLines > 0
|
||||
? "test lines excluded"
|
||||
: "all non-test changes";
|
||||
|
||||
core.info(
|
||||
`PR #${issueNumber}: ${nonTestChangedLines} non-test lines, ${testChangedLines} test lines, ${changedLines} effective lines -> ${nextLabelName} (${classification})`,
|
||||
);
|
||||
@@ -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 }}
|
||||
|
||||
|
||||
+3
-1
@@ -17,4 +17,6 @@ release/
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
.vitest-*
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
@@ -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": {
|
||||
|
||||
@@ -56,8 +56,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 +924,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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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) =>
|
||||
@@ -116,7 +115,10 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModel,
|
||||
defaultModelSelection: {
|
||||
provider,
|
||||
model: defaultModel,
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -126,7 +128,10 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
model: defaultModel,
|
||||
modelSelection: {
|
||||
provider,
|
||||
model: defaultModel,
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -152,7 +157,14 @@ const startTurn = (input: {
|
||||
text: input.text,
|
||||
attachments: [],
|
||||
},
|
||||
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||
...(input.provider !== undefined
|
||||
? {
|
||||
modelSelection: {
|
||||
provider: input.provider,
|
||||
model: DEFAULT_MODEL_BY_PROVIDER[input.provider],
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: nowIso(),
|
||||
@@ -255,7 +267,10 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModel: "gpt-5.3-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -265,7 +280,10 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -31,7 +31,7 @@ function makeSnapshot(input: {
|
||||
id: input.projectId,
|
||||
title: "Project",
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
@@ -43,7 +43,10 @@ function makeSnapshot(input: {
|
||||
id: input.threadId,
|
||||
projectId: input.projectId,
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
|
||||
@@ -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);
|
||||
@@ -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
+1494
-1101
File diff suppressed because it is too large.
Load diff
@@ -6,6 +6,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { expect } from "vitest";
|
||||
import type { GitActionProgressEvent } from "@t3tools/contracts";
|
||||
|
||||
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
|
||||
import { type GitManagerShape } from "../Services/GitManager.ts";
|
||||
@@ -15,10 +16,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 +107,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 +125,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 +141,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-");
|
||||
@@ -449,12 +450,20 @@ function runStackedAction(
|
||||
input: {
|
||||
cwd: string;
|
||||
action: "commit" | "commit_push" | "commit_push_pr";
|
||||
actionId?: string;
|
||||
commitMessage?: string;
|
||||
featureBranch?: boolean;
|
||||
filePaths?: readonly string[];
|
||||
},
|
||||
options?: Parameters<GitManagerShape["runStackedAction"]>[1],
|
||||
) {
|
||||
return manager.runStackedAction(input);
|
||||
return manager.runStackedAction(
|
||||
{
|
||||
...input,
|
||||
actionId: input.actionId ?? "test-action-id",
|
||||
},
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; reference: string }) {
|
||||
@@ -474,18 +483,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 +504,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", () =>
|
||||
@@ -1936,4 +1950,117 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
expect(errorMessage).toContain("already checked out in the main repo");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("emits ordered progress events for commit hooks", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
fs.writeFileSync(path.join(repoDir, "hooked.txt"), "hooked\n");
|
||||
fs.writeFileSync(
|
||||
path.join(repoDir, ".git", "hooks", "pre-commit"),
|
||||
'#!/bin/sh\necho "hook: start" >&2\nsleep 1\necho "hook: end" >&2\n',
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const events: GitActionProgressEvent[] = [];
|
||||
|
||||
const result = yield* runStackedAction(
|
||||
manager,
|
||||
{
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
},
|
||||
{
|
||||
actionId: "action-1",
|
||||
progressReporter: {
|
||||
publish: (event) =>
|
||||
Effect.sync(() => {
|
||||
events.push(event);
|
||||
}),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(events.map((event) => event.kind)).toContain("action_started");
|
||||
expect(events).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "phase_started",
|
||||
phase: "commit",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "hook_started",
|
||||
hookName: "pre-commit",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "hook_output",
|
||||
text: "hook: start",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "hook_output",
|
||||
text: "hook: end",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "hook_finished",
|
||||
hookName: "pre-commit",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "action_finished",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("emits action_failed when a commit hook rejects", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
fs.writeFileSync(path.join(repoDir, "hook-failure.txt"), "broken\n");
|
||||
fs.writeFileSync(
|
||||
path.join(repoDir, ".git", "hooks", "pre-commit"),
|
||||
'#!/bin/sh\necho "hook: fail" >&2\nexit 1\n',
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const events: GitActionProgressEvent[] = [];
|
||||
|
||||
const errorMessage = yield* runStackedAction(
|
||||
manager,
|
||||
{
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
},
|
||||
{
|
||||
actionId: "action-2",
|
||||
progressReporter: {
|
||||
publish: (event) =>
|
||||
Effect.sync(() => {
|
||||
events.push(event);
|
||||
}),
|
||||
},
|
||||
},
|
||||
).pipe(
|
||||
Effect.flip,
|
||||
Effect.map((error) => error.message),
|
||||
);
|
||||
|
||||
expect(errorMessage).toContain("hook: fail");
|
||||
expect(events).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "hook_started",
|
||||
hookName: "pre-commit",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "action_failed",
|
||||
phase: "commit",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import type { GitActionProgressEvent, GitActionProgressPhase } from "@t3tools/contracts";
|
||||
import {
|
||||
resolveAutoFeatureBranchName,
|
||||
sanitizeBranchFragment,
|
||||
@@ -9,11 +10,21 @@ import {
|
||||
} from "@t3tools/shared/git";
|
||||
|
||||
import { GitManagerError } from "../Errors.ts";
|
||||
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
|
||||
import {
|
||||
GitManager,
|
||||
type GitActionProgressReporter,
|
||||
type GitManagerShape,
|
||||
type GitRunStackedActionOptions,
|
||||
} from "../Services/GitManager.ts";
|
||||
import { GitCore } from "../Services/GitCore.ts";
|
||||
import { GitHubCli } from "../Services/GitHubCli.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
|
||||
const COMMIT_TIMEOUT_MS = 10 * 60_000;
|
||||
const MAX_PROGRESS_TEXT_LENGTH = 500;
|
||||
type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never;
|
||||
type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
|
||||
|
||||
interface OpenPrInfo {
|
||||
number: number;
|
||||
title: string;
|
||||
@@ -200,6 +211,17 @@ function sanitizeCommitMessage(generated: {
|
||||
};
|
||||
}
|
||||
|
||||
function sanitizeProgressText(value: string): string | null {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (trimmed.length <= MAX_PROGRESS_TEXT_LENGTH) {
|
||||
return trimmed;
|
||||
}
|
||||
return trimmed.slice(0, MAX_PROGRESS_TEXT_LENGTH).trimEnd();
|
||||
}
|
||||
|
||||
interface CommitAndBranchSuggestion {
|
||||
subject: string;
|
||||
body: string;
|
||||
@@ -337,6 +359,29 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
const gitHubCli = yield* GitHubCli;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const createProgressEmitter = (
|
||||
input: { cwd: string; action: "commit" | "commit_push" | "commit_push_pr" },
|
||||
options?: GitRunStackedActionOptions,
|
||||
) => {
|
||||
const actionId = options?.actionId ?? randomUUID();
|
||||
const reporter = options?.progressReporter;
|
||||
|
||||
const emit = (event: GitActionProgressPayload) =>
|
||||
reporter
|
||||
? reporter.publish({
|
||||
actionId,
|
||||
cwd: input.cwd,
|
||||
action: input.action,
|
||||
...event,
|
||||
} as GitActionProgressEvent)
|
||||
: Effect.void;
|
||||
|
||||
return {
|
||||
actionId,
|
||||
emit,
|
||||
};
|
||||
};
|
||||
|
||||
const configurePullRequestHeadUpstream = (
|
||||
cwd: string,
|
||||
pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
|
||||
@@ -680,27 +725,111 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
|
||||
const runCommitStep = (
|
||||
cwd: string,
|
||||
action: "commit" | "commit_push" | "commit_push_pr",
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
preResolvedSuggestion?: CommitAndBranchSuggestion,
|
||||
filePaths?: readonly string[],
|
||||
model?: string,
|
||||
progressReporter?: GitActionProgressReporter,
|
||||
actionId?: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion =
|
||||
preResolvedSuggestion ??
|
||||
(yield* resolveCommitAndBranchSuggestion({
|
||||
const emit = (event: GitActionProgressPayload) =>
|
||||
progressReporter && actionId
|
||||
? progressReporter.publish({
|
||||
actionId,
|
||||
cwd,
|
||||
action,
|
||||
...event,
|
||||
} as GitActionProgressEvent)
|
||||
: Effect.void;
|
||||
|
||||
let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion;
|
||||
if (!suggestion) {
|
||||
const needsGeneration = !commitMessage?.trim();
|
||||
if (needsGeneration) {
|
||||
yield* emit({
|
||||
kind: "phase_started",
|
||||
phase: "commit",
|
||||
label: "Generating commit message...",
|
||||
});
|
||||
}
|
||||
suggestion = yield* resolveCommitAndBranchSuggestion({
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
...(model ? { model } : {}),
|
||||
}));
|
||||
});
|
||||
}
|
||||
if (!suggestion) {
|
||||
return { status: "skipped_no_changes" as const };
|
||||
}
|
||||
|
||||
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
|
||||
yield* emit({
|
||||
kind: "phase_started",
|
||||
phase: "commit",
|
||||
label: "Committing...",
|
||||
});
|
||||
|
||||
let currentHookName: string | null = null;
|
||||
const commitProgress =
|
||||
progressReporter && actionId
|
||||
? {
|
||||
onOutputLine: ({ stream, text }: { stream: "stdout" | "stderr"; text: string }) => {
|
||||
const sanitized = sanitizeProgressText(text);
|
||||
if (!sanitized) {
|
||||
return Effect.void;
|
||||
}
|
||||
return emit({
|
||||
kind: "hook_output",
|
||||
hookName: currentHookName,
|
||||
stream,
|
||||
text: sanitized,
|
||||
});
|
||||
},
|
||||
onHookStarted: (hookName: string) => {
|
||||
currentHookName = hookName;
|
||||
return emit({
|
||||
kind: "hook_started",
|
||||
hookName,
|
||||
});
|
||||
},
|
||||
onHookFinished: ({
|
||||
hookName,
|
||||
exitCode,
|
||||
durationMs,
|
||||
}: {
|
||||
hookName: string;
|
||||
exitCode: number | null;
|
||||
durationMs: number | null;
|
||||
}) => {
|
||||
if (currentHookName === hookName) {
|
||||
currentHookName = null;
|
||||
}
|
||||
return emit({
|
||||
kind: "hook_finished",
|
||||
hookName,
|
||||
exitCode,
|
||||
durationMs,
|
||||
});
|
||||
},
|
||||
}
|
||||
: null;
|
||||
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, {
|
||||
timeoutMs: COMMIT_TIMEOUT_MS,
|
||||
...(commitProgress ? { progress: commitProgress } : {}),
|
||||
});
|
||||
if (currentHookName !== null) {
|
||||
yield* emit({
|
||||
kind: "hook_finished",
|
||||
hookName: currentHookName,
|
||||
exitCode: 0,
|
||||
durationMs: null,
|
||||
});
|
||||
currentHookName = null;
|
||||
}
|
||||
return {
|
||||
status: "created" as const,
|
||||
commitSha,
|
||||
@@ -1010,66 +1139,135 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
|
||||
function* (input) {
|
||||
const wantsPush = input.action !== "commit";
|
||||
const wantsPr = input.action === "commit_push_pr";
|
||||
function* (input, options) {
|
||||
const progress = createProgressEmitter(input, options);
|
||||
const phases: GitActionProgressPhase[] = [
|
||||
...(input.featureBranch ? (["branch"] as const) : []),
|
||||
"commit",
|
||||
...(input.action !== "commit" ? (["push"] as const) : []),
|
||||
...(input.action === "commit_push_pr" ? (["pr"] as const) : []),
|
||||
];
|
||||
let currentPhase: GitActionProgressPhase | null = null;
|
||||
|
||||
const initialStatus = yield* gitCore.statusDetails(input.cwd);
|
||||
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
|
||||
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
|
||||
}
|
||||
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
|
||||
return yield* gitManagerError(
|
||||
"runStackedAction",
|
||||
"Cannot create a pull request from detached HEAD.",
|
||||
);
|
||||
}
|
||||
const runAction = Effect.gen(function* () {
|
||||
yield* progress.emit({
|
||||
kind: "action_started",
|
||||
phases,
|
||||
});
|
||||
|
||||
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
|
||||
let commitMessageForStep = input.commitMessage;
|
||||
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
|
||||
const wantsPush = input.action !== "commit";
|
||||
const wantsPr = input.action === "commit_push_pr";
|
||||
|
||||
if (input.featureBranch) {
|
||||
const result = yield* runFeatureBranchStep(
|
||||
const initialStatus = yield* gitCore.statusDetails(input.cwd);
|
||||
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
|
||||
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
|
||||
}
|
||||
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
|
||||
return yield* gitManagerError(
|
||||
"runStackedAction",
|
||||
"Cannot create a pull request from detached HEAD.",
|
||||
);
|
||||
}
|
||||
|
||||
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
|
||||
let commitMessageForStep = input.commitMessage;
|
||||
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
|
||||
|
||||
if (input.featureBranch) {
|
||||
currentPhase = "branch";
|
||||
yield* progress.emit({
|
||||
kind: "phase_started",
|
||||
phase: "branch",
|
||||
label: "Preparing feature branch...",
|
||||
});
|
||||
const result = yield* runFeatureBranchStep(
|
||||
input.cwd,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
);
|
||||
branchStep = result.branchStep;
|
||||
commitMessageForStep = result.resolvedCommitMessage;
|
||||
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
|
||||
} else {
|
||||
branchStep = { status: "skipped_not_requested" as const };
|
||||
}
|
||||
|
||||
const currentBranch = branchStep.name ?? initialStatus.branch;
|
||||
|
||||
currentPhase = "commit";
|
||||
const commit = yield* runCommitStep(
|
||||
input.cwd,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
input.action,
|
||||
currentBranch,
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
options?.progressReporter,
|
||||
progress.actionId,
|
||||
);
|
||||
branchStep = result.branchStep;
|
||||
commitMessageForStep = result.resolvedCommitMessage;
|
||||
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
|
||||
} else {
|
||||
branchStep = { status: "skipped_not_requested" as const };
|
||||
}
|
||||
|
||||
const currentBranch = branchStep.name ?? initialStatus.branch;
|
||||
const push = wantsPush
|
||||
? yield* progress
|
||||
.emit({
|
||||
kind: "phase_started",
|
||||
phase: "push",
|
||||
label: "Pushing...",
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap(() =>
|
||||
Effect.gen(function* () {
|
||||
currentPhase = "push";
|
||||
return yield* gitCore.pushCurrentBranch(input.cwd, currentBranch);
|
||||
}),
|
||||
),
|
||||
)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const commit = yield* runCommitStep(
|
||||
input.cwd,
|
||||
currentBranch,
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
const pr = wantsPr
|
||||
? yield* progress
|
||||
.emit({
|
||||
kind: "phase_started",
|
||||
phase: "pr",
|
||||
label: "Creating PR...",
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap(() =>
|
||||
Effect.gen(function* () {
|
||||
currentPhase = "pr";
|
||||
return yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel);
|
||||
}),
|
||||
),
|
||||
)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const result = {
|
||||
action: input.action,
|
||||
branch: branchStep,
|
||||
commit,
|
||||
push,
|
||||
pr,
|
||||
};
|
||||
yield* progress.emit({
|
||||
kind: "action_finished",
|
||||
result,
|
||||
});
|
||||
return result;
|
||||
});
|
||||
|
||||
return yield* runAction.pipe(
|
||||
Effect.catch((error) =>
|
||||
progress
|
||||
.emit({
|
||||
kind: "action_failed",
|
||||
phase: currentPhase,
|
||||
message: error.message,
|
||||
})
|
||||
.pipe(Effect.flatMap(() => Effect.fail(error))),
|
||||
),
|
||||
);
|
||||
|
||||
const push = wantsPush
|
||||
? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const pr = wantsPr
|
||||
? yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
return {
|
||||
action: input.action,
|
||||
branch: branchStep,
|
||||
commit,
|
||||
push,
|
||||
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,23 @@ 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;
|
||||
readonly progress?: ExecuteGitProgress;
|
||||
}
|
||||
|
||||
export interface ExecuteGitResult {
|
||||
readonly code: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
}
|
||||
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
||||
upstreamRef: string | null;
|
||||
}
|
||||
@@ -33,6 +50,35 @@ export interface GitPreparedCommitContext {
|
||||
stagedPatch: string;
|
||||
}
|
||||
|
||||
export interface ExecuteGitProgress {
|
||||
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
|
||||
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
|
||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
|
||||
readonly onHookFinished?: (input: {
|
||||
hookName: string;
|
||||
exitCode: number | null;
|
||||
durationMs: number | null;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface GitCommitProgress {
|
||||
readonly onOutputLine?: (input: {
|
||||
stream: "stdout" | "stderr";
|
||||
text: string;
|
||||
}) => Effect.Effect<void, never>;
|
||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
|
||||
readonly onHookFinished?: (input: {
|
||||
hookName: string;
|
||||
exitCode: number | null;
|
||||
durationMs: number | null;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface GitCommitOptions {
|
||||
readonly timeoutMs?: number;
|
||||
readonly progress?: GitCommitProgress;
|
||||
}
|
||||
|
||||
export interface GitPushResult {
|
||||
status: "pushed" | "skipped_up_to_date";
|
||||
branch: string;
|
||||
@@ -86,6 +132,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.
|
||||
*/
|
||||
@@ -111,6 +162,7 @@ export interface GitCoreShape {
|
||||
cwd: string,
|
||||
subject: string,
|
||||
body: string,
|
||||
options?: GitCommitOptions,
|
||||
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* @module GitManager
|
||||
*/
|
||||
import {
|
||||
GitActionProgressEvent,
|
||||
GitPreparePullRequestThreadInput,
|
||||
GitPreparePullRequestThreadResult,
|
||||
GitPullRequestRefInput,
|
||||
@@ -20,6 +21,15 @@ import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { GitManagerServiceError } from "../Errors.ts";
|
||||
|
||||
export interface GitActionProgressReporter {
|
||||
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface GitRunStackedActionOptions {
|
||||
readonly actionId?: string;
|
||||
readonly progressReporter?: GitActionProgressReporter;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitManagerShape - Service API for high-level Git workflow actions.
|
||||
*/
|
||||
@@ -51,6 +61,7 @@ export interface GitManagerShape {
|
||||
*/
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
options?: GitRunStackedActionOptions,
|
||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
|
||||
@@ -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),
|
||||
);
|
||||
|
||||
@@ -277,7 +282,10 @@ describe("CheckpointReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Test Project",
|
||||
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -288,7 +296,10 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
|
||||
@@ -35,12 +35,15 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
|
||||
|
||||
async function createOrchestrationSystem() {
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-orchestration-engine-test-",
|
||||
});
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(orchestrationLayer);
|
||||
@@ -69,7 +72,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -80,7 +86,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -123,7 +132,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "Replay Project",
|
||||
workspaceRoot: "/tmp/project-replay",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -134,7 +146,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-replay"),
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "replay",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -175,7 +190,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "Stream Project",
|
||||
workspaceRoot: "/tmp/project-stream",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -196,7 +214,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-stream"),
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "domain-stream",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -230,7 +251,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn Diff Project",
|
||||
workspaceRoot: "/tmp/project-turn-diff",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -241,7 +265,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn diff thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -317,13 +344,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),
|
||||
),
|
||||
);
|
||||
@@ -337,7 +368,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "Flaky Project",
|
||||
workspaceRoot: "/tmp/project-flaky",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -350,7 +384,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-fail",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -367,7 +404,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-ok",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -421,7 +461,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "Atomic Project",
|
||||
workspaceRoot: "/tmp/project-atomic",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -432,7 +475,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-atomic"),
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "atomic",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -556,7 +602,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "Sync Project",
|
||||
workspaceRoot: "/tmp/project-sync",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -567,7 +616,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-sync"),
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "sync-before",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -635,7 +687,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "Duplicate Project",
|
||||
workspaceRoot: "/tmp/project-duplicate",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -647,7 +702,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -664,7 +722,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
|
||||
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,
|
||||
@@ -362,7 +362,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
projectId: event.payload.projectId,
|
||||
title: event.payload.title,
|
||||
workspaceRoot: event.payload.workspaceRoot,
|
||||
defaultModel: event.payload.defaultModel,
|
||||
defaultModelSelection: event.payload.defaultModelSelection,
|
||||
scripts: event.payload.scripts,
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
@@ -383,8 +383,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
...(event.payload.workspaceRoot !== undefined
|
||||
? { workspaceRoot: event.payload.workspaceRoot }
|
||||
: {}),
|
||||
...(event.payload.defaultModel !== undefined
|
||||
? { defaultModel: event.payload.defaultModel }
|
||||
...(event.payload.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: event.payload.defaultModelSelection }
|
||||
: {}),
|
||||
...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
|
||||
updatedAt: event.payload.updatedAt,
|
||||
@@ -420,7 +420,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
projectId: event.payload.projectId,
|
||||
title: event.payload.title,
|
||||
model: event.payload.model,
|
||||
modelSelection: event.payload.modelSelection,
|
||||
runtimeMode: event.payload.runtimeMode,
|
||||
interactionMode: event.payload.interactionMode,
|
||||
branch: event.payload.branch,
|
||||
@@ -442,7 +442,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
|
||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||
...(event.payload.modelSelection !== undefined
|
||||
? { modelSelection: event.payload.modelSelection }
|
||||
: {}),
|
||||
...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
|
||||
...(event.payload.worktreePath !== undefined
|
||||
? { worktreePath: event.payload.worktreePath }
|
||||
|
||||
@@ -34,6 +34,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_provider,
|
||||
default_model,
|
||||
scripts_json,
|
||||
created_at,
|
||||
@@ -44,6 +45,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'project-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'codex',
|
||||
'gpt-5-codex',
|
||||
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
|
||||
'2026-02-24T00:00:00.000Z',
|
||||
@@ -57,6 +59,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
provider,
|
||||
model,
|
||||
branch,
|
||||
worktree_path,
|
||||
@@ -69,6 +72,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'codex',
|
||||
'gpt-5-codex',
|
||||
NULL,
|
||||
NULL,
|
||||
@@ -234,7 +238,10 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
id: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [
|
||||
{
|
||||
id: "script-1",
|
||||
@@ -254,7 +261,10 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
ChatAttachment,
|
||||
IsoDateTime,
|
||||
ModelSelection,
|
||||
MessageId,
|
||||
NonNegativeInt,
|
||||
OrchestrationCheckpointFile,
|
||||
@@ -42,12 +43,19 @@ import {
|
||||
type ProjectionSnapshotQueryShape,
|
||||
} from "../Services/ProjectionSnapshotQuery.ts";
|
||||
|
||||
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
|
||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
}),
|
||||
);
|
||||
const decodeReadModelSync = Schema.decodeUnknownSync(OrchestrationReadModel);
|
||||
const ProjectionProjectDbRowSchema = Schema.Struct({
|
||||
projectId: ProjectionProject.fields.projectId,
|
||||
title: ProjectionProject.fields.title,
|
||||
workspaceRoot: ProjectionProject.fields.workspaceRoot,
|
||||
defaultProvider: Schema.NullOr(Schema.Literals(["codex", "claudeAgent"])),
|
||||
defaultModel: Schema.NullOr(Schema.String),
|
||||
defaultModelOptions: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
createdAt: ProjectionProject.fields.createdAt,
|
||||
updatedAt: ProjectionProject.fields.updatedAt,
|
||||
deletedAt: ProjectionProject.fields.deletedAt,
|
||||
});
|
||||
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
Struct.assign({
|
||||
isStreaming: Schema.Number,
|
||||
@@ -55,7 +63,22 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread;
|
||||
const ProjectionThreadDbRowSchema = Schema.Struct({
|
||||
threadId: ProjectionThread.fields.threadId,
|
||||
projectId: ProjectionThread.fields.projectId,
|
||||
title: ProjectionThread.fields.title,
|
||||
provider: Schema.Literals(["codex", "claudeAgent"]),
|
||||
model: Schema.String,
|
||||
modelOptions: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
|
||||
runtimeMode: ProjectionThread.fields.runtimeMode,
|
||||
interactionMode: ProjectionThread.fields.interactionMode,
|
||||
branch: ProjectionThread.fields.branch,
|
||||
worktreePath: ProjectionThread.fields.worktreePath,
|
||||
latestTurnId: ProjectionThread.fields.latestTurnId,
|
||||
createdAt: ProjectionThread.fields.createdAt,
|
||||
updatedAt: ProjectionThread.fields.updatedAt,
|
||||
deletedAt: ProjectionThread.fields.deletedAt,
|
||||
});
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
Struct.assign({
|
||||
payload: Schema.fromJsonString(Schema.Unknown),
|
||||
@@ -80,6 +103,7 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
|
||||
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
|
||||
});
|
||||
const ProjectionStateDbRowSchema = ProjectionState;
|
||||
const decodeModelSelectionSync = Schema.decodeUnknownSync(ModelSelection);
|
||||
|
||||
const REQUIRED_SNAPSHOT_PROJECTORS = [
|
||||
ORCHESTRATION_PROJECTOR_NAMES.projects,
|
||||
@@ -129,6 +153,26 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
|
||||
const decodeModelSelection = (input: {
|
||||
readonly provider: "codex" | "claudeAgent";
|
||||
readonly model: string;
|
||||
readonly options: unknown;
|
||||
}) =>
|
||||
Effect.try({
|
||||
try: () =>
|
||||
decodeModelSelectionSync({
|
||||
provider: input.provider,
|
||||
model: input.model,
|
||||
...(input.options !== null && input.options !== undefined
|
||||
? { options: input.options }
|
||||
: {}),
|
||||
}),
|
||||
catch: (error) =>
|
||||
Schema.isSchemaError(error)
|
||||
? toPersistenceDecodeError("ProjectionSnapshotQuery.decodeModelSelection")(error)
|
||||
: toPersistenceSqlError("ProjectionSnapshotQuery.decodeModelSelection")(error),
|
||||
});
|
||||
|
||||
const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
@@ -141,7 +185,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_provider AS "defaultProvider",
|
||||
default_model AS "defaultModel",
|
||||
default_model_options_json AS "defaultModelOptions",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -160,7 +206,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
provider,
|
||||
model,
|
||||
model_options_json AS "modelOptions",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
@@ -531,36 +579,65 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const projects: Array<OrchestrationProject> = projectRows.map((row) => ({
|
||||
id: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModel: row.defaultModel,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
}));
|
||||
const projects: ReadonlyArray<OrchestrationProject> = yield* Effect.forEach(
|
||||
projectRows,
|
||||
(row) => {
|
||||
const defaultModelSelectionEffect: Effect.Effect<
|
||||
OrchestrationProject["defaultModelSelection"],
|
||||
ProjectionRepositoryError
|
||||
> =
|
||||
row.defaultProvider === null || row.defaultModel === null
|
||||
? Effect.succeed(null)
|
||||
: decodeModelSelection({
|
||||
provider: row.defaultProvider,
|
||||
model: row.defaultModel,
|
||||
options: row.defaultModelOptions,
|
||||
});
|
||||
|
||||
const threads: Array<OrchestrationThread> = threadRows.map((row) => ({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
model: row.model,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
activities: activitiesByThread.get(row.threadId) ?? [],
|
||||
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
|
||||
session: sessionsByThread.get(row.threadId) ?? null,
|
||||
}));
|
||||
return defaultModelSelectionEffect.pipe(
|
||||
Effect.map((defaultModelSelection) => ({
|
||||
id: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
})),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const threads: ReadonlyArray<OrchestrationThread> = yield* Effect.forEach(
|
||||
threadRows,
|
||||
(row) =>
|
||||
decodeModelSelection({
|
||||
provider: row.provider,
|
||||
model: row.model,
|
||||
options: row.modelOptions,
|
||||
}).pipe(
|
||||
Effect.map((modelSelection) => ({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
activities: activitiesByThread.get(row.threadId) ?? [],
|
||||
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
|
||||
session: sessionsByThread.get(row.threadId) ?? null,
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
const snapshot = {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
@@ -569,11 +646,13 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
updatedAt: updatedAt ?? new Date(0).toISOString(),
|
||||
};
|
||||
|
||||
return yield* decodeReadModel(snapshot).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel"),
|
||||
),
|
||||
);
|
||||
return yield* Effect.try({
|
||||
try: () => decodeReadModelSync(snapshot),
|
||||
catch: (error) =>
|
||||
toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel")(
|
||||
error as Schema.SchemaError,
|
||||
),
|
||||
});
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
|
||||
@@ -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,
|
||||
@@ -60,6 +63,9 @@ async function waitFor(
|
||||
return poll();
|
||||
}
|
||||
|
||||
const inferTestProviderForModel = (model: string): "codex" | "claudeAgent" =>
|
||||
model.startsWith("claude-") ? "claudeAgent" : "codex";
|
||||
|
||||
describe("ProviderCommandReactor", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | ProviderCommandReactor,
|
||||
@@ -67,6 +73,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 +88,23 @@ 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 threadProvider = inferTestProviderForModel(threadModel);
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
let nextSessionIndex = 1;
|
||||
const runtimeSessions: Array<ProviderSession> = [];
|
||||
@@ -214,7 +228,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);
|
||||
@@ -232,7 +246,10 @@ describe("ProviderCommandReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot: "/tmp/provider-project",
|
||||
defaultModel: threadModel,
|
||||
defaultModelSelection: {
|
||||
provider: threadProvider,
|
||||
model: threadModel,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -243,7 +260,10 @@ describe("ProviderCommandReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: threadModel,
|
||||
modelSelection: {
|
||||
provider: threadProvider,
|
||||
model: threadModel,
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -318,10 +338,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello fast mode",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -370,10 +390,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello with effort",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
@@ -420,10 +440,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello with fast mode",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
@@ -508,7 +528,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello claude",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
@@ -542,50 +565,41 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a turn when the requested model belongs to a different provider", async () => {
|
||||
it("allows custom model strings on the thread's explicit provider", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-model-provider-mismatch"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-custom-model"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-model-provider-mismatch"),
|
||||
messageId: asMessageId("user-message-custom-model"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
model: "claude-sonnet-4-6",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
);
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
provider: "codex",
|
||||
model: "claude-sonnet-4-6",
|
||||
});
|
||||
|
||||
expect(harness.startSession).not.toHaveBeenCalled();
|
||||
expect(harness.sendTurn).not.toHaveBeenCalled();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
).toMatchObject({
|
||||
payload: {
|
||||
detail: expect.stringContaining("does not belong to provider 'codex'"),
|
||||
},
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
model: "claude-sonnet-4-6",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -650,10 +664,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "first claude turn",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "medium",
|
||||
},
|
||||
},
|
||||
@@ -677,10 +691,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "second claude turn",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
@@ -825,7 +839,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
CommandId,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
EventId,
|
||||
type ModelSelection,
|
||||
type OrchestrationEvent,
|
||||
type ProviderModelOptions,
|
||||
ProviderKind,
|
||||
@@ -26,7 +27,6 @@ import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
} from "../Services/ProviderCommandReactor.ts";
|
||||
import { inferProviderForModel } from "@t3tools/shared/model";
|
||||
|
||||
type ProviderIntentEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
@@ -81,6 +81,17 @@ const sameModelOptions = (
|
||||
right: ProviderModelOptions | undefined,
|
||||
): boolean => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
|
||||
|
||||
function toProviderModelOptions(
|
||||
modelSelection: ModelSelection | undefined,
|
||||
): ProviderModelOptions | undefined {
|
||||
if (!modelSelection?.options) {
|
||||
return undefined;
|
||||
}
|
||||
return modelSelection.provider === "codex"
|
||||
? { codex: modelSelection.options }
|
||||
: { claudeAgent: modelSelection.options };
|
||||
}
|
||||
|
||||
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||
const error = Cause.squash(cause);
|
||||
if (Schema.is(ProviderAdapterRequestError)(error)) {
|
||||
@@ -215,8 +226,7 @@ const make = Effect.gen(function* () {
|
||||
threadId: ThreadId,
|
||||
createdAt: string,
|
||||
options?: {
|
||||
readonly provider?: ProviderKind;
|
||||
readonly model?: string;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly providerOptions?: ProviderStartOptions;
|
||||
},
|
||||
@@ -233,26 +243,23 @@ const make = Effect.gen(function* () {
|
||||
)
|
||||
? thread.session.providerName
|
||||
: undefined;
|
||||
const threadProvider: ProviderKind = currentProvider ?? inferProviderForModel(thread.model);
|
||||
if (options?.provider !== undefined && options.provider !== threadProvider) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: threadProvider,
|
||||
method: "thread.turn.start",
|
||||
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${options.provider}'.`,
|
||||
});
|
||||
}
|
||||
const requestedModelSelection = options?.modelSelection;
|
||||
const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider;
|
||||
if (
|
||||
options?.model !== undefined &&
|
||||
inferProviderForModel(options.model, threadProvider) !== threadProvider
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== threadProvider
|
||||
) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: threadProvider,
|
||||
method: "thread.turn.start",
|
||||
detail: `Model '${options.model}' does not belong to provider '${threadProvider}' for thread '${threadId}'.`,
|
||||
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
|
||||
});
|
||||
}
|
||||
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
|
||||
const desiredModel = options?.model ?? thread.model;
|
||||
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
|
||||
const desiredModel = desiredModelSelection.model;
|
||||
const desiredModelOptions =
|
||||
options?.modelOptions ?? toProviderModelOptions(desiredModelSelection);
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
@@ -269,12 +276,10 @@ const make = Effect.gen(function* () {
|
||||
}) =>
|
||||
providerService.startSession(threadId, {
|
||||
threadId,
|
||||
...((input?.provider ?? preferredProvider)
|
||||
? { provider: input?.provider ?? preferredProvider }
|
||||
: {}),
|
||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||
...(desiredModel ? { model: desiredModel } : {}),
|
||||
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
|
||||
...(desiredModelOptions !== undefined ? { modelOptions: desiredModelOptions } : {}),
|
||||
...(options?.providerOptions !== undefined
|
||||
? { providerOptions: options.providerOptions }
|
||||
: {}),
|
||||
@@ -303,13 +308,16 @@ const make = Effect.gen(function* () {
|
||||
if (existingSessionThreadId) {
|
||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||
const providerChanged =
|
||||
options?.provider !== undefined && options.provider !== currentProvider;
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== currentProvider;
|
||||
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
|
||||
const sessionModelSwitch =
|
||||
currentProvider === undefined
|
||||
? "in-session"
|
||||
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
|
||||
const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;
|
||||
const modelChanged =
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.model !== activeSession?.model;
|
||||
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
|
||||
const previousModelOptions = threadModelOptions.get(threadId);
|
||||
const shouldRestartForModelOptionsChange =
|
||||
@@ -334,7 +342,7 @@ const make = Effect.gen(function* () {
|
||||
threadId,
|
||||
existingSessionThreadId,
|
||||
currentProvider,
|
||||
desiredProvider: options?.provider ?? currentProvider,
|
||||
desiredProvider: desiredModelSelection.provider,
|
||||
currentRuntimeMode: thread.session?.runtimeMode,
|
||||
desiredRuntimeMode: thread.runtimeMode,
|
||||
runtimeModeChanged,
|
||||
@@ -344,10 +352,9 @@ const make = Effect.gen(function* () {
|
||||
shouldRestartForModelOptionsChange,
|
||||
hasResumeCursor: resumeCursor !== undefined,
|
||||
});
|
||||
const restartedSession = yield* startProviderSession({
|
||||
...(resumeCursor !== undefined ? { resumeCursor } : {}),
|
||||
...(options?.provider !== undefined ? { provider: options.provider } : {}),
|
||||
});
|
||||
const restartedSession = yield* startProviderSession(
|
||||
resumeCursor !== undefined ? { resumeCursor } : undefined,
|
||||
);
|
||||
yield* Effect.logInfo("provider command reactor restarted provider session", {
|
||||
threadId,
|
||||
previousSessionId: existingSessionThreadId,
|
||||
@@ -359,9 +366,7 @@ const make = Effect.gen(function* () {
|
||||
return restartedSession.threadId;
|
||||
}
|
||||
|
||||
const startedSession = yield* startProviderSession(
|
||||
options?.provider !== undefined ? { provider: options.provider } : undefined,
|
||||
);
|
||||
const startedSession = yield* startProviderSession(undefined);
|
||||
yield* bindSessionToThread(startedSession);
|
||||
return startedSession.threadId;
|
||||
});
|
||||
@@ -370,8 +375,7 @@ const make = Effect.gen(function* () {
|
||||
readonly threadId: ThreadId;
|
||||
readonly messageText: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
readonly provider?: ProviderKind;
|
||||
readonly model?: string;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly providerOptions?: ProviderStartOptions;
|
||||
readonly interactionMode?: "default" | "plan";
|
||||
@@ -382,8 +386,7 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
||||
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
|
||||
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
|
||||
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
|
||||
});
|
||||
@@ -404,7 +407,8 @@ const make = Effect.gen(function* () {
|
||||
activeSession === undefined
|
||||
? "in-session"
|
||||
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
|
||||
const modelForTurn = sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;
|
||||
const modelForTurn =
|
||||
sessionModelSwitch === "unsupported" ? activeSession?.model : input.modelSelection?.model;
|
||||
|
||||
yield* providerService.sendTurn({
|
||||
threadId: input.threadId,
|
||||
@@ -520,15 +524,18 @@ const make = Effect.gen(function* () {
|
||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
const requestedModelOptions = event.payload.modelSelection
|
||||
? toProviderModelOptions(event.payload.modelSelection)
|
||||
: undefined;
|
||||
|
||||
yield* sendTurnForThread({
|
||||
threadId: event.payload.threadId,
|
||||
messageText: message.text,
|
||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||
...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),
|
||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||
...(event.payload.modelOptions !== undefined
|
||||
? { modelOptions: event.payload.modelOptions }
|
||||
...(event.payload.modelSelection !== undefined
|
||||
? { modelSelection: event.payload.modelSelection }
|
||||
: {}),
|
||||
...(requestedModelOptions !== undefined ? { modelOptions: requestedModelOptions } : {}),
|
||||
...(event.payload.providerOptions !== undefined
|
||||
? { providerOptions: event.payload.providerOptions }
|
||||
: {}),
|
||||
|
||||
@@ -187,7 +187,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -198,7 +201,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -724,7 +730,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -756,7 +765,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: targetThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Target",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -905,7 +917,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -1055,7 +1070,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -1087,7 +1105,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: targetThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Target",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
|
||||
@@ -28,7 +28,10 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Project A",
|
||||
workspaceRoot: "/tmp/project-a",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -38,7 +41,10 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ProjectId.makeUnsafe("project-b"),
|
||||
title: "Project B",
|
||||
workspaceRoot: "/tmp/project-b",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -50,7 +56,10 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Thread A",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -69,7 +78,10 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ThreadId.makeUnsafe("thread-2"),
|
||||
projectId: ProjectId.makeUnsafe("project-b"),
|
||||
title: "Thread B",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -144,7 +156,10 @@ describe("commandInvariants", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-3"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "new",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -165,7 +180,10 @@ describe("commandInvariants", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "dup",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
|
||||
@@ -59,7 +59,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-scripts"),
|
||||
title: "Scripts",
|
||||
workspaceRoot: "/tmp/scripts",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -113,7 +113,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -136,7 +136,10 @@ describe("decider project scripts", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -159,10 +162,10 @@ describe("decider project scripts", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -189,10 +192,10 @@ describe("decider project scripts", () => {
|
||||
expect(turnStartEvent.payload).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
messageId: asMessageId("message-user-1"),
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -220,7 +223,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -243,7 +246,10 @@ describe("decider project scripts", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -299,7 +305,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -322,7 +328,10 @@ describe("decider project scripts", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
|
||||
@@ -77,7 +77,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
projectId: command.projectId,
|
||||
title: command.title,
|
||||
workspaceRoot: command.workspaceRoot,
|
||||
defaultModel: command.defaultModel ?? null,
|
||||
defaultModelSelection: command.defaultModelSelection ?? null,
|
||||
scripts: [],
|
||||
createdAt: command.createdAt,
|
||||
updatedAt: command.createdAt,
|
||||
@@ -104,7 +104,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
projectId: command.projectId,
|
||||
...(command.title !== undefined ? { title: command.title } : {}),
|
||||
...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),
|
||||
...(command.defaultModel !== undefined ? { defaultModel: command.defaultModel } : {}),
|
||||
...(command.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: command.defaultModelSelection }
|
||||
: {}),
|
||||
...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
@@ -156,7 +158,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
projectId: command.projectId,
|
||||
title: command.title,
|
||||
model: command.model,
|
||||
modelSelection: command.modelSelection,
|
||||
runtimeMode: command.runtimeMode,
|
||||
interactionMode: command.interactionMode,
|
||||
branch: command.branch,
|
||||
@@ -207,7 +209,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
...(command.title !== undefined ? { title: command.title } : {}),
|
||||
...(command.model !== undefined ? { model: command.model } : {}),
|
||||
...(command.modelSelection !== undefined
|
||||
? { modelSelection: command.modelSelection }
|
||||
: {}),
|
||||
...(command.branch !== undefined ? { branch: command.branch } : {}),
|
||||
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
|
||||
updatedAt: occurredAt,
|
||||
@@ -323,9 +327,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: command.message.messageId,
|
||||
...(command.provider !== undefined ? { provider: command.provider } : {}),
|
||||
...(command.model !== undefined ? { model: command.model } : {}),
|
||||
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
|
||||
...(command.modelSelection !== undefined
|
||||
? { modelSelection: command.modelSelection }
|
||||
: {}),
|
||||
...(command.providerOptions !== undefined
|
||||
? { providerOptions: command.providerOptions }
|
||||
: {}),
|
||||
|
||||
@@ -56,7 +56,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -73,7 +76,10 @@ describe("orchestration projector", () => {
|
||||
id: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
@@ -110,7 +116,10 @@ describe("orchestration projector", () => {
|
||||
// missing required threadId
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -170,7 +179,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -233,7 +245,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -287,7 +302,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -371,7 +389,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -583,7 +604,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-revert",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -733,7 +757,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-capped",
|
||||
projectId: "project-1",
|
||||
title: "capped",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
|
||||
@@ -181,7 +181,7 @@ export function projectEvent(
|
||||
id: payload.projectId,
|
||||
title: payload.title,
|
||||
workspaceRoot: payload.workspaceRoot,
|
||||
defaultModel: payload.defaultModel,
|
||||
defaultModelSelection: payload.defaultModelSelection,
|
||||
scripts: payload.scripts,
|
||||
createdAt: payload.createdAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
@@ -211,8 +211,8 @@ export function projectEvent(
|
||||
...(payload.workspaceRoot !== undefined
|
||||
? { workspaceRoot: payload.workspaceRoot }
|
||||
: {}),
|
||||
...(payload.defaultModel !== undefined
|
||||
? { defaultModel: payload.defaultModel }
|
||||
...(payload.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: payload.defaultModelSelection }
|
||||
: {}),
|
||||
...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),
|
||||
updatedAt: payload.updatedAt,
|
||||
@@ -252,7 +252,7 @@ export function projectEvent(
|
||||
id: payload.threadId,
|
||||
projectId: payload.projectId,
|
||||
title: payload.title,
|
||||
model: payload.model,
|
||||
modelSelection: payload.modelSelection,
|
||||
runtimeMode: payload.runtimeMode,
|
||||
interactionMode: payload.interactionMode,
|
||||
branch: payload.branch,
|
||||
@@ -295,7 +295,9 @@ export function projectEvent(
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
...(payload.title !== undefined ? { title: payload.title } : {}),
|
||||
...(payload.model !== undefined ? { model: payload.model } : {}),
|
||||
...(payload.modelSelection !== undefined
|
||||
? { modelSelection: payload.modelSelection }
|
||||
: {}),
|
||||
...(payload.branch !== undefined ? { branch: payload.branch } : {}),
|
||||
...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),
|
||||
updatedAt: payload.updatedAt,
|
||||
|
||||
@@ -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()));
|
||||
});
|
||||
@@ -35,7 +35,7 @@ layer("OrchestrationEventStore", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-roundtrip"),
|
||||
title: "Roundtrip Project",
|
||||
workspaceRoot: "/tmp/project-roundtrip",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer, Option, Schema, Struct } from "effect";
|
||||
|
||||
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
|
||||
import { Effect, Layer, Option, Schema } from "effect";
|
||||
|
||||
import { ModelSelection, ProjectScript } from "@t3tools/contracts";
|
||||
import {
|
||||
PersistenceDecodeError,
|
||||
toPersistenceDecodeError,
|
||||
toPersistenceSqlError,
|
||||
} from "../Errors.ts";
|
||||
import {
|
||||
DeleteProjectionProjectInput,
|
||||
GetProjectionProjectInput,
|
||||
@@ -11,69 +15,100 @@ import {
|
||||
ProjectionProjectRepository,
|
||||
type ProjectionProjectRepositoryShape,
|
||||
} from "../Services/ProjectionProjects.ts";
|
||||
import { ProjectScript } from "@t3tools/contracts";
|
||||
|
||||
// Makes sure that the scripts are parsed from the JSON string the DB returns
|
||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
Struct.assign({ scripts: Schema.fromJsonString(Schema.Array(ProjectScript)) }),
|
||||
);
|
||||
const ProjectionProjectDbRow = Schema.Struct({
|
||||
projectId: ProjectionProject.fields.projectId,
|
||||
title: ProjectionProject.fields.title,
|
||||
workspaceRoot: ProjectionProject.fields.workspaceRoot,
|
||||
defaultProvider: Schema.NullOr(Schema.Literals(["codex", "claudeAgent"])),
|
||||
defaultModel: Schema.NullOr(Schema.String),
|
||||
defaultModelOptions: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
createdAt: ProjectionProject.fields.createdAt,
|
||||
updatedAt: ProjectionProject.fields.updatedAt,
|
||||
deletedAt: ProjectionProject.fields.deletedAt,
|
||||
});
|
||||
type ProjectionProjectDbRow = typeof ProjectionProjectDbRow.Type;
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown) =>
|
||||
Schema.isSchemaError(cause)
|
||||
? toPersistenceDecodeError(decodeOperation)(cause)
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
const decodeModelSelectionSync = Schema.decodeUnknownSync(ModelSelection);
|
||||
|
||||
function decodeDefaultModelSelection(
|
||||
row: ProjectionProjectDbRow,
|
||||
): Effect.Effect<ProjectionProject["defaultModelSelection"], PersistenceDecodeError> {
|
||||
if (row.defaultProvider === null || row.defaultModel === null) {
|
||||
return Effect.succeed(null);
|
||||
}
|
||||
return Effect.try({
|
||||
try: () =>
|
||||
decodeModelSelectionSync({
|
||||
provider: row.defaultProvider,
|
||||
model: row.defaultModel,
|
||||
...(row.defaultModelOptions !== null ? { options: row.defaultModelOptions } : {}),
|
||||
}),
|
||||
catch: (error) =>
|
||||
toPersistenceDecodeError("ProjectionProjectRepository.decodeDefaultModelSelection")(
|
||||
error as Schema.SchemaError,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertProjectionProjectRow = SqlSchema.void({
|
||||
Request: ProjectionProjectDbRowSchema,
|
||||
Request: ProjectionProject,
|
||||
execute: (row) =>
|
||||
sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
${row.projectId},
|
||||
${row.title},
|
||||
${row.workspaceRoot},
|
||||
${row.defaultModel},
|
||||
${row.scripts},
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.deletedAt}
|
||||
)
|
||||
ON CONFLICT (project_id)
|
||||
DO UPDATE SET
|
||||
title = excluded.title,
|
||||
workspace_root = excluded.workspace_root,
|
||||
default_model = excluded.default_model,
|
||||
scripts_json = excluded.scripts_json,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
deleted_at = excluded.deleted_at
|
||||
`,
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_provider,
|
||||
default_model,
|
||||
default_model_options_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
${row.projectId},
|
||||
${row.title},
|
||||
${row.workspaceRoot},
|
||||
${row.defaultModelSelection?.provider ?? null},
|
||||
${row.defaultModelSelection?.model ?? null},
|
||||
${JSON.stringify(row.defaultModelSelection?.options ?? null)},
|
||||
${JSON.stringify(row.scripts)},
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.deletedAt}
|
||||
)
|
||||
ON CONFLICT (project_id)
|
||||
DO UPDATE SET
|
||||
title = excluded.title,
|
||||
workspace_root = excluded.workspace_root,
|
||||
default_provider = excluded.default_provider,
|
||||
default_model = excluded.default_model,
|
||||
default_model_options_json = excluded.default_model_options_json,
|
||||
scripts_json = excluded.scripts_json,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
deleted_at = excluded.deleted_at
|
||||
`,
|
||||
});
|
||||
|
||||
const getProjectionProjectRow = SqlSchema.findOneOption({
|
||||
Request: GetProjectionProjectInput,
|
||||
Result: ProjectionProjectDbRowSchema,
|
||||
Result: ProjectionProjectDbRow,
|
||||
execute: ({ projectId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_provider AS "defaultProvider",
|
||||
default_model AS "defaultModel",
|
||||
default_model_options_json AS "defaultModelOptions",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -85,14 +120,16 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
|
||||
const listProjectionProjectRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionProjectDbRowSchema,
|
||||
Result: ProjectionProjectDbRow,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_provider AS "defaultProvider",
|
||||
default_model AS "defaultModel",
|
||||
default_model_options_json AS "defaultModelOptions",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -113,40 +150,53 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
|
||||
const upsert: ProjectionProjectRepositoryShape["upsert"] = (row) =>
|
||||
upsertProjectionProjectRow(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionProjectRepository.upsert:query",
|
||||
"ProjectionProjectRepository.upsert:encodeRequest",
|
||||
),
|
||||
),
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.upsert:query")),
|
||||
);
|
||||
|
||||
const getById: ProjectionProjectRepositoryShape["getById"] = (input) =>
|
||||
getProjectionProjectRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionProjectRepository.getById:query",
|
||||
"ProjectionProjectRepository.getById:decodeRow",
|
||||
),
|
||||
),
|
||||
Effect.flatMap((rowOption) =>
|
||||
Option.match(rowOption, {
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.getById:query")),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed(Option.none()),
|
||||
onSome: (row) =>
|
||||
Effect.succeed(Option.some(row as Schema.Schema.Type<typeof ProjectionProject>)),
|
||||
decodeDefaultModelSelection(row).pipe(
|
||||
Effect.map((defaultModelSelection) =>
|
||||
Option.some({
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
}),
|
||||
),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listAll: ProjectionProjectRepositoryShape["listAll"] = () =>
|
||||
listProjectionProjectRows().pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionProjectRepository.listAll:query",
|
||||
"ProjectionProjectRepository.listAll:decodeRows",
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.listAll:query")),
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(rows, (row) =>
|
||||
decodeDefaultModelSelection(row).pipe(
|
||||
Effect.map((defaultModelSelection) => ({
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
})),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map((rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionProject>>),
|
||||
);
|
||||
|
||||
const deleteById: ProjectionProjectRepositoryShape["deleteById"] = (input) =>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { Effect, Layer, Option, Schema } from "effect";
|
||||
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import { ModelSelection } from "@t3tools/contracts";
|
||||
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
DeleteProjectionThreadInput,
|
||||
GetProjectionThreadInput,
|
||||
@@ -12,6 +13,53 @@ import {
|
||||
type ProjectionThreadRepositoryShape,
|
||||
} from "../Services/ProjectionThreads.ts";
|
||||
|
||||
const ProjectionThreadDbRow = Schema.Struct({
|
||||
threadId: ProjectionThread.fields.threadId,
|
||||
projectId: ProjectionThread.fields.projectId,
|
||||
title: ProjectionThread.fields.title,
|
||||
provider: Schema.Literals(["codex", "claudeAgent"]),
|
||||
model: Schema.String,
|
||||
modelOptions: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
|
||||
runtimeMode: ProjectionThread.fields.runtimeMode,
|
||||
interactionMode: ProjectionThread.fields.interactionMode,
|
||||
branch: ProjectionThread.fields.branch,
|
||||
worktreePath: ProjectionThread.fields.worktreePath,
|
||||
latestTurnId: ProjectionThread.fields.latestTurnId,
|
||||
createdAt: ProjectionThread.fields.createdAt,
|
||||
updatedAt: ProjectionThread.fields.updatedAt,
|
||||
deletedAt: ProjectionThread.fields.deletedAt,
|
||||
});
|
||||
type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;
|
||||
|
||||
const decodeModelSelectionSync = Schema.decodeUnknownSync(ModelSelection);
|
||||
|
||||
function decodeProjectionThread(row: ProjectionThreadDbRow) {
|
||||
return Effect.try({
|
||||
try: () => ({
|
||||
threadId: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection: decodeModelSelectionSync({
|
||||
provider: row.provider,
|
||||
model: row.model,
|
||||
...(row.modelOptions !== null ? { options: row.modelOptions } : {}),
|
||||
}),
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurnId: row.latestTurnId,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
}),
|
||||
catch: (error) =>
|
||||
toPersistenceDecodeError("ProjectionThreadRepository.decodeProjectionThread")(
|
||||
error as Schema.SchemaError,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
@@ -23,7 +71,9 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
provider,
|
||||
model,
|
||||
model_options_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
@@ -37,7 +87,9 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
${row.projectId},
|
||||
${row.title},
|
||||
${row.model},
|
||||
${row.modelSelection.provider},
|
||||
${row.modelSelection.model},
|
||||
${JSON.stringify(row.modelSelection.options ?? null)},
|
||||
${row.runtimeMode},
|
||||
${row.interactionMode},
|
||||
${row.branch},
|
||||
@@ -51,7 +103,9 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
DO UPDATE SET
|
||||
project_id = excluded.project_id,
|
||||
title = excluded.title,
|
||||
provider = excluded.provider,
|
||||
model = excluded.model,
|
||||
model_options_json = excluded.model_options_json,
|
||||
runtime_mode = excluded.runtime_mode,
|
||||
interaction_mode = excluded.interaction_mode,
|
||||
branch = excluded.branch,
|
||||
@@ -65,14 +119,16 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
|
||||
const getProjectionThreadRow = SqlSchema.findOneOption({
|
||||
Request: GetProjectionThreadInput,
|
||||
Result: ProjectionThread,
|
||||
Result: ProjectionThreadDbRow,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
provider,
|
||||
model,
|
||||
model_options_json AS "modelOptions",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
@@ -88,14 +144,16 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
|
||||
const listProjectionThreadRows = SqlSchema.findAll({
|
||||
Request: ListProjectionThreadsByProjectInput,
|
||||
Result: ProjectionThread,
|
||||
Result: ProjectionThreadDbRow,
|
||||
execute: ({ projectId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
provider,
|
||||
model,
|
||||
model_options_json AS "modelOptions",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
@@ -127,11 +185,18 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
const getById: ProjectionThreadRepositoryShape["getById"] = (input) =>
|
||||
getProjectionThreadRow(input).pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.getById:query")),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed(Option.none()),
|
||||
onSome: (row) => decodeProjectionThread(row).pipe(Effect.map(Option.some)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listByProjectId: ProjectionThreadRepositoryShape["listByProjectId"] = (input) =>
|
||||
listProjectionThreadRows(input).pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.listByProjectId:query")),
|
||||
Effect.flatMap((rows) => Effect.forEach(rows, decodeProjectionThread)),
|
||||
);
|
||||
|
||||
const deleteById: ProjectionThreadRepositoryShape["deleteById"] = (input) =>
|
||||
|
||||
@@ -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)),
|
||||
);
|
||||
@@ -27,6 +27,8 @@ import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts"
|
||||
import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
|
||||
import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
|
||||
import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
|
||||
import Migration0016 from "./Migrations/016_ProjectionProviders.ts";
|
||||
import Migration0017 from "./Migrations/017_ProjectionModelSelectionOptions.ts";
|
||||
import { Effect } from "effect";
|
||||
|
||||
/**
|
||||
@@ -55,6 +57,8 @@ const loader = Migrator.fromRecord({
|
||||
"13_ProjectionThreadProposedPlans": Migration0013,
|
||||
"14_ProjectionThreadProposedPlanImplementation": Migration0014,
|
||||
"15_ProjectionTurnsSourceProposedPlan": Migration0015,
|
||||
"16_ProjectionProviders": Migration0016,
|
||||
"17_ProjectionModelSelectionOptions": Migration0017,
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_projects
|
||||
ADD COLUMN default_provider TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_projects
|
||||
SET default_provider = CASE
|
||||
WHEN default_model IS NULL THEN NULL
|
||||
ELSE 'codex'
|
||||
END
|
||||
WHERE default_provider IS NULL
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN provider TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET provider = COALESCE(
|
||||
(
|
||||
SELECT provider_name
|
||||
FROM projection_thread_sessions
|
||||
WHERE projection_thread_sessions.thread_id = projection_threads.thread_id
|
||||
),
|
||||
'codex'
|
||||
)
|
||||
WHERE provider IS NULL
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_projects
|
||||
ADD COLUMN default_model_options_json TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_projects
|
||||
SET default_model_options_json = NULL
|
||||
WHERE default_model_options_json IS NULL
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN model_options_json TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET model_options_json = NULL
|
||||
WHERE model_options_json IS NULL
|
||||
`;
|
||||
});
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module ProjectionProjectRepository
|
||||
*/
|
||||
import { IsoDateTime, ProjectId, ProjectScript } from "@t3tools/contracts";
|
||||
import { IsoDateTime, ModelSelection, ProjectId, ProjectScript } from "@t3tools/contracts";
|
||||
import { Option, Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
@@ -16,7 +16,7 @@ export const ProjectionProject = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: Schema.String,
|
||||
workspaceRoot: Schema.String,
|
||||
defaultModel: Schema.NullOr(Schema.String),
|
||||
defaultModelSelection: Schema.NullOr(ModelSelection),
|
||||
scripts: Schema.Array(ProjectScript),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
import {
|
||||
IsoDateTime,
|
||||
ModelSelection,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
@@ -23,7 +24,7 @@ export const ProjectionThread = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: Schema.String,
|
||||
model: Schema.String,
|
||||
modelSelection: ModelSelection,
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode,
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
|
||||
@@ -133,7 +133,7 @@ function makeHarness(config?: {
|
||||
readonly nativeEventLogPath?: string;
|
||||
readonly nativeEventLogger?: ClaudeAdapterLiveOptions["nativeEventLogger"];
|
||||
readonly cwd?: string;
|
||||
readonly stateDir?: string;
|
||||
readonly baseDir?: string;
|
||||
}) {
|
||||
const query = new FakeClaudeQuery();
|
||||
let createInput:
|
||||
@@ -165,7 +165,7 @@ function makeHarness(config?: {
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(
|
||||
config?.cwd ?? "/tmp/claude-adapter-test",
|
||||
config?.stateDir ?? "/tmp",
|
||||
config?.baseDir ?? "/tmp",
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -272,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(
|
||||
@@ -280,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* () {
|
||||
@@ -515,15 +536,15 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
it.effect("embeds image attachments in Claude user messages", () => {
|
||||
const stateDir = mkdtempSync(path.join(os.tmpdir(), "claude-attachments-"));
|
||||
const baseDir = mkdtempSync(path.join(os.tmpdir(), "claude-attachments-"));
|
||||
const harness = makeHarness({
|
||||
cwd: "/tmp/project-claude-attachments",
|
||||
stateDir,
|
||||
baseDir,
|
||||
});
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() =>
|
||||
rmSync(stateDir, {
|
||||
rmSync(baseDir, {
|
||||
recursive: true,
|
||||
force: true,
|
||||
}),
|
||||
@@ -531,6 +552,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
const { attachmentsDir } = yield* ServerConfig;
|
||||
|
||||
const attachment = {
|
||||
type: "image" as const,
|
||||
@@ -539,7 +561,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4,
|
||||
};
|
||||
const attachmentPath = path.join(stateDir, "attachments", attachmentRelativePath(attachment));
|
||||
const attachmentPath = path.join(attachmentsDir, attachmentRelativePath(attachment));
|
||||
mkdirSync(path.dirname(attachmentPath), { recursive: true });
|
||||
writeFileSync(attachmentPath, Uint8Array.from([1, 2, 3, 4]));
|
||||
|
||||
@@ -1131,6 +1153,73 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("stopSession does not throw into the SDK prompt consumer", () => {
|
||||
// The SDK consumes user messages via `for await (... of prompt)`.
|
||||
// Stopping a session must end that loop cleanly — not throw an error.
|
||||
//
|
||||
// FakeClaudeQuery.close() masks this by resolving pending iterators
|
||||
// before the shutdown propagates. Override it to match real SDK behavior
|
||||
// where close() does not resolve the prompt consumer.
|
||||
const query = new FakeClaudeQuery();
|
||||
(query as { close: () => void }).close = () => {
|
||||
query.closeCalls += 1;
|
||||
};
|
||||
|
||||
let promptConsumerError: unknown = undefined;
|
||||
|
||||
const layer = makeClaudeAdapterLive({
|
||||
createQuery: (input) => {
|
||||
// Simulate the SDK consuming the prompt iterable
|
||||
(async () => {
|
||||
try {
|
||||
for await (const _message of input.prompt) {
|
||||
/* SDK processes user messages */
|
||||
}
|
||||
} catch (error) {
|
||||
promptConsumerError = error;
|
||||
}
|
||||
})();
|
||||
return query;
|
||||
},
|
||||
}).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = Effect.runFork(
|
||||
Stream.runForEach(adapter.streamEvents, () => Effect.void),
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.stopSession(THREAD_ID);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 50)));
|
||||
|
||||
runtimeEventsFiber.interruptUnsafe();
|
||||
|
||||
assert.equal(
|
||||
promptConsumerError,
|
||||
undefined,
|
||||
`Prompt consumer should not receive a thrown error on session stop, ` +
|
||||
`but got: "${promptConsumerError instanceof Error ? promptConsumerError.message : String(promptConsumerError)}"`,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("forwards Claude task progress summaries for subagent updates", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
type PermissionUpdate,
|
||||
type SDKMessage,
|
||||
type SDKResultMessage,
|
||||
type SettingSource,
|
||||
type SDKUserMessage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
@@ -426,6 +427,11 @@ const SUPPORTED_CLAUDE_IMAGE_MIME_TYPES = new Set([
|
||||
"image/png",
|
||||
"image/webp",
|
||||
]);
|
||||
const CLAUDE_SETTING_SOURCES = [
|
||||
"user",
|
||||
"project",
|
||||
"local",
|
||||
] as const satisfies ReadonlyArray<SettingSource>;
|
||||
|
||||
function buildPromptText(input: ProviderSendTurnInput): string {
|
||||
const requestedEffort = resolveReasoningEffortForProvider(
|
||||
@@ -474,7 +480,7 @@ function buildUserMessageEffect(
|
||||
input: ProviderSendTurnInput,
|
||||
dependencies: {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly stateDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
},
|
||||
): Effect.Effect<SDKUserMessage, ProviderAdapterRequestError> {
|
||||
return Effect.gen(function* () {
|
||||
@@ -499,7 +505,7 @@ function buildUserMessageEffect(
|
||||
}
|
||||
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
stateDir: dependencies.stateDir,
|
||||
attachmentsDir: dependencies.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
@@ -2252,6 +2258,9 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
const prompt = Stream.fromQueue(promptQueue).pipe(
|
||||
Stream.filter((item) => item.type === "message"),
|
||||
Stream.map((item) => item.message),
|
||||
Stream.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),
|
||||
),
|
||||
Stream.toAsyncIterable,
|
||||
);
|
||||
|
||||
@@ -2562,6 +2571,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
pathToClaudeCodeExecutable: providerOptions?.binaryPath ?? "claude",
|
||||
settingSources: [...CLAUDE_SETTING_SOURCES],
|
||||
...(effectiveEffort ? { effort: effectiveEffort } : {}),
|
||||
...(permissionMode ? { permissionMode } : {}),
|
||||
...(permissionMode === "bypassPermissions"
|
||||
@@ -2765,7 +2775,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
|
||||
const message = yield* buildUserMessageEffect(input, {
|
||||
fileSystem,
|
||||
stateDir: serverConfig.stateDir,
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
});
|
||||
|
||||
yield* Queue.offer(context.promptQueue, {
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1336,7 +1336,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
stateDir: serverConfig.stateDir,
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -469,6 +469,89 @@ describe("TerminalManager", () => {
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("strips replay-unsafe terminal query and reply sequences from persisted history", async () => {
|
||||
const { manager, ptyAdapter } = makeManager();
|
||||
await manager.open(openInput());
|
||||
const process = ptyAdapter.processes[0];
|
||||
expect(process).toBeDefined();
|
||||
if (!process) return;
|
||||
|
||||
process.emitData("prompt ");
|
||||
process.emitData("\u001b[32mok\u001b[0m ");
|
||||
process.emitData("\u001b]11;rgb:ffff/ffff/ffff\u0007");
|
||||
process.emitData("\u001b[1;1R");
|
||||
process.emitData("done\n");
|
||||
|
||||
await manager.close({ threadId: "thread-1" });
|
||||
|
||||
const reopened = await manager.open(openInput());
|
||||
expect(reopened.history).toBe("prompt \u001b[32mok\u001b[0m done\n");
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("preserves clear and style control sequences while dropping chunk-split query traffic", async () => {
|
||||
const { manager, ptyAdapter } = makeManager();
|
||||
await manager.open(openInput());
|
||||
const process = ptyAdapter.processes[0];
|
||||
expect(process).toBeDefined();
|
||||
if (!process) return;
|
||||
|
||||
process.emitData("before clear\n");
|
||||
process.emitData("\u001b[H\u001b[2J");
|
||||
process.emitData("prompt ");
|
||||
process.emitData("\u001b]11;");
|
||||
process.emitData("rgb:ffff/ffff/ffff\u0007\u001b[1;1");
|
||||
process.emitData("R\u001b[36mdone\u001b[0m\n");
|
||||
|
||||
await manager.close({ threadId: "thread-1" });
|
||||
|
||||
const reopened = await manager.open(openInput());
|
||||
expect(reopened.history).toBe(
|
||||
"before clear\n\u001b[H\u001b[2Jprompt \u001b[36mdone\u001b[0m\n",
|
||||
);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("does not leak final bytes from ESC sequences with intermediate bytes", async () => {
|
||||
const { manager, ptyAdapter } = makeManager();
|
||||
await manager.open(openInput());
|
||||
const process = ptyAdapter.processes[0];
|
||||
expect(process).toBeDefined();
|
||||
if (!process) return;
|
||||
|
||||
process.emitData("before ");
|
||||
process.emitData("\u001b(B");
|
||||
process.emitData("after\n");
|
||||
|
||||
await manager.close({ threadId: "thread-1" });
|
||||
|
||||
const reopened = await manager.open(openInput());
|
||||
expect(reopened.history).toBe("before \u001b(Bafter\n");
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("preserves chunk-split ESC sequences with intermediate bytes without leaking final bytes", async () => {
|
||||
const { manager, ptyAdapter } = makeManager();
|
||||
await manager.open(openInput());
|
||||
const process = ptyAdapter.processes[0];
|
||||
expect(process).toBeDefined();
|
||||
if (!process) return;
|
||||
|
||||
process.emitData("before ");
|
||||
process.emitData("\u001b(");
|
||||
process.emitData("Bafter\n");
|
||||
|
||||
await manager.close({ threadId: "thread-1" });
|
||||
|
||||
const reopened = await manager.open(openInput());
|
||||
expect(reopened.history).toBe("before \u001b(Bafter\n");
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("deletes history file when close(deleteHistory=true)", async () => {
|
||||
const { manager, ptyAdapter, logsDir } = makeManager();
|
||||
await manager.open(openInput());
|
||||
|
||||
@@ -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";
|
||||
@@ -254,6 +254,180 @@ function capHistory(history: string, maxLines: number): string {
|
||||
return hasTrailingNewline ? `${capped}\n` : capped;
|
||||
}
|
||||
|
||||
function isCsiFinalByte(codePoint: number): boolean {
|
||||
return codePoint >= 0x40 && codePoint <= 0x7e;
|
||||
}
|
||||
|
||||
function shouldStripCsiSequence(body: string, finalByte: string): boolean {
|
||||
if (finalByte === "n") {
|
||||
return true;
|
||||
}
|
||||
if (finalByte === "R" && /^[0-9;?]*$/.test(body)) {
|
||||
return true;
|
||||
}
|
||||
if (finalByte === "c" && /^[>0-9;?]*$/.test(body)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function shouldStripOscSequence(content: string): boolean {
|
||||
return /^(10|11|12);(?:\?|rgb:)/.test(content);
|
||||
}
|
||||
|
||||
function stripStringTerminator(value: string): string {
|
||||
if (value.endsWith("\u001b\\")) {
|
||||
return value.slice(0, -2);
|
||||
}
|
||||
const lastCharacter = value.at(-1);
|
||||
if (lastCharacter === "\u0007" || lastCharacter === "\u009c") {
|
||||
return value.slice(0, -1);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function findStringTerminatorIndex(input: string, start: number): number | null {
|
||||
for (let index = start; index < input.length; index += 1) {
|
||||
const codePoint = input.charCodeAt(index);
|
||||
if (codePoint === 0x07 || codePoint === 0x9c) {
|
||||
return index + 1;
|
||||
}
|
||||
if (codePoint === 0x1b && input.charCodeAt(index + 1) === 0x5c) {
|
||||
return index + 2;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isEscapeIntermediateByte(codePoint: number): boolean {
|
||||
return codePoint >= 0x20 && codePoint <= 0x2f;
|
||||
}
|
||||
|
||||
function isEscapeFinalByte(codePoint: number): boolean {
|
||||
return codePoint >= 0x30 && codePoint <= 0x7e;
|
||||
}
|
||||
|
||||
function findEscapeSequenceEndIndex(input: string, start: number): number | null {
|
||||
let cursor = start;
|
||||
while (cursor < input.length && isEscapeIntermediateByte(input.charCodeAt(cursor))) {
|
||||
cursor += 1;
|
||||
}
|
||||
if (cursor >= input.length) {
|
||||
return null;
|
||||
}
|
||||
return isEscapeFinalByte(input.charCodeAt(cursor)) ? cursor + 1 : start + 1;
|
||||
}
|
||||
|
||||
function sanitizeTerminalHistoryChunk(
|
||||
pendingControlSequence: string,
|
||||
data: string,
|
||||
): { visibleText: string; pendingControlSequence: string } {
|
||||
const input = `${pendingControlSequence}${data}`;
|
||||
let visibleText = "";
|
||||
let index = 0;
|
||||
|
||||
const append = (value: string) => {
|
||||
visibleText += value;
|
||||
};
|
||||
|
||||
while (index < input.length) {
|
||||
const codePoint = input.charCodeAt(index);
|
||||
|
||||
if (codePoint === 0x1b) {
|
||||
const nextCodePoint = input.charCodeAt(index + 1);
|
||||
if (Number.isNaN(nextCodePoint)) {
|
||||
return { visibleText, pendingControlSequence: input.slice(index) };
|
||||
}
|
||||
|
||||
if (nextCodePoint === 0x5b) {
|
||||
let cursor = index + 2;
|
||||
while (cursor < input.length) {
|
||||
if (isCsiFinalByte(input.charCodeAt(cursor))) {
|
||||
const sequence = input.slice(index, cursor + 1);
|
||||
const body = input.slice(index + 2, cursor);
|
||||
if (!shouldStripCsiSequence(body, input[cursor] ?? "")) {
|
||||
append(sequence);
|
||||
}
|
||||
index = cursor + 1;
|
||||
break;
|
||||
}
|
||||
cursor += 1;
|
||||
}
|
||||
if (cursor >= input.length) {
|
||||
return { visibleText, pendingControlSequence: input.slice(index) };
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
nextCodePoint === 0x5d ||
|
||||
nextCodePoint === 0x50 ||
|
||||
nextCodePoint === 0x5e ||
|
||||
nextCodePoint === 0x5f
|
||||
) {
|
||||
const terminatorIndex = findStringTerminatorIndex(input, index + 2);
|
||||
if (terminatorIndex === null) {
|
||||
return { visibleText, pendingControlSequence: input.slice(index) };
|
||||
}
|
||||
const sequence = input.slice(index, terminatorIndex);
|
||||
const content = stripStringTerminator(input.slice(index + 2, terminatorIndex));
|
||||
if (nextCodePoint !== 0x5d || !shouldStripOscSequence(content)) {
|
||||
append(sequence);
|
||||
}
|
||||
index = terminatorIndex;
|
||||
continue;
|
||||
}
|
||||
|
||||
const escapeSequenceEndIndex = findEscapeSequenceEndIndex(input, index + 1);
|
||||
if (escapeSequenceEndIndex === null) {
|
||||
return { visibleText, pendingControlSequence: input.slice(index) };
|
||||
}
|
||||
append(input.slice(index, escapeSequenceEndIndex));
|
||||
index = escapeSequenceEndIndex;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (codePoint === 0x9b) {
|
||||
let cursor = index + 1;
|
||||
while (cursor < input.length) {
|
||||
if (isCsiFinalByte(input.charCodeAt(cursor))) {
|
||||
const sequence = input.slice(index, cursor + 1);
|
||||
const body = input.slice(index + 1, cursor);
|
||||
if (!shouldStripCsiSequence(body, input[cursor] ?? "")) {
|
||||
append(sequence);
|
||||
}
|
||||
index = cursor + 1;
|
||||
break;
|
||||
}
|
||||
cursor += 1;
|
||||
}
|
||||
if (cursor >= input.length) {
|
||||
return { visibleText, pendingControlSequence: input.slice(index) };
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (codePoint === 0x9d || codePoint === 0x90 || codePoint === 0x9e || codePoint === 0x9f) {
|
||||
const terminatorIndex = findStringTerminatorIndex(input, index + 1);
|
||||
if (terminatorIndex === null) {
|
||||
return { visibleText, pendingControlSequence: input.slice(index) };
|
||||
}
|
||||
const sequence = input.slice(index, terminatorIndex);
|
||||
const content = stripStringTerminator(input.slice(index + 1, terminatorIndex));
|
||||
if (codePoint !== 0x9d || !shouldStripOscSequence(content)) {
|
||||
append(sequence);
|
||||
}
|
||||
index = terminatorIndex;
|
||||
continue;
|
||||
}
|
||||
|
||||
append(input[index] ?? "");
|
||||
index += 1;
|
||||
}
|
||||
|
||||
return { visibleText, pendingControlSequence: "" };
|
||||
}
|
||||
|
||||
function legacySafeThreadId(threadId: string): string {
|
||||
return threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
|
||||
}
|
||||
@@ -378,6 +552,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
status: "starting",
|
||||
pid: null,
|
||||
history,
|
||||
pendingHistoryControlSequence: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
@@ -407,10 +582,12 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
existing.cwd = input.cwd;
|
||||
existing.runtimeEnv = nextRuntimeEnv;
|
||||
existing.history = "";
|
||||
existing.pendingHistoryControlSequence = "";
|
||||
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
|
||||
} else if (existing.status === "exited" || existing.status === "error") {
|
||||
existing.runtimeEnv = nextRuntimeEnv;
|
||||
existing.history = "";
|
||||
existing.pendingHistoryControlSequence = "";
|
||||
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
|
||||
} else if (currentRuntimeEnv !== nextRuntimeEnv) {
|
||||
existing.runtimeEnv = nextRuntimeEnv;
|
||||
@@ -469,6 +646,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
await this.runWithThreadLock(input.threadId, async () => {
|
||||
const session = this.requireSession(input.threadId, input.terminalId);
|
||||
session.history = "";
|
||||
session.pendingHistoryControlSequence = "";
|
||||
session.updatedAt = new Date().toISOString();
|
||||
await this.persistHistory(input.threadId, input.terminalId, session.history);
|
||||
this.emitEvent({
|
||||
@@ -497,6 +675,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
status: "starting",
|
||||
pid: null,
|
||||
history: "",
|
||||
pendingHistoryControlSequence: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
@@ -520,6 +699,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
const rows = input.rows ?? session.rows;
|
||||
|
||||
session.history = "";
|
||||
session.pendingHistoryControlSequence = "";
|
||||
await this.persistHistory(input.threadId, input.terminalId, session.history);
|
||||
await this.startSession(session, { ...input, cols, rows }, "restarted");
|
||||
return this.snapshot(session);
|
||||
@@ -694,9 +874,16 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
}
|
||||
|
||||
private onProcessData(session: TerminalSessionState, data: string): void {
|
||||
session.history = capHistory(`${session.history}${data}`, this.historyLineLimit);
|
||||
const sanitized = sanitizeTerminalHistoryChunk(session.pendingHistoryControlSequence, data);
|
||||
session.pendingHistoryControlSequence = sanitized.pendingControlSequence;
|
||||
if (sanitized.visibleText.length > 0) {
|
||||
session.history = capHistory(
|
||||
`${session.history}${sanitized.visibleText}`,
|
||||
this.historyLineLimit,
|
||||
);
|
||||
this.queuePersist(session.threadId, session.terminalId, session.history);
|
||||
}
|
||||
session.updatedAt = new Date().toISOString();
|
||||
this.queuePersist(session.threadId, session.terminalId, session.history);
|
||||
this.emitEvent({
|
||||
type: "output",
|
||||
threadId: session.threadId,
|
||||
@@ -713,6 +900,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
session.pid = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.status = "exited";
|
||||
session.pendingHistoryControlSequence = "";
|
||||
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
|
||||
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
|
||||
session.updatedAt = new Date().toISOString();
|
||||
@@ -736,6 +924,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
session.pid = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.status = "exited";
|
||||
session.pendingHistoryControlSequence = "";
|
||||
session.updatedAt = new Date().toISOString();
|
||||
this.killProcessWithEscalation(process, session.threadId, session.terminalId);
|
||||
this.evictInactiveSessionsIfNeeded();
|
||||
@@ -1172,13 +1361,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;
|
||||
|
||||
@@ -32,6 +32,7 @@ export interface TerminalSessionState {
|
||||
status: TerminalSessionStatus;
|
||||
pid: number | null;
|
||||
history: string;
|
||||
pendingHistoryControlSequence: string;
|
||||
exitCode: number | null;
|
||||
exitSignal: number | null;
|
||||
updatedAt: string;
|
||||
|
||||
@@ -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);
|
||||
@@ -690,13 +703,19 @@ describe("WebSocket Server", () => {
|
||||
id: string;
|
||||
workspaceRoot: string;
|
||||
title: string;
|
||||
defaultModel: string | null;
|
||||
defaultModelSelection: {
|
||||
provider: string;
|
||||
model: string;
|
||||
} | null;
|
||||
}>;
|
||||
threads: Array<{
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
modelSelection: {
|
||||
provider: string;
|
||||
model: string;
|
||||
};
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}>;
|
||||
@@ -712,7 +731,10 @@ describe("WebSocket Server", () => {
|
||||
id: bootstrapProjectId,
|
||||
workspaceRoot: "/test/bootstrap-workspace",
|
||||
title: "bootstrap-workspace",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
}),
|
||||
]),
|
||||
);
|
||||
@@ -722,7 +744,10 @@ describe("WebSocket Server", () => {
|
||||
id: bootstrapThreadId,
|
||||
projectId: bootstrapProjectId,
|
||||
title: "New thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
}),
|
||||
@@ -731,15 +756,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 +788,7 @@ describe("WebSocket Server", () => {
|
||||
|
||||
server = await createTestServer({
|
||||
cwd,
|
||||
stateDir,
|
||||
baseDir,
|
||||
persistenceLayer,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
});
|
||||
@@ -811,11 +837,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 +863,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 +893,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 +925,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 +938,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 +977,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 +1038,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 +1050,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 +1074,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;
|
||||
|
||||
@@ -1172,7 +1204,10 @@ describe("WebSocket Server", () => {
|
||||
projectId: "project-diff",
|
||||
title: "Diff Project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
expect(createProjectResponse.error).toBeUndefined();
|
||||
@@ -1182,7 +1217,10 @@ describe("WebSocket Server", () => {
|
||||
threadId: "thread-diff",
|
||||
projectId: "project-diff",
|
||||
title: "Diff Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
@@ -1250,7 +1288,10 @@ describe("WebSocket Server", () => {
|
||||
projectId: "project-1",
|
||||
title: "WS Project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
expect(createProjectResponse.error).toBeUndefined();
|
||||
@@ -1260,7 +1301,10 @@ describe("WebSocket Server", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
@@ -1791,15 +1835,94 @@ describe("WebSocket Server", () => {
|
||||
connections.push(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.gitRunStackedAction, {
|
||||
actionId: "client-action-1",
|
||||
cwd: "/test",
|
||||
action: "commit_push",
|
||||
});
|
||||
expect(response.result).toBeUndefined();
|
||||
expect(response.error?.message).toContain("detached HEAD");
|
||||
expect(runStackedAction).toHaveBeenCalledWith({
|
||||
expect(runStackedAction).toHaveBeenCalledWith(
|
||||
{
|
||||
actionId: "client-action-1",
|
||||
cwd: "/test",
|
||||
action: "commit_push",
|
||||
},
|
||||
expect.objectContaining({
|
||||
actionId: "client-action-1",
|
||||
progressReporter: expect.any(Object),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("publishes git action progress only to the initiating websocket", async () => {
|
||||
const runStackedAction = vi.fn(
|
||||
(_input, options) =>
|
||||
options?.progressReporter
|
||||
?.publish({
|
||||
actionId: options.actionId ?? "action-1",
|
||||
cwd: "/test",
|
||||
action: "commit",
|
||||
kind: "phase_started",
|
||||
phase: "commit",
|
||||
label: "Committing...",
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap(() =>
|
||||
Effect.succeed({
|
||||
action: "commit" as const,
|
||||
branch: { status: "skipped_not_requested" as const },
|
||||
commit: {
|
||||
status: "created" as const,
|
||||
commitSha: "abc1234",
|
||||
subject: "Test commit",
|
||||
},
|
||||
push: { status: "skipped_not_requested" as const },
|
||||
pr: { status: "skipped_not_requested" as const },
|
||||
}),
|
||||
),
|
||||
) ?? Effect.void,
|
||||
);
|
||||
const gitManager: GitManagerShape = {
|
||||
status: vi.fn(() => Effect.void as any),
|
||||
resolvePullRequest: vi.fn(() => Effect.void as any),
|
||||
preparePullRequestThread: vi.fn(() => Effect.void as any),
|
||||
runStackedAction,
|
||||
};
|
||||
|
||||
server = await createTestServer({ cwd: "/test", gitManager });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const [initiatingWs] = await connectAndAwaitWelcome(port);
|
||||
const [otherWs] = await connectAndAwaitWelcome(port);
|
||||
connections.push(initiatingWs, otherWs);
|
||||
|
||||
const responsePromise = sendRequest(initiatingWs, WS_METHODS.gitRunStackedAction, {
|
||||
actionId: "client-action-2",
|
||||
cwd: "/test",
|
||||
action: "commit_push",
|
||||
action: "commit",
|
||||
});
|
||||
const progressPush = await waitForPush(initiatingWs, WS_CHANNELS.gitActionProgress);
|
||||
|
||||
expect(progressPush.data).toEqual({
|
||||
actionId: "client-action-2",
|
||||
cwd: "/test",
|
||||
action: "commit",
|
||||
kind: "phase_started",
|
||||
phase: "commit",
|
||||
label: "Committing...",
|
||||
});
|
||||
|
||||
await expect(
|
||||
waitForPush(otherWs, WS_CHANNELS.gitActionProgress, undefined, 10, 100),
|
||||
).rejects.toThrow("Timed out waiting for WebSocket message after 100ms");
|
||||
await expect(responsePromise).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
result: expect.objectContaining({
|
||||
action: "commit",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects websocket connections without a valid auth token", async () => {
|
||||
|
||||
+23
-11
@@ -370,7 +370,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 +440,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) {
|
||||
@@ -631,25 +631,31 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
(project) => project.workspaceRoot === cwd && project.deletedAt === null,
|
||||
);
|
||||
let bootstrapProjectId: ProjectId;
|
||||
let bootstrapProjectDefaultModel: string;
|
||||
let bootstrapProjectDefaultModelSelection;
|
||||
|
||||
if (!existingProject) {
|
||||
const createdAt = new Date().toISOString();
|
||||
bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
|
||||
const bootstrapProjectTitle = path.basename(cwd) || "project";
|
||||
bootstrapProjectDefaultModel = "gpt-5-codex";
|
||||
bootstrapProjectDefaultModelSelection = {
|
||||
provider: "codex" as const,
|
||||
model: "gpt-5-codex",
|
||||
};
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
projectId: bootstrapProjectId,
|
||||
title: bootstrapProjectTitle,
|
||||
workspaceRoot: cwd,
|
||||
defaultModel: bootstrapProjectDefaultModel,
|
||||
defaultModelSelection: bootstrapProjectDefaultModelSelection,
|
||||
createdAt,
|
||||
});
|
||||
} else {
|
||||
bootstrapProjectId = existingProject.id;
|
||||
bootstrapProjectDefaultModel = existingProject.defaultModel ?? "gpt-5-codex";
|
||||
bootstrapProjectDefaultModelSelection = existingProject.defaultModelSelection ?? {
|
||||
provider: "codex" as const,
|
||||
model: "gpt-5-codex",
|
||||
};
|
||||
}
|
||||
|
||||
const existingThread = snapshot.threads.find(
|
||||
@@ -664,7 +670,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
threadId,
|
||||
projectId: bootstrapProjectId,
|
||||
title: "New thread",
|
||||
model: bootstrapProjectDefaultModel,
|
||||
modelSelection: bootstrapProjectDefaultModelSelection,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -704,7 +710,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
Effect.all([closeAllClients, closeWebSocketServer.pipe(Effect.ignoreCause({ log: true }))]),
|
||||
);
|
||||
|
||||
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
|
||||
const routeRequest = Effect.fnUntraced(function* (ws: WebSocket, request: WebSocketRequest) {
|
||||
switch (request.body._tag) {
|
||||
case ORCHESTRATION_WS_METHODS.getSnapshot:
|
||||
return yield* projectionReadModelQuery.getSnapshot();
|
||||
@@ -793,7 +799,13 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
|
||||
case WS_METHODS.gitRunStackedAction: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* gitManager.runStackedAction(body);
|
||||
return yield* gitManager.runStackedAction(body, {
|
||||
actionId: body.actionId,
|
||||
progressReporter: {
|
||||
publish: (event) =>
|
||||
pushBus.publishClient(ws, WS_CHANNELS.gitActionProgress, event).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
case WS_METHODS.gitResolvePullRequest: {
|
||||
@@ -915,7 +927,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
});
|
||||
}
|
||||
|
||||
const result = yield* Effect.exit(routeRequest(request.success));
|
||||
const result = yield* Effect.exit(routeRequest(ws, request.success));
|
||||
if (Exit.isFailure(result)) {
|
||||
return yield* sendWsResponse({
|
||||
id: request.success.id,
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -5,7 +5,14 @@ import {
|
||||
AppSettingsSchema,
|
||||
DEFAULT_TIMESTAMP_FORMAT,
|
||||
getAppModelOptions,
|
||||
getCustomModelOptionsByProvider,
|
||||
getCustomModelsByProvider,
|
||||
getCustomModelsForProvider,
|
||||
getDefaultCustomModelsForProvider,
|
||||
getProviderStartOptions,
|
||||
MODEL_PROVIDER_SETTINGS,
|
||||
normalizeCustomModelSlugs,
|
||||
patchCustomModels,
|
||||
resolveAppModelSelection,
|
||||
} from "./appSettings";
|
||||
|
||||
@@ -66,13 +73,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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -90,6 +119,114 @@ describe("provider-specific custom models", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getProviderStartOptions", () => {
|
||||
it("returns only populated provider overrides", () => {
|
||||
expect(
|
||||
getProviderStartOptions({
|
||||
claudeBinaryPath: "/usr/local/bin/claude",
|
||||
codexBinaryPath: "",
|
||||
codexHomePath: "/Users/you/.codex",
|
||||
}),
|
||||
).toEqual({
|
||||
claudeAgent: {
|
||||
binaryPath: "/usr/local/bin/claude",
|
||||
},
|
||||
codex: {
|
||||
homePath: "/Users/you/.codex",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("returns undefined when no provider overrides are configured", () => {
|
||||
expect(
|
||||
getProviderStartOptions({
|
||||
claudeBinaryPath: "",
|
||||
codexBinaryPath: "",
|
||||
codexHomePath: "",
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
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));
|
||||
@@ -102,6 +239,7 @@ describe("AppSettingsSchema", () => {
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
claudeBinaryPath: "",
|
||||
codexBinaryPath: "/usr/local/bin/codex",
|
||||
codexHomePath: "",
|
||||
defaultThreadEnvMode: "local",
|
||||
|
||||
+121
-26
@@ -1,7 +1,16 @@
|
||||
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 {
|
||||
TrimmedNonEmptyString,
|
||||
type ProviderKind,
|
||||
type ProviderStartOptions,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getDefaultModel,
|
||||
getModelOptions,
|
||||
normalizeModelSlug,
|
||||
resolveSelectableModel,
|
||||
} from "@t3tools/shared/model";
|
||||
import { useLocalStorage } from "./hooks/useLocalStorage";
|
||||
import { EnvMode } from "./components/BranchToolbar.logic";
|
||||
|
||||
@@ -12,6 +21,16 @@ export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
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)),
|
||||
@@ -32,10 +51,12 @@ const withDefaults =
|
||||
);
|
||||
|
||||
export const AppSettingsSchema = Schema.Struct({
|
||||
claudeBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
|
||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
|
||||
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
|
||||
defaultThreadEnvMode: EnvMode.pipe(withDefaults(() => "local" as const satisfies EnvMode)),
|
||||
confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),
|
||||
diffWordWrap: Schema.Boolean.pipe(withDefaults(() => false)),
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(withDefaults(() => false)),
|
||||
timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
|
||||
@@ -50,6 +71,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>,
|
||||
@@ -87,6 +129,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[],
|
||||
@@ -98,6 +173,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)) {
|
||||
@@ -113,7 +189,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,
|
||||
@@ -126,34 +209,46 @@ 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;
|
||||
}
|
||||
}
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
|
||||
if (!normalizedSelectedModel) {
|
||||
return getDefaultModel(provider);
|
||||
}
|
||||
export function getProviderStartOptions(
|
||||
settings: Pick<AppSettings, "claudeBinaryPath" | "codexBinaryPath" | "codexHomePath">,
|
||||
): ProviderStartOptions | undefined {
|
||||
const providerOptions: ProviderStartOptions = {
|
||||
...(settings.codexBinaryPath || settings.codexHomePath
|
||||
? {
|
||||
codex: {
|
||||
...(settings.codexBinaryPath ? { binaryPath: settings.codexBinaryPath } : {}),
|
||||
...(settings.codexHomePath ? { homePath: settings.codexHomePath } : {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
...(settings.claudeBinaryPath
|
||||
? {
|
||||
claudeAgent: {
|
||||
binaryPath: settings.claudeBinaryPath,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
return (
|
||||
options.find((option) => option.slug === normalizedSelectedModel)?.slug ??
|
||||
getDefaultModel(provider)
|
||||
);
|
||||
return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
|
||||
}
|
||||
|
||||
export function useAppSettings() {
|
||||
|
||||
@@ -24,6 +24,7 @@ import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
type TerminalContextDraft,
|
||||
removeInlineTerminalContextPlaceholder,
|
||||
} from "../lib/terminalContext";
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
import { getRouter } from "../router";
|
||||
@@ -220,7 +221,10 @@ function createSnapshotForTargetUser(options: {
|
||||
id: PROJECT_ID,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModel: "gpt-5",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
@@ -232,7 +236,10 @@ function createSnapshotForTargetUser(options: {
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Browser test thread",
|
||||
model: "gpt-5",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: "main",
|
||||
@@ -286,7 +293,10 @@ function addThreadToSnapshot(
|
||||
id: threadId,
|
||||
projectId: PROJECT_ID,
|
||||
title: "New thread",
|
||||
model: "gpt-5",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: "main",
|
||||
@@ -324,6 +334,18 @@ function createDraftOnlySnapshot(): OrchestrationReadModel {
|
||||
};
|
||||
}
|
||||
|
||||
function withProjectScripts(
|
||||
snapshot: OrchestrationReadModel,
|
||||
scripts: OrchestrationReadModel["projects"][number]["scripts"],
|
||||
): OrchestrationReadModel {
|
||||
return {
|
||||
...snapshot,
|
||||
projects: snapshot.projects.map((project) =>
|
||||
project.id === PROJECT_ID ? { ...project, scripts: Array.from(scripts) } : project,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
|
||||
const snapshot = createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-plan-target" as MessageId,
|
||||
@@ -575,6 +597,58 @@ async function waitForInteractionModeButton(
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForServerConfigToApply(): Promise<void> {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(wsRequests.some((request) => request._tag === WS_METHODS.serverGetConfig)).toBe(true);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
await waitForLayout();
|
||||
}
|
||||
|
||||
function dispatchChatNewShortcut(): void {
|
||||
const useMetaForMod = isMacPlatform(navigator.platform);
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "o",
|
||||
shiftKey: true,
|
||||
metaKey: useMetaForMod,
|
||||
ctrlKey: !useMetaForMod,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function triggerChatNewShortcutUntilPath(
|
||||
router: ReturnType<typeof getRouter>,
|
||||
predicate: (pathname: string) => boolean,
|
||||
errorMessage: string,
|
||||
): Promise<string> {
|
||||
let pathname = router.state.location.pathname;
|
||||
const deadline = Date.now() + 8_000;
|
||||
while (Date.now() < deadline) {
|
||||
dispatchChatNewShortcut();
|
||||
await waitForLayout();
|
||||
pathname = router.state.location.pathname;
|
||||
if (predicate(pathname)) {
|
||||
return pathname;
|
||||
}
|
||||
}
|
||||
throw new Error(`${errorMessage} Last path: ${pathname}`);
|
||||
}
|
||||
|
||||
async function waitForNewThreadShortcutLabel(): Promise<void> {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
await newThreadButton.hover();
|
||||
const shortcutLabel = isMacPlatform(navigator.platform)
|
||||
? "New thread (⇧⌘O)"
|
||||
: "New thread (Ctrl+Shift+O)";
|
||||
await expect.element(page.getByText(shortcutLabel)).toBeInTheDocument();
|
||||
}
|
||||
|
||||
async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
|
||||
const images = Array.from(scope.querySelectorAll("img"));
|
||||
if (images.length === 0) {
|
||||
@@ -752,6 +826,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelection: null,
|
||||
});
|
||||
useStore.setState({
|
||||
projects: [],
|
||||
@@ -978,6 +1053,145 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("runs project scripts from local draft threads at the project cwd", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadId: {
|
||||
[THREAD_ID]: {
|
||||
projectId: PROJECT_ID,
|
||||
createdAt: NOW_ISO,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
envMode: "local",
|
||||
},
|
||||
},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[PROJECT_ID]: THREAD_ID,
|
||||
},
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
|
||||
{
|
||||
id: "lint",
|
||||
name: "Lint",
|
||||
command: "bun run lint",
|
||||
icon: "lint",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
]),
|
||||
});
|
||||
|
||||
try {
|
||||
const runButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.title === "Run Lint",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Run Lint button.",
|
||||
);
|
||||
runButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.terminalOpen,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.terminalOpen,
|
||||
threadId: THREAD_ID,
|
||||
cwd: "/repo/project",
|
||||
env: {
|
||||
T3CODE_PROJECT_ROOT: "/repo/project",
|
||||
},
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const writeRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.terminalWrite,
|
||||
);
|
||||
expect(writeRequest).toMatchObject({
|
||||
_tag: WS_METHODS.terminalWrite,
|
||||
threadId: THREAD_ID,
|
||||
data: "bun run lint\r",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("runs project scripts from worktree draft threads at the worktree cwd", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadId: {
|
||||
[THREAD_ID]: {
|
||||
projectId: PROJECT_ID,
|
||||
createdAt: NOW_ISO,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "feature/draft",
|
||||
worktreePath: "/repo/worktrees/feature-draft",
|
||||
envMode: "worktree",
|
||||
},
|
||||
},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[PROJECT_ID]: THREAD_ID,
|
||||
},
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
|
||||
{
|
||||
id: "test",
|
||||
name: "Test",
|
||||
command: "bun run test",
|
||||
icon: "test",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
]),
|
||||
});
|
||||
|
||||
try {
|
||||
const runButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.title === "Run Test",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Run Test button.",
|
||||
);
|
||||
runButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.terminalOpen,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.terminalOpen,
|
||||
threadId: THREAD_ID,
|
||||
cwd: "/repo/worktrees/feature-draft",
|
||||
env: {
|
||||
T3CODE_PROJECT_ROOT: "/repo/project",
|
||||
T3CODE_WORKTREE_PATH: "/repo/worktrees/feature-draft",
|
||||
},
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("toggles plan mode with Shift+Tab only while the composer is focused", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
@@ -1043,7 +1257,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps backspaced terminal context pills removed when a new one is added", async () => {
|
||||
it("keeps removed terminal context pills removed when a new one is added", async () => {
|
||||
const removedLabel = "Terminal 1 lines 1-2";
|
||||
const addedLabel = "Terminal 2 lines 9-10";
|
||||
useComposerDraftStore.getState().addTerminalContext(
|
||||
@@ -1073,15 +1287,11 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
const composerEditor = await waitForComposerEditor();
|
||||
composerEditor.focus();
|
||||
composerEditor.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Backspace",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
const store = useComposerDraftStore.getState();
|
||||
const currentPrompt = store.draftsByThreadId[THREAD_ID]?.prompt ?? "";
|
||||
const nextPrompt = removeInlineTerminalContextPlaceholder(currentPrompt, 0);
|
||||
store.setPrompt(THREAD_ID, nextPrompt.prompt);
|
||||
store.removeTerminalContext(THREAD_ID, "ctx-removed");
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
@@ -1279,6 +1489,204 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("snapshots sticky codex settings into a new draft thread", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
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({
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("hydrates the provider alongside a sticky claude model", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
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({
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
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({
|
||||
stickyModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
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({
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
useComposerDraftStore.getState().setModelSelection(threadId, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
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({
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
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,
|
||||
@@ -1311,19 +1719,12 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
const useMetaForMod = isMacPlatform(navigator.platform);
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "o",
|
||||
shiftKey: true,
|
||||
metaKey: useMetaForMod,
|
||||
ctrlKey: !useMetaForMod,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitForURL(
|
||||
await waitForNewThreadShortcutLabel();
|
||||
await waitForServerConfigToApply();
|
||||
const composerEditor = await waitForComposerEditor();
|
||||
composerEditor.focus();
|
||||
await waitForLayout();
|
||||
await triggerChatNewShortcutUntilPath(
|
||||
mounted.router,
|
||||
(path) => UUID_ROUTE_RE.test(path),
|
||||
"Route should have changed to a new draft thread UUID from the shortcut.",
|
||||
@@ -1332,7 +1733,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("creates a fresh draft after the previous draft thread is promoted", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
@@ -1367,6 +1767,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
try {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
await waitForNewThreadShortcutLabel();
|
||||
await waitForServerConfigToApply();
|
||||
await newThreadButton.click();
|
||||
|
||||
const promotedThreadPath = await waitForURL(
|
||||
@@ -1380,19 +1782,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId));
|
||||
useComposerDraftStore.getState().clearDraftThread(promotedThreadId);
|
||||
|
||||
const useMetaForMod = isMacPlatform(navigator.platform);
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "o",
|
||||
shiftKey: true,
|
||||
metaKey: useMetaForMod,
|
||||
ctrlKey: !useMetaForMod,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
|
||||
const freshThreadPath = await waitForURL(
|
||||
const freshThreadPath = await triggerChatNewShortcutUntilPath(
|
||||
mounted.router,
|
||||
(path) => UUID_ROUTE_RE.test(path) && path !== promotedThreadPath,
|
||||
"Shortcut should create a fresh draft instead of reusing the promoted thread.",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { ProjectId, type ProviderKind, type ThreadId } from "@t3tools/contracts";
|
||||
import { ProjectId, type ModelSelection, 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 {
|
||||
@@ -18,7 +17,7 @@ export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.
|
||||
export function buildLocalDraftThread(
|
||||
threadId: ThreadId,
|
||||
draftThread: DraftThreadState,
|
||||
fallbackModel: string,
|
||||
fallbackModelSelection: ModelSelection,
|
||||
error: string | null,
|
||||
): Thread {
|
||||
return {
|
||||
@@ -26,7 +25,7 @@ export function buildLocalDraftThread(
|
||||
codexThreadId: null,
|
||||
projectId: draftThread.projectId,
|
||||
title: "New thread",
|
||||
model: fallbackModel,
|
||||
modelSelection: fallbackModelSelection,
|
||||
runtimeMode: draftThread.runtimeMode,
|
||||
interactionMode: draftThread.interactionMode,
|
||||
session: null,
|
||||
@@ -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;
|
||||
|
||||
@@ -3,9 +3,11 @@ import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ClaudeCodeEffort,
|
||||
type MessageId,
|
||||
type ModelSelection,
|
||||
type ProjectScript,
|
||||
type ModelSlug,
|
||||
type ProviderKind,
|
||||
type ProviderModelOptions,
|
||||
type ProjectEntry,
|
||||
type ProjectId,
|
||||
type ProviderApprovalDecision,
|
||||
@@ -24,15 +26,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";
|
||||
@@ -119,6 +114,7 @@ import { type NewProjectScriptInput } from "./ProjectScriptsControl";
|
||||
import {
|
||||
commandForProjectScript,
|
||||
nextProjectScriptId,
|
||||
projectScriptCwd,
|
||||
projectScriptRuntimeEnv,
|
||||
projectScriptIdFromCommand,
|
||||
setupProjectScript,
|
||||
@@ -126,7 +122,13 @@ 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,
|
||||
getProviderStartOptions,
|
||||
resolveAppModelSelection,
|
||||
useAppSettings,
|
||||
} from "../appSettings";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import {
|
||||
type ComposerImageAttachment,
|
||||
@@ -153,12 +155,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 +173,6 @@ import {
|
||||
cloneComposerImageForRetry,
|
||||
collectUserMessageBlobPreviewUrls,
|
||||
deriveComposerSendState,
|
||||
getCustomModelOptionsByProvider,
|
||||
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
|
||||
LastInvokedScriptByProjectSchema,
|
||||
PullRequestDialogState,
|
||||
@@ -200,6 +204,23 @@ function formatOutgoingPrompt(params: {
|
||||
}
|
||||
return params.text;
|
||||
}
|
||||
function extractModelSelectionOptions(
|
||||
provider: ProviderKind,
|
||||
modelOptions: ProviderModelOptions | undefined,
|
||||
): ModelSelection["options"] | undefined {
|
||||
return provider === "codex" ? modelOptions?.codex : modelOptions?.claudeAgent;
|
||||
}
|
||||
|
||||
function toProviderModelOptions(
|
||||
modelSelection: ModelSelection | null | undefined,
|
||||
): ProviderModelOptions | undefined {
|
||||
if (!modelSelection?.options) {
|
||||
return undefined;
|
||||
}
|
||||
return modelSelection.provider === "codex"
|
||||
? { codex: modelSelection.options }
|
||||
: { claudeAgent: modelSelection.options };
|
||||
}
|
||||
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
|
||||
const SCRIPT_TERMINAL_COLS = 120;
|
||||
const SCRIPT_TERMINAL_ROWS = 30;
|
||||
@@ -244,6 +265,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const setStoreThreadError = useStore((store) => store.setError);
|
||||
const setStoreThreadBranch = useStore((store) => store.setThreadBranch);
|
||||
const { settings } = useAppSettings();
|
||||
const setStickyComposerModelSelection = useComposerDraftStore(
|
||||
(store) => store.setStickyModelSelection,
|
||||
);
|
||||
const timestampFormat = settings.timestampFormat;
|
||||
const navigate = useNavigate();
|
||||
const rawSearch = useSearch({
|
||||
@@ -268,8 +292,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
|
||||
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
|
||||
const setComposerDraftProvider = useComposerDraftStore((store) => store.setProvider);
|
||||
const setComposerDraftModel = useComposerDraftStore((store) => store.setModel);
|
||||
const setComposerDraftModelSelection = useComposerDraftStore((store) => store.setModelSelection);
|
||||
const setComposerDraftRuntimeMode = useComposerDraftStore((store) => store.setRuntimeMode);
|
||||
const setComposerDraftInteractionMode = useComposerDraftStore(
|
||||
(store) => store.setInteractionMode,
|
||||
@@ -462,11 +485,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
? buildLocalDraftThread(
|
||||
threadId,
|
||||
draftThread,
|
||||
fallbackDraftProject?.model ?? DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
fallbackDraftProject?.defaultModelSelection ?? {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
localDraftError,
|
||||
)
|
||||
: undefined,
|
||||
[draftThread, fallbackDraftProject?.model, localDraftError, threadId],
|
||||
[draftThread, fallbackDraftProject?.defaultModelSelection, localDraftError, threadId],
|
||||
);
|
||||
const activeThread = serverThread ?? localDraftThread;
|
||||
const runtimeMode =
|
||||
@@ -581,7 +607,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
]);
|
||||
|
||||
const sessionProvider = activeThread?.session?.provider ?? null;
|
||||
const selectedProviderByThreadId = composerDraft.provider;
|
||||
const selectedProviderByThreadId = composerDraft.modelSelection?.provider ?? null;
|
||||
const threadProvider =
|
||||
activeThread?.modelSelection.provider ?? activeProject?.defaultModelSelection?.provider ?? null;
|
||||
const hasThreadStarted = Boolean(
|
||||
activeThread &&
|
||||
(activeThread.latestTurn !== null ||
|
||||
@@ -589,90 +617,58 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeThread.session !== null),
|
||||
);
|
||||
const lockedProvider: ProviderKind | null = hasThreadStarted
|
||||
? (sessionProvider ?? selectedProviderByThreadId ?? null)
|
||||
? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)
|
||||
: null;
|
||||
const selectedProvider: ProviderKind = lockedProvider ?? selectedProviderByThreadId ?? "codex";
|
||||
const selectedProvider: ProviderKind =
|
||||
lockedProvider ?? selectedProviderByThreadId ?? threadProvider ?? "codex";
|
||||
const baseThreadModel = resolveModelSlugForProvider(
|
||||
selectedProvider,
|
||||
activeThread?.model ?? activeProject?.model ?? getDefaultModel(selectedProvider),
|
||||
activeThread?.modelSelection.model ??
|
||||
activeProject?.defaultModelSelection?.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;
|
||||
const draftModel = composerDraft.modelSelection?.model;
|
||||
if (!draftModel) {
|
||||
return baseThreadModel;
|
||||
}
|
||||
return resolveAppModelSelection(
|
||||
selectedProvider,
|
||||
customModelsForSelectedProvider,
|
||||
draftModel,
|
||||
) as ModelSlug;
|
||||
}, [baseThreadModel, composerDraft.model, customModelsForSelectedProvider, 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;
|
||||
return resolveAppModelSelection(selectedProvider, customModelsByProvider, draftModel);
|
||||
}, [
|
||||
baseThreadModel,
|
||||
composerDraft.modelSelection?.model,
|
||||
customModelsByProvider,
|
||||
selectedProvider,
|
||||
]);
|
||||
const draftModelOptions = toProviderModelOptions(composerDraft.modelSelection);
|
||||
const composerProviderState = useMemo(
|
||||
() =>
|
||||
getComposerProviderState({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
prompt,
|
||||
modelOptions: draftModelOptions,
|
||||
}),
|
||||
[draftModelOptions, prompt, selectedModel, selectedProvider],
|
||||
);
|
||||
const selectedPromptEffort = composerProviderState.promptEffort;
|
||||
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
|
||||
const selectedModelSelection = useMemo<ModelSelection>(
|
||||
() => ({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
...(extractModelSelectionOptions(selectedProvider, selectedModelOptionsForDispatch)
|
||||
? {
|
||||
options: extractModelSelectionOptions(
|
||||
selectedProvider,
|
||||
selectedModelOptionsForDispatch,
|
||||
),
|
||||
}
|
||||
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 providerOptionsForDispatch = useMemo(() => {
|
||||
if (!settings.codexBinaryPath && !settings.codexHomePath) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
codex: {
|
||||
...(settings.codexBinaryPath ? { binaryPath: settings.codexBinaryPath } : {}),
|
||||
...(settings.codexHomePath ? { homePath: settings.codexHomePath } : {}),
|
||||
},
|
||||
};
|
||||
}, [settings.codexBinaryPath, settings.codexHomePath]);
|
||||
: {}),
|
||||
}),
|
||||
[selectedModel, selectedModelOptionsForDispatch, selectedProvider],
|
||||
);
|
||||
const providerOptionsForDispatch = useMemo(() => getProviderStartOptions(settings), [settings]);
|
||||
const selectedModelForPicker = selectedModel;
|
||||
const modelOptionsByProvider = useMemo(
|
||||
() => getCustomModelOptionsByProvider(settings),
|
||||
@@ -1047,7 +1043,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
latestTurnSettled,
|
||||
timelineEntries,
|
||||
]);
|
||||
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
|
||||
const gitCwd = activeProject
|
||||
? projectScriptCwd({
|
||||
project: { cwd: activeProject.cwd },
|
||||
worktreePath: activeThread?.worktreePath ?? null,
|
||||
})
|
||||
: null;
|
||||
const composerTriggerKind = composerTrigger?.kind ?? null;
|
||||
const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : "";
|
||||
const isPathTrigger = composerTriggerKind === "path";
|
||||
@@ -1149,10 +1150,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;
|
||||
@@ -1167,6 +1167,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}, [activeProjectCwd, activeThreadWorktreePath]);
|
||||
// Default true while loading to avoid toolbar flicker.
|
||||
const isGitRepo = branchesQuery.data?.isRepo ?? true;
|
||||
const terminalToggleShortcutLabel = useMemo(
|
||||
() => shortcutLabelForCommand(keybindings, "terminal.toggle"),
|
||||
[keybindings],
|
||||
);
|
||||
const splitTerminalShortcutLabel = useMemo(
|
||||
() => shortcutLabelForCommand(keybindings, "terminal.split"),
|
||||
[keybindings],
|
||||
@@ -1357,12 +1361,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
worktreePath?: string | null;
|
||||
preferNewTerminal?: boolean;
|
||||
rememberAsLastInvoked?: boolean;
|
||||
allowLocalDraftThread?: boolean;
|
||||
},
|
||||
) => {
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThreadId || !activeProject || !activeThread) return;
|
||||
if (!isServerThread && !options?.allowLocalDraftThread) return;
|
||||
if (options?.rememberAsLastInvoked !== false) {
|
||||
setLastInvokedScriptByProjectId((current) => {
|
||||
if (current[activeProject.id] === script.id) return current;
|
||||
@@ -1431,7 +1433,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeThread,
|
||||
activeThreadId,
|
||||
gitCwd,
|
||||
isServerThread,
|
||||
setTerminalOpen,
|
||||
setThreadError,
|
||||
storeNewTerminal,
|
||||
@@ -1635,7 +1636,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
async (input: {
|
||||
threadId: ThreadId;
|
||||
createdAt: string;
|
||||
model?: string;
|
||||
modelSelection?: ModelSelection;
|
||||
runtimeMode: RuntimeMode;
|
||||
interactionMode: ProviderInteractionMode;
|
||||
}) => {
|
||||
@@ -1647,12 +1648,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (input.model !== undefined && input.model !== serverThread.model) {
|
||||
if (
|
||||
input.modelSelection !== undefined &&
|
||||
(input.modelSelection.model !== serverThread.modelSelection.model ||
|
||||
input.modelSelection.provider !== serverThread.modelSelection.provider ||
|
||||
JSON.stringify(input.modelSelection.options ?? null) !==
|
||||
JSON.stringify(serverThread.modelSelection.options ?? null))
|
||||
) {
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId: input.threadId,
|
||||
model: input.model,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2583,8 +2590,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
}
|
||||
const title = truncateTitle(titleSeed);
|
||||
let threadCreateModel: ModelSlug =
|
||||
selectedModel || (activeProject.model as ModelSlug) || DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
const threadCreateModelSelection: ModelSelection = {
|
||||
provider: selectedProvider,
|
||||
model:
|
||||
selectedModel ||
|
||||
activeProject.defaultModelSelection?.model ||
|
||||
DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
...(selectedModelSelection.options ? { options: selectedModelSelection.options } : {}),
|
||||
};
|
||||
|
||||
if (isLocalDraftThread) {
|
||||
await api.orchestration.dispatchCommand({
|
||||
@@ -2593,7 +2606,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
threadId: threadIdForSend,
|
||||
projectId: activeProject.id,
|
||||
title,
|
||||
model: threadCreateModel,
|
||||
modelSelection: threadCreateModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
branch: nextThreadBranch,
|
||||
@@ -2620,7 +2633,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const setupScriptOptions: Parameters<typeof runProjectScript>[1] = {
|
||||
worktreePath: nextThreadWorktreePath,
|
||||
rememberAsLastInvoked: false,
|
||||
allowLocalDraftThread: createdServerThreadForLocalDraft,
|
||||
};
|
||||
if (nextThreadWorktreePath) {
|
||||
setupScriptOptions.cwd = nextThreadWorktreePath;
|
||||
@@ -2643,7 +2655,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
await persistThreadSettingsForNextTurn({
|
||||
threadId: threadIdForSend,
|
||||
createdAt: messageCreatedAt,
|
||||
...(selectedModel ? { model: selectedModel } : {}),
|
||||
...(selectedModel ? { modelSelection: selectedModelSelection } : {}),
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
});
|
||||
@@ -2661,12 +2673,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
text: outgoingMessageText,
|
||||
attachments: turnAttachments,
|
||||
},
|
||||
model: selectedModel || undefined,
|
||||
...(selectedModelOptionsForDispatch
|
||||
? { modelOptions: selectedModelOptionsForDispatch }
|
||||
: {}),
|
||||
modelSelection: selectedModelSelection,
|
||||
...(providerOptionsForDispatch ? { providerOptions: providerOptionsForDispatch } : {}),
|
||||
provider: selectedProvider,
|
||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
@@ -2927,7 +2935,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
await persistThreadSettingsForNextTurn({
|
||||
threadId: threadIdForSend,
|
||||
createdAt: messageCreatedAt,
|
||||
...(selectedModel ? { model: selectedModel } : {}),
|
||||
modelSelection: selectedModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode: nextInteractionMode,
|
||||
});
|
||||
@@ -2946,11 +2954,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
text: outgoingMessageText,
|
||||
attachments: [],
|
||||
},
|
||||
provider: selectedProvider,
|
||||
model: selectedModel || undefined,
|
||||
...(selectedModelOptionsForDispatch
|
||||
? { modelOptions: selectedModelOptionsForDispatch }
|
||||
: {}),
|
||||
modelSelection: selectedModelSelection,
|
||||
...(providerOptionsForDispatch ? { providerOptions: providerOptionsForDispatch } : {}),
|
||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
||||
runtimeMode,
|
||||
@@ -2997,8 +3001,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedPromptEffort,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
selectedModelSelection,
|
||||
providerOptionsForDispatch,
|
||||
selectedProvider,
|
||||
setComposerDraftInteractionMode,
|
||||
@@ -3032,11 +3035,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
text: implementationPrompt,
|
||||
});
|
||||
const nextThreadTitle = truncateTitle(buildPlanImplementationThreadTitle(planMarkdown));
|
||||
const nextThreadModel: ModelSlug =
|
||||
selectedModel ||
|
||||
(activeThread.model as ModelSlug) ||
|
||||
(activeProject.model as ModelSlug) ||
|
||||
DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
const nextThreadModelSelection: ModelSelection = selectedModelSelection;
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
beginSendPhase("sending-turn");
|
||||
@@ -3052,7 +3051,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
threadId: nextThreadId,
|
||||
projectId: activeProject.id,
|
||||
title: nextThreadTitle,
|
||||
model: nextThreadModel,
|
||||
modelSelection: nextThreadModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode: "default",
|
||||
branch: activeThread.branch,
|
||||
@@ -3070,11 +3069,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
text: outgoingImplementationPrompt,
|
||||
attachments: [],
|
||||
},
|
||||
provider: selectedProvider,
|
||||
model: selectedModel || undefined,
|
||||
...(selectedModelOptionsForDispatch
|
||||
? { modelOptions: selectedModelOptionsForDispatch }
|
||||
: {}),
|
||||
modelSelection: selectedModelSelection,
|
||||
...(providerOptionsForDispatch ? { providerOptions: providerOptionsForDispatch } : {}),
|
||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
||||
runtimeMode,
|
||||
@@ -3126,8 +3121,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedPromptEffort,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
selectedModelSelection,
|
||||
providerOptionsForDispatch,
|
||||
selectedProvider,
|
||||
settings.enableAssistantStreaming,
|
||||
@@ -3141,20 +3135,28 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
setComposerDraftProvider(activeThread.id, provider);
|
||||
setComposerDraftModel(
|
||||
activeThread.id,
|
||||
resolveAppModelSelection(provider, customModelsByProvider[provider], model),
|
||||
);
|
||||
const resolvedModel = resolveAppModelSelection(provider, customModelsByProvider, model);
|
||||
const existingModelSelection = composerDraft.modelSelection;
|
||||
const preserveOptions =
|
||||
existingModelSelection?.provider === provider &&
|
||||
existingModelSelection.options !== undefined;
|
||||
const nextModelSelection: ModelSelection = {
|
||||
provider,
|
||||
model: resolvedModel,
|
||||
...(preserveOptions ? { options: existingModelSelection.options } : {}),
|
||||
};
|
||||
setComposerDraftModelSelection(activeThread.id, nextModelSelection);
|
||||
setStickyComposerModelSelection(nextModelSelection);
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
customModelsByProvider,
|
||||
composerDraft.modelSelection,
|
||||
lockedProvider,
|
||||
scheduleComposerFocus,
|
||||
setComposerDraftModel,
|
||||
setComposerDraftProvider,
|
||||
setComposerDraftModelSelection,
|
||||
setStickyComposerModelSelection,
|
||||
customModelsByProvider,
|
||||
],
|
||||
);
|
||||
const setPromptFromTraits = useCallback(
|
||||
@@ -3173,6 +3175,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) {
|
||||
@@ -3507,13 +3521,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeThreadTitle={activeThread.title}
|
||||
activeProjectName={activeProject?.name}
|
||||
isGitRepo={isGitRepo}
|
||||
openInCwd={activeThread.worktreePath ?? activeProject?.cwd ?? null}
|
||||
openInCwd={gitCwd}
|
||||
activeProjectScripts={activeProject?.scripts}
|
||||
preferredScriptId={
|
||||
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
|
||||
}
|
||||
keybindings={keybindings}
|
||||
availableEditors={availableEditors}
|
||||
terminalAvailable={activeProject !== undefined}
|
||||
terminalOpen={terminalState.terminalOpen}
|
||||
terminalToggleShortcutLabel={terminalToggleShortcutLabel}
|
||||
diffToggleShortcutLabel={diffPanelShortcutLabel}
|
||||
gitCwd={gitCwd}
|
||||
diffOpen={diffOpen}
|
||||
@@ -3523,6 +3540,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
onAddProjectScript={saveProjectScript}
|
||||
onUpdateProjectScript={updateProjectScript}
|
||||
onDeleteProjectScript={deleteProjectScript}
|
||||
onToggleTerminal={toggleTerminalVisibility}
|
||||
onToggleDiff={onToggleDiff}
|
||||
/>
|
||||
</header>
|
||||
@@ -3586,7 +3604,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 +3624,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 +3635,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 +3824,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
model={selectedModelForPickerWithCustomFallback}
|
||||
lockedProvider={lockedProvider}
|
||||
modelOptionsByProvider={modelOptionsByProvider}
|
||||
ultrathinkActive={isClaudeUltrathink}
|
||||
{...(composerProviderState.modelPickerIconClassName
|
||||
? {
|
||||
activeProviderIconClassName:
|
||||
composerProviderState.modelPickerIconClassName,
|
||||
}
|
||||
: {})}
|
||||
onProviderModelChange={onProviderModelSelect}
|
||||
/>
|
||||
|
||||
@@ -3818,42 +3841,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}
|
||||
|
||||
|
||||
@@ -3,7 +3,13 @@ import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/reac
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||
import { ThreadId, type TurnId } from "@t3tools/contracts";
|
||||
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
|
||||
import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
Columns2Icon,
|
||||
Rows3Icon,
|
||||
TextWrapIcon,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
type WheelEvent as ReactWheelEvent,
|
||||
useCallback,
|
||||
@@ -162,8 +168,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const { settings } = useAppSettings();
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
|
||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
||||
const turnStripRef = useRef<HTMLDivElement>(null);
|
||||
const previousDiffOpenRef = useRef(false);
|
||||
const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
|
||||
const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
|
||||
const routeThreadId = useParams({
|
||||
@@ -171,6 +179,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
|
||||
});
|
||||
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
|
||||
const diffOpen = diffSearch.diff === "1";
|
||||
const activeThreadId = routeThreadId;
|
||||
const activeThread = useStore((store) =>
|
||||
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
|
||||
@@ -293,6 +302,13 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
);
|
||||
}, [renderablePatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (diffOpen && !previousDiffOpenRef.current) {
|
||||
setDiffWordWrap(settings.diffWordWrap);
|
||||
}
|
||||
previousDiffOpenRef.current = diffOpen;
|
||||
}, [diffOpen, settings.diffWordWrap]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedFilePath || !patchViewportRef.current) {
|
||||
return;
|
||||
@@ -490,25 +506,39 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<ToggleGroup
|
||||
className="shrink-0 [-webkit-app-region:no-drag]"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
value={[diffRenderMode]}
|
||||
onValueChange={(value) => {
|
||||
const next = value[0];
|
||||
if (next === "stacked" || next === "split") {
|
||||
setDiffRenderMode(next);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Toggle aria-label="Stacked diff view" value="stacked">
|
||||
<Rows3Icon className="size-3" />
|
||||
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
|
||||
<ToggleGroup
|
||||
className="shrink-0"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
value={[diffRenderMode]}
|
||||
onValueChange={(value) => {
|
||||
const next = value[0];
|
||||
if (next === "stacked" || next === "split") {
|
||||
setDiffRenderMode(next);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Toggle aria-label="Stacked diff view" value="stacked">
|
||||
<Rows3Icon className="size-3" />
|
||||
</Toggle>
|
||||
<Toggle aria-label="Split diff view" value="split">
|
||||
<Columns2Icon className="size-3" />
|
||||
</Toggle>
|
||||
</ToggleGroup>
|
||||
<Toggle
|
||||
aria-label={diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
|
||||
title={diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
|
||||
variant="outline"
|
||||
size="xs"
|
||||
pressed={diffWordWrap}
|
||||
onPressedChange={(pressed) => {
|
||||
setDiffWordWrap(Boolean(pressed));
|
||||
}}
|
||||
>
|
||||
<TextWrapIcon className="size-3" />
|
||||
</Toggle>
|
||||
<Toggle aria-label="Split diff view" value="split">
|
||||
<Columns2Icon className="size-3" />
|
||||
</Toggle>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -582,6 +612,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
options={{
|
||||
diffStyle: diffRenderMode === "split" ? "split" : "unified",
|
||||
lineDiffType: "none",
|
||||
overflow: diffWordWrap ? "wrap" : "scroll",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
themeType: resolvedTheme as DiffThemeType,
|
||||
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
|
||||
@@ -595,7 +626,14 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
<div className="h-full overflow-auto p-2">
|
||||
<div className="space-y-2">
|
||||
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
|
||||
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
|
||||
<pre
|
||||
className={cn(
|
||||
"max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90",
|
||||
diffWordWrap
|
||||
? "overflow-auto whitespace-pre-wrap wrap-break-word"
|
||||
: "overflow-auto",
|
||||
)}
|
||||
>
|
||||
{renderablePatch.text}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import type { GitStackedAction, GitStatusResult, ThreadId } from "@t3tools/contracts";
|
||||
import type {
|
||||
GitActionProgressEvent,
|
||||
GitStackedAction,
|
||||
GitStatusResult,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
||||
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
||||
import { GitHubIcon } from "./Icons";
|
||||
import {
|
||||
@@ -43,6 +48,7 @@ import {
|
||||
gitStatusQueryOptions,
|
||||
invalidateGitQueries,
|
||||
} from "~/lib/gitReactQuery";
|
||||
import { randomUUID } from "~/lib/utils";
|
||||
import { resolvePathLinkTarget } from "~/terminal-links";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
|
||||
@@ -63,6 +69,50 @@ interface PendingDefaultBranchAction {
|
||||
|
||||
type GitActionToastId = ReturnType<typeof toastManager.add>;
|
||||
|
||||
interface ActiveGitActionProgress {
|
||||
toastId: GitActionToastId;
|
||||
actionId: string;
|
||||
title: string;
|
||||
phaseStartedAtMs: number | null;
|
||||
hookStartedAtMs: number | null;
|
||||
hookName: string | null;
|
||||
lastOutputLine: string | null;
|
||||
currentPhaseLabel: string | null;
|
||||
}
|
||||
|
||||
interface RunGitActionWithToastInput {
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress?: boolean;
|
||||
onConfirmed?: () => void;
|
||||
skipDefaultBranchPrompt?: boolean;
|
||||
statusOverride?: GitStatusResult | null;
|
||||
featureBranch?: boolean;
|
||||
isDefaultBranchOverride?: boolean;
|
||||
progressToastId?: GitActionToastId;
|
||||
filePaths?: string[];
|
||||
}
|
||||
|
||||
function formatElapsedDescription(startedAtMs: number | null): string | undefined {
|
||||
if (startedAtMs === null) {
|
||||
return undefined;
|
||||
}
|
||||
const elapsedSeconds = Math.max(0, Math.floor((Date.now() - startedAtMs) / 1000));
|
||||
if (elapsedSeconds < 60) {
|
||||
return `Running for ${elapsedSeconds}s`;
|
||||
}
|
||||
const minutes = Math.floor(elapsedSeconds / 60);
|
||||
const seconds = elapsedSeconds % 60;
|
||||
return `Running for ${minutes}m ${seconds}s`;
|
||||
}
|
||||
|
||||
function resolveProgressDescription(progress: ActiveGitActionProgress): string | undefined {
|
||||
if (progress.lastOutputLine) {
|
||||
return progress.lastOutputLine;
|
||||
}
|
||||
return formatElapsedDescription(progress.hookStartedAtMs ?? progress.phaseStartedAtMs);
|
||||
}
|
||||
|
||||
function getMenuActionDisabledReason({
|
||||
item,
|
||||
gitStatus,
|
||||
@@ -167,6 +217,21 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const [isEditingFiles, setIsEditingFiles] = useState(false);
|
||||
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
|
||||
useState<PendingDefaultBranchAction | null>(null);
|
||||
const activeGitActionProgressRef = useRef<ActiveGitActionProgress | null>(null);
|
||||
|
||||
const updateActiveProgressToast = useCallback(() => {
|
||||
const progress = activeGitActionProgressRef.current;
|
||||
if (!progress) {
|
||||
return;
|
||||
}
|
||||
toastManager.update(progress.toastId, {
|
||||
type: "loading",
|
||||
title: progress.title,
|
||||
description: resolveProgressDescription(progress),
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
}, [threadToastData]);
|
||||
|
||||
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
|
||||
|
||||
@@ -232,6 +297,84 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
})
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
return;
|
||||
}
|
||||
|
||||
const applyProgressEvent = (event: GitActionProgressEvent) => {
|
||||
const progress = activeGitActionProgressRef.current;
|
||||
if (!progress) {
|
||||
return;
|
||||
}
|
||||
if (gitCwd && event.cwd !== gitCwd) {
|
||||
return;
|
||||
}
|
||||
if (progress.actionId !== event.actionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
switch (event.kind) {
|
||||
case "action_started":
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "phase_started":
|
||||
progress.title = event.label;
|
||||
progress.currentPhaseLabel = event.label;
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_started":
|
||||
progress.title = `Running ${event.hookName}...`;
|
||||
progress.hookName = event.hookName;
|
||||
progress.hookStartedAtMs = now;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_output":
|
||||
progress.lastOutputLine = event.text;
|
||||
break;
|
||||
case "hook_finished":
|
||||
progress.title = progress.currentPhaseLabel ?? "Committing...";
|
||||
progress.hookName = null;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "action_finished":
|
||||
progress.phaseStartedAtMs = null;
|
||||
progress.hookStartedAtMs = null;
|
||||
break;
|
||||
case "action_failed":
|
||||
progress.phaseStartedAtMs = null;
|
||||
progress.hookStartedAtMs = null;
|
||||
break;
|
||||
}
|
||||
|
||||
updateActiveProgressToast();
|
||||
};
|
||||
|
||||
return api.git.onActionProgress(applyProgressEvent);
|
||||
}, [gitCwd, updateActiveProgressToast]);
|
||||
|
||||
useEffect(() => {
|
||||
const interval = window.setInterval(() => {
|
||||
if (!activeGitActionProgressRef.current) {
|
||||
return;
|
||||
}
|
||||
updateActiveProgressToast();
|
||||
}, 1000);
|
||||
|
||||
return () => {
|
||||
window.clearInterval(interval);
|
||||
};
|
||||
}, [updateActiveProgressToast]);
|
||||
|
||||
const openExistingPr = useCallback(async () => {
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
@@ -259,9 +402,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
data: threadToastData,
|
||||
});
|
||||
});
|
||||
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
|
||||
}, [gitStatusForActions, threadToastData]);
|
||||
|
||||
const runGitActionWithToast = useCallback(
|
||||
const runGitActionWithToast = useEffectEvent(
|
||||
async ({
|
||||
action,
|
||||
commitMessage,
|
||||
@@ -273,18 +416,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
isDefaultBranchOverride,
|
||||
progressToastId,
|
||||
filePaths,
|
||||
}: {
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress?: boolean;
|
||||
onConfirmed?: () => void;
|
||||
skipDefaultBranchPrompt?: boolean;
|
||||
statusOverride?: GitStatusResult | null;
|
||||
featureBranch?: boolean;
|
||||
isDefaultBranchOverride?: boolean;
|
||||
progressToastId?: GitActionToastId;
|
||||
filePaths?: string[];
|
||||
}) => {
|
||||
}: RunGitActionWithToastInput) => {
|
||||
const actionStatus = statusOverride ?? gitStatusForActions;
|
||||
const actionBranch = actionStatus?.branch ?? null;
|
||||
const actionIsDefaultBranch =
|
||||
@@ -319,40 +451,40 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
forcePushOnly: forcePushOnlyProgress,
|
||||
featureBranch,
|
||||
});
|
||||
const actionId = randomUUID();
|
||||
const resolvedProgressToastId =
|
||||
progressToastId ??
|
||||
toastManager.add({
|
||||
type: "loading",
|
||||
title: progressStages[0] ?? "Running git action...",
|
||||
description: "Waiting for Git...",
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
|
||||
activeGitActionProgressRef.current = {
|
||||
toastId: resolvedProgressToastId,
|
||||
actionId,
|
||||
title: progressStages[0] ?? "Running git action...",
|
||||
phaseStartedAtMs: null,
|
||||
hookStartedAtMs: null,
|
||||
hookName: null,
|
||||
lastOutputLine: null,
|
||||
currentPhaseLabel: progressStages[0] ?? "Running git action...",
|
||||
};
|
||||
|
||||
if (progressToastId) {
|
||||
toastManager.update(progressToastId, {
|
||||
type: "loading",
|
||||
title: progressStages[0] ?? "Running git action...",
|
||||
description: "Waiting for Git...",
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
}
|
||||
|
||||
let stageIndex = 0;
|
||||
const stageInterval = setInterval(() => {
|
||||
stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
|
||||
toastManager.update(resolvedProgressToastId, {
|
||||
title: progressStages[stageIndex] ?? "Running git action...",
|
||||
type: "loading",
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
}, 1100);
|
||||
|
||||
const stopProgressUpdates = () => {
|
||||
clearInterval(stageInterval);
|
||||
};
|
||||
|
||||
const promise = runImmediateGitActionMutation.mutateAsync({
|
||||
actionId,
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
@@ -361,7 +493,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
|
||||
try {
|
||||
const result = await promise;
|
||||
stopProgressUpdates();
|
||||
activeGitActionProgressRef.current = null;
|
||||
const resultToast = summarizeGitResult(result);
|
||||
|
||||
const existingOpenPrUrl =
|
||||
@@ -437,7 +569,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
: {}),
|
||||
});
|
||||
} catch (err) {
|
||||
stopProgressUpdates();
|
||||
activeGitActionProgressRef.current = null;
|
||||
toastManager.update(resolvedProgressToastId, {
|
||||
type: "error",
|
||||
title: "Action failed",
|
||||
@@ -446,14 +578,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
[
|
||||
isDefaultBranch,
|
||||
runImmediateGitActionMutation,
|
||||
setPendingDefaultBranchAction,
|
||||
threadToastData,
|
||||
gitStatusForActions,
|
||||
],
|
||||
);
|
||||
|
||||
const continuePendingDefaultBranchAction = useCallback(() => {
|
||||
@@ -469,38 +593,23 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
skipDefaultBranchPrompt: true,
|
||||
});
|
||||
}, [pendingDefaultBranchAction, runGitActionWithToast]);
|
||||
|
||||
const checkoutNewBranchAndRunAction = useCallback(
|
||||
(actionParams: {
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress?: boolean;
|
||||
onConfirmed?: () => void;
|
||||
filePaths?: string[];
|
||||
}) => {
|
||||
void runGitActionWithToast({
|
||||
...actionParams,
|
||||
featureBranch: true,
|
||||
skipDefaultBranchPrompt: true,
|
||||
});
|
||||
},
|
||||
[runGitActionWithToast],
|
||||
);
|
||||
}, [pendingDefaultBranchAction]);
|
||||
|
||||
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
|
||||
if (!pendingDefaultBranchAction) return;
|
||||
const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } =
|
||||
pendingDefaultBranchAction;
|
||||
setPendingDefaultBranchAction(null);
|
||||
checkoutNewBranchAndRunAction({
|
||||
void runGitActionWithToast({
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
forcePushOnlyProgress,
|
||||
...(onConfirmed ? { onConfirmed } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
featureBranch: true,
|
||||
skipDefaultBranchPrompt: true,
|
||||
});
|
||||
}, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]);
|
||||
}, [pendingDefaultBranchAction]);
|
||||
|
||||
const runDialogActionOnNewBranch = useCallback(() => {
|
||||
if (!isCommitDialogOpen) return;
|
||||
@@ -511,18 +620,14 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
setExcludedFiles(new Set());
|
||||
setIsEditingFiles(false);
|
||||
|
||||
checkoutNewBranchAndRunAction({
|
||||
void runGitActionWithToast({
|
||||
action: "commit",
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
|
||||
featureBranch: true,
|
||||
skipDefaultBranchPrompt: true,
|
||||
});
|
||||
}, [
|
||||
allSelected,
|
||||
isCommitDialogOpen,
|
||||
dialogCommitMessage,
|
||||
checkoutNewBranchAndRunAction,
|
||||
selectedFiles,
|
||||
]);
|
||||
}, [allSelected, isCommitDialogOpen, dialogCommitMessage, selectedFiles]);
|
||||
|
||||
const runQuickAction = useCallback(() => {
|
||||
if (quickAction.kind === "open_pr") {
|
||||
@@ -562,7 +667,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
if (quickAction.action) {
|
||||
void runGitActionWithToast({ action: quickAction.action });
|
||||
}
|
||||
}, [openExistingPr, pullMutation, quickAction, runGitActionWithToast, threadToastData]);
|
||||
}, [openExistingPr, pullMutation, quickAction, threadToastData]);
|
||||
|
||||
const openDialogForMenuItem = useCallback(
|
||||
(item: GitActionMenuItem) => {
|
||||
@@ -583,7 +688,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
setIsEditingFiles(false);
|
||||
setIsCommitDialogOpen(true);
|
||||
},
|
||||
[openExistingPr, runGitActionWithToast, setIsCommitDialogOpen],
|
||||
[openExistingPr, setIsCommitDialogOpen],
|
||||
);
|
||||
|
||||
const runDialogAction = useCallback(() => {
|
||||
@@ -602,7 +707,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
allSelected,
|
||||
dialogCommitMessage,
|
||||
isCommitDialogOpen,
|
||||
runGitActionWithToast,
|
||||
selectedFiles,
|
||||
setDialogCommitMessage,
|
||||
setIsCommitDialogOpen,
|
||||
|
||||
@@ -64,7 +64,10 @@ function createMinimalSnapshot(): OrchestrationReadModel {
|
||||
id: PROJECT_ID,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModel: "gpt-5",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
@@ -76,7 +79,10 @@ function createMinimalSnapshot(): OrchestrationReadModel {
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Test thread",
|
||||
model: "gpt-5",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: "main",
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -39,7 +39,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";
|
||||
@@ -84,6 +84,7 @@ import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
import { isNonEmpty as isNonEmptyString } from "effect/String";
|
||||
import {
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
@@ -257,7 +258,7 @@ export default function Sidebar() {
|
||||
const markThreadUnread = useStore((store) => store.markThreadUnread);
|
||||
const toggleProject = useStore((store) => store.toggleProject);
|
||||
const reorderProjects = useStore((store) => store.reorderProjects);
|
||||
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
|
||||
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
|
||||
const getDraftThreadByProjectId = useComposerDraftStore(
|
||||
(store) => store.getDraftThreadByProjectId,
|
||||
);
|
||||
@@ -305,7 +306,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)),
|
||||
@@ -432,7 +434,10 @@ export default function Sidebar() {
|
||||
projectId,
|
||||
title,
|
||||
workspaceRoot: cwd,
|
||||
defaultModel: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
await handleNewThread(projectId, {
|
||||
@@ -1235,9 +1240,9 @@ export default function Sidebar() {
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Add project"
|
||||
aria-label={shouldShowProjectPathEntry ? "Cancel add project" : "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"
|
||||
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={handleStartAddProject}
|
||||
/>
|
||||
}
|
||||
@@ -1248,7 +1253,9 @@ export default function Sidebar() {
|
||||
}`}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="right">Add project</TooltipPopup>
|
||||
<TooltipPopup side="right">
|
||||
{shouldShowProjectPathEntry ? "Cancel add project" : "Add project"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -1339,13 +1346,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 +1384,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}
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import GitActionsControl from "../GitActionsControl";
|
||||
import { DiffIcon } from "lucide-react";
|
||||
import { DiffIcon, TerminalSquareIcon } from "lucide-react";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import ProjectScriptsControl, { type NewProjectScriptInput } from "../ProjectScriptsControl";
|
||||
@@ -24,6 +24,9 @@ interface ChatHeaderProps {
|
||||
preferredScriptId: string | null;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
availableEditors: ReadonlyArray<EditorId>;
|
||||
terminalAvailable: boolean;
|
||||
terminalOpen: boolean;
|
||||
terminalToggleShortcutLabel: string | null;
|
||||
diffToggleShortcutLabel: string | null;
|
||||
gitCwd: string | null;
|
||||
diffOpen: boolean;
|
||||
@@ -31,6 +34,7 @@ interface ChatHeaderProps {
|
||||
onAddProjectScript: (input: NewProjectScriptInput) => Promise<void>;
|
||||
onUpdateProjectScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void>;
|
||||
onDeleteProjectScript: (scriptId: string) => Promise<void>;
|
||||
onToggleTerminal: () => void;
|
||||
onToggleDiff: () => void;
|
||||
}
|
||||
|
||||
@@ -44,6 +48,9 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
preferredScriptId,
|
||||
keybindings,
|
||||
availableEditors,
|
||||
terminalAvailable,
|
||||
terminalOpen,
|
||||
terminalToggleShortcutLabel,
|
||||
diffToggleShortcutLabel,
|
||||
gitCwd,
|
||||
diffOpen,
|
||||
@@ -51,6 +58,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
onAddProjectScript,
|
||||
onUpdateProjectScript,
|
||||
onDeleteProjectScript,
|
||||
onToggleTerminal,
|
||||
onToggleDiff,
|
||||
}: ChatHeaderProps) {
|
||||
return (
|
||||
@@ -94,6 +102,30 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
/>
|
||||
)}
|
||||
{activeProjectName && <GitActionsControl gitCwd={gitCwd} activeThreadId={activeThreadId} />}
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Toggle
|
||||
className="shrink-0"
|
||||
pressed={terminalOpen}
|
||||
onPressedChange={onToggleTerminal}
|
||||
aria-label="Toggle terminal drawer"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={!terminalAvailable}
|
||||
>
|
||||
<TerminalSquareIcon className="size-3" />
|
||||
</Toggle>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom">
|
||||
{!terminalAvailable
|
||||
? "Terminal is unavailable until this thread has an active project."
|
||||
: terminalToggleShortcutLabel
|
||||
? `Toggle terminal drawer (${terminalToggleShortcutLabel})`
|
||||
: "Toggle terminal drawer"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
|
||||
@@ -25,10 +25,10 @@ async function mountPicker(props?: {
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
provider: "claudeAgent",
|
||||
model: props?.model ?? "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: props?.model ?? "claude-opus-4-6",
|
||||
options: {
|
||||
...(props?.effort ? { effort: props.effort } : {}),
|
||||
...(props?.thinkingEnabled === false ? { thinking: false } : {}),
|
||||
...(props?.fastModeEnabled ? { fastMode: true } : {}),
|
||||
@@ -173,4 +173,26 @@ 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().stickyModelSelection).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
options: {
|
||||
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,22 @@ 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.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
|
||||
const {
|
||||
effort,
|
||||
thinkingEnabled,
|
||||
@@ -94,19 +103,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 +157,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 +173,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 +197,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 +216,20 @@ 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.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
const { effort, thinkingEnabled, fastModeEnabled, ultrathinkPromptControlled, supportsFastMode } =
|
||||
getSelectedClaudeTraits(props.model, prompt, modelOptions);
|
||||
getSelectedClaudeTraits(model, prompt, modelOptions);
|
||||
const triggerLabel = [
|
||||
ultrathinkPromptControlled
|
||||
? "Ultrathink"
|
||||
@@ -247,9 +264,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>
|
||||
|
||||
@@ -22,10 +22,10 @@ async function mountPicker(props: {
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
provider: "codex",
|
||||
model: null,
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
...(props.reasoningEffort ? { reasoningEffort: props.reasoningEffort } : {}),
|
||||
...(props.fastModeEnabled ? { fastMode: true } : {}),
|
||||
},
|
||||
@@ -116,6 +116,26 @@ 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().stickyModelSelection).toMatchObject({
|
||||
provider: "codex",
|
||||
options: {
|
||||
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(
|
||||
@@ -126,6 +146,7 @@ describe("CodexTraitsPicker", () => {
|
||||
[threadId]: {
|
||||
prompt: "",
|
||||
attachments: [],
|
||||
modelSelection: null,
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "xhigh",
|
||||
@@ -154,12 +175,16 @@ describe("CodexTraitsPicker", () => {
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("Extra High · Fast");
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
{
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
|
||||
@@ -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,13 @@ 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.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
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 +65,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 +90,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 },
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -114,7 +113,9 @@ export const CodexTraitsMenuContent = memo(CodexTraitsMenuContentImpl);
|
||||
|
||||
export const CodexTraitsPicker = memo(function CodexTraitsPicker(props: { threadId: ThreadId }) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const modelOptions = useComposerThreadDraft(props.threadId).modelOptions?.codex;
|
||||
const draft = useComposerThreadDraft(props.threadId);
|
||||
const modelOptions =
|
||||
draft.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
const { effort, fastModeEnabled } = getSelectedCodexTraits(modelOptions);
|
||||
const triggerLabel = [CODEX_REASONING_LABELS[effort], ...(fastModeEnabled ? ["Fast"] : [])]
|
||||
.filter(Boolean)
|
||||
|
||||
@@ -27,9 +27,16 @@ async function mountMenu(props?: {
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
provider,
|
||||
model: props?.model ?? "claude-opus-4-6",
|
||||
modelOptions: props?.modelOptions ?? null,
|
||||
modelSelection: {
|
||||
provider,
|
||||
model: props?.model ?? "claude-opus-4-6",
|
||||
...(props?.modelOptions
|
||||
? {
|
||||
options:
|
||||
provider === "codex" ? props.modelOptions.codex : props.modelOptions.claudeAgent,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -164,32 +164,45 @@ function SelectPopup({
|
||||
);
|
||||
}
|
||||
|
||||
function SelectItem({ className, children, ...props }: SelectPrimitive.Item.Props) {
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
hideIndicator = false,
|
||||
...props
|
||||
}: SelectPrimitive.Item.Props & {
|
||||
hideIndicator?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
className={cn(
|
||||
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default items-center gap-2 rounded-sm py-1 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
hideIndicator ? "grid-cols-[1fr] ps-3 pe-3" : "grid-cols-[1rem_1fr] ps-2 pe-4",
|
||||
className,
|
||||
)}
|
||||
data-slot="select-item"
|
||||
{...props}
|
||||
>
|
||||
<SelectPrimitive.ItemIndicator className="col-start-1">
|
||||
<svg
|
||||
fill="none"
|
||||
height="24"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
xmlns="http://www.w3.org/1500/svg"
|
||||
>
|
||||
<path d="M5.252 12.7 10.2 18.63 18.748 5.37" />
|
||||
</svg>
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
<SelectPrimitive.ItemText className="col-start-2 min-w-0">
|
||||
{hideIndicator ? null : (
|
||||
<SelectPrimitive.ItemIndicator className="col-start-1" data-slot="select-item-indicator">
|
||||
<svg
|
||||
fill="none"
|
||||
height="24"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
xmlns="http://www.w3.org/1500/svg"
|
||||
>
|
||||
<path d="M5.252 12.7 10.2 18.63 18.748 5.37" />
|
||||
</svg>
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
)}
|
||||
<SelectPrimitive.ItemText
|
||||
className={cn("min-w-0", hideIndicator ? "col-start-1" : "col-start-2")}
|
||||
data-slot="select-item-text"
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { ProjectId, ThreadId, type ModelSelection } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
@@ -62,17 +62,34 @@ function makeTerminalContext(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function resetComposerDraftStore() {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelection: null,
|
||||
});
|
||||
}
|
||||
|
||||
function modelSelection(
|
||||
provider: "codex" | "claudeAgent",
|
||||
model: string,
|
||||
options?: ModelSelection["options"],
|
||||
): ModelSelection {
|
||||
return {
|
||||
provider,
|
||||
model,
|
||||
...(options ? { options } : {}),
|
||||
} as ModelSelection;
|
||||
}
|
||||
|
||||
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 +174,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 +436,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", () => {
|
||||
@@ -519,9 +528,11 @@ describe("composerDraftStore project draft thread mapping", () => {
|
||||
it("clears draft registration independently", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectId, threadId);
|
||||
store.setPrompt(threadId, "remove me");
|
||||
store.clearDraftThread(threadId);
|
||||
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("updates branch context on an existing draft thread", () => {
|
||||
@@ -595,103 +606,246 @@ describe("composerDraftStore project draft thread mapping", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore modelOptions", () => {
|
||||
describe("composerDraftStore modelSelection", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-model-options");
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("stores provider-scoped model options in the draft", () => {
|
||||
it("stores a model selection in the draft", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
claudeAgent: {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps default-only model selections on the draft", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.4"));
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.4"),
|
||||
);
|
||||
});
|
||||
|
||||
it("replaces only the targeted provider options on the current model selection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
}),
|
||||
);
|
||||
store.setStickyModelSelection(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
}),
|
||||
);
|
||||
|
||||
store.setProviderModelOptions(
|
||||
threadId,
|
||||
"claudeAgent",
|
||||
{
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
{ persistSticky: true },
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("drops default-only model options from the draft", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: true,
|
||||
},
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore setModel", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-model");
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps explicit DEFAULT_MODEL overrides instead of coercing to null", () => {
|
||||
it("removes selection options when the patched provider options normalize empty", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModel(threadId, "gpt-5.3-codex");
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
effort: "max",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.model).toBe(
|
||||
"gpt-5.3-codex",
|
||||
store.setProviderModelOptions(threadId, "claudeAgent", {
|
||||
thinking: true,
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6"),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toBeNull();
|
||||
});
|
||||
|
||||
it("removes model options entirely when the last provider entry normalizes empty", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.4", { fastMode: true }));
|
||||
|
||||
store.setProviderModelOptions(threadId, "codex", {
|
||||
reasoningEffort: "high",
|
||||
fastMode: false,
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.4"),
|
||||
);
|
||||
});
|
||||
|
||||
it("updates only the draft when sticky persistence is omitted", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setStickyModelSelection(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
|
||||
store.setProviderModelOptions(threadId, "claudeAgent", {
|
||||
thinking: false,
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("updates only the draft when sticky persistence is disabled", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setStickyModelSelection(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
|
||||
store.setProviderModelOptions(
|
||||
threadId,
|
||||
"claudeAgent",
|
||||
{
|
||||
thinking: false,
|
||||
},
|
||||
{ persistSticky: false },
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore setProvider", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-provider");
|
||||
describe("composerDraftStore setModelSelection", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-model");
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("keeps explicit model overrides instead of coercing to null", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.3-codex"));
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore sticky composer settings", () => {
|
||||
beforeEach(() => {
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("stores a sticky model selection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setStickyModelSelection(
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState()).toMatchObject({
|
||||
stickyModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("persists provider-only selection even when prompt/model are empty", () => {
|
||||
it("normalizes empty sticky model options by dropping selection options", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setProvider(threadId, "codex");
|
||||
store.setStickyModelSelection(modelSelection("codex", "gpt-5.4"));
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.provider).toBe("codex");
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.4"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore provider-scoped option updates", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-provider");
|
||||
|
||||
beforeEach(() => {
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("removes empty provider-only draft when provider is reset", () => {
|
||||
it("does not patch provider options when the draft selection is on another provider", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setProvider(threadId, "codex");
|
||||
store.setProvider(threadId, null);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "medium",
|
||||
}),
|
||||
);
|
||||
store.setProviderModelOptions(threadId, "claudeAgent", { effort: "max" });
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "medium",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -699,11 +853,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", () => {
|
||||
|
||||
+255
-185
@@ -3,6 +3,7 @@ import {
|
||||
type ClaudeCodeEffort,
|
||||
type CodexReasoningEffort,
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
type ModelSelection,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
ProviderKind,
|
||||
@@ -11,6 +12,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";
|
||||
@@ -72,9 +74,7 @@ const PersistedComposerThreadDraftState = Schema.Struct({
|
||||
prompt: Schema.String,
|
||||
attachments: Schema.Array(PersistedComposerImageAttachment),
|
||||
terminalContexts: Schema.optionalKey(Schema.Array(PersistedTerminalContextDraft)),
|
||||
provider: Schema.optionalKey(ProviderKind),
|
||||
model: Schema.optionalKey(Schema.String),
|
||||
modelOptions: Schema.optionalKey(ProviderModelOptions),
|
||||
modelSelection: Schema.optionalKey(Schema.NullOr(Schema.Unknown)),
|
||||
runtimeMode: Schema.optionalKey(RuntimeMode),
|
||||
interactionMode: Schema.optionalKey(ProviderInteractionMode),
|
||||
});
|
||||
@@ -88,6 +88,11 @@ const LegacyCodexFields = Schema.Struct({
|
||||
type LegacyCodexFields = typeof LegacyCodexFields.Type;
|
||||
|
||||
type LegacyPersistedCodexThreadDraftState = PersistedComposerThreadDraftState & LegacyCodexFields;
|
||||
type LegacyPersistedComposerThreadDraftState = LegacyPersistedCodexThreadDraftState & {
|
||||
provider?: ProviderKind;
|
||||
model?: string;
|
||||
modelOptions?: ProviderModelOptions | null;
|
||||
};
|
||||
|
||||
const PersistedDraftThreadState = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
@@ -104,6 +109,7 @@ const PersistedComposerDraftStoreState = Schema.Struct({
|
||||
draftsByThreadId: Schema.Record(ThreadId, PersistedComposerThreadDraftState),
|
||||
draftThreadsByThreadId: Schema.Record(ThreadId, PersistedDraftThreadState),
|
||||
projectDraftThreadIdByProjectId: Schema.Record(ProjectId, ThreadId),
|
||||
stickyModelSelection: Schema.NullOr(Schema.Unknown),
|
||||
});
|
||||
type PersistedComposerDraftStoreState = typeof PersistedComposerDraftStoreState.Type;
|
||||
|
||||
@@ -118,9 +124,7 @@ interface ComposerThreadDraftState {
|
||||
nonPersistedImageIds: string[];
|
||||
persistedAttachments: PersistedComposerImageAttachment[];
|
||||
terminalContexts: TerminalContextDraft[];
|
||||
provider: ProviderKind | null;
|
||||
model: string | null;
|
||||
modelOptions: ProviderModelOptions | null;
|
||||
modelSelection: ModelSelection | null;
|
||||
runtimeMode: RuntimeMode | null;
|
||||
interactionMode: ProviderInteractionMode | null;
|
||||
}
|
||||
@@ -143,6 +147,7 @@ interface ComposerDraftStoreState {
|
||||
draftsByThreadId: Record<ThreadId, ComposerThreadDraftState>;
|
||||
draftThreadsByThreadId: Record<ThreadId, DraftThreadState>;
|
||||
projectDraftThreadIdByProjectId: Record<ProjectId, ThreadId>;
|
||||
stickyModelSelection: ModelSelection | null;
|
||||
getDraftThreadByProjectId: (projectId: ProjectId) => ProjectDraftThread | null;
|
||||
getDraftThread: (threadId: ThreadId) => DraftThreadState | null;
|
||||
setProjectDraftThreadId: (
|
||||
@@ -172,13 +177,20 @@ interface ComposerDraftStoreState {
|
||||
clearProjectDraftThreadId: (projectId: ProjectId) => void;
|
||||
clearProjectDraftThreadById: (projectId: ProjectId, threadId: ThreadId) => void;
|
||||
clearDraftThread: (threadId: ThreadId) => void;
|
||||
setStickyModelSelection: (modelSelection: ModelSelection | null | undefined) => void;
|
||||
setPrompt: (threadId: ThreadId, prompt: string) => void;
|
||||
setTerminalContexts: (threadId: ThreadId, contexts: TerminalContextDraft[]) => void;
|
||||
setProvider: (threadId: ThreadId, provider: ProviderKind | null | undefined) => void;
|
||||
setModel: (threadId: ThreadId, model: string | null | undefined) => void;
|
||||
setModelOptions: (
|
||||
setModelSelection: (
|
||||
threadId: ThreadId,
|
||||
modelOptions: ProviderModelOptions | null | undefined,
|
||||
modelSelection: ModelSelection | 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: (
|
||||
@@ -204,14 +216,14 @@ interface ComposerDraftStoreState {
|
||||
attachments: PersistedComposerImageAttachment[],
|
||||
) => void;
|
||||
clearComposerContent: (threadId: ThreadId) => void;
|
||||
clearThreadDraft: (threadId: ThreadId) => void;
|
||||
}
|
||||
|
||||
const EMPTY_PERSISTED_DRAFT_STORE_STATE: PersistedComposerDraftStoreState = {
|
||||
const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftStoreState>({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
};
|
||||
stickyModelSelection: null,
|
||||
});
|
||||
|
||||
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
|
||||
const EMPTY_IDS: string[] = [];
|
||||
@@ -226,9 +238,7 @@ const EMPTY_THREAD_DRAFT = Object.freeze<ComposerThreadDraftState>({
|
||||
nonPersistedImageIds: EMPTY_IDS,
|
||||
persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
|
||||
terminalContexts: EMPTY_TERMINAL_CONTEXTS,
|
||||
provider: null,
|
||||
model: null,
|
||||
modelOptions: null,
|
||||
modelSelection: null,
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
});
|
||||
@@ -240,9 +250,7 @@ function createEmptyThreadDraft(): ComposerThreadDraftState {
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
provider: null,
|
||||
model: null,
|
||||
modelOptions: null,
|
||||
modelSelection: null,
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
@@ -311,9 +319,7 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
|
||||
draft.images.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.terminalContexts.length === 0 &&
|
||||
draft.provider === null &&
|
||||
draft.model === null &&
|
||||
draft.modelOptions === null &&
|
||||
draft.modelSelection === null &&
|
||||
draft.runtimeMode === null &&
|
||||
draft.interactionMode === null
|
||||
);
|
||||
@@ -397,6 +403,59 @@ function normalizeProviderModelOptions(
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeModelSelection(
|
||||
value: unknown,
|
||||
legacy?: {
|
||||
provider?: unknown;
|
||||
model?: unknown;
|
||||
modelOptions?: unknown;
|
||||
legacyCodex?: LegacyCodexFields;
|
||||
},
|
||||
): ModelSelection | null {
|
||||
const candidate = value && typeof value === "object" ? (value as Record<string, unknown>) : null;
|
||||
const provider = normalizeProviderKind(candidate?.provider ?? legacy?.provider);
|
||||
if (provider === null) {
|
||||
return null;
|
||||
}
|
||||
const rawModel = candidate?.model ?? legacy?.model;
|
||||
if (typeof rawModel !== "string") {
|
||||
return null;
|
||||
}
|
||||
const model = normalizeModelSlug(rawModel, provider);
|
||||
if (!model) {
|
||||
return null;
|
||||
}
|
||||
const modelOptions = normalizeProviderModelOptions(
|
||||
candidate?.options ? { [provider]: candidate.options } : legacy?.modelOptions,
|
||||
provider,
|
||||
provider === "codex" ? legacy?.legacyCodex : undefined,
|
||||
);
|
||||
const options = provider === "codex" ? modelOptions?.codex : modelOptions?.claudeAgent;
|
||||
return {
|
||||
provider,
|
||||
model,
|
||||
...(options ? { options } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -583,10 +642,6 @@ function normalizePersistedDraftThreads(
|
||||
|
||||
function normalizePersistedDraftsByThreadId(
|
||||
rawDraftMap: unknown,
|
||||
resolveModelOptions: (
|
||||
draftCandidate: PersistedComposerThreadDraftState | LegacyPersistedCodexThreadDraftState,
|
||||
provider: ProviderKind | null,
|
||||
) => ProviderModelOptions | null,
|
||||
): PersistedComposerDraftStoreState["draftsByThreadId"] {
|
||||
if (!rawDraftMap || typeof rawDraftMap !== "object") {
|
||||
return {};
|
||||
@@ -617,11 +672,6 @@ function normalizePersistedDraftsByThreadId(
|
||||
return normalized ? [normalized] : [];
|
||||
})
|
||||
: [];
|
||||
const provider = normalizeProviderKind(draftCandidate.provider);
|
||||
const model =
|
||||
typeof draftCandidate.model === "string"
|
||||
? normalizeModelSlug(draftCandidate.model, provider ?? "codex")
|
||||
: null;
|
||||
const runtimeMode =
|
||||
draftCandidate.runtimeMode === "approval-required" ||
|
||||
draftCandidate.runtimeMode === "full-access"
|
||||
@@ -631,18 +681,22 @@ function normalizePersistedDraftsByThreadId(
|
||||
draftCandidate.interactionMode === "plan" || draftCandidate.interactionMode === "default"
|
||||
? draftCandidate.interactionMode
|
||||
: null;
|
||||
const modelOptions = resolveModelOptions(draftCandidate, provider);
|
||||
const prompt = ensureInlineTerminalContextPlaceholders(
|
||||
promptCandidate,
|
||||
terminalContexts.length,
|
||||
);
|
||||
const legacyDraftCandidate = draftCandidate as LegacyPersistedComposerThreadDraftState;
|
||||
const modelSelection = normalizeModelSelection(draftCandidate.modelSelection, {
|
||||
provider: legacyDraftCandidate.provider,
|
||||
model: legacyDraftCandidate.model,
|
||||
modelOptions: legacyDraftCandidate.modelOptions,
|
||||
legacyCodex: legacyDraftCandidate,
|
||||
});
|
||||
if (
|
||||
promptCandidate.length === 0 &&
|
||||
attachments.length === 0 &&
|
||||
terminalContexts.length === 0 &&
|
||||
!provider &&
|
||||
!model &&
|
||||
modelOptions === null &&
|
||||
modelSelection === null &&
|
||||
!runtimeMode &&
|
||||
!interactionMode
|
||||
) {
|
||||
@@ -652,9 +706,7 @@ function normalizePersistedDraftsByThreadId(
|
||||
prompt,
|
||||
attachments,
|
||||
...(terminalContexts.length > 0 ? { terminalContexts } : {}),
|
||||
...(provider ? { provider } : {}),
|
||||
...(model ? { model } : {}),
|
||||
...(modelOptions ? { modelOptions } : {}),
|
||||
...(modelSelection ? { modelSelection } : {}),
|
||||
...(runtimeMode ? { runtimeMode } : {}),
|
||||
...(interactionMode ? { interactionMode } : {}),
|
||||
};
|
||||
@@ -665,7 +717,6 @@ function normalizePersistedDraftsByThreadId(
|
||||
|
||||
function migratePersistedComposerDraftStoreState(
|
||||
persistedState: unknown,
|
||||
persistedVersion: number,
|
||||
): PersistedComposerDraftStoreState {
|
||||
if (!persistedState || typeof persistedState !== "object") {
|
||||
return EMPTY_PERSISTED_DRAFT_STORE_STATE;
|
||||
@@ -674,23 +725,19 @@ function migratePersistedComposerDraftStoreState(
|
||||
const rawDraftMap = candidate.draftsByThreadId;
|
||||
const rawDraftThreadsByThreadId = candidate.draftThreadsByThreadId;
|
||||
const rawProjectDraftThreadIdByProjectId = candidate.projectDraftThreadIdByProjectId;
|
||||
const stickyModelSelection = normalizeModelSelection(candidate.stickyModelSelection, {
|
||||
provider: candidate.stickyProvider ?? "codex",
|
||||
model: candidate.stickyModel,
|
||||
modelOptions: candidate.stickyModelOptions,
|
||||
});
|
||||
const { draftThreadsByThreadId, projectDraftThreadIdByProjectId } =
|
||||
normalizePersistedDraftThreads(rawDraftThreadsByThreadId, rawProjectDraftThreadIdByProjectId);
|
||||
const draftsByThreadId = normalizePersistedDraftsByThreadId(
|
||||
rawDraftMap,
|
||||
(draftCandidate, provider) =>
|
||||
persistedVersion >= COMPOSER_DRAFT_STORAGE_VERSION
|
||||
? normalizeProviderModelOptions(draftCandidate.modelOptions, provider)
|
||||
: normalizeProviderModelOptions(
|
||||
draftCandidate.modelOptions,
|
||||
provider,
|
||||
draftCandidate as LegacyPersistedCodexThreadDraftState,
|
||||
),
|
||||
);
|
||||
const draftsByThreadId = normalizePersistedDraftsByThreadId(rawDraftMap);
|
||||
return {
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId,
|
||||
stickyModelSelection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -708,9 +755,7 @@ function partializeComposerDraftStoreState(
|
||||
draft.prompt.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.terminalContexts.length === 0 &&
|
||||
draft.provider === null &&
|
||||
draft.model === null &&
|
||||
draft.modelOptions === null &&
|
||||
draft.modelSelection === null &&
|
||||
draft.runtimeMode === null &&
|
||||
draft.interactionMode === null
|
||||
) {
|
||||
@@ -732,9 +777,7 @@ function partializeComposerDraftStoreState(
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
...(draft.model ? { model: draft.model } : {}),
|
||||
...(draft.modelOptions ? { modelOptions: draft.modelOptions } : {}),
|
||||
...(draft.provider ? { provider: draft.provider } : {}),
|
||||
...(draft.modelSelection ? { modelSelection: draft.modelSelection } : {}),
|
||||
...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}),
|
||||
...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}),
|
||||
};
|
||||
@@ -744,6 +787,7 @@ function partializeComposerDraftStoreState(
|
||||
draftsByThreadId: persistedDraftsByThreadId,
|
||||
draftThreadsByThreadId: state.draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: state.projectDraftThreadIdByProjectId,
|
||||
stickyModelSelection: state.stickyModelSelection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -759,14 +803,19 @@ function normalizeCurrentPersistedComposerDraftStoreState(
|
||||
normalizedPersistedState.draftThreadsByThreadId,
|
||||
normalizedPersistedState.projectDraftThreadIdByProjectId,
|
||||
);
|
||||
const stickyModelSelection = normalizeModelSelection(
|
||||
normalizedPersistedState.stickyModelSelection,
|
||||
{
|
||||
provider: normalizedPersistedState.stickyProvider,
|
||||
model: normalizedPersistedState.stickyModel,
|
||||
modelOptions: normalizedPersistedState.stickyModelOptions,
|
||||
},
|
||||
);
|
||||
return {
|
||||
draftsByThreadId: normalizePersistedDraftsByThreadId(
|
||||
normalizedPersistedState.draftsByThreadId,
|
||||
(draftCandidate, provider) =>
|
||||
normalizeProviderModelOptions(draftCandidate.modelOptions, provider),
|
||||
),
|
||||
draftsByThreadId: normalizePersistedDraftsByThreadId(normalizedPersistedState.draftsByThreadId),
|
||||
draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId,
|
||||
stickyModelSelection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -790,6 +839,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 {
|
||||
@@ -856,9 +952,12 @@ function toHydratedThreadDraft(
|
||||
...context,
|
||||
text: "",
|
||||
})) ?? [],
|
||||
provider: persistedDraft.provider ?? null,
|
||||
model: persistedDraft.model ?? null,
|
||||
modelOptions: persistedDraft.modelOptions ?? null,
|
||||
modelSelection: normalizeModelSelection(persistedDraft.modelSelection, {
|
||||
provider: (persistedDraft as LegacyPersistedComposerThreadDraftState).provider,
|
||||
model: (persistedDraft as LegacyPersistedComposerThreadDraftState).model,
|
||||
modelOptions: (persistedDraft as LegacyPersistedComposerThreadDraftState).modelOptions,
|
||||
legacyCodex: persistedDraft as LegacyPersistedComposerThreadDraftState,
|
||||
}),
|
||||
runtimeMode: persistedDraft.runtimeMode ?? null,
|
||||
interactionMode: persistedDraft.interactionMode ?? null,
|
||||
};
|
||||
@@ -870,6 +969,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelection: null,
|
||||
getDraftThreadByProjectId: (projectId) => {
|
||||
if (projectId.length === 0) {
|
||||
return null;
|
||||
@@ -1084,12 +1184,19 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const existing = get().draftsByThreadId[threadId];
|
||||
if (existing) {
|
||||
for (const image of existing.images) {
|
||||
revokeObjectPreviewUrl(image.previewUrl);
|
||||
}
|
||||
}
|
||||
set((state) => {
|
||||
const hasDraftThread = state.draftThreadsByThreadId[threadId] !== undefined;
|
||||
const hasProjectMapping = Object.values(state.projectDraftThreadIdByProjectId).includes(
|
||||
threadId,
|
||||
);
|
||||
if (!hasDraftThread && !hasProjectMapping) {
|
||||
const hasComposerDraft = state.draftsByThreadId[threadId] !== undefined;
|
||||
if (!hasDraftThread && !hasProjectMapping && !hasComposerDraft) {
|
||||
return state;
|
||||
}
|
||||
const nextProjectDraftThreadIdByProjectId = Object.fromEntries(
|
||||
@@ -1099,12 +1206,23 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
) as Record<ProjectId, ThreadId>;
|
||||
const { [threadId]: _removedDraftThread, ...restDraftThreadsByThreadId } =
|
||||
state.draftThreadsByThreadId;
|
||||
const { [threadId]: _removedComposerDraft, ...restDraftsByThreadId } =
|
||||
state.draftsByThreadId;
|
||||
return {
|
||||
draftsByThreadId: restDraftsByThreadId,
|
||||
draftThreadsByThreadId: restDraftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: nextProjectDraftThreadIdByProjectId,
|
||||
};
|
||||
});
|
||||
},
|
||||
setStickyModelSelection: (modelSelection) => {
|
||||
const normalizedModelSelection = normalizeModelSelection(modelSelection);
|
||||
set((state) =>
|
||||
Equal.equals(state.stickyModelSelection, normalizedModelSelection)
|
||||
? state
|
||||
: { stickyModelSelection: normalizedModelSelection },
|
||||
);
|
||||
},
|
||||
setPrompt: (threadId, prompt) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
@@ -1148,50 +1266,83 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setProvider: (threadId, provider) => {
|
||||
setModelSelection: (threadId, modelSelection) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const normalizedModelSelection = normalizeModelSelection(modelSelection);
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
if (!existing && normalizedModelSelection === null) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
if (Equal.equals(base.modelSelection, normalizedModelSelection)) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelSelection: normalizedModelSelection,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setProviderModelOptions: (threadId, provider, nextProviderOptions, options) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const normalizedProvider = normalizeProviderKind(provider);
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
if (!existing && normalizedProvider === null) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
if (base.provider === normalizedProvider) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
provider: normalizedProvider,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setModel: (threadId, model) => {
|
||||
if (threadId.length === 0) {
|
||||
if (normalizedProvider === null) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
const normalizedModel = normalizeModelSlug(model, existing?.provider ?? "codex") ?? null;
|
||||
if (!existing && normalizedModel === null) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
if (base.model === normalizedModel) {
|
||||
if (base.modelSelection?.provider !== normalizedProvider) {
|
||||
return state;
|
||||
}
|
||||
const nextProviderModelOptions = replaceProviderModelOptions(
|
||||
base.modelSelection?.options
|
||||
? { [normalizedProvider]: base.modelSelection.options }
|
||||
: null,
|
||||
normalizedProvider,
|
||||
nextProviderOptions,
|
||||
);
|
||||
const nextOptions =
|
||||
normalizedProvider === "codex"
|
||||
? nextProviderModelOptions?.codex
|
||||
: nextProviderModelOptions?.claudeAgent;
|
||||
const nextModelSelection =
|
||||
base.modelSelection === null
|
||||
? null
|
||||
: {
|
||||
provider: base.modelSelection.provider,
|
||||
model: base.modelSelection.model,
|
||||
...(nextOptions ? { options: nextOptions } : {}),
|
||||
};
|
||||
const nextStickyModelSelection =
|
||||
options?.persistSticky === true &&
|
||||
state.stickyModelSelection?.provider === normalizedProvider &&
|
||||
nextModelSelection !== null
|
||||
? nextModelSelection
|
||||
: state.stickyModelSelection;
|
||||
|
||||
if (
|
||||
Equal.equals(base.modelSelection, nextModelSelection) &&
|
||||
Equal.equals(state.stickyModelSelection, nextStickyModelSelection)
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
model: normalizedModel,
|
||||
modelSelection: nextModelSelection,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
@@ -1199,35 +1350,13 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setModelOptions: (threadId, modelOptions) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
const provider = existing?.provider ?? null;
|
||||
const nextModelOptions = normalizeProviderModelOptions(modelOptions, provider);
|
||||
if (!existing && nextModelOptions === null) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
if (JSON.stringify(base.modelOptions) === JSON.stringify(nextModelOptions)) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelOptions: nextModelOptions,
|
||||
|
||||
return {
|
||||
draftsByThreadId: nextDraftsByThreadId,
|
||||
...(options?.persistSticky === true
|
||||
? { stickyModelSelection: nextStickyModelSelection }
|
||||
: {}),
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setRuntimeMode: (threadId, runtimeMode) => {
|
||||
@@ -1534,32 +1663,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) => {
|
||||
@@ -1588,41 +1692,6 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
clearThreadDraft: (threadId) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const existing = get().draftsByThreadId[threadId];
|
||||
if (existing) {
|
||||
for (const image of existing.images) {
|
||||
revokeObjectPreviewUrl(image.previewUrl);
|
||||
}
|
||||
}
|
||||
set((state) => {
|
||||
const hasComposerDraft = state.draftsByThreadId[threadId] !== undefined;
|
||||
const hasDraftThread = state.draftThreadsByThreadId[threadId] !== undefined;
|
||||
const hasProjectMapping = Object.values(state.projectDraftThreadIdByProjectId).includes(
|
||||
threadId,
|
||||
);
|
||||
if (!hasComposerDraft && !hasDraftThread && !hasProjectMapping) {
|
||||
return state;
|
||||
}
|
||||
const { [threadId]: _removedComposerDraft, ...restComposerDraftsByThreadId } =
|
||||
state.draftsByThreadId;
|
||||
const { [threadId]: _removedDraftThread, ...restDraftThreadsByThreadId } =
|
||||
state.draftThreadsByThreadId;
|
||||
const nextProjectDraftThreadIdByProjectId = Object.fromEntries(
|
||||
Object.entries(state.projectDraftThreadIdByProjectId).filter(
|
||||
([, draftThreadId]) => draftThreadId !== threadId,
|
||||
),
|
||||
) as Record<ProjectId, ThreadId>;
|
||||
return {
|
||||
draftsByThreadId: restComposerDraftsByThreadId,
|
||||
draftThreadsByThreadId: restDraftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: nextProjectDraftThreadIdByProjectId,
|
||||
};
|
||||
});
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: COMPOSER_DRAFT_STORAGE_KEY,
|
||||
@@ -1644,6 +1713,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: normalizedPersisted.draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: normalizedPersisted.projectDraftThreadIdByProjectId,
|
||||
stickyModelSelection: normalizedPersisted.stickyModelSelection as ModelSelection | null,
|
||||
};
|
||||
},
|
||||
},
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useStore } from "../store";
|
||||
export function useHandleNewThread() {
|
||||
const projects = useStore((store) => store.projects);
|
||||
const threads = useStore((store) => store.threads);
|
||||
const stickyModelSelection = useComposerDraftStore((store) => store.stickyModelSelection);
|
||||
const navigate = useNavigate();
|
||||
const routeThreadId = useParams({
|
||||
strict: false,
|
||||
@@ -38,6 +39,7 @@ export function useHandleNewThread() {
|
||||
clearProjectDraftThreadId,
|
||||
getDraftThread,
|
||||
getDraftThreadByProjectId,
|
||||
setModelSelection,
|
||||
setDraftThreadContext,
|
||||
setProjectDraftThreadId,
|
||||
} = useComposerDraftStore.getState();
|
||||
@@ -96,6 +98,9 @@ export function useHandleNewThread() {
|
||||
envMode: options?.envMode ?? "local",
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
});
|
||||
if (stickyModelSelection) {
|
||||
setModelSelection(threadId, stickyModelSelection);
|
||||
}
|
||||
|
||||
await navigate({
|
||||
to: "/$threadId",
|
||||
@@ -103,7 +108,7 @@ export function useHandleNewThread() {
|
||||
});
|
||||
})();
|
||||
},
|
||||
[navigate, routeThreadId],
|
||||
[navigate, routeThreadId, stickyModelSelection],
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -117,11 +117,13 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.runStackedAction(input.cwd),
|
||||
mutationFn: async ({
|
||||
actionId,
|
||||
action,
|
||||
commitMessage,
|
||||
featureBranch,
|
||||
filePaths,
|
||||
}: {
|
||||
actionId: string;
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
featureBranch?: boolean;
|
||||
@@ -130,6 +132,7 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Git action is unavailable.");
|
||||
return api.git.runStackedAction({
|
||||
actionId,
|
||||
cwd: input.cwd,
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { isTerminalFocused } from "./terminalFocus";
|
||||
|
||||
class MockHTMLElement {
|
||||
isConnected = false;
|
||||
className = "";
|
||||
|
||||
readonly classList = {
|
||||
contains: (value: string) => this.className.split(/\s+/).includes(value),
|
||||
};
|
||||
|
||||
closest(selector: string): MockHTMLElement | null {
|
||||
return selector === ".thread-terminal-drawer .xterm" && this.isConnected ? this : null;
|
||||
}
|
||||
}
|
||||
|
||||
const originalDocument = globalThis.document;
|
||||
const originalHTMLElement = globalThis.HTMLElement;
|
||||
|
||||
afterEach(() => {
|
||||
if (originalDocument === undefined) {
|
||||
delete (globalThis as { document?: Document }).document;
|
||||
} else {
|
||||
globalThis.document = originalDocument;
|
||||
}
|
||||
|
||||
if (originalHTMLElement === undefined) {
|
||||
delete (globalThis as { HTMLElement?: typeof HTMLElement }).HTMLElement;
|
||||
} else {
|
||||
globalThis.HTMLElement = originalHTMLElement;
|
||||
}
|
||||
});
|
||||
|
||||
describe("isTerminalFocused", () => {
|
||||
it("returns false for detached xterm helper textareas", () => {
|
||||
const detached = new MockHTMLElement();
|
||||
detached.className = "xterm-helper-textarea";
|
||||
|
||||
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
|
||||
globalThis.document = { activeElement: detached } as Document;
|
||||
|
||||
expect(isTerminalFocused()).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true for connected xterm helper textareas", () => {
|
||||
const attached = new MockHTMLElement();
|
||||
attached.className = "xterm-helper-textarea";
|
||||
attached.isConnected = true;
|
||||
|
||||
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
|
||||
globalThis.document = { activeElement: attached } as Document;
|
||||
|
||||
expect(isTerminalFocused()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
export function isTerminalFocused(): boolean {
|
||||
const activeElement = document.activeElement;
|
||||
if (!(activeElement instanceof HTMLElement)) return false;
|
||||
if (!activeElement.isConnected) return false;
|
||||
if (activeElement.classList.contains("xterm-helper-textarea")) return true;
|
||||
return activeElement.closest(".thread-terminal-drawer .xterm") !== null;
|
||||
}
|
||||
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user