Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
14070d6c45 | ||
|
|
8cad01a57b | ||
|
|
340634eeee | ||
|
|
fa0a1c1567 | ||
|
|
01358d1006 | ||
|
|
529315b4c8 | ||
|
|
0a503d0cde | ||
|
|
d4a7e1ac0b | ||
|
|
be1abc88fd | ||
|
|
384f35084e | ||
|
|
1371ce2cce | ||
|
|
d6408a2949 | ||
|
|
e823f8f14e | ||
|
|
2b08d86696 |
No files matched your search
@@ -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})`,
|
||||
);
|
||||
+2
-1
@@ -18,4 +18,5 @@ apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
__screenshots__/
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
@@ -115,7 +115,10 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModel,
|
||||
defaultModelSelection: {
|
||||
provider,
|
||||
model: defaultModel,
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -125,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,
|
||||
@@ -151,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(),
|
||||
@@ -254,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,
|
||||
});
|
||||
|
||||
@@ -264,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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -8,7 +8,12 @@ import {
|
||||
Layer,
|
||||
Option,
|
||||
Path,
|
||||
PlatformError,
|
||||
Ref,
|
||||
Result,
|
||||
Schema,
|
||||
Scope,
|
||||
Semaphore,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
@@ -16,11 +21,14 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import {
|
||||
GitCore,
|
||||
type ExecuteGitProgress,
|
||||
type GitCommitOptions,
|
||||
type GitCoreShape,
|
||||
type ExecuteGitInput,
|
||||
type ExecuteGitResult,
|
||||
} from "../Services/GitCore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
@@ -29,6 +37,11 @@ const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
|
||||
|
||||
type TraceTailState = {
|
||||
processedChars: number;
|
||||
remainder: string;
|
||||
};
|
||||
|
||||
class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
cwd: string;
|
||||
upstreamRef: string;
|
||||
@@ -40,6 +53,7 @@ interface ExecuteGitOptions {
|
||||
timeoutMs?: number | undefined;
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
fallbackErrorMessage?: string | undefined;
|
||||
progress?: ExecuteGitProgress | undefined;
|
||||
}
|
||||
|
||||
function parseBranchAb(value: string): { ahead: number; behind: number } {
|
||||
@@ -257,14 +271,201 @@ function toGitCommandError(
|
||||
});
|
||||
}
|
||||
|
||||
interface Trace2Monitor {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly flush: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
function trace2ChildKey(record: Record<string, unknown>): string | null {
|
||||
const childId = record.child_id;
|
||||
if (typeof childId === "number" || typeof childId === "string") {
|
||||
return String(childId);
|
||||
}
|
||||
const hookName = record.hook_name;
|
||||
return typeof hookName === "string" && hookName.trim().length > 0 ? hookName.trim() : null;
|
||||
}
|
||||
|
||||
const Trace2Record = Schema.Record(Schema.String, Schema.Unknown);
|
||||
|
||||
const createTrace2Monitor = Effect.fn(function* (
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
progress: ExecuteGitProgress | undefined,
|
||||
): Effect.fn.Return<
|
||||
Trace2Monitor,
|
||||
PlatformError.PlatformError,
|
||||
Scope.Scope | FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
if (!progress?.onHookStarted && !progress?.onHookFinished) {
|
||||
return {
|
||||
env: {},
|
||||
flush: Effect.void,
|
||||
};
|
||||
}
|
||||
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const traceFilePath = yield* fs.makeTempFileScoped({
|
||||
prefix: `t3code-git-trace2-${process.pid}-`,
|
||||
suffix: ".json",
|
||||
});
|
||||
const hookStartByChildKey = new Map<string, { hookName: string; startedAtMs: number }>();
|
||||
const traceTailState = yield* Ref.make<TraceTailState>({
|
||||
processedChars: 0,
|
||||
remainder: "",
|
||||
});
|
||||
|
||||
const handleTraceLine = (line: string) =>
|
||||
Effect.gen(function* () {
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const traceRecord = decodeJsonResult(Trace2Record)(trimmedLine);
|
||||
if (Result.isFailure(traceRecord)) {
|
||||
yield* Effect.logDebug(
|
||||
`GitCore.trace2: failed to parse trace line for ${quoteGitCommand(input.args)} in ${input.cwd}`,
|
||||
traceRecord.failure,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (traceRecord.success.child_class !== "hook") {
|
||||
return;
|
||||
}
|
||||
|
||||
const event = traceRecord.success.event;
|
||||
const childKey = trace2ChildKey(traceRecord.success);
|
||||
if (childKey === null) {
|
||||
return;
|
||||
}
|
||||
const started = hookStartByChildKey.get(childKey);
|
||||
const hookNameFromEvent =
|
||||
typeof traceRecord.success.hook_name === "string"
|
||||
? traceRecord.success.hook_name.trim()
|
||||
: "";
|
||||
const hookName = hookNameFromEvent.length > 0 ? hookNameFromEvent : (started?.hookName ?? "");
|
||||
if (hookName.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event === "child_start") {
|
||||
hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() });
|
||||
if (progress.onHookStarted) {
|
||||
yield* progress.onHookStarted(hookName);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event === "child_exit") {
|
||||
hookStartByChildKey.delete(childKey);
|
||||
if (progress.onHookFinished) {
|
||||
const code = traceRecord.success.code;
|
||||
yield* progress.onHookFinished({
|
||||
hookName: started?.hookName ?? hookName,
|
||||
exitCode: typeof code === "number" && Number.isInteger(code) ? code : null,
|
||||
durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const deltaMutex = yield* Semaphore.make(1);
|
||||
const readTraceDelta = deltaMutex.withPermit(
|
||||
fs.readFileString(traceFilePath).pipe(
|
||||
Effect.flatMap((contents) =>
|
||||
Effect.uninterruptible(
|
||||
Ref.modify(traceTailState, ({ processedChars, remainder }) => {
|
||||
if (contents.length <= processedChars) {
|
||||
return [[], { processedChars, remainder }];
|
||||
}
|
||||
|
||||
const appended = contents.slice(processedChars);
|
||||
const combined = remainder + appended;
|
||||
const lines = combined.split("\n");
|
||||
const nextRemainder = lines.pop() ?? "";
|
||||
|
||||
return [
|
||||
lines.map((line) => line.replace(/\r$/, "")),
|
||||
{
|
||||
processedChars: contents.length,
|
||||
remainder: nextRemainder,
|
||||
},
|
||||
];
|
||||
}).pipe(
|
||||
Effect.flatMap((lines) => Effect.forEach(lines, handleTraceLine, { discard: true })),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.ignore({ log: true }),
|
||||
),
|
||||
);
|
||||
const traceFileName = path.basename(traceFilePath);
|
||||
yield* Stream.runForEach(fs.watch(traceFilePath), (event) => {
|
||||
const eventPath = event.path;
|
||||
const isTargetTraceEvent =
|
||||
eventPath === traceFilePath ||
|
||||
eventPath === traceFileName ||
|
||||
path.basename(eventPath) === traceFileName;
|
||||
if (!isTargetTraceEvent) return Effect.void;
|
||||
return readTraceDelta;
|
||||
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.gen(function* () {
|
||||
yield* readTraceDelta;
|
||||
const finalLine = yield* Ref.modify(traceTailState, ({ processedChars, remainder }) => [
|
||||
remainder.trim(),
|
||||
{
|
||||
processedChars,
|
||||
remainder: "",
|
||||
},
|
||||
]);
|
||||
if (finalLine.length > 0) {
|
||||
yield* handleTraceLine(finalLine);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
env: {
|
||||
GIT_TRACE2_EVENT: traceFilePath,
|
||||
},
|
||||
flush: readTraceDelta,
|
||||
};
|
||||
});
|
||||
|
||||
const collectOutput = Effect.fn(function* <E>(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
maxOutputBytes: number,
|
||||
onLine: ((line: string) => Effect.Effect<void, never>) | undefined,
|
||||
): Effect.fn.Return<string, GitCommandError> {
|
||||
const decoder = new TextDecoder();
|
||||
let bytes = 0;
|
||||
let text = "";
|
||||
let lineBuffer = "";
|
||||
|
||||
const emitCompleteLines = (flush: boolean) =>
|
||||
Effect.gen(function* () {
|
||||
let newlineIndex = lineBuffer.indexOf("\n");
|
||||
while (newlineIndex >= 0) {
|
||||
const line = lineBuffer.slice(0, newlineIndex).replace(/\r$/, "");
|
||||
lineBuffer = lineBuffer.slice(newlineIndex + 1);
|
||||
if (line.length > 0 && onLine) {
|
||||
yield* onLine(line);
|
||||
}
|
||||
newlineIndex = lineBuffer.indexOf("\n");
|
||||
}
|
||||
|
||||
if (flush) {
|
||||
const trailing = lineBuffer.replace(/\r$/, "");
|
||||
lineBuffer = "";
|
||||
if (trailing.length > 0 && onLine) {
|
||||
yield* onLine(trailing);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(stream, (chunk) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -277,11 +478,17 @@ const collectOutput = Effect.fn(function* <E>(
|
||||
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
|
||||
});
|
||||
}
|
||||
text += decoder.decode(chunk, { stream: true });
|
||||
const decoded = decoder.decode(chunk, { stream: true });
|
||||
text += decoded;
|
||||
lineBuffer += decoded;
|
||||
yield* emitCompleteLines(false);
|
||||
}),
|
||||
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
|
||||
|
||||
text += decoder.decode();
|
||||
const remainder = decoder.decode();
|
||||
text += remainder;
|
||||
lineBuffer += remainder;
|
||||
yield* emitCompleteLines(true);
|
||||
return text;
|
||||
});
|
||||
|
||||
@@ -306,19 +513,38 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
|
||||
const commandEffect = Effect.gen(function* () {
|
||||
const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to create trace2 monitor.")),
|
||||
);
|
||||
const child = yield* commandSpawner
|
||||
.spawn(
|
||||
ChildProcess.make("git", commandInput.args, {
|
||||
cwd: commandInput.cwd,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
env: {
|
||||
...process.env,
|
||||
...input.env,
|
||||
...trace2Monitor.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),
|
||||
collectOutput(
|
||||
commandInput,
|
||||
child.stdout,
|
||||
maxOutputBytes,
|
||||
input.progress?.onStdoutLine,
|
||||
),
|
||||
collectOutput(
|
||||
commandInput,
|
||||
child.stderr,
|
||||
maxOutputBytes,
|
||||
input.progress?.onStderrLine,
|
||||
),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
|
||||
@@ -326,6 +552,7 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
yield* trace2Monitor.flush;
|
||||
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = stderr.trim();
|
||||
@@ -376,6 +603,7 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"
|
||||
args,
|
||||
allowNonZeroExit: true,
|
||||
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
||||
...(options.progress ? { progress: options.progress } : {}),
|
||||
}).pipe(
|
||||
Effect.flatMap((result) => {
|
||||
if (options.allowNonZeroExit || result.code === 0) {
|
||||
@@ -947,14 +1175,37 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"
|
||||
};
|
||||
});
|
||||
|
||||
const commit: GitCoreShape["commit"] = (cwd, subject, body) =>
|
||||
const commit: GitCoreShape["commit"] = (cwd, subject, body, options?: GitCommitOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const args = ["commit", "-m", subject];
|
||||
const trimmedBody = body.trim();
|
||||
if (trimmedBody.length > 0) {
|
||||
args.push("-m", trimmedBody);
|
||||
}
|
||||
yield* runGit("GitCore.commit.commit", cwd, args);
|
||||
const progress = options?.progress
|
||||
? {
|
||||
...(options.progress.onOutputLine
|
||||
? {
|
||||
onStdoutLine: (line: string) =>
|
||||
options.progress?.onOutputLine?.({ stream: "stdout", text: line }) ??
|
||||
Effect.void,
|
||||
onStderrLine: (line: string) =>
|
||||
options.progress?.onOutputLine?.({ stream: "stderr", text: line }) ??
|
||||
Effect.void,
|
||||
}
|
||||
: {}),
|
||||
...(options.progress.onHookStarted
|
||||
? { onHookStarted: options.progress.onHookStarted }
|
||||
: {}),
|
||||
...(options.progress.onHookFinished
|
||||
? { onHookFinished: options.progress.onHookFinished }
|
||||
: {}),
|
||||
}
|
||||
: null;
|
||||
yield* executeGit("GitCore.commit.commit", cwd, args, {
|
||||
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
||||
...(progress ? { progress } : {}),
|
||||
}).pipe(Effect.asVoid);
|
||||
const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [
|
||||
"rev-parse",
|
||||
"HEAD",
|
||||
|
||||
@@ -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";
|
||||
@@ -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 }) {
|
||||
@@ -1941,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,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ export interface ExecuteGitInput {
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly progress?: ExecuteGitProgress;
|
||||
}
|
||||
|
||||
export interface ExecuteGitResult {
|
||||
@@ -49,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;
|
||||
@@ -132,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>;
|
||||
}
|
||||
|
||||
|
||||
@@ -282,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,
|
||||
}),
|
||||
);
|
||||
@@ -293,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,
|
||||
|
||||
@@ -72,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,
|
||||
}),
|
||||
);
|
||||
@@ -83,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,
|
||||
@@ -126,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,
|
||||
}),
|
||||
);
|
||||
@@ -137,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,
|
||||
@@ -178,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,
|
||||
}),
|
||||
);
|
||||
@@ -199,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,
|
||||
@@ -233,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,
|
||||
}),
|
||||
);
|
||||
@@ -244,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,
|
||||
@@ -344,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,
|
||||
}),
|
||||
);
|
||||
@@ -357,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,
|
||||
@@ -374,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,
|
||||
@@ -428,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,
|
||||
}),
|
||||
);
|
||||
@@ -439,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,
|
||||
@@ -563,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,
|
||||
}),
|
||||
);
|
||||
@@ -574,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,
|
||||
@@ -642,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,
|
||||
}),
|
||||
);
|
||||
@@ -654,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,
|
||||
@@ -671,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,
|
||||
|
||||
@@ -68,7 +68,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -89,7 +89,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -337,7 +340,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-clear-attachments"),
|
||||
title: "Project Clear Attachments",
|
||||
workspaceRoot: "/tmp/project-clear-attachments",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -358,7 +361,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-clear-attachments"),
|
||||
projectId: ProjectId.makeUnsafe("project-clear-attachments"),
|
||||
title: "Thread Clear Attachments",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -462,7 +468,7 @@ it.layer(
|
||||
projectId: ProjectId.makeUnsafe("project-overwrite"),
|
||||
title: "Project Overwrite",
|
||||
workspaceRoot: "/tmp/project-overwrite",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -483,7 +489,10 @@ it.layer(
|
||||
threadId: ThreadId.makeUnsafe("thread-overwrite"),
|
||||
projectId: ProjectId.makeUnsafe("project-overwrite"),
|
||||
title: "Thread Overwrite",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -607,7 +616,7 @@ it.layer(
|
||||
projectId: ProjectId.makeUnsafe("project-rollback"),
|
||||
title: "Project Rollback",
|
||||
workspaceRoot: "/tmp/project-rollback",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -628,7 +637,10 @@ it.layer(
|
||||
threadId: ThreadId.makeUnsafe("thread-rollback"),
|
||||
projectId: ProjectId.makeUnsafe("project-rollback"),
|
||||
title: "Thread Rollback",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -733,7 +745,7 @@ it.layer(
|
||||
projectId: ProjectId.makeUnsafe("project-revert-files"),
|
||||
title: "Project Revert Files",
|
||||
workspaceRoot: "/tmp/project-revert-files",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -754,7 +766,10 @@ it.layer(
|
||||
threadId,
|
||||
projectId: ProjectId.makeUnsafe("project-revert-files"),
|
||||
title: "Thread Revert Files",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -938,7 +953,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
|
||||
projectId: ProjectId.makeUnsafe("project-delete-files"),
|
||||
title: "Project Delete Files",
|
||||
workspaceRoot: "/tmp/project-delete-files",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -959,7 +974,10 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
|
||||
threadId,
|
||||
projectId: ProjectId.makeUnsafe("project-delete-files"),
|
||||
title: "Thread Delete Files",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1098,7 +1116,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Project A",
|
||||
workspaceRoot: "/tmp/project-a",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -1119,7 +1137,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-a"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Thread A",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1222,7 +1243,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-empty"),
|
||||
title: "Project Empty",
|
||||
workspaceRoot: "/tmp/project-empty",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -1243,7 +1264,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-empty"),
|
||||
projectId: ProjectId.makeUnsafe("project-empty"),
|
||||
title: "Thread Empty",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1359,7 +1383,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-conflict"),
|
||||
title: "Project Conflict",
|
||||
workspaceRoot: "/tmp/project-conflict",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T13:00:00.000Z",
|
||||
updatedAt: "2026-02-26T13:00:00.000Z",
|
||||
@@ -1380,7 +1404,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-conflict"),
|
||||
projectId: ProjectId.makeUnsafe("project-conflict"),
|
||||
title: "Thread Conflict",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1500,7 +1527,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-revert"),
|
||||
title: "Project Revert",
|
||||
workspaceRoot: "/tmp/project-revert",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T12:00:00.000Z",
|
||||
updatedAt: "2026-02-26T12:00:00.000Z",
|
||||
@@ -1521,7 +1548,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-revert"),
|
||||
projectId: ProjectId.makeUnsafe("project-revert"),
|
||||
title: "Thread Revert",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1837,7 +1867,10 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-live"),
|
||||
title: "Live Project",
|
||||
workspaceRoot: "/tmp/project-live",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -1872,7 +1905,10 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-scripts"),
|
||||
title: "Scripts Project",
|
||||
workspaceRoot: "/tmp/project-scripts",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -1889,7 +1925,10 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
defaultModel: "gpt-5",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
},
|
||||
});
|
||||
|
||||
const projectRows = yield* sql<{
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -63,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,
|
||||
@@ -101,6 +104,7 @@ describe("ProviderCommandReactor", () => {
|
||||
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> = [];
|
||||
@@ -242,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,
|
||||
}),
|
||||
);
|
||||
@@ -253,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,
|
||||
@@ -328,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,
|
||||
},
|
||||
@@ -380,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",
|
||||
},
|
||||
},
|
||||
@@ -430,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,
|
||||
},
|
||||
},
|
||||
@@ -518,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,
|
||||
@@ -552,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",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -660,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",
|
||||
},
|
||||
},
|
||||
@@ -687,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",
|
||||
},
|
||||
},
|
||||
@@ -835,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,
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -1153,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* () {
|
||||
|
||||
@@ -2258,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,
|
||||
);
|
||||
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -32,6 +32,7 @@ export interface TerminalSessionState {
|
||||
status: TerminalSessionStatus;
|
||||
pid: number | null;
|
||||
history: string;
|
||||
pendingHistoryControlSequence: string;
|
||||
exitCode: number | null;
|
||||
exitSignal: number | null;
|
||||
updatedAt: string;
|
||||
|
||||
@@ -703,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;
|
||||
}>;
|
||||
@@ -725,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",
|
||||
},
|
||||
}),
|
||||
]),
|
||||
);
|
||||
@@ -735,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,
|
||||
}),
|
||||
@@ -1192,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();
|
||||
@@ -1202,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,
|
||||
@@ -1270,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();
|
||||
@@ -1280,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,
|
||||
@@ -1811,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 () => {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
getCustomModelsByProvider,
|
||||
getCustomModelsForProvider,
|
||||
getDefaultCustomModelsForProvider,
|
||||
getProviderStartOptions,
|
||||
MODEL_PROVIDER_SETTINGS,
|
||||
normalizeCustomModelSlugs,
|
||||
patchCustomModels,
|
||||
@@ -118,6 +119,35 @@ 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"],
|
||||
@@ -209,6 +239,7 @@ describe("AppSettingsSchema", () => {
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
claudeBinaryPath: "",
|
||||
codexBinaryPath: "/usr/local/bin/codex",
|
||||
codexHomePath: "",
|
||||
defaultThreadEnvMode: "local",
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { useCallback } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { TrimmedNonEmptyString, type ProviderKind } from "@t3tools/contracts";
|
||||
import {
|
||||
TrimmedNonEmptyString,
|
||||
type ProviderKind,
|
||||
type ProviderStartOptions,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getDefaultModel,
|
||||
getModelOptions,
|
||||
@@ -47,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(() => [])),
|
||||
@@ -221,6 +227,30 @@ export function getCustomModelOptionsByProvider(
|
||||
};
|
||||
}
|
||||
|
||||
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 Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
|
||||
}
|
||||
|
||||
export function useAppSettings() {
|
||||
const [settings, setSettings] = useLocalStorage(
|
||||
APP_SETTINGS_STORAGE_KEY,
|
||||
|
||||
@@ -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,8 +826,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModel: null,
|
||||
stickyModelOptions: {},
|
||||
stickyModelSelection: null,
|
||||
});
|
||||
useStore.setState({
|
||||
projects: [],
|
||||
@@ -980,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,
|
||||
@@ -1045,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(
|
||||
@@ -1075,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(
|
||||
() => {
|
||||
@@ -1283,9 +1491,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
it("snapshots sticky codex settings into a new draft thread", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModel: "gpt-5.3-codex",
|
||||
stickyModelOptions: {
|
||||
codex: {
|
||||
stickyModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -1314,10 +1523,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const newThreadId = newThreadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
|
||||
model: "gpt-5.3-codex",
|
||||
provider: "codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
@@ -1329,9 +1538,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
it("hydrates the provider alongside a sticky claude model", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModel: "claude-opus-4-6",
|
||||
stickyModelOptions: {
|
||||
claudeAgent: {
|
||||
stickyModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -1360,10 +1570,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const newThreadId = newThreadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -1405,9 +1615,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
it("prefers draft state over sticky composer settings and defaults", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModel: "gpt-5.3-codex",
|
||||
stickyModelOptions: {
|
||||
codex: {
|
||||
stickyModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -1436,17 +1647,19 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const threadId = threadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
useComposerDraftStore.getState().setModel(threadId, "gpt-5.4");
|
||||
useComposerDraftStore.getState().setModelOptions(threadId, {
|
||||
codex: {
|
||||
useComposerDraftStore.getState().setModelSelection(threadId, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -1460,9 +1673,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
"New-thread should reuse the existing project draft thread.",
|
||||
);
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
|
||||
model: "gpt-5.4",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -1505,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.",
|
||||
@@ -1526,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,
|
||||
@@ -1561,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(
|
||||
@@ -1574,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,4 +1,4 @@
|
||||
import { ProjectId, 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 { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
@@ -17,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 {
|
||||
@@ -25,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,
|
||||
|
||||
@@ -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,
|
||||
@@ -112,6 +114,7 @@ import { type NewProjectScriptInput } from "./ProjectScriptsControl";
|
||||
import {
|
||||
commandForProjectScript,
|
||||
nextProjectScriptId,
|
||||
projectScriptCwd,
|
||||
projectScriptRuntimeEnv,
|
||||
projectScriptIdFromCommand,
|
||||
setupProjectScript,
|
||||
@@ -122,6 +125,7 @@ import { readNativeApi } from "~/nativeApi";
|
||||
import {
|
||||
getCustomModelOptionsByProvider,
|
||||
getCustomModelsByProvider,
|
||||
getProviderStartOptions,
|
||||
resolveAppModelSelection,
|
||||
useAppSettings,
|
||||
} from "../appSettings";
|
||||
@@ -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,7 +265,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const setStoreThreadError = useStore((store) => store.setError);
|
||||
const setStoreThreadBranch = useStore((store) => store.setThreadBranch);
|
||||
const { settings } = useAppSettings();
|
||||
const setStickyComposerModel = useComposerDraftStore((store) => store.setStickyModel);
|
||||
const setStickyComposerModelSelection = useComposerDraftStore(
|
||||
(store) => store.setStickyModelSelection,
|
||||
);
|
||||
const timestampFormat = settings.timestampFormat;
|
||||
const navigate = useNavigate();
|
||||
const rawSearch = useSearch({
|
||||
@@ -269,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,
|
||||
@@ -463,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 =
|
||||
@@ -582,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 ||
|
||||
@@ -590,22 +617,30 @@ 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(() => getCustomModelsByProvider(settings), [settings]);
|
||||
const selectedModel = useMemo(() => {
|
||||
const draftModel = composerDraft.model;
|
||||
const draftModel = composerDraft.modelSelection?.model;
|
||||
if (!draftModel) {
|
||||
return baseThreadModel;
|
||||
}
|
||||
return resolveAppModelSelection(selectedProvider, customModelsByProvider, draftModel);
|
||||
}, [baseThreadModel, composerDraft.model, customModelsByProvider, selectedProvider]);
|
||||
const draftModelOptions = composerDraft.modelOptions;
|
||||
}, [
|
||||
baseThreadModel,
|
||||
composerDraft.modelSelection?.model,
|
||||
customModelsByProvider,
|
||||
selectedProvider,
|
||||
]);
|
||||
const draftModelOptions = toProviderModelOptions(composerDraft.modelSelection);
|
||||
const composerProviderState = useMemo(
|
||||
() =>
|
||||
getComposerProviderState({
|
||||
@@ -618,17 +653,22 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
const selectedPromptEffort = composerProviderState.promptEffort;
|
||||
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
|
||||
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]);
|
||||
const selectedModelSelection = useMemo<ModelSelection>(
|
||||
() => ({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
...(extractModelSelectionOptions(selectedProvider, selectedModelOptionsForDispatch)
|
||||
? {
|
||||
options: extractModelSelectionOptions(
|
||||
selectedProvider,
|
||||
selectedModelOptionsForDispatch,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
[selectedModel, selectedModelOptionsForDispatch, selectedProvider],
|
||||
);
|
||||
const providerOptionsForDispatch = useMemo(() => getProviderStartOptions(settings), [settings]);
|
||||
const selectedModelForPicker = selectedModel;
|
||||
const modelOptionsByProvider = useMemo(
|
||||
() => getCustomModelOptionsByProvider(settings),
|
||||
@@ -1003,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";
|
||||
@@ -1122,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],
|
||||
@@ -1312,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;
|
||||
@@ -1386,7 +1433,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeThread,
|
||||
activeThreadId,
|
||||
gitCwd,
|
||||
isServerThread,
|
||||
setTerminalOpen,
|
||||
setThreadError,
|
||||
storeNewTerminal,
|
||||
@@ -1590,7 +1636,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
async (input: {
|
||||
threadId: ThreadId;
|
||||
createdAt: string;
|
||||
model?: string;
|
||||
modelSelection?: ModelSelection;
|
||||
runtimeMode: RuntimeMode;
|
||||
interactionMode: ProviderInteractionMode;
|
||||
}) => {
|
||||
@@ -1602,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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2538,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({
|
||||
@@ -2548,7 +2606,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
threadId: threadIdForSend,
|
||||
projectId: activeProject.id,
|
||||
title,
|
||||
model: threadCreateModel,
|
||||
modelSelection: threadCreateModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
branch: nextThreadBranch,
|
||||
@@ -2575,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;
|
||||
@@ -2598,7 +2655,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
await persistThreadSettingsForNextTurn({
|
||||
threadId: threadIdForSend,
|
||||
createdAt: messageCreatedAt,
|
||||
...(selectedModel ? { model: selectedModel } : {}),
|
||||
...(selectedModel ? { modelSelection: selectedModelSelection } : {}),
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
});
|
||||
@@ -2616,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,
|
||||
@@ -2882,7 +2935,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
await persistThreadSettingsForNextTurn({
|
||||
threadId: threadIdForSend,
|
||||
createdAt: messageCreatedAt,
|
||||
...(selectedModel ? { model: selectedModel } : {}),
|
||||
modelSelection: selectedModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode: nextInteractionMode,
|
||||
});
|
||||
@@ -2901,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,
|
||||
@@ -2952,8 +3001,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedPromptEffort,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
selectedModelSelection,
|
||||
providerOptionsForDispatch,
|
||||
selectedProvider,
|
||||
setComposerDraftInteractionMode,
|
||||
@@ -2987,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");
|
||||
@@ -3007,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,
|
||||
@@ -3025,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,
|
||||
@@ -3081,8 +3121,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedPromptEffort,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
selectedModelSelection,
|
||||
providerOptionsForDispatch,
|
||||
selectedProvider,
|
||||
settings.enableAssistantStreaming,
|
||||
@@ -3097,18 +3136,26 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return;
|
||||
}
|
||||
const resolvedModel = resolveAppModelSelection(provider, customModelsByProvider, model);
|
||||
setComposerDraftProvider(activeThread.id, provider);
|
||||
setComposerDraftModel(activeThread.id, resolvedModel);
|
||||
setStickyComposerModel(resolvedModel);
|
||||
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,
|
||||
composerDraft.modelSelection,
|
||||
lockedProvider,
|
||||
scheduleComposerFocus,
|
||||
setComposerDraftModel,
|
||||
setComposerDraftProvider,
|
||||
setStickyComposerModel,
|
||||
setComposerDraftModelSelection,
|
||||
setStickyComposerModelSelection,
|
||||
customModelsByProvider,
|
||||
],
|
||||
);
|
||||
@@ -3474,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}
|
||||
@@ -3490,6 +3540,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
onAddProjectScript={saveProjectScript}
|
||||
onUpdateProjectScript={updateProjectScript}
|
||||
onDeleteProjectScript={deleteProjectScript}
|
||||
onToggleTerminal={toggleTerminalVisibility}
|
||||
onToggleDiff={onToggleDiff}
|
||||
/>
|
||||
</header>
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -258,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,
|
||||
);
|
||||
@@ -434,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, {
|
||||
|
||||
@@ -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 } : {}),
|
||||
@@ -185,8 +185,9 @@ describe("ClaudeTraitsPicker", () => {
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitemradio", { name: "Max" }).click();
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toMatchObject({
|
||||
claudeAgent: {
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -93,7 +93,8 @@ export const ClaudeTraitsMenuContent = memo(function ClaudeTraitsMenuContentImpl
|
||||
}: ClaudeTraitsMenuContentProps) {
|
||||
const draft = useComposerThreadDraft(threadId);
|
||||
const prompt = draft.prompt;
|
||||
const modelOptions = draft.modelOptions?.[PROVIDER];
|
||||
const modelOptions =
|
||||
draft.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
|
||||
const {
|
||||
effort,
|
||||
@@ -225,7 +226,8 @@ export const ClaudeTraitsPicker = memo(function ClaudeTraitsPicker({
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const draft = useComposerThreadDraft(threadId);
|
||||
const prompt = draft.prompt;
|
||||
const modelOptions = draft.modelOptions?.[PROVIDER];
|
||||
const modelOptions =
|
||||
draft.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
const { effort, thinkingEnabled, fastModeEnabled, ultrathinkPromptControlled, supportsFastMode } =
|
||||
getSelectedClaudeTraits(model, prompt, modelOptions);
|
||||
const triggerLabel = [
|
||||
|
||||
@@ -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 } : {}),
|
||||
},
|
||||
@@ -125,8 +125,9 @@ describe("CodexTraitsPicker", () => {
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitemradio", { name: "on" }).click();
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toMatchObject({
|
||||
codex: {
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toMatchObject({
|
||||
provider: "codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
@@ -145,6 +146,7 @@ describe("CodexTraitsPicker", () => {
|
||||
[threadId]: {
|
||||
prompt: "",
|
||||
attachments: [],
|
||||
modelSelection: null,
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "xhigh",
|
||||
@@ -173,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();
|
||||
|
||||
@@ -48,7 +48,8 @@ function getSelectedCodexTraits(modelOptions: CodexModelOptions | null | undefin
|
||||
|
||||
function CodexTraitsMenuContentImpl(props: { threadId: ThreadId }) {
|
||||
const draft = useComposerThreadDraft(props.threadId);
|
||||
const modelOptions = draft.modelOptions?.[PROVIDER];
|
||||
const modelOptions =
|
||||
draft.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
|
||||
const options = getReasoningEffortOptions(PROVIDER);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER);
|
||||
@@ -112,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,
|
||||
};
|
||||
|
||||
@@ -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 {
|
||||
@@ -67,11 +67,22 @@ function resetComposerDraftStore() {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModel: null,
|
||||
stickyModelOptions: {},
|
||||
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;
|
||||
@@ -517,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", () => {
|
||||
@@ -593,62 +606,56 @@ describe("composerDraftStore project draft thread mapping", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore modelOptions", () => {
|
||||
describe("composerDraftStore modelSelection", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-model-options");
|
||||
|
||||
beforeEach(() => {
|
||||
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: {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("drops default-only model options from the draft", () => {
|
||||
it("keeps default-only model selections on the draft", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: true,
|
||||
},
|
||||
});
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.4"));
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.4"),
|
||||
);
|
||||
});
|
||||
|
||||
it("replaces only the targeted provider model options", () => {
|
||||
it("replaces only the targeted provider options on the current model selection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
claudeAgent: {
|
||||
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,
|
||||
@@ -659,114 +666,88 @@ describe("composerDraftStore modelOptions", () => {
|
||||
{ persistSticky: true },
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
claudeAgent: {
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
claudeAgent: {
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("removes only the targeted provider entry when next options normalize empty", () => {
|
||||
it("removes selection options when the patched provider options normalize empty", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
claudeAgent: {
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
store.setProviderModelOptions(threadId, "claudeAgent", {
|
||||
thinking: true,
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
});
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({});
|
||||
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.setModelOptions(threadId, {
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.4", { fastMode: true }));
|
||||
|
||||
store.setProviderModelOptions(threadId, "codex", {
|
||||
reasoningEffort: "high",
|
||||
fastMode: false,
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
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.setStickyModelOptions({
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
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]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
claudeAgent: {
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
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.setStickyModelOptions({
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
store.setModelOptions(threadId, {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
store.setStickyModelSelection(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
|
||||
store.setProviderModelOptions(
|
||||
threadId,
|
||||
@@ -777,33 +758,31 @@ describe("composerDraftStore modelOptions", () => {
|
||||
{ persistSticky: false },
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
claudeAgent: {
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore setModel", () => {
|
||||
describe("composerDraftStore setModelSelection", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-model");
|
||||
|
||||
beforeEach(() => {
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("keeps explicit DEFAULT_MODEL overrides instead of coercing to null", () => {
|
||||
it("keeps explicit model overrides instead of coercing to null", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModel(threadId, "gpt-5.3-codex");
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.3-codex"));
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.model).toBe(
|
||||
"gpt-5.3-codex",
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex"),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -813,21 +792,21 @@ describe("composerDraftStore sticky composer settings", () => {
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("stores sticky model and codex model options", () => {
|
||||
it("stores a sticky model selection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setStickyModel("gpt-5.3-codex");
|
||||
store.setStickyModelOptions({
|
||||
codex: {
|
||||
store.setStickyModelSelection(
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState()).toMatchObject({
|
||||
stickyModel: "gpt-5.3-codex",
|
||||
stickyModelOptions: {
|
||||
codex: {
|
||||
stickyModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -835,41 +814,38 @@ describe("composerDraftStore sticky composer settings", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes empty sticky model options", () => {
|
||||
it("normalizes empty sticky model options by dropping selection options", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setStickyModelOptions({
|
||||
codex: {
|
||||
fastMode: false,
|
||||
},
|
||||
});
|
||||
store.setStickyModelSelection(modelSelection("codex", "gpt-5.4"));
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({});
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.4"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore setProvider", () => {
|
||||
describe("composerDraftStore provider-scoped option updates", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-provider");
|
||||
|
||||
beforeEach(() => {
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("persists provider-only selection even when prompt/model are empty", () => {
|
||||
it("does not patch provider options when the draft selection is on another provider", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setProvider(threadId, "codex");
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.provider).toBe("codex");
|
||||
});
|
||||
|
||||
it("removes empty provider-only draft when provider is reset", () => {
|
||||
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",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+141
-223
@@ -3,6 +3,7 @@ import {
|
||||
type ClaudeCodeEffort,
|
||||
type CodexReasoningEffort,
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
type ModelSelection,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
ProviderKind,
|
||||
@@ -73,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),
|
||||
});
|
||||
@@ -89,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,
|
||||
@@ -105,8 +109,7 @@ const PersistedComposerDraftStoreState = Schema.Struct({
|
||||
draftsByThreadId: Schema.Record(ThreadId, PersistedComposerThreadDraftState),
|
||||
draftThreadsByThreadId: Schema.Record(ThreadId, PersistedDraftThreadState),
|
||||
projectDraftThreadIdByProjectId: Schema.Record(ProjectId, ThreadId),
|
||||
stickyModel: Schema.NullOr(Schema.String),
|
||||
stickyModelOptions: ProviderModelOptions,
|
||||
stickyModelSelection: Schema.NullOr(Schema.Unknown),
|
||||
});
|
||||
type PersistedComposerDraftStoreState = typeof PersistedComposerDraftStoreState.Type;
|
||||
|
||||
@@ -121,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;
|
||||
}
|
||||
@@ -146,8 +147,7 @@ interface ComposerDraftStoreState {
|
||||
draftsByThreadId: Record<ThreadId, ComposerThreadDraftState>;
|
||||
draftThreadsByThreadId: Record<ThreadId, DraftThreadState>;
|
||||
projectDraftThreadIdByProjectId: Record<ProjectId, ThreadId>;
|
||||
stickyModel: string | null;
|
||||
stickyModelOptions: ProviderModelOptions;
|
||||
stickyModelSelection: ModelSelection | null;
|
||||
getDraftThreadByProjectId: (projectId: ProjectId) => ProjectDraftThread | null;
|
||||
getDraftThread: (threadId: ThreadId) => DraftThreadState | null;
|
||||
setProjectDraftThreadId: (
|
||||
@@ -177,15 +177,12 @@ interface ComposerDraftStoreState {
|
||||
clearProjectDraftThreadId: (projectId: ProjectId) => void;
|
||||
clearProjectDraftThreadById: (projectId: ProjectId, threadId: ThreadId) => void;
|
||||
clearDraftThread: (threadId: ThreadId) => void;
|
||||
setStickyModel: (model: string | null | undefined) => void;
|
||||
setStickyModelOptions: (modelOptions: ProviderModelOptions | null | undefined) => void;
|
||||
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,
|
||||
@@ -219,17 +216,13 @@ interface ComposerDraftStoreState {
|
||||
attachments: PersistedComposerImageAttachment[],
|
||||
) => void;
|
||||
clearComposerContent: (threadId: ThreadId) => void;
|
||||
clearThreadDraft: (threadId: ThreadId) => void;
|
||||
}
|
||||
|
||||
const EMPTY_PROVIDER_MODEL_OPTIONS = Object.freeze<ProviderModelOptions>({});
|
||||
|
||||
const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftStoreState>({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModel: null,
|
||||
stickyModelOptions: EMPTY_PROVIDER_MODEL_OPTIONS,
|
||||
stickyModelSelection: null,
|
||||
});
|
||||
|
||||
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
|
||||
@@ -245,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,
|
||||
});
|
||||
@@ -259,9 +250,7 @@ function createEmptyThreadDraft(): ComposerThreadDraftState {
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
provider: null,
|
||||
model: null,
|
||||
modelOptions: null,
|
||||
modelSelection: null,
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
@@ -330,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
|
||||
);
|
||||
@@ -416,6 +403,41 @@ 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,
|
||||
@@ -620,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 {};
|
||||
@@ -654,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"
|
||||
@@ -668,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
|
||||
) {
|
||||
@@ -689,9 +706,7 @@ function normalizePersistedDraftsByThreadId(
|
||||
prompt,
|
||||
attachments,
|
||||
...(terminalContexts.length > 0 ? { terminalContexts } : {}),
|
||||
...(provider ? { provider } : {}),
|
||||
...(model ? { model } : {}),
|
||||
...(modelOptions ? { modelOptions } : {}),
|
||||
...(modelSelection ? { modelSelection } : {}),
|
||||
...(runtimeMode ? { runtimeMode } : {}),
|
||||
...(interactionMode ? { interactionMode } : {}),
|
||||
};
|
||||
@@ -702,7 +717,6 @@ function normalizePersistedDraftsByThreadId(
|
||||
|
||||
function migratePersistedComposerDraftStoreState(
|
||||
persistedState: unknown,
|
||||
persistedVersion: number,
|
||||
): PersistedComposerDraftStoreState {
|
||||
if (!persistedState || typeof persistedState !== "object") {
|
||||
return EMPTY_PERSISTED_DRAFT_STORE_STATE;
|
||||
@@ -711,31 +725,19 @@ function migratePersistedComposerDraftStoreState(
|
||||
const rawDraftMap = candidate.draftsByThreadId;
|
||||
const rawDraftThreadsByThreadId = candidate.draftThreadsByThreadId;
|
||||
const rawProjectDraftThreadIdByProjectId = candidate.projectDraftThreadIdByProjectId;
|
||||
const stickyModel =
|
||||
typeof candidate.stickyModel === "string"
|
||||
? (normalizeModelSlug(candidate.stickyModel, "codex") ?? null)
|
||||
: null;
|
||||
const stickyModelOptions =
|
||||
normalizeProviderModelOptions(candidate.stickyModelOptions) ?? EMPTY_PROVIDER_MODEL_OPTIONS;
|
||||
const 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,
|
||||
stickyModel,
|
||||
stickyModelOptions,
|
||||
stickyModelSelection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -753,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
|
||||
) {
|
||||
@@ -777,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 } : {}),
|
||||
};
|
||||
@@ -789,8 +787,7 @@ function partializeComposerDraftStoreState(
|
||||
draftsByThreadId: persistedDraftsByThreadId,
|
||||
draftThreadsByThreadId: state.draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: state.projectDraftThreadIdByProjectId,
|
||||
stickyModel: state.stickyModel,
|
||||
stickyModelOptions: state.stickyModelOptions,
|
||||
stickyModelSelection: state.stickyModelSelection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -806,23 +803,19 @@ function normalizeCurrentPersistedComposerDraftStoreState(
|
||||
normalizedPersistedState.draftThreadsByThreadId,
|
||||
normalizedPersistedState.projectDraftThreadIdByProjectId,
|
||||
);
|
||||
const stickyModel =
|
||||
typeof normalizedPersistedState.stickyModel === "string"
|
||||
? (normalizeModelSlug(normalizedPersistedState.stickyModel, "codex") ?? null)
|
||||
: null;
|
||||
const stickyModelOptions =
|
||||
normalizeProviderModelOptions(normalizedPersistedState.stickyModelOptions) ??
|
||||
EMPTY_PROVIDER_MODEL_OPTIONS;
|
||||
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,
|
||||
stickyModel,
|
||||
stickyModelOptions,
|
||||
stickyModelSelection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -959,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,
|
||||
};
|
||||
@@ -973,8 +969,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModel: null,
|
||||
stickyModelOptions: EMPTY_PROVIDER_MODEL_OPTIONS,
|
||||
stickyModelSelection: null,
|
||||
getDraftThreadByProjectId: (projectId) => {
|
||||
if (projectId.length === 0) {
|
||||
return null;
|
||||
@@ -1189,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(
|
||||
@@ -1204,34 +1206,22 @@ 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,
|
||||
};
|
||||
});
|
||||
},
|
||||
setStickyModel: (model) => {
|
||||
const normalizedModel = normalizeModelSlug(model, "codex") ?? null;
|
||||
set((state) => {
|
||||
if (state.stickyModel === normalizedModel) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
stickyModel: normalizedModel,
|
||||
};
|
||||
});
|
||||
},
|
||||
setStickyModelOptions: (modelOptions) => {
|
||||
const normalizedModelOptions =
|
||||
normalizeProviderModelOptions(modelOptions) ?? EMPTY_PROVIDER_MODEL_OPTIONS;
|
||||
set((state) => {
|
||||
if (Equal.equals(state.stickyModelOptions, normalizedModelOptions)) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
stickyModelOptions: normalizedModelOptions,
|
||||
};
|
||||
});
|
||||
setStickyModelSelection: (modelSelection) => {
|
||||
const normalizedModelSelection = normalizeModelSelection(modelSelection);
|
||||
set((state) =>
|
||||
Equal.equals(state.stickyModelSelection, normalizedModelSelection)
|
||||
? state
|
||||
: { stickyModelSelection: normalizedModelSelection },
|
||||
);
|
||||
},
|
||||
setPrompt: (threadId, prompt) => {
|
||||
if (threadId.length === 0) {
|
||||
@@ -1276,78 +1266,23 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setProvider: (threadId, provider) => {
|
||||
setModelSelection: (threadId, modelSelection) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const normalizedProvider = normalizeProviderKind(provider);
|
||||
const normalizedModelSelection = normalizeModelSelection(modelSelection);
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
if (!existing && normalizedProvider === null) {
|
||||
if (!existing && normalizedModelSelection === null) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
if (base.provider === normalizedProvider) {
|
||||
if (Equal.equals(base.modelSelection, normalizedModelSelection)) {
|
||||
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) {
|
||||
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) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
model: normalizedModel,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} 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 (Equal.equals(base.modelOptions, nextModelOptions)) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelOptions: nextModelOptions,
|
||||
modelSelection: normalizedModelSelection,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
@@ -1369,26 +1304,45 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
const nextModelOptions = replaceProviderModelOptions(
|
||||
base.modelOptions,
|
||||
if (base.modelSelection?.provider !== normalizedProvider) {
|
||||
return state;
|
||||
}
|
||||
const nextProviderModelOptions = replaceProviderModelOptions(
|
||||
base.modelSelection?.options
|
||||
? { [normalizedProvider]: base.modelSelection.options }
|
||||
: null,
|
||||
normalizedProvider,
|
||||
nextProviderOptions,
|
||||
);
|
||||
const nextStickyModelOptions =
|
||||
options?.persistSticky === true
|
||||
? (nextModelOptions ?? EMPTY_PROVIDER_MODEL_OPTIONS)
|
||||
: state.stickyModelOptions;
|
||||
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.modelOptions, nextModelOptions) &&
|
||||
Equal.equals(state.stickyModelOptions, nextStickyModelOptions)
|
||||
Equal.equals(base.modelSelection, nextModelSelection) &&
|
||||
Equal.equals(state.stickyModelSelection, nextStickyModelSelection)
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelOptions: nextModelOptions,
|
||||
modelSelection: nextModelSelection,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
@@ -1400,7 +1354,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return {
|
||||
draftsByThreadId: nextDraftsByThreadId,
|
||||
...(options?.persistSticky === true
|
||||
? { stickyModelOptions: nextStickyModelOptions }
|
||||
? { stickyModelSelection: nextStickyModelSelection }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
@@ -1738,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,
|
||||
@@ -1794,8 +1713,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: normalizedPersisted.draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: normalizedPersisted.projectDraftThreadIdByProjectId,
|
||||
stickyModel: normalizedPersisted.stickyModel,
|
||||
stickyModelOptions: normalizedPersisted.stickyModelOptions,
|
||||
stickyModelSelection: normalizedPersisted.stickyModelSelection as ModelSelection | null,
|
||||
};
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { DEFAULT_RUNTIME_MODE, type ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useCallback } from "react";
|
||||
import { inferProviderForModel } from "@t3tools/shared/model";
|
||||
import {
|
||||
type DraftThreadEnvMode,
|
||||
type DraftThreadState,
|
||||
@@ -13,8 +12,7 @@ import { useStore } from "../store";
|
||||
export function useHandleNewThread() {
|
||||
const projects = useStore((store) => store.projects);
|
||||
const threads = useStore((store) => store.threads);
|
||||
const stickyModel = useComposerDraftStore((store) => store.stickyModel);
|
||||
const stickyModelOptions = useComposerDraftStore((store) => store.stickyModelOptions);
|
||||
const stickyModelSelection = useComposerDraftStore((store) => store.stickyModelSelection);
|
||||
const navigate = useNavigate();
|
||||
const routeThreadId = useParams({
|
||||
strict: false,
|
||||
@@ -41,9 +39,7 @@ export function useHandleNewThread() {
|
||||
clearProjectDraftThreadId,
|
||||
getDraftThread,
|
||||
getDraftThreadByProjectId,
|
||||
setModel,
|
||||
setModelOptions,
|
||||
setProvider,
|
||||
setModelSelection,
|
||||
setDraftThreadContext,
|
||||
setProjectDraftThreadId,
|
||||
} = useComposerDraftStore.getState();
|
||||
@@ -102,12 +98,8 @@ export function useHandleNewThread() {
|
||||
envMode: options?.envMode ?? "local",
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
});
|
||||
if (stickyModel) {
|
||||
setProvider(threadId, inferProviderForModel(stickyModel));
|
||||
setModel(threadId, stickyModel);
|
||||
}
|
||||
if (Object.keys(stickyModelOptions).length > 0) {
|
||||
setModelOptions(threadId, stickyModelOptions);
|
||||
if (stickyModelSelection) {
|
||||
setModelSelection(threadId, stickyModelSelection);
|
||||
}
|
||||
|
||||
await navigate({
|
||||
@@ -116,7 +108,7 @@ export function useHandleNewThread() {
|
||||
});
|
||||
})();
|
||||
},
|
||||
[navigate, routeThreadId, stickyModel, stickyModelOptions],
|
||||
[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;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
commandForProjectScript,
|
||||
nextProjectScriptId,
|
||||
primaryProjectScript,
|
||||
projectScriptCwd,
|
||||
projectScriptRuntimeEnv,
|
||||
projectScriptIdFromCommand,
|
||||
setupProjectScript,
|
||||
@@ -70,4 +71,19 @@ describe("projectScripts helpers", () => {
|
||||
expect(env.CUSTOM_FLAG).toBe("1");
|
||||
expect(env.T3CODE_WORKTREE_PATH).toBeUndefined();
|
||||
});
|
||||
|
||||
it("prefers the worktree path for script cwd resolution", () => {
|
||||
expect(
|
||||
projectScriptCwd({
|
||||
project: { cwd: "/repo" },
|
||||
worktreePath: "/repo/worktree-a",
|
||||
}),
|
||||
).toBe("/repo/worktree-a");
|
||||
expect(
|
||||
projectScriptCwd({
|
||||
project: { cwd: "/repo" },
|
||||
worktreePath: null,
|
||||
}),
|
||||
).toBe("/repo");
|
||||
});
|
||||
});
|
||||
@@ -63,6 +63,15 @@ interface ProjectScriptRuntimeEnvInput {
|
||||
extraEnv?: Record<string, string>;
|
||||
}
|
||||
|
||||
export function projectScriptCwd(input: {
|
||||
project: {
|
||||
cwd: string;
|
||||
};
|
||||
worktreePath?: string | null;
|
||||
}): string {
|
||||
return input.worktreePath ?? input.project.cwd;
|
||||
}
|
||||
|
||||
export function projectScriptRuntimeEnv(
|
||||
input: ProjectScriptRuntimeEnvInput,
|
||||
): Record<string, string> {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -10,11 +10,14 @@ import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { resolveShortcutCommand } from "../keybindings";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { Sidebar, SidebarProvider } from "~/components/ui/sidebar";
|
||||
import { resolveSidebarNewThreadEnvMode } from "~/components/Sidebar.logic";
|
||||
import { useAppSettings } from "~/appSettings";
|
||||
import { Sidebar, SidebarProvider, SidebarRail } from "~/components/ui/sidebar";
|
||||
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width";
|
||||
const THREAD_SIDEBAR_MIN_WIDTH = 13 * 16;
|
||||
const THREAD_MAIN_CONTENT_MIN_WIDTH = 40 * 16;
|
||||
|
||||
function ChatRouteGlobalShortcuts() {
|
||||
const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
|
||||
@@ -116,8 +119,15 @@ function ChatRouteLayout() {
|
||||
side="left"
|
||||
collapsible="offcanvas"
|
||||
className="border-r border-border bg-card text-foreground"
|
||||
resizable={{
|
||||
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
|
||||
shouldAcceptWidth: ({ nextWidth, wrapper }) =>
|
||||
wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
|
||||
storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
|
||||
}}
|
||||
>
|
||||
<ThreadSidebar />
|
||||
<SidebarRail />
|
||||
</Sidebar>
|
||||
<Outlet />
|
||||
</SidebarProvider>
|
||||
|
||||
+50
-14
@@ -16,7 +16,10 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
codexThreadId: null,
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_INTERACTION_MODE,
|
||||
session: null,
|
||||
@@ -40,7 +43,10 @@ function makeState(thread: Thread): AppState {
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
@@ -55,7 +61,10 @@ function makeReadModelThread(overrides: Partial<OrchestrationReadModel["threads"
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_INTERACTION_MODE,
|
||||
branch: null,
|
||||
@@ -82,7 +91,10 @@ function makeReadModel(thread: OrchestrationReadModel["threads"][number]): Orche
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: "gpt-5.3-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
createdAt: "2026-02-27T00:00:00.000Z",
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
@@ -100,7 +112,10 @@ function makeReadModelProject(
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: "gpt-5.3-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
createdAt: "2026-02-27T00:00:00.000Z",
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
@@ -159,7 +174,10 @@ describe("store pure functions", () => {
|
||||
id: project1,
|
||||
name: "Project 1",
|
||||
cwd: "/tmp/project-1",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
@@ -167,7 +185,10 @@ describe("store pure functions", () => {
|
||||
id: project2,
|
||||
name: "Project 2",
|
||||
cwd: "/tmp/project-2",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
@@ -175,7 +196,10 @@ describe("store pure functions", () => {
|
||||
id: project3,
|
||||
name: "Project 3",
|
||||
cwd: "/tmp/project-3",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
@@ -195,20 +219,26 @@ describe("store read model sync", () => {
|
||||
const initialState = makeState(makeThread());
|
||||
const readModel = makeReadModel(
|
||||
makeReadModelThread({
|
||||
model: "claude-opus-4-6",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const next = syncServerReadModel(initialState, readModel);
|
||||
|
||||
expect(next.threads[0]?.model).toBe("claude-opus-4-6");
|
||||
expect(next.threads[0]?.modelSelection.model).toBe("claude-opus-4-6");
|
||||
});
|
||||
|
||||
it("resolves claude aliases when session provider is claudeAgent", () => {
|
||||
const initialState = makeState(makeThread());
|
||||
const readModel = makeReadModel(
|
||||
makeReadModelThread({
|
||||
model: "sonnet",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "sonnet",
|
||||
},
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
@@ -223,7 +253,7 @@ describe("store read model sync", () => {
|
||||
|
||||
const next = syncServerReadModel(initialState, readModel);
|
||||
|
||||
expect(next.threads[0]?.model).toBe("claude-sonnet-4-6");
|
||||
expect(next.threads[0]?.modelSelection.model).toBe("claude-sonnet-4-6");
|
||||
});
|
||||
|
||||
it("preserves the current project order when syncing incoming read model updates", () => {
|
||||
@@ -236,7 +266,10 @@ describe("store read model sync", () => {
|
||||
id: project2,
|
||||
name: "Project 2",
|
||||
cwd: "/tmp/project-2",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
@@ -244,7 +277,10 @@ describe("store read model sync", () => {
|
||||
id: project1,
|
||||
name: "Project 1",
|
||||
cwd: "/tmp/project-1",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
|
||||
+40
-25
@@ -1,16 +1,13 @@
|
||||
import { Fragment, type ReactNode, createElement, useEffect } from "react";
|
||||
import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ModelSelection,
|
||||
type ProviderKind,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
type OrchestrationSessionStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
inferProviderForModel,
|
||||
resolveModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
} from "@t3tools/shared/model";
|
||||
import { resolveModelSlugForProvider } from "@t3tools/shared/model";
|
||||
import { create } from "zustand";
|
||||
import { type ChatMessage, type Project, type Thread } from "./types";
|
||||
import { Debouncer } from "@tanstack/react-pacer";
|
||||
@@ -137,9 +134,17 @@ function mapProjectsFromReadModel(
|
||||
id: project.id,
|
||||
name: project.title,
|
||||
cwd: project.workspaceRoot,
|
||||
model:
|
||||
existing?.model ??
|
||||
resolveModelSlug(project.defaultModel ?? DEFAULT_MODEL_BY_PROVIDER.codex),
|
||||
defaultModelSelection:
|
||||
existing?.defaultModelSelection ??
|
||||
(project.defaultModelSelection
|
||||
? {
|
||||
...project.defaultModelSelection,
|
||||
model: resolveModelSlugForProvider(
|
||||
project.defaultModelSelection.provider,
|
||||
project.defaultModelSelection.model,
|
||||
),
|
||||
}
|
||||
: null),
|
||||
expanded:
|
||||
existing?.expanded ??
|
||||
(persistedExpandedProjectCwds.size > 0
|
||||
@@ -194,16 +199,6 @@ function toLegacyProvider(providerName: string | null): ProviderKind {
|
||||
return "codex";
|
||||
}
|
||||
|
||||
function inferProviderForThreadModel(input: {
|
||||
readonly model: string;
|
||||
readonly sessionProviderName: string | null;
|
||||
}): ProviderKind {
|
||||
if (input.sessionProviderName === "codex" || input.sessionProviderName === "claudeAgent") {
|
||||
return input.sessionProviderName;
|
||||
}
|
||||
return inferProviderForModel(input.model);
|
||||
}
|
||||
|
||||
function resolveWsHttpOrigin(): string {
|
||||
if (typeof window === "undefined") return "";
|
||||
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||
@@ -253,13 +248,13 @@ export function syncServerReadModel(state: AppState, readModel: OrchestrationRea
|
||||
codexThreadId: null,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: resolveModelSlugForProvider(
|
||||
inferProviderForThreadModel({
|
||||
model: thread.model,
|
||||
sessionProviderName: thread.session?.providerName ?? null,
|
||||
}),
|
||||
thread.model,
|
||||
),
|
||||
modelSelection: {
|
||||
...thread.modelSelection,
|
||||
model: resolveModelSlugForProvider(
|
||||
thread.modelSelection.provider,
|
||||
thread.modelSelection.model,
|
||||
),
|
||||
},
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
session: thread.session
|
||||
@@ -328,6 +323,26 @@ export function syncServerReadModel(state: AppState, readModel: OrchestrationRea
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveModelSelection(
|
||||
modelSelection: ModelSelection | null | undefined,
|
||||
fallbackProvider: ProviderKind,
|
||||
fallbackModel?: string | null,
|
||||
): ModelSelection {
|
||||
if (modelSelection) {
|
||||
return {
|
||||
...modelSelection,
|
||||
model: resolveModelSlugForProvider(modelSelection.provider, modelSelection.model),
|
||||
};
|
||||
}
|
||||
return {
|
||||
provider: fallbackProvider,
|
||||
model: resolveModelSlugForProvider(
|
||||
fallbackProvider,
|
||||
fallbackModel ?? DEFAULT_MODEL_BY_PROVIDER[fallbackProvider],
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function markThreadVisited(
|
||||
state: AppState,
|
||||
threadId: ThreadId,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {
|
||||
ModelSelection,
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationProposedPlanId,
|
||||
OrchestrationSessionStatus,
|
||||
@@ -8,8 +9,8 @@ import type {
|
||||
ProjectId,
|
||||
TurnId,
|
||||
MessageId,
|
||||
CheckpointRef,
|
||||
ProviderKind,
|
||||
CheckpointRef,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -80,7 +81,7 @@ export interface Project {
|
||||
id: ProjectId;
|
||||
name: string;
|
||||
cwd: string;
|
||||
model: string;
|
||||
defaultModelSelection: ModelSelection | null;
|
||||
expanded: boolean;
|
||||
scripts: ProjectScript[];
|
||||
}
|
||||
@@ -90,7 +91,7 @@ export interface Thread {
|
||||
codexThreadId: string | null;
|
||||
projectId: ProjectId;
|
||||
title: string;
|
||||
model: string;
|
||||
modelSelection: ModelSelection;
|
||||
runtimeMode: RuntimeMode;
|
||||
interactionMode: ProviderInteractionMode;
|
||||
session: ThreadSession | null;
|
||||
|
||||
@@ -10,7 +10,10 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
codexThreadId: null,
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_INTERACTION_MODE,
|
||||
session: null,
|
||||
|
||||
@@ -239,9 +239,11 @@ describe("wsNativeApi", () => {
|
||||
const api = createWsNativeApi();
|
||||
const onTerminalEvent = vi.fn();
|
||||
const onDomainEvent = vi.fn();
|
||||
const onActionProgress = vi.fn();
|
||||
|
||||
api.terminal.onEvent(onTerminalEvent);
|
||||
api.orchestration.onDomainEvent(onDomainEvent);
|
||||
api.git.onActionProgress(onActionProgress);
|
||||
|
||||
const terminalEvent = {
|
||||
threadId: "thread-1",
|
||||
@@ -267,18 +269,35 @@ describe("wsNativeApi", () => {
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-24T00:00:00.000Z",
|
||||
updatedAt: "2026-02-24T00:00:00.000Z",
|
||||
},
|
||||
} satisfies Extract<OrchestrationEvent, { type: "project.created" }>;
|
||||
emitPush(ORCHESTRATION_WS_CHANNELS.domainEvent, orchestrationEvent);
|
||||
emitPush(WS_CHANNELS.gitActionProgress, {
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
kind: "phase_started",
|
||||
phase: "commit",
|
||||
label: "Committing...",
|
||||
});
|
||||
|
||||
expect(onTerminalEvent).toHaveBeenCalledTimes(1);
|
||||
expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent);
|
||||
expect(onDomainEvent).toHaveBeenCalledTimes(1);
|
||||
expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
|
||||
expect(onActionProgress).toHaveBeenCalledTimes(1);
|
||||
expect(onActionProgress).toHaveBeenCalledWith({
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
kind: "phase_started",
|
||||
phase: "commit",
|
||||
label: "Committing...",
|
||||
});
|
||||
});
|
||||
|
||||
it("wraps orchestration dispatch commands in the command envelope", async () => {
|
||||
@@ -292,7 +311,10 @@ describe("wsNativeApi", () => {
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt: "2026-02-24T00:00:00.000Z",
|
||||
} as const;
|
||||
await api.orchestration.dispatchCommand(command);
|
||||
@@ -320,6 +342,26 @@ describe("wsNativeApi", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("uses no client timeout for git.runStackedAction", async () => {
|
||||
requestMock.mockResolvedValue({
|
||||
action: "commit",
|
||||
branch: { status: "skipped_not_requested" },
|
||||
commit: { status: "created", commitSha: "abc1234", subject: "Test" },
|
||||
push: { status: "skipped_not_requested" },
|
||||
pr: { status: "skipped_not_requested" },
|
||||
});
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
const api = createWsNativeApi();
|
||||
await api.git.runStackedAction({ actionId: "action-1", cwd: "/repo", action: "commit" });
|
||||
|
||||
expect(requestMock).toHaveBeenCalledWith(
|
||||
WS_METHODS.gitRunStackedAction,
|
||||
{ actionId: "action-1", cwd: "/repo", action: "commit" },
|
||||
{ timeoutMs: null },
|
||||
);
|
||||
});
|
||||
|
||||
it("forwards full-thread diff requests to the orchestration websocket method", async () => {
|
||||
requestMock.mockResolvedValue({ diff: "patch" });
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
type GitActionProgressEvent,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type ContextMenuItem,
|
||||
@@ -15,6 +16,7 @@ import { WsTransport } from "./wsTransport";
|
||||
let instance: { api: NativeApi; transport: WsTransport } | null = null;
|
||||
const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>();
|
||||
const serverConfigUpdatedListeners = new Set<(payload: ServerConfigUpdatedPayload) => void>();
|
||||
const gitActionProgressListeners = new Set<(payload: GitActionProgressEvent) => void>();
|
||||
|
||||
/**
|
||||
* Subscribe to the server welcome message. If a welcome was already received
|
||||
@@ -87,6 +89,16 @@ export function createWsNativeApi(): NativeApi {
|
||||
}
|
||||
}
|
||||
});
|
||||
transport.subscribe(WS_CHANNELS.gitActionProgress, (message) => {
|
||||
const payload = message.data;
|
||||
for (const listener of gitActionProgressListeners) {
|
||||
try {
|
||||
listener(payload);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const api: NativeApi = {
|
||||
dialogs: {
|
||||
@@ -135,7 +147,8 @@ export function createWsNativeApi(): NativeApi {
|
||||
git: {
|
||||
pull: (input) => transport.request(WS_METHODS.gitPull, input),
|
||||
status: (input) => transport.request(WS_METHODS.gitStatus, input),
|
||||
runStackedAction: (input) => transport.request(WS_METHODS.gitRunStackedAction, input),
|
||||
runStackedAction: (input) =>
|
||||
transport.request(WS_METHODS.gitRunStackedAction, input, { timeoutMs: null }),
|
||||
listBranches: (input) => transport.request(WS_METHODS.gitListBranches, input),
|
||||
createWorktree: (input) => transport.request(WS_METHODS.gitCreateWorktree, input),
|
||||
removeWorktree: (input) => transport.request(WS_METHODS.gitRemoveWorktree, input),
|
||||
@@ -145,6 +158,12 @@ export function createWsNativeApi(): NativeApi {
|
||||
resolvePullRequest: (input) => transport.request(WS_METHODS.gitResolvePullRequest, input),
|
||||
preparePullRequestThread: (input) =>
|
||||
transport.request(WS_METHODS.gitPreparePullRequestThread, input),
|
||||
onActionProgress: (callback) => {
|
||||
gitActionProgressListeners.add(callback);
|
||||
return () => {
|
||||
gitActionProgressListeners.delete(callback);
|
||||
};
|
||||
},
|
||||
},
|
||||
contextMenu: {
|
||||
show: async <T extends string>(
|
||||
|
||||
@@ -206,4 +206,51 @@ describe("WsTransport", () => {
|
||||
await expect(requestPromise).resolves.toEqual({ projects: [] });
|
||||
transport.dispose();
|
||||
});
|
||||
|
||||
it("does not create a timeout for requests with timeoutMs null", async () => {
|
||||
const timeoutSpy = vi.spyOn(globalThis, "setTimeout");
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
const requestPromise = transport.request(
|
||||
"git.runStackedAction",
|
||||
{ cwd: "/repo" },
|
||||
{ timeoutMs: null },
|
||||
);
|
||||
const sent = socket.sent.at(-1);
|
||||
if (!sent) {
|
||||
throw new Error("Expected request envelope to be sent");
|
||||
}
|
||||
const requestEnvelope = JSON.parse(sent) as { id: string };
|
||||
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
id: requestEnvelope.id,
|
||||
result: { ok: true },
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(requestPromise).resolves.toEqual({ ok: true });
|
||||
expect(timeoutSpy.mock.calls.some(([callback]) => typeof callback === "function")).toBe(false);
|
||||
|
||||
transport.dispose();
|
||||
});
|
||||
|
||||
it("rejects pending requests when the websocket closes", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
const requestPromise = transport.request(
|
||||
"git.runStackedAction",
|
||||
{ cwd: "/repo" },
|
||||
{ timeoutMs: null },
|
||||
);
|
||||
|
||||
socket.close();
|
||||
|
||||
await expect(requestPromise).rejects.toThrow("WebSocket connection closed.");
|
||||
transport.dispose();
|
||||
});
|
||||
});
|
||||
@@ -14,13 +14,17 @@ type PushListener<C extends WsPushChannel> = (message: WsPushMessage<C>) => void
|
||||
interface PendingRequest {
|
||||
resolve: (result: unknown) => void;
|
||||
reject: (error: Error) => void;
|
||||
timeout: ReturnType<typeof setTimeout>;
|
||||
timeout: ReturnType<typeof setTimeout> | null;
|
||||
}
|
||||
|
||||
interface SubscribeOptions {
|
||||
readonly replayLatest?: boolean;
|
||||
}
|
||||
|
||||
interface RequestOptions {
|
||||
readonly timeoutMs?: number | null;
|
||||
}
|
||||
|
||||
type TransportState = "connecting" | "open" | "reconnecting" | "closed" | "disposed";
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 60_000;
|
||||
@@ -72,7 +76,11 @@ export class WsTransport {
|
||||
this.connect();
|
||||
}
|
||||
|
||||
async request<T = unknown>(method: string, params?: unknown): Promise<T> {
|
||||
async request<T = unknown>(
|
||||
method: string,
|
||||
params?: unknown,
|
||||
options?: RequestOptions,
|
||||
): Promise<T> {
|
||||
if (typeof method !== "string" || method.length === 0) {
|
||||
throw new Error("Request method is required");
|
||||
}
|
||||
@@ -83,10 +91,14 @@ export class WsTransport {
|
||||
const encoded = JSON.stringify(message);
|
||||
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`Request timed out: ${method}`));
|
||||
}, REQUEST_TIMEOUT_MS);
|
||||
const timeoutMs = options?.timeoutMs === undefined ? REQUEST_TIMEOUT_MS : options.timeoutMs;
|
||||
const timeout =
|
||||
timeoutMs === null
|
||||
? null
|
||||
: setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`Request timed out: ${method}`));
|
||||
}, timeoutMs);
|
||||
|
||||
this.pending.set(id, {
|
||||
resolve: resolve as (result: unknown) => void,
|
||||
@@ -146,7 +158,9 @@ export class WsTransport {
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
for (const pending of this.pending.values()) {
|
||||
clearTimeout(pending.timeout);
|
||||
if (pending.timeout !== null) {
|
||||
clearTimeout(pending.timeout);
|
||||
}
|
||||
pending.reject(new Error("Transport disposed"));
|
||||
}
|
||||
this.pending.clear();
|
||||
@@ -177,6 +191,14 @@ export class WsTransport {
|
||||
ws.addEventListener("close", () => {
|
||||
if (this.ws === ws) {
|
||||
this.ws = null;
|
||||
this.outboundQueue.length = 0;
|
||||
for (const [id, pending] of this.pending.entries()) {
|
||||
if (pending.timeout !== null) {
|
||||
clearTimeout(pending.timeout);
|
||||
}
|
||||
this.pending.delete(id);
|
||||
pending.reject(new Error("WebSocket connection closed."));
|
||||
}
|
||||
}
|
||||
if (this.disposed) {
|
||||
this.state = "disposed";
|
||||
@@ -224,7 +246,9 @@ export class WsTransport {
|
||||
return;
|
||||
}
|
||||
|
||||
clearTimeout(pending.timeout);
|
||||
if (pending.timeout !== null) {
|
||||
clearTimeout(pending.timeout);
|
||||
}
|
||||
this.pending.delete(message.id);
|
||||
|
||||
if (message.error) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Schema } from "effect";
|
||||
import {
|
||||
GitCreateWorktreeInput,
|
||||
GitPreparePullRequestThreadInput,
|
||||
GitRunStackedActionInput,
|
||||
GitResolvePullRequestResult,
|
||||
} from "./git";
|
||||
|
||||
@@ -11,6 +12,7 @@ const decodeCreateWorktreeInput = Schema.decodeUnknownSync(GitCreateWorktreeInpu
|
||||
const decodePreparePullRequestThreadInput = Schema.decodeUnknownSync(
|
||||
GitPreparePullRequestThreadInput,
|
||||
);
|
||||
const decodeRunStackedActionInput = Schema.decodeUnknownSync(GitRunStackedActionInput);
|
||||
const decodeResolvePullRequestResult = Schema.decodeUnknownSync(GitResolvePullRequestResult);
|
||||
|
||||
describe("GitCreateWorktreeInput", () => {
|
||||
@@ -56,3 +58,16 @@ describe("GitResolvePullRequestResult", () => {
|
||||
expect(parsed.pullRequest.headBranch).toBe("feature/pr-threads");
|
||||
});
|
||||
});
|
||||
|
||||
describe("GitRunStackedActionInput", () => {
|
||||
it("requires a client-provided actionId for progress correlation", () => {
|
||||
const parsed = decodeRunStackedActionInput({
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(parsed.actionId).toBe("action-1");
|
||||
expect(parsed.action).toBe("commit");
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,20 @@ const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
|
||||
export const GitStackedAction = Schema.Literals(["commit", "commit_push", "commit_push_pr"]);
|
||||
export type GitStackedAction = typeof GitStackedAction.Type;
|
||||
export const GitActionProgressPhase = Schema.Literals(["branch", "commit", "push", "pr"]);
|
||||
export type GitActionProgressPhase = typeof GitActionProgressPhase.Type;
|
||||
export const GitActionProgressKind = Schema.Literals([
|
||||
"action_started",
|
||||
"phase_started",
|
||||
"hook_started",
|
||||
"hook_output",
|
||||
"hook_finished",
|
||||
"action_finished",
|
||||
"action_failed",
|
||||
]);
|
||||
export type GitActionProgressKind = typeof GitActionProgressKind.Type;
|
||||
export const GitActionProgressStream = Schema.Literals(["stdout", "stderr"]);
|
||||
export type GitActionProgressStream = typeof GitActionProgressStream.Type;
|
||||
const GitCommitStepStatus = Schema.Literals(["created", "skipped_no_changes"]);
|
||||
const GitPushStepStatus = Schema.Literals([
|
||||
"pushed",
|
||||
@@ -58,6 +72,7 @@ export const GitPullInput = Schema.Struct({
|
||||
export type GitPullInput = typeof GitPullInput.Type;
|
||||
|
||||
export const GitRunStackedActionInput = Schema.Struct({
|
||||
actionId: TrimmedNonEmptyStringSchema,
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
action: GitStackedAction,
|
||||
commitMessage: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(10_000))),
|
||||
@@ -211,3 +226,62 @@ export const GitPullResult = Schema.Struct({
|
||||
upstreamBranch: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
|
||||
});
|
||||
export type GitPullResult = typeof GitPullResult.Type;
|
||||
|
||||
const GitActionProgressBase = Schema.Struct({
|
||||
actionId: TrimmedNonEmptyStringSchema,
|
||||
cwd: TrimmedNonEmptyStringSchema,
|
||||
action: GitStackedAction,
|
||||
});
|
||||
|
||||
const GitActionStartedEvent = Schema.Struct({
|
||||
...GitActionProgressBase.fields,
|
||||
kind: Schema.Literal("action_started"),
|
||||
phases: Schema.Array(GitActionProgressPhase),
|
||||
});
|
||||
const GitActionPhaseStartedEvent = Schema.Struct({
|
||||
...GitActionProgressBase.fields,
|
||||
kind: Schema.Literal("phase_started"),
|
||||
phase: GitActionProgressPhase,
|
||||
label: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
const GitActionHookStartedEvent = Schema.Struct({
|
||||
...GitActionProgressBase.fields,
|
||||
kind: Schema.Literal("hook_started"),
|
||||
hookName: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
const GitActionHookOutputEvent = Schema.Struct({
|
||||
...GitActionProgressBase.fields,
|
||||
kind: Schema.Literal("hook_output"),
|
||||
hookName: Schema.NullOr(TrimmedNonEmptyStringSchema),
|
||||
stream: GitActionProgressStream,
|
||||
text: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
const GitActionHookFinishedEvent = Schema.Struct({
|
||||
...GitActionProgressBase.fields,
|
||||
kind: Schema.Literal("hook_finished"),
|
||||
hookName: TrimmedNonEmptyStringSchema,
|
||||
exitCode: Schema.NullOr(Schema.Int),
|
||||
durationMs: Schema.NullOr(NonNegativeInt),
|
||||
});
|
||||
const GitActionFinishedEvent = Schema.Struct({
|
||||
...GitActionProgressBase.fields,
|
||||
kind: Schema.Literal("action_finished"),
|
||||
result: GitRunStackedActionResult,
|
||||
});
|
||||
const GitActionFailedEvent = Schema.Struct({
|
||||
...GitActionProgressBase.fields,
|
||||
kind: Schema.Literal("action_failed"),
|
||||
phase: Schema.NullOr(GitActionProgressPhase),
|
||||
message: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
|
||||
export const GitActionProgressEvent = Schema.Union([
|
||||
GitActionStartedEvent,
|
||||
GitActionPhaseStartedEvent,
|
||||
GitActionHookStartedEvent,
|
||||
GitActionHookOutputEvent,
|
||||
GitActionHookFinishedEvent,
|
||||
GitActionFinishedEvent,
|
||||
GitActionFailedEvent,
|
||||
]);
|
||||
export type GitActionProgressEvent = typeof GitActionProgressEvent.Type;
|
||||
@@ -1,5 +1,6 @@
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
GitActionProgressEvent,
|
||||
GitCreateBranchInput,
|
||||
GitPreparePullRequestThreadInput,
|
||||
GitPreparePullRequestThreadResult,
|
||||
@@ -149,6 +150,7 @@ export interface NativeApi {
|
||||
pull: (input: GitPullInput) => Promise<GitPullResult>;
|
||||
status: (input: GitStatusInput) => Promise<GitStatusResult>;
|
||||
runStackedAction: (input: GitRunStackedActionInput) => Promise<GitRunStackedActionResult>;
|
||||
onActionProgress: (callback: (event: GitActionProgressEvent) => void) => () => void;
|
||||
};
|
||||
contextMenu: {
|
||||
show: <T extends string>(
|
||||
|
||||
@@ -7,9 +7,12 @@ import {
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationLatestTurn,
|
||||
ProjectCreatedPayload,
|
||||
ProjectMetaUpdatedPayload,
|
||||
OrchestrationProposedPlan,
|
||||
OrchestrationSession,
|
||||
ProjectCreateCommand,
|
||||
ThreadMetaUpdatedPayload,
|
||||
ThreadTurnStartCommand,
|
||||
ThreadCreatedPayload,
|
||||
ThreadTurnDiff,
|
||||
@@ -19,6 +22,8 @@ import {
|
||||
const decodeTurnDiffInput = Schema.decodeUnknownEffect(OrchestrationGetTurnDiffInput);
|
||||
const decodeThreadTurnDiff = Schema.decodeUnknownEffect(ThreadTurnDiff);
|
||||
const decodeProjectCreateCommand = Schema.decodeUnknownEffect(ProjectCreateCommand);
|
||||
const decodeProjectCreatedPayload = Schema.decodeUnknownEffect(ProjectCreatedPayload);
|
||||
const decodeProjectMetaUpdatedPayload = Schema.decodeUnknownEffect(ProjectMetaUpdatedPayload);
|
||||
const decodeThreadTurnStartCommand = Schema.decodeUnknownEffect(ThreadTurnStartCommand);
|
||||
const decodeThreadTurnStartRequestedPayload = Schema.decodeUnknownEffect(
|
||||
ThreadTurnStartRequestedPayload,
|
||||
@@ -27,6 +32,7 @@ const decodeOrchestrationLatestTurn = Schema.decodeUnknownEffect(OrchestrationLa
|
||||
const decodeOrchestrationProposedPlan = Schema.decodeUnknownEffect(OrchestrationProposedPlan);
|
||||
const decodeOrchestrationSession = Schema.decodeUnknownEffect(OrchestrationSession);
|
||||
const decodeThreadCreatedPayload = Schema.decodeUnknownEffect(ThreadCreatedPayload);
|
||||
const decodeThreadMetaUpdatedPayload = Schema.decodeUnknownEffect(ThreadMetaUpdatedPayload);
|
||||
|
||||
it.effect("parses turn diff input when fromTurnCount <= toTurnCount", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -75,14 +81,85 @@ it.effect("trims branded ids and command string fields at decode boundaries", ()
|
||||
projectId: " project-1 ",
|
||||
title: " Project Title ",
|
||||
workspaceRoot: " /tmp/workspace ",
|
||||
defaultModel: " gpt-5.2 ",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: " gpt-5.2 ",
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(parsed.commandId, "cmd-1");
|
||||
assert.strictEqual(parsed.projectId, "project-1");
|
||||
assert.strictEqual(parsed.title, "Project Title");
|
||||
assert.strictEqual(parsed.workspaceRoot, "/tmp/workspace");
|
||||
assert.strictEqual(parsed.defaultModel, "gpt-5.2");
|
||||
assert.deepStrictEqual(parsed.defaultModelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.2",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes historical project.created payloads with a default provider", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeProjectCreatedPayload({
|
||||
projectId: "project-1",
|
||||
title: "Project Title",
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(parsed.defaultModelSelection?.provider, "codex");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy project.created payloads into defaultModelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeProjectCreatedPayload({
|
||||
projectId: "project-legacy-1",
|
||||
title: "Project Title",
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
defaultModel: "gpt-5.4",
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.deepStrictEqual(parsed.defaultModelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes project.meta-updated payloads with explicit default provider", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeProjectMetaUpdatedPayload({
|
||||
projectId: "project-1",
|
||||
defaultModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(parsed.defaultModelSelection?.provider, "claudeAgent");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy project.meta-updated payloads into defaultModelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeProjectMetaUpdatedPayload({
|
||||
projectId: "project-legacy-2",
|
||||
defaultProvider: "claudeAgent",
|
||||
defaultModel: "claude-opus-4-6",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.deepStrictEqual(parsed.defaultModelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -116,7 +193,7 @@ it.effect("decodes thread.turn.start defaults for provider and runtime mode", ()
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(parsed.provider, undefined);
|
||||
assert.strictEqual(parsed.modelSelection, undefined);
|
||||
assert.strictEqual(parsed.runtimeMode, DEFAULT_RUNTIME_MODE);
|
||||
assert.strictEqual(parsed.interactionMode, DEFAULT_PROVIDER_INTERACTION_MODE);
|
||||
}),
|
||||
@@ -134,11 +211,14 @@ it.effect("preserves explicit provider and runtime mode in thread.turn.start", (
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(parsed.provider, "codex");
|
||||
assert.strictEqual(parsed.modelSelection?.provider, "codex");
|
||||
assert.strictEqual(parsed.runtimeMode, "full-access");
|
||||
assert.strictEqual(parsed.interactionMode, DEFAULT_PROVIDER_INTERACTION_MODE);
|
||||
}),
|
||||
@@ -150,7 +230,10 @@ it.effect("decodes thread.created runtime mode for historical events", () =>
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread title",
|
||||
model: "gpt-5.4",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -159,6 +242,58 @@ it.effect("decodes thread.created runtime mode for historical events", () =>
|
||||
});
|
||||
|
||||
assert.strictEqual(parsed.runtimeMode, DEFAULT_RUNTIME_MODE);
|
||||
assert.strictEqual(parsed.modelSelection.provider, "codex");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy thread.created payloads into modelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadCreatedPayload({
|
||||
threadId: "thread-legacy-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread title",
|
||||
model: "claude-opus-4-6",
|
||||
provider: "claudeAgent",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(parsed.modelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
});
|
||||
assert.strictEqual(parsed.runtimeMode, DEFAULT_RUNTIME_MODE);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes thread.meta-updated payloads with explicit provider", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadMetaUpdatedPayload({
|
||||
threadId: "thread-1",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(parsed.modelSelection?.provider, "claudeAgent");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy thread.meta-updated payloads into modelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadMetaUpdatedPayload({
|
||||
threadId: "thread-legacy-2",
|
||||
model: "gpt-5.4",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.deepStrictEqual(parsed.modelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -174,19 +309,19 @@ it.effect("accepts provider-scoped model options in thread.turn.start", () =>
|
||||
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,
|
||||
},
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(parsed.provider, "codex");
|
||||
assert.strictEqual(parsed.modelOptions?.codex?.reasoningEffort, "high");
|
||||
assert.strictEqual(parsed.modelOptions?.codex?.fastMode, true);
|
||||
assert.strictEqual(parsed.modelSelection?.provider, "codex");
|
||||
assert.strictEqual(parsed.modelSelection?.options?.reasoningEffort, "high");
|
||||
assert.strictEqual(parsed.modelSelection?.options?.fastMode, true);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -224,7 +359,7 @@ it.effect(
|
||||
messageId: "msg-1",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(parsed.provider, undefined);
|
||||
assert.strictEqual(parsed.modelSelection, undefined);
|
||||
assert.strictEqual(parsed.runtimeMode, DEFAULT_RUNTIME_MODE);
|
||||
assert.strictEqual(parsed.interactionMode, DEFAULT_PROVIDER_INTERACTION_MODE);
|
||||
assert.strictEqual(parsed.sourceProposedPlan, undefined);
|
||||
@@ -249,6 +384,21 @@ it.effect("decodes thread.turn-start-requested source proposed plan metadata whe
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy thread.turn-start-requested payloads into modelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadTurnStartRequestedPayload({
|
||||
threadId: "thread-legacy-3",
|
||||
messageId: "msg-legacy-3",
|
||||
model: "gpt-5.4",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.deepStrictEqual(parsed.modelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes latest turn source proposed plan metadata when present", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeOrchestrationLatestTurn({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Option, Schema, SchemaIssue, Struct } from "effect";
|
||||
import { ProviderModelOptions } from "./model";
|
||||
import { Effect, Option, Schema, SchemaIssue, SchemaTransformation, Struct } from "effect";
|
||||
import { ClaudeModelOptions, CodexModelOptions } from "./model";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CheckpointRef,
|
||||
@@ -44,6 +44,113 @@ export const ProviderSandboxMode = Schema.Literals([
|
||||
export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
|
||||
export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
|
||||
|
||||
export const CodexModelSelection = Schema.Struct({
|
||||
provider: Schema.Literal("codex"),
|
||||
model: TrimmedNonEmptyString,
|
||||
options: Schema.optional(CodexModelOptions),
|
||||
});
|
||||
export type CodexModelSelection = typeof CodexModelSelection.Type;
|
||||
|
||||
export const ClaudeModelSelection = Schema.Struct({
|
||||
provider: Schema.Literal("claudeAgent"),
|
||||
model: TrimmedNonEmptyString,
|
||||
options: Schema.optional(ClaudeModelOptions),
|
||||
});
|
||||
export type ClaudeModelSelection = typeof ClaudeModelSelection.Type;
|
||||
|
||||
export const ModelSelection = Schema.Union([CodexModelSelection, ClaudeModelSelection]);
|
||||
export type ModelSelection = typeof ModelSelection.Type;
|
||||
const decodeModelSelectionSync = Schema.decodeUnknownSync(ModelSelection);
|
||||
|
||||
const LegacyDefaultModelSelectionFields = {
|
||||
defaultProvider: Schema.optional(ProviderKind),
|
||||
defaultModel: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
defaultModelOptions: Schema.optional(Schema.NullOr(Schema.Unknown)),
|
||||
} as const;
|
||||
|
||||
const LegacyThreadModelSelectionFields = {
|
||||
provider: Schema.optional(ProviderKind),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
modelOptions: Schema.optional(Schema.NullOr(Schema.Unknown)),
|
||||
} as const;
|
||||
|
||||
function invalidLegacyModelSelectionIssue(
|
||||
value: unknown,
|
||||
title: string,
|
||||
cause: unknown,
|
||||
): SchemaIssue.InvalidValue {
|
||||
return new SchemaIssue.InvalidValue(Option.some(value), {
|
||||
title,
|
||||
...(Schema.isSchemaError(cause)
|
||||
? { description: SchemaIssue.makeFormatterDefault()(cause.issue) }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
type LegacyDefaultModelSelectionInput = {
|
||||
readonly defaultModelSelection?: ModelSelection | null | undefined;
|
||||
readonly defaultProvider?: ProviderKind | undefined;
|
||||
readonly defaultModel?: string | null | undefined;
|
||||
readonly defaultModelOptions?: unknown | null | undefined;
|
||||
};
|
||||
|
||||
type LegacyThreadModelSelectionInput = {
|
||||
readonly modelSelection?: ModelSelection | undefined;
|
||||
readonly provider?: ProviderKind | undefined;
|
||||
readonly model?: string | undefined;
|
||||
readonly modelOptions?: unknown | null | undefined;
|
||||
};
|
||||
|
||||
function normalizeLegacyDefaultModelSelection(
|
||||
input: LegacyDefaultModelSelectionInput,
|
||||
): Effect.Effect<ModelSelection | null, SchemaIssue.InvalidValue> {
|
||||
if (input.defaultModelSelection !== undefined) {
|
||||
return Effect.succeed(input.defaultModelSelection);
|
||||
}
|
||||
if (input.defaultModel === undefined || input.defaultModel === null) {
|
||||
return Effect.succeed(null);
|
||||
}
|
||||
return Effect.try({
|
||||
try: () =>
|
||||
decodeModelSelectionSync({
|
||||
provider: input.defaultProvider ?? DEFAULT_PROVIDER_KIND,
|
||||
model: input.defaultModel,
|
||||
...(input.defaultModelOptions != null ? { options: input.defaultModelOptions } : {}),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
invalidLegacyModelSelectionIssue(
|
||||
input,
|
||||
"Invalid legacy default model selection payload",
|
||||
cause,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeLegacyThreadModelSelection(
|
||||
input: LegacyThreadModelSelectionInput,
|
||||
): Effect.Effect<ModelSelection | undefined, SchemaIssue.InvalidValue> {
|
||||
if (input.modelSelection !== undefined) {
|
||||
return Effect.succeed(input.modelSelection);
|
||||
}
|
||||
if (input.model === undefined) {
|
||||
return Effect.succeed(undefined);
|
||||
}
|
||||
return Effect.try({
|
||||
try: () =>
|
||||
decodeModelSelectionSync({
|
||||
provider: input.provider ?? DEFAULT_PROVIDER_KIND,
|
||||
model: input.model,
|
||||
...(input.modelOptions != null ? { options: input.modelOptions } : {}),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
invalidLegacyModelSelectionIssue(
|
||||
input,
|
||||
"Invalid legacy thread model selection payload",
|
||||
cause,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export const CodexProviderStartOptions = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyString),
|
||||
homePath: Schema.optional(TrimmedNonEmptyString),
|
||||
@@ -144,7 +251,7 @@ export const OrchestrationProject = Schema.Struct({
|
||||
id: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
defaultModel: Schema.NullOr(TrimmedNonEmptyString),
|
||||
defaultModelSelection: Schema.NullOr(ModelSelection),
|
||||
scripts: Schema.Array(ProjectScript),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
@@ -273,7 +380,7 @@ export const OrchestrationThread = Schema.Struct({
|
||||
id: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
model: TrimmedNonEmptyString,
|
||||
modelSelection: ModelSelection,
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
@@ -306,7 +413,7 @@ export const ProjectCreateCommand = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
defaultModel: Schema.optional(TrimmedNonEmptyString),
|
||||
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
@@ -316,7 +423,7 @@ const ProjectMetaUpdateCommand = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
|
||||
defaultModel: Schema.optional(TrimmedNonEmptyString),
|
||||
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
|
||||
scripts: Schema.optional(Schema.Array(ProjectScript)),
|
||||
});
|
||||
|
||||
@@ -332,7 +439,7 @@ const ThreadCreateCommand = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
model: TrimmedNonEmptyString,
|
||||
modelSelection: ModelSelection,
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
@@ -353,7 +460,7 @@ const ThreadMetaUpdateCommand = Schema.Struct({
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
});
|
||||
@@ -384,9 +491,7 @@ export const ThreadTurnStartCommand = Schema.Struct({
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(ChatAttachment),
|
||||
}),
|
||||
provider: Schema.optional(ProviderKind),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
modelOptions: Schema.optional(ProviderModelOptions),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
providerOptions: Schema.optional(ProviderStartOptions),
|
||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
||||
@@ -407,9 +512,7 @@ const ClientThreadTurnStartCommand = Schema.Struct({
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(UploadChatAttachment),
|
||||
}),
|
||||
provider: Schema.optional(ProviderKind),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
modelOptions: Schema.optional(ProviderModelOptions),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
providerOptions: Schema.optional(ProviderStartOptions),
|
||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||
runtimeMode: RuntimeMode,
|
||||
@@ -606,35 +709,122 @@ export const OrchestrationAggregateKind = Schema.Literals(["project", "thread"])
|
||||
export type OrchestrationAggregateKind = typeof OrchestrationAggregateKind.Type;
|
||||
export const OrchestrationActorKind = Schema.Literals(["client", "server", "provider"]);
|
||||
|
||||
export const ProjectCreatedPayload = Schema.Struct({
|
||||
const ProjectCreatedPayloadCanonical = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
defaultModel: Schema.NullOr(TrimmedNonEmptyString),
|
||||
defaultModelSelection: Schema.NullOr(ModelSelection),
|
||||
scripts: Schema.Array(ProjectScript),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
const ProjectCreatedPayloadSource = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
|
||||
...LegacyDefaultModelSelectionFields,
|
||||
scripts: Schema.Array(ProjectScript),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ProjectCreatedPayloadSource = typeof ProjectCreatedPayloadSource.Type;
|
||||
export const ProjectCreatedPayload = ProjectCreatedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ProjectCreatedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input) =>
|
||||
normalizeLegacyDefaultModelSelection(input).pipe(
|
||||
Effect.map((defaultModelSelection) => ({
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
defaultModelSelection,
|
||||
scripts: input.scripts,
|
||||
createdAt: input.createdAt,
|
||||
updatedAt: input.updatedAt,
|
||||
})),
|
||||
),
|
||||
encode: (canonical) =>
|
||||
Effect.succeed({
|
||||
projectId: canonical.projectId,
|
||||
title: canonical.title,
|
||||
workspaceRoot: canonical.workspaceRoot,
|
||||
defaultModelSelection: canonical.defaultModelSelection,
|
||||
scripts: canonical.scripts,
|
||||
createdAt: canonical.createdAt,
|
||||
updatedAt: canonical.updatedAt,
|
||||
} as ProjectCreatedPayloadSource),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const ProjectMetaUpdatedPayload = Schema.Struct({
|
||||
const ProjectMetaUpdatedPayloadCanonical = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
|
||||
defaultModel: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
|
||||
scripts: Schema.optional(Schema.Array(ProjectScript)),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ProjectMetaUpdatedPayloadCanonical = typeof ProjectMetaUpdatedPayloadCanonical.Type;
|
||||
const ProjectMetaUpdatedPayloadSource = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
|
||||
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
|
||||
...LegacyDefaultModelSelectionFields,
|
||||
scripts: Schema.optional(Schema.Array(ProjectScript)),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ProjectMetaUpdatedPayloadSource = typeof ProjectMetaUpdatedPayloadSource.Type;
|
||||
export const ProjectMetaUpdatedPayload = ProjectMetaUpdatedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ProjectMetaUpdatedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input: ProjectMetaUpdatedPayloadSource) =>
|
||||
normalizeLegacyDefaultModelSelection(input).pipe(
|
||||
Effect.map((defaultModelSelection) => ({
|
||||
projectId: input.projectId,
|
||||
...(input.title !== undefined ? { title: input.title } : {}),
|
||||
...(input.workspaceRoot !== undefined ? { workspaceRoot: input.workspaceRoot } : {}),
|
||||
...(input.defaultModelSelection !== undefined ||
|
||||
input.defaultModel !== undefined ||
|
||||
input.defaultProvider !== undefined ||
|
||||
input.defaultModelOptions !== undefined
|
||||
? { defaultModelSelection }
|
||||
: {}),
|
||||
...(input.scripts !== undefined ? { scripts: input.scripts } : {}),
|
||||
updatedAt: input.updatedAt,
|
||||
})),
|
||||
),
|
||||
encode: (canonical: ProjectMetaUpdatedPayloadCanonical) =>
|
||||
Effect.succeed({
|
||||
projectId: canonical.projectId,
|
||||
...(canonical.title !== undefined ? { title: canonical.title } : {}),
|
||||
...(canonical.workspaceRoot !== undefined
|
||||
? { workspaceRoot: canonical.workspaceRoot }
|
||||
: {}),
|
||||
...(canonical.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: canonical.defaultModelSelection }
|
||||
: {}),
|
||||
...(canonical.scripts !== undefined ? { scripts: canonical.scripts } : {}),
|
||||
updatedAt: canonical.updatedAt,
|
||||
} as ProjectMetaUpdatedPayloadSource),
|
||||
} as any),
|
||||
),
|
||||
);
|
||||
|
||||
export const ProjectDeletedPayload = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
deletedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadCreatedPayload = Schema.Struct({
|
||||
const ThreadCreatedPayloadCanonical = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
model: TrimmedNonEmptyString,
|
||||
modelSelection: ModelSelection,
|
||||
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
@@ -644,20 +834,119 @@ export const ThreadCreatedPayload = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
const ThreadCreatedPayloadSource = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
...LegacyThreadModelSelectionFields,
|
||||
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
),
|
||||
branch: Schema.NullOr(TrimmedNonEmptyString),
|
||||
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ThreadCreatedPayloadSource = typeof ThreadCreatedPayloadSource.Type;
|
||||
export const ThreadCreatedPayload = ThreadCreatedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ThreadCreatedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input) =>
|
||||
normalizeLegacyThreadModelSelection(input).pipe(
|
||||
Effect.flatMap((modelSelection) =>
|
||||
modelSelection === undefined
|
||||
? Effect.fail(
|
||||
new SchemaIssue.InvalidValue(Option.some(input), {
|
||||
title: "Legacy thread.created payload is missing a model selection",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({
|
||||
threadId: input.threadId,
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
branch: input.branch,
|
||||
worktreePath: input.worktreePath,
|
||||
createdAt: input.createdAt,
|
||||
updatedAt: input.updatedAt,
|
||||
}),
|
||||
),
|
||||
),
|
||||
encode: (canonical) =>
|
||||
Effect.succeed({
|
||||
threadId: canonical.threadId,
|
||||
projectId: canonical.projectId,
|
||||
title: canonical.title,
|
||||
modelSelection: canonical.modelSelection,
|
||||
runtimeMode: canonical.runtimeMode,
|
||||
interactionMode: canonical.interactionMode,
|
||||
branch: canonical.branch,
|
||||
worktreePath: canonical.worktreePath,
|
||||
createdAt: canonical.createdAt,
|
||||
updatedAt: canonical.updatedAt,
|
||||
} as ThreadCreatedPayloadSource),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const ThreadDeletedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
deletedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadMetaUpdatedPayload = Schema.Struct({
|
||||
const ThreadMetaUpdatedPayloadCanonical = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ThreadMetaUpdatedPayloadCanonical = typeof ThreadMetaUpdatedPayloadCanonical.Type;
|
||||
const ThreadMetaUpdatedPayloadSource = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
...LegacyThreadModelSelectionFields,
|
||||
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ThreadMetaUpdatedPayloadSource = typeof ThreadMetaUpdatedPayloadSource.Type;
|
||||
export const ThreadMetaUpdatedPayload = ThreadMetaUpdatedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ThreadMetaUpdatedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input: ThreadMetaUpdatedPayloadSource) =>
|
||||
normalizeLegacyThreadModelSelection(input).pipe(
|
||||
Effect.map((modelSelection) => ({
|
||||
threadId: input.threadId,
|
||||
...(input.title !== undefined ? { title: input.title } : {}),
|
||||
...(modelSelection !== undefined ? { modelSelection } : {}),
|
||||
...(input.branch !== undefined ? { branch: input.branch } : {}),
|
||||
...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
|
||||
updatedAt: input.updatedAt,
|
||||
})),
|
||||
),
|
||||
encode: (canonical: ThreadMetaUpdatedPayloadCanonical) =>
|
||||
Effect.succeed({
|
||||
threadId: canonical.threadId,
|
||||
...(canonical.title !== undefined ? { title: canonical.title } : {}),
|
||||
...(canonical.modelSelection !== undefined
|
||||
? { modelSelection: canonical.modelSelection }
|
||||
: {}),
|
||||
...(canonical.branch !== undefined ? { branch: canonical.branch } : {}),
|
||||
...(canonical.worktreePath !== undefined ? { worktreePath: canonical.worktreePath } : {}),
|
||||
updatedAt: canonical.updatedAt,
|
||||
} as ThreadMetaUpdatedPayloadSource),
|
||||
} as any),
|
||||
),
|
||||
);
|
||||
|
||||
export const ThreadRuntimeModeSetPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
@@ -685,12 +974,10 @@ export const ThreadMessageSentPayload = Schema.Struct({
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadTurnStartRequestedPayload = Schema.Struct({
|
||||
const ThreadTurnStartRequestedPayloadCanonical = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
provider: Schema.optional(ProviderKind),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
modelOptions: Schema.optional(ProviderModelOptions),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
providerOptions: Schema.optional(ProviderStartOptions),
|
||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
||||
@@ -700,6 +987,70 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
|
||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
type ThreadTurnStartRequestedPayloadCanonical =
|
||||
typeof ThreadTurnStartRequestedPayloadCanonical.Type;
|
||||
const ThreadTurnStartRequestedPayloadSource = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
...LegacyThreadModelSelectionFields,
|
||||
providerOptions: Schema.optional(ProviderStartOptions),
|
||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
),
|
||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
type ThreadTurnStartRequestedPayloadSource = typeof ThreadTurnStartRequestedPayloadSource.Type;
|
||||
export const ThreadTurnStartRequestedPayload = ThreadTurnStartRequestedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ThreadTurnStartRequestedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input: ThreadTurnStartRequestedPayloadSource) =>
|
||||
normalizeLegacyThreadModelSelection(input).pipe(
|
||||
Effect.map((modelSelection) => ({
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
...(modelSelection !== undefined ? { modelSelection } : {}),
|
||||
...(input.providerOptions !== undefined
|
||||
? { providerOptions: input.providerOptions }
|
||||
: {}),
|
||||
...(input.assistantDeliveryMode !== undefined
|
||||
? { assistantDeliveryMode: input.assistantDeliveryMode }
|
||||
: {}),
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
...(input.sourceProposedPlan !== undefined
|
||||
? { sourceProposedPlan: input.sourceProposedPlan }
|
||||
: {}),
|
||||
createdAt: input.createdAt,
|
||||
})),
|
||||
),
|
||||
encode: (canonical: ThreadTurnStartRequestedPayloadCanonical) =>
|
||||
Effect.succeed({
|
||||
threadId: canonical.threadId,
|
||||
messageId: canonical.messageId,
|
||||
...(canonical.modelSelection !== undefined
|
||||
? { modelSelection: canonical.modelSelection }
|
||||
: {}),
|
||||
...(canonical.providerOptions !== undefined
|
||||
? { providerOptions: canonical.providerOptions }
|
||||
: {}),
|
||||
...(canonical.assistantDeliveryMode !== undefined
|
||||
? { assistantDeliveryMode: canonical.assistantDeliveryMode }
|
||||
: {}),
|
||||
runtimeMode: canonical.runtimeMode,
|
||||
interactionMode: canonical.interactionMode,
|
||||
...(canonical.sourceProposedPlan !== undefined
|
||||
? { sourceProposedPlan: canonical.sourceProposedPlan }
|
||||
: {}),
|
||||
createdAt: canonical.createdAt,
|
||||
} as ThreadTurnStartRequestedPayloadSource),
|
||||
} as any),
|
||||
),
|
||||
);
|
||||
|
||||
export const ThreadTurnInterruptRequestedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
|
||||
@@ -95,6 +95,30 @@ it.effect("accepts typed websocket push envelopes with sequence", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts git.actionProgress push envelopes", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeWsResponse({
|
||||
type: "push",
|
||||
sequence: 3,
|
||||
channel: WS_CHANNELS.gitActionProgress,
|
||||
data: {
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
kind: "phase_started",
|
||||
phase: "commit",
|
||||
label: "Committing...",
|
||||
},
|
||||
});
|
||||
|
||||
if (!("type" in parsed) || parsed.type !== "push") {
|
||||
assert.fail("expected websocket response to decode as a push envelope");
|
||||
}
|
||||
|
||||
assert.strictEqual(parsed.channel, WS_CHANNELS.gitActionProgress);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects push envelopes when channel payload does not match the channel schema", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* Effect.exit(
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
OrchestrationReplayEventsInput,
|
||||
} from "./orchestration";
|
||||
import {
|
||||
GitActionProgressEvent,
|
||||
GitCheckoutInput,
|
||||
GitCreateBranchInput,
|
||||
GitPreparePullRequestThreadInput,
|
||||
@@ -80,6 +81,7 @@ export const WS_METHODS = {
|
||||
// ── Push Event Channels ──────────────────────────────────────────────
|
||||
|
||||
export const WS_CHANNELS = {
|
||||
gitActionProgress: "git.actionProgress",
|
||||
terminalEvent: "terminal.event",
|
||||
serverWelcome: "server.welcome",
|
||||
serverConfigUpdated: "server.configUpdated",
|
||||
@@ -172,6 +174,7 @@ export type WsWelcomePayload = typeof WsWelcomePayload.Type;
|
||||
export interface WsPushPayloadByChannel {
|
||||
readonly [WS_CHANNELS.serverWelcome]: WsWelcomePayload;
|
||||
readonly [WS_CHANNELS.serverConfigUpdated]: typeof ServerConfigUpdatedPayload.Type;
|
||||
readonly [WS_CHANNELS.gitActionProgress]: typeof GitActionProgressEvent.Type;
|
||||
readonly [WS_CHANNELS.terminalEvent]: typeof TerminalEvent.Type;
|
||||
readonly [ORCHESTRATION_WS_CHANNELS.domainEvent]: OrchestrationEvent;
|
||||
}
|
||||
@@ -195,6 +198,10 @@ export const WsPushServerConfigUpdated = makeWsPushSchema(
|
||||
WS_CHANNELS.serverConfigUpdated,
|
||||
ServerConfigUpdatedPayload,
|
||||
);
|
||||
export const WsPushGitActionProgress = makeWsPushSchema(
|
||||
WS_CHANNELS.gitActionProgress,
|
||||
GitActionProgressEvent,
|
||||
);
|
||||
export const WsPushTerminalEvent = makeWsPushSchema(WS_CHANNELS.terminalEvent, TerminalEvent);
|
||||
export const WsPushOrchestrationDomainEvent = makeWsPushSchema(
|
||||
ORCHESTRATION_WS_CHANNELS.domainEvent,
|
||||
@@ -202,6 +209,7 @@ export const WsPushOrchestrationDomainEvent = makeWsPushSchema(
|
||||
);
|
||||
|
||||
export const WsPushChannelSchema = Schema.Literals([
|
||||
WS_CHANNELS.gitActionProgress,
|
||||
WS_CHANNELS.serverWelcome,
|
||||
WS_CHANNELS.serverConfigUpdated,
|
||||
WS_CHANNELS.terminalEvent,
|
||||
@@ -212,6 +220,7 @@ export type WsPushChannelSchema = typeof WsPushChannelSchema.Type;
|
||||
export const WsPush = Schema.Union([
|
||||
WsPushServerWelcome,
|
||||
WsPushServerConfigUpdated,
|
||||
WsPushGitActionProgress,
|
||||
WsPushTerminalEvent,
|
||||
WsPushOrchestrationDomainEvent,
|
||||
]);
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
getDefaultReasoningEffort,
|
||||
getModelOptions,
|
||||
getReasoningEffortOptions,
|
||||
inferProviderForModel,
|
||||
isClaudeUltrathinkPrompt,
|
||||
normalizeClaudeModelOptions,
|
||||
normalizeCodexModelOptions,
|
||||
@@ -188,23 +187,6 @@ describe("getReasoningEffortOptions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("inferProviderForModel", () => {
|
||||
it("detects known provider model slugs", () => {
|
||||
expect(inferProviderForModel("gpt-5.3-codex")).toBe("codex");
|
||||
expect(inferProviderForModel("claude-sonnet-4-6")).toBe("claudeAgent");
|
||||
expect(inferProviderForModel("sonnet")).toBe("claudeAgent");
|
||||
});
|
||||
|
||||
it("falls back when the model is unknown", () => {
|
||||
expect(inferProviderForModel("custom/internal-model")).toBe("codex");
|
||||
expect(inferProviderForModel("custom/internal-model", "claudeAgent")).toBe("claudeAgent");
|
||||
});
|
||||
|
||||
it("treats claude-prefixed custom slugs as claude", () => {
|
||||
expect(inferProviderForModel("claude-custom-internal")).toBe("claudeAgent");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getDefaultReasoningEffort", () => {
|
||||
it("returns provider-scoped defaults", () => {
|
||||
expect(getDefaultReasoningEffort("codex")).toBe(DEFAULT_REASONING_EFFORT_BY_PROVIDER.codex);
|
||||
|
||||
@@ -136,23 +136,6 @@ export function resolveModelSlugForProvider(
|
||||
return resolveModelSlug(model, provider);
|
||||
}
|
||||
|
||||
export function inferProviderForModel(
|
||||
model: string | null | undefined,
|
||||
fallback: ProviderKind = "codex",
|
||||
): ProviderKind {
|
||||
const normalizedClaude = normalizeModelSlug(model, "claudeAgent");
|
||||
if (normalizedClaude && MODEL_SLUG_SET_BY_PROVIDER.claudeAgent.has(normalizedClaude)) {
|
||||
return "claudeAgent";
|
||||
}
|
||||
|
||||
const normalizedCodex = normalizeModelSlug(model, "codex");
|
||||
if (normalizedCodex && MODEL_SLUG_SET_BY_PROVIDER.codex.has(normalizedCodex)) {
|
||||
return "codex";
|
||||
}
|
||||
|
||||
return typeof model === "string" && model.trim().startsWith("claude-") ? "claudeAgent" : fallback;
|
||||
}
|
||||
|
||||
export function getReasoningEffortOptions(provider: "codex"): ReadonlyArray<CodexReasoningEffort>;
|
||||
export function getReasoningEffortOptions(
|
||||
provider: "claudeAgent",
|
||||
|
||||
Reference in new issue
Block a user