Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42afbb2266 | ||
|
|
775794743d | ||
|
|
b4b3b2b636 | ||
|
|
53726680e4 | ||
|
|
19f09b7ba1 | ||
|
|
57ff0ae390 | ||
|
|
6715932142 | ||
|
|
619fd2027c | ||
|
|
c91bd26b3c | ||
|
|
da0eaff9d4 | ||
|
|
7b0c9c0a9d | ||
|
|
007bd1755e | ||
|
|
5b750e2b1e | ||
|
|
d6099ed9ca | ||
|
|
69e5d81ef6 | ||
|
|
14e81b90b6 | ||
|
|
f942c3484a | ||
|
|
a9aa5c4a05 | ||
|
|
3f089a454b | ||
|
|
b225dfaf77 |
No files matched your search
@@ -1,2 +0,0 @@
|
||||
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
|
||||
* text=auto eol=lf
|
||||
@@ -124,49 +124,25 @@ jobs:
|
||||
group: pr-size-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
steps:
|
||||
- name: Checkout base repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Sync PR size label
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
|
||||
with:
|
||||
script: |
|
||||
const { execFileSync } = require("node:child_process");
|
||||
|
||||
const issueNumber = context.payload.pull_request.number;
|
||||
const baseSha = context.payload.pull_request.base.sha;
|
||||
const headSha = context.payload.pull_request.head.sha;
|
||||
const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`;
|
||||
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 testExcludePathspecs = [
|
||||
":(glob,exclude)**/__tests__/**",
|
||||
":(glob,exclude)**/test/**",
|
||||
":(glob,exclude)**/tests/**",
|
||||
":(glob,exclude)apps/server/integration/**",
|
||||
":(glob,exclude)**/*.test.*",
|
||||
":(glob,exclude)**/*.spec.*",
|
||||
":(glob,exclude)**/*.browser.*",
|
||||
":(glob,exclude)**/*.integration.*",
|
||||
const testFilePatterns = [
|
||||
/(^|\/)__tests__(\/|$)/,
|
||||
/(^|\/)tests?(\/|$)/,
|
||||
/^apps\/server\/integration\//,
|
||||
/\.(test|spec|browser|integration)\.[^.\/]+$/,
|
||||
];
|
||||
|
||||
const sumNumstat = (text) =>
|
||||
text
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.reduce((total, line) => {
|
||||
const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t");
|
||||
const additions =
|
||||
insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0;
|
||||
const deletions =
|
||||
deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0;
|
||||
|
||||
return total + additions + deletions;
|
||||
}, 0);
|
||||
const isTestFile = (filename) =>
|
||||
testFilePatterns.some((pattern) => pattern.test(filename));
|
||||
|
||||
const resolveSizeLabel = (totalChangedLines) => {
|
||||
if (totalChangedLines < 10) {
|
||||
@@ -192,53 +168,40 @@ jobs:
|
||||
return "size:XXL";
|
||||
};
|
||||
|
||||
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
execFileSync(
|
||||
"git",
|
||||
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
|
||||
const files = await github.paginate(
|
||||
github.rest.pulls.listFiles,
|
||||
{
|
||||
stdio: "inherit",
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: issueNumber,
|
||||
per_page: 100,
|
||||
},
|
||||
(response) => response.data,
|
||||
);
|
||||
|
||||
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
|
||||
if (resolvedHeadSha !== headSha) {
|
||||
if (files.length >= 3000) {
|
||||
core.warning(
|
||||
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
|
||||
"The GitHub pull request files API may truncate results at 3,000 files; PR size may be undercounted.",
|
||||
);
|
||||
}
|
||||
|
||||
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
let testChangedLines = 0;
|
||||
let nonTestChangedLines = 0;
|
||||
|
||||
const diffArgs = [
|
||||
"diff",
|
||||
"--numstat",
|
||||
"--ignore-all-space",
|
||||
"--ignore-blank-lines",
|
||||
`${baseSha}...${resolvedHeadSha}`,
|
||||
];
|
||||
for (const file of files) {
|
||||
const changedLinesForFile = (file.additions ?? 0) + (file.deletions ?? 0);
|
||||
|
||||
const totalChangedLines = sumNumstat(
|
||||
execFileSync(
|
||||
"git",
|
||||
diffArgs,
|
||||
{ encoding: "utf8" },
|
||||
),
|
||||
);
|
||||
const nonTestChangedLines = sumNumstat(
|
||||
execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], {
|
||||
encoding: "utf8",
|
||||
}),
|
||||
);
|
||||
const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines);
|
||||
if (changedLinesForFile === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isTestFile(file.filename)) {
|
||||
testChangedLines += changedLinesForFile;
|
||||
continue;
|
||||
}
|
||||
|
||||
nonTestChangedLines += changedLinesForFile;
|
||||
}
|
||||
|
||||
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
|
||||
const nextLabelName = resolveSizeLabel(changedLines);
|
||||
|
||||
@@ -12,7 +12,6 @@ packages/*/dist
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
release-mock/
|
||||
.t3
|
||||
.idea/
|
||||
apps/web/.playwright
|
||||
|
||||
@@ -287,12 +287,10 @@ let updatePollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let updateStartupTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let updateCheckInFlight = false;
|
||||
let updateDownloadInFlight = false;
|
||||
let updateInstallInFlight = false;
|
||||
let updaterConfigured = false;
|
||||
let updateState: DesktopUpdateState = initialUpdateState();
|
||||
|
||||
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
|
||||
if (updateInstallInFlight) return "install";
|
||||
if (updateDownloadInFlight) return "download";
|
||||
if (updateCheckInFlight) return "check";
|
||||
return updateState.errorContext;
|
||||
@@ -809,22 +807,13 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
|
||||
}
|
||||
|
||||
isQuitting = true;
|
||||
updateInstallInFlight = true;
|
||||
clearUpdatePollTimer();
|
||||
try {
|
||||
await stopBackendAndWaitForExit();
|
||||
// Destroy all windows before launching the NSIS installer to avoid the installer finding live windows it needs to close.
|
||||
for (const win of BrowserWindow.getAllWindows()) {
|
||||
win.destroy();
|
||||
}
|
||||
// `quitAndInstall()` only starts the handoff to the updater. The actual
|
||||
// install may still fail asynchronously, so keep the action incomplete
|
||||
// until we either quit or receive an updater error.
|
||||
autoUpdater.quitAndInstall(true, true);
|
||||
return { accepted: true, completed: false };
|
||||
autoUpdater.quitAndInstall();
|
||||
return { accepted: true, completed: true };
|
||||
} catch (error: unknown) {
|
||||
const message = formatErrorMessage(error);
|
||||
updateInstallInFlight = false;
|
||||
isQuitting = false;
|
||||
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
||||
console.error(`[desktop-updater] Failed to install update: ${message}`);
|
||||
@@ -861,13 +850,6 @@ function configureAutoUpdater(): void {
|
||||
}
|
||||
}
|
||||
|
||||
if (process.env.T3CODE_DESKTOP_MOCK_UPDATES) {
|
||||
autoUpdater.setFeedURL({
|
||||
provider: "generic",
|
||||
url: `http://localhost:${process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000}`,
|
||||
});
|
||||
}
|
||||
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
// Keep alpha branding, but force all installs onto the stable update track.
|
||||
@@ -904,13 +886,6 @@ function configureAutoUpdater(): void {
|
||||
});
|
||||
autoUpdater.on("error", (error) => {
|
||||
const message = formatErrorMessage(error);
|
||||
if (updateInstallInFlight) {
|
||||
updateInstallInFlight = false;
|
||||
isQuitting = false;
|
||||
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
||||
console.error(`[desktop-updater] Updater error: ${message}`);
|
||||
return;
|
||||
}
|
||||
if (!updateCheckInFlight && !updateDownloadInFlight) {
|
||||
setUpdateState({
|
||||
status: "error",
|
||||
@@ -1166,7 +1141,6 @@ function registerIpcHandlers(): void {
|
||||
id: item.id,
|
||||
label: item.label,
|
||||
destructive: item.destructive === true,
|
||||
disabled: item.disabled === true,
|
||||
}));
|
||||
if (normalizedItems.length === 0) {
|
||||
return null;
|
||||
@@ -1197,7 +1171,6 @@ function registerIpcHandlers(): void {
|
||||
}
|
||||
const itemOption: MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
click: () => resolve(item.id),
|
||||
};
|
||||
if (item.destructive) {
|
||||
@@ -1386,7 +1359,6 @@ async function bootstrap(): Promise<void> {
|
||||
|
||||
app.on("before-quit", () => {
|
||||
isQuitting = true;
|
||||
updateInstallInFlight = false;
|
||||
writeDesktopLogHeader("before-quit received");
|
||||
clearUpdatePollTimer();
|
||||
stopBackend();
|
||||
@@ -1416,7 +1388,7 @@ app
|
||||
});
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin" && !isQuitting) {
|
||||
if (process.platform !== "darwin") {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -62,13 +62,14 @@ describe("syncShellEnvironment", () => {
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => {
|
||||
it("does nothing outside macOS", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
}));
|
||||
|
||||
@@ -77,29 +78,8 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS and linux", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
||||
PATH: "C:\\Windows\\System32",
|
||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/usr/local/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).not.toHaveBeenCalled();
|
||||
expect(env.PATH).toBe("C:\\Windows\\System32");
|
||||
expect(env.PATH).toBe("/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
readEnvironmentFromLoginShell,
|
||||
resolveLoginShell,
|
||||
ShellEnvironmentReader,
|
||||
} from "@t3tools/shared/shell";
|
||||
import { readEnvironmentFromLoginShell, ShellEnvironmentReader } from "@t3tools/shared/shell";
|
||||
|
||||
export function syncShellEnvironment(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
@@ -11,13 +7,10 @@ export function syncShellEnvironment(
|
||||
readEnvironment?: ShellEnvironmentReader;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
if ((options.platform ?? process.platform) !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
|
||||
const shell = env.SHELL ?? "/bin/zsh";
|
||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
|
||||
@@ -8,33 +8,10 @@ import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
|
||||
import { assertNone, assertSome } from "@effect/vitest/utils";
|
||||
|
||||
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
|
||||
|
||||
vi.mock("node:fs", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("node:fs")>();
|
||||
return {
|
||||
...actual,
|
||||
openSync: (...args: Parameters<typeof actual.openSync>) => {
|
||||
const [filePath, flags] = args;
|
||||
if (
|
||||
typeof filePath === "string" &&
|
||||
filePath === openSyncInterceptor.failPath &&
|
||||
flags === "r"
|
||||
) {
|
||||
const error = new Error("no such device or address");
|
||||
Object.assign(error, { code: "ENXIO" });
|
||||
throw error;
|
||||
}
|
||||
return (actual.openSync as (...a: typeof args) => number)(...args);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
|
||||
|
||||
it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||
@@ -70,36 +47,6 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to reading the inherited fd when path duplication fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||
|
||||
yield* fs.writeFileString(
|
||||
filePath,
|
||||
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
||||
mode: "desktop",
|
||||
})}\n`,
|
||||
);
|
||||
|
||||
// Open without acquireRelease: the direct-stream fallback uses autoClose: true,
|
||||
// so the stream owns the fd lifecycle and closes it asynchronously on end.
|
||||
// Attempting to also close it synchronously in a finalizer races with the
|
||||
// stream's async close and produces an uncaught EBADF.
|
||||
const fd = NFS.openSync(filePath, "r");
|
||||
|
||||
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
|
||||
try {
|
||||
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||
assertSome(payload, {
|
||||
mode: "desktop",
|
||||
});
|
||||
} finally {
|
||||
openSyncInterceptor.failPath = null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none when the fd is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fd = NFS.openSync("/dev/null", "r");
|
||||
|
||||
@@ -108,26 +108,21 @@ const makeBootstrapInputStream = (fd: number) =>
|
||||
try: () => {
|
||||
const fdPath = resolveFdPath(fd);
|
||||
if (fdPath === undefined) {
|
||||
return makeDirectBootstrapStream(fd);
|
||||
const stream = new Net.Socket({
|
||||
fd,
|
||||
readable: true,
|
||||
writable: false,
|
||||
});
|
||||
stream.setEncoding("utf8");
|
||||
return stream;
|
||||
}
|
||||
|
||||
let streamFd: number | undefined;
|
||||
try {
|
||||
streamFd = NFS.openSync(fdPath, "r");
|
||||
return NFS.createReadStream("", {
|
||||
fd: streamFd,
|
||||
encoding: "utf8",
|
||||
autoClose: true,
|
||||
});
|
||||
} catch (error) {
|
||||
if (isBootstrapFdPathDuplicationError(error)) {
|
||||
if (streamFd !== undefined) {
|
||||
NFS.closeSync(streamFd);
|
||||
}
|
||||
return makeDirectBootstrapStream(fd);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const streamFd = NFS.openSync(fdPath, "r");
|
||||
return NFS.createReadStream("", {
|
||||
fd: streamFd,
|
||||
encoding: "utf8",
|
||||
autoClose: true,
|
||||
});
|
||||
},
|
||||
catch: (error) =>
|
||||
new BootstrapError({
|
||||
@@ -136,29 +131,6 @@ const makeBootstrapInputStream = (fd: number) =>
|
||||
}),
|
||||
});
|
||||
|
||||
const makeDirectBootstrapStream = (fd: number): Readable => {
|
||||
try {
|
||||
return NFS.createReadStream("", {
|
||||
fd,
|
||||
encoding: "utf8",
|
||||
autoClose: true,
|
||||
});
|
||||
} catch {
|
||||
const stream = new Net.Socket({
|
||||
fd,
|
||||
readable: true,
|
||||
writable: false,
|
||||
});
|
||||
stream.setEncoding("utf8");
|
||||
return stream;
|
||||
}
|
||||
};
|
||||
|
||||
const isBootstrapFdPathDuplicationError = Predicate.compose(
|
||||
Predicate.hasProperty("code"),
|
||||
(_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM",
|
||||
);
|
||||
|
||||
export function resolveFdPath(
|
||||
fd: number,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
|
||||
@@ -61,7 +61,6 @@ function makeSnapshot(input: {
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
|
||||
@@ -207,42 +207,6 @@ describe("classifyCodexStderrLine", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("process stderr events", () => {
|
||||
it("emits classified stderr lines as notifications", () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const emitEvent = vi
|
||||
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
emitNotificationEvent: (
|
||||
context: { session: { threadId: ThreadId } },
|
||||
method: string,
|
||||
message: string,
|
||||
) => void;
|
||||
}
|
||||
).emitNotificationEvent(
|
||||
{
|
||||
session: {
|
||||
threadId: asThreadId("thread-1"),
|
||||
},
|
||||
},
|
||||
"process/stderr",
|
||||
"fatal: permission denied",
|
||||
);
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: "notification",
|
||||
method: "process/stderr",
|
||||
threadId: "thread-1",
|
||||
message: "fatal: permission denied",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeCodexModelSlug", () => {
|
||||
it("maps 5.3 aliases to gpt-5.3-codex", () => {
|
||||
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
|
||||
|
||||
@@ -1046,7 +1046,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
continue;
|
||||
}
|
||||
|
||||
this.emitNotificationEvent(context, "process/stderr", classified.message);
|
||||
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1354,22 +1354,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
private emitNotificationEvent(
|
||||
context: CodexSessionContext,
|
||||
method: string,
|
||||
message: string,
|
||||
): void {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method,
|
||||
message,
|
||||
});
|
||||
}
|
||||
|
||||
private emitEvent(event: ProviderEvent): void {
|
||||
this.emit("event", event);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ClaudeModelSelection } from "@t3tools/contracts";
|
||||
import { resolveApiModelId } from "@t3tools/shared/model";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
@@ -104,7 +103,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
"--json-schema",
|
||||
jsonSchemaStr,
|
||||
"--model",
|
||||
resolveApiModelId(modelSelection),
|
||||
modelSelection.model,
|
||||
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
|
||||
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
|
||||
"--dangerously-skip-permissions",
|
||||
|
||||
@@ -24,20 +24,7 @@ const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
function makeFakeCodexBinary(
|
||||
dir: string,
|
||||
input: {
|
||||
output: string;
|
||||
exitCode?: number;
|
||||
stderr?: string;
|
||||
requireImage?: boolean;
|
||||
requireFastServiceTier?: boolean;
|
||||
requireReasoningEffort?: string;
|
||||
forbidReasoningEffort?: boolean;
|
||||
stdinMustContain?: string;
|
||||
stdinMustNotContain?: string;
|
||||
},
|
||||
) {
|
||||
function makeFakeCodexBinary(dir: string) {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -50,16 +37,12 @@ function makeFakeCodexBinary(
|
||||
[
|
||||
"#!/bin/sh",
|
||||
'output_path=""',
|
||||
'seen_image="0"',
|
||||
'seen_fast_service_tier="0"',
|
||||
'seen_reasoning_effort=""',
|
||||
"while [ $# -gt 0 ]; do",
|
||||
' if [ "$1" = "--image" ]; then',
|
||||
" shift",
|
||||
' if [ -n "$1" ]; then',
|
||||
' seen_image="1"',
|
||||
" fi",
|
||||
" shift",
|
||||
" continue",
|
||||
" fi",
|
||||
' if [ "$1" = "--config" ]; then',
|
||||
@@ -72,80 +55,55 @@ function makeFakeCodexBinary(
|
||||
' seen_reasoning_effort="$1"',
|
||||
" ;;",
|
||||
" esac",
|
||||
" shift",
|
||||
" continue",
|
||||
" fi",
|
||||
' if [ "$1" = "--output-last-message" ]; then',
|
||||
" shift",
|
||||
' output_path="$1"',
|
||||
" shift",
|
||||
" continue",
|
||||
" fi",
|
||||
" shift",
|
||||
"done",
|
||||
'stdin_content="$(cat)"',
|
||||
...(input.requireImage
|
||||
? [
|
||||
'if [ "$seen_image" != "1" ]; then',
|
||||
' printf "%s\\n" "missing --image input" >&2',
|
||||
` exit 2`,
|
||||
"fi",
|
||||
]
|
||||
: []),
|
||||
...(input.requireFastServiceTier
|
||||
? [
|
||||
'if [ "$seen_fast_service_tier" != "1" ]; then',
|
||||
' printf "%s\\n" "missing fast service tier config" >&2',
|
||||
` exit 5`,
|
||||
"fi",
|
||||
]
|
||||
: []),
|
||||
...(input.requireReasoningEffort !== undefined
|
||||
? [
|
||||
`if [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"${input.requireReasoningEffort}\\"" ]; then`,
|
||||
' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2',
|
||||
` exit 6`,
|
||||
"fi",
|
||||
]
|
||||
: []),
|
||||
...(input.forbidReasoningEffort
|
||||
? [
|
||||
'if [ -n "$seen_reasoning_effort" ]; then',
|
||||
' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2',
|
||||
` exit 7`,
|
||||
"fi",
|
||||
]
|
||||
: []),
|
||||
...(input.stdinMustContain !== undefined
|
||||
? [
|
||||
`if ! printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustContain)} >/dev/null; then`,
|
||||
' printf "%s\\n" "stdin missing expected content" >&2',
|
||||
` exit 3`,
|
||||
"fi",
|
||||
]
|
||||
: []),
|
||||
...(input.stdinMustNotContain !== undefined
|
||||
? [
|
||||
`if printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustNotContain)} >/dev/null; then`,
|
||||
' printf "%s\\n" "stdin contained forbidden content" >&2',
|
||||
` exit 4`,
|
||||
"fi",
|
||||
]
|
||||
: []),
|
||||
...(input.stderr !== undefined
|
||||
? [`printf "%s\\n" ${JSON.stringify(input.stderr)} >&2`]
|
||||
: []),
|
||||
'if [ -n "$output_path" ]; then',
|
||||
" cat > \"$output_path\" <<'__T3CODE_FAKE_CODEX_OUTPUT__'",
|
||||
input.output,
|
||||
"__T3CODE_FAKE_CODEX_OUTPUT__",
|
||||
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
|
||||
' printf "%s\\n" "missing --image input" >&2',
|
||||
" exit 2",
|
||||
"fi",
|
||||
`exit ${input.exitCode ?? 0}`,
|
||||
'if [ "$T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER" = "1" ] && [ "$seen_fast_service_tier" != "1" ]; then',
|
||||
' printf "%s\\n" "missing fast service tier config" >&2',
|
||||
" exit 5",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT" ] && [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"$T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT\\"" ]; then',
|
||||
' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2',
|
||||
" exit 6",
|
||||
"fi",
|
||||
'if [ "$T3_FAKE_CODEX_FORBID_REASONING_EFFORT" = "1" ] && [ -n "$seen_reasoning_effort" ]; then',
|
||||
' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2',
|
||||
" exit 7",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
|
||||
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
|
||||
' printf "%s\\n" "stdin missing expected content" >&2',
|
||||
" exit 3",
|
||||
" }",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
|
||||
' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
|
||||
' printf "%s\\n" "stdin contained forbidden content" >&2',
|
||||
" exit 4",
|
||||
" fi",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
|
||||
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
|
||||
"fi",
|
||||
'if [ -n "$output_path" ]; then',
|
||||
' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"',
|
||||
"fi",
|
||||
'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fs.chmod(codexPath, 0o755);
|
||||
return codexPath;
|
||||
return binDir;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -167,29 +125,146 @@ function withFakeCodexEnv<A, E, R>(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
||||
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const previousSettings = yield* serverSettings.getSettings;
|
||||
yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: codexPath,
|
||||
},
|
||||
},
|
||||
const binDir = yield* makeFakeCodexBinary(tempDir);
|
||||
const previousPath = process.env.PATH;
|
||||
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
||||
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
|
||||
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||
const previousRequireFastServiceTier = process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER;
|
||||
const previousRequireReasoningEffort = process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT;
|
||||
const previousForbidReasoningEffort = process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT;
|
||||
const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||
const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||
|
||||
yield* Effect.sync(() => {
|
||||
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
||||
process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64");
|
||||
|
||||
if (input.exitCode !== undefined) {
|
||||
process.env.T3_FAKE_CODEX_EXIT_CODE = String(input.exitCode);
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||
}
|
||||
|
||||
if (input.stderr !== undefined) {
|
||||
process.env.T3_FAKE_CODEX_STDERR = input.stderr;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_STDERR;
|
||||
}
|
||||
|
||||
if (input.requireImage) {
|
||||
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = "1";
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||
}
|
||||
|
||||
if (input.requireFastServiceTier) {
|
||||
process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER = "1";
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER;
|
||||
}
|
||||
|
||||
if (input.requireReasoningEffort !== undefined) {
|
||||
process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT = input.requireReasoningEffort;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT;
|
||||
}
|
||||
|
||||
if (input.forbidReasoningEffort) {
|
||||
process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT = "1";
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT;
|
||||
}
|
||||
|
||||
if (input.stdinMustContain !== undefined) {
|
||||
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = input.stdinMustContain;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||
}
|
||||
|
||||
if (input.stdinMustNotContain !== undefined) {
|
||||
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = input.stdinMustNotContain;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||
}
|
||||
});
|
||||
return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };
|
||||
|
||||
return {
|
||||
previousPath,
|
||||
previousOutput,
|
||||
previousExitCode,
|
||||
previousStderr,
|
||||
previousRequireImage,
|
||||
previousRequireFastServiceTier,
|
||||
previousRequireReasoningEffort,
|
||||
previousForbidReasoningEffort,
|
||||
previousStdinMustContain,
|
||||
previousStdinMustNotContain,
|
||||
};
|
||||
}),
|
||||
() => effect,
|
||||
({ serverSettings, previousBinaryPath }) =>
|
||||
serverSettings
|
||||
.updateSettings({
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: previousBinaryPath,
|
||||
},
|
||||
},
|
||||
})
|
||||
.pipe(Effect.asVoid),
|
||||
(previous) =>
|
||||
Effect.sync(() => {
|
||||
process.env.PATH = previous.previousPath;
|
||||
|
||||
if (previous.previousOutput === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_OUTPUT_B64 = previous.previousOutput;
|
||||
}
|
||||
|
||||
if (previous.previousExitCode === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_EXIT_CODE = previous.previousExitCode;
|
||||
}
|
||||
|
||||
if (previous.previousStderr === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_STDERR;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
|
||||
}
|
||||
|
||||
if (previous.previousRequireImage === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = previous.previousRequireImage;
|
||||
}
|
||||
|
||||
if (previous.previousRequireFastServiceTier === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER =
|
||||
previous.previousRequireFastServiceTier;
|
||||
}
|
||||
|
||||
if (previous.previousRequireReasoningEffort === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT =
|
||||
previous.previousRequireReasoningEffort;
|
||||
}
|
||||
|
||||
if (previous.previousForbidReasoningEffort === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT =
|
||||
previous.previousForbidReasoningEffort;
|
||||
}
|
||||
|
||||
if (previous.previousStdinMustContain === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
|
||||
}
|
||||
|
||||
if (previous.previousStdinMustNotContain === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = previous.previousStdinMustNotContain;
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -415,9 +415,6 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
|
||||
it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
|
||||
Effect.gen(function* () {
|
||||
const services = yield* Effect.services();
|
||||
const runPromise = Effect.runPromiseWith(services);
|
||||
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
const clone = yield* makeTmpDir();
|
||||
@@ -452,7 +449,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
const core = yield* GitCore;
|
||||
yield* Effect.promise(() =>
|
||||
vi.waitFor(async () => {
|
||||
const details = await runPromise(core.statusDetails(source));
|
||||
const details = await Effect.runPromise(core.statusDetails(source));
|
||||
expect(details.branch).toBe(featureBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
|
||||
@@ -674,7 +674,6 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
|
||||
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||
Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)),
|
||||
Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
|
||||
@@ -6,6 +6,7 @@ import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Command from "effect/unstable/cli/Command";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
import { beforeEach } from "vitest";
|
||||
@@ -16,12 +17,12 @@ import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
|
||||
import { Server, type ServerShape } from "./wsServer";
|
||||
import { ServerSettingsService } from "./serverSettings";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings";
|
||||
|
||||
const start = vi.fn(() => undefined);
|
||||
const stop = vi.fn(() => undefined);
|
||||
const fixPath = vi.fn(() => undefined);
|
||||
let resolvedConfig: ServerConfigShape | null = null;
|
||||
const serverStart = Effect.acquireRelease(
|
||||
Effect.gen(function* () {
|
||||
@@ -37,7 +38,7 @@ const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred)
|
||||
const testLayer = Layer.mergeAll(
|
||||
Layer.succeed(CliConfig, {
|
||||
cwd: "/tmp/t3-test-workspace",
|
||||
fixPath: Effect.sync(fixPath),
|
||||
fixPath: Effect.void,
|
||||
resolveStaticDir: Effect.undefined,
|
||||
} satisfies CliConfigShape),
|
||||
Layer.succeed(NetService, {
|
||||
@@ -54,7 +55,13 @@ const testLayer = Layer.mergeAll(
|
||||
openBrowser: (_target: string) => Effect.void,
|
||||
openInEditor: () => Effect.void,
|
||||
} satisfies OpenShape),
|
||||
ServerSettingsService.layerTest(),
|
||||
Layer.succeed(ServerSettingsService, {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
|
||||
updateSettings: () => Effect.succeed(DEFAULT_SERVER_SETTINGS),
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsShape),
|
||||
AnalyticsService.layerTest,
|
||||
FetchHttpClient.layer,
|
||||
NodeServices.layer,
|
||||
@@ -82,7 +89,6 @@ beforeEach(() => {
|
||||
resolvedConfig = null;
|
||||
start.mockImplementation(() => undefined);
|
||||
stop.mockImplementation(() => undefined);
|
||||
fixPath.mockImplementation(() => undefined);
|
||||
findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred));
|
||||
});
|
||||
|
||||
@@ -331,21 +337,6 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("hydrates PATH before server startup", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([]);
|
||||
|
||||
assert.equal(fixPath.mock.calls.length, 1);
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
const fixPathOrder = fixPath.mock.invocationCallOrder[0];
|
||||
const startOrder = start.mock.invocationCallOrder[0];
|
||||
if (typeof fixPathOrder !== "number" || typeof startOrder !== "number") {
|
||||
assert.fail("Expected fixPath and start to be called");
|
||||
}
|
||||
assert.isTrue(fixPathOrder < startOrder);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records a startup heartbeat with thread/project counts", () =>
|
||||
Effect.gen(function* () {
|
||||
const recordTelemetry = vi.fn(
|
||||
@@ -385,7 +376,7 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
|
||||
it.effect("does not start server for invalid --mode values", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--mode", "invalid"]).pipe(Effect.catch(() => Effect.void));
|
||||
yield* runCli(["--mode", "invalid"]);
|
||||
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
assert.equal(stop.mock.calls.length, 0);
|
||||
@@ -403,7 +394,7 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
|
||||
it.effect("does not start server for out-of-range --port values", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--port", "70000"]).pipe(Effect.catch(() => Effect.void));
|
||||
yield* runCli(["--port", "70000"]);
|
||||
|
||||
// effect/unstable/cli renders help/errors for parse failures and returns success.
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
|
||||
@@ -40,24 +40,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLaunch, {
|
||||
command: "code-insiders",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodiumLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLaunch, {
|
||||
command: "codium",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const zedLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
"darwin",
|
||||
@@ -98,24 +80,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLineAndColumn, {
|
||||
command: "code-insiders",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLineAndColumn, {
|
||||
command: "codium",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
"darwin",
|
||||
@@ -256,14 +220,13 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
|
||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "cursor.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
|
||||
assert.deepEqual(editors, ["cursor", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -39,8 +39,10 @@ interface CommandAvailabilityOptions {
|
||||
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
|
||||
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
|
||||
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
|
||||
return (
|
||||
(editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target)
|
||||
);
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
@@ -211,7 +213,7 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
}
|
||||
|
||||
if (editorDef.command) {
|
||||
return shouldUseGotoFlag(editorDef, input.cwd)
|
||||
return shouldUseGotoFlag(editorDef.id, input.cwd)
|
||||
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
||||
: { command: editorDef.command, args: [input.cwd] };
|
||||
}
|
||||
|
||||
@@ -120,73 +120,6 @@ describe("OrchestrationEngine", () => {
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("archives and unarchives threads through orchestration commands", async () => {
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
const createdAt = now();
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-archive-create"),
|
||||
projectId: asProjectId("project-archive"),
|
||||
title: "Project Archive",
|
||||
workspaceRoot: "/tmp/project-archive",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-archive-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
||||
projectId: asProjectId("project-archive"),
|
||||
title: "Archive me",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-archive"),
|
||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
(await system.run(engine.getReadModel())).threads.find(
|
||||
(thread) => thread.id === "thread-archive",
|
||||
)?.archivedAt,
|
||||
).not.toBeNull();
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.unarchive",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-unarchive"),
|
||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
(await system.run(engine.getReadModel())).threads.find(
|
||||
(thread) => thread.id === "thread-archive",
|
||||
)?.archivedAt,
|
||||
).toBeNull();
|
||||
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("replays append-only events from sequence", async () => {
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
|
||||
@@ -428,41 +428,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
latestTurnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
});
|
||||
return;
|
||||
|
||||
case "thread.archived": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
archivedAt: event.payload.archivedAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.unarchived": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
archivedAt: null,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.meta-updated": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
|
||||
@@ -279,7 +279,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
},
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
|
||||
@@ -174,7 +174,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
ORDER BY created_at ASC, thread_id ASC
|
||||
@@ -561,7 +560,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
|
||||
@@ -424,39 +424,48 @@ const make = Effect.gen(function* () {
|
||||
const oldBranch = input.branch;
|
||||
const cwd = input.worktreePath;
|
||||
const attachments = input.attachments ?? [];
|
||||
yield* Effect.gen(function* () {
|
||||
const { textGenerationModelSelection: modelSelection } =
|
||||
yield* serverSettingsService.getSettings;
|
||||
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd,
|
||||
message: input.messageText,
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
modelSelection,
|
||||
});
|
||||
if (!generated) return;
|
||||
modelSelection: yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.textGenerationModelSelection,
|
||||
),
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
"provider command reactor failed to generate worktree branch name; skipping rename",
|
||||
{ threadId: input.threadId, cwd, oldBranch, reason: error.message },
|
||||
),
|
||||
),
|
||||
Effect.flatMap((generated) => {
|
||||
if (!generated) return Effect.void;
|
||||
|
||||
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
||||
if (targetBranch === oldBranch) return;
|
||||
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
||||
if (targetBranch === oldBranch) return Effect.void;
|
||||
|
||||
const renamed = yield* git.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: serverCommandId("worktree-branch-rename"),
|
||||
threadId: input.threadId,
|
||||
branch: renamed.branch,
|
||||
worktreePath: cwd,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
|
||||
threadId: input.threadId,
|
||||
cwd,
|
||||
oldBranch,
|
||||
cause: Cause.pretty(cause),
|
||||
return Effect.flatMap(
|
||||
git.renameBranch({ cwd, oldBranch, newBranch: targetBranch }),
|
||||
(renamed) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: serverCommandId("worktree-branch-rename"),
|
||||
threadId: input.threadId,
|
||||
branch: renamed.branch,
|
||||
worktreePath: cwd,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning(
|
||||
"provider command reactor failed to generate or rename worktree branch",
|
||||
{ threadId: input.threadId, cwd, oldBranch, cause: Cause.pretty(cause) },
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const processTurnStartRequested = Effect.fnUntraced(function* (
|
||||
|
||||
@@ -4,6 +4,7 @@ import path from "node:path";
|
||||
|
||||
import type {
|
||||
OrchestrationReadModel,
|
||||
ProviderKind,
|
||||
ProviderRuntimeEvent,
|
||||
ProviderSession,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
@@ -38,11 +40,18 @@ import {
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
function makeTestServerSettingsLayer(overrides: Partial<ServerSettings> = {}) {
|
||||
return ServerSettingsService.layerTest(overrides);
|
||||
const settings: ServerSettings = { ...DEFAULT_SERVER_SETTINGS, ...overrides };
|
||||
return Layer.succeed(ServerSettingsService, {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Effect.succeed(settings),
|
||||
updateSettings: () => Effect.succeed(settings),
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsShape);
|
||||
}
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
@@ -55,7 +64,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: ProviderRuntimeEvent["provider"];
|
||||
readonly provider: ProviderKind;
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -65,23 +74,6 @@ type LegacyProviderRuntimeEvent = {
|
||||
readonly [key: string]: unknown;
|
||||
};
|
||||
|
||||
type LegacyTurnCompletedEvent = LegacyProviderRuntimeEvent & {
|
||||
readonly type: "turn.completed";
|
||||
readonly payload?: undefined;
|
||||
readonly status: "completed" | "failed" | "interrupted" | "cancelled";
|
||||
readonly errorMessage?: string | undefined;
|
||||
};
|
||||
|
||||
function isLegacyTurnCompletedEvent(
|
||||
event: LegacyProviderRuntimeEvent,
|
||||
): event is LegacyTurnCompletedEvent {
|
||||
return (
|
||||
event.type === "turn.completed" &&
|
||||
event.payload === undefined &&
|
||||
typeof event.status === "string"
|
||||
);
|
||||
}
|
||||
|
||||
function createProviderServiceHarness() {
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
const runtimeSessions: ProviderSession[] = [];
|
||||
@@ -109,23 +101,8 @@ function createProviderServiceHarness() {
|
||||
runtimeSessions.push(session);
|
||||
};
|
||||
|
||||
const normalizeLegacyEvent = (event: LegacyProviderRuntimeEvent): ProviderRuntimeEvent => {
|
||||
if (isLegacyTurnCompletedEvent(event)) {
|
||||
const normalized: Extract<ProviderRuntimeEvent, { type: "turn.completed" }> = {
|
||||
...(event as Omit<Extract<ProviderRuntimeEvent, { type: "turn.completed" }>, "payload">),
|
||||
payload: {
|
||||
state: event.status,
|
||||
...(typeof event.errorMessage === "string" ? { errorMessage: event.errorMessage } : {}),
|
||||
},
|
||||
};
|
||||
return normalized;
|
||||
}
|
||||
|
||||
return event as ProviderRuntimeEvent;
|
||||
};
|
||||
|
||||
const emit = (event: LegacyProviderRuntimeEvent): void => {
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, normalizeLegacyEvent(event)));
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -1726,37 +1703,6 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(thread.session?.lastError).toBe("runtime exploded");
|
||||
});
|
||||
|
||||
it("records runtime.error activities from the typed payload message", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "runtime.error",
|
||||
eventId: asEventId("evt-runtime-error-activity"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-runtime-error-activity"),
|
||||
payload: {
|
||||
message: "runtime activity exploded",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some((activity) => activity.id === "evt-runtime-error-activity"),
|
||||
);
|
||||
const activity = thread.activities.find(
|
||||
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-runtime-error-activity",
|
||||
);
|
||||
const activityPayload =
|
||||
activity?.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
expect(activity?.kind).toBe("runtime.error");
|
||||
expect(activityPayload?.message).toBe("runtime activity exploded");
|
||||
});
|
||||
|
||||
it("keeps the session running when a runtime.warning arrives during an active turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -98,6 +98,10 @@ function proposedPlanIdFromEvent(event: ProviderRuntimeEvent, threadId: ThreadId
|
||||
return `plan:${threadId}:event:${event.eventId}`;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function buildContextWindowActivityPayload(
|
||||
event: ProviderRuntimeEvent,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
@@ -107,6 +111,14 @@ function buildContextWindowActivityPayload(
|
||||
return event.payload.usage;
|
||||
}
|
||||
|
||||
function runtimePayloadRecord(event: ProviderRuntimeEvent): Record<string, unknown> | undefined {
|
||||
const payload = (event as { payload?: unknown }).payload;
|
||||
if (!payload || typeof payload !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return payload as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function normalizeRuntimeTurnState(
|
||||
value: string | undefined,
|
||||
): "completed" | "failed" | "interrupted" | "cancelled" {
|
||||
@@ -121,6 +133,23 @@ function normalizeRuntimeTurnState(
|
||||
}
|
||||
}
|
||||
|
||||
function runtimeTurnState(
|
||||
event: ProviderRuntimeEvent,
|
||||
): "completed" | "failed" | "interrupted" | "cancelled" {
|
||||
const payloadState = asString(runtimePayloadRecord(event)?.state);
|
||||
return normalizeRuntimeTurnState(payloadState);
|
||||
}
|
||||
|
||||
function runtimeTurnErrorMessage(event: ProviderRuntimeEvent): string | undefined {
|
||||
const payloadErrorMessage = asString(runtimePayloadRecord(event)?.errorMessage);
|
||||
return payloadErrorMessage;
|
||||
}
|
||||
|
||||
function runtimeErrorMessageFromEvent(event: ProviderRuntimeEvent): string | undefined {
|
||||
const payloadMessage = asString(runtimePayloadRecord(event)?.message);
|
||||
return payloadMessage;
|
||||
}
|
||||
|
||||
function orchestrationSessionStatusFromRuntimeState(
|
||||
state: "starting" | "running" | "waiting" | "ready" | "interrupted" | "stopped" | "error",
|
||||
): "starting" | "running" | "ready" | "interrupted" | "stopped" | "error" {
|
||||
@@ -224,6 +253,10 @@ function runtimeEventToActivities(
|
||||
}
|
||||
|
||||
case "runtime.error": {
|
||||
const message = runtimeErrorMessageFromEvent(event);
|
||||
if (!message) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
id: event.eventId,
|
||||
@@ -232,7 +265,7 @@ function runtimeEventToActivities(
|
||||
kind: "runtime.error",
|
||||
summary: "Runtime error",
|
||||
payload: {
|
||||
message: truncateDetail(event.payload.message),
|
||||
message: truncateDetail(message),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
@@ -940,9 +973,7 @@ const make = Effect.gen(function* () {
|
||||
case "session.exited":
|
||||
return "stopped";
|
||||
case "turn.completed":
|
||||
return normalizeRuntimeTurnState(event.payload.state) === "failed"
|
||||
? "error"
|
||||
: "ready";
|
||||
return runtimeTurnState(event) === "failed" ? "error" : "ready";
|
||||
case "session.started":
|
||||
case "thread.started":
|
||||
// Provider thread/session start notifications can arrive during an
|
||||
@@ -953,9 +984,8 @@ const make = Effect.gen(function* () {
|
||||
const lastError =
|
||||
event.type === "session.state.changed" && event.payload.state === "error"
|
||||
? (event.payload.reason ?? thread.session?.lastError ?? "Provider session error")
|
||||
: event.type === "turn.completed" &&
|
||||
normalizeRuntimeTurnState(event.payload.state) === "failed"
|
||||
? (event.payload.errorMessage ?? thread.session?.lastError ?? "Turn failed")
|
||||
: event.type === "turn.completed" && runtimeTurnState(event) === "failed"
|
||||
? (runtimeTurnErrorMessage(event) ?? thread.session?.lastError ?? "Turn failed")
|
||||
: status === "ready"
|
||||
? null
|
||||
: (thread.session?.lastError ?? null);
|
||||
@@ -1146,7 +1176,7 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (event.type === "runtime.error") {
|
||||
const runtimeErrorMessage = event.payload.message;
|
||||
const runtimeErrorMessage = runtimeErrorMessageFromEvent(event) ?? "Provider runtime error";
|
||||
|
||||
const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD
|
||||
? true
|
||||
|
||||
@@ -3,12 +3,10 @@ import {
|
||||
ProjectMetaUpdatedPayload as ContractsProjectMetaUpdatedPayloadSchema,
|
||||
ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,
|
||||
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
|
||||
ThreadArchivedPayload as ContractsThreadArchivedPayloadSchema,
|
||||
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
|
||||
ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,
|
||||
ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,
|
||||
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
||||
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
@@ -28,12 +26,10 @@ export const ProjectMetaUpdatedPayload = ContractsProjectMetaUpdatedPayloadSchem
|
||||
export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;
|
||||
|
||||
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
|
||||
export const ThreadArchivedPayload = ContractsThreadArchivedPayloadSchema;
|
||||
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
|
||||
export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;
|
||||
export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;
|
||||
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
|
||||
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
|
||||
|
||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||
|
||||
@@ -66,7 +66,6 @@ const readModel: OrchestrationReadModel = {
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
@@ -89,7 +88,6 @@ const readModel: OrchestrationReadModel = {
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
|
||||
@@ -88,44 +88,6 @@ export function requireThread(input: {
|
||||
);
|
||||
}
|
||||
|
||||
export function requireThreadArchived(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly threadId: ThreadId;
|
||||
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
|
||||
return requireThread(input).pipe(
|
||||
Effect.flatMap((thread) =>
|
||||
thread.archivedAt !== null
|
||||
? Effect.succeed(thread)
|
||||
: Effect.fail(
|
||||
invariantError(
|
||||
input.command.type,
|
||||
`Thread '${input.threadId}' is not archived for command '${input.command.type}'.`,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function requireThreadNotArchived(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly threadId: ThreadId;
|
||||
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
|
||||
return requireThread(input).pipe(
|
||||
Effect.flatMap((thread) =>
|
||||
thread.archivedAt === null
|
||||
? Effect.succeed(thread)
|
||||
: Effect.fail(
|
||||
invariantError(
|
||||
input.command.type,
|
||||
`Thread '${input.threadId}' is already archived and cannot handle command '${input.command.type}'.`,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function requireThreadAbsent(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
|
||||
@@ -10,9 +10,7 @@ import {
|
||||
requireProject,
|
||||
requireProjectAbsent,
|
||||
requireThread,
|
||||
requireThreadArchived,
|
||||
requireThreadAbsent,
|
||||
requireThreadNotArchived,
|
||||
} from "./commandInvariants.ts";
|
||||
|
||||
const nowIso = () => new Date().toISOString();
|
||||
@@ -192,51 +190,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.archive": {
|
||||
yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = nowIso();
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.archived",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
archivedAt: occurredAt,
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.unarchive": {
|
||||
yield* requireThreadArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = nowIso();
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.unarchived",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.meta.update": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
|
||||
@@ -87,7 +87,6 @@ describe("orchestration projector", () => {
|
||||
latestTurn: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
@@ -132,78 +131,6 @@ describe("orchestration projector", () => {
|
||||
).rejects.toBeDefined();
|
||||
});
|
||||
|
||||
it("applies thread.archived and thread.unarchived events", async () => {
|
||||
const now = new Date().toISOString();
|
||||
const later = new Date(Date.parse(now) + 1_000).toISOString();
|
||||
const created = await Effect.runPromise(
|
||||
projectEvent(
|
||||
createEmptyReadModel(now),
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: now,
|
||||
commandId: "cmd-thread-create",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const archived = await Effect.runPromise(
|
||||
projectEvent(
|
||||
created,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.archived",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: later,
|
||||
commandId: "cmd-thread-archive",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
archivedAt: later,
|
||||
updatedAt: later,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(archived.threads[0]?.archivedAt).toBe(later);
|
||||
|
||||
const unarchived = await Effect.runPromise(
|
||||
projectEvent(
|
||||
archived,
|
||||
makeEvent({
|
||||
sequence: 3,
|
||||
type: "thread.unarchived",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: later,
|
||||
commandId: "cmd-thread-unarchive",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
updatedAt: later,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(unarchived.threads[0]?.archivedAt).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps projector forward-compatible for unhandled event types", async () => {
|
||||
const now = new Date().toISOString();
|
||||
const model = createEmptyReadModel(now);
|
||||
|
||||
@@ -14,14 +14,12 @@ import {
|
||||
ProjectDeletedPayload,
|
||||
ProjectMetaUpdatedPayload,
|
||||
ThreadActivityAppendedPayload,
|
||||
ThreadArchivedPayload,
|
||||
ThreadCreatedPayload,
|
||||
ThreadDeletedPayload,
|
||||
ThreadInteractionModeSetPayload,
|
||||
ThreadMetaUpdatedPayload,
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -262,7 +260,6 @@ export function projectEvent(
|
||||
latestTurn: null,
|
||||
createdAt: payload.createdAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
@@ -292,28 +289,6 @@ export function projectEvent(
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.archived":
|
||||
return decodeForEvent(ThreadArchivedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
archivedAt: payload.archivedAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.unarchived":
|
||||
return decodeForEvent(ThreadUnarchivedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
archivedAt: null,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.meta-updated":
|
||||
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { fixPath } from "./os-jank";
|
||||
|
||||
describe("fixPath", () => {
|
||||
it("hydrates PATH on linux using the resolved login shell", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
|
||||
fixPath({
|
||||
env,
|
||||
platform: "linux",
|
||||
readPath,
|
||||
});
|
||||
|
||||
expect(readPath).toHaveBeenCalledWith("/bin/zsh");
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS and linux even when SHELL is set", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
||||
PATH: "C:\\Windows\\System32",
|
||||
};
|
||||
const readPath = vi.fn(() => "/usr/local/bin:/usr/bin");
|
||||
|
||||
fixPath({
|
||||
env,
|
||||
platform: "win32",
|
||||
readPath,
|
||||
});
|
||||
|
||||
expect(readPath).not.toHaveBeenCalled();
|
||||
expect(env.PATH).toBe("C:\\Windows\\System32");
|
||||
});
|
||||
});
|
||||
@@ -1,25 +1,15 @@
|
||||
import * as OS from "node:os";
|
||||
import { Effect, Path } from "effect";
|
||||
import { readPathFromLoginShell, resolveLoginShell } from "@t3tools/shared/shell";
|
||||
import { readPathFromLoginShell } from "@t3tools/shared/shell";
|
||||
|
||||
export function fixPath(
|
||||
options: {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
platform?: NodeJS.Platform;
|
||||
readPath?: typeof readPathFromLoginShell;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
const env = options.env ?? process.env;
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
const result = (options.readPath ?? readPathFromLoginShell)(shell);
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = readPathFromLoginShell(shell);
|
||||
if (result) {
|
||||
env.PATH = result;
|
||||
process.env.PATH = result;
|
||||
}
|
||||
} catch {
|
||||
// Silently ignore — keep default PATH
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_KIND,
|
||||
EventId,
|
||||
IsoDateTime,
|
||||
NonNegativeInt,
|
||||
@@ -11,7 +10,6 @@ import {
|
||||
OrchestrationEventType,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
isSupportedProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
@@ -28,29 +26,6 @@ import {
|
||||
} from "../Services/OrchestrationEventStore.ts";
|
||||
|
||||
const decodeEvent = Schema.decodeUnknownEffect(OrchestrationEvent);
|
||||
|
||||
/**
|
||||
* Coerce unsupported provider names in `modelSelection` /
|
||||
* `defaultModelSelection` payloads to the default provider so the strict
|
||||
* `OrchestrationEvent` schema can always decode persisted events. This
|
||||
* keeps the read path tolerant of legacy or future provider data without
|
||||
* widening the canonical types.
|
||||
*/
|
||||
function coerceUnsupportedProviders<T>(row: T): T {
|
||||
const r = row as Record<string, unknown>;
|
||||
const payload = r.payload;
|
||||
if (typeof payload !== "object" || payload === null) return row;
|
||||
const p = payload as Record<string, unknown>;
|
||||
let patched: Record<string, unknown> | null = null;
|
||||
for (const key of ["modelSelection", "defaultModelSelection"] as const) {
|
||||
const ms = p[key] as Record<string, unknown> | null | undefined;
|
||||
if (ms && typeof ms.provider === "string" && !isSupportedProvider(ms.provider)) {
|
||||
patched ??= { ...p };
|
||||
patched[key] = { provider: DEFAULT_PROVIDER_KIND, model: ms.model };
|
||||
}
|
||||
}
|
||||
return patched ? ({ ...r, payload: patched } as T) : row;
|
||||
}
|
||||
const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);
|
||||
const EventMetadataFromJsonString = Schema.fromJsonString(OrchestrationEventMetadata);
|
||||
|
||||
@@ -255,7 +230,7 @@ const makeEventStore = Effect.gen(function* () {
|
||||
),
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(rows, (row) =>
|
||||
decodeEvent(coerceUnsupportedProviders(row)).pipe(
|
||||
decodeEvent(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError("OrchestrationEventStore.readFromSequence:rowToEvent"),
|
||||
),
|
||||
|
||||
@@ -87,7 +87,6 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
latestTurnId: null,
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-24T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
|
||||
@@ -39,7 +39,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
@@ -54,7 +53,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.latestTurnId},
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.archivedAt},
|
||||
${row.deletedAt}
|
||||
)
|
||||
ON CONFLICT (thread_id)
|
||||
@@ -69,7 +67,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
latest_turn_id = excluded.latest_turn_id,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
archived_at = excluded.archived_at,
|
||||
deleted_at = excluded.deleted_at
|
||||
`,
|
||||
});
|
||||
@@ -91,7 +88,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = ${threadId}
|
||||
@@ -115,7 +111,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE project_id = ${projectId}
|
||||
|
||||
@@ -29,8 +29,6 @@ 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_CanonicalizeModelSelections.ts";
|
||||
import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts";
|
||||
import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -59,8 +57,6 @@ export const migrationEntries = [
|
||||
[14, "ProjectionThreadProposedPlanImplementation", Migration0014],
|
||||
[15, "ProjectionTurnsSourceProposedPlan", Migration0015],
|
||||
[16, "CanonicalizeModelSelections", Migration0016],
|
||||
[17, "ProjectionThreadsArchivedAt", Migration0017],
|
||||
[18, "ProjectionThreadsArchivedAtIndex", Migration0018],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -128,20 +128,6 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
'{"projectId":"project-2","title":"Fallback Project","workspaceRoot":"/tmp/project-2","defaultModel":"claude-opus-4-6","defaultModelOptions":{"codex":{"reasoningEffort":"low"}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-project-created-null-model',
|
||||
'project',
|
||||
'project-3',
|
||||
1,
|
||||
'project.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-project-created-null-model',
|
||||
NULL,
|
||||
'correlation-project-created-null-model',
|
||||
'user',
|
||||
'{"projectId":"project-3","title":"Null Model Project","workspaceRoot":"/tmp/project-3","defaultModel":null,"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-thread-created',
|
||||
'thread',
|
||||
@@ -298,16 +284,6 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[2]!.payloadJson), {
|
||||
projectId: "project-3",
|
||||
title: "Null Model Project",
|
||||
workspaceRoot: "/tmp/project-3",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[3]!.payloadJson), {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
@@ -327,7 +303,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), {
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[3]!.payloadJson), {
|
||||
threadId: "thread-2",
|
||||
projectId: "project-1",
|
||||
title: "Fallback Thread",
|
||||
@@ -346,7 +322,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), {
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), {
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
input: "hi",
|
||||
@@ -360,7 +336,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
deliveryMode: "buffered",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[6]!.payloadJson), {
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), {
|
||||
threadId: "thread-3",
|
||||
projectId: "project-1",
|
||||
title: "Ancient Thread",
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const columns = yield* sql<{ readonly name: string }>`
|
||||
PRAGMA table_info(projection_threads)
|
||||
`;
|
||||
|
||||
if (columns.some((column) => column.name === "archived_at")) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN archived_at TEXT
|
||||
`;
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
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`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_threads_project_archived_at
|
||||
ON projection_threads(project_id, archived_at)
|
||||
`;
|
||||
});
|
||||
@@ -20,7 +20,7 @@ import * as Stream from "effect/Stream";
|
||||
import * as Reactivity from "effect/unstable/reactivity/Reactivity";
|
||||
import * as Client from "effect/unstable/sql/SqlClient";
|
||||
import type { Connection } from "effect/unstable/sql/SqlConnection";
|
||||
import { SqlError, classifySqliteError } from "effect/unstable/sql/SqlError";
|
||||
import { SqlError } from "effect/unstable/sql/SqlError";
|
||||
import * as Statement from "effect/unstable/sql/Statement";
|
||||
|
||||
const ATTR_DB_SYSTEM_NAME = "db.system.name";
|
||||
@@ -29,9 +29,6 @@ export const TypeId: TypeId = "~local/sqlite-node/SqliteClient";
|
||||
|
||||
export type TypeId = "~local/sqlite-node/SqliteClient";
|
||||
|
||||
const classifyError = (cause: unknown, message: string, operation: string) =>
|
||||
classifySqliteError(cause, { message, operation });
|
||||
|
||||
/**
|
||||
* SqliteClient - Effect service tag for the sqlite SQL client.
|
||||
*/
|
||||
@@ -112,10 +109,7 @@ const makeWithDatabase = (
|
||||
lookup: (sql: string) =>
|
||||
Effect.try({
|
||||
try: () => db.prepare(sql),
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifyError(cause, "Failed to prepare statement", "prepare"),
|
||||
}),
|
||||
catch: (cause) => new SqlError({ cause, message: "Failed to prepare statement" }),
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -133,11 +127,7 @@ const makeWithDatabase = (
|
||||
const result = statement.run(...(params as any));
|
||||
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
|
||||
} catch (cause) {
|
||||
return Effect.fail(
|
||||
new SqlError({
|
||||
reason: classifyError(cause, "Failed to execute statement", "execute"),
|
||||
}),
|
||||
);
|
||||
return Effect.fail(new SqlError({ cause, message: "Failed to execute statement" }));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -160,10 +150,7 @@ const makeWithDatabase = (
|
||||
statement.run(...(params as any));
|
||||
return [];
|
||||
},
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifyError(cause, "Failed to execute statement", "execute"),
|
||||
}),
|
||||
catch: (cause) => new SqlError({ cause, message: "Failed to execute statement" }),
|
||||
}),
|
||||
(statement) =>
|
||||
Effect.sync(() => {
|
||||
|
||||
@@ -32,7 +32,6 @@ export const ProjectionThread = Schema.Struct({
|
||||
latestTurnId: Schema.NullOr(TurnId),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
archivedAt: Schema.NullOr(IsoDateTime),
|
||||
deletedAt: Schema.NullOr(IsoDateTime),
|
||||
});
|
||||
export type ProjectionThread = typeof ProjectionThread.Type;
|
||||
|
||||
@@ -37,7 +37,7 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
|
||||
}
|
||||
|
||||
export function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
|
||||
function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
|
||||
if (process.platform !== "win32") return false;
|
||||
if (code === 9009) return true;
|
||||
return /is not recognized as an internal or external command/i.test(stderr);
|
||||
|
||||
@@ -347,7 +347,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
|
||||
it.effect("ignores unsupported max effort for Sonnet 4.6", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
@@ -365,7 +365,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, "high");
|
||||
assert.equal(createInput?.options.effort, undefined);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -532,7 +532,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, "high");
|
||||
assert.equal(createInput?.options.effort, undefined);
|
||||
const promptText = yield* Effect.promise(() => readFirstPromptText(createInput));
|
||||
assert.equal(promptText, "Ultrathink:\nInvestigate the edge cases");
|
||||
}).pipe(
|
||||
@@ -1100,13 +1100,10 @@ describe("ClaudeAdapterLive", () => {
|
||||
it.effect("closes the session when the Claude stream aborts after a turn starts", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const services = yield* Effect.services();
|
||||
const runFork = Effect.runForkWith(services);
|
||||
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
|
||||
|
||||
const runtimeEventsFiber = runFork(
|
||||
const runtimeEventsFiber = Effect.runFork(
|
||||
Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
@@ -1200,12 +1197,9 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const services = yield* Effect.services();
|
||||
const runFork = Effect.runForkWith(services);
|
||||
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = runFork(
|
||||
const runtimeEventsFiber = Effect.runFork(
|
||||
Stream.runForEach(adapter.streamEvents, () => Effect.void),
|
||||
);
|
||||
|
||||
@@ -2390,85 +2384,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"does not re-set the Claude model when the session already uses the same effective API model",
|
||||
() => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
const modelSelection = {
|
||||
provider: "claudeAgent" as const,
|
||||
model: "claude-opus-4-6",
|
||||
};
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
modelSelection,
|
||||
attachments: [],
|
||||
});
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello again",
|
||||
modelSelection,
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.deepEqual(harness.query.setModelCalls, []);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("re-sets the Claude model when the effective API model changes", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
contextWindow: "1m",
|
||||
},
|
||||
},
|
||||
attachments: [],
|
||||
});
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello again",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6[1m]", "claude-opus-4-6"]);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("sets plan permission mode on sendTurn when interactionMode is plan", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -9,22 +9,22 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Equal, Layer, Option, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
|
||||
import { getDefaultEffort, hasEffortLevel, trimOrNull } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
collectStreamAsString,
|
||||
DEFAULT_TIMEOUT_MS,
|
||||
detailFromResult,
|
||||
extractAuthBoolean,
|
||||
isCommandMissingCause,
|
||||
parseGenericCliVersion,
|
||||
providerModelsFromSettings,
|
||||
spawnAndCollect,
|
||||
type CommandResult,
|
||||
} from "../providerSnapshot";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider";
|
||||
import { ClaudeProvider } from "../Services/ClaudeProvider";
|
||||
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
|
||||
import { ClaudeProvider, type ClaudeProviderShape } from "../Services/ClaudeProvider";
|
||||
import { ServerSettingsService } from "../../serverSettings";
|
||||
|
||||
const PROVIDER = "claudeAgent" as const;
|
||||
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
@@ -42,10 +42,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
@@ -62,10 +58,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
@@ -77,7 +69,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
@@ -90,7 +81,6 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
}
|
||||
);
|
||||
@@ -101,16 +91,23 @@ export function normalizeClaudeModelOptions(
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): ClaudeModelOptions | undefined {
|
||||
const caps = getClaudeModelCapabilities(model);
|
||||
const effort = resolveEffort(caps, modelOptions?.effort);
|
||||
const defaultReasoningEffort = getDefaultEffort(caps);
|
||||
const resolvedEffort = trimOrNull(modelOptions?.effort);
|
||||
const isPromptInjected = caps.promptInjectedEffortLevels.includes(resolvedEffort ?? "");
|
||||
const effort =
|
||||
resolvedEffort &&
|
||||
!isPromptInjected &&
|
||||
hasEffortLevel(caps, resolvedEffort) &&
|
||||
resolvedEffort !== defaultReasoningEffort
|
||||
? resolvedEffort
|
||||
: undefined;
|
||||
const thinking =
|
||||
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
|
||||
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
|
||||
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
|
||||
const nextOptions: ClaudeModelOptions = {
|
||||
...(thinking === false ? { thinking: false } : {}),
|
||||
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
|
||||
...(effort ? { effort } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(contextWindow ? { contextWindow } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
@@ -198,154 +195,100 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
|
||||
const runClaudeCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const settingsService = yield* ServerSettingsService;
|
||||
const claudeSettings = yield* settingsService.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.claudeAgent),
|
||||
);
|
||||
const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
|
||||
});
|
||||
|
||||
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
function* (): Effect.fn.Return<
|
||||
ServerProvider,
|
||||
ServerSettingsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
|
||||
> {
|
||||
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
Effect.map((settings) => settings.providers.claudeAgent),
|
||||
);
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
claudeSettings.customModels,
|
||||
const child = yield* spawner.spawn(command);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectStreamAsString(child.stdout),
|
||||
collectStreamAsString(child.stderr),
|
||||
child.exitCode.pipe(Effect.map(Number)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (!claudeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Claude is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
export const checkClaudeProviderStatus: Effect.Effect<
|
||||
ServerProvider,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
|
||||
> = Effect.gen(function* () {
|
||||
const settingsService = yield* ServerSettingsService;
|
||||
const settings = yield* settingsService.getSettings.pipe(Effect.orDie);
|
||||
const claudeSettings = settings.providers.claudeAgent;
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, claudeSettings.customModels);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: isCommandMissingCause(error)
|
||||
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
|
||||
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!claudeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Claude is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Claude Agent CLI is installed but failed to run. ${detail}`
|
||||
: "Claude Agent CLI is installed but failed to run.",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: isCommandMissingCause(error)
|
||||
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
|
||||
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Claude authentication status: ${error.message}.`
|
||||
: "Could not verify Claude authentication status.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Could not verify Claude authentication status. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
|
||||
const version = versionProbe.success.value;
|
||||
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
@@ -354,13 +297,71 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: parsed.status,
|
||||
authStatus: parsed.authStatus,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Claude Agent CLI is installed but failed to run. ${detail}`
|
||||
: "Claude Agent CLI is installed but failed to run.",
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Claude authentication status: ${error.message}.`
|
||||
: "Could not verify Claude authentication status.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Could not verify Claude authentication status. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: parsed.status,
|
||||
authStatus: parsed.authStatus,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const ClaudeProviderLive = Layer.effect(
|
||||
ClaudeProvider,
|
||||
@@ -368,7 +369,7 @@ export const ClaudeProviderLive = Layer.effect(
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const checkProvider = checkClaudeProviderStatus().pipe(
|
||||
const checkProvider = checkClaudeProviderStatus.pipe(
|
||||
Effect.provideService(ServerSettingsService, serverSettings),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
@@ -384,5 +385,5 @@ export const ClaudeProviderLive = Layer.effect(
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
checkProvider,
|
||||
});
|
||||
}),
|
||||
}).pipe(Effect.map((service) => service satisfies ClaudeProviderShape)),
|
||||
);
|
||||
@@ -474,40 +474,6 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps process stderr notifications to runtime.warning", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
|
||||
lifecycleManager.emit("event", {
|
||||
id: asEventId("evt-process-stderr"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "process/stderr",
|
||||
turnId: asTurnId("turn-1"),
|
||||
message: "The filename or extension is too long. (os error 206)",
|
||||
} satisfies ProviderEvent);
|
||||
|
||||
const firstEvent = yield* Fiber.join(firstEventFiber);
|
||||
|
||||
assert.equal(firstEvent._tag, "Some");
|
||||
if (firstEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.type, "runtime.warning");
|
||||
if (firstEvent.value.type !== "runtime.warning") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.turnId, "turn-1");
|
||||
assert.equal(
|
||||
firstEvent.value.payload.message,
|
||||
"The filename or extension is too long. (os error 206)",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves request type when mapping serverRequest/resolved", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
ProviderItemId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderSendTurnInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Layer, Queue, Schema, ServiceMap, Stream } from "effect";
|
||||
|
||||
@@ -1268,19 +1267,6 @@ function mapToRuntimeEvents(
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "process/stderr") {
|
||||
return [
|
||||
{
|
||||
type: "runtime.warning",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
message: event.message ?? "Codex process stderr",
|
||||
...(event.payload !== undefined ? { detail: event.payload } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "windows/worldWritableWarning") {
|
||||
return [
|
||||
{
|
||||
@@ -1328,40 +1314,38 @@ function mapToRuntimeEvents(
|
||||
return [];
|
||||
}
|
||||
|
||||
const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
options?: CodexAdapterLiveOptions,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
|
||||
const acquireManager = Effect.fn("acquireManager")(function* () {
|
||||
if (options?.manager) {
|
||||
return options.manager;
|
||||
}
|
||||
const services = yield* Effect.services<never>();
|
||||
return options?.makeManager?.(services) ?? new CodexAppServerManager(services);
|
||||
});
|
||||
const manager = yield* Effect.acquireRelease(
|
||||
Effect.gen(function* () {
|
||||
if (options?.manager) {
|
||||
return options.manager;
|
||||
}
|
||||
const services = yield* Effect.services<never>();
|
||||
return options?.makeManager?.(services) ?? new CodexAppServerManager(services);
|
||||
}),
|
||||
(manager) =>
|
||||
Effect.sync(() => {
|
||||
try {
|
||||
manager.stopAll();
|
||||
} catch {
|
||||
// Finalizers should never fail and block shutdown.
|
||||
}
|
||||
}),
|
||||
);
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
|
||||
const manager = yield* Effect.acquireRelease(acquireManager(), (manager) =>
|
||||
Effect.sync(() => {
|
||||
try {
|
||||
manager.stopAll();
|
||||
} catch {
|
||||
// Finalizers should never fail and block shutdown.
|
||||
}
|
||||
}),
|
||||
);
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
|
||||
const startSession: CodexAdapterShape["startSession"] = Effect.fn("startSession")(
|
||||
function* (input) {
|
||||
const startSession: CodexAdapterShape["startSession"] = Effect.fn(function* (input) {
|
||||
if (input.provider !== undefined && input.provider !== PROVIDER) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
@@ -1410,212 +1394,211 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const resolveAttachment = Effect.fn("resolveAttachment")(function* (
|
||||
input: ProviderSendTurnInput,
|
||||
attachment: NonNullable<ProviderSendTurnInput["attachments"]>[number],
|
||||
) {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* toRequestError(
|
||||
input.threadId,
|
||||
"turn/start",
|
||||
new Error(`Invalid attachment id '${attachment.id}'.`),
|
||||
|
||||
const sendTurn: CodexAdapterShape["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const codexAttachments = yield* Effect.forEach(
|
||||
input.attachments ?? [],
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* toRequestError(
|
||||
input.threadId,
|
||||
"turn/start",
|
||||
new Error(`Invalid attachment id '${attachment.id}'.`),
|
||||
);
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "turn/start",
|
||||
detail: toMessage(cause, "Failed to read attachment file."),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
type: "image" as const,
|
||||
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
|
||||
};
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => {
|
||||
const managerInput = {
|
||||
threadId: input.threadId,
|
||||
...(input.input !== undefined ? { input: input.input } : {}),
|
||||
...(input.modelSelection?.provider === "codex"
|
||||
? { model: input.modelSelection.model }
|
||||
: {}),
|
||||
...(input.modelSelection?.provider === "codex" &&
|
||||
input.modelSelection.options?.reasoningEffort !== undefined
|
||||
? { effort: input.modelSelection.options.reasoningEffort }
|
||||
: {}),
|
||||
...(input.modelSelection?.provider === "codex" &&
|
||||
input.modelSelection.options?.fastMode
|
||||
? { serviceTier: "fast" }
|
||||
: {}),
|
||||
...(input.interactionMode !== undefined
|
||||
? { interactionMode: input.interactionMode }
|
||||
: {}),
|
||||
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
|
||||
};
|
||||
return manager.sendTurn(managerInput);
|
||||
},
|
||||
catch: (cause) => toRequestError(input.threadId, "turn/start", cause),
|
||||
}).pipe(
|
||||
Effect.map((result) => ({
|
||||
...result,
|
||||
threadId: input.threadId,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
const interruptTurn: CodexAdapterShape["interruptTurn"] = (threadId, turnId) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.interruptTurn(threadId, turnId),
|
||||
catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),
|
||||
});
|
||||
|
||||
const readThread: CodexAdapterShape["readThread"] = (threadId) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.readThread(threadId),
|
||||
catch: (cause) => toRequestError(threadId, "thread/read", cause),
|
||||
}).pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
threadId,
|
||||
turns: snapshot.turns,
|
||||
})),
|
||||
);
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
|
||||
const rollbackThread: CodexAdapterShape["rollbackThread"] = (threadId, numTurns) => {
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
method: "turn/start",
|
||||
detail: toMessage(cause, "Failed to read attachment file."),
|
||||
cause,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer >= 1.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
type: "image" as const,
|
||||
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
|
||||
};
|
||||
});
|
||||
|
||||
const sendTurn: CodexAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
|
||||
const codexAttachments = yield* Effect.forEach(
|
||||
input.attachments ?? [],
|
||||
(attachment) => resolveAttachment(input, attachment),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => {
|
||||
const managerInput = {
|
||||
threadId: input.threadId,
|
||||
...(input.input !== undefined ? { input: input.input } : {}),
|
||||
...(input.modelSelection?.provider === "codex"
|
||||
? { model: input.modelSelection.model }
|
||||
: {}),
|
||||
...(input.modelSelection?.provider === "codex" &&
|
||||
input.modelSelection.options?.reasoningEffort !== undefined
|
||||
? { effort: input.modelSelection.options.reasoningEffort }
|
||||
: {}),
|
||||
...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
|
||||
? { serviceTier: "fast" }
|
||||
: {}),
|
||||
...(input.interactionMode !== undefined
|
||||
? { interactionMode: input.interactionMode }
|
||||
: {}),
|
||||
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
|
||||
};
|
||||
return manager.sendTurn(managerInput);
|
||||
},
|
||||
catch: (cause) => toRequestError(input.threadId, "turn/start", cause),
|
||||
}).pipe(
|
||||
Effect.map((result) => ({
|
||||
...result,
|
||||
threadId: input.threadId,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
const interruptTurn: CodexAdapterShape["interruptTurn"] = (threadId, turnId) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.interruptTurn(threadId, turnId),
|
||||
catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),
|
||||
});
|
||||
|
||||
const readThread: CodexAdapterShape["readThread"] = (threadId) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.readThread(threadId),
|
||||
catch: (cause) => toRequestError(threadId, "thread/read", cause),
|
||||
}).pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
threadId,
|
||||
turns: snapshot.turns,
|
||||
})),
|
||||
);
|
||||
|
||||
const rollbackThread: CodexAdapterShape["rollbackThread"] = (threadId, numTurns) => {
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer >= 1.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.tryPromise({
|
||||
try: () => manager.rollbackThread(threadId, numTurns),
|
||||
catch: (cause) => toRequestError(threadId, "thread/rollback", cause),
|
||||
}).pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
threadId,
|
||||
turns: snapshot.turns,
|
||||
})),
|
||||
);
|
||||
};
|
||||
|
||||
const respondToRequest: CodexAdapterShape["respondToRequest"] = (threadId, requestId, decision) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.respondToRequest(threadId, requestId, decision),
|
||||
catch: (cause) => toRequestError(threadId, "item/requestApproval/decision", cause),
|
||||
});
|
||||
|
||||
const respondToUserInput: CodexAdapterShape["respondToUserInput"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
answers,
|
||||
) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.respondToUserInput(threadId, requestId, answers),
|
||||
catch: (cause) => toRequestError(threadId, "item/tool/requestUserInput", cause),
|
||||
});
|
||||
|
||||
const stopSession: CodexAdapterShape["stopSession"] = (threadId) =>
|
||||
Effect.sync(() => {
|
||||
manager.stopSession(threadId);
|
||||
});
|
||||
|
||||
const listSessions: CodexAdapterShape["listSessions"] = () =>
|
||||
Effect.sync(() => manager.listSessions());
|
||||
|
||||
const hasSession: CodexAdapterShape["hasSession"] = (threadId) =>
|
||||
Effect.sync(() => manager.hasSession(threadId));
|
||||
|
||||
const stopAll: CodexAdapterShape["stopAll"] = () =>
|
||||
Effect.sync(() => {
|
||||
manager.stopAll();
|
||||
});
|
||||
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) {
|
||||
if (!nativeEventLogger) {
|
||||
return;
|
||||
}
|
||||
yield* nativeEventLogger.write(event, event.threadId);
|
||||
});
|
||||
|
||||
const registerListener = Effect.fn("registerListener")(function* () {
|
||||
const services = yield* Effect.services<never>();
|
||||
const listenerEffect = Effect.fn("listener")(function* (event: ProviderEvent) {
|
||||
yield* writeNativeEvent(event);
|
||||
const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
|
||||
if (runtimeEvents.length === 0) {
|
||||
yield* Effect.logDebug("ignoring unhandled Codex provider event", {
|
||||
method: event.method,
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId,
|
||||
itemId: event.itemId,
|
||||
});
|
||||
return;
|
||||
);
|
||||
}
|
||||
yield* Queue.offerAll(runtimeEventQueue, runtimeEvents);
|
||||
});
|
||||
const listener = (event: ProviderEvent) =>
|
||||
listenerEffect(event).pipe(Effect.runPromiseWith(services));
|
||||
manager.on("event", listener);
|
||||
return listener;
|
||||
|
||||
return Effect.tryPromise({
|
||||
try: () => manager.rollbackThread(threadId, numTurns),
|
||||
catch: (cause) => toRequestError(threadId, "thread/rollback", cause),
|
||||
}).pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
threadId,
|
||||
turns: snapshot.turns,
|
||||
})),
|
||||
);
|
||||
};
|
||||
|
||||
const respondToRequest: CodexAdapterShape["respondToRequest"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
decision,
|
||||
) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.respondToRequest(threadId, requestId, decision),
|
||||
catch: (cause) => toRequestError(threadId, "item/requestApproval/decision", cause),
|
||||
});
|
||||
|
||||
const respondToUserInput: CodexAdapterShape["respondToUserInput"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
answers,
|
||||
) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.respondToUserInput(threadId, requestId, answers),
|
||||
catch: (cause) => toRequestError(threadId, "item/tool/requestUserInput", cause),
|
||||
});
|
||||
|
||||
const stopSession: CodexAdapterShape["stopSession"] = (threadId) =>
|
||||
Effect.sync(() => {
|
||||
manager.stopSession(threadId);
|
||||
});
|
||||
|
||||
const listSessions: CodexAdapterShape["listSessions"] = () =>
|
||||
Effect.sync(() => manager.listSessions());
|
||||
|
||||
const hasSession: CodexAdapterShape["hasSession"] = (threadId) =>
|
||||
Effect.sync(() => manager.hasSession(threadId));
|
||||
|
||||
const stopAll: CodexAdapterShape["stopAll"] = () =>
|
||||
Effect.sync(() => {
|
||||
manager.stopAll();
|
||||
});
|
||||
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.gen(function* () {
|
||||
const writeNativeEvent = (event: ProviderEvent) =>
|
||||
Effect.gen(function* () {
|
||||
if (!nativeEventLogger) {
|
||||
return;
|
||||
}
|
||||
yield* nativeEventLogger.write(event, event.threadId);
|
||||
});
|
||||
|
||||
const services = yield* Effect.services<never>();
|
||||
const listener = (event: ProviderEvent) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeNativeEvent(event);
|
||||
const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
|
||||
if (runtimeEvents.length === 0) {
|
||||
yield* Effect.logDebug("ignoring unhandled Codex provider event", {
|
||||
method: event.method,
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId,
|
||||
itemId: event.itemId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
yield* Queue.offerAll(runtimeEventQueue, runtimeEvents);
|
||||
}).pipe(Effect.runPromiseWith(services));
|
||||
manager.on("event", listener);
|
||||
return listener;
|
||||
}),
|
||||
(listener) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.sync(() => {
|
||||
manager.off("event", listener);
|
||||
});
|
||||
yield* Queue.shutdown(runtimeEventQueue);
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
provider: PROVIDER,
|
||||
capabilities: {
|
||||
sessionModelSwitch: "in-session",
|
||||
},
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEventQueue),
|
||||
} satisfies CodexAdapterShape;
|
||||
});
|
||||
|
||||
const unregisterListener = Effect.fn("unregisterListener")(function* (
|
||||
listener: (event: ProviderEvent) => Promise<void>,
|
||||
) {
|
||||
yield* Effect.sync(() => {
|
||||
manager.off("event", listener);
|
||||
});
|
||||
yield* Queue.shutdown(runtimeEventQueue);
|
||||
});
|
||||
|
||||
yield* Effect.acquireRelease(registerListener(), unregisterListener);
|
||||
|
||||
return {
|
||||
provider: PROVIDER,
|
||||
capabilities: {
|
||||
sessionModelSwitch: "in-session",
|
||||
},
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEventQueue),
|
||||
} satisfies CodexAdapterShape;
|
||||
});
|
||||
|
||||
export const CodexAdapterLive = Layer.effect(CodexAdapter, makeCodexAdapter());
|
||||
|
||||
export function makeCodexAdapterLive(options?: CodexAdapterLiveOptions) {
|
||||
|
||||
@@ -10,17 +10,17 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Equal, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { resolveEffort } from "@t3tools/shared/model";
|
||||
import { getDefaultEffort, trimOrNull } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
collectStreamAsString,
|
||||
DEFAULT_TIMEOUT_MS,
|
||||
detailFromResult,
|
||||
extractAuthBoolean,
|
||||
isCommandMissingCause,
|
||||
parseGenericCliVersion,
|
||||
providerModelsFromSettings,
|
||||
spawnAndCollect,
|
||||
type CommandResult,
|
||||
} from "../providerSnapshot";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider";
|
||||
@@ -29,8 +29,8 @@ import {
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "../codexCliVersion";
|
||||
import { CodexProvider } from "../Services/CodexProvider";
|
||||
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
|
||||
import { CodexProvider, type CodexProviderShape } from "../Services/CodexProvider";
|
||||
import { ServerSettingsService } from "../../serverSettings";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
|
||||
@@ -48,9 +48,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.4-mini",
|
||||
@@ -65,9 +64,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex",
|
||||
@@ -82,9 +80,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex-spark",
|
||||
@@ -99,9 +96,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.2-codex",
|
||||
@@ -116,9 +112,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.2",
|
||||
@@ -133,9 +128,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -146,7 +140,6 @@ export function getCodexModelCapabilities(model: string | null | undefined): Mod
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
}
|
||||
);
|
||||
@@ -157,10 +150,11 @@ export function normalizeCodexModelOptions(
|
||||
modelOptions: CodexModelOptions | null | undefined,
|
||||
): CodexModelOptions | undefined {
|
||||
const caps = getCodexModelCapabilities(model);
|
||||
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
|
||||
const defaultReasoningEffort = getDefaultEffort(caps);
|
||||
const reasoningEffort = trimOrNull(modelOptions?.reasoningEffort) ?? defaultReasoningEffort;
|
||||
const fastModeEnabled = modelOptions?.fastMode === true;
|
||||
const nextOptions: CodexModelOptions = {
|
||||
...(reasoningEffort
|
||||
...(reasoningEffort && reasoningEffort !== defaultReasoningEffort
|
||||
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
|
||||
: {}),
|
||||
...(fastModeEnabled ? { fastMode: true } : {}),
|
||||
@@ -248,7 +242,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
};
|
||||
}
|
||||
|
||||
export const readCodexConfigModelProvider = Effect.fn("readCodexConfigModelProvider")(function* () {
|
||||
export const readCodexConfigModelProvider = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const settingsService = yield* ServerSettingsService;
|
||||
@@ -285,13 +279,14 @@ export const readCodexConfigModelProvider = Effect.fn("readCodexConfigModelProvi
|
||||
return undefined;
|
||||
});
|
||||
|
||||
export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(
|
||||
export const hasCustomModelProvider = readCodexConfigModelProvider.pipe(
|
||||
Effect.map((provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider)),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
|
||||
const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const settingsService = yield* ServerSettingsService;
|
||||
const codexSettings = yield* settingsService.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.codex),
|
||||
@@ -303,182 +298,96 @@ const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
},
|
||||
});
|
||||
return yield* spawnAndCollect(codexSettings.binaryPath, command);
|
||||
});
|
||||
|
||||
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
|
||||
function* (): Effect.fn.Return<
|
||||
ServerProvider,
|
||||
ServerSettingsError,
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| Path.Path
|
||||
| ServerSettingsService
|
||||
> {
|
||||
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
Effect.map((settings) => settings.providers.codex),
|
||||
);
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
codexSettings.customModels,
|
||||
const child = yield* spawner.spawn(command);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectStreamAsString(child.stdout),
|
||||
collectStreamAsString(child.stderr),
|
||||
child.exitCode.pipe(Effect.map(Number)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (!codexSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Codex is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
export const checkCodexProviderStatus: Effect.Effect<
|
||||
ServerProvider,
|
||||
never,
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| Path.Path
|
||||
| ServerSettingsService
|
||||
> = Effect.gen(function* () {
|
||||
const settingsService = yield* ServerSettingsService;
|
||||
const settings = yield* settingsService.getSettings.pipe(Effect.orDie);
|
||||
const codexSettings = settings.providers.codex;
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: isCommandMissingCause(error)
|
||||
? "Codex CLI (`codex`) is not installed or not on PATH."
|
||||
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!codexSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Codex is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: "Codex CLI is installed but failed to run. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
const parsedVersion =
|
||||
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
|
||||
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Codex CLI is installed but failed to run. ${detail}`
|
||||
: "Codex CLI is installed but failed to run.",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: isCommandMissingCause(error)
|
||||
? "Codex CLI (`codex`) is not installed or not on PATH."
|
||||
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: formatCodexCliUpgradeMessage(parsedVersion),
|
||||
},
|
||||
});
|
||||
}
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: "Codex CLI is installed but failed to run. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (yield* hasCustomModelProvider) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "ready",
|
||||
authStatus: "unknown",
|
||||
message: "Using a custom Codex model provider; OpenAI login check skipped.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Codex authentication status: ${error.message}.`
|
||||
: "Could not verify Codex authentication status.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Could not verify Codex authentication status. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
|
||||
const version = versionProbe.success.value;
|
||||
const parsedVersion =
|
||||
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
|
||||
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
@@ -487,13 +396,103 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: parsed.status,
|
||||
authStatus: parsed.authStatus,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Codex CLI is installed but failed to run. ${detail}`
|
||||
: "Codex CLI is installed but failed to run.",
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "error",
|
||||
authStatus: "unknown",
|
||||
message: formatCodexCliUpgradeMessage(parsedVersion),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (yield* hasCustomModelProvider) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "ready",
|
||||
authStatus: "unknown",
|
||||
message: "Using a custom Codex model provider; OpenAI login check skipped.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Codex authentication status: ${error.message}.`
|
||||
: "Could not verify Codex authentication status.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Could not verify Codex authentication status. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: parsed.status,
|
||||
authStatus: parsed.authStatus,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const CodexProviderLive = Layer.effect(
|
||||
CodexProvider,
|
||||
@@ -503,7 +502,7 @@ export const CodexProviderLive = Layer.effect(
|
||||
const path = yield* Path.Path;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const checkProvider = checkCodexProviderStatus().pipe(
|
||||
const checkProvider = checkCodexProviderStatus.pipe(
|
||||
Effect.provideService(ServerSettingsService, serverSettings),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
@@ -521,5 +520,5 @@ export const CodexProviderLive = Layer.effect(
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
checkProvider,
|
||||
});
|
||||
}),
|
||||
}).pipe(Effect.map((service) => service satisfies CodexProviderShape)),
|
||||
);
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
ServerSettings,
|
||||
type ServerProvider,
|
||||
type ServerSettings as ContractServerSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
@@ -30,7 +29,7 @@ import {
|
||||
readCodexConfigModelProvider,
|
||||
} from "./CodexProvider";
|
||||
import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider";
|
||||
import { haveProvidersChanged, ProviderRegistryLive } from "./ProviderRegistry";
|
||||
import { ProviderRegistryLive } from "./ProviderRegistry";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings";
|
||||
import { ProviderRegistry } from "../Services/ProviderRegistry";
|
||||
|
||||
@@ -169,7 +168,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
// Point CODEX_HOME at an empty tmp dir (no config.toml) so the
|
||||
// default code path (OpenAI provider, auth probe runs) is exercised.
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
@@ -186,66 +185,73 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
),
|
||||
);
|
||||
|
||||
it.effect.skipIf(process.platform === "win32")(
|
||||
"inherits PATH when launching the codex probe with a CODEX_HOME override",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const binDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-test-codex-bin-",
|
||||
});
|
||||
const codexPath = path.join(binDir, "codex");
|
||||
yield* fileSystem.writeFileString(
|
||||
codexPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
'if [ "$1" = "--version" ]; then',
|
||||
' echo "codex-cli 1.0.0"',
|
||||
" exit 0",
|
||||
"fi",
|
||||
'if [ "$1" = "login" ] && [ "$2" = "status" ]; then',
|
||||
' echo "Logged in using ChatGPT"',
|
||||
" exit 0",
|
||||
"fi",
|
||||
'echo "unexpected args: $*" >&2',
|
||||
"exit 1",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fileSystem.chmod(codexPath, 0o755);
|
||||
const customCodexHome = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-test-codex-home-",
|
||||
});
|
||||
const previousPath = process.env.PATH;
|
||||
process.env.PATH = binDir;
|
||||
it.effect("inherits PATH when launching the codex probe with a CODEX_HOME override", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const binDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-test-codex-bin-",
|
||||
});
|
||||
const codexPath = path.join(binDir, "codex");
|
||||
yield* fileSystem.writeFileString(
|
||||
codexPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
'if [ "$1" = "--version" ]; then',
|
||||
' echo "codex-cli 1.0.0"',
|
||||
" exit 0",
|
||||
"fi",
|
||||
'if [ "$1" = "login" ] && [ "$2" = "status" ]; then',
|
||||
' echo "Logged in using ChatGPT"',
|
||||
" exit 0",
|
||||
"fi",
|
||||
'echo "unexpected args: $*" >&2',
|
||||
"exit 1",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fileSystem.chmod(codexPath, 0o755);
|
||||
const customCodexHome = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-test-codex-home-",
|
||||
});
|
||||
const previousPath = process.env.PATH;
|
||||
process.env.PATH = binDir;
|
||||
|
||||
try {
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest({
|
||||
try {
|
||||
const serverSettingsLayer = Layer.succeed(ServerSettingsService, {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Effect.succeed({
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providers: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers,
|
||||
codex: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.codex,
|
||||
homePath: customCodexHome,
|
||||
},
|
||||
},
|
||||
});
|
||||
}),
|
||||
updateSettings: () => Effect.die("not used"),
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsShape);
|
||||
|
||||
const status = yield* checkCodexProviderStatus().pipe(
|
||||
Effect.provide(serverSettingsLayer),
|
||||
);
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
} finally {
|
||||
process.env.PATH = previousPath;
|
||||
}
|
||||
}),
|
||||
const status = yield* checkCodexProviderStatus.pipe(
|
||||
Effect.provide(serverSettingsLayer),
|
||||
);
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
} finally {
|
||||
process.env.PATH = previousPath;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, false);
|
||||
@@ -260,7 +266,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
it.effect("returns unavailable when codex is below the minimum supported version", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
@@ -283,7 +289,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
it.effect("returns unauthenticated when auth probe reports login required", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
@@ -309,7 +315,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
it.effect("returns unauthenticated when login status output includes 'not logged in'", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
@@ -334,7 +340,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
it.effect("returns warning when login status command is unsupported", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.installed, true);
|
||||
@@ -359,33 +365,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
});
|
||||
|
||||
describe("ProviderRegistryLive", () => {
|
||||
it("treats equal provider snapshots as unchanged", () => {
|
||||
const providers = [
|
||||
{
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
authStatus: "authenticated",
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
},
|
||||
{
|
||||
provider: "claudeAgent",
|
||||
status: "warning",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
authStatus: "unknown",
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
},
|
||||
] as const satisfies ReadonlyArray<ServerProvider>;
|
||||
|
||||
assert.strictEqual(haveProvidersChanged(providers, [...providers]), false);
|
||||
});
|
||||
|
||||
it.effect("reruns codex health when codex provider settings change", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* makeMutableServerSettingsService();
|
||||
@@ -452,15 +431,24 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
|
||||
it.effect("skips codex probes entirely when the provider is disabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
codex: {
|
||||
enabled: false,
|
||||
const serverSettingsLayer = Layer.succeed(ServerSettingsService, {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Effect.succeed({
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providers: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers,
|
||||
codex: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.codex,
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}),
|
||||
updateSettings: () => Effect.die("not used"),
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsShape);
|
||||
|
||||
const status = yield* checkCodexProviderStatus().pipe(
|
||||
const status = yield* checkCodexProviderStatus.pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(serverSettingsLayer, failingSpawnerLayer("spawn codex ENOENT")),
|
||||
),
|
||||
@@ -490,7 +478,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
'env_key = "PORTKEY_API_KEY"',
|
||||
].join("\n"),
|
||||
);
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
@@ -523,7 +511,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
'env_key = "PORTKEY_API_KEY"',
|
||||
].join("\n"),
|
||||
);
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, false);
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
|
||||
@@ -534,7 +522,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
it.effect("still runs auth probe when model_provider is openai", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "openai"\n');
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
// The auth probe runs and sees "not logged in" → error
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
@@ -588,28 +576,28 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
it.effect("returns undefined when config file does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns undefined when config has no model_provider key", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model = "gpt-5-codex"\n');
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the provider when model_provider is set at top level", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model = "gpt-5-codex"\nmodel_provider = "portkey"\n');
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider(), "portkey");
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider, "portkey");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns openai when model_provider is openai", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome('model_provider = "openai"\n');
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider(), "openai");
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider, "openai");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -625,7 +613,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -641,14 +629,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
'model = "gpt-5-pro"',
|
||||
].join("\n"),
|
||||
);
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider(), "azure");
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider, "azure");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("handles single-quoted values in TOML", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome("model_provider = 'mistral'\n");
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider(), "mistral");
|
||||
assert.strictEqual(yield* readCodexConfigModelProvider, "mistral");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -711,7 +699,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
describe("checkClaudeProviderStatus", () => {
|
||||
it.effect("returns ready when claude is installed and authenticated", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
@@ -735,7 +723,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
|
||||
it.effect("returns unavailable when claude is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, false);
|
||||
@@ -749,7 +737,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
|
||||
it.effect("returns error when version check fails with non-zero exit code", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
@@ -767,7 +755,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
|
||||
it.effect("returns unauthenticated when auth status reports not logged in", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
@@ -795,7 +783,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
|
||||
it.effect("returns unauthenticated when output includes 'not logged in'", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
@@ -815,7 +803,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
|
||||
it.effect("returns warning when auth status command is unsupported", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.installed, true);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* @module ProviderRegistryLive
|
||||
*/
|
||||
import type { ProviderKind, ServerProvider } from "@t3tools/contracts";
|
||||
import { Effect, Equal, Layer, PubSub, Ref, Stream } from "effect";
|
||||
import { Effect, Layer, PubSub, Ref, Stream } from "effect";
|
||||
|
||||
import { ClaudeProviderLive } from "./ClaudeProvider";
|
||||
import { CodexProviderLive } from "./CodexProvider";
|
||||
@@ -22,11 +22,6 @@ const loadProviders = (
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
|
||||
export const haveProvidersChanged = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): boolean => !Equal.equals(previousProviders, nextProviders);
|
||||
|
||||
export const ProviderRegistryLive = Layer.effect(
|
||||
ProviderRegistry,
|
||||
Effect.gen(function* () {
|
||||
@@ -40,28 +35,22 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
yield* loadProviders(codexProvider, claudeProvider),
|
||||
);
|
||||
|
||||
const syncProviders = (options?: { readonly publish?: boolean }) =>
|
||||
Effect.gen(function* () {
|
||||
const previousProviders = yield* Ref.get(providersRef);
|
||||
const providers = yield* loadProviders(codexProvider, claudeProvider);
|
||||
yield* Ref.set(providersRef, providers);
|
||||
const syncProviders = Effect.gen(function* () {
|
||||
const providers = yield* loadProviders(codexProvider, claudeProvider);
|
||||
yield* Ref.set(providersRef, providers);
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
return providers;
|
||||
});
|
||||
|
||||
if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
|
||||
return providers;
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(codexProvider.streamChanges, () => syncProviders()).pipe(
|
||||
yield* Stream.runForEach(codexProvider.streamChanges, () => syncProviders).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Stream.runForEach(claudeProvider.streamChanges, () => syncProviders()).pipe(
|
||||
yield* Stream.runForEach(claudeProvider.streamChanges, () => syncProviders).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
return {
|
||||
getProviders: syncProviders({ publish: false }).pipe(
|
||||
getProviders: syncProviders.pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => []),
|
||||
),
|
||||
@@ -80,7 +69,7 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
});
|
||||
break;
|
||||
}
|
||||
return yield* syncProviders();
|
||||
return yield* syncProviders;
|
||||
}).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => []),
|
||||
|
||||
@@ -36,16 +36,23 @@ import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.t
|
||||
import { makeProviderServiceLive } from "./ProviderService.ts";
|
||||
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
import {
|
||||
makeSqlitePersistenceLive,
|
||||
SqlitePersistenceMemory,
|
||||
} from "../../persistence/Layers/Sqlite.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
|
||||
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
|
||||
|
||||
const defaultServerSettingsLayer = ServerSettingsService.layerTest();
|
||||
const defaultServerSettingsLayer = Layer.succeed(ServerSettingsService, {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
|
||||
updateSettings: () => Effect.succeed(DEFAULT_SERVER_SETTINGS),
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsShape);
|
||||
|
||||
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
@@ -285,13 +292,22 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", ()
|
||||
listProviders: () => Effect.succeed(["codex", "claudeAgent"]),
|
||||
};
|
||||
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
claudeAgent: {
|
||||
enabled: false,
|
||||
const serverSettingsLayer = Layer.succeed(ServerSettingsService, {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Effect.succeed({
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providers: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers,
|
||||
claudeAgent: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.claudeAgent,
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}),
|
||||
updateSettings: () => Effect.die("not used"),
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsShape);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
|
||||
@@ -18,25 +18,19 @@ function toPersistenceError(operation: string) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept any non-empty provider string.
|
||||
* Legacy or future providers are passed through so the read path never fails;
|
||||
* unsupported providers are simply cast — the caller is responsible for
|
||||
* checking `isSupportedProvider` before dispatching adapter operations.
|
||||
*/
|
||||
function decodeProviderKind(
|
||||
providerName: string,
|
||||
_operation: string,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderKind, ProviderSessionDirectoryPersistenceError> {
|
||||
if (providerName.trim().length === 0) {
|
||||
return Effect.fail(
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: _operation,
|
||||
detail: `Provider name must be a non-empty string.`,
|
||||
}),
|
||||
);
|
||||
if (providerName === "codex" || providerName === "claudeAgent") {
|
||||
return Effect.succeed(providerName);
|
||||
}
|
||||
return Effect.succeed(providerName as ProviderKind);
|
||||
return Effect.fail(
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation,
|
||||
detail: `Unknown persisted provider '${providerName}'.`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
|
||||
@@ -3,15 +3,14 @@ import { Duration, Effect, PubSub, Ref, Scope, Stream } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import type { ServerProviderShape } from "./Services/ServerProvider";
|
||||
import { ServerSettingsError } from "../serverSettings";
|
||||
|
||||
export function makeManagedServerProvider<Settings>(input: {
|
||||
readonly getSettings: Effect.Effect<Settings>;
|
||||
readonly streamSettings: Stream.Stream<Settings>;
|
||||
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
|
||||
readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
|
||||
readonly checkProvider: Effect.Effect<ServerProvider>;
|
||||
readonly refreshInterval?: Duration.Input;
|
||||
}): Effect.Effect<ServerProviderShape, ServerSettingsError, Scope.Scope> {
|
||||
}): Effect.Effect<ServerProviderShape, never, Scope.Scope> {
|
||||
return Effect.gen(function* () {
|
||||
const refreshSemaphore = yield* Semaphore.make(1);
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
@@ -23,31 +22,29 @@ export function makeManagedServerProvider<Settings>(input: {
|
||||
const snapshotRef = yield* Ref.make(initialSnapshot);
|
||||
const settingsRef = yield* Ref.make(initialSettings);
|
||||
|
||||
const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
|
||||
refreshSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const forceRefresh = options?.forceRefresh === true;
|
||||
const previousSettings = yield* Ref.get(settingsRef);
|
||||
if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
|
||||
yield* Ref.set(settingsRef, nextSettings);
|
||||
return yield* Ref.get(snapshotRef);
|
||||
}
|
||||
const refreshSnapshot = refreshSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const nextSettings = yield* input.getSettings;
|
||||
const nextSnapshot = yield* input.checkProvider;
|
||||
yield* Ref.set(settingsRef, nextSettings);
|
||||
yield* Ref.set(snapshotRef, nextSnapshot);
|
||||
yield* PubSub.publish(changesPubSub, nextSnapshot);
|
||||
return nextSnapshot;
|
||||
}),
|
||||
);
|
||||
|
||||
const nextSnapshot = yield* input.checkProvider;
|
||||
const reconcileSnapshot = (nextSettings: Settings) =>
|
||||
Effect.gen(function* () {
|
||||
const previousSettings = yield* Ref.get(settingsRef);
|
||||
if (!input.haveSettingsChanged(previousSettings, nextSettings)) {
|
||||
yield* Ref.set(settingsRef, nextSettings);
|
||||
yield* Ref.set(snapshotRef, nextSnapshot);
|
||||
yield* PubSub.publish(changesPubSub, nextSnapshot);
|
||||
return nextSnapshot;
|
||||
}),
|
||||
);
|
||||
|
||||
const refreshSnapshot = Effect.gen(function* () {
|
||||
const nextSettings = yield* input.getSettings;
|
||||
return yield* applySnapshot(nextSettings, { forceRefresh: true });
|
||||
});
|
||||
return yield* Ref.get(snapshotRef);
|
||||
}
|
||||
return yield* refreshSnapshot;
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
|
||||
Effect.asVoid(applySnapshot(nextSettings)),
|
||||
Effect.asVoid(reconcileSnapshot(nextSettings)),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.forever(
|
||||
@@ -59,7 +56,7 @@ export function makeManagedServerProvider<Settings>(input: {
|
||||
|
||||
return {
|
||||
getSnapshot: input.getSettings.pipe(
|
||||
Effect.flatMap(applySnapshot),
|
||||
Effect.flatMap(reconcileSnapshot),
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orDie,
|
||||
),
|
||||
|
||||
@@ -5,9 +5,7 @@ import type {
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { isWindowsCommandNotFound } from "../processRunner";
|
||||
|
||||
export const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
|
||||
@@ -37,26 +35,6 @@ export function isCommandMissingCause(error: unknown): boolean {
|
||||
return lower.includes("enoent") || lower.includes("notfound");
|
||||
}
|
||||
|
||||
export const spawnAndCollect = (binaryPath: string, command: ChildProcess.Command) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* spawner.spawn(command);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectStreamAsString(child.stdout),
|
||||
collectStreamAsString(child.stderr),
|
||||
child.exitCode.pipe(Effect.map(Number)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const result: CommandResult = { stdout, stderr, code: exitCode };
|
||||
if (isWindowsCommandNotFound(exitCode, stderr)) {
|
||||
return yield* Effect.fail(new Error(`spawn ${binaryPath} ENOENT`));
|
||||
}
|
||||
return result;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
export function detailFromResult(
|
||||
result: CommandResult & { readonly timedOut?: boolean },
|
||||
): string | undefined {
|
||||
@@ -147,10 +125,8 @@ export function buildServerProvider(input: {
|
||||
export const collectStreamAsString = <E>(
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): Effect.Effect<string, E> =>
|
||||
stream.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runFold(
|
||||
() => "",
|
||||
(acc, chunk) => acc + chunk,
|
||||
),
|
||||
Stream.runFold(
|
||||
stream,
|
||||
() => "",
|
||||
(acc, chunk) => acc + new TextDecoder().decode(chunk),
|
||||
);
|
||||
@@ -37,7 +37,7 @@ import {
|
||||
} from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
|
||||
import { deepMerge } from "@t3tools/shared/Struct";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
|
||||
@@ -76,27 +76,14 @@ export class ServerSettingsService extends ServiceMap.Service<
|
||||
ServerSettingsService,
|
||||
ServerSettingsShape
|
||||
>()("t3/serverSettings/ServerSettingsService") {
|
||||
static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
|
||||
Layer.effect(
|
||||
ServerSettingsService,
|
||||
Effect.gen(function* () {
|
||||
const currentSettingsRef = yield* Ref.make<ServerSettings>(
|
||||
deepMerge(DEFAULT_SERVER_SETTINGS, overrides),
|
||||
);
|
||||
|
||||
return {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Ref.get(currentSettingsRef),
|
||||
updateSettings: (patch) =>
|
||||
Ref.get(currentSettingsRef).pipe(
|
||||
Effect.map((currentSettings) => deepMerge(currentSettings, patch)),
|
||||
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
|
||||
),
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsShape;
|
||||
}),
|
||||
);
|
||||
static readonly layerTest = (overrides: Partial<ServerSettings> = {}) =>
|
||||
Layer.succeed(ServerSettingsService, {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, ...overrides }),
|
||||
updateSettings: () => Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, ...overrides }),
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsShape);
|
||||
}
|
||||
|
||||
const ServerSettingsJson = fromLenientJson(ServerSettings);
|
||||
@@ -226,7 +213,6 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
Effect.tap(() => fs.makeDirectory(pathService.dirname(settingsPath), { recursive: true })),
|
||||
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||
Effect.flatMap(() => fs.rename(tempPath, settingsPath)),
|
||||
Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSettingsError({
|
||||
@@ -286,11 +272,12 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const start = Effect.gen(function* () {
|
||||
const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);
|
||||
if (!shouldStart) {
|
||||
const alreadyStarted = yield* Ref.get(startedRef);
|
||||
if (alreadyStarted) {
|
||||
return yield* Deferred.await(startedDeferred);
|
||||
}
|
||||
|
||||
yield* Ref.set(startedRef, true);
|
||||
const startup = Effect.gen(function* () {
|
||||
yield* startWatcher;
|
||||
yield* Cache.invalidate(settingsCache, cacheKey);
|
||||
|
||||
@@ -672,9 +672,9 @@ describe("TerminalManager", () => {
|
||||
).toBe(true);
|
||||
} else {
|
||||
expect(
|
||||
ptyAdapter.spawnInputs
|
||||
.slice(1)
|
||||
.some((input) => input.shell !== "/definitely/missing-shell"),
|
||||
ptyAdapter.spawnInputs.some((input) =>
|
||||
["/bin/zsh", "/bin/bash", "/bin/sh", "zsh", "bash", "sh"].includes(input.shell),
|
||||
),
|
||||
).toBe(true);
|
||||
}
|
||||
|
||||
|
||||
@@ -252,11 +252,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
} = serverConfig;
|
||||
const availableEditors = resolveAvailableEditors();
|
||||
|
||||
const runtimeServices = yield* Effect.services<
|
||||
ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
>();
|
||||
const runPromise = Effect.runPromiseWith(runtimeServices);
|
||||
|
||||
const gitManager = yield* GitManager;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const keybindingsManager = yield* Keybindings;
|
||||
@@ -434,7 +429,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
res.end(body);
|
||||
};
|
||||
|
||||
void runPromise(
|
||||
void Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||
@@ -718,8 +713,13 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
);
|
||||
}
|
||||
|
||||
const unsubscribeTerminalEvents = yield* terminalManager.subscribe((event) =>
|
||||
runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)),
|
||||
const runtimeServices = yield* Effect.services<
|
||||
ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
>();
|
||||
const runPromise = Effect.runPromiseWith(runtimeServices);
|
||||
|
||||
const unsubscribeTerminalEvents = yield* terminalManager.subscribe(
|
||||
(event) => void Effect.runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)),
|
||||
);
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
|
||||
yield* readiness.markTerminalSubscriptionsReady;
|
||||
@@ -916,12 +916,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
};
|
||||
}
|
||||
|
||||
case WS_METHODS.serverRefreshProviders: {
|
||||
const providers = yield* providerRegistry.refresh();
|
||||
yield* Ref.set(providersRef, providers);
|
||||
return { providers };
|
||||
}
|
||||
|
||||
case WS_METHODS.serverUpsertKeybinding: {
|
||||
const body = stripRequestTag(request.body);
|
||||
const keybindingsConfig = yield* keybindingsManager.upsertKeybindingRule(body);
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import ThreadSidebar from "./Sidebar";
|
||||
import { Sidebar, SidebarProvider, SidebarRail } from "./ui/sidebar";
|
||||
|
||||
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;
|
||||
|
||||
export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
const onMenuAction = window.desktopBridge?.onMenuAction;
|
||||
if (typeof onMenuAction !== "function") {
|
||||
return;
|
||||
}
|
||||
|
||||
const unsubscribe = onMenuAction((action) => {
|
||||
if (action !== "open-settings") return;
|
||||
void navigate({ to: "/settings" });
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribe?.();
|
||||
};
|
||||
}, [navigate]);
|
||||
|
||||
return (
|
||||
<SidebarProvider defaultOpen>
|
||||
<Sidebar
|
||||
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>
|
||||
{children}
|
||||
</SidebarProvider>
|
||||
);
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
resolveBranchSelectionTarget,
|
||||
resolveDraftEnvModeAfterBranchChange,
|
||||
resolveBranchToolbarValue,
|
||||
shouldIncludeBranchPickerItem,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
@@ -268,38 +267,3 @@ describe("resolveBranchSelectionTarget", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldIncludeBranchPickerItem", () => {
|
||||
it("keeps the synthetic checkout PR item visible for gh pr checkout input", () => {
|
||||
expect(
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue: "__checkout_pull_request__:1359",
|
||||
normalizedQuery: "gh pr checkout 1359",
|
||||
createBranchItemValue: "__create_new_branch__:gh pr checkout 1359",
|
||||
checkoutPullRequestItemValue: "__checkout_pull_request__:1359",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the synthetic create-branch item visible for arbitrary branch input", () => {
|
||||
expect(
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue: "__create_new_branch__:feature/demo",
|
||||
normalizedQuery: "feature/demo",
|
||||
createBranchItemValue: "__create_new_branch__:feature/demo",
|
||||
checkoutPullRequestItemValue: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("still filters ordinary branch items by query text", () => {
|
||||
expect(
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue: "main",
|
||||
normalizedQuery: "gh pr checkout 1359",
|
||||
createBranchItemValue: "__create_new_branch__:gh pr checkout 1359",
|
||||
checkoutPullRequestItemValue: "__checkout_pull_request__:1359",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -123,26 +123,3 @@ export function resolveBranchSelectionTarget(input: {
|
||||
reuseExistingWorktree: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function shouldIncludeBranchPickerItem(input: {
|
||||
itemValue: string;
|
||||
normalizedQuery: string;
|
||||
createBranchItemValue: string | null;
|
||||
checkoutPullRequestItemValue: string | null;
|
||||
}): boolean {
|
||||
const { itemValue, normalizedQuery, createBranchItemValue, checkoutPullRequestItemValue } = input;
|
||||
|
||||
if (normalizedQuery.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (createBranchItemValue && itemValue === createBranchItemValue) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return itemValue.toLowerCase().includes(normalizedQuery);
|
||||
}
|
||||
@@ -28,7 +28,6 @@ import {
|
||||
EnvMode,
|
||||
resolveBranchSelectionTarget,
|
||||
resolveBranchToolbarValue,
|
||||
shouldIncludeBranchPickerItem,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
@@ -135,20 +134,11 @@ export function BranchToolbarBranchSelector({
|
||||
() =>
|
||||
normalizedDeferredBranchQuery.length === 0
|
||||
? branchPickerItems
|
||||
: branchPickerItems.filter((itemValue) =>
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue,
|
||||
normalizedQuery: normalizedDeferredBranchQuery,
|
||||
createBranchItemValue,
|
||||
checkoutPullRequestItemValue,
|
||||
}),
|
||||
),
|
||||
[
|
||||
branchPickerItems,
|
||||
checkoutPullRequestItemValue,
|
||||
createBranchItemValue,
|
||||
normalizedDeferredBranchQuery,
|
||||
],
|
||||
: branchPickerItems.filter((itemValue) => {
|
||||
if (createBranchItemValue && itemValue === createBranchItemValue) return true;
|
||||
return itemValue.toLowerCase().includes(normalizedDeferredBranchQuery);
|
||||
}),
|
||||
[branchPickerItems, createBranchItemValue, normalizedDeferredBranchQuery],
|
||||
);
|
||||
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
|
||||
canonicalActiveBranch,
|
||||
|
||||
@@ -243,7 +243,7 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
a({ node: _node, href, ...props }) {
|
||||
const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
|
||||
if (!targetPath) {
|
||||
return <a {...props} href={href} target="_blank" rel="noopener noreferrer" />;
|
||||
return <a {...props} href={href} target="_blank" rel="noreferrer" />;
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -56,7 +56,6 @@ interface TestFixture {
|
||||
|
||||
let fixture: TestFixture;
|
||||
const wsRequests: WsRequestEnvelope["body"][] = [];
|
||||
let customWsRpcResolver: ((body: WsRequestEnvelope["body"]) => unknown | undefined) | null = null;
|
||||
const wsLink = ws.link(/ws(s)?:\/\/.*/);
|
||||
|
||||
interface ViewportSpec {
|
||||
@@ -258,7 +257,6 @@ function createSnapshotForTargetUser(options: {
|
||||
latestTurn: null,
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages,
|
||||
activities: [],
|
||||
@@ -316,7 +314,6 @@ function addThreadToSnapshot(
|
||||
latestTurn: null,
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
@@ -359,25 +356,6 @@ function withProjectScripts(
|
||||
};
|
||||
}
|
||||
|
||||
function setDraftThreadWithoutWorktree(): void {
|
||||
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,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
|
||||
const snapshot = createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-plan-target" as MessageId,
|
||||
@@ -436,10 +414,6 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
|
||||
}
|
||||
|
||||
function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
|
||||
const customResult = customWsRpcResolver?.(body);
|
||||
if (customResult !== undefined) {
|
||||
return customResult;
|
||||
}
|
||||
const tag = body._tag;
|
||||
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
|
||||
return fixture.snapshot;
|
||||
@@ -774,11 +748,9 @@ async function mountChatView(options: {
|
||||
viewport: ViewportSpec;
|
||||
snapshot: OrchestrationReadModel;
|
||||
configureFixture?: (fixture: TestFixture) => void;
|
||||
resolveRpc?: (body: WsRequestEnvelope["body"]) => unknown | undefined;
|
||||
}): Promise<MountedChatView> {
|
||||
fixture = buildFixture(options.snapshot);
|
||||
options.configureFixture?.(fixture);
|
||||
customWsRpcResolver = options.resolveRpc ?? null;
|
||||
await setViewport(options.viewport);
|
||||
await waitForProductionStyles();
|
||||
|
||||
@@ -804,7 +776,6 @@ async function mountChatView(options: {
|
||||
await waitForLayout();
|
||||
|
||||
const cleanup = async () => {
|
||||
customWsRpcResolver = null;
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
};
|
||||
@@ -864,7 +835,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
localStorage.clear();
|
||||
document.body.innerHTML = "";
|
||||
wsRequests.length = 0;
|
||||
customWsRpcResolver = null;
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
@@ -880,7 +850,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
customWsRpcResolver = null;
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
@@ -1042,7 +1011,22 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
);
|
||||
|
||||
it("opens the project cwd for draft threads without a worktree path", async () => {
|
||||
setDraftThreadWithoutWorktree();
|
||||
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,
|
||||
@@ -1083,153 +1067,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("opens the project cwd with VS Code Insiders when it is the only available editor", async () => {
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
availableEditors: ["vscode-insiders"],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const openButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.trim() === "Open",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Open button.",
|
||||
);
|
||||
openButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.shellOpenInEditor,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.shellOpenInEditor,
|
||||
cwd: "/repo/project",
|
||||
editor: "vscode-insiders",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("filters the open picker menu and opens VSCodium from the menu", async () => {
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
availableEditors: ["vscode-insiders", "vscodium"],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const menuButton = await waitForElement(
|
||||
() => document.querySelector('button[aria-label="Copy options"]'),
|
||||
"Unable to find Open picker button.",
|
||||
);
|
||||
(menuButton as HTMLButtonElement).click();
|
||||
|
||||
await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) =>
|
||||
item.textContent?.includes("VS Code Insiders"),
|
||||
) ?? null,
|
||||
"Unable to find VS Code Insiders menu item.",
|
||||
);
|
||||
|
||||
expect(
|
||||
Array.from(document.querySelectorAll('[data-slot="menu-item"]')).some((item) =>
|
||||
item.textContent?.includes("Zed"),
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
const vscodiumItem = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) =>
|
||||
item.textContent?.includes("VSCodium"),
|
||||
) ?? null,
|
||||
"Unable to find VSCodium menu item.",
|
||||
);
|
||||
(vscodiumItem as HTMLElement).click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.shellOpenInEditor,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.shellOpenInEditor,
|
||||
cwd: "/repo/project",
|
||||
editor: "vscodium",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to the first installed editor when the stored favorite is unavailable", async () => {
|
||||
localStorage.setItem("t3code:last-editor", "vscodium");
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
availableEditors: ["vscode-insiders"],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const openButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.trim() === "Open",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Open button.",
|
||||
);
|
||||
openButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.shellOpenInEditor,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.shellOpenInEditor,
|
||||
cwd: "/repo/project",
|
||||
editor: "vscode-insiders",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("runs project scripts from local draft threads at the project cwd", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadId: {
|
||||
@@ -1369,154 +1206,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("runs setup scripts after preparing a pull request worktree thread", 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: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
]),
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.gitResolvePullRequest) {
|
||||
return {
|
||||
pullRequest: {
|
||||
number: 1359,
|
||||
title: "Add thread archiving and settings navigation",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/1359",
|
||||
baseBranch: "main",
|
||||
headBranch: "archive-settings-overhaul",
|
||||
state: "open",
|
||||
},
|
||||
};
|
||||
}
|
||||
if (body._tag === WS_METHODS.gitPreparePullRequestThread) {
|
||||
return {
|
||||
pullRequest: {
|
||||
number: 1359,
|
||||
title: "Add thread archiving and settings navigation",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/1359",
|
||||
baseBranch: "main",
|
||||
headBranch: "archive-settings-overhaul",
|
||||
state: "open",
|
||||
},
|
||||
branch: "archive-settings-overhaul",
|
||||
worktreePath: "/repo/worktrees/pr-1359",
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const branchButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.trim() === "main",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find branch selector button.",
|
||||
);
|
||||
branchButton.click();
|
||||
|
||||
const branchInput = await waitForElement(
|
||||
() => document.querySelector<HTMLInputElement>('input[placeholder="Search branches..."]'),
|
||||
"Unable to find branch search input.",
|
||||
);
|
||||
branchInput.focus();
|
||||
await page.getByPlaceholder("Search branches...").fill("1359");
|
||||
|
||||
const checkoutItem = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("span")).find(
|
||||
(element) => element.textContent?.trim() === "Checkout Pull Request",
|
||||
) as HTMLSpanElement | null,
|
||||
"Unable to find checkout pull request option.",
|
||||
);
|
||||
checkoutItem.click();
|
||||
|
||||
const worktreeButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.trim() === "Worktree",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Worktree button.",
|
||||
);
|
||||
worktreeButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const prepareRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.gitPreparePullRequestThread,
|
||||
);
|
||||
expect(prepareRequest).toMatchObject({
|
||||
_tag: WS_METHODS.gitPreparePullRequestThread,
|
||||
cwd: "/repo/project",
|
||||
reference: "1359",
|
||||
mode: "worktree",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) =>
|
||||
request._tag === WS_METHODS.terminalOpen && request.cwd === "/repo/worktrees/pr-1359",
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.terminalOpen,
|
||||
threadId: expect.any(String),
|
||||
cwd: "/repo/worktrees/pr-1359",
|
||||
env: {
|
||||
T3CODE_PROJECT_ROOT: "/repo/project",
|
||||
T3CODE_WORKTREE_PATH: "/repo/worktrees/pr-1359",
|
||||
},
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const writeRequest = wsRequests.find(
|
||||
(request) =>
|
||||
request._tag === WS_METHODS.terminalWrite && request.data === "bun install\r",
|
||||
);
|
||||
expect(writeRequest).toMatchObject({
|
||||
_tag: WS_METHODS.terminalWrite,
|
||||
threadId: expect.any(String),
|
||||
data: "bun install\r",
|
||||
});
|
||||
},
|
||||
{ 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,
|
||||
|
||||
@@ -32,7 +32,6 @@ export function buildLocalDraftThread(
|
||||
messages: [],
|
||||
error,
|
||||
createdAt: draftThread.createdAt,
|
||||
archivedAt: null,
|
||||
latestTurn: null,
|
||||
lastVisitedAt: draftThread.createdAt,
|
||||
branch: draftThread.branch,
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
type MessageId,
|
||||
type ModelSelection,
|
||||
type ProjectScript,
|
||||
type ModelSlug,
|
||||
type ProviderKind,
|
||||
type ProjectEntry,
|
||||
type ProjectId,
|
||||
@@ -239,12 +240,6 @@ interface ChatViewProps {
|
||||
threadId: ThreadId;
|
||||
}
|
||||
|
||||
interface PendingPullRequestSetupRequest {
|
||||
threadId: ThreadId;
|
||||
worktreePath: string;
|
||||
scriptId: string;
|
||||
}
|
||||
|
||||
export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const threads = useStore((store) => store.threads);
|
||||
const projects = useStore((store) => store.projects);
|
||||
@@ -356,8 +351,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
|
||||
const [pullRequestDialogState, setPullRequestDialogState] =
|
||||
useState<PullRequestDialogState | null>(null);
|
||||
const [pendingPullRequestSetupRequest, setPendingPullRequestSetupRequest] =
|
||||
useState<PendingPullRequestSetupRequest | null>(null);
|
||||
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
|
||||
Record<string, string[]>
|
||||
>({});
|
||||
@@ -535,14 +528,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
params: { threadId: storedDraftThread.threadId },
|
||||
});
|
||||
}
|
||||
return storedDraftThread.threadId;
|
||||
return;
|
||||
}
|
||||
|
||||
const activeDraftThread = getDraftThread(threadId);
|
||||
if (!isServerThread && activeDraftThread?.projectId === activeProject.id) {
|
||||
setDraftThreadContext(threadId, input);
|
||||
setProjectDraftThreadId(activeProject.id, threadId, input);
|
||||
return threadId;
|
||||
return;
|
||||
}
|
||||
|
||||
clearProjectDraftThreadId(activeProject.id);
|
||||
@@ -557,7 +550,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
to: "/$threadId",
|
||||
params: { threadId: nextThreadId },
|
||||
});
|
||||
return nextThreadId;
|
||||
},
|
||||
[
|
||||
activeProject,
|
||||
@@ -574,24 +566,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
const handlePreparedPullRequestThread = useCallback(
|
||||
async (input: { branch: string; worktreePath: string | null }) => {
|
||||
const targetThreadId = await openOrReuseProjectDraftThread({
|
||||
await openOrReuseProjectDraftThread({
|
||||
branch: input.branch,
|
||||
worktreePath: input.worktreePath,
|
||||
envMode: input.worktreePath ? "worktree" : "local",
|
||||
});
|
||||
const setupScript =
|
||||
input.worktreePath && activeProject ? setupProjectScript(activeProject.scripts) : null;
|
||||
if (targetThreadId && input.worktreePath && setupScript) {
|
||||
setPendingPullRequestSetupRequest({
|
||||
threadId: targetThreadId,
|
||||
worktreePath: input.worktreePath,
|
||||
scriptId: setupScript.id,
|
||||
});
|
||||
} else {
|
||||
setPendingPullRequestSetupRequest(null);
|
||||
}
|
||||
},
|
||||
[activeProject, openOrReuseProjectDraftThread],
|
||||
[openOrReuseProjectDraftThread],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -1438,45 +1419,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
terminalState.terminalIds,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingPullRequestSetupRequest || !activeProject || !activeThreadId || !activeThread) {
|
||||
return;
|
||||
}
|
||||
if (pendingPullRequestSetupRequest.threadId !== activeThreadId) {
|
||||
return;
|
||||
}
|
||||
if (activeThread.worktreePath !== pendingPullRequestSetupRequest.worktreePath) {
|
||||
return;
|
||||
}
|
||||
|
||||
const setupScript =
|
||||
activeProject.scripts.find(
|
||||
(script) => script.id === pendingPullRequestSetupRequest.scriptId,
|
||||
) ?? null;
|
||||
setPendingPullRequestSetupRequest(null);
|
||||
if (!setupScript) {
|
||||
return;
|
||||
}
|
||||
|
||||
void runProjectScript(setupScript, {
|
||||
cwd: pendingPullRequestSetupRequest.worktreePath,
|
||||
worktreePath: pendingPullRequestSetupRequest.worktreePath,
|
||||
rememberAsLastInvoked: false,
|
||||
}).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to run setup script.",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
});
|
||||
}, [
|
||||
activeProject,
|
||||
activeThread,
|
||||
activeThreadId,
|
||||
pendingPullRequestSetupRequest,
|
||||
runProjectScript,
|
||||
]);
|
||||
const persistProjectScripts = useCallback(
|
||||
async (input: {
|
||||
projectId: ProjectId;
|
||||
@@ -3163,7 +3105,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
]);
|
||||
|
||||
const onProviderModelSelect = useCallback(
|
||||
(provider: ProviderKind, model: string) => {
|
||||
(provider: ProviderKind, model: ModelSlug) => {
|
||||
if (!activeThread) return;
|
||||
if (lockedProvider !== null && provider !== lockedProvider) {
|
||||
scheduleComposerFocus();
|
||||
@@ -3674,7 +3616,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-[20px] border bg-card transition-colors duration-200 has-focus-visible:border-ring/45",
|
||||
"rounded-[20px] border bg-card transition-colors duration-200 focus-within:border-ring/45",
|
||||
isDragOverComposer ? "border-primary/70 bg-accent/30" : "border-border",
|
||||
composerProviderState.composerSurfaceClassName,
|
||||
)}
|
||||
@@ -4092,7 +4034,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
) : (
|
||||
<button
|
||||
type="submit"
|
||||
className="flex h-9 w-9 enabled:cursor-pointer items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:pointer-events-none disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
|
||||
className="flex h-9 w-9 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
|
||||
disabled={
|
||||
isSendBusy || isConnecting || !composerSendState.hasSendableContent
|
||||
}
|
||||
|
||||
@@ -750,7 +750,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
{initMutation.isPending ? "Initializing..." : "Initialize Git"}
|
||||
</Button>
|
||||
) : (
|
||||
<Group aria-label="Git actions" className="shrink-0">
|
||||
<Group aria-label="Git actions">
|
||||
{quickActionDisabledReason ? (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
@@ -765,7 +765,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
}
|
||||
>
|
||||
<GitQuickActionIcon quickAction={quickAction} />
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
{quickAction.label}
|
||||
</span>
|
||||
</PopoverTrigger>
|
||||
@@ -781,12 +781,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
onClick={runQuickAction}
|
||||
>
|
||||
<GitQuickActionIcon quickAction={quickAction} />
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
{quickAction.label}
|
||||
</span>
|
||||
</Button>
|
||||
)}
|
||||
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
||||
<GroupSeparator className="hidden @sm/header-actions:block" />
|
||||
<Menu
|
||||
onOpenChange={(open) => {
|
||||
if (open) void invalidateGitQueries(queryClient);
|
||||
|
||||
@@ -102,7 +102,6 @@ function createMinimalSnapshot(): OrchestrationReadModel {
|
||||
latestTurn: null,
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import { FolderIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
function getServerHttpOrigin(): string {
|
||||
const bridgeUrl = window.desktopBridge?.getWsUrl();
|
||||
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsUrl =
|
||||
bridgeUrl && bridgeUrl.length > 0
|
||||
? bridgeUrl
|
||||
: envUrl && envUrl.length > 0
|
||||
? envUrl
|
||||
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`;
|
||||
// Parse to extract just the origin, dropping path/query (e.g. ?token=…)
|
||||
const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
|
||||
try {
|
||||
return new URL(httpUrl).origin;
|
||||
} catch {
|
||||
return httpUrl;
|
||||
}
|
||||
}
|
||||
|
||||
const serverHttpOrigin = getServerHttpOrigin();
|
||||
|
||||
const loadedProjectFaviconSrcs = new Set<string>();
|
||||
|
||||
export function ProjectFavicon({ cwd, className }: { cwd: string; className?: string }) {
|
||||
const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`;
|
||||
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
|
||||
loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading",
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{status !== "loaded" ? (
|
||||
<FolderIcon className={`size-3.5 shrink-0 text-muted-foreground/50 ${className ?? ""}`} />
|
||||
) : null}
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loaded" ? "" : "hidden"} ${className ?? ""}`}
|
||||
onLoad={() => {
|
||||
loadedProjectFaviconSrcs.add(src);
|
||||
setStatus("loaded");
|
||||
}}
|
||||
onError={() => setStatus("error")}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -277,11 +277,11 @@ export default function ProjectScriptsControl({
|
||||
title={`Run ${primaryScript.name}`}
|
||||
>
|
||||
<ScriptIcon icon={primaryScript.icon} />
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
{primaryScript.name}
|
||||
</span>
|
||||
</Button>
|
||||
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
||||
<GroupSeparator className="hidden @sm/header-actions:block" />
|
||||
<Menu highlightItemOnHover={false}>
|
||||
<MenuTrigger
|
||||
render={<Button size="icon-xs" variant="outline" aria-label="Script actions" />}
|
||||
@@ -342,7 +342,7 @@ export default function ProjectScriptsControl({
|
||||
) : (
|
||||
<Button size="xs" variant="outline" onClick={openAddDialog} title="Add action">
|
||||
<PlusIcon className="size-3.5" />
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
Add action
|
||||
</span>
|
||||
</Button>
|
||||
|
||||
@@ -153,9 +153,9 @@ export function PullRequestThreadDialog({
|
||||
const validationMessage = !referenceDirty
|
||||
? null
|
||||
: reference.trim().length === 0
|
||||
? "Paste a GitHub pull request URL, `gh pr checkout 123`, or enter 123 / #123."
|
||||
? "Paste a GitHub pull request URL or enter 123 / #123."
|
||||
: parsedReference === null
|
||||
? "Use a GitHub pull request URL, `gh pr checkout 123`, 123, or #123."
|
||||
? "Use a GitHub pull request URL, 123, or #123."
|
||||
: null;
|
||||
const errorMessage =
|
||||
validationMessage ??
|
||||
@@ -191,7 +191,7 @@ export function PullRequestThreadDialog({
|
||||
<span className="text-xs font-medium text-foreground">Pull request</span>
|
||||
<Input
|
||||
ref={referenceInputRef}
|
||||
placeholder="https://github.com/owner/repo/pull/42, gh pr checkout 42, or #42"
|
||||
placeholder="https://github.com/owner/repo/pull/42 or #42"
|
||||
value={reference}
|
||||
onChange={(event) => {
|
||||
setReferenceDirty(true);
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
getVisibleThreadsForProject,
|
||||
getProjectSortTimestamp,
|
||||
hasUnseenCompletion,
|
||||
isContextMenuPointerDown,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveThreadRowClassName,
|
||||
@@ -97,38 +96,6 @@ describe("resolveSidebarNewThreadEnvMode", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isContextMenuPointerDown", () => {
|
||||
it("treats secondary-button presses as context menu gestures on all platforms", () => {
|
||||
expect(
|
||||
isContextMenuPointerDown({
|
||||
button: 2,
|
||||
ctrlKey: false,
|
||||
isMac: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("treats ctrl+primary-click as a context menu gesture on macOS", () => {
|
||||
expect(
|
||||
isContextMenuPointerDown({
|
||||
button: 0,
|
||||
ctrlKey: true,
|
||||
isMac: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not treat ctrl+primary-click as a context menu gesture off macOS", () => {
|
||||
expect(
|
||||
isContextMenuPointerDown({
|
||||
button: 0,
|
||||
ctrlKey: true,
|
||||
isMac: false,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadStatusPill", () => {
|
||||
const baseThread = {
|
||||
interactionMode: "plan" as const,
|
||||
@@ -413,7 +380,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
archivedAt: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
latestTurn: null,
|
||||
branch: null,
|
||||
@@ -731,43 +697,6 @@ describe("sortProjectsForSidebar", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("ignores archived threads when sorting projects", () => {
|
||||
const sorted = sortProjectsForSidebar(
|
||||
[
|
||||
makeProject({
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
name: "Visible project",
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
}),
|
||||
makeProject({
|
||||
id: ProjectId.makeUnsafe("project-2"),
|
||||
name: "Archived-only project",
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-visible"),
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
updatedAt: "2026-03-09T10:02:00.000Z",
|
||||
archivedAt: null,
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-archived"),
|
||||
projectId: ProjectId.makeUnsafe("project-2"),
|
||||
updatedAt: "2026-03-09T10:10:00.000Z",
|
||||
archivedAt: "2026-03-09T10:11:00.000Z",
|
||||
}),
|
||||
].filter((thread) => thread.archivedAt === null),
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((project) => project.id)).toEqual([
|
||||
ProjectId.makeUnsafe("project-1"),
|
||||
ProjectId.makeUnsafe("project-2"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns the project timestamp when no threads are present", () => {
|
||||
const timestamp = getProjectSortTimestamp(
|
||||
makeProject({ updatedAt: "2026-03-09T10:10:00.000Z" }),
|
||||
|
||||
@@ -67,15 +67,6 @@ export function resolveSidebarNewThreadEnvMode(input: {
|
||||
return input.requestedEnvMode ?? input.defaultEnvMode;
|
||||
}
|
||||
|
||||
export function isContextMenuPointerDown(input: {
|
||||
button: number;
|
||||
ctrlKey: boolean;
|
||||
isMac: boolean;
|
||||
}): boolean {
|
||||
if (input.button === 2) return true;
|
||||
return input.isMac && input.button === 0 && input.ctrlKey;
|
||||
}
|
||||
|
||||
export function resolveThreadRowClassName(input: {
|
||||
isActive: boolean;
|
||||
isSelected: boolean;
|
||||
|
||||
+459
-424
File diff suppressed because it is too large.
Load diff
@@ -62,7 +62,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
onToggleDiff,
|
||||
}: ChatHeaderProps) {
|
||||
return (
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
|
||||
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
|
||||
<h2
|
||||
@@ -72,8 +72,8 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
{activeThreadTitle}
|
||||
</h2>
|
||||
{activeProjectName && (
|
||||
<Badge variant="outline" className="min-w-0 shrink overflow-hidden">
|
||||
<span className="min-w-0 truncate">{activeProjectName}</span>
|
||||
<Badge variant="outline" className="min-w-0 shrink truncate">
|
||||
{activeProjectName}
|
||||
</Badge>
|
||||
)}
|
||||
{activeProjectName && !isGitRepo && (
|
||||
@@ -82,7 +82,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3">
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 items-center justify-end gap-2 @sm/header-actions:gap-3">
|
||||
{activeProjectScripts && (
|
||||
<ProjectScriptsControl
|
||||
scripts={activeProjectScripts}
|
||||
|
||||
@@ -60,22 +60,9 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-haiku-4-5",
|
||||
name: "Claude Haiku 4.5",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
name: "Claude Sonnet 4.6",
|
||||
@@ -89,7 +76,6 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
@@ -106,7 +92,6 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -220,7 +205,7 @@ describe("CompactComposerControlsMenu", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("shows prompt-controlled Ultrathink state with selectable effort controls", async () => {
|
||||
it("shows prompt-controlled Ultrathink messaging with disabled effort controls", async () => {
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
@@ -235,27 +220,8 @@ describe("CompactComposerControlsMenu", () => {
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Effort");
|
||||
expect(text).not.toContain("ultrathink");
|
||||
});
|
||||
});
|
||||
|
||||
it("warns when ultrathink appears in prompt body text", async () => {
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: { effort: "high" },
|
||||
},
|
||||
prompt: "Ultrathink:\nplease ultrathink about this problem",
|
||||
});
|
||||
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain(
|
||||
'Your prompt contains "ultrathink" in the text. Remove it to change effort.',
|
||||
);
|
||||
expect(text).toContain("Remove Ultrathink from the prompt to change effort.");
|
||||
expect(text).not.toContain("Fallback Effort");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ProjectEntry, type ProviderKind } from "@t3tools/contracts";
|
||||
import { type ProjectEntry, type ModelSlug, type ProviderKind } from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
|
||||
import { BotIcon } from "lucide-react";
|
||||
@@ -27,7 +27,7 @@ export type ComposerCommandItem =
|
||||
id: string;
|
||||
type: "model";
|
||||
provider: ProviderKind;
|
||||
model: string;
|
||||
model: ModelSlug;
|
||||
label: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
@@ -22,16 +22,6 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
|
||||
Icon: VisualStudioCode,
|
||||
value: "vscode",
|
||||
},
|
||||
{
|
||||
label: "VS Code Insiders",
|
||||
Icon: VisualStudioCode,
|
||||
value: "vscode-insiders",
|
||||
},
|
||||
{
|
||||
label: "VSCodium",
|
||||
Icon: VisualStudioCode,
|
||||
value: "vscodium",
|
||||
},
|
||||
{
|
||||
label: "Zed",
|
||||
Icon: Zed,
|
||||
@@ -111,11 +101,11 @@ export const OpenInPicker = memo(function OpenInPicker({
|
||||
onClick={() => openInEditor(preferredEditor)}
|
||||
>
|
||||
{primaryOption?.Icon && <primaryOption.Icon aria-hidden="true" className="size-3.5" />}
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
Open
|
||||
</span>
|
||||
</Button>
|
||||
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
||||
<GroupSeparator className="hidden @sm/header-actions:block" />
|
||||
<Menu>
|
||||
<MenuTrigger render={<Button aria-label="Copy options" size="icon-xs" variant="outline" />}>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-4" />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ProviderKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { type ModelSlug, type ProviderKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
@@ -33,7 +33,6 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -45,7 +44,6 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -73,7 +71,6 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -90,7 +87,6 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -102,7 +98,6 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -112,7 +107,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
|
||||
async function mountPicker(props: {
|
||||
provider: ProviderKind;
|
||||
model: string;
|
||||
model: ModelSlug;
|
||||
lockedProvider: ProviderKind | null;
|
||||
providers?: ReadonlyArray<ServerProvider>;
|
||||
triggerVariant?: "ghost" | "outline";
|
||||
@@ -271,7 +266,6 @@ describe("ProviderModelPicker", () => {
|
||||
disabledProviders[claudeIndex] = {
|
||||
...claudeProvider,
|
||||
enabled: false,
|
||||
status: "disabled",
|
||||
};
|
||||
}
|
||||
const mounted = await mountPicker({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ProviderKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { type ModelSlug, type ProviderKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { resolveSelectableModel } from "@t3tools/shared/model";
|
||||
import { memo, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
@@ -52,7 +52,7 @@ function providerIconClassName(
|
||||
|
||||
export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
provider: ProviderKind;
|
||||
model: string;
|
||||
model: ModelSlug;
|
||||
lockedProvider: ProviderKind | null;
|
||||
providers?: ReadonlyArray<ServerProvider>;
|
||||
modelOptionsByProvider: Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>>;
|
||||
@@ -61,7 +61,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
disabled?: boolean;
|
||||
triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
|
||||
triggerClassName?: string;
|
||||
onProviderModelChange: (provider: ProviderKind, model: string) => void;
|
||||
onProviderModelChange: (provider: ProviderKind, model: ModelSlug) => void;
|
||||
}) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const activeProvider = props.lockedProvider ?? props.provider;
|
||||
|
||||
@@ -49,7 +49,6 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -78,7 +77,6 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
@@ -95,7 +93,6 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
@@ -107,7 +104,6 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -296,7 +292,7 @@ describe("TraitsPicker (Claude)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("shows prompt-controlled Ultrathink state with selectable effort controls", async () => {
|
||||
it("shows prompt-controlled Ultrathink state with disabled effort controls", async () => {
|
||||
await using _ = await mountClaudePicker({
|
||||
model: "claude-opus-4-6",
|
||||
options: { effort: "high" },
|
||||
@@ -312,24 +308,8 @@ describe("TraitsPicker (Claude)", () => {
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Effort");
|
||||
expect(text).not.toContain("ultrathink");
|
||||
});
|
||||
});
|
||||
|
||||
it("warns when ultrathink appears in prompt body text", async () => {
|
||||
await using _ = await mountClaudePicker({
|
||||
model: "claude-opus-4-6",
|
||||
options: { effort: "high" },
|
||||
prompt: "Ultrathink:\nplease ultrathink about this problem",
|
||||
});
|
||||
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain(
|
||||
'Your prompt contains "ultrathink" in the text. Remove it to change effort.',
|
||||
);
|
||||
expect(text).toContain("Remove Ultrathink from the prompt to change effort.");
|
||||
expect(text).not.toContain("Fallback Effort");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -470,10 +450,10 @@ describe("TraitsPicker (Codex)", () => {
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Extra High");
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).not.toContain("Low");
|
||||
expect(text).not.toContain("Medium");
|
||||
expect(text).toContain("Extra High");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -11,9 +11,7 @@ import {
|
||||
isClaudeUltrathinkPrompt,
|
||||
trimOrNull,
|
||||
getDefaultEffort,
|
||||
getDefaultContextWindow,
|
||||
hasContextWindowOption,
|
||||
resolveEffort,
|
||||
hasEffortLevel,
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
@@ -55,16 +53,6 @@ function getRawEffort(
|
||||
return trimOrNull((modelOptions as ClaudeModelOptions | undefined)?.effort);
|
||||
}
|
||||
|
||||
function getRawContextWindow(
|
||||
provider: ProviderKind,
|
||||
modelOptions: ProviderOptions | null | undefined,
|
||||
): string | null {
|
||||
if (provider === "claudeAgent") {
|
||||
return trimOrNull((modelOptions as ClaudeModelOptions | undefined)?.contextWindow);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildNextOptions(
|
||||
provider: ProviderKind,
|
||||
modelOptions: ProviderOptions | null | undefined,
|
||||
@@ -90,10 +78,21 @@ function getSelectedTraits(
|
||||
: caps.reasoningEffortLevels.filter(
|
||||
(option) => !caps.promptInjectedEffortLevels.includes(option.value),
|
||||
);
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
|
||||
// Resolve effort from options (provider-specific key)
|
||||
const rawEffort = getRawEffort(provider, modelOptions);
|
||||
const effort = resolveEffort(caps, rawEffort) ?? null;
|
||||
const resolvedEffort = getRawEffort(provider, modelOptions);
|
||||
|
||||
// Filter out prompt-injected efforts from the "current effort" display
|
||||
const isPromptInjected = resolvedEffort
|
||||
? caps.promptInjectedEffortLevels.includes(resolvedEffort)
|
||||
: false;
|
||||
const effort =
|
||||
resolvedEffort && !isPromptInjected && hasEffortLevel(caps, resolvedEffort)
|
||||
? resolvedEffort
|
||||
: defaultEffort && hasEffortLevel(caps, defaultEffort)
|
||||
? defaultEffort
|
||||
: null;
|
||||
|
||||
// Thinking toggle (only for models that support it)
|
||||
const thinkingEnabled = caps.supportsThinkingToggle
|
||||
@@ -105,36 +104,19 @@ function getSelectedTraits(
|
||||
caps.supportsFastMode &&
|
||||
(modelOptions as { fastMode?: boolean } | undefined)?.fastMode === true;
|
||||
|
||||
// Context window
|
||||
const contextWindowOptions = caps.contextWindowOptions;
|
||||
const rawContextWindow = getRawContextWindow(provider, modelOptions);
|
||||
const defaultContextWindow = getDefaultContextWindow(caps);
|
||||
const contextWindow =
|
||||
rawContextWindow && hasContextWindowOption(caps, rawContextWindow)
|
||||
? rawContextWindow
|
||||
: defaultContextWindow;
|
||||
|
||||
// Prompt-controlled effort (e.g. ultrathink in prompt text)
|
||||
const ultrathinkPromptControlled =
|
||||
allowPromptInjectedEffort &&
|
||||
caps.promptInjectedEffortLevels.length > 0 &&
|
||||
isClaudeUltrathinkPrompt(prompt);
|
||||
|
||||
// Check if "ultrathink" appears in the body text (not just our prefix)
|
||||
const ultrathinkInBodyText =
|
||||
ultrathinkPromptControlled && isClaudeUltrathinkPrompt(prompt.replace(/^Ultrathink:\s*/i, ""));
|
||||
|
||||
return {
|
||||
caps,
|
||||
effort,
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
contextWindowOptions,
|
||||
contextWindow,
|
||||
defaultContextWindow,
|
||||
ultrathinkPromptControlled,
|
||||
ultrathinkInBodyText,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -177,16 +159,13 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
contextWindowOptions,
|
||||
contextWindow,
|
||||
defaultContextWindow,
|
||||
ultrathinkPromptControlled,
|
||||
ultrathinkInBodyText,
|
||||
} = getSelectedTraits(provider, models, model, prompt, modelOptions, allowPromptInjectedEffort);
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
|
||||
const handleEffortChange = useCallback(
|
||||
(value: string) => {
|
||||
if (ultrathinkPromptControlled) return;
|
||||
if (!value) return;
|
||||
const nextOption = effortLevels.find((option) => option.value === value);
|
||||
if (!nextOption) return;
|
||||
@@ -198,11 +177,6 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
onPromptChange(nextPrompt);
|
||||
return;
|
||||
}
|
||||
if (ultrathinkInBodyText) return;
|
||||
if (ultrathinkPromptControlled) {
|
||||
const stripped = prompt.replace(/^Ultrathink:\s*/i, "");
|
||||
onPromptChange(stripped);
|
||||
}
|
||||
const effortKey = provider === "codex" ? "reasoningEffort" : "effort";
|
||||
updateModelOptions(
|
||||
buildNextOptions(provider, modelOptions, { [effortKey]: nextOption.value }),
|
||||
@@ -210,7 +184,6 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
},
|
||||
[
|
||||
ultrathinkPromptControlled,
|
||||
ultrathinkInBodyText,
|
||||
modelOptions,
|
||||
onPromptChange,
|
||||
updateModelOptions,
|
||||
@@ -221,7 +194,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
],
|
||||
);
|
||||
|
||||
if (effort === null && thinkingEnabled === null && contextWindowOptions.length <= 1) {
|
||||
if (effort === null && thinkingEnabled === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -231,20 +204,17 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
<>
|
||||
<MenuGroup>
|
||||
<div className="px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs">Effort</div>
|
||||
{ultrathinkInBodyText ? (
|
||||
{ultrathinkPromptControlled ? (
|
||||
<div className="px-2 pb-1.5 text-muted-foreground/80 text-xs">
|
||||
Your prompt contains "ultrathink" in the text. Remove it to change effort.
|
||||
Remove Ultrathink from the prompt to change effort.
|
||||
</div>
|
||||
) : null}
|
||||
<MenuRadioGroup
|
||||
value={ultrathinkPromptControlled ? "ultrathink" : effort}
|
||||
onValueChange={handleEffortChange}
|
||||
>
|
||||
<MenuRadioGroup value={effort} onValueChange={handleEffortChange}>
|
||||
{effortLevels.map((option) => (
|
||||
<MenuRadioItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
disabled={ultrathinkInBodyText}
|
||||
disabled={ultrathinkPromptControlled}
|
||||
>
|
||||
{option.label}
|
||||
{option.value === defaultEffort ? " (default)" : ""}
|
||||
@@ -288,33 +258,6 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
{contextWindowOptions.length > 1 ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
Context Window
|
||||
</div>
|
||||
<MenuRadioGroup
|
||||
value={contextWindow ?? defaultContextWindow ?? ""}
|
||||
onValueChange={(value) => {
|
||||
updateModelOptions(
|
||||
buildNextOptions(provider, modelOptions, {
|
||||
contextWindow: value,
|
||||
}),
|
||||
);
|
||||
}}
|
||||
>
|
||||
{contextWindowOptions.map((option) => (
|
||||
<MenuRadioItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
{option.value === defaultContextWindow ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
});
|
||||
@@ -338,19 +281,12 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
contextWindowOptions,
|
||||
contextWindow,
|
||||
defaultContextWindow,
|
||||
ultrathinkPromptControlled,
|
||||
} = getSelectedTraits(provider, models, model, prompt, modelOptions, allowPromptInjectedEffort);
|
||||
|
||||
const effortLabel = effort
|
||||
? (effortLevels.find((l) => l.value === effort)?.label ?? effort)
|
||||
: null;
|
||||
const contextWindowLabel =
|
||||
contextWindowOptions.length > 1 && contextWindow !== defaultContextWindow
|
||||
? (contextWindowOptions.find((o) => o.value === contextWindow)?.label ?? null)
|
||||
: null;
|
||||
const triggerLabel = [
|
||||
ultrathinkPromptControlled
|
||||
? "Ultrathink"
|
||||
@@ -360,7 +296,6 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
? null
|
||||
: `Thinking ${thinkingEnabled ? "On" : "Off"}`,
|
||||
...(caps.supportsFastMode && fastModeEnabled ? ["Fast"] : []),
|
||||
...(contextWindowLabel ? [contextWindowLabel] : []),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
@@ -16,7 +16,6 @@ const CODEX_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -36,7 +35,6 @@ const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
@@ -53,7 +51,6 @@ const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
@@ -65,7 +62,6 @@ const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -84,9 +80,7 @@ describe("getComposerProviderState", () => {
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
modelOptionsForDispatch: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -131,13 +125,12 @@ describe("getComposerProviderState", () => {
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves codex default effort explicitly in dispatch options", () => {
|
||||
it("drops explicit codex default/off overrides from dispatch while keeping the selected effort label", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
@@ -154,9 +147,7 @@ describe("getComposerProviderState", () => {
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
modelOptionsForDispatch: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -172,9 +163,7 @@ describe("getComposerProviderState", () => {
|
||||
expect(state).toEqual({
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
effort: "high",
|
||||
},
|
||||
modelOptionsForDispatch: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -243,13 +232,12 @@ describe("getComposerProviderState", () => {
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
effort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves Claude default effort explicitly in dispatch options", () => {
|
||||
it("drops explicit Claude default/off overrides from dispatch while keeping the selected effort label", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
@@ -266,9 +254,7 @@ describe("getComposerProviderState", () => {
|
||||
expect(state).toEqual({
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
effort: "high",
|
||||
},
|
||||
modelOptionsForDispatch: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,16 @@
|
||||
import {
|
||||
type ModelSlug,
|
||||
type ProviderKind,
|
||||
type ProviderModelOptions,
|
||||
type ServerProviderModel,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { isClaudeUltrathinkPrompt, resolveEffort } from "@t3tools/shared/model";
|
||||
import {
|
||||
isClaudeUltrathinkPrompt,
|
||||
trimOrNull,
|
||||
getDefaultEffort,
|
||||
hasEffortLevel,
|
||||
} from "@t3tools/shared/model";
|
||||
import type { ReactNode } from "react";
|
||||
import {
|
||||
getProviderModelCapabilities,
|
||||
@@ -15,7 +21,7 @@ import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
|
||||
|
||||
export type ComposerProviderStateInput = {
|
||||
provider: ProviderKind;
|
||||
model: string;
|
||||
model: ModelSlug;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
prompt: string;
|
||||
modelOptions: ProviderModelOptions | null | undefined;
|
||||
@@ -34,7 +40,7 @@ type ProviderRegistryEntry = {
|
||||
getState: (input: ComposerProviderStateInput) => ComposerProviderState;
|
||||
renderTraitsMenuContent: (input: {
|
||||
threadId: ThreadId;
|
||||
model: string;
|
||||
model: ModelSlug;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
@@ -42,7 +48,7 @@ type ProviderRegistryEntry = {
|
||||
}) => ReactNode;
|
||||
renderTraitsPicker: (input: {
|
||||
threadId: ThreadId;
|
||||
model: string;
|
||||
model: ModelSlug;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
@@ -66,7 +72,17 @@ function getProviderStateFromCapabilities(
|
||||
: null
|
||||
: null;
|
||||
|
||||
const promptEffort = resolveEffort(caps, rawEffort) ?? null;
|
||||
const draftEffort = trimOrNull(rawEffort);
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
const isPromptInjected = draftEffort
|
||||
? caps.promptInjectedEffortLevels.includes(draftEffort)
|
||||
: false;
|
||||
const promptEffort =
|
||||
draftEffort && !isPromptInjected && hasEffortLevel(caps, draftEffort)
|
||||
? draftEffort
|
||||
: defaultEffort && hasEffortLevel(caps, defaultEffort)
|
||||
? defaultEffort
|
||||
: null;
|
||||
|
||||
// Normalize options for dispatch
|
||||
const normalizedOptions =
|
||||
@@ -164,7 +180,7 @@ export function getComposerProviderState(input: ComposerProviderStateInput): Com
|
||||
export function renderProviderTraitsMenuContent(input: {
|
||||
provider: ProviderKind;
|
||||
threadId: ThreadId;
|
||||
model: string;
|
||||
model: ModelSlug;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
@@ -183,7 +199,7 @@ export function renderProviderTraitsMenuContent(input: {
|
||||
export function renderProviderTraitsPicker(input: {
|
||||
provider: ProviderKind;
|
||||
threadId: ThreadId;
|
||||
model: string;
|
||||
model: ModelSlug;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
|
||||
@@ -145,26 +145,19 @@ describe("getDesktopUpdateActionError", () => {
|
||||
});
|
||||
|
||||
describe("desktop update UI helpers", () => {
|
||||
it("toasts only for actionable updater errors", () => {
|
||||
it("toasts only for accepted incomplete actions", () => {
|
||||
expect(
|
||||
shouldToastDesktopUpdateActionResult({
|
||||
accepted: true,
|
||||
completed: false,
|
||||
state: { ...baseState, message: "checksum mismatch" },
|
||||
state: baseState,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldToastDesktopUpdateActionResult({
|
||||
accepted: true,
|
||||
completed: false,
|
||||
state: { ...baseState, message: null },
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldToastDesktopUpdateActionResult({
|
||||
accepted: true,
|
||||
completed: true,
|
||||
state: { ...baseState, message: "checksum mismatch" },
|
||||
state: baseState,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
@@ -87,7 +87,7 @@ export function getDesktopUpdateActionError(result: DesktopUpdateActionResult):
|
||||
}
|
||||
|
||||
export function shouldToastDesktopUpdateActionResult(result: DesktopUpdateActionResult): boolean {
|
||||
return getDesktopUpdateActionError(result) !== null;
|
||||
return result.accepted && !result.completed;
|
||||
}
|
||||
|
||||
export function shouldHighlightDesktopUpdateError(state: DesktopUpdateState | null): boolean {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,82 +0,0 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { ArchiveIcon, ArrowLeftIcon, Settings2Icon } from "lucide-react";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import {
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarSeparator,
|
||||
} from "../ui/sidebar";
|
||||
|
||||
export type SettingsSectionPath = "/settings/general" | "/settings/archived";
|
||||
|
||||
export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
|
||||
label: string;
|
||||
to: SettingsSectionPath;
|
||||
icon: ComponentType<{ className?: string }>;
|
||||
}> = [
|
||||
{ label: "General", to: "/settings/general", icon: Settings2Icon },
|
||||
{ label: "Archived threads", to: "/settings/archived", icon: ArchiveIcon },
|
||||
];
|
||||
|
||||
export function SettingsSidebarNav({ pathname }: { pathname: string }) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<>
|
||||
<SidebarContent className="overflow-x-hidden">
|
||||
<SidebarGroup className="px-2 py-3">
|
||||
<SidebarMenu>
|
||||
{SETTINGS_NAV_ITEMS.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = pathname === item.to;
|
||||
return (
|
||||
<SidebarMenuItem key={item.to}>
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
isActive={isActive}
|
||||
className={
|
||||
isActive
|
||||
? "gap-2 px-2 py-2 text-left text-xs text-foreground"
|
||||
: "gap-2 px-2 py-2 text-left text-xs text-muted-foreground hover:text-foreground/80"
|
||||
}
|
||||
onClick={() => void navigate({ to: item.to, replace: true })}
|
||||
>
|
||||
<Icon
|
||||
className={
|
||||
isActive
|
||||
? "size-4 shrink-0 text-foreground"
|
||||
: "size-4 shrink-0 text-muted-foreground"
|
||||
}
|
||||
/>
|
||||
<span className="truncate">{item.label}</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
);
|
||||
})}
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
</SidebarContent>
|
||||
|
||||
<SidebarSeparator />
|
||||
<SidebarFooter className="p-2">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="gap-2 px-2 py-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
onClick={() => window.history.back()}
|
||||
>
|
||||
<ArrowLeftIcon className="size-4" />
|
||||
<span>Back</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarFooter>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -5,10 +5,8 @@ import { useEffect, type CSSProperties } from "react";
|
||||
import { useParams } from "@tanstack/react-router";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CheckIcon,
|
||||
CircleAlertIcon,
|
||||
CircleCheckIcon,
|
||||
CopyIcon,
|
||||
InfoIcon,
|
||||
LoaderCircleIcon,
|
||||
TriangleAlertIcon,
|
||||
@@ -16,7 +14,6 @@ import {
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { buttonVariants } from "~/components/ui/button";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { buildVisibleToastLayout, shouldHideCollapsedToastContent } from "./toast.logic";
|
||||
|
||||
type ThreadToastData = {
|
||||
@@ -38,25 +35,6 @@ const TOAST_ICONS = {
|
||||
warning: TriangleAlertIcon,
|
||||
} as const;
|
||||
|
||||
function CopyErrorButton({ text }: { text: string }) {
|
||||
const { copyToClipboard, isCopied } = useCopyToClipboard();
|
||||
|
||||
return (
|
||||
<button
|
||||
className="shrink-0 cursor-pointer rounded-md p-1 text-muted-foreground opacity-60 transition-opacity hover:opacity-100"
|
||||
onClick={() => copyToClipboard(text)}
|
||||
title="Copy error"
|
||||
type="button"
|
||||
>
|
||||
{isCopied ? (
|
||||
<CheckIcon className="size-3.5 text-success" />
|
||||
) : (
|
||||
<CopyIcon className="size-3.5" />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
type ToastPosition =
|
||||
| "top-left"
|
||||
| "top-center"
|
||||
@@ -306,17 +284,12 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
)}
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<div className="flex items-center justify-between gap-1">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
{toast.type === "error" && typeof toast.description === "string" && (
|
||||
<CopyErrorButton text={toast.description} />
|
||||
)}
|
||||
</div>
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
<Toast.Description
|
||||
className="min-w-0 select-text break-words text-muted-foreground"
|
||||
className="min-w-0 break-words text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
@@ -400,17 +373,12 @@ function AnchoredToasts() {
|
||||
)}
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<div className="flex items-center gap-1">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
{toast.type === "error" && typeof toast.description === "string" && (
|
||||
<CopyErrorButton text={toast.description} />
|
||||
)}
|
||||
</div>
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
<Toast.Description
|
||||
className="min-w-0 select-text break-words text-muted-foreground"
|
||||
className="min-w-0 break-words text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
CODEX_REASONING_EFFORT_OPTIONS,
|
||||
type ClaudeCodeEffort,
|
||||
type CodexReasoningEffort,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ModelSlug,
|
||||
ModelSelection,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Equal from "effect/Equal";
|
||||
import { DeepMutable } from "effect/Types";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { getDefaultModel, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { useMemo } from "react";
|
||||
import { getLocalStorageItem } from "./hooks/useLocalStorage";
|
||||
import { resolveAppModelSelection } from "./modelSelection";
|
||||
@@ -263,7 +263,7 @@ interface ComposerDraftStoreState {
|
||||
}
|
||||
|
||||
export interface EffectiveComposerModelState {
|
||||
selectedModel: string;
|
||||
selectedModel: ModelSlug;
|
||||
modelOptions: ProviderModelOptions | null;
|
||||
}
|
||||
|
||||
@@ -475,20 +475,12 @@ function normalizeProviderModelOptions(
|
||||
: claudeCandidate?.fastMode === false
|
||||
? false
|
||||
: undefined;
|
||||
const claudeContextWindow =
|
||||
typeof claudeCandidate?.contextWindow === "string" && claudeCandidate.contextWindow.length > 0
|
||||
? claudeCandidate.contextWindow
|
||||
: undefined;
|
||||
const claude =
|
||||
claudeThinking !== undefined ||
|
||||
claudeEffort !== undefined ||
|
||||
claudeFastMode !== undefined ||
|
||||
claudeContextWindow !== undefined
|
||||
claudeThinking !== undefined || claudeEffort !== undefined || claudeFastMode !== undefined
|
||||
? {
|
||||
...(claudeThinking !== undefined ? { thinking: claudeThinking } : {}),
|
||||
...(claudeEffort !== undefined ? { effort: claudeEffort } : {}),
|
||||
...(claudeFastMode !== undefined ? { fastMode: claudeFastMode } : {}),
|
||||
...(claudeContextWindow !== undefined ? { contextWindow: claudeContextWindow } : {}),
|
||||
}
|
||||
: undefined;
|
||||
|
||||
@@ -602,7 +594,7 @@ function legacyToModelSelectionByProvider(
|
||||
model:
|
||||
modelSelection?.provider === provider
|
||||
? modelSelection.model
|
||||
: DEFAULT_MODEL_BY_PROVIDER[provider],
|
||||
: getDefaultModel(provider),
|
||||
options,
|
||||
};
|
||||
}
|
||||
@@ -1684,7 +1676,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (opts) {
|
||||
nextMap[provider] = {
|
||||
provider,
|
||||
model: current?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider],
|
||||
model: current?.model ?? getDefaultModel(provider),
|
||||
options: opts,
|
||||
};
|
||||
} else if (current?.options) {
|
||||
@@ -1734,7 +1726,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (providerOpts) {
|
||||
nextMap[normalizedProvider] = {
|
||||
provider: normalizedProvider,
|
||||
model: currentForProvider?.model ?? DEFAULT_MODEL_BY_PROVIDER[normalizedProvider],
|
||||
model: currentForProvider?.model ?? getDefaultModel(normalizedProvider),
|
||||
options: providerOpts,
|
||||
};
|
||||
} else if (currentForProvider?.options) {
|
||||
@@ -1752,7 +1744,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
base.modelSelectionByProvider[normalizedProvider] ??
|
||||
({
|
||||
provider: normalizedProvider,
|
||||
model: DEFAULT_MODEL_BY_PROVIDER[normalizedProvider],
|
||||
model: getDefaultModel(normalizedProvider),
|
||||
} as ModelSelection);
|
||||
if (providerOpts) {
|
||||
nextStickyMap[normalizedProvider] = {
|
||||
|
||||
@@ -44,16 +44,10 @@ export function showContextMenuFallback<T extends string>(
|
||||
btn.type = "button";
|
||||
btn.textContent = item.label;
|
||||
const isDestructiveAction = item.destructive === true || item.id === "delete";
|
||||
const isDisabled = item.disabled === true;
|
||||
btn.disabled = isDisabled;
|
||||
btn.className = isDisabled
|
||||
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-muted-foreground/60 cursor-not-allowed"
|
||||
: isDestructiveAction
|
||||
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
|
||||
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
|
||||
if (!isDisabled) {
|
||||
btn.addEventListener("click", () => cleanup(item.id));
|
||||
}
|
||||
btn.className = isDestructiveAction
|
||||
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
|
||||
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
|
||||
btn.addEventListener("click", () => cleanup(item.id));
|
||||
menu.appendChild(btn);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildLegacyClientSettingsMigrationPatch } from "./useSettings";
|
||||
|
||||
describe("buildLegacyClientSettingsMigrationPatch", () => {
|
||||
it("migrates archive confirmation from legacy local settings", () => {
|
||||
expect(
|
||||
buildLegacyClientSettingsMigrationPatch({
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
}),
|
||||
).toEqual({
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -202,10 +202,6 @@ export function buildLegacyClientSettingsMigrationPatch(
|
||||
): Partial<DeepMutable<ClientSettings>> {
|
||||
const patch: Partial<DeepMutable<ClientSettings>> = {};
|
||||
|
||||
if (Predicate.isBoolean(legacySettings.confirmThreadArchive)) {
|
||||
patch.confirmThreadArchive = legacySettings.confirmThreadArchive;
|
||||
}
|
||||
|
||||
if (Predicate.isBoolean(legacySettings.confirmThreadDelete)) {
|
||||
patch.confirmThreadDelete = legacySettings.confirmThreadDelete;
|
||||
}
|
||||
|
||||
@@ -1,211 +0,0 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useHandleNewThread } from "./useHandleNewThread";
|
||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
||||
import { newCommandId } from "../lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useStore } from "../store";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
import { toastManager } from "../components/ui/toast";
|
||||
import { useSettings } from "./useSettings";
|
||||
|
||||
export function useThreadActions() {
|
||||
const threads = useStore((store) => store.threads);
|
||||
const projects = useStore((store) => store.projects);
|
||||
const appSettings = useSettings();
|
||||
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
|
||||
const clearProjectDraftThreadById = useComposerDraftStore(
|
||||
(store) => store.clearProjectDraftThreadById,
|
||||
);
|
||||
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
|
||||
const routeThreadId = useParams({
|
||||
strict: false,
|
||||
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
|
||||
});
|
||||
const navigate = useNavigate();
|
||||
const { handleNewThread } = useHandleNewThread();
|
||||
const queryClient = useQueryClient();
|
||||
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
|
||||
|
||||
const archiveThread = useCallback(
|
||||
async (threadId: ThreadId) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const thread = threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) return;
|
||||
if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
|
||||
throw new Error("Cannot archive a running thread.");
|
||||
}
|
||||
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.archive",
|
||||
commandId: newCommandId(),
|
||||
threadId,
|
||||
});
|
||||
|
||||
if (routeThreadId === threadId) {
|
||||
await handleNewThread(thread.projectId);
|
||||
}
|
||||
},
|
||||
[handleNewThread, routeThreadId, threads],
|
||||
);
|
||||
|
||||
const unarchiveThread = useCallback(async (threadId: ThreadId) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.unarchive",
|
||||
commandId: newCommandId(),
|
||||
threadId,
|
||||
});
|
||||
}, []);
|
||||
|
||||
const deleteThread = useCallback(
|
||||
async (threadId: ThreadId, opts: { deletedThreadIds?: ReadonlySet<ThreadId> } = {}) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const thread = threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) return;
|
||||
const threadProject = projects.find((project) => project.id === thread.projectId);
|
||||
const deletedIds = opts.deletedThreadIds;
|
||||
const survivingThreads =
|
||||
deletedIds && deletedIds.size > 0
|
||||
? threads.filter((entry) => entry.id === threadId || !deletedIds.has(entry.id))
|
||||
: threads;
|
||||
const orphanedWorktreePath = getOrphanedWorktreePathForThread(survivingThreads, threadId);
|
||||
const displayWorktreePath = orphanedWorktreePath
|
||||
? formatWorktreePathForDisplay(orphanedWorktreePath)
|
||||
: null;
|
||||
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
|
||||
const shouldDeleteWorktree =
|
||||
canDeleteWorktree &&
|
||||
(await api.dialogs.confirm(
|
||||
[
|
||||
"This thread is the only one linked to this worktree:",
|
||||
displayWorktreePath ?? orphanedWorktreePath,
|
||||
"",
|
||||
"Delete the worktree too?",
|
||||
].join("\n"),
|
||||
));
|
||||
|
||||
if (thread.session && thread.session.status !== "closed") {
|
||||
await api.orchestration
|
||||
.dispatchCommand({
|
||||
type: "thread.session.stop",
|
||||
commandId: newCommandId(),
|
||||
threadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
try {
|
||||
await api.terminal.close({ threadId, deleteHistory: true });
|
||||
} catch {
|
||||
// Terminal may already be closed.
|
||||
}
|
||||
|
||||
const deletedThreadIds = opts.deletedThreadIds ?? new Set<ThreadId>();
|
||||
const shouldNavigateToFallback = routeThreadId === threadId;
|
||||
const fallbackThreadId = getFallbackThreadIdAfterDelete({
|
||||
threads,
|
||||
deletedThreadId: threadId,
|
||||
deletedThreadIds,
|
||||
sortOrder: appSettings.sidebarThreadSortOrder,
|
||||
});
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.delete",
|
||||
commandId: newCommandId(),
|
||||
threadId,
|
||||
});
|
||||
clearComposerDraftForThread(threadId);
|
||||
clearProjectDraftThreadById(thread.projectId, thread.id);
|
||||
clearTerminalState(threadId);
|
||||
|
||||
if (shouldNavigateToFallback) {
|
||||
if (fallbackThreadId) {
|
||||
await navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: fallbackThreadId },
|
||||
replace: true,
|
||||
});
|
||||
} else {
|
||||
await navigate({ to: "/", replace: true });
|
||||
}
|
||||
}
|
||||
|
||||
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await removeWorktreeMutation.mutateAsync({
|
||||
cwd: threadProject.cwd,
|
||||
path: orphanedWorktreePath,
|
||||
force: true,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
|
||||
console.error("Failed to remove orphaned worktree after thread deletion", {
|
||||
threadId,
|
||||
projectCwd: threadProject.cwd,
|
||||
worktreePath: orphanedWorktreePath,
|
||||
error,
|
||||
});
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Thread deleted, but worktree removal failed",
|
||||
description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
|
||||
});
|
||||
}
|
||||
},
|
||||
[
|
||||
clearComposerDraftForThread,
|
||||
clearProjectDraftThreadById,
|
||||
clearTerminalState,
|
||||
appSettings.sidebarThreadSortOrder,
|
||||
navigate,
|
||||
projects,
|
||||
removeWorktreeMutation,
|
||||
routeThreadId,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
|
||||
const confirmAndDeleteThread = useCallback(
|
||||
async (threadId: ThreadId) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const thread = threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) return;
|
||||
|
||||
if (appSettings.confirmThreadDelete) {
|
||||
const confirmed = await api.dialogs.confirm(
|
||||
[
|
||||
`Delete thread "${thread.title}"?`,
|
||||
"This permanently clears conversation history for this thread.",
|
||||
].join("\n"),
|
||||
);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await deleteThread(threadId);
|
||||
},
|
||||
[appSettings.confirmThreadDelete, deleteThread, threads],
|
||||
);
|
||||
|
||||
return {
|
||||
archiveThread,
|
||||
unarchiveThread,
|
||||
deleteThread,
|
||||
confirmAndDeleteThread,
|
||||
};
|
||||
}
|
||||
@@ -23,42 +23,25 @@ export function createMemoryStorage(): StateStorage {
|
||||
};
|
||||
}
|
||||
|
||||
export function isStateStorage(
|
||||
storage: Partial<StateStorage> | null | undefined,
|
||||
): storage is StateStorage {
|
||||
return (
|
||||
storage !== null &&
|
||||
storage !== undefined &&
|
||||
typeof storage.getItem === "function" &&
|
||||
typeof storage.setItem === "function" &&
|
||||
typeof storage.removeItem === "function"
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveStorage(storage: Partial<StateStorage> | null | undefined): StateStorage {
|
||||
return isStateStorage(storage) ? storage : createMemoryStorage();
|
||||
}
|
||||
|
||||
export function createDebouncedStorage(
|
||||
baseStorage: Partial<StateStorage> | null | undefined,
|
||||
baseStorage: StateStorage,
|
||||
debounceMs: number = 300,
|
||||
): DebouncedStorage {
|
||||
const resolvedStorage = resolveStorage(baseStorage);
|
||||
const debouncedSetItem = new Debouncer(
|
||||
(name: string, value: string) => {
|
||||
resolvedStorage.setItem(name, value);
|
||||
baseStorage.setItem(name, value);
|
||||
},
|
||||
{ wait: debounceMs },
|
||||
);
|
||||
|
||||
return {
|
||||
getItem: (name) => resolvedStorage.getItem(name),
|
||||
getItem: (name) => baseStorage.getItem(name),
|
||||
setItem: (name, value) => {
|
||||
debouncedSetItem.maybeExecute(name, value);
|
||||
},
|
||||
removeItem: (name) => {
|
||||
debouncedSetItem.cancel();
|
||||
resolvedStorage.removeItem(name);
|
||||
baseStorage.removeItem(name);
|
||||
},
|
||||
flush: () => {
|
||||
debouncedSetItem.flush();
|
||||
|
||||
@@ -7,13 +7,17 @@ import {
|
||||
type ServerProvider,
|
||||
type ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeModelSlug, resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
|
||||
import {
|
||||
getDefaultEffort,
|
||||
hasEffortLevel,
|
||||
normalizeModelSlug,
|
||||
trimOrNull,
|
||||
} from "@t3tools/shared/model";
|
||||
|
||||
const EMPTY_CAPABILITIES: ModelCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
};
|
||||
|
||||
@@ -74,10 +78,11 @@ export function normalizeCodexModelOptionsWithCapabilities(
|
||||
caps: ModelCapabilities,
|
||||
modelOptions: CodexModelOptions | null | undefined,
|
||||
): CodexModelOptions | undefined {
|
||||
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
|
||||
const defaultReasoningEffort = getDefaultEffort(caps);
|
||||
const reasoningEffort = trimOrNull(modelOptions?.reasoningEffort) ?? defaultReasoningEffort;
|
||||
const fastModeEnabled = modelOptions?.fastMode === true;
|
||||
const nextOptions: CodexModelOptions = {
|
||||
...(reasoningEffort
|
||||
...(reasoningEffort && reasoningEffort !== defaultReasoningEffort
|
||||
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
|
||||
: {}),
|
||||
...(fastModeEnabled ? { fastMode: true } : {}),
|
||||
@@ -89,16 +94,23 @@ export function normalizeClaudeModelOptionsWithCapabilities(
|
||||
caps: ModelCapabilities,
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): ClaudeModelOptions | undefined {
|
||||
const effort = resolveEffort(caps, modelOptions?.effort);
|
||||
const defaultReasoningEffort = getDefaultEffort(caps);
|
||||
const resolvedEffort = trimOrNull(modelOptions?.effort);
|
||||
const isPromptInjected = caps.promptInjectedEffortLevels.includes(resolvedEffort ?? "");
|
||||
const effort =
|
||||
resolvedEffort &&
|
||||
!isPromptInjected &&
|
||||
hasEffortLevel(caps, resolvedEffort) &&
|
||||
resolvedEffort !== defaultReasoningEffort
|
||||
? resolvedEffort
|
||||
: undefined;
|
||||
const thinking =
|
||||
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
|
||||
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
|
||||
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
|
||||
const nextOptions: ClaudeModelOptions = {
|
||||
...(thinking === false ? { thinking: false } : {}),
|
||||
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
|
||||
...(effort ? { effort } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(contextWindow ? { contextWindow } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
@@ -17,20 +17,6 @@ describe("parsePullRequestReference", () => {
|
||||
expect(parsePullRequestReference("#42")).toBe("#42");
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with raw numbers", () => {
|
||||
expect(parsePullRequestReference("gh pr checkout 42")).toBe("42");
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with #number references", () => {
|
||||
expect(parsePullRequestReference("gh pr checkout #42")).toBe("#42");
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with GitHub pull request URLs", () => {
|
||||
expect(
|
||||
parsePullRequestReference("gh pr checkout https://github.com/pingdotgg/t3code/pull/42"),
|
||||
).toBe("https://github.com/pingdotgg/t3code/pull/42");
|
||||
});
|
||||
|
||||
it("rejects non-pull-request input", () => {
|
||||
expect(parsePullRequestReference("feature/my-branch")).toBeNull();
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
const GITHUB_PULL_REQUEST_URL_PATTERN =
|
||||
/^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)(?:[/?#].*)?$/i;
|
||||
const PULL_REQUEST_NUMBER_PATTERN = /^#?(\d+)$/;
|
||||
const GITHUB_CLI_PR_CHECKOUT_PATTERN = /^gh\s+pr\s+checkout\s+(.+)$/i;
|
||||
|
||||
export function parsePullRequestReference(input: string): string | null {
|
||||
const trimmed = input.trim();
|
||||
@@ -9,20 +8,14 @@ export function parsePullRequestReference(input: string): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
const ghCliCheckoutMatch = GITHUB_CLI_PR_CHECKOUT_PATTERN.exec(trimmed);
|
||||
const normalizedInput = ghCliCheckoutMatch?.[1]?.trim() ?? trimmed;
|
||||
if (normalizedInput.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const urlMatch = GITHUB_PULL_REQUEST_URL_PATTERN.exec(normalizedInput);
|
||||
const urlMatch = GITHUB_PULL_REQUEST_URL_PATTERN.exec(trimmed);
|
||||
if (urlMatch?.[1]) {
|
||||
return normalizedInput;
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const numberMatch = PULL_REQUEST_NUMBER_PATTERN.exec(normalizedInput);
|
||||
const numberMatch = PULL_REQUEST_NUMBER_PATTERN.exec(trimmed);
|
||||
if (numberMatch?.[1]) {
|
||||
return normalizedInput.startsWith("#") ? normalizedInput : numberMatch[1];
|
||||
return trimmed.startsWith("#") ? trimmed : numberMatch[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -9,18 +9,11 @@
|
||||
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
|
||||
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as SettingsRouteImport } from './routes/settings'
|
||||
import { Route as ChatRouteImport } from './routes/_chat'
|
||||
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
|
||||
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
|
||||
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
|
||||
import { Route as ChatSettingsRouteImport } from './routes/_chat.settings'
|
||||
import { Route as ChatThreadIdRouteImport } from './routes/_chat.$threadId'
|
||||
|
||||
const SettingsRoute = SettingsRouteImport.update({
|
||||
id: '/settings',
|
||||
path: '/settings',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const ChatRoute = ChatRouteImport.update({
|
||||
id: '/_chat',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
@@ -30,15 +23,10 @@ const ChatIndexRoute = ChatIndexRouteImport.update({
|
||||
path: '/',
|
||||
getParentRoute: () => ChatRoute,
|
||||
} as any)
|
||||
const SettingsGeneralRoute = SettingsGeneralRouteImport.update({
|
||||
id: '/general',
|
||||
path: '/general',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
|
||||
id: '/archived',
|
||||
path: '/archived',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
const ChatSettingsRoute = ChatSettingsRouteImport.update({
|
||||
id: '/settings',
|
||||
path: '/settings',
|
||||
getParentRoute: () => ChatRoute,
|
||||
} as any)
|
||||
const ChatThreadIdRoute = ChatThreadIdRouteImport.update({
|
||||
id: '/$threadId',
|
||||
@@ -48,66 +36,35 @@ const ChatThreadIdRoute = ChatThreadIdRouteImport.update({
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof ChatIndexRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/$threadId': typeof ChatThreadIdRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/settings': typeof ChatSettingsRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/$threadId': typeof ChatThreadIdRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/settings': typeof ChatSettingsRoute
|
||||
'/': typeof ChatIndexRoute
|
||||
}
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/_chat': typeof ChatRouteWithChildren
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/_chat/$threadId': typeof ChatThreadIdRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/_chat/settings': typeof ChatSettingsRoute
|
||||
'/_chat/': typeof ChatIndexRoute
|
||||
}
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths:
|
||||
| '/'
|
||||
| '/settings'
|
||||
| '/$threadId'
|
||||
| '/settings/archived'
|
||||
| '/settings/general'
|
||||
fullPaths: '/' | '/$threadId' | '/settings'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to:
|
||||
| '/settings'
|
||||
| '/$threadId'
|
||||
| '/settings/archived'
|
||||
| '/settings/general'
|
||||
| '/'
|
||||
id:
|
||||
| '__root__'
|
||||
| '/_chat'
|
||||
| '/settings'
|
||||
| '/_chat/$threadId'
|
||||
| '/settings/archived'
|
||||
| '/settings/general'
|
||||
| '/_chat/'
|
||||
to: '/$threadId' | '/settings' | '/'
|
||||
id: '__root__' | '/_chat' | '/_chat/$threadId' | '/_chat/settings' | '/_chat/'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
ChatRoute: typeof ChatRouteWithChildren
|
||||
SettingsRoute: typeof SettingsRouteWithChildren
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface FileRoutesByPath {
|
||||
'/settings': {
|
||||
id: '/settings'
|
||||
path: '/settings'
|
||||
fullPath: '/settings'
|
||||
preLoaderRoute: typeof SettingsRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/_chat': {
|
||||
id: '/_chat'
|
||||
path: ''
|
||||
@@ -122,19 +79,12 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof ChatIndexRouteImport
|
||||
parentRoute: typeof ChatRoute
|
||||
}
|
||||
'/settings/general': {
|
||||
id: '/settings/general'
|
||||
path: '/general'
|
||||
fullPath: '/settings/general'
|
||||
preLoaderRoute: typeof SettingsGeneralRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/archived': {
|
||||
id: '/settings/archived'
|
||||
path: '/archived'
|
||||
fullPath: '/settings/archived'
|
||||
preLoaderRoute: typeof SettingsArchivedRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
'/_chat/settings': {
|
||||
id: '/_chat/settings'
|
||||
path: '/settings'
|
||||
fullPath: '/settings'
|
||||
preLoaderRoute: typeof ChatSettingsRouteImport
|
||||
parentRoute: typeof ChatRoute
|
||||
}
|
||||
'/_chat/$threadId': {
|
||||
id: '/_chat/$threadId'
|
||||
@@ -148,33 +98,20 @@ declare module '@tanstack/react-router' {
|
||||
|
||||
interface ChatRouteChildren {
|
||||
ChatThreadIdRoute: typeof ChatThreadIdRoute
|
||||
ChatSettingsRoute: typeof ChatSettingsRoute
|
||||
ChatIndexRoute: typeof ChatIndexRoute
|
||||
}
|
||||
|
||||
const ChatRouteChildren: ChatRouteChildren = {
|
||||
ChatThreadIdRoute: ChatThreadIdRoute,
|
||||
ChatSettingsRoute: ChatSettingsRoute,
|
||||
ChatIndexRoute: ChatIndexRoute,
|
||||
}
|
||||
|
||||
const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
|
||||
|
||||
interface SettingsRouteChildren {
|
||||
SettingsArchivedRoute: typeof SettingsArchivedRoute
|
||||
SettingsGeneralRoute: typeof SettingsGeneralRoute
|
||||
}
|
||||
|
||||
const SettingsRouteChildren: SettingsRouteChildren = {
|
||||
SettingsArchivedRoute: SettingsArchivedRoute,
|
||||
SettingsGeneralRoute: SettingsGeneralRoute,
|
||||
}
|
||||
|
||||
const SettingsRouteWithChildren = SettingsRoute._addFileChildren(
|
||||
SettingsRouteChildren,
|
||||
)
|
||||
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
ChatRoute: ChatRouteWithChildren,
|
||||
SettingsRoute: SettingsRouteWithChildren,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
._addFileChildren(rootRouteChildren)
|
||||
|
||||
@@ -11,7 +11,6 @@ import { QueryClient, useQueryClient } from "@tanstack/react-query";
|
||||
import { Throttler } from "@tanstack/react-pacer";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "../branding";
|
||||
import { AppSidebarLayout } from "../components/AppSidebarLayout";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast";
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
@@ -55,9 +54,7 @@ function RootRouteView() {
|
||||
<AnchoredToastProvider>
|
||||
<EventRouter />
|
||||
<DesktopProjectBootstrap />
|
||||
<AppSidebarLayout>
|
||||
<Outlet />
|
||||
</AppSidebarLayout>
|
||||
<Outlet />
|
||||
</AnchoredToastProvider>
|
||||
</ToastProvider>
|
||||
);
|
||||
|
||||
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user