Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89c6025328 |
No files matched your search
@@ -1 +0,0 @@
|
||||
plans/
|
||||
@@ -2,22 +2,15 @@
|
||||
"name": "T3 Code Dev",
|
||||
"image": "debian:bookworm",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/git:1": {},
|
||||
"ghcr.io/devcontainers-extra/features/bun:1": {
|
||||
"version": "1.3.11"
|
||||
},
|
||||
"ghcr.io/devcontainers-extra/features/bun:1": {},
|
||||
"ghcr.io/devcontainers/features/node:1": {
|
||||
"version": "24.13.1"
|
||||
"version": "24",
|
||||
"nodeGypDependencies": true
|
||||
},
|
||||
"ghcr.io/devcontainers/features/python:1": {
|
||||
"version": "3.10",
|
||||
"installTools": false
|
||||
"version": "3.12"
|
||||
}
|
||||
},
|
||||
"overrideFeatureInstallOrder": [
|
||||
"ghcr.io/devcontainers/features/git",
|
||||
"ghcr.io/devcontainers-extra/features/bun"
|
||||
],
|
||||
"postCreateCommand": {
|
||||
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
|
||||
},
|
||||
|
||||
@@ -4,7 +4,6 @@ on:
|
||||
push:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
- "!v*-nightly.*"
|
||||
schedule:
|
||||
- cron: "0 */3 * * *"
|
||||
workflow_dispatch:
|
||||
@@ -42,7 +41,7 @@ jobs:
|
||||
- id: check
|
||||
name: Compare HEAD to last nightly tag
|
||||
run: |
|
||||
last_nightly_tag=$(git tag --list 'v*-nightly.*' 'nightly-v*' --sort=-creatordate | head -n 1)
|
||||
last_nightly_tag=$(git tag --list 'nightly-v*' --sort=-creatordate | head -n 1)
|
||||
if [[ -z "$last_nightly_tag" ]]; then
|
||||
echo "No previous nightly tag found. Proceeding with release."
|
||||
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||
@@ -394,14 +393,6 @@ jobs:
|
||||
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
@@ -486,7 +477,6 @@ jobs:
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
|
||||
- name: Publish first release
|
||||
if: needs.preflight.outputs.previous_tag == ''
|
||||
@@ -506,7 +496,6 @@ jobs:
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
|
||||
+1
-9
@@ -13,13 +13,5 @@
|
||||
"apps/web/src/lib/vendor/qrcodegen.ts",
|
||||
"*.icon/**"
|
||||
],
|
||||
"sortPackageJson": {},
|
||||
"overrides": [
|
||||
{
|
||||
"files": [".devcontainer/devcontainer.json"],
|
||||
"options": {
|
||||
"trailingComma": "none"
|
||||
}
|
||||
}
|
||||
]
|
||||
"sortPackageJson": {}
|
||||
}
|
||||
Vendored
+1
-1
@@ -5,5 +5,5 @@
|
||||
"source.fixAll.oxc": "always"
|
||||
},
|
||||
"oxc.unusedDisableDirectives": "warn",
|
||||
"js/ts.tsdk.path": "node_modules/typescript/lib"
|
||||
"typescript.tsdk": "node_modules/typescript/lib"
|
||||
}
|
||||
@@ -52,7 +52,6 @@ const clientSettings: ClientSettings = {
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
|
||||
+10
-12
@@ -75,7 +75,6 @@ import {
|
||||
} from "./updateMachine.ts";
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
|
||||
import { resolveDesktopAppBranding } from "./appBranding.ts";
|
||||
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
|
||||
|
||||
syncShellEnvironment();
|
||||
|
||||
@@ -1999,17 +1998,16 @@ function createWindow(): BrowserWindow {
|
||||
emitUpdateState();
|
||||
});
|
||||
|
||||
// On Linux/Wayland with `show: false`, Electron's `ready-to-show` only
|
||||
// fires after `show()` is called, deadlocking the standard "wait for
|
||||
// ready, then show" pattern. Add `did-finish-load` as a Linux-only
|
||||
// fallback so the window still surfaces once the renderer has loaded
|
||||
// the page. Other platforms keep the no-flash `ready-to-show` path,
|
||||
// since `did-finish-load` typically fires before the first paint there.
|
||||
const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
|
||||
if (process.platform === "linux") {
|
||||
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
|
||||
}
|
||||
bindFirstRevealTrigger(revealSubscribers, () => revealWindow(window));
|
||||
let initialRevealScheduled = false;
|
||||
const revealInitialWindow = () => {
|
||||
if (initialRevealScheduled) {
|
||||
return;
|
||||
}
|
||||
initialRevealScheduled = true;
|
||||
revealWindow(window);
|
||||
};
|
||||
|
||||
window.once("ready-to-show", revealInitialWindow);
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(resolveDesktopDevServerUrl());
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { bindFirstRevealTrigger } from "./windowReveal.ts";
|
||||
|
||||
describe("bindFirstRevealTrigger", () => {
|
||||
it("reveals when the first trigger fires", () => {
|
||||
const window = new EventEmitter();
|
||||
const webContents = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger(
|
||||
[
|
||||
(fire) => window.once("ready-to-show", fire),
|
||||
(fire) => webContents.once("did-finish-load", fire),
|
||||
],
|
||||
reveal,
|
||||
);
|
||||
|
||||
window.emit("ready-to-show");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("reveals when only the fallback trigger fires (Wayland deadlock case)", () => {
|
||||
const window = new EventEmitter();
|
||||
const webContents = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger(
|
||||
[
|
||||
(fire) => window.once("ready-to-show", fire),
|
||||
(fire) => webContents.once("did-finish-load", fire),
|
||||
],
|
||||
reveal,
|
||||
);
|
||||
|
||||
webContents.emit("did-finish-load");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("only reveals once when multiple triggers fire", () => {
|
||||
const window = new EventEmitter();
|
||||
const webContents = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger(
|
||||
[
|
||||
(fire) => window.once("ready-to-show", fire),
|
||||
(fire) => webContents.once("did-finish-load", fire),
|
||||
],
|
||||
reveal,
|
||||
);
|
||||
|
||||
webContents.emit("did-finish-load");
|
||||
window.emit("ready-to-show");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("subscribers using `once` ignore re-emitted events after reveal", () => {
|
||||
const window = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger([(fire) => window.once("ready-to-show", fire)], reveal);
|
||||
|
||||
window.emit("ready-to-show");
|
||||
window.emit("ready-to-show");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
export type RevealSubscription = (listener: () => void) => void;
|
||||
|
||||
/**
|
||||
* Wire a reveal callback to fire exactly once, on whichever of the provided
|
||||
* event subscribers fires first. Each subscriber is responsible for binding
|
||||
* its own event source.
|
||||
*
|
||||
* Used by the desktop main window's first-paint reveal logic. The standard
|
||||
* Electron pattern is to wait for `ready-to-show` before calling `show()`,
|
||||
* but on Linux/Wayland with `show: false`, `ready-to-show` only fires after
|
||||
* `show()` is called, deadlocking that pattern. Subscribing to both
|
||||
* `ready-to-show` and `did-finish-load` (or any other "renderer is alive"
|
||||
* signal) lets the window surface reliably across platforms.
|
||||
*/
|
||||
export function bindFirstRevealTrigger(
|
||||
subscribers: readonly RevealSubscription[],
|
||||
reveal: () => void,
|
||||
): void {
|
||||
let revealed = false;
|
||||
const fire = () => {
|
||||
if (revealed) return;
|
||||
revealed = true;
|
||||
reveal();
|
||||
};
|
||||
for (const subscribe of subscribers) {
|
||||
subscribe(fire);
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,6 @@
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"effect-codex-app-server": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
import { Effect, FileSystem, Path } from "effect";
|
||||
import * as Random from "effect/Random";
|
||||
|
||||
export const writeFileStringAtomically = (input: {
|
||||
readonly filePath: string;
|
||||
readonly contents: string;
|
||||
}) =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempFileId = yield* Random.nextUUIDv4;
|
||||
const targetDirectory = path.dirname(input.filePath);
|
||||
|
||||
yield* fs.makeDirectory(targetDirectory, { recursive: true });
|
||||
const tempDirectory = yield* fs.makeTempDirectoryScoped({
|
||||
directory: targetDirectory,
|
||||
prefix: `${path.basename(input.filePath)}.`,
|
||||
});
|
||||
const tempPath = path.join(tempDirectory, `${tempFileId}.tmp`);
|
||||
|
||||
yield* fs.writeFileString(tempPath, input.contents);
|
||||
yield* fs.rename(tempPath, input.filePath);
|
||||
}),
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,6 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
@@ -200,10 +199,12 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: {
|
||||
...createModelSelection("claudeAgent", "claude-haiku-4-5", [
|
||||
{ id: "thinking", value: false },
|
||||
{ id: "effort", value: "high" },
|
||||
]),
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
options: {
|
||||
thinking: false,
|
||||
effort: "high",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -234,10 +235,12 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
|
||||
diffSummary: "1 file changed",
|
||||
diffPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: {
|
||||
...createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||
{ id: "effort", value: "max" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -28,17 +28,10 @@ import {
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import {
|
||||
getModelSelectionStringOptionValue,
|
||||
getProviderOptionDescriptors,
|
||||
} from "@t3tools/shared/model";
|
||||
import {
|
||||
getClaudeModelCapabilities,
|
||||
normalizeClaudeCliEffort,
|
||||
resolveClaudeApiModelId,
|
||||
resolveClaudeEffort,
|
||||
} from "../../provider/Layers/ClaudeProvider.ts";
|
||||
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
||||
import { resolveClaudeApiModelId } from "../../provider/Layers/ClaudeProvider.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
|
||||
|
||||
const CLAUDE_TIMEOUT_MS = 180_000;
|
||||
|
||||
@@ -91,24 +84,15 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
modelSelection: ClaudeModelSelection;
|
||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
|
||||
const caps = getClaudeModelCapabilities(modelSelection.model);
|
||||
const descriptors = getProviderOptionDescriptors({
|
||||
caps,
|
||||
selections: modelSelection.options,
|
||||
});
|
||||
const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id);
|
||||
const rawEffortSelection = getModelSelectionStringOptionValue(modelSelection, "effort");
|
||||
const resolvedEffort = resolveClaudeEffort(caps, rawEffortSelection);
|
||||
const cliEffort = normalizeClaudeCliEffort(resolvedEffort);
|
||||
const thinkingDescriptor = findDescriptor("thinking");
|
||||
const fastModeDescriptor = findDescriptor("fastMode");
|
||||
const thinking =
|
||||
thinkingDescriptor?.type === "boolean" ? thinkingDescriptor.currentValue : undefined;
|
||||
const fastMode =
|
||||
fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined;
|
||||
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
|
||||
getClaudeModelCapabilities(modelSelection.model),
|
||||
modelSelection.options,
|
||||
);
|
||||
const settings = {
|
||||
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(typeof normalizedOptions?.thinking === "boolean"
|
||||
? { alwaysThinkingEnabled: normalizedOptions.thinking }
|
||||
: {}),
|
||||
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
|
||||
};
|
||||
|
||||
const claudeSettings = yield* Effect.map(
|
||||
@@ -127,7 +111,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
jsonSchemaStr,
|
||||
"--model",
|
||||
resolveClaudeApiModelId(modelSelection),
|
||||
...(cliEffort ? ["--effort", cliEffort] : []),
|
||||
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
|
||||
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
|
||||
"--dangerously-skip-permissions",
|
||||
],
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, Result } from "effect";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
@@ -245,10 +244,14 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
branch: "feature/codex-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: createModelSelection("codex", "gpt-5.4", [
|
||||
{ id: "reasoningEffort", value: "xhigh" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -8,7 +8,6 @@ import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shar
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
@@ -29,11 +28,9 @@ import {
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import {
|
||||
getModelSelectionBooleanOptionValue,
|
||||
getModelSelectionStringOptionValue,
|
||||
} from "@t3tools/shared/model";
|
||||
import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
|
||||
const CODEX_TIMEOUT_MS = 180_000;
|
||||
@@ -158,9 +155,12 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
|
||||
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
|
||||
getCodexModelCapabilities(modelSelection.model),
|
||||
modelSelection.options,
|
||||
);
|
||||
const reasoningEffort =
|
||||
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
|
||||
CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
||||
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
||||
const command = ChildProcess.make(
|
||||
codexSettings?.binaryPath || "codex",
|
||||
[
|
||||
@@ -173,9 +173,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
modelSelection.model,
|
||||
"--config",
|
||||
`model_reasoning_effort="${reasoningEffort}"`,
|
||||
...(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true
|
||||
? ["--config", `service_tier="fast"`]
|
||||
: []),
|
||||
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
@@ -186,9 +184,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings?.homePath
|
||||
? { CODEX_HOME: expandHomePath(codexSettings.homePath) }
|
||||
: {}),
|
||||
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
},
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
|
||||
@@ -6,7 +6,6 @@ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
@@ -136,11 +135,13 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
|
||||
stagedPatch:
|
||||
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
modelSelection: {
|
||||
...createModelSelection("cursor", "gpt-5.4", [
|
||||
{ id: "reasoning", value: "xhigh" },
|
||||
{ id: "fastMode", value: true },
|
||||
{ id: "contextWindow", value: "1m" },
|
||||
]),
|
||||
provider: "cursor",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoning: "xhigh",
|
||||
fastMode: true,
|
||||
contextWindow: "1m",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -16,12 +16,7 @@ import {
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "../Prompts.ts";
|
||||
import {
|
||||
extractJsonObject,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
} from "../Utils.ts";
|
||||
import { sanitizeCommitSubject, sanitizePrTitle, sanitizeThreadTitle } from "../Utils.ts";
|
||||
import {
|
||||
applyCursorAcpModelSelection,
|
||||
makeCursorAcpRuntime,
|
||||
@@ -30,6 +25,54 @@ import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const CURSOR_TIMEOUT_MS = 180_000;
|
||||
|
||||
function extractJsonObject(raw: string): string {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const start = trimmed.indexOf("{");
|
||||
if (start < 0) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
let depth = 0;
|
||||
let inString = false;
|
||||
let escaping = false;
|
||||
for (let index = start; index < trimmed.length; index += 1) {
|
||||
const char = trimmed[index];
|
||||
if (inString) {
|
||||
if (escaping) {
|
||||
escaping = false;
|
||||
} else if (char === "\\") {
|
||||
escaping = true;
|
||||
} else if (char === '"') {
|
||||
inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === '"') {
|
||||
inString = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === "{") {
|
||||
depth += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === "}") {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
return trimmed.slice(start, index + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return trimmed.slice(start);
|
||||
}
|
||||
|
||||
function mapCursorAcpError(
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
@@ -108,7 +151,7 @@ const makeCursorTextGeneration = Effect.gen(function* () {
|
||||
yield* applyCursorAcpModelSelection({
|
||||
runtime,
|
||||
model: modelSelection.model,
|
||||
selections: modelSelection.options,
|
||||
modelOptions: modelSelection.options,
|
||||
mapError: ({ cause, configId, step }) =>
|
||||
mapCursorAcpError(
|
||||
operation,
|
||||
|
||||
@@ -40,6 +40,15 @@ function writeTextFile(
|
||||
});
|
||||
}
|
||||
|
||||
function readTextFile(
|
||||
filePath: string,
|
||||
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.readFileString(filePath);
|
||||
});
|
||||
}
|
||||
|
||||
function removePath(
|
||||
targetPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
@@ -659,8 +668,32 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
"feature/demo",
|
||||
"origin/feature/remote-only",
|
||||
]);
|
||||
expect(result.branches.find((branch) => branch.name === "feature/demo")?.originRef).toBe(
|
||||
"origin/feature/demo",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("matches branch queries against tracked origin refs for local branches", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
const { initialBranch } = yield* initRepoWithCommit(tmp);
|
||||
yield* git(tmp, ["remote", "add", "origin", remote]);
|
||||
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
|
||||
|
||||
const result = yield* (yield* GitCore).listBranches({
|
||||
cwd: tmp,
|
||||
query: "origin/",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
expect(result.branches.map((branch) => branch.name)).toEqual([initialBranch]);
|
||||
expect(result.branches[0]?.originRef).toBe(`origin/${initialBranch}`);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── checkoutGitBranch ──
|
||||
@@ -1361,6 +1394,40 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("can base a new worktree on the latest fetched origin branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
const updater = yield* makeTmpDir();
|
||||
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
const { initialBranch } = yield* initRepoWithCommit(source);
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", initialBranch]);
|
||||
|
||||
yield* git(updater, ["clone", remote, "."]);
|
||||
yield* git(updater, ["config", "user.email", "[email protected]"]);
|
||||
yield* git(updater, ["config", "user.name", "Test"]);
|
||||
yield* writeTextFile(path.join(updater, "README.md"), "latest from origin\n");
|
||||
yield* git(updater, ["add", "README.md"]);
|
||||
yield* git(updater, ["commit", "-m", "advance origin"]);
|
||||
yield* git(updater, ["push", "origin", initialBranch]);
|
||||
|
||||
const wtPath = path.join(source, "wt-origin-latest");
|
||||
yield* (yield* GitCore).createWorktree({
|
||||
cwd: source,
|
||||
branch: initialBranch,
|
||||
newBranch: "wt-origin-latest",
|
||||
fetchLatestOrigin: true,
|
||||
path: wtPath,
|
||||
});
|
||||
|
||||
expect(yield* readTextFile(path.join(wtPath, "README.md"))).toBe("latest from origin\n");
|
||||
|
||||
yield* (yield* GitCore).removeWorktree({ cwd: source, path: wtPath });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("throws when new branch name already exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
@@ -213,7 +213,11 @@ function filterBranchesForListQuery(
|
||||
}
|
||||
|
||||
const normalizedQuery = query.toLowerCase();
|
||||
return branches.filter((branch) => branch.name.toLowerCase().includes(normalizedQuery));
|
||||
return branches.filter(
|
||||
(branch) =>
|
||||
branch.name.toLowerCase().includes(normalizedQuery) ||
|
||||
branch.originRef?.toLowerCase().includes(normalizedQuery) === true,
|
||||
);
|
||||
}
|
||||
|
||||
function paginateBranches(input: {
|
||||
@@ -1868,28 +1872,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
}
|
||||
}
|
||||
|
||||
const localBranches = localBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
|
||||
.map((branch) => ({
|
||||
name: branch.name,
|
||||
current: branch.current,
|
||||
isRemote: false,
|
||||
isDefault: branch.name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(branch.name) ?? null,
|
||||
}))
|
||||
.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
const remoteBranches =
|
||||
remoteBranchResult.code === 0
|
||||
? remoteBranchResult.stdout
|
||||
@@ -1925,6 +1907,38 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
})
|
||||
: [];
|
||||
|
||||
const originRemoteRefs = new Set(
|
||||
remoteBranches
|
||||
.filter((branch) => branch.remoteName === "origin")
|
||||
.map((branch) => branch.name),
|
||||
);
|
||||
|
||||
const localBranches = localBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
|
||||
.map((branch) => {
|
||||
const originRef = `origin/${branch.name}`;
|
||||
return {
|
||||
name: branch.name,
|
||||
current: branch.current,
|
||||
isRemote: false,
|
||||
originRef: originRemoteRefs.has(originRef) ? originRef : undefined,
|
||||
isDefault: branch.name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(branch.name) ?? null,
|
||||
};
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
const branches = paginateBranches({
|
||||
branches: filterBranchesForListQuery(
|
||||
dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]),
|
||||
@@ -1949,9 +1963,29 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
const sanitizedBranch = targetBranch.replace(/\//g, "-");
|
||||
const repoName = path.basename(input.cwd);
|
||||
const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch);
|
||||
let baseRef = input.branch;
|
||||
|
||||
if (input.fetchLatestOrigin) {
|
||||
yield* executeGit(
|
||||
"GitCore.createWorktree.fetchLatestOrigin",
|
||||
input.cwd,
|
||||
[
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"origin",
|
||||
`+refs/heads/${input.branch}:refs/remotes/origin/${input.branch}`,
|
||||
],
|
||||
{
|
||||
fallbackErrorMessage: `git fetch origin ${input.branch} failed`,
|
||||
},
|
||||
);
|
||||
baseRef = `origin/${input.branch}`;
|
||||
}
|
||||
|
||||
const args = input.newBranch
|
||||
? ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch]
|
||||
: ["worktree", "add", worktreePath, input.branch];
|
||||
? ["worktree", "add", "-b", input.newBranch, worktreePath, baseRef]
|
||||
: ["worktree", "add", worktreePath, baseRef];
|
||||
|
||||
yield* executeGit("GitCore.createWorktree", input.cwd, args, {
|
||||
fallbackErrorMessage: "git worktree add failed",
|
||||
|
||||
@@ -205,50 +205,6 @@ layer("GitHubCliLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates pull requests with the title passed as a single argv value", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: "https://github.com/pingdotgg/codething-mvp/pull/42\n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli;
|
||||
yield* gh.createPullRequest({
|
||||
cwd: "/repo",
|
||||
baseBranch: "main",
|
||||
headSelector: "dev",
|
||||
title: "Stabilize map selection, pricing badges, and camera handling",
|
||||
bodyFile:
|
||||
"C:\\Users\\leo20\\AppData\\Local\\Temp\\t3code-pr-body-38228-73481782-d57c-4b4d-ab5e-9906dc728b2b.md",
|
||||
});
|
||||
});
|
||||
|
||||
expect(mockedRunProcess).toHaveBeenCalledWith(
|
||||
"gh",
|
||||
[
|
||||
"pr",
|
||||
"create",
|
||||
"--base",
|
||||
"main",
|
||||
"--head",
|
||||
"dev",
|
||||
"--title",
|
||||
"Stabilize map selection, pricing badges, and camera handling",
|
||||
"--body-file",
|
||||
"C:\\Users\\leo20\\AppData\\Local\\Temp\\t3code-pr-body-38228-73481782-d57c-4b4d-ab5e-9906dc728b2b.md",
|
||||
],
|
||||
expect.objectContaining({
|
||||
cwd: "/repo",
|
||||
shell: false,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces a friendly error when the pull request is not found", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockRejectedValueOnce(
|
||||
|
||||
@@ -107,7 +107,6 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
try: () =>
|
||||
runProcess("gh", input.args, {
|
||||
cwd: input.cwd,
|
||||
shell: false,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
}),
|
||||
catch: (error) => normalizeGitHubCliError("execute", error),
|
||||
|
||||
@@ -1,100 +1,83 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Duration, Effect, Layer } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { beforeEach, expect } from "vitest";
|
||||
import { beforeEach, expect, vi } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
type OpenCodeRuntimeShape,
|
||||
} from "../../provider/opencodeRuntime.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
|
||||
|
||||
const runtimeMock = {
|
||||
state: {
|
||||
const runtimeMock = vi.hoisted(() => {
|
||||
const state = {
|
||||
startCalls: [] as string[],
|
||||
promptUrls: [] as string[],
|
||||
authHeaders: [] as Array<string | null>,
|
||||
closeCalls: [] as string[],
|
||||
promptResult: undefined as
|
||||
| { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } }
|
||||
| undefined,
|
||||
},
|
||||
reset() {
|
||||
this.state.startCalls.length = 0;
|
||||
this.state.promptUrls.length = 0;
|
||||
this.state.authHeaders.length = 0;
|
||||
this.state.closeCalls.length = 0;
|
||||
this.state.promptResult = undefined;
|
||||
},
|
||||
};
|
||||
promptResult: undefined as { data?: { info?: { structured?: unknown } } } | undefined,
|
||||
};
|
||||
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: ({ binaryPath }) =>
|
||||
Effect.gen(function* () {
|
||||
return {
|
||||
state,
|
||||
reset() {
|
||||
state.startCalls.length = 0;
|
||||
state.promptUrls.length = 0;
|
||||
state.authHeaders.length = 0;
|
||||
state.closeCalls.length = 0;
|
||||
state.promptResult = undefined;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../provider/opencodeRuntime.ts", async () => {
|
||||
const actual = await vi.importActual<typeof import("../../provider/opencodeRuntime.ts")>(
|
||||
"../../provider/opencodeRuntime.ts",
|
||||
);
|
||||
|
||||
return {
|
||||
...actual,
|
||||
startOpenCodeServerProcess: vi.fn(async ({ binaryPath }: { binaryPath: string }) => {
|
||||
const index = runtimeMock.state.startCalls.length + 1;
|
||||
const url = `http://127.0.0.1:${4_300 + index}`;
|
||||
runtimeMock.state.startCalls.push(binaryPath);
|
||||
// The production runtime binds server lifetime to the caller's scope.
|
||||
// Mirror that here so the closeCalls probe observes scope close.
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
runtimeMock.state.closeCalls.push(url);
|
||||
}),
|
||||
);
|
||||
return {
|
||||
url,
|
||||
exitCode: Effect.never,
|
||||
process: {} as ChildProcess,
|
||||
close: () => {
|
||||
runtimeMock.state.closeCalls.push(url);
|
||||
},
|
||||
};
|
||||
}),
|
||||
connectToOpenCodeServer: ({ serverUrl }) =>
|
||||
Effect.succeed({
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
exitCode: null,
|
||||
external: Boolean(serverUrl),
|
||||
}),
|
||||
runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
|
||||
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
|
||||
({
|
||||
session: {
|
||||
create: async () => ({ data: { id: `${baseUrl}/session` } }),
|
||||
prompt: async () => {
|
||||
runtimeMock.state.promptUrls.push(baseUrl);
|
||||
runtimeMock.state.authHeaders.push(
|
||||
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
|
||||
);
|
||||
return (
|
||||
runtimeMock.state.promptResult ?? {
|
||||
data: {
|
||||
parts: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify({
|
||||
createOpenCodeSdkClient: vi.fn(
|
||||
({ baseUrl, serverPassword }: { baseUrl: string; serverPassword?: string }) => ({
|
||||
session: {
|
||||
create: vi.fn(async () => ({ data: { id: `${baseUrl}/session` } })),
|
||||
prompt: vi.fn(async () => {
|
||||
runtimeMock.state.promptUrls.push(baseUrl);
|
||||
runtimeMock.state.authHeaders.push(
|
||||
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
|
||||
);
|
||||
return (
|
||||
runtimeMock.state.promptResult ?? {
|
||||
data: {
|
||||
info: {
|
||||
structured: {
|
||||
subject: "Improve OpenCode reuse",
|
||||
body: "Reuse one server for the full action.",
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
);
|
||||
},
|
||||
}
|
||||
);
|
||||
}),
|
||||
},
|
||||
},
|
||||
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
|
||||
loadOpenCodeInventory: () =>
|
||||
Effect.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "loadOpenCodeInventory",
|
||||
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
|
||||
cause: null,
|
||||
}),
|
||||
),
|
||||
};
|
||||
};
|
||||
});
|
||||
|
||||
const DEFAULT_TEST_MODEL_SELECTION = {
|
||||
provider: "opencode" as const,
|
||||
@@ -104,7 +87,6 @@ const DEFAULT_TEST_MODEL_SELECTION = {
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
|
||||
|
||||
const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
@@ -119,12 +101,10 @@ const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe(
|
||||
prefix: "t3code-opencode-text-generation-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
@@ -141,7 +121,6 @@ const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive
|
||||
prefix: "t3code-opencode-text-generation-existing-server-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -219,7 +198,7 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) =>
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
|
||||
it.effect("returns a typed missing-output error when OpenCode omits info.structured", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.promptResult = { data: {} };
|
||||
const textGeneration = yield* TextGeneration;
|
||||
@@ -234,67 +213,7 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) =>
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("OpenCode returned empty output.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("parses JSON returned as plain text output", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.promptResult = {
|
||||
data: {
|
||||
parts: [
|
||||
{
|
||||
type: "text",
|
||||
text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const result = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
subject: "Tighten OpenCode parsing",
|
||||
body: "Handle JSON text output locally.",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces the upstream OpenCode structured-output error message", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.promptResult = {
|
||||
data: {
|
||||
info: {
|
||||
error: {
|
||||
name: "StructuredOutputError",
|
||||
data: {
|
||||
message: "Model did not produce structured output",
|
||||
retries: 2,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const error = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("Model did not produce structured output");
|
||||
expect(error.message).toContain("OpenCode returned no structured output.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Effect, Exit, Fiber, Layer, Schema, Scope } from "effect";
|
||||
import { Duration, Effect, Exit, Fiber, Layer, Schema, Scope } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import {
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
type OpenCodeModelSelection,
|
||||
} from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
@@ -20,74 +19,24 @@ import {
|
||||
} from "../Prompts.ts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
extractJsonObject,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
createOpenCodeSdkClient,
|
||||
type OpenCodeServerConnection,
|
||||
type OpenCodeServerProcess,
|
||||
openCodeRuntimeErrorDetail,
|
||||
parseOpenCodeModelSlug,
|
||||
startOpenCodeServerProcess,
|
||||
toOpenCodeFileParts,
|
||||
} from "../../provider/opencodeRuntime.ts";
|
||||
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
|
||||
|
||||
function getOpenCodePromptErrorMessage(error: unknown): string | null {
|
||||
if (!error || typeof error !== "object") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const message =
|
||||
"data" in error &&
|
||||
error.data &&
|
||||
typeof error.data === "object" &&
|
||||
"message" in error.data &&
|
||||
typeof error.data.message === "string"
|
||||
? error.data.message.trim()
|
||||
: "";
|
||||
if (message.length > 0) {
|
||||
return message;
|
||||
}
|
||||
|
||||
if ("name" in error && typeof error.name === "string") {
|
||||
const name = error.name.trim();
|
||||
return name.length > 0 ? name : null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function getOpenCodeTextResponse(parts: ReadonlyArray<unknown> | undefined): string {
|
||||
return (parts ?? [])
|
||||
.flatMap((part) => {
|
||||
if (!part || typeof part !== "object") {
|
||||
return [];
|
||||
}
|
||||
if (!("type" in part) || part.type !== "text") {
|
||||
return [];
|
||||
}
|
||||
if (!("text" in part) || typeof part.text !== "string") {
|
||||
return [];
|
||||
}
|
||||
return [part.text];
|
||||
})
|
||||
.join("")
|
||||
.trim();
|
||||
}
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
|
||||
|
||||
interface SharedOpenCodeTextGenerationServerState {
|
||||
server: OpenCodeServerProcess | null;
|
||||
/**
|
||||
* The scope that owns the shared server's lifetime. Closing this scope
|
||||
* terminates the OpenCode child process and interrupts any fibers the
|
||||
* runtime forked during startup. We don't hold a `close()` function on
|
||||
* the server handle anymore — the scope is the only lifecycle handle.
|
||||
*/
|
||||
serverScope: Scope.Closeable | null;
|
||||
binaryPath: string | null;
|
||||
activeRequests: number;
|
||||
idleCloseFiber: Fiber.Fiber<void, never> | null;
|
||||
@@ -96,28 +45,24 @@ interface SharedOpenCodeTextGenerationServerState {
|
||||
const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
|
||||
Scope.close(scope, Exit.void),
|
||||
);
|
||||
const sharedServerMutex = yield* Semaphore.make(1);
|
||||
const sharedServerState: SharedOpenCodeTextGenerationServerState = {
|
||||
server: null,
|
||||
serverScope: null,
|
||||
binaryPath: null,
|
||||
activeRequests: 0,
|
||||
idleCloseFiber: null,
|
||||
};
|
||||
|
||||
const closeSharedServer = Effect.fn("closeSharedServer")(function* () {
|
||||
const scope = sharedServerState.serverScope;
|
||||
sharedServerState.server = null;
|
||||
sharedServerState.serverScope = null;
|
||||
sharedServerState.binaryPath = null;
|
||||
if (scope !== null) {
|
||||
yield* Scope.close(scope, Exit.void).pipe(Effect.ignore);
|
||||
const closeSharedServer = (server: OpenCodeServerProcess) => {
|
||||
if (sharedServerState.server === server) {
|
||||
sharedServerState.server = null;
|
||||
sharedServerState.binaryPath = null;
|
||||
}
|
||||
});
|
||||
server.close();
|
||||
};
|
||||
|
||||
const cancelIdleCloseFiber = Effect.fn("cancelIdleCloseFiber")(function* () {
|
||||
const idleCloseFiber = sharedServerState.idleCloseFiber;
|
||||
@@ -131,15 +76,15 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
server: OpenCodeServerProcess,
|
||||
) {
|
||||
yield* cancelIdleCloseFiber();
|
||||
const fiber = yield* Effect.sleep(OPENCODE_TEXT_GENERATION_IDLE_TTL).pipe(
|
||||
const fiber = yield* Effect.sleep(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS)).pipe(
|
||||
Effect.andThen(
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
Effect.sync(() => {
|
||||
if (sharedServerState.server !== server || sharedServerState.activeRequests > 0) {
|
||||
return;
|
||||
}
|
||||
sharedServerState.idleCloseFiber = null;
|
||||
yield* closeSharedServer();
|
||||
closeSharedServer(server);
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -166,7 +111,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
sharedServerState.binaryPath !== input.binaryPath &&
|
||||
sharedServerState.activeRequests === 0
|
||||
) {
|
||||
yield* closeSharedServer();
|
||||
closeSharedServer(existingServer);
|
||||
} else {
|
||||
if (sharedServerState.binaryPath !== input.binaryPath) {
|
||||
yield* Effect.logWarning(
|
||||
@@ -182,53 +127,20 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
// Create a fresh scope that owns this shared server. The runtime
|
||||
// will attach its child-process and fiber finalizers to this scope;
|
||||
// closing it kills the server and interrupts those fibers.
|
||||
//
|
||||
// The `Scope.make` / spawn / record-or-close transitions run inside
|
||||
// `uninterruptibleMask` so an interrupt arriving between any two
|
||||
// steps can't orphan the scope (and the child process attached to
|
||||
// it) before we either close it on failure or hand ownership to
|
||||
// `sharedServerState`. `restore` keeps the actual spawn
|
||||
// interruptible; an interrupt during the spawn is captured by
|
||||
// `Effect.exit` and drives us through the failure branch that
|
||||
// closes the fresh scope.
|
||||
return yield* Effect.uninterruptibleMask((restore) =>
|
||||
Effect.gen(function* () {
|
||||
const serverScope = yield* Scope.make();
|
||||
const startedExit = yield* Effect.exit(
|
||||
restore(
|
||||
openCodeRuntime
|
||||
.startOpenCodeServerProcess({
|
||||
binaryPath: input.binaryPath,
|
||||
})
|
||||
.pipe(
|
||||
Effect.provideService(Scope.Scope, serverScope),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: openCodeRuntimeErrorDetail(cause),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (startedExit._tag === "Failure") {
|
||||
yield* Scope.close(serverScope, Exit.void).pipe(Effect.ignore);
|
||||
return yield* Effect.failCause(startedExit.cause);
|
||||
}
|
||||
const server = yield* Effect.tryPromise({
|
||||
try: () => startOpenCodeServerProcess({ binaryPath: input.binaryPath }),
|
||||
catch: (cause) =>
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: cause instanceof Error ? cause.message : "Failed to start OpenCode server.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const server = startedExit.value;
|
||||
sharedServerState.server = server;
|
||||
sharedServerState.serverScope = serverScope;
|
||||
sharedServerState.binaryPath = input.binaryPath;
|
||||
sharedServerState.activeRequests = 1;
|
||||
return server;
|
||||
}),
|
||||
);
|
||||
sharedServerState.server = server;
|
||||
sharedServerState.binaryPath = input.binaryPath;
|
||||
sharedServerState.activeRequests = 1;
|
||||
return server;
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -245,15 +157,17 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
// Module-level finalizer: on layer shutdown, cancel the idle close fiber
|
||||
// and close the shared server scope. Consumers therefore cannot leak
|
||||
// the shared OpenCode server by forgetting to call anything.
|
||||
yield* Effect.addFinalizer(() =>
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
yield* cancelIdleCloseFiber();
|
||||
const server = sharedServerState.server;
|
||||
sharedServerState.server = null;
|
||||
sharedServerState.binaryPath = null;
|
||||
sharedServerState.activeRequests = 0;
|
||||
yield* closeSharedServer();
|
||||
if (server !== null) {
|
||||
server.close();
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -307,7 +221,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
const runAgainstServer = (server: Pick<OpenCodeServerConnection, "url">) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const client = openCodeRuntime.createOpenCodeSdkClient({
|
||||
const client = createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: input.cwd,
|
||||
...(settings.serverUrl.length > 0 && settings.serverPassword
|
||||
@@ -321,39 +235,38 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
if (!session.data) {
|
||||
throw new Error("OpenCode session.create returned no session payload.");
|
||||
}
|
||||
const selectedAgent = getModelSelectionStringOptionValue(input.modelSelection, "agent");
|
||||
const selectedVariant = getModelSelectionStringOptionValue(
|
||||
input.modelSelection,
|
||||
"variant",
|
||||
);
|
||||
|
||||
const result = await client.session.prompt({
|
||||
sessionID: session.data.id,
|
||||
model: parsedModel,
|
||||
...(selectedAgent ? { agent: selectedAgent } : {}),
|
||||
...(selectedVariant ? { variant: selectedVariant } : {}),
|
||||
...(input.modelSelection.options?.agent
|
||||
? { agent: input.modelSelection.options.agent }
|
||||
: {}),
|
||||
...(input.modelSelection.options?.variant
|
||||
? { variant: input.modelSelection.options.variant }
|
||||
: {}),
|
||||
format: {
|
||||
type: "json_schema",
|
||||
schema: toJsonSchemaObject(input.outputSchemaJson) as Record<string, unknown>,
|
||||
},
|
||||
parts: [{ type: "text", text: input.prompt }, ...fileParts],
|
||||
});
|
||||
const info = result.data?.info;
|
||||
const errorMessage = getOpenCodePromptErrorMessage(info?.error);
|
||||
if (errorMessage) {
|
||||
throw new Error(errorMessage);
|
||||
const structured = result.data?.info?.structured;
|
||||
if (structured === undefined) {
|
||||
throw new Error("OpenCode returned no structured output.");
|
||||
}
|
||||
const rawText = getOpenCodeTextResponse(result.data?.parts);
|
||||
if (rawText.length === 0) {
|
||||
throw new Error("OpenCode returned empty output.");
|
||||
}
|
||||
return rawText;
|
||||
return structured;
|
||||
},
|
||||
catch: (cause) =>
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: openCodeRuntimeErrorDetail(cause),
|
||||
detail:
|
||||
cause instanceof Error ? cause.message : "OpenCode text generation request failed.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const rawOutput =
|
||||
const structuredOutput =
|
||||
settings.serverUrl.length > 0
|
||||
? yield* runAgainstServer({ url: settings.serverUrl })
|
||||
: yield* Effect.acquireUseRelease(
|
||||
@@ -365,9 +278,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
releaseSharedServer,
|
||||
);
|
||||
|
||||
return yield* Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson))(
|
||||
extractJsonObject(rawOutput),
|
||||
).pipe(
|
||||
return yield* Schema.decodeUnknownEffect(input.outputSchemaJson)(structuredOutput).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
|
||||
@@ -11,7 +11,11 @@
|
||||
*/
|
||||
import { Effect, Layer, Context } from "effect";
|
||||
|
||||
import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
TextGeneration,
|
||||
type TextGenerationProvider,
|
||||
type TextGenerationShape,
|
||||
} from "../Services/TextGeneration.ts";
|
||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
||||
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
|
||||
@@ -42,22 +46,26 @@ class OpenCodeTextGen extends Context.Service<OpenCodeTextGen, TextGenerationSha
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const makeRoutingTextGeneration = Effect.gen(function* () {
|
||||
const byProvider = {
|
||||
codex: yield* CodexTextGen,
|
||||
claudeAgent: yield* ClaudeTextGen,
|
||||
cursor: yield* CursorTextGen,
|
||||
opencode: yield* OpenCodeTextGen,
|
||||
};
|
||||
const codex = yield* CodexTextGen;
|
||||
const claude = yield* ClaudeTextGen;
|
||||
const cursor = yield* CursorTextGen;
|
||||
const openCode = yield* OpenCodeTextGen;
|
||||
|
||||
const route = (provider?: TextGenerationProvider): TextGenerationShape =>
|
||||
provider === "claudeAgent"
|
||||
? claude
|
||||
: provider === "opencode"
|
||||
? openCode
|
||||
: provider === "cursor"
|
||||
? cursor
|
||||
: codex;
|
||||
|
||||
return {
|
||||
generateCommitMessage: (input) =>
|
||||
byProvider[input.modelSelection.provider].generateCommitMessage(input),
|
||||
generatePrContent: (input) =>
|
||||
byProvider[input.modelSelection.provider].generatePrContent(input),
|
||||
generateBranchName: (input) =>
|
||||
byProvider[input.modelSelection.provider].generateBranchName(input),
|
||||
generateThreadTitle: (input) =>
|
||||
byProvider[input.modelSelection.provider].generateThreadTitle(input),
|
||||
route(input.modelSelection.provider).generateCommitMessage(input),
|
||||
generatePrContent: (input) => route(input.modelSelection.provider).generatePrContent(input),
|
||||
generateBranchName: (input) => route(input.modelSelection.provider).generateBranchName(input),
|
||||
generateThreadTitle: (input) => route(input.modelSelection.provider).generateThreadTitle(input),
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -30,54 +30,6 @@ export function limitSection(value: string, maxChars: number): string {
|
||||
return `${truncated}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
export function extractJsonObject(raw: string): string {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const start = trimmed.indexOf("{");
|
||||
if (start < 0) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
let depth = 0;
|
||||
let inString = false;
|
||||
let escaping = false;
|
||||
for (let index = start; index < trimmed.length; index += 1) {
|
||||
const char = trimmed[index];
|
||||
if (inString) {
|
||||
if (escaping) {
|
||||
escaping = false;
|
||||
} else if (char === "\\") {
|
||||
escaping = true;
|
||||
} else if (char === '"') {
|
||||
inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === '"') {
|
||||
inString = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === "{") {
|
||||
depth += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === "}") {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
return trimmed.slice(start, index + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return trimmed.slice(start);
|
||||
}
|
||||
|
||||
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
|
||||
export function sanitizeCommitSubject(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
|
||||
@@ -192,9 +192,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.jump.9"), "mod+9");
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
KeybindingShortcut,
|
||||
KeybindingWhenNode,
|
||||
MAX_KEYBINDINGS_COUNT,
|
||||
MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
|
||||
MAX_WHEN_EXPRESSION_DEPTH,
|
||||
ResolvedKeybindingRule,
|
||||
ResolvedKeybindingsConfig,
|
||||
@@ -46,7 +45,6 @@ import {
|
||||
} from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import { writeFileStringAtomically } from "./atomicWrite.ts";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
|
||||
type WhenToken =
|
||||
@@ -67,7 +65,6 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+o", command: "editor.openFavorite" },
|
||||
{ key: "mod+shift+[", command: "thread.previous" },
|
||||
{ key: "mod+shift+]", command: "thread.next" },
|
||||
@@ -75,11 +72,6 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
key: `mod+${index + 1}`,
|
||||
command,
|
||||
})),
|
||||
...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
|
||||
key: `mod+${index + 1}`,
|
||||
command,
|
||||
when: "modelPickerOpen",
|
||||
})),
|
||||
];
|
||||
|
||||
function normalizeKeyToken(token: string): string {
|
||||
@@ -671,17 +663,14 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
|
||||
const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
|
||||
return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
|
||||
Effect.map((encoded) => `${encoded}\n`),
|
||||
Effect.flatMap((encoded) =>
|
||||
writeFileStringAtomically({
|
||||
filePath: keybindingsConfigPath,
|
||||
contents: encoded,
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fs),
|
||||
Effect.provideService(Path.Path, path),
|
||||
),
|
||||
),
|
||||
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({
|
||||
|
||||
@@ -3,7 +3,6 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
@@ -568,10 +567,14 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello fast mode",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
@@ -581,17 +584,25 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -612,9 +623,13 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello with effort",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||
{ id: "effort", value: "max" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
@@ -624,15 +639,23 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||
{ id: "effort", value: "max" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||
{ id: "effort", value: "max" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -653,9 +676,13 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello with fast mode",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
@@ -665,15 +692,23 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -881,9 +916,13 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "first claude turn",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||
{ id: "effort", value: "medium" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "medium",
|
||||
},
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
@@ -904,9 +943,13 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "second claude turn",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||
{ id: "effort", value: "max" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
@@ -917,9 +960,13 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
||||
resumeCursor: { opaque: "resume-1" },
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||
{ id: "effort", value: "max" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Effect } from "effect";
|
||||
|
||||
@@ -163,10 +162,14 @@ describe("decider project scripts", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
@@ -188,10 +191,14 @@ describe("decider project scripts", () => {
|
||||
expect(turnStartEvent.payload).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
messageId: asMessageId("message-user-1"),
|
||||
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { expandHomePath } from "./pathExpansion.ts";
|
||||
|
||||
describe("expandHomePath", () => {
|
||||
it("returns an empty string unchanged", () => {
|
||||
expect(expandHomePath("")).toBe("");
|
||||
});
|
||||
|
||||
it("returns paths without a leading tilde unchanged", () => {
|
||||
expect(expandHomePath("/absolute/path")).toBe("/absolute/path");
|
||||
expect(expandHomePath("relative/path")).toBe("relative/path");
|
||||
expect(expandHomePath("some~weird~path")).toBe("some~weird~path");
|
||||
});
|
||||
|
||||
it("expands a lone tilde to the home directory", () => {
|
||||
expect(expandHomePath("~")).toBe(homedir());
|
||||
});
|
||||
|
||||
it("expands ~/ to a subpath of the home directory", () => {
|
||||
expect(expandHomePath("~/.codex-work")).toBe(join(homedir(), ".codex-work"));
|
||||
});
|
||||
|
||||
it("expands a Windows-style ~\\ prefix", () => {
|
||||
expect(expandHomePath("~\\.codex")).toBe(join(homedir(), ".codex"));
|
||||
});
|
||||
|
||||
it("does not expand ~user paths", () => {
|
||||
expect(expandHomePath("~alice/foo")).toBe("~alice/foo");
|
||||
});
|
||||
});
|
||||
@@ -1,23 +0,0 @@
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
/**
|
||||
* Expand a leading `~` (or `~/…`, `~\…`) in a user-supplied path to the
|
||||
* current user's home directory. Spawned processes don't get shell
|
||||
* expansion, so env vars like `CODEX_HOME=~/.codex-work` would be passed
|
||||
* verbatim and treated as relative paths by the receiver.
|
||||
*
|
||||
* Matches the behavior of the other `expandHomePath` helpers in the
|
||||
* workspace layers and CLI bootstrap: `~` alone and both `~/` and `~\`
|
||||
* separators are handled. Returns the input unchanged if it doesn't
|
||||
* start with `~` or is empty. Does not handle `~user` (other-user)
|
||||
* expansion.
|
||||
*/
|
||||
export function expandHomePath(value: string): string {
|
||||
if (!value) return value;
|
||||
if (value === "~") return homedir();
|
||||
if (value.startsWith("~/") || value.startsWith("~\\")) {
|
||||
return join(homedir(), value.slice(2));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -38,7 +38,6 @@ import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts";
|
||||
import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts";
|
||||
import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts";
|
||||
import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts";
|
||||
import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -76,7 +75,6 @@ export const migrationEntries = [
|
||||
[23, "ProjectionThreadShellSummary", Migration0023],
|
||||
[24, "BackfillProjectionThreadShellSummary", Migration0024],
|
||||
[25, "CleanupInvalidProjectionPendingApprovals", Migration0025],
|
||||
[26, "CanonicalizeModelSelectionOptions", Migration0026],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -1,450 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { runMigrations } from "../Migrations.ts";
|
||||
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
||||
|
||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
||||
|
||||
layer("026_CanonicalizeModelSelectionOptions", (it) => {
|
||||
it.effect("converts legacy object-shape options into array-shape on projections and events", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 25 });
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'project-legacy',
|
||||
'Legacy options project',
|
||||
'/tmp/legacy',
|
||||
'{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","fastMode":true}}',
|
||||
'[]',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
NULL
|
||||
),
|
||||
(
|
||||
'project-no-options',
|
||||
'No options project',
|
||||
'/tmp/no-options',
|
||||
'{"provider":"codex","model":"gpt-5.4"}',
|
||||
'[]',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
NULL
|
||||
),
|
||||
(
|
||||
'project-null-selection',
|
||||
'Null model selection project',
|
||||
'/tmp/null-selection',
|
||||
NULL,
|
||||
'[]',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
NULL
|
||||
),
|
||||
(
|
||||
'project-already-array',
|
||||
'Already-canonical options project',
|
||||
'/tmp/already-array',
|
||||
'{"provider":"codex","model":"gpt-5.4","options":[{"id":"reasoningEffort","value":"high"}]}',
|
||||
'[]',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
deleted_at,
|
||||
runtime_mode,
|
||||
interaction_mode
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'thread-legacy',
|
||||
'project-legacy',
|
||||
'Legacy thread',
|
||||
'{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","thinking":false,"contextWindow":"1m"}}',
|
||||
NULL, NULL, NULL,
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
NULL, NULL, 0, 0, 0, NULL,
|
||||
'full-access', 'default'
|
||||
),
|
||||
(
|
||||
'thread-empty-options',
|
||||
'project-legacy',
|
||||
'Empty options thread',
|
||||
'{"provider":"codex","model":"gpt-5.4","options":{}}',
|
||||
NULL, NULL, NULL,
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
NULL, NULL, 0, 0, 0, NULL,
|
||||
'full-access', 'default'
|
||||
),
|
||||
(
|
||||
'thread-drop-garbage',
|
||||
'project-legacy',
|
||||
'Thread with non-scalar entries',
|
||||
'{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"high","thinking":{"enabled":true,"budgetTokens":2000},"emptyStr":" ","nullish":null}}',
|
||||
NULL, NULL, NULL,
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
NULL, NULL, 0, 0, 0, NULL,
|
||||
'full-access', 'default'
|
||||
),
|
||||
(
|
||||
'thread-no-options',
|
||||
'project-legacy',
|
||||
'No options thread',
|
||||
'{"provider":"codex","model":"gpt-5.4"}',
|
||||
NULL, NULL, NULL,
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
NULL, NULL, 0, 0, 0, NULL,
|
||||
'full-access', 'default'
|
||||
),
|
||||
(
|
||||
'thread-already-array',
|
||||
'project-legacy',
|
||||
'Already array thread',
|
||||
'{"provider":"codex","model":"gpt-5.4","options":[{"id":"fastMode","value":true}]}',
|
||||
NULL, NULL, NULL,
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
NULL, NULL, 0, 0, 0, NULL,
|
||||
'full-access', 'default'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO orchestration_events (
|
||||
event_id,
|
||||
aggregate_kind,
|
||||
stream_id,
|
||||
stream_version,
|
||||
event_type,
|
||||
occurred_at,
|
||||
command_id,
|
||||
causation_event_id,
|
||||
correlation_id,
|
||||
actor_kind,
|
||||
payload_json,
|
||||
metadata_json
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'event-project-created',
|
||||
'project',
|
||||
'project-legacy',
|
||||
1,
|
||||
'project.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'cmd-pc',
|
||||
NULL,
|
||||
'corr-pc',
|
||||
'user',
|
||||
'{"projectId":"project-legacy","title":"Project","workspaceRoot":"/tmp/legacy","defaultModelSelection":{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","fastMode":true}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-project-meta-updated',
|
||||
'project',
|
||||
'project-legacy',
|
||||
2,
|
||||
'project.meta-updated',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'cmd-pmu',
|
||||
NULL,
|
||||
'corr-pmu',
|
||||
'user',
|
||||
'{"projectId":"project-legacy","defaultModelSelection":{"provider":"codex","model":"gpt-5.4","options":{"reasoningEffort":"low"}},"updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-project-null-selection',
|
||||
'project',
|
||||
'project-legacy',
|
||||
3,
|
||||
'project.meta-updated',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'cmd-null',
|
||||
NULL,
|
||||
'corr-null',
|
||||
'user',
|
||||
'{"projectId":"project-legacy","defaultModelSelection":null,"updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-thread-created',
|
||||
'thread',
|
||||
'thread-legacy',
|
||||
1,
|
||||
'thread.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'cmd-tc',
|
||||
NULL,
|
||||
'corr-tc',
|
||||
'user',
|
||||
'{"threadId":"thread-legacy","projectId":"project-legacy","title":"Thread","modelSelection":{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","thinking":false}},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-thread-meta-updated',
|
||||
'thread',
|
||||
'thread-legacy',
|
||||
2,
|
||||
'thread.meta-updated',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'cmd-tmu',
|
||||
NULL,
|
||||
'corr-tmu',
|
||||
'user',
|
||||
'{"threadId":"thread-legacy","modelSelection":{"provider":"codex","model":"gpt-5.4","options":{"fastMode":true}},"updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-thread-turn-start',
|
||||
'thread',
|
||||
'thread-legacy',
|
||||
3,
|
||||
'thread.turn-start-requested',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'cmd-tts',
|
||||
NULL,
|
||||
'corr-tts',
|
||||
'user',
|
||||
'{"threadId":"thread-legacy","messageId":"msg-1","modelSelection":{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"high","contextWindow":"1m"}},"runtimeMode":"full-access","interactionMode":"default","createdAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-thread-already-array',
|
||||
'thread',
|
||||
'thread-legacy',
|
||||
4,
|
||||
'thread.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'cmd-taa',
|
||||
NULL,
|
||||
'corr-taa',
|
||||
'user',
|
||||
'{"threadId":"thread-already-array","projectId":"project-legacy","title":"Already Array","modelSelection":{"provider":"codex","model":"gpt-5.4","options":[{"id":"reasoningEffort","value":"medium"}]},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-activity-append',
|
||||
'thread',
|
||||
'thread-legacy',
|
||||
5,
|
||||
'thread.activity-appended',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'cmd-aa',
|
||||
NULL,
|
||||
'corr-aa',
|
||||
'user',
|
||||
'{"threadId":"thread-legacy","activity":{"id":"a","tone":"info","kind":"k","summary":"s","payload":null,"turnId":null,"createdAt":"2026-01-01T00:00:00.000Z"}}',
|
||||
'{}'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 26 });
|
||||
|
||||
// Projection projects
|
||||
const projectRows = yield* sql<{
|
||||
readonly projectId: string;
|
||||
readonly defaultModelSelection: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
default_model_selection_json AS "defaultModelSelection"
|
||||
FROM projection_projects
|
||||
ORDER BY project_id
|
||||
`;
|
||||
assert.deepStrictEqual(
|
||||
projectRows.map((row) => ({
|
||||
projectId: row.projectId,
|
||||
selection: row.defaultModelSelection ? JSON.parse(row.defaultModelSelection) : null,
|
||||
})),
|
||||
[
|
||||
{
|
||||
projectId: "project-already-array",
|
||||
selection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "high" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
projectId: "project-legacy",
|
||||
selection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: [
|
||||
{ id: "effort", value: "max" },
|
||||
{ id: "fastMode", value: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
projectId: "project-no-options",
|
||||
selection: { provider: "codex", model: "gpt-5.4" },
|
||||
},
|
||||
{ projectId: "project-null-selection", selection: null },
|
||||
],
|
||||
);
|
||||
|
||||
// Projection threads
|
||||
const threadRows = yield* sql<{
|
||||
readonly threadId: string;
|
||||
readonly modelSelection: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
model_selection_json AS "modelSelection"
|
||||
FROM projection_threads
|
||||
ORDER BY thread_id
|
||||
`;
|
||||
assert.deepStrictEqual(
|
||||
threadRows.map((row) => ({
|
||||
threadId: row.threadId,
|
||||
selection: row.modelSelection ? JSON.parse(row.modelSelection) : null,
|
||||
})),
|
||||
[
|
||||
{
|
||||
threadId: "thread-already-array",
|
||||
selection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "fastMode", value: true }],
|
||||
},
|
||||
},
|
||||
{
|
||||
threadId: "thread-drop-garbage",
|
||||
selection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
// Only the scalar string survives; nested object, whitespace
|
||||
// string, and null are dropped.
|
||||
options: [{ id: "effort", value: "high" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
threadId: "thread-empty-options",
|
||||
selection: { provider: "codex", model: "gpt-5.4", options: [] },
|
||||
},
|
||||
{
|
||||
threadId: "thread-legacy",
|
||||
selection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: [
|
||||
{ id: "effort", value: "max" },
|
||||
{ id: "thinking", value: false },
|
||||
{ id: "contextWindow", value: "1m" },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
threadId: "thread-no-options",
|
||||
selection: { provider: "codex", model: "gpt-5.4" },
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
// Orchestration events
|
||||
const eventRows = yield* sql<{
|
||||
readonly eventId: string;
|
||||
readonly payloadJson: string;
|
||||
}>`
|
||||
SELECT event_id AS "eventId", payload_json AS "payloadJson"
|
||||
FROM orchestration_events
|
||||
ORDER BY event_id
|
||||
`;
|
||||
|
||||
const payloads = Object.fromEntries(
|
||||
eventRows.map((row) => [row.eventId, JSON.parse(row.payloadJson)]),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(payloads["event-project-created"].defaultModelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: [
|
||||
{ id: "effort", value: "max" },
|
||||
{ id: "fastMode", value: true },
|
||||
],
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(payloads["event-project-meta-updated"].defaultModelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "low" }],
|
||||
});
|
||||
|
||||
assert.strictEqual(payloads["event-project-null-selection"].defaultModelSelection, null);
|
||||
|
||||
assert.deepStrictEqual(payloads["event-thread-created"].modelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: [
|
||||
{ id: "effort", value: "max" },
|
||||
{ id: "thinking", value: false },
|
||||
],
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(payloads["event-thread-meta-updated"].modelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "fastMode", value: true }],
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(payloads["event-thread-turn-start"].modelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: [
|
||||
{ id: "effort", value: "high" },
|
||||
{ id: "contextWindow", value: "1m" },
|
||||
],
|
||||
});
|
||||
|
||||
// Already-array records are left untouched.
|
||||
assert.deepStrictEqual(payloads["event-thread-already-array"].modelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "medium" }],
|
||||
});
|
||||
|
||||
// Events with no modelSelection at all are untouched.
|
||||
assert.isUndefined(payloads["event-activity-append"].modelSelection);
|
||||
assert.isUndefined(payloads["event-activity-append"].defaultModelSelection);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,138 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
/**
|
||||
* Canonicalize `modelSelection.options` / `defaultModelSelection.options` from
|
||||
* the legacy object shape (`{ effort: "max", fastMode: true, ... }`) to the
|
||||
* current array-of-selections shape (`[{ id: "effort", value: "max" }, ...]`).
|
||||
*
|
||||
* Migration 016 introduced `modelSelection` with `options` stored as a
|
||||
* per-provider object. Later the schema was reshaped so that options are a
|
||||
* generic `Array<{ id, value }>` of user-selected option entries. Stored rows
|
||||
* from before the reshape still have the object shape and fail to decode.
|
||||
*
|
||||
* For each value in the legacy object:
|
||||
* - string values are kept if non-empty after trim
|
||||
* - boolean values are always kept (true | false)
|
||||
* - any other value type (number, null, nested object/array) is dropped,
|
||||
* matching the permissive client-side normalizer in composerDraftStore.
|
||||
*
|
||||
* Touched storage:
|
||||
* - `projection_threads.model_selection_json.options`
|
||||
* - `projection_projects.default_model_selection_json.options`
|
||||
* - `orchestration_events.payload_json.$.modelSelection.options`
|
||||
* (thread.created | thread.meta-updated | thread.turn-start-requested)
|
||||
* - `orchestration_events.payload_json.$.defaultModelSelection.options`
|
||||
* (project.created | project.meta-updated)
|
||||
*/
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET model_selection_json = json_set(
|
||||
model_selection_json,
|
||||
'$.options',
|
||||
(
|
||||
SELECT json_group_array(
|
||||
json_object(
|
||||
'id', key,
|
||||
'value',
|
||||
CASE type
|
||||
WHEN 'true' THEN json('true')
|
||||
WHEN 'false' THEN json('false')
|
||||
ELSE atom
|
||||
END
|
||||
)
|
||||
)
|
||||
FROM json_each(json_extract(model_selection_json, '$.options'))
|
||||
WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')
|
||||
OR type IN ('true', 'false')
|
||||
)
|
||||
)
|
||||
WHERE model_selection_json IS NOT NULL
|
||||
AND json_type(model_selection_json, '$.options') = 'object'
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_projects
|
||||
SET default_model_selection_json = json_set(
|
||||
default_model_selection_json,
|
||||
'$.options',
|
||||
(
|
||||
SELECT json_group_array(
|
||||
json_object(
|
||||
'id', key,
|
||||
'value',
|
||||
CASE type
|
||||
WHEN 'true' THEN json('true')
|
||||
WHEN 'false' THEN json('false')
|
||||
ELSE atom
|
||||
END
|
||||
)
|
||||
)
|
||||
FROM json_each(json_extract(default_model_selection_json, '$.options'))
|
||||
WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')
|
||||
OR type IN ('true', 'false')
|
||||
)
|
||||
)
|
||||
WHERE default_model_selection_json IS NOT NULL
|
||||
AND json_type(default_model_selection_json, '$.options') = 'object'
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE orchestration_events
|
||||
SET payload_json = json_set(
|
||||
payload_json,
|
||||
'$.modelSelection.options',
|
||||
(
|
||||
SELECT json_group_array(
|
||||
json_object(
|
||||
'id', key,
|
||||
'value',
|
||||
CASE type
|
||||
WHEN 'true' THEN json('true')
|
||||
WHEN 'false' THEN json('false')
|
||||
ELSE atom
|
||||
END
|
||||
)
|
||||
)
|
||||
FROM json_each(json_extract(payload_json, '$.modelSelection.options'))
|
||||
WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')
|
||||
OR type IN ('true', 'false')
|
||||
)
|
||||
)
|
||||
WHERE event_type IN (
|
||||
'thread.created',
|
||||
'thread.meta-updated',
|
||||
'thread.turn-start-requested'
|
||||
)
|
||||
AND json_type(payload_json, '$.modelSelection.options') = 'object'
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE orchestration_events
|
||||
SET payload_json = json_set(
|
||||
payload_json,
|
||||
'$.defaultModelSelection.options',
|
||||
(
|
||||
SELECT json_group_array(
|
||||
json_object(
|
||||
'id', key,
|
||||
'value',
|
||||
CASE type
|
||||
WHEN 'true' THEN json('true')
|
||||
WHEN 'false' THEN json('false')
|
||||
ELSE atom
|
||||
END
|
||||
)
|
||||
)
|
||||
FROM json_each(json_extract(payload_json, '$.defaultModelSelection.options'))
|
||||
WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')
|
||||
OR type IN ('true', 'false')
|
||||
)
|
||||
)
|
||||
WHERE event_type IN ('project.created', 'project.meta-updated')
|
||||
AND json_type(payload_json, '$.defaultModelSelection.options') = 'object'
|
||||
`;
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isWindowsCommandNotFound, runProcess } from "./processRunner.ts";
|
||||
import { runProcess } from "./processRunner.ts";
|
||||
|
||||
describe("runProcess", () => {
|
||||
it("fails when output exceeds max buffer in default mode", async () => {
|
||||
@@ -21,21 +21,3 @@ describe("runProcess", () => {
|
||||
expect(result.stderrTruncated).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isWindowsCommandNotFound", () => {
|
||||
it("matches the localized German cmd.exe error text", () => {
|
||||
const originalPlatform = process.platform;
|
||||
Object.defineProperty(process, "platform", { value: "win32", configurable: true });
|
||||
|
||||
try {
|
||||
expect(
|
||||
isWindowsCommandNotFound(
|
||||
1,
|
||||
"wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
|
||||
),
|
||||
).toBe(true);
|
||||
} finally {
|
||||
Object.defineProperty(process, "platform", { value: originalPlatform, configurable: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,6 @@ export interface ProcessRunOptions {
|
||||
timeoutMs?: number | undefined;
|
||||
env?: NodeJS.ProcessEnv | undefined;
|
||||
stdin?: string | undefined;
|
||||
shell?: boolean | string | undefined;
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
maxBufferBytes?: number | undefined;
|
||||
outputMode?: "error" | "truncate" | undefined;
|
||||
@@ -38,23 +37,10 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
|
||||
}
|
||||
|
||||
const WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [
|
||||
/is not recognized as an internal or external command/i,
|
||||
/n.o . reconhecido como um comando interno/i,
|
||||
/non . riconosciuto come comando interno o esterno/i,
|
||||
/n.est pas reconnu en tant que commande interne/i,
|
||||
/no se reconoce como un comando interno o externo/i,
|
||||
/wird nicht als interner oder externer befehl/i,
|
||||
] as const;
|
||||
|
||||
function hasWindowsCommandNotFoundMessage(output: string): boolean {
|
||||
return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(output));
|
||||
}
|
||||
|
||||
export function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
|
||||
if (process.platform !== "win32") return false;
|
||||
if (code === 9009) return true;
|
||||
return hasWindowsCommandNotFoundMessage(stderr);
|
||||
return /is not recognized as an internal or external command/i.test(stderr);
|
||||
}
|
||||
|
||||
function normalizeExitError(
|
||||
@@ -153,7 +139,7 @@ export async function runProcess(
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
stdio: "pipe",
|
||||
shell: options.shell ?? process.platform === "win32",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
let stdout = "";
|
||||
|
||||
@@ -27,7 +27,6 @@ const FAVICON_CANDIDATES = [
|
||||
"assets/icon.png",
|
||||
"assets/logo.svg",
|
||||
"assets/logo.png",
|
||||
".idea/icon.svg",
|
||||
] as const;
|
||||
|
||||
// Files that may contain a <link rel="icon"> or icon metadata declaration.
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
|
||||
|
||||
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
|
||||
|
||||
## Mode rules (strict)
|
||||
|
||||
You are in **Plan Mode** until a developer message explicitly ends it.
|
||||
|
||||
Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.
|
||||
|
||||
## Plan Mode vs update_plan tool
|
||||
|
||||
Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`<proposed_plan>\` block.
|
||||
|
||||
Separately, \`update_plan\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \`update_plan\` in Plan mode, it will return an error.
|
||||
|
||||
## Execution vs. mutation in Plan Mode
|
||||
|
||||
You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.
|
||||
|
||||
### Allowed (non-mutating, plan-improving)
|
||||
|
||||
Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:
|
||||
|
||||
* Reading or searching files, configs, schemas, types, manifests, and docs
|
||||
* Static analysis, inspection, and repo exploration
|
||||
* Dry-run style commands when they do not edit repo-tracked files
|
||||
* Tests, builds, or checks that may write to caches or build artifacts (for example, \`target/\`, \`.cache/\`, or snapshots) so long as they do not edit repo-tracked files
|
||||
|
||||
### Not allowed (mutating, plan-executing)
|
||||
|
||||
Actions that implement the plan or change repo-tracked state. Examples:
|
||||
|
||||
* Editing or writing files
|
||||
* Running formatters or linters that rewrite files
|
||||
* Applying patches, migrations, or codegen that updates repo-tracked files
|
||||
* Side-effectful commands whose purpose is to carry out the plan rather than refine it
|
||||
|
||||
When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it.
|
||||
|
||||
## PHASE 1 - Ground in the environment (explore first, ask second)
|
||||
|
||||
Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.
|
||||
|
||||
Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.
|
||||
|
||||
Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.
|
||||
|
||||
Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.
|
||||
|
||||
## PHASE 2 - Intent chat (what they actually want)
|
||||
|
||||
* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.
|
||||
* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.
|
||||
|
||||
## PHASE 3 - Implementation chat (what/how we'll build)
|
||||
|
||||
* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints.
|
||||
|
||||
## Asking questions
|
||||
|
||||
Critical rules:
|
||||
|
||||
* Strongly prefer using the \`request_user_input\` tool to ask any questions.
|
||||
* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.
|
||||
* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool.
|
||||
|
||||
You SHOULD ask many questions, but each question must:
|
||||
|
||||
* materially change the spec/plan, OR
|
||||
* confirm/lock an assumption, OR
|
||||
* choose between meaningful tradeoffs.
|
||||
* not be answerable by non-mutating commands.
|
||||
|
||||
Use the \`request_user_input\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.
|
||||
|
||||
## Two kinds of unknowns (treat differently)
|
||||
|
||||
1. **Discoverable facts** (repo/system truth): explore first.
|
||||
|
||||
* Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).
|
||||
* Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.
|
||||
* If asking, present concrete candidates (paths/service names) + recommend one.
|
||||
* Never ask questions you can answer from your environment (e.g., "where is this struct").
|
||||
|
||||
2. **Preferences/tradeoffs** (not discoverable): ask early.
|
||||
|
||||
* These are intent or implementation preferences that cannot be derived from exploration.
|
||||
* Provide 2-4 mutually exclusive options + a recommended default.
|
||||
* If unanswered, proceed with the recommended option and record it as an assumption in the final plan.
|
||||
|
||||
## Finalization rule
|
||||
|
||||
Only output the final plan when it is decision complete and leaves no decisions to the implementer.
|
||||
|
||||
When you present the official plan, wrap it in a \`<proposed_plan>\` block so the client can render it specially:
|
||||
|
||||
1) The opening tag must be on its own line.
|
||||
2) Start the plan content on the next line (no text on the same line as the tag).
|
||||
3) The closing tag must be on its own line.
|
||||
4) Use Markdown inside the block.
|
||||
5) Keep the tags exactly as \`<proposed_plan>\` and \`</proposed_plan>\` (do not translate or rename them), even if the plan content is in another language.
|
||||
|
||||
Example:
|
||||
|
||||
<proposed_plan>
|
||||
plan content
|
||||
</proposed_plan>
|
||||
|
||||
plan content should be human and agent digestible. The final plan must be plan-only and include:
|
||||
|
||||
* A clear title
|
||||
* A brief summary section
|
||||
* Important changes or additions to public APIs/interfaces/types
|
||||
* Test cases and scenarios
|
||||
* Explicit assumptions and defaults chosen where needed
|
||||
|
||||
Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
|
||||
|
||||
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
|
||||
</collaboration_mode>`;
|
||||
|
||||
export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
|
||||
|
||||
You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
|
||||
|
||||
Your active mode changes only when new developer instructions with a different \`<collaboration_mode>...</collaboration_mode>\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.
|
||||
|
||||
## request_user_input availability
|
||||
|
||||
The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
|
||||
|
||||
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
|
||||
</collaboration_mode>`;
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
type RuntimeMode,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect, Fiber, Layer, Random, Stream } from "effect";
|
||||
|
||||
@@ -334,9 +333,13 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||
{ id: "effort", value: "max" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
@@ -377,9 +380,13 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-7", [
|
||||
{ id: "effort", value: "xhigh" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-7",
|
||||
options: {
|
||||
effort: "xhigh",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
@@ -398,9 +405,13 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||
{ id: "effort", value: "max" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
@@ -419,9 +430,13 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [
|
||||
{ id: "effort", value: "high" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
options: {
|
||||
effort: "high",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
@@ -440,9 +455,13 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [
|
||||
{ id: "thinking", value: false },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
options: {
|
||||
thinking: false,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
@@ -463,9 +482,13 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||
{ id: "thinking", value: false },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
thinking: false,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
@@ -484,9 +507,13 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
@@ -507,9 +534,13 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
@@ -528,9 +559,13 @@ describe("ClaudeAdapterLive", () => {
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||
{ id: "effort", value: "ultrathink" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "ultrathink",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
@@ -538,9 +573,13 @@ describe("ClaudeAdapterLive", () => {
|
||||
threadId: session.threadId,
|
||||
input: "Investigate the edge cases",
|
||||
attachments: [],
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||
{ id: "effort", value: "ultrathink" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "ultrathink",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
@@ -2755,9 +2794,13 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||
{ id: "contextWindow", value: "1m" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
contextWindow: "1m",
|
||||
},
|
||||
},
|
||||
attachments: [],
|
||||
});
|
||||
yield* adapter.sendTurn({
|
||||
|
||||
@@ -40,14 +40,9 @@ import {
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type UserInputQuestion,
|
||||
ClaudeAgentEffort,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getModelSelectionBooleanOptionValue,
|
||||
getModelSelectionStringOptionValue,
|
||||
getProviderOptionDescriptors,
|
||||
resolvePromptInjectedEffort,
|
||||
} from "@t3tools/shared/model";
|
||||
import { applyClaudePromptEffortPrefix, resolveEffort, trimOrNull } from "@t3tools/shared/model";
|
||||
import {
|
||||
Cause,
|
||||
DateTime,
|
||||
@@ -66,12 +61,7 @@ import {
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import {
|
||||
getClaudeModelCapabilities,
|
||||
normalizeClaudeCliEffort,
|
||||
resolveClaudeApiModelId,
|
||||
resolveClaudeEffort,
|
||||
} from "./ClaudeProvider.ts";
|
||||
import { getClaudeModelCapabilities, resolveClaudeApiModelId } from "./ClaudeProvider.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
ProviderAdapterRequestError,
|
||||
@@ -221,9 +211,19 @@ function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray
|
||||
return squashed.length > 0 ? [squashed] : [];
|
||||
}
|
||||
|
||||
function getEffectiveClaudeAgentEffort(effort: string | null | undefined): ClaudeSdkEffort | null {
|
||||
const normalized = normalizeClaudeCliEffort(effort);
|
||||
return normalized ? (normalized as ClaudeSdkEffort) : null;
|
||||
function getEffectiveClaudeAgentEffort(
|
||||
effort: ClaudeAgentEffort | null | undefined,
|
||||
): ClaudeSdkEffort | null {
|
||||
if (!effort) {
|
||||
return null;
|
||||
}
|
||||
if (effort === "ultrathink") {
|
||||
return null;
|
||||
}
|
||||
if (effort === "xhigh") {
|
||||
return "max";
|
||||
}
|
||||
return effort;
|
||||
}
|
||||
|
||||
function isClaudeInterruptedMessage(message: string): boolean {
|
||||
@@ -555,14 +555,16 @@ const CLAUDE_SETTING_SOURCES = [
|
||||
|
||||
function buildPromptText(input: ProviderSendTurnInput): string {
|
||||
const rawEffort =
|
||||
input.modelSelection?.provider === "claudeAgent"
|
||||
? getModelSelectionStringOptionValue(input.modelSelection, "effort")
|
||||
: null;
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.options?.effort : null;
|
||||
const claudeModel =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined;
|
||||
const caps = getClaudeModelCapabilities(claudeModel);
|
||||
|
||||
const promptEffort = resolvePromptInjectedEffort(caps, rawEffort);
|
||||
// For prompt injection, we check if the raw effort is a prompt-injected level (e.g. "ultrathink").
|
||||
// resolveEffort strips prompt-injected values (returning the default instead), so we check the raw value directly.
|
||||
const trimmedEffort = trimOrNull(rawEffort);
|
||||
const promptEffort =
|
||||
trimmedEffort && caps.promptInjectedEffortLevels.includes(trimmedEffort) ? trimmedEffort : null;
|
||||
return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort);
|
||||
}
|
||||
|
||||
@@ -2822,22 +2824,14 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const modelSelection =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
|
||||
const caps = getClaudeModelCapabilities(modelSelection?.model);
|
||||
const descriptors = getProviderOptionDescriptors({ caps });
|
||||
const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;
|
||||
const rawEffort = getModelSelectionStringOptionValue(modelSelection, "effort");
|
||||
const effort = resolveClaudeEffort(caps, rawEffort) ?? null;
|
||||
const fastModeSupported = descriptors.some(
|
||||
(descriptor) => descriptor.type === "boolean" && descriptor.id === "fastMode",
|
||||
);
|
||||
const thinkingSupported = descriptors.some(
|
||||
(descriptor) => descriptor.type === "boolean" && descriptor.id === "thinking",
|
||||
);
|
||||
const fastMode =
|
||||
getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true &&
|
||||
fastModeSupported;
|
||||
const thinking = thinkingSupported
|
||||
? getModelSelectionBooleanOptionValue(modelSelection, "thinking")
|
||||
: undefined;
|
||||
const effort = (resolveEffort(caps, modelSelection?.options?.effort) ??
|
||||
null) as ClaudeAgentEffort | null;
|
||||
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
|
||||
const thinking =
|
||||
typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
|
||||
? modelSelection.options.thinking
|
||||
: undefined;
|
||||
const effectiveEffort = getEffectiveClaudeAgentEffort(effort);
|
||||
const runtimeModeToPermission: Record<string, PermissionMode> = {
|
||||
"auto-accept-edits": "acceptEdits",
|
||||
|
||||
@@ -11,23 +11,13 @@ import type {
|
||||
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
import {
|
||||
createModelCapabilities,
|
||||
getModelSelectionStringOptionValue,
|
||||
getProviderOptionCurrentValue,
|
||||
getProviderOptionDescriptors,
|
||||
} from "@t3tools/shared/model";
|
||||
import {
|
||||
query as claudeQuery,
|
||||
type SlashCommand as ClaudeSlashCommand,
|
||||
type SDKUserMessage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
import {
|
||||
buildBooleanOptionDescriptor,
|
||||
buildSelectOptionDescriptor,
|
||||
buildServerProvider,
|
||||
AUTH_PROBE_TIMEOUT_MS,
|
||||
DEFAULT_TIMEOUT_MS,
|
||||
detailFromResult,
|
||||
extractAuthBoolean,
|
||||
@@ -43,143 +33,108 @@ import { ClaudeProvider } from "../Services/ClaudeProvider.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [],
|
||||
});
|
||||
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
};
|
||||
|
||||
const PROVIDER = "claudeAgent" as const;
|
||||
const CLAUDE_PRESENTATION = {
|
||||
displayName: "Claude",
|
||||
showInteractionModeToggle: true,
|
||||
} as const;
|
||||
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
|
||||
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
{
|
||||
slug: "claude-opus-4-7",
|
||||
name: "Claude Opus 4.7",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High" },
|
||||
{ value: "xhigh", label: "Extra High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
options: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
}),
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High" },
|
||||
{ value: "xhigh", label: "Extra High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
}),
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Claude Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildBooleanOptionDescriptor({
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
options: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
}),
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
}),
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-4-5",
|
||||
name: "Claude Opus 4.5",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
],
|
||||
}),
|
||||
buildBooleanOptionDescriptor({
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
}),
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
],
|
||||
}),
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
name: "Claude Sonnet 4.6",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
options: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
}),
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
}),
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "claude-haiku-4-5",
|
||||
name: "Claude Haiku 4.5",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
buildBooleanOptionDescriptor({
|
||||
id: "thinking",
|
||||
label: "Thinking",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -209,41 +164,8 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveClaudeEffort(
|
||||
caps: ModelCapabilities,
|
||||
raw: string | null | undefined,
|
||||
): string | undefined {
|
||||
const descriptors = getProviderOptionDescriptors({
|
||||
caps,
|
||||
...(raw ? { selections: [{ id: "effort", value: raw }] } : {}),
|
||||
});
|
||||
const effortDescriptor = descriptors.find((descriptor) => descriptor.id === "effort");
|
||||
const value = getProviderOptionCurrentValue(effortDescriptor);
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a resolved Claude effort value into one suitable for the Claude
|
||||
* CLI's `--effort` flag.
|
||||
*
|
||||
* Mirrors the mapping used when invoking the Claude Agent SDK
|
||||
* ({@link getEffectiveClaudeAgentEffort} in ClaudeAdapter): the Opus 4.7
|
||||
* capability `"xhigh"` is rewritten to the accepted CLI value `"max"`, and
|
||||
* `"ultrathink"` is filtered out because it is a prompt-prefix mode rather
|
||||
* than a CLI-effort value. Returns `undefined` when no flag should be passed.
|
||||
*/
|
||||
export function normalizeClaudeCliEffort(effort: string | null | undefined): string | undefined {
|
||||
if (!effort || effort === "ultrathink") {
|
||||
return undefined;
|
||||
}
|
||||
if (effort === "xhigh") {
|
||||
return "max";
|
||||
}
|
||||
return effort;
|
||||
}
|
||||
|
||||
export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string {
|
||||
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
|
||||
switch (modelSelection.options?.contextWindow) {
|
||||
case "1m":
|
||||
return `${modelSelection.model}[1m]`;
|
||||
default:
|
||||
@@ -558,24 +480,13 @@ function dedupeSlashCommands(
|
||||
return [...commandsByName.values()];
|
||||
}
|
||||
|
||||
function waitForAbortSignal(signal: AbortSignal): Promise<void> {
|
||||
if (signal.aborted) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
signal.addEventListener("abort", () => resolve(), { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe account information by spawning a lightweight Claude Agent SDK
|
||||
* session and reading the initialization result.
|
||||
*
|
||||
* We pass a never-yielding AsyncIterable as the prompt so that no user
|
||||
* message is ever written to the subprocess stdin. This means the Claude
|
||||
* Code subprocess completes its local initialization IPC (returning
|
||||
* account info and slash commands) but never starts an API request to
|
||||
* Anthropic. We read the init data and then abort the subprocess.
|
||||
* The prompt is never sent to the Anthropic API — we abort immediately
|
||||
* after the local initialization phase completes. This gives us the
|
||||
* user's subscription type without incurring any token cost.
|
||||
*
|
||||
* This is used as a fallback when `claude auth status` does not include
|
||||
* subscription type information.
|
||||
@@ -584,16 +495,12 @@ const probeClaudeCapabilities = (binaryPath: string) => {
|
||||
const abort = new AbortController();
|
||||
return Effect.tryPromise(async () => {
|
||||
const q = claudeQuery({
|
||||
// Never yield — we only need initialization data, not a conversation.
|
||||
// This prevents any prompt from reaching the Anthropic API.
|
||||
// oxlint-disable-next-line require-yield
|
||||
prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
|
||||
await waitForAbortSignal(abort.signal);
|
||||
})(),
|
||||
prompt: ".",
|
||||
options: {
|
||||
persistSession: false,
|
||||
pathToClaudeCodeExecutable: binaryPath,
|
||||
abortController: abort,
|
||||
maxTurns: 0,
|
||||
settingSources: ["user", "project", "local"],
|
||||
allowedTools: [],
|
||||
stderr: () => {},
|
||||
@@ -655,7 +562,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
if (!claudeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CLAUDE_PRESENTATION,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models: allModels,
|
||||
@@ -678,7 +584,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CLAUDE_PRESENTATION,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models: allModels,
|
||||
@@ -697,7 +602,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CLAUDE_PRESENTATION,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models: allModels,
|
||||
@@ -718,7 +622,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
const detail = detailFromResult(version);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CLAUDE_PRESENTATION,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models: allModels,
|
||||
@@ -755,7 +658,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
// ── Auth check + subscription detection ────────────────────────────
|
||||
|
||||
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
|
||||
Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
@@ -783,7 +686,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
const error = authProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CLAUDE_PRESENTATION,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
@@ -804,7 +706,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CLAUDE_PRESENTATION,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
@@ -823,7 +724,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod });
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CLAUDE_PRESENTATION,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
@@ -857,7 +757,6 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid
|
||||
if (!claudeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CLAUDE_PRESENTATION,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
@@ -873,7 +772,6 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid
|
||||
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CLAUDE_PRESENTATION,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,275 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { Effect, Schema } from "effect";
|
||||
import { describe, it } from "vitest";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import * as CodexErrors from "effect-codex-app-server/errors";
|
||||
import * as CodexRpc from "effect-codex-app-server/rpc";
|
||||
|
||||
import {
|
||||
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
} from "../CodexDeveloperInstructions.ts";
|
||||
import {
|
||||
buildTurnStartParams,
|
||||
isRecoverableThreadResumeError,
|
||||
openCodexThread,
|
||||
} from "./CodexSessionRuntime.ts";
|
||||
|
||||
function makeThreadOpenResponse(
|
||||
threadId: string,
|
||||
): CodexRpc.ClientRequestResponsesByMethod["thread/start"] {
|
||||
return {
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
modelProvider: "openai",
|
||||
approvalPolicy: "never",
|
||||
approvalsReviewer: "user",
|
||||
sandbox: { type: "danger-full-access" },
|
||||
thread: {
|
||||
id: threadId,
|
||||
createdAt: "2026-04-18T00:00:00.000Z",
|
||||
source: { session: "cli" },
|
||||
turns: [],
|
||||
status: {
|
||||
state: "idle",
|
||||
activeFlags: [],
|
||||
},
|
||||
},
|
||||
} as unknown as CodexRpc.ClientRequestResponsesByMethod["thread/start"];
|
||||
}
|
||||
|
||||
describe("buildTurnStartParams", () => {
|
||||
it("includes plan collaboration mode when requested", () => {
|
||||
const params = Effect.runSync(
|
||||
buildTurnStartParams({
|
||||
threadId: "provider-thread-1",
|
||||
runtimeMode: "full-access",
|
||||
prompt: "Make a plan",
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "medium",
|
||||
interactionMode: "plan",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(params, {
|
||||
threadId: "provider-thread-1",
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: {
|
||||
type: "dangerFullAccess",
|
||||
},
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Make a plan",
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "medium",
|
||||
collaborationMode: {
|
||||
mode: "plan",
|
||||
settings: {
|
||||
model: "gpt-5.3-codex",
|
||||
reasoning_effort: "medium",
|
||||
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("includes default collaboration mode and image attachments", () => {
|
||||
const params = Effect.runSync(
|
||||
buildTurnStartParams({
|
||||
threadId: "provider-thread-1",
|
||||
runtimeMode: "auto-accept-edits",
|
||||
prompt: "Implement it",
|
||||
model: "gpt-5.3-codex",
|
||||
interactionMode: "default",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
url: "data:image/png;base64,abc",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(params, {
|
||||
threadId: "provider-thread-1",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxPolicy: {
|
||||
type: "workspaceWrite",
|
||||
},
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Implement it",
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
url: "data:image/png;base64,abc",
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3-codex",
|
||||
collaborationMode: {
|
||||
mode: "default",
|
||||
settings: {
|
||||
model: "gpt-5.3-codex",
|
||||
reasoning_effort: "medium",
|
||||
developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("omits collaboration mode when interaction mode is absent", () => {
|
||||
const params = Effect.runSync(
|
||||
buildTurnStartParams({
|
||||
threadId: "provider-thread-1",
|
||||
runtimeMode: "approval-required",
|
||||
prompt: "Review",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(params, {
|
||||
threadId: "provider-thread-1",
|
||||
approvalPolicy: "untrusted",
|
||||
sandboxPolicy: {
|
||||
type: "readOnly",
|
||||
},
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Review",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("isRecoverableThreadResumeError", () => {
|
||||
it("matches missing thread errors", () => {
|
||||
assert.equal(
|
||||
isRecoverableThreadResumeError(
|
||||
new CodexErrors.CodexAppServerRequestError({
|
||||
code: -32603,
|
||||
errorMessage: "Thread does not exist",
|
||||
}),
|
||||
),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores non-recoverable resume errors", () => {
|
||||
assert.equal(
|
||||
isRecoverableThreadResumeError(
|
||||
new CodexErrors.CodexAppServerRequestError({
|
||||
code: -32603,
|
||||
errorMessage: "Permission denied",
|
||||
}),
|
||||
),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores unrelated missing-resource errors that do not mention threads", () => {
|
||||
assert.equal(
|
||||
isRecoverableThreadResumeError(
|
||||
new CodexErrors.CodexAppServerRequestError({
|
||||
code: -32603,
|
||||
errorMessage: "Config file not found",
|
||||
}),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isRecoverableThreadResumeError(
|
||||
new CodexErrors.CodexAppServerRequestError({
|
||||
code: -32603,
|
||||
errorMessage: "Model does not exist",
|
||||
}),
|
||||
),
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("openCodexThread", () => {
|
||||
it("falls back to thread/start when resume fails recoverably", async () => {
|
||||
const calls: Array<{ method: "thread/start" | "thread/resume"; payload: unknown }> = [];
|
||||
const started = makeThreadOpenResponse("fresh-thread");
|
||||
const client = {
|
||||
request: <M extends "thread/start" | "thread/resume">(
|
||||
method: M,
|
||||
payload: CodexRpc.ClientRequestParamsByMethod[M],
|
||||
) => {
|
||||
calls.push({ method, payload });
|
||||
if (method === "thread/resume") {
|
||||
return Effect.fail(
|
||||
new CodexErrors.CodexAppServerRequestError({
|
||||
code: -32603,
|
||||
errorMessage: "thread not found",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(started as CodexRpc.ClientRequestResponsesByMethod[M]);
|
||||
},
|
||||
};
|
||||
|
||||
const opened = await Effect.runPromise(
|
||||
openCodexThread({
|
||||
client,
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
cwd: "/tmp/project",
|
||||
requestedModel: "gpt-5.3-codex",
|
||||
serviceTier: undefined,
|
||||
resumeThreadId: "stale-thread",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(opened.thread.id, "fresh-thread");
|
||||
assert.deepStrictEqual(
|
||||
calls.map((call) => call.method),
|
||||
["thread/resume", "thread/start"],
|
||||
);
|
||||
});
|
||||
|
||||
it("propagates non-recoverable resume failures", async () => {
|
||||
const client = {
|
||||
request: <M extends "thread/start" | "thread/resume">(
|
||||
method: M,
|
||||
_payload: CodexRpc.ClientRequestParamsByMethod[M],
|
||||
) => {
|
||||
if (method === "thread/resume") {
|
||||
return Effect.fail(
|
||||
new CodexErrors.CodexAppServerRequestError({
|
||||
code: -32603,
|
||||
errorMessage: "timed out waiting for server",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(
|
||||
makeThreadOpenResponse("fresh-thread") as CodexRpc.ClientRequestResponsesByMethod[M],
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
await assert.rejects(
|
||||
Effect.runPromise(
|
||||
openCodexThread({
|
||||
client,
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
cwd: "/tmp/project",
|
||||
requestedModel: "gpt-5.3-codex",
|
||||
serviceTier: undefined,
|
||||
resumeThreadId: "stale-thread",
|
||||
}),
|
||||
),
|
||||
(error: unknown) =>
|
||||
Schema.is(CodexErrors.CodexAppServerRequestError)(error) &&
|
||||
error.errorMessage === "timed out waiting for server",
|
||||
);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -6,7 +6,6 @@ import { fileURLToPath } from "node:url";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Deferred, Effect, Fiber, Layer, Stream } from "effect";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
|
||||
import { ApprovalRequestId, type ProviderRuntimeEvent, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
@@ -358,11 +357,15 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
providers: { cursor: { binaryPath: wrapperPath } },
|
||||
});
|
||||
|
||||
const modelSelection = createModelSelection("cursor", "gpt-5.4", [
|
||||
{ id: "reasoning", value: "xhigh" },
|
||||
{ id: "contextWindow", value: "1m" },
|
||||
{ id: "fastMode", value: true },
|
||||
]);
|
||||
const modelSelection = {
|
||||
provider: "cursor" as const,
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoning: "xhigh" as const,
|
||||
contextWindow: "1m",
|
||||
fastMode: true,
|
||||
},
|
||||
};
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
@@ -1089,9 +1092,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
threadId,
|
||||
input: "second turn after switching model",
|
||||
attachments: [],
|
||||
modelSelection: createModelSelection("cursor", "composer-2", [
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
modelSelection: { provider: "cursor", model: "composer-2", options: { fastMode: true } },
|
||||
});
|
||||
|
||||
const argvRuns = yield* Effect.promise(() => readArgvLog(argvLogPath));
|
||||
@@ -1146,18 +1147,14 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
threadId,
|
||||
input: "first turn with fast mode",
|
||||
attachments: [],
|
||||
modelSelection: createModelSelection("cursor", "composer-2", [
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
modelSelection: { provider: "cursor", model: "composer-2", options: { fastMode: true } },
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "second turn without fast mode",
|
||||
attachments: [],
|
||||
modelSelection: createModelSelection("cursor", "composer-2", [
|
||||
{ id: "fastMode", value: false },
|
||||
]),
|
||||
modelSelection: { provider: "cursor", model: "composer-2", options: { fastMode: false } },
|
||||
});
|
||||
|
||||
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
|
||||
|
||||
@@ -7,7 +7,7 @@ import * as nodePath from "node:path";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type ProviderOptionSelection,
|
||||
type CursorModelOptions,
|
||||
EventId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderInteractionMode,
|
||||
@@ -222,7 +222,7 @@ function applyRequestedSessionConfiguration<E>(input: {
|
||||
readonly modelSelection:
|
||||
| {
|
||||
readonly model: string;
|
||||
readonly options?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
|
||||
readonly options?: CursorModelOptions | null | undefined;
|
||||
}
|
||||
| undefined;
|
||||
readonly mapError: (context: {
|
||||
@@ -235,7 +235,7 @@ function applyRequestedSessionConfiguration<E>(input: {
|
||||
yield* applyCursorAcpModelSelection({
|
||||
runtime: input.runtime,
|
||||
model: input.modelSelection.model,
|
||||
selections: input.modelSelection.options,
|
||||
modelOptions: input.modelSelection.options,
|
||||
mapError: ({ cause }) =>
|
||||
input.mapError({
|
||||
cause,
|
||||
|
||||
@@ -8,7 +8,6 @@ import { Effect } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildCursorProviderSnapshot,
|
||||
@@ -28,31 +27,6 @@ import {
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
|
||||
function selectDescriptor(
|
||||
id: string,
|
||||
label: string,
|
||||
options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>,
|
||||
) {
|
||||
return {
|
||||
id,
|
||||
label,
|
||||
type: "select" as const,
|
||||
options: [...options],
|
||||
...(options.find((option) => option.isDefault)?.id
|
||||
? { currentValue: options.find((option) => option.isDefault)?.id }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function booleanDescriptor(id: string, label: string, currentValue?: boolean) {
|
||||
return {
|
||||
id,
|
||||
label,
|
||||
type: "boolean" as const,
|
||||
...(typeof currentValue === "boolean" ? { currentValue } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-mock-"));
|
||||
const wrapperPath = path.join(dir, "fake-agent.sh");
|
||||
@@ -265,7 +239,13 @@ const baseCursorSettings: CursorSettings = {
|
||||
customModels: [],
|
||||
};
|
||||
|
||||
const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] });
|
||||
const emptyCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
} as const;
|
||||
|
||||
describe("getCursorFallbackModels", () => {
|
||||
it("does not publish any built-in cursor models before ACP discovery", () => {
|
||||
@@ -329,57 +309,52 @@ describe("buildCursorProviderSnapshot", () => {
|
||||
|
||||
describe("buildCursorCapabilitiesFromConfigOptions", () => {
|
||||
it("derives model capabilities from parameterized Cursor ACP config options", () => {
|
||||
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual(
|
||||
createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
selectDescriptor("reasoning", "Reasoning", [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium", isDefault: true },
|
||||
{ id: "high", label: "High" },
|
||||
{ id: "xhigh", label: "Extra High" },
|
||||
]),
|
||||
selectDescriptor("contextWindow", "Context", [
|
||||
{ id: "272k", label: "272K", isDefault: true },
|
||||
{ id: "1m", label: "1M" },
|
||||
]),
|
||||
booleanDescriptor("fastMode", "Fast", false),
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual({
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium", isDefault: true },
|
||||
{ value: "high", label: "High" },
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "272k", label: "272K", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
promptInjectedEffortLevels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("detects boolean thinking toggles from model_config options", () => {
|
||||
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeConfigOptions)).toEqual(
|
||||
createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
selectDescriptor("reasoning", "Reasoning", [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium" },
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
]),
|
||||
booleanDescriptor("thinking", "Thinking", true),
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeConfigOptions)).toEqual({
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers the newer model_option effort control over legacy thought_level", () => {
|
||||
expect(
|
||||
buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeModelOptionConfigOptions),
|
||||
).toEqual(
|
||||
createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
selectDescriptor("reasoning", "Effort", [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium" },
|
||||
{ id: "high", label: "High" },
|
||||
{ id: "max", label: "Max", isDefault: true },
|
||||
]),
|
||||
booleanDescriptor("fastMode", "Fast", true),
|
||||
booleanDescriptor("thinking", "Thinking", true),
|
||||
],
|
||||
}),
|
||||
);
|
||||
).toEqual({
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High" },
|
||||
{ value: "max", label: "Max", isDefault: true },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -390,39 +365,73 @@ describe("buildCursorDiscoveredModelsFromConfigOptions", () => {
|
||||
slug: "default",
|
||||
name: "Auto",
|
||||
isCustom: false,
|
||||
capabilities: emptyCapabilities,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "composer-2",
|
||||
name: "Composer 2",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [booleanDescriptor("fastMode", "Fast", true)],
|
||||
}),
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
capabilities: emptyCapabilities,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
name: "Sonnet 4.6",
|
||||
isCustom: false,
|
||||
capabilities: emptyCapabilities,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: emptyCapabilities,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex-spark",
|
||||
name: "Codex 5.3 Spark",
|
||||
isCustom: false,
|
||||
capabilities: emptyCapabilities,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -636,11 +645,11 @@ describe("resolveCursorAcpBaseModelId", () => {
|
||||
describe("resolveCursorAcpConfigUpdates", () => {
|
||||
it("maps Cursor model options onto separate ACP config option updates", () => {
|
||||
expect(
|
||||
resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [
|
||||
{ id: "reasoning", value: "xhigh" },
|
||||
{ id: "fastMode", value: true },
|
||||
{ id: "contextWindow", value: "1m" },
|
||||
]),
|
||||
resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, {
|
||||
reasoning: "xhigh",
|
||||
fastMode: true,
|
||||
contextWindow: "1m",
|
||||
}),
|
||||
).toEqual([
|
||||
{ configId: "reasoning", value: "extra-high" },
|
||||
{ configId: "context", value: "1m" },
|
||||
@@ -650,26 +659,26 @@ describe("resolveCursorAcpConfigUpdates", () => {
|
||||
|
||||
it("maps boolean thinking toggles when the model exposes them separately", () => {
|
||||
expect(
|
||||
resolveCursorAcpConfigUpdates(parameterizedClaudeConfigOptions, [
|
||||
{ id: "thinking", value: false },
|
||||
]),
|
||||
resolveCursorAcpConfigUpdates(parameterizedClaudeConfigOptions, {
|
||||
thinking: false,
|
||||
}),
|
||||
).toEqual([{ configId: "thinking", value: false }]);
|
||||
});
|
||||
|
||||
it("maps explicit fastMode: false so the adapter can clear a prior fast selection", () => {
|
||||
expect(
|
||||
resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [
|
||||
{ id: "fastMode", value: false },
|
||||
]),
|
||||
resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, {
|
||||
fastMode: false,
|
||||
}),
|
||||
).toEqual([{ configId: "fast", value: "false" }]);
|
||||
});
|
||||
|
||||
it("writes Cursor effort changes through the newer model_option config when available", () => {
|
||||
expect(
|
||||
resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, [
|
||||
{ id: "reasoning", value: "max" },
|
||||
{ id: "thinking", value: false },
|
||||
]),
|
||||
resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, {
|
||||
reasoning: "max",
|
||||
thinking: false,
|
||||
}),
|
||||
).toEqual([
|
||||
{ configId: "effort", value: "max" },
|
||||
{ configId: "thinking", value: "false" },
|
||||
|
||||
@@ -3,9 +3,9 @@ import * as nodeOs from "node:os";
|
||||
import * as nodePath from "node:path";
|
||||
|
||||
import type {
|
||||
CursorModelOptions,
|
||||
CursorSettings,
|
||||
ModelCapabilities,
|
||||
ProviderOptionSelection,
|
||||
ServerProvider,
|
||||
ServerProviderAuth,
|
||||
ServerProviderModel,
|
||||
@@ -15,15 +15,8 @@ import type {
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { Cause, Effect, Equal, Exit, Layer, Option, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import {
|
||||
createModelCapabilities,
|
||||
getProviderOptionBooleanSelectionValue,
|
||||
getProviderOptionStringSelectionValue,
|
||||
} from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildBooleanOptionDescriptor,
|
||||
buildSelectOptionDescriptor,
|
||||
buildServerProvider,
|
||||
collectStreamAsString,
|
||||
isCommandMissingCause,
|
||||
@@ -36,14 +29,13 @@ import { AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const PROVIDER = "cursor" as const;
|
||||
const CURSOR_PRESENTATION = {
|
||||
displayName: "Cursor",
|
||||
badgeLabel: "Early Access",
|
||||
showInteractionModeToggle: true,
|
||||
} as const;
|
||||
const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [],
|
||||
});
|
||||
const EMPTY_CAPABILITIES: ModelCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
};
|
||||
|
||||
const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
|
||||
const CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT = "4 seconds";
|
||||
@@ -63,7 +55,6 @@ function buildInitialCursorProviderSnapshot(cursorSettings: CursorSettings): Ser
|
||||
if (!cursorSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CURSOR_PRESENTATION,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
@@ -79,7 +70,6 @@ function buildInitialCursorProviderSnapshot(cursorSettings: CursorSettings): Ser
|
||||
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CURSOR_PRESENTATION,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
@@ -208,28 +198,6 @@ function isBooleanLikeConfigOption(option: EffectAcpSchema.SessionConfigOption):
|
||||
return values.has("true") && values.has("false");
|
||||
}
|
||||
|
||||
function getBooleanCurrentValue(
|
||||
option: EffectAcpSchema.SessionConfigOption | undefined,
|
||||
): boolean | undefined {
|
||||
if (!option) {
|
||||
return undefined;
|
||||
}
|
||||
if (option.type === "boolean") {
|
||||
return option.currentValue;
|
||||
}
|
||||
if (option.type !== "select") {
|
||||
return undefined;
|
||||
}
|
||||
const normalized = option.currentValue?.trim().toLowerCase();
|
||||
if (normalized === "true") {
|
||||
return true;
|
||||
}
|
||||
if (normalized === "false") {
|
||||
return false;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function buildCursorCapabilitiesFromConfigOptions(
|
||||
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
|
||||
): ModelCapabilities {
|
||||
@@ -283,60 +251,14 @@ export function buildCursorCapabilitiesFromConfigOptions(
|
||||
const thinkingOption = configOptions.find(
|
||||
(option) => option.category === "model_config" && isCursorThinkingConfigOption(option),
|
||||
);
|
||||
const fastCurrentValue = getBooleanCurrentValue(fastOption);
|
||||
const thinkingCurrentValue = getBooleanCurrentValue(thinkingOption);
|
||||
const optionDescriptors = [
|
||||
...(reasoningEffortLevels.length > 0
|
||||
? [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "reasoning",
|
||||
label: reasoningConfig?.name?.trim() || "Reasoning",
|
||||
options: reasoningEffortLevels,
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(contextWindowOptions.length > 0
|
||||
? [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: contextOption?.name?.trim() || "Context Window",
|
||||
options: contextWindowOptions,
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(fastOption && isBooleanLikeConfigOption(fastOption)
|
||||
? [
|
||||
typeof fastCurrentValue === "boolean"
|
||||
? buildBooleanOptionDescriptor({
|
||||
id: "fastMode",
|
||||
label: fastOption.name?.trim() || "Fast Mode",
|
||||
currentValue: fastCurrentValue,
|
||||
})
|
||||
: buildBooleanOptionDescriptor({
|
||||
id: "fastMode",
|
||||
label: fastOption.name?.trim() || "Fast Mode",
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(thinkingOption && isBooleanLikeConfigOption(thinkingOption)
|
||||
? [
|
||||
typeof thinkingCurrentValue === "boolean"
|
||||
? buildBooleanOptionDescriptor({
|
||||
id: "thinking",
|
||||
label: thinkingOption.name?.trim() || "Thinking",
|
||||
currentValue: thinkingCurrentValue,
|
||||
})
|
||||
: buildBooleanOptionDescriptor({
|
||||
id: "thinking",
|
||||
label: thinkingOption.name?.trim() || "Thinking",
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
return createModelCapabilities({
|
||||
optionDescriptors,
|
||||
});
|
||||
return {
|
||||
reasoningEffortLevels,
|
||||
supportsFastMode: fastOption ? isBooleanLikeConfigOption(fastOption) : false,
|
||||
supportsThinkingToggle: thinkingOption ? isBooleanLikeConfigOption(thinkingOption) : false,
|
||||
contextWindowOptions,
|
||||
promptInjectedEffortLevels: [],
|
||||
};
|
||||
}
|
||||
|
||||
function buildCursorDiscoveredModels(
|
||||
@@ -360,7 +282,13 @@ function buildCursorDiscoveredModels(
|
||||
}
|
||||
|
||||
function hasCursorModelCapabilities(model: Pick<ServerProviderModel, "capabilities">): boolean {
|
||||
return (model.capabilities?.optionDescriptors?.length ?? 0) > 0;
|
||||
return (
|
||||
(model.capabilities?.reasoningEffortLevels.length ?? 0) > 0 ||
|
||||
model.capabilities?.supportsFastMode === true ||
|
||||
model.capabilities?.supportsThinkingToggle === true ||
|
||||
(model.capabilities?.contextWindowOptions.length ?? 0) > 0 ||
|
||||
(model.capabilities?.promptInjectedEffortLevels.length ?? 0) > 0
|
||||
);
|
||||
}
|
||||
|
||||
export function buildCursorDiscoveredModelsFromConfigOptions(
|
||||
@@ -459,7 +387,7 @@ export function resolveCursorAcpBaseModelId(model: string | null | undefined): s
|
||||
|
||||
export function resolveCursorAcpConfigUpdates(
|
||||
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
|
||||
selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
|
||||
modelOptions: CursorModelOptions | null | undefined,
|
||||
): ReadonlyArray<{ readonly configId: string; readonly value: string | boolean }> {
|
||||
if (!configOptions || configOptions.length === 0) {
|
||||
return [];
|
||||
@@ -468,9 +396,7 @@ export function resolveCursorAcpConfigUpdates(
|
||||
const updates: Array<{ readonly configId: string; readonly value: string | boolean }> = [];
|
||||
|
||||
const reasoningOption = findCursorEffortConfigOption(configOptions);
|
||||
const requestedReasoning = normalizeCursorReasoningValue(
|
||||
getProviderOptionStringSelectionValue(selections, "reasoning"),
|
||||
);
|
||||
const requestedReasoning = normalizeCursorReasoningValue(modelOptions?.reasoning);
|
||||
if (reasoningOption && requestedReasoning) {
|
||||
const value = findCursorSelectOptionValue(reasoningOption, (option) => {
|
||||
const normalizedValue = normalizeCursorReasoningValue(option.value);
|
||||
@@ -485,15 +411,14 @@ export function resolveCursorAcpConfigUpdates(
|
||||
const contextOption = configOptions.find(
|
||||
(option) => option.category === "model_config" && isCursorContextConfigOption(option),
|
||||
);
|
||||
const requestedContextWindow = getProviderOptionStringSelectionValue(selections, "contextWindow");
|
||||
if (contextOption && requestedContextWindow) {
|
||||
if (contextOption && modelOptions?.contextWindow) {
|
||||
const value = findCursorSelectOptionValue(
|
||||
contextOption,
|
||||
(option) =>
|
||||
normalizeCursorConfigOptionToken(option.value) ===
|
||||
normalizeCursorConfigOptionToken(requestedContextWindow) ||
|
||||
normalizeCursorConfigOptionToken(modelOptions.contextWindow) ||
|
||||
normalizeCursorConfigOptionToken(option.name) ===
|
||||
normalizeCursorConfigOptionToken(requestedContextWindow),
|
||||
normalizeCursorConfigOptionToken(modelOptions.contextWindow),
|
||||
);
|
||||
if (value) {
|
||||
updates.push({ configId: contextOption.id, value });
|
||||
@@ -503,9 +428,8 @@ export function resolveCursorAcpConfigUpdates(
|
||||
const fastOption = configOptions.find(
|
||||
(option) => option.category === "model_config" && isCursorFastConfigOption(option),
|
||||
);
|
||||
const requestedFastMode = getProviderOptionBooleanSelectionValue(selections, "fastMode");
|
||||
if (fastOption && typeof requestedFastMode === "boolean") {
|
||||
const value = findCursorBooleanConfigValue(fastOption, requestedFastMode);
|
||||
if (fastOption && typeof modelOptions?.fastMode === "boolean") {
|
||||
const value = findCursorBooleanConfigValue(fastOption, modelOptions.fastMode);
|
||||
if (value !== undefined) {
|
||||
updates.push({ configId: fastOption.id, value });
|
||||
}
|
||||
@@ -514,9 +438,8 @@ export function resolveCursorAcpConfigUpdates(
|
||||
const thinkingOption = configOptions.find(
|
||||
(option) => option.category === "model_config" && isCursorThinkingConfigOption(option),
|
||||
);
|
||||
const requestedThinking = getProviderOptionBooleanSelectionValue(selections, "thinking");
|
||||
if (thinkingOption && typeof requestedThinking === "boolean") {
|
||||
const value = findCursorBooleanConfigValue(thinkingOption, requestedThinking);
|
||||
if (thinkingOption && typeof modelOptions?.thinking === "boolean") {
|
||||
const value = findCursorBooleanConfigValue(thinkingOption, modelOptions.thinking);
|
||||
if (value !== undefined) {
|
||||
updates.push({ configId: thinkingOption.id, value });
|
||||
}
|
||||
@@ -687,7 +610,6 @@ export function buildCursorProviderSnapshot(input: {
|
||||
const message = joinProviderMessages(input.parsed.message, input.discoveryWarning);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CURSOR_PRESENTATION,
|
||||
enabled: input.cursorSettings.enabled,
|
||||
checkedAt: input.checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
@@ -1040,7 +962,6 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
if (!cursorSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CURSOR_PRESENTATION,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
@@ -1064,7 +985,6 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
const error = aboutProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CURSOR_PRESENTATION,
|
||||
enabled: cursorSettings.enabled,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
@@ -1083,7 +1003,6 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
if (Option.isNone(aboutProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CURSOR_PRESENTATION,
|
||||
enabled: cursorSettings.enabled,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
@@ -1106,7 +1025,6 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
if (parameterizedModelPickerUnsupportedMessage) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: CURSOR_PRESENTATION,
|
||||
enabled: cursorSettings.enabled,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
|
||||
@@ -3,18 +3,13 @@ import assert from "node:assert/strict";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { beforeEach } from "vitest";
|
||||
import { beforeEach, vi } from "vitest";
|
||||
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
type OpenCodeRuntimeShape,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import {
|
||||
appendOpenCodeAssistantTextDelta,
|
||||
makeOpenCodeAdapterLive,
|
||||
@@ -23,16 +18,16 @@ import {
|
||||
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
type MessageEntry = {
|
||||
info: {
|
||||
id: string;
|
||||
role: "user" | "assistant";
|
||||
const runtimeMock = vi.hoisted(() => {
|
||||
type MessageEntry = {
|
||||
info: {
|
||||
id: string;
|
||||
role: "user" | "assistant";
|
||||
};
|
||||
parts: Array<unknown>;
|
||||
};
|
||||
parts: Array<unknown>;
|
||||
};
|
||||
|
||||
const runtimeMock = {
|
||||
state: {
|
||||
const state = {
|
||||
startCalls: [] as string[],
|
||||
sessionCreateUrls: [] as string[],
|
||||
authHeaders: [] as Array<string | null>,
|
||||
@@ -43,118 +38,105 @@ const runtimeMock = {
|
||||
closeError: null as Error | null,
|
||||
messages: [] as MessageEntry[],
|
||||
subscribedEvents: [] as unknown[],
|
||||
},
|
||||
reset() {
|
||||
this.state.startCalls.length = 0;
|
||||
this.state.sessionCreateUrls.length = 0;
|
||||
this.state.authHeaders.length = 0;
|
||||
this.state.abortCalls.length = 0;
|
||||
this.state.closeCalls.length = 0;
|
||||
this.state.revertCalls.length = 0;
|
||||
this.state.promptAsyncError = null;
|
||||
this.state.closeError = null;
|
||||
this.state.messages = [];
|
||||
this.state.subscribedEvents = [];
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: ({ binaryPath }) =>
|
||||
Effect.gen(function* () {
|
||||
return {
|
||||
state,
|
||||
reset() {
|
||||
state.startCalls.length = 0;
|
||||
state.sessionCreateUrls.length = 0;
|
||||
state.authHeaders.length = 0;
|
||||
state.abortCalls.length = 0;
|
||||
state.closeCalls.length = 0;
|
||||
state.revertCalls.length = 0;
|
||||
state.promptAsyncError = null;
|
||||
state.closeError = null;
|
||||
state.messages = [];
|
||||
state.subscribedEvents = [];
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../opencodeRuntime.ts", async () => {
|
||||
const actual =
|
||||
await vi.importActual<typeof import("../opencodeRuntime.ts")>("../opencodeRuntime.ts");
|
||||
|
||||
return {
|
||||
...actual,
|
||||
startOpenCodeServerProcess: vi.fn(async ({ binaryPath }: { binaryPath: string }) => {
|
||||
runtimeMock.state.startCalls.push(binaryPath);
|
||||
const url = "http://127.0.0.1:4301";
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
runtimeMock.state.closeCalls.push(url);
|
||||
if (runtimeMock.state.closeError) {
|
||||
throw runtimeMock.state.closeError;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return {
|
||||
url,
|
||||
exitCode: Effect.never,
|
||||
url: "http://127.0.0.1:4301",
|
||||
process: {
|
||||
once() {},
|
||||
},
|
||||
close() {},
|
||||
};
|
||||
}),
|
||||
connectToOpenCodeServer: ({ serverUrl }) =>
|
||||
Effect.gen(function* () {
|
||||
const url = serverUrl ?? "http://127.0.0.1:4301";
|
||||
// Unconditionally register a scope finalizer for test observability —
|
||||
// preserves the `closeCalls` / `closeError` probes that the existing
|
||||
// suites rely on. Production code never attaches a finalizer to an
|
||||
// external server (it simply returns `Effect.succeed(...)`).
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
runtimeMock.state.closeCalls.push(url);
|
||||
if (runtimeMock.state.closeError) {
|
||||
throw runtimeMock.state.closeError;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return {
|
||||
url,
|
||||
exitCode: null,
|
||||
external: Boolean(serverUrl),
|
||||
};
|
||||
}),
|
||||
runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
|
||||
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
|
||||
({
|
||||
session: {
|
||||
create: async () => {
|
||||
runtimeMock.state.sessionCreateUrls.push(baseUrl);
|
||||
runtimeMock.state.authHeaders.push(
|
||||
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
|
||||
);
|
||||
return { data: { id: `${baseUrl}/session` } };
|
||||
},
|
||||
abort: async ({ sessionID }: { sessionID: string }) => {
|
||||
runtimeMock.state.abortCalls.push(sessionID);
|
||||
},
|
||||
promptAsync: async () => {
|
||||
if (runtimeMock.state.promptAsyncError) {
|
||||
throw runtimeMock.state.promptAsyncError;
|
||||
}
|
||||
},
|
||||
messages: async () => ({ data: runtimeMock.state.messages }),
|
||||
revert: async ({ sessionID, messageID }: { sessionID: string; messageID?: string }) => {
|
||||
runtimeMock.state.revertCalls.push({
|
||||
sessionID,
|
||||
...(messageID ? { messageID } : {}),
|
||||
});
|
||||
if (!messageID) {
|
||||
runtimeMock.state.messages = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const targetIndex = runtimeMock.state.messages.findIndex(
|
||||
(entry) => entry.info.id === messageID,
|
||||
);
|
||||
runtimeMock.state.messages =
|
||||
targetIndex >= 0
|
||||
? runtimeMock.state.messages.slice(0, targetIndex + 1)
|
||||
: runtimeMock.state.messages;
|
||||
},
|
||||
connectToOpenCodeServer: vi.fn(async ({ serverUrl }: { serverUrl?: string }) => ({
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
process: null,
|
||||
external: Boolean(serverUrl),
|
||||
close() {
|
||||
runtimeMock.state.closeCalls.push(serverUrl ?? "http://127.0.0.1:4301");
|
||||
if (runtimeMock.state.closeError) {
|
||||
throw runtimeMock.state.closeError;
|
||||
}
|
||||
},
|
||||
event: {
|
||||
subscribe: async () => ({
|
||||
stream: (async function* () {
|
||||
for (const event of runtimeMock.state.subscribedEvents) {
|
||||
yield event;
|
||||
})),
|
||||
createOpenCodeSdkClient: vi.fn(
|
||||
({ baseUrl, serverPassword }: { baseUrl: string; serverPassword?: string }) => ({
|
||||
session: {
|
||||
create: vi.fn(async () => {
|
||||
runtimeMock.state.sessionCreateUrls.push(baseUrl);
|
||||
runtimeMock.state.authHeaders.push(
|
||||
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
|
||||
);
|
||||
return { data: { id: `${baseUrl}/session` } };
|
||||
}),
|
||||
abort: vi.fn(async ({ sessionID }: { sessionID: string }) => {
|
||||
runtimeMock.state.abortCalls.push(sessionID);
|
||||
}),
|
||||
promptAsync: vi.fn(async () => {
|
||||
if (runtimeMock.state.promptAsyncError) {
|
||||
throw runtimeMock.state.promptAsyncError;
|
||||
}
|
||||
})(),
|
||||
}),
|
||||
},
|
||||
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
|
||||
loadOpenCodeInventory: () =>
|
||||
Effect.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "loadOpenCodeInventory",
|
||||
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
|
||||
cause: null,
|
||||
}),
|
||||
messages: vi.fn(async () => ({ data: runtimeMock.state.messages })),
|
||||
revert: vi.fn(
|
||||
async ({ sessionID, messageID }: { sessionID: string; messageID?: string }) => {
|
||||
runtimeMock.state.revertCalls.push({
|
||||
sessionID,
|
||||
...(messageID ? { messageID } : {}),
|
||||
});
|
||||
if (!messageID) {
|
||||
runtimeMock.state.messages = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const targetIndex = runtimeMock.state.messages.findIndex(
|
||||
(entry) => entry.info.id === messageID,
|
||||
);
|
||||
runtimeMock.state.messages =
|
||||
targetIndex >= 0
|
||||
? runtimeMock.state.messages.slice(0, targetIndex + 1)
|
||||
: runtimeMock.state.messages;
|
||||
},
|
||||
),
|
||||
},
|
||||
event: {
|
||||
subscribe: vi.fn(async () => ({
|
||||
stream: (async function* () {
|
||||
for (const event of runtimeMock.state.subscribedEvents) {
|
||||
yield event;
|
||||
}
|
||||
})(),
|
||||
})),
|
||||
},
|
||||
}),
|
||||
),
|
||||
};
|
||||
};
|
||||
});
|
||||
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
|
||||
upsert: () => Effect.void,
|
||||
@@ -166,7 +148,6 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
|
||||
});
|
||||
|
||||
const OpenCodeAdapterTestLayer = makeOpenCodeAdapterLive().pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
@@ -230,7 +211,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears session state even when cleanup finalizers throw", () =>
|
||||
it.effect("clears session state when stopAll cleanup fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
yield* adapter.startSession({
|
||||
@@ -245,14 +226,11 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
});
|
||||
|
||||
runtimeMock.state.closeError = new Error("close failed");
|
||||
// `stopAll` relies on `stopOpenCodeContext`, which is typed as
|
||||
// never-failing. A throwing finalizer surfaces as a defect — `Effect.exit`
|
||||
// captures it so the assertions can still run. The key invariant we're
|
||||
// validating is "the sessions map and close-call probes reflect cleanup
|
||||
// attempts regardless of finalizer outcome".
|
||||
yield* Effect.exit(adapter.stopAll());
|
||||
const error = yield* adapter.stopAll().pipe(Effect.flip);
|
||||
const sessions = yield* adapter.listSessions();
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterProcessError");
|
||||
assert.equal(error.detail, "Failed to stop 2 OpenCode sessions.");
|
||||
assert.deepEqual(runtimeMock.state.closeCalls, [
|
||||
"http://127.0.0.1:9999",
|
||||
"http://127.0.0.1:9999",
|
||||
@@ -396,10 +374,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
close: () => Effect.void,
|
||||
};
|
||||
|
||||
const adapterLayer = makeOpenCodeAdapterLive({
|
||||
nativeEventLogger,
|
||||
}).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
const adapterLayer = makeOpenCodeAdapterLive({ nativeEventLogger }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
@@ -475,10 +450,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
close: () => Effect.void,
|
||||
};
|
||||
|
||||
const adapterLayer = makeOpenCodeAdapterLive({
|
||||
nativeEventLogger,
|
||||
}).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
const adapterLayer = makeOpenCodeAdapterLive({ nativeEventLogger }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
@@ -495,13 +467,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
// Capture closeCalls *inside* the provided layer scope: the adapter's
|
||||
// layer finalizer now tears down any live sessions when the layer
|
||||
// closes (which is exactly what we want for leak prevention), so
|
||||
// inspecting closeCalls after `Effect.provide` completes would observe
|
||||
// the teardown — not the behavior under test. We care that the event
|
||||
// pump kept the session alive while logging was failing.
|
||||
const { sessions, closeCallsDuringRun } = yield* Effect.gen(function* () {
|
||||
const sessions = yield* Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
@@ -509,15 +475,12 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* sleep(10);
|
||||
return {
|
||||
sessions: yield* adapter.listSessions(),
|
||||
closeCallsDuringRun: [...runtimeMock.state.closeCalls],
|
||||
};
|
||||
return yield* adapter.listSessions();
|
||||
}).pipe(Effect.provide(adapterLayer));
|
||||
|
||||
assert.equal(sessions.length, 1);
|
||||
assert.equal(sessions[0]?.threadId, "thread-native-log-failure");
|
||||
assert.deepEqual(closeCallsDuringRun, []);
|
||||
assert.deepEqual(runtimeMock.state.closeCalls, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,85 +3,66 @@ import assert from "node:assert/strict";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { beforeEach } from "vitest";
|
||||
import { beforeEach, vi } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
type OpenCodeRuntimeShape,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import { OpenCodeProviderLive } from "./OpenCodeProvider.ts";
|
||||
import type { OpenCodeInventory } from "../opencodeRuntime.ts";
|
||||
import { makeOpenCodeProviderLive } from "./OpenCodeProvider.ts";
|
||||
|
||||
const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\n";
|
||||
|
||||
const runtimeMock = {
|
||||
state: {
|
||||
const runtimeMock = vi.hoisted(() => {
|
||||
const state = {
|
||||
runVersionError: null as Error | null,
|
||||
versionStdout: DEFAULT_VERSION_STDOUT,
|
||||
inventoryError: null as Error | null,
|
||||
inventory: {
|
||||
providerList: { connected: [] as string[], all: [] as unknown[], default: {} },
|
||||
agents: [] as unknown[],
|
||||
} as unknown,
|
||||
},
|
||||
reset() {
|
||||
this.state.runVersionError = null;
|
||||
this.state.versionStdout = DEFAULT_VERSION_STDOUT;
|
||||
this.state.inventoryError = null;
|
||||
this.state.inventory = {
|
||||
providerList: { connected: [], all: [] as unknown[], default: {} },
|
||||
agents: [] as unknown[],
|
||||
};
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: () =>
|
||||
Effect.succeed({
|
||||
url: "http://127.0.0.1:4301",
|
||||
exitCode: Effect.never,
|
||||
return {
|
||||
state,
|
||||
reset() {
|
||||
state.runVersionError = null;
|
||||
state.inventoryError = null;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../opencodeRuntime.ts", async () => {
|
||||
const actual =
|
||||
await vi.importActual<typeof import("../opencodeRuntime.ts")>("../opencodeRuntime.ts");
|
||||
|
||||
return {
|
||||
...actual,
|
||||
runOpenCodeCommand: vi.fn(async () => {
|
||||
if (runtimeMock.state.runVersionError) {
|
||||
throw runtimeMock.state.runVersionError;
|
||||
}
|
||||
return { stdout: "opencode 1.0.0\n", stderr: "", code: 0 };
|
||||
}),
|
||||
connectToOpenCodeServer: ({ serverUrl }) =>
|
||||
Effect.succeed({
|
||||
connectToOpenCodeServer: vi.fn(async ({ serverUrl }: { serverUrl?: string }) => ({
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
exitCode: null,
|
||||
process: null,
|
||||
external: Boolean(serverUrl),
|
||||
close() {},
|
||||
})),
|
||||
createOpenCodeSdkClient: vi.fn(() => ({})),
|
||||
loadOpenCodeInventory: vi.fn(async () => {
|
||||
if (runtimeMock.state.inventoryError) {
|
||||
throw runtimeMock.state.inventoryError;
|
||||
}
|
||||
return {
|
||||
providerList: { connected: [], all: [] },
|
||||
agents: [],
|
||||
};
|
||||
}),
|
||||
runOpenCodeCommand: () =>
|
||||
runtimeMock.state.runVersionError
|
||||
? Effect.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "runOpenCodeCommand",
|
||||
detail: runtimeMock.state.runVersionError.message,
|
||||
cause: runtimeMock.state.runVersionError,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }),
|
||||
createOpenCodeSdkClient: () =>
|
||||
({}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
|
||||
loadOpenCodeInventory: () =>
|
||||
runtimeMock.state.inventoryError
|
||||
? Effect.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "loadOpenCodeInventory",
|
||||
detail: runtimeMock.state.inventoryError.message,
|
||||
cause: runtimeMock.state.inventoryError,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory),
|
||||
};
|
||||
flattenOpenCodeModels: vi.fn(() => []),
|
||||
};
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
runtimeMock.reset();
|
||||
});
|
||||
|
||||
const makeTestLayer = (settingsOverrides?: Parameters<typeof ServerSettingsService.layerTest>[0]) =>
|
||||
OpenCodeProviderLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
makeOpenCodeProviderLive().pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest(settingsOverrides)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -111,83 +92,6 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {
|
||||
assert.equal(snapshot.message, "Failed to execute OpenCode CLI health check.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses to probe when opencode is older than the required minimum", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.versionStdout = "opencode 1.4.7\n";
|
||||
const provider = yield* OpenCodeProvider;
|
||||
const snapshot = yield* provider.refresh;
|
||||
|
||||
assert.equal(snapshot.status, "error");
|
||||
assert.equal(snapshot.installed, true);
|
||||
assert.equal(snapshot.version, "1.4.7");
|
||||
assert.ok(snapshot.message?.includes("1.14.19"));
|
||||
assert.ok(snapshot.message?.toLowerCase().includes("upgrade"));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses to probe when opencode --version output is unparseable", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.versionStdout = "garbled binary output\n";
|
||||
const provider = yield* OpenCodeProvider;
|
||||
const snapshot = yield* provider.refresh;
|
||||
|
||||
assert.equal(snapshot.status, "error");
|
||||
assert.equal(snapshot.installed, true);
|
||||
assert.equal(snapshot.version, null);
|
||||
assert.ok(snapshot.message?.includes("1.14.19"));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("emits OpenCode variant defaults so trait picker can resolve a visible selection", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.inventory = {
|
||||
providerList: {
|
||||
connected: ["openai"],
|
||||
all: [
|
||||
{
|
||||
id: "openai",
|
||||
name: "OpenAI",
|
||||
models: {
|
||||
"gpt-5.4": {
|
||||
id: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
variants: {
|
||||
none: {},
|
||||
low: {},
|
||||
medium: {},
|
||||
high: {},
|
||||
xhigh: {},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
default: {},
|
||||
},
|
||||
agents: [
|
||||
{ name: "build", hidden: false, mode: "primary" },
|
||||
{ name: "plan", hidden: false, mode: "primary" },
|
||||
],
|
||||
};
|
||||
|
||||
const provider = yield* OpenCodeProvider;
|
||||
const snapshot = yield* provider.refresh;
|
||||
const model = snapshot.models.find((entry) => entry.slug === "openai/gpt-5.4");
|
||||
|
||||
assert.ok(model);
|
||||
const variantDescriptor = model.capabilities?.optionDescriptors?.find(
|
||||
(descriptor) => descriptor.id === "variant" && descriptor.type === "select",
|
||||
);
|
||||
assert.ok(variantDescriptor && variantDescriptor.type === "select");
|
||||
assert.equal(variantDescriptor.options.find((option) => option.isDefault)?.id, "medium");
|
||||
const agentDescriptor = model.capabilities?.optionDescriptors?.find(
|
||||
(descriptor) => descriptor.id === "agent" && descriptor.type === "select",
|
||||
);
|
||||
assert.ok(agentDescriptor && agentDescriptor.type === "select");
|
||||
assert.equal(agentDescriptor.options.find((option) => option.isDefault)?.id, "build");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(
|
||||
|
||||
@@ -1,67 +1,57 @@
|
||||
import type {
|
||||
ModelCapabilities,
|
||||
OpenCodeSettings,
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause, Data, Effect, Equal, Layer, Stream } from "effect";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import type { OpenCodeSettings, ServerProvider } from "@t3tools/contracts";
|
||||
import { Cause, Effect, Equal, Layer, Stream } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
buildServerProvider,
|
||||
nonEmptyTrimmed,
|
||||
isCommandMissingCause,
|
||||
parseGenericCliVersion,
|
||||
providerModelsFromSettings,
|
||||
} from "../providerSnapshot.ts";
|
||||
import { compareCliVersions } from "../cliVersion.ts";
|
||||
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
openCodeRuntimeErrorDetail,
|
||||
type OpenCodeInventory,
|
||||
connectToOpenCodeServer,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
createOpenCodeSdkClient,
|
||||
flattenOpenCodeModels,
|
||||
loadOpenCodeInventory,
|
||||
runOpenCodeCommand,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
|
||||
|
||||
const PROVIDER = "opencode" as const;
|
||||
const OPENCODE_PRESENTATION = {
|
||||
displayName: "OpenCode",
|
||||
showInteractionModeToggle: false,
|
||||
} as const;
|
||||
const MINIMUM_OPENCODE_VERSION = "1.14.19";
|
||||
|
||||
class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{
|
||||
readonly cause: unknown;
|
||||
readonly detail: string;
|
||||
}> {}
|
||||
class OpenCodeProbePromiseError extends Error {
|
||||
override readonly cause: unknown;
|
||||
|
||||
function normalizeProbeMessage(message: string): string | undefined {
|
||||
const trimmed = message.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return undefined;
|
||||
constructor(cause: unknown) {
|
||||
super(cause instanceof Error ? cause.message : String(cause));
|
||||
this.cause = cause;
|
||||
this.name = "OpenCodeProbePromiseError";
|
||||
}
|
||||
if (
|
||||
trimmed === "An error occurred in Effect.tryPromise" ||
|
||||
trimmed === "An error occurred in Effect.try"
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function toOpenCodeProbeError(cause: unknown): OpenCodeProbePromiseError {
|
||||
return new OpenCodeProbePromiseError(cause);
|
||||
}
|
||||
|
||||
function normalizedErrorMessage(cause: unknown): string | undefined {
|
||||
if (cause instanceof OpenCodeProbeError) {
|
||||
return normalizeProbeMessage(cause.detail);
|
||||
}
|
||||
|
||||
if (!(cause instanceof Error)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return normalizeProbeMessage(cause.message);
|
||||
const message = cause.message.trim();
|
||||
if (message.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
message === "An error occurred in Effect.tryPromise" ||
|
||||
message === "An error occurred in Effect.try"
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
function formatOpenCodeProbeError(input: {
|
||||
@@ -69,8 +59,8 @@ function formatOpenCodeProbeError(input: {
|
||||
readonly isExternalServer: boolean;
|
||||
readonly serverUrl: string;
|
||||
}): { readonly installed: boolean; readonly message: string } {
|
||||
const lower = input.cause instanceof Error ? input.cause.message.toLowerCase() : "";
|
||||
const detail = normalizedErrorMessage(input.cause);
|
||||
const lower = detail?.toLowerCase() ?? "";
|
||||
|
||||
if (input.isExternalServer) {
|
||||
if (
|
||||
@@ -106,7 +96,7 @@ function formatOpenCodeProbeError(input: {
|
||||
};
|
||||
}
|
||||
|
||||
if (lower.includes("enoent") || lower.includes("notfound")) {
|
||||
if (input.cause instanceof Error && isCommandMissingCause(input.cause)) {
|
||||
return {
|
||||
installed: false,
|
||||
message: "OpenCode CLI (`opencode`) is not installed or not on PATH.",
|
||||
@@ -137,120 +127,6 @@ function formatOpenCodeProbeError(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function titleCaseSlug(value: string): string {
|
||||
return value
|
||||
.split(/[-_/]+/)
|
||||
.filter((segment) => segment.length > 0)
|
||||
.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function inferDefaultVariant(
|
||||
providerID: string,
|
||||
variants: ReadonlyArray<string>,
|
||||
): string | undefined {
|
||||
if (variants.length === 1) {
|
||||
return variants[0];
|
||||
}
|
||||
if (providerID === "anthropic" || providerID.startsWith("google")) {
|
||||
return variants.includes("high") ? "high" : undefined;
|
||||
}
|
||||
if (providerID === "openai" || providerID === "opencode") {
|
||||
return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function inferDefaultAgent(agents: ReadonlyArray<Agent>): string | undefined {
|
||||
return agents.find((agent) => agent.name === "build")?.name ?? agents[0]?.name ?? undefined;
|
||||
}
|
||||
|
||||
const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [],
|
||||
});
|
||||
|
||||
function openCodeCapabilitiesForModel(input: {
|
||||
readonly providerID: string;
|
||||
readonly model: ProviderListResponse["all"][number]["models"][string];
|
||||
readonly agents: ReadonlyArray<Agent>;
|
||||
}): ModelCapabilities {
|
||||
const variantValues = Object.keys(input.model.variants ?? {});
|
||||
const defaultVariant = inferDefaultVariant(input.providerID, variantValues);
|
||||
const variantOptions = variantValues.map((value) =>
|
||||
defaultVariant === value
|
||||
? { id: value, label: titleCaseSlug(value), isDefault: true as const }
|
||||
: { id: value, label: titleCaseSlug(value) },
|
||||
);
|
||||
const primaryAgents = input.agents.filter(
|
||||
(agent) => !agent.hidden && (agent.mode === "primary" || agent.mode === "all"),
|
||||
);
|
||||
const defaultAgent = inferDefaultAgent(primaryAgents);
|
||||
const agentOptions = primaryAgents.map((agent) =>
|
||||
defaultAgent === agent.name
|
||||
? { id: agent.name, label: titleCaseSlug(agent.name), isDefault: true as const }
|
||||
: { id: agent.name, label: titleCaseSlug(agent.name) },
|
||||
);
|
||||
return createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
...(variantOptions.length > 0
|
||||
? [
|
||||
{
|
||||
id: "variant",
|
||||
label: "Variant",
|
||||
type: "select" as const,
|
||||
options: variantOptions,
|
||||
...(defaultVariant ? { currentValue: defaultVariant } : {}),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(agentOptions.length > 0
|
||||
? [
|
||||
{
|
||||
id: "agent",
|
||||
label: "Agent",
|
||||
type: "select" as const,
|
||||
options: agentOptions,
|
||||
...(defaultAgent ? { currentValue: defaultAgent } : {}),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray<ServerProviderModel> {
|
||||
const connected = new Set(input.providerList.connected);
|
||||
const models: Array<ServerProviderModel> = [];
|
||||
|
||||
for (const provider of input.providerList.all) {
|
||||
if (!connected.has(provider.id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const model of Object.values(provider.models)) {
|
||||
const name = nonEmptyTrimmed(model.name);
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const subProvider = nonEmptyTrimmed(provider.name);
|
||||
models.push({
|
||||
slug: `${provider.id}/${model.id}`,
|
||||
name,
|
||||
...(subProvider ? { subProvider } : {}),
|
||||
isCustom: false,
|
||||
capabilities: openCodeCapabilitiesForModel({
|
||||
providerID: provider.id,
|
||||
model,
|
||||
agents: input.agents,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return models.toSorted((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
|
||||
const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): ServerProvider => {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
@@ -263,7 +139,6 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server
|
||||
if (!openCodeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: OPENCODE_PRESENTATION,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
@@ -282,7 +157,6 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server
|
||||
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: OPENCODE_PRESENTATION,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
@@ -296,210 +170,173 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server
|
||||
});
|
||||
};
|
||||
|
||||
export const OpenCodeProviderLive = Layer.effect(
|
||||
OpenCodeProvider,
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
export function checkOpenCodeProviderStatus(input: {
|
||||
readonly settings: OpenCodeSettings;
|
||||
readonly cwd: string;
|
||||
}): Effect.Effect<ServerProvider> {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const customModels = input.settings.customModels;
|
||||
const isExternalServer = input.settings.serverUrl.trim().length > 0;
|
||||
|
||||
const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (input: {
|
||||
readonly settings: OpenCodeSettings;
|
||||
readonly cwd: string;
|
||||
}): Effect.fn.Return<ServerProvider, never> {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const customModels = input.settings.customModels;
|
||||
const isExternalServer = input.settings.serverUrl.trim().length > 0;
|
||||
|
||||
const fallback = (cause: unknown, version: string | null = null) => {
|
||||
const failure = formatOpenCodeProbeError({
|
||||
cause,
|
||||
isExternalServer,
|
||||
serverUrl: input.settings.serverUrl,
|
||||
});
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: OPENCODE_PRESENTATION,
|
||||
enabled: input.settings.enabled,
|
||||
checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
[],
|
||||
PROVIDER,
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
),
|
||||
probe: {
|
||||
installed: failure.installed,
|
||||
version,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: failure.message,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
if (!input.settings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: OPENCODE_PRESENTATION,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
[],
|
||||
PROVIDER,
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
),
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: isExternalServer
|
||||
? "OpenCode is disabled in T3 Code settings. A server URL is configured."
|
||||
: "OpenCode is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
let version: string | null = null;
|
||||
if (!isExternalServer) {
|
||||
const versionExit = yield* Effect.exit(
|
||||
openCodeRuntime
|
||||
.runOpenCodeCommand({
|
||||
binaryPath: input.settings.binaryPath,
|
||||
args: ["--version"],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (versionExit._tag === "Failure") {
|
||||
return fallback(Cause.squash(versionExit.cause));
|
||||
}
|
||||
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
|
||||
|
||||
if (!version) {
|
||||
return fallback(
|
||||
new Error(
|
||||
`Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
|
||||
),
|
||||
null,
|
||||
);
|
||||
}
|
||||
if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: OPENCODE_PRESENTATION,
|
||||
enabled: input.settings.enabled,
|
||||
checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
[],
|
||||
PROVIDER,
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
),
|
||||
probe: {
|
||||
installed: true,
|
||||
version,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const inventoryExit = yield* Effect.exit(
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* openCodeRuntime
|
||||
.connectToOpenCodeServer({
|
||||
binaryPath: input.settings.binaryPath,
|
||||
serverUrl: input.settings.serverUrl,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
);
|
||||
return yield* openCodeRuntime
|
||||
.loadOpenCodeInventory(
|
||||
openCodeRuntime.createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: input.cwd,
|
||||
...(isExternalServer && input.settings.serverPassword
|
||||
? { serverPassword: input.settings.serverPassword }
|
||||
: {}),
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (inventoryExit._tag === "Failure") {
|
||||
return fallback(Cause.squash(inventoryExit.cause), version);
|
||||
}
|
||||
|
||||
const models = providerModelsFromSettings(
|
||||
flattenOpenCodeModels(inventoryExit.value),
|
||||
const fallback = (cause: unknown, version: string | null = null) => {
|
||||
const failure = formatOpenCodeProbeError({
|
||||
cause,
|
||||
isExternalServer,
|
||||
serverUrl: input.settings.serverUrl,
|
||||
});
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: input.settings.enabled,
|
||||
checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
[],
|
||||
PROVIDER,
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
);
|
||||
const connectedCount = inventoryExit.value.providerList.connected.length;
|
||||
),
|
||||
probe: {
|
||||
installed: failure.installed,
|
||||
version,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: failure.message,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
if (!input.settings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
presentation: OPENCODE_PRESENTATION,
|
||||
enabled: true,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
models: providerModelsFromSettings(
|
||||
[],
|
||||
PROVIDER,
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
),
|
||||
probe: {
|
||||
installed: true,
|
||||
version,
|
||||
status: connectedCount > 0 ? "ready" : "warning",
|
||||
auth: {
|
||||
status: connectedCount > 0 ? "authenticated" : "unknown",
|
||||
type: "opencode",
|
||||
},
|
||||
message:
|
||||
connectedCount > 0
|
||||
? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
|
||||
: isExternalServer
|
||||
? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
|
||||
: "OpenCode is available, but it did not report any connected upstream providers.",
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: isExternalServer
|
||||
? "OpenCode is disabled in T3 Code settings. A server URL is configured."
|
||||
: "OpenCode is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const getProviderSettings = serverSettings.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.opencode),
|
||||
);
|
||||
let version: string | null = null;
|
||||
if (!isExternalServer) {
|
||||
const versionExit = yield* Effect.exit(
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
runOpenCodeCommand({
|
||||
binaryPath: input.settings.binaryPath,
|
||||
args: ["--version"],
|
||||
}),
|
||||
catch: toOpenCodeProbeError,
|
||||
}),
|
||||
);
|
||||
if (versionExit._tag === "Failure") {
|
||||
return fallback(Cause.squash(versionExit.cause));
|
||||
}
|
||||
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
|
||||
}
|
||||
|
||||
return yield* makeManagedServerProvider<OpenCodeSettings>({
|
||||
getSettings: getProviderSettings.pipe(Effect.orDie),
|
||||
streamSettings: serverSettings.streamChanges.pipe(
|
||||
Stream.map((settings) => settings.providers.opencode),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
initialSnapshot: makePendingOpenCodeProvider,
|
||||
checkProvider: getProviderSettings.pipe(
|
||||
Effect.flatMap((settings) =>
|
||||
checkOpenCodeProviderStatus({
|
||||
settings,
|
||||
cwd: serverConfig.cwd,
|
||||
const inventoryExit = yield* Effect.exit(
|
||||
Effect.acquireUseRelease(
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
connectToOpenCodeServer({
|
||||
binaryPath: input.settings.binaryPath,
|
||||
serverUrl: input.settings.serverUrl,
|
||||
}),
|
||||
catch: toOpenCodeProbeError,
|
||||
}),
|
||||
(server) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const client = createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: input.cwd,
|
||||
...(isExternalServer && input.settings.serverPassword
|
||||
? { serverPassword: input.settings.serverPassword }
|
||||
: {}),
|
||||
});
|
||||
return await loadOpenCodeInventory(client);
|
||||
},
|
||||
catch: toOpenCodeProbeError,
|
||||
}),
|
||||
),
|
||||
(server) => Effect.sync(() => server.close()),
|
||||
),
|
||||
);
|
||||
if (inventoryExit._tag === "Failure") {
|
||||
return fallback(Cause.squash(inventoryExit.cause), version);
|
||||
}
|
||||
|
||||
const models = providerModelsFromSettings(
|
||||
flattenOpenCodeModels(inventoryExit.value),
|
||||
PROVIDER,
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
);
|
||||
const connectedCount = inventoryExit.value.providerList.connected.length;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version,
|
||||
status: connectedCount > 0 ? "ready" : "warning",
|
||||
auth: {
|
||||
status: connectedCount > 0 ? "authenticated" : "unknown",
|
||||
type: "opencode",
|
||||
},
|
||||
message:
|
||||
connectedCount > 0
|
||||
? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
|
||||
: isExternalServer
|
||||
? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
|
||||
: "OpenCode is available, but it did not report any connected upstream providers.",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function makeOpenCodeProviderLive() {
|
||||
return Layer.effect(
|
||||
OpenCodeProvider,
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
|
||||
const getProviderSettings = serverSettings.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.opencode),
|
||||
);
|
||||
|
||||
return yield* makeManagedServerProvider<OpenCodeSettings>({
|
||||
getSettings: getProviderSettings.pipe(Effect.orDie),
|
||||
streamSettings: serverSettings.streamChanges.pipe(
|
||||
Stream.map((settings) => settings.providers.opencode),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
initialSnapshot: makePendingOpenCodeProvider,
|
||||
checkProvider: getProviderSettings.pipe(
|
||||
Effect.flatMap((settings) =>
|
||||
checkOpenCodeProviderStatus({
|
||||
settings,
|
||||
cwd: serverConfig.cwd,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const OpenCodeProviderLive = makeOpenCodeProviderLive();
|
||||
@@ -19,7 +19,6 @@ import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import { CursorAdapter } from "../Services/CursorAdapter.ts";
|
||||
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
|
||||
import { createBuiltInAdapterList } from "../builtInProviderCatalog.ts";
|
||||
|
||||
export interface ProviderAdapterRegistryLiveOptions {
|
||||
readonly adapters?: ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>>;
|
||||
@@ -32,12 +31,12 @@ const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(fun
|
||||
const adapters =
|
||||
options?.adapters !== undefined
|
||||
? options.adapters
|
||||
: createBuiltInAdapterList({
|
||||
codex: yield* CodexAdapter,
|
||||
claudeAgent: yield* ClaudeAdapter,
|
||||
opencode: yield* OpenCodeAdapter,
|
||||
...(cursorAdapterOption._tag === "Some" ? { cursor: cursorAdapterOption.value } : {}),
|
||||
});
|
||||
: [
|
||||
yield* CodexAdapter,
|
||||
yield* ClaudeAdapter,
|
||||
yield* OpenCodeAdapter,
|
||||
...(cursorAdapterOption._tag === "Some" ? [cursorAdapterOption.value] : []),
|
||||
];
|
||||
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
|
||||
|
||||
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -16,7 +16,6 @@ import { CodexProvider } from "../Services/CodexProvider.ts";
|
||||
import { CursorProvider } from "../Services/CursorProvider.ts";
|
||||
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";
|
||||
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
import {
|
||||
hydrateCachedProvider,
|
||||
PROVIDER_CACHE_IDS,
|
||||
@@ -25,8 +24,13 @@ import {
|
||||
resolveProviderStatusCachePath,
|
||||
writeProviderStatusCache,
|
||||
} from "../providerStatusCache.ts";
|
||||
import { createBuiltInProviderSources } from "../builtInProviderCatalog.ts";
|
||||
import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts";
|
||||
|
||||
type ProviderSnapshotSource = {
|
||||
readonly provider: ProviderKind;
|
||||
readonly getSnapshot: Effect.Effect<ServerProvider>;
|
||||
readonly refresh: Effect.Effect<ServerProvider>;
|
||||
readonly streamChanges: Stream.Stream<ServerProvider>;
|
||||
};
|
||||
|
||||
const loadProviders = (
|
||||
providerSources: ReadonlyArray<ProviderSnapshotSource>,
|
||||
@@ -36,7 +40,11 @@ const loadProviders = (
|
||||
});
|
||||
|
||||
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
|
||||
(model.capabilities?.optionDescriptors?.length ?? 0) > 0;
|
||||
(model.capabilities?.reasoningEffortLevels.length ?? 0) > 0 ||
|
||||
model.capabilities?.supportsFastMode === true ||
|
||||
model.capabilities?.supportsThinkingToggle === true ||
|
||||
(model.capabilities?.contextWindowOptions.length ?? 0) > 0 ||
|
||||
(model.capabilities?.promptInjectedEffortLevels.length ?? 0) > 0;
|
||||
|
||||
const mergeProviderModels = (
|
||||
previousModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
@@ -89,12 +97,32 @@ const ProviderRegistryLiveBase = Layer.effect(
|
||||
|
||||
const cursorProvider = yield* CursorProvider;
|
||||
|
||||
const providerSources = createBuiltInProviderSources({
|
||||
codex: codexProvider,
|
||||
claudeAgent: claudeProvider,
|
||||
opencode: openCodeProvider,
|
||||
cursor: cursorProvider,
|
||||
}) satisfies ReadonlyArray<ProviderSnapshotSource>;
|
||||
const providerSources = [
|
||||
{
|
||||
provider: "codex",
|
||||
getSnapshot: codexProvider.getSnapshot,
|
||||
refresh: codexProvider.refresh,
|
||||
streamChanges: codexProvider.streamChanges,
|
||||
},
|
||||
{
|
||||
provider: "claudeAgent",
|
||||
getSnapshot: claudeProvider.getSnapshot,
|
||||
refresh: claudeProvider.refresh,
|
||||
streamChanges: claudeProvider.streamChanges,
|
||||
},
|
||||
{
|
||||
provider: "opencode",
|
||||
getSnapshot: openCodeProvider.getSnapshot,
|
||||
refresh: openCodeProvider.refresh,
|
||||
streamChanges: openCodeProvider.streamChanges,
|
||||
},
|
||||
{
|
||||
provider: "cursor",
|
||||
getSnapshot: cursorProvider.getSnapshot,
|
||||
refresh: cursorProvider.refresh,
|
||||
streamChanges: cursorProvider.streamChanges,
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderSnapshotSource>;
|
||||
const activeProviders = PROVIDER_CACHE_IDS;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
|
||||
@@ -259,7 +287,6 @@ export const ProviderRegistryLive = Layer.unwrap(
|
||||
Layer.provideMerge(CodexProviderLive),
|
||||
Layer.provideMerge(ClaudeProviderLive),
|
||||
Layer.provideMerge(OpenCodeProviderLive),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { it, assert, vi } from "@effect/vitest";
|
||||
|
||||
import { Effect, Fiber, Layer, Metric, Option, PubSub, Ref, Stream } from "effect";
|
||||
@@ -861,9 +860,13 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
provider: "claudeAgent",
|
||||
threadId: asThreadId("thread-claude-send-turn"),
|
||||
cwd: "/tmp/project-claude-send-turn",
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||
{ id: "effort", value: "max" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
@@ -890,10 +893,13 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
};
|
||||
assert.equal(startPayload.provider, "claudeAgent");
|
||||
assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn");
|
||||
assert.deepEqual(
|
||||
startPayload.modelSelection,
|
||||
createModelSelection("claudeAgent", "claude-opus-4-6", [{ id: "effort", value: "max" }]),
|
||||
);
|
||||
assert.deepEqual(startPayload.modelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);
|
||||
assert.equal(startPayload.threadId, initial.threadId);
|
||||
}
|
||||
|
||||
@@ -99,11 +99,11 @@ describe("applyCursorAcpModelSelection", () => {
|
||||
applyCursorAcpModelSelection({
|
||||
runtime,
|
||||
model: "gpt-5.4-medium-fast[reasoning=medium,context=272k]",
|
||||
selections: [
|
||||
{ id: "reasoning", value: "xhigh" },
|
||||
{ id: "contextWindow", value: "1m" },
|
||||
{ id: "fastMode", value: true },
|
||||
],
|
||||
modelOptions: {
|
||||
reasoning: "xhigh",
|
||||
contextWindow: "1m",
|
||||
fastMode: true,
|
||||
},
|
||||
mapError: ({ step, configId, cause }) =>
|
||||
new Error(
|
||||
step === "set-config-option"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type CursorSettings, type ProviderOptionSelection } from "@t3tools/contracts";
|
||||
import { type CursorModelOptions, type CursorSettings } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Scope } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import type * as EffectAcpErrors from "effect-acp/errors";
|
||||
@@ -76,7 +76,7 @@ interface CursorAcpModelSelectionRuntime {
|
||||
export function applyCursorAcpModelSelection<E>(input: {
|
||||
readonly runtime: CursorAcpModelSelectionRuntime;
|
||||
readonly model: string | null | undefined;
|
||||
readonly selections: ReadonlyArray<ProviderOptionSelection> | null | undefined;
|
||||
readonly modelOptions: CursorModelOptions | null | undefined;
|
||||
readonly mapError: (context: CursorAcpModelSelectionErrorContext) => E;
|
||||
}): Effect.Effect<void, E> {
|
||||
return Effect.gen(function* () {
|
||||
@@ -91,7 +91,7 @@ export function applyCursorAcpModelSelection<E>(input: {
|
||||
|
||||
const configUpdates = resolveCursorAcpConfigUpdates(
|
||||
yield* input.runtime.getConfigOptions,
|
||||
input.selections,
|
||||
input.modelOptions,
|
||||
);
|
||||
for (const update of configUpdates) {
|
||||
yield* input.runtime.setConfigOption(update.configId, update.value).pipe(
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import type { ProviderKind, ServerProvider } from "@t3tools/contracts";
|
||||
import type { Stream } from "effect";
|
||||
import type { ProviderAdapterError } from "./Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
|
||||
import type { ServerProviderShape } from "./Services/ServerProvider.ts";
|
||||
|
||||
export type ProviderSnapshotSource = {
|
||||
readonly provider: ProviderKind;
|
||||
readonly getSnapshot: ServerProviderShape["getSnapshot"];
|
||||
readonly refresh: ServerProviderShape["refresh"];
|
||||
readonly streamChanges: Stream.Stream<ServerProvider>;
|
||||
};
|
||||
|
||||
type BuiltInProviderServiceMap = Record<ProviderKind, ServerProviderShape>;
|
||||
type BuiltInAdapterMap = {
|
||||
readonly codex: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly claudeAgent: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly opencode: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly cursor?: ProviderAdapterShape<ProviderAdapterError>;
|
||||
};
|
||||
|
||||
export const BUILT_IN_PROVIDER_ORDER = [
|
||||
"codex",
|
||||
"claudeAgent",
|
||||
"opencode",
|
||||
"cursor",
|
||||
] as const satisfies ReadonlyArray<ProviderKind>;
|
||||
|
||||
export function createBuiltInProviderSources(
|
||||
services: BuiltInProviderServiceMap,
|
||||
): ReadonlyArray<ProviderSnapshotSource> {
|
||||
return BUILT_IN_PROVIDER_ORDER.map((provider) => ({
|
||||
provider,
|
||||
getSnapshot: services[provider].getSnapshot,
|
||||
refresh: services[provider].refresh,
|
||||
streamChanges: services[provider].streamChanges,
|
||||
}));
|
||||
}
|
||||
|
||||
export function createBuiltInAdapterList(
|
||||
adapters: BuiltInAdapterMap,
|
||||
): ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>> {
|
||||
return [
|
||||
adapters.codex,
|
||||
adapters.claudeAgent,
|
||||
adapters.opencode,
|
||||
...(adapters.cursor ? [adapters.cursor] : []),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { ServerProviderModel } from "@t3tools/contracts";
|
||||
|
||||
export type CodexPlanType =
|
||||
| "free"
|
||||
| "go"
|
||||
| "plus"
|
||||
| "pro"
|
||||
| "team"
|
||||
| "business"
|
||||
| "enterprise"
|
||||
| "edu"
|
||||
| "unknown";
|
||||
|
||||
export interface CodexAccountSnapshot {
|
||||
readonly type: "apiKey" | "chatgpt" | "unknown";
|
||||
readonly planType: CodexPlanType | null;
|
||||
readonly sparkEnabled: boolean;
|
||||
}
|
||||
|
||||
export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
|
||||
const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set<CodexPlanType>(["pro"]);
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
|
||||
const record = asObject(response);
|
||||
const account = asObject(record?.account) ?? record;
|
||||
const accountType = asString(account?.type);
|
||||
|
||||
if (accountType === "apiKey") {
|
||||
return {
|
||||
type: "apiKey",
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (accountType === "chatgpt") {
|
||||
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
|
||||
return {
|
||||
type: "chatgpt",
|
||||
planType,
|
||||
sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(planType),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: "unknown",
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function codexAuthSubType(account: CodexAccountSnapshot | undefined): string | undefined {
|
||||
if (account?.type === "apiKey") {
|
||||
return "apiKey";
|
||||
}
|
||||
|
||||
if (account?.type !== "chatgpt") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return account.planType && account.planType !== "unknown" ? account.planType : "chatgpt";
|
||||
}
|
||||
|
||||
export function codexAuthSubLabel(account: CodexAccountSnapshot | undefined): string | undefined {
|
||||
switch (codexAuthSubType(account)) {
|
||||
case "apiKey":
|
||||
return "OpenAI API Key";
|
||||
case "chatgpt":
|
||||
return "ChatGPT Subscription";
|
||||
case "free":
|
||||
return "ChatGPT Free Subscription";
|
||||
case "go":
|
||||
return "ChatGPT Go Subscription";
|
||||
case "plus":
|
||||
return "ChatGPT Plus Subscription";
|
||||
case "pro":
|
||||
return "ChatGPT Pro Subscription";
|
||||
case "team":
|
||||
return "ChatGPT Team Subscription";
|
||||
case "business":
|
||||
return "ChatGPT Business Subscription";
|
||||
case "enterprise":
|
||||
return "ChatGPT Enterprise Subscription";
|
||||
case "edu":
|
||||
return "ChatGPT Edu Subscription";
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function adjustCodexModelsForAccount(
|
||||
baseModels: ReadonlyArray<ServerProviderModel>,
|
||||
account: CodexAccountSnapshot | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
if (account?.sparkEnabled !== false) {
|
||||
return baseModels;
|
||||
}
|
||||
|
||||
return baseModels.filter((model) => model.isCustom || model.slug !== CODEX_SPARK_MODEL);
|
||||
}
|
||||
|
||||
export function resolveCodexModelForAccount(
|
||||
model: string | undefined,
|
||||
account: CodexAccountSnapshot,
|
||||
): string | undefined {
|
||||
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
|
||||
return model;
|
||||
}
|
||||
|
||||
return CODEX_DEFAULT_MODEL;
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import readline from "node:readline";
|
||||
import type { ServerProviderSkill } from "@t3tools/contracts";
|
||||
import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount.ts";
|
||||
|
||||
interface JsonRpcProbeResponse {
|
||||
readonly id?: unknown;
|
||||
readonly result?: unknown;
|
||||
readonly error?: {
|
||||
readonly message?: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CodexDiscoverySnapshot {
|
||||
readonly account: CodexAccountSnapshot;
|
||||
readonly skills: ReadonlyArray<ServerProviderSkill>;
|
||||
}
|
||||
|
||||
function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
|
||||
return typeof response.error?.message === "string" ? response.error.message : undefined;
|
||||
}
|
||||
|
||||
function readObject(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function readArray(value: unknown): ReadonlyArray<unknown> | undefined {
|
||||
return Array.isArray(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function readString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function nonEmptyTrimmed(value: unknown): string | undefined {
|
||||
const candidate = readString(value)?.trim();
|
||||
return candidate ? candidate : undefined;
|
||||
}
|
||||
|
||||
function parseCodexSkillsResult(result: unknown, cwd: string): ReadonlyArray<ServerProviderSkill> {
|
||||
const resultRecord = readObject(result);
|
||||
const dataBuckets = readArray(resultRecord?.data) ?? [];
|
||||
const matchingBucket = dataBuckets.find(
|
||||
(value) => nonEmptyTrimmed(readObject(value)?.cwd) === cwd,
|
||||
);
|
||||
const rawSkills =
|
||||
readArray(readObject(matchingBucket)?.skills) ?? readArray(resultRecord?.skills) ?? [];
|
||||
|
||||
return rawSkills.flatMap((value) => {
|
||||
const skill = readObject(value);
|
||||
const display = readObject(skill?.interface);
|
||||
const name = nonEmptyTrimmed(skill?.name);
|
||||
const path = nonEmptyTrimmed(skill?.path);
|
||||
if (!name || !path) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
name,
|
||||
path,
|
||||
enabled: skill?.enabled !== false,
|
||||
...(nonEmptyTrimmed(skill?.description)
|
||||
? { description: nonEmptyTrimmed(skill?.description) }
|
||||
: {}),
|
||||
...(nonEmptyTrimmed(skill?.scope) ? { scope: nonEmptyTrimmed(skill?.scope) } : {}),
|
||||
...(nonEmptyTrimmed(display?.displayName)
|
||||
? { displayName: nonEmptyTrimmed(display?.displayName) }
|
||||
: {}),
|
||||
...(nonEmptyTrimmed(skill?.shortDescription) || nonEmptyTrimmed(display?.shortDescription)
|
||||
? {
|
||||
shortDescription:
|
||||
nonEmptyTrimmed(skill?.shortDescription) ??
|
||||
nonEmptyTrimmed(display?.shortDescription),
|
||||
}
|
||||
: {}),
|
||||
} satisfies ServerProviderSkill,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export function buildCodexInitializeParams() {
|
||||
return {
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
title: "T3 Code Desktop",
|
||||
version: "0.1.0",
|
||||
},
|
||||
capabilities: {
|
||||
experimentalApi: true,
|
||||
},
|
||||
} as const;
|
||||
}
|
||||
|
||||
export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void {
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
} catch {
|
||||
// Fall through to direct kill when taskkill is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
child.kill();
|
||||
}
|
||||
|
||||
export async function probeCodexDiscovery(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly cwd: string;
|
||||
readonly signal?: AbortSignal;
|
||||
}): Promise<CodexDiscoverySnapshot> {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const child = spawn(input.binaryPath, ["app-server"], {
|
||||
env: {
|
||||
...process.env,
|
||||
...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
let completed = false;
|
||||
let account: CodexAccountSnapshot | undefined;
|
||||
let skills: ReadonlyArray<ServerProviderSkill> | undefined;
|
||||
|
||||
const cleanup = () => {
|
||||
output.removeAllListeners();
|
||||
output.close();
|
||||
child.removeAllListeners();
|
||||
if (!child.killed) {
|
||||
killCodexChildProcess(child);
|
||||
}
|
||||
};
|
||||
|
||||
const finish = (callback: () => void) => {
|
||||
if (completed) return;
|
||||
completed = true;
|
||||
cleanup();
|
||||
callback();
|
||||
};
|
||||
|
||||
const fail = (error: unknown) =>
|
||||
finish(() =>
|
||||
reject(
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error(`Codex discovery probe failed: ${String(error)}.`),
|
||||
),
|
||||
);
|
||||
|
||||
const maybeResolve = () => {
|
||||
if (account && skills !== undefined) {
|
||||
const resolvedAccount = account;
|
||||
const resolvedSkills = skills;
|
||||
finish(() => resolve({ account: resolvedAccount, skills: resolvedSkills }));
|
||||
}
|
||||
};
|
||||
|
||||
if (input.signal?.aborted) {
|
||||
fail(new Error("Codex discovery probe aborted."));
|
||||
return;
|
||||
}
|
||||
input.signal?.addEventListener("abort", () =>
|
||||
fail(new Error("Codex discovery probe aborted.")),
|
||||
);
|
||||
|
||||
const writeMessage = (message: unknown) => {
|
||||
if (!child.stdin.writable) {
|
||||
fail(new Error("Cannot write to codex app-server stdin."));
|
||||
return;
|
||||
}
|
||||
|
||||
child.stdin.write(`${JSON.stringify(message)}\n`);
|
||||
};
|
||||
|
||||
output.on("line", (line) => {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
fail(new Error("Received invalid JSON from codex app-server during discovery probe."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!parsed || typeof parsed !== "object") {
|
||||
return;
|
||||
}
|
||||
|
||||
const response = parsed as JsonRpcProbeResponse;
|
||||
if (response.id === 1) {
|
||||
const errorMessage = readErrorMessage(response);
|
||||
if (errorMessage) {
|
||||
fail(new Error(`initialize failed: ${errorMessage}`));
|
||||
return;
|
||||
}
|
||||
|
||||
writeMessage({ method: "initialized" });
|
||||
writeMessage({ id: 2, method: "skills/list", params: { cwds: [input.cwd] } });
|
||||
writeMessage({ id: 3, method: "account/read", params: {} });
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.id === 2) {
|
||||
const errorMessage = readErrorMessage(response);
|
||||
skills = errorMessage ? [] : parseCodexSkillsResult(response.result, input.cwd);
|
||||
maybeResolve();
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.id === 3) {
|
||||
const errorMessage = readErrorMessage(response);
|
||||
if (errorMessage) {
|
||||
fail(new Error(`account/read failed: ${errorMessage}`));
|
||||
return;
|
||||
}
|
||||
|
||||
account = readCodexAccountSnapshot(response.result);
|
||||
maybeResolve();
|
||||
}
|
||||
});
|
||||
|
||||
child.once("error", fail);
|
||||
child.once("exit", (code, signal) => {
|
||||
if (completed) return;
|
||||
fail(
|
||||
new Error(
|
||||
`codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
writeMessage({
|
||||
id: 1,
|
||||
method: "initialize",
|
||||
params: buildCodexInitializeParams(),
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { compareCliVersions, normalizeCliVersion } from "./cliVersion.ts";
|
||||
|
||||
const CODEX_VERSION_PATTERN = /\bv?(\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?)\b/;
|
||||
|
||||
export const MINIMUM_CODEX_CLI_VERSION = "0.37.0";
|
||||
|
||||
export const compareCodexCliVersions = compareCliVersions;
|
||||
|
||||
export function parseCodexCliVersion(output: string): string | null {
|
||||
const match = CODEX_VERSION_PATTERN.exec(output);
|
||||
if (!match?.[1]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeCliVersion(match[1]);
|
||||
}
|
||||
|
||||
export function isCodexCliVersionSupported(version: string): boolean {
|
||||
return compareCodexCliVersions(version, MINIMUM_CODEX_CLI_VERSION) >= 0;
|
||||
}
|
||||
|
||||
export function formatCodexCliUpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Codex CLI ${versionLabel} is too old for T3 Code. Upgrade to v${MINIMUM_CODEX_CLI_VERSION} or newer and restart T3 Code.`;
|
||||
}
|
||||
@@ -1,21 +1,9 @@
|
||||
import { describe, it, assert } from "@effect/vitest";
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { Deferred, Effect, Fiber, PubSub, Ref, Stream } from "effect";
|
||||
|
||||
import { makeManagedServerProvider } from "./makeManagedServerProvider.ts";
|
||||
|
||||
const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] });
|
||||
const fastModeCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
{
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
type: "boolean",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
interface TestSettings {
|
||||
readonly enabled: boolean;
|
||||
}
|
||||
@@ -55,7 +43,13 @@ const enrichedSnapshot: ServerProvider = {
|
||||
slug: "composer-2",
|
||||
name: "Composer 2",
|
||||
isCustom: false,
|
||||
capabilities: fastModeCapabilities,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -74,7 +68,13 @@ const enrichedSnapshotSecond: ServerProvider = {
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
capabilities: emptyCapabilities,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { describe, it, vi } from "vitest";
|
||||
|
||||
const childProcessMock = vi.hoisted(() => ({
|
||||
execFileSync: vi.fn((command: string, args: ReadonlyArray<string>) => {
|
||||
if (command === "which" && args[0] === "opencode") {
|
||||
return "/opt/homebrew/bin/opencode\n";
|
||||
}
|
||||
return "";
|
||||
}),
|
||||
spawn: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("node:child_process", () => childProcessMock);
|
||||
|
||||
describe("resolveOpenCodeBinaryPath", () => {
|
||||
it("returns absolute binary paths without PATH lookup", async () => {
|
||||
const { resolveOpenCodeBinaryPath } = await import("./opencodeRuntime.ts");
|
||||
|
||||
assert.equal(resolveOpenCodeBinaryPath("/usr/local/bin/opencode"), "/usr/local/bin/opencode");
|
||||
assert.equal(childProcessMock.execFileSync.mock.calls.length, 0);
|
||||
});
|
||||
|
||||
it("resolves command names through PATH", async () => {
|
||||
const { resolveOpenCodeBinaryPath } = await import("./opencodeRuntime.ts");
|
||||
|
||||
assert.equal(resolveOpenCodeBinaryPath("opencode"), "/opt/homebrew/bin/opencode");
|
||||
assert.deepEqual(childProcessMock.execFileSync.mock.calls[0], [
|
||||
"which",
|
||||
["opencode"],
|
||||
{
|
||||
encoding: "utf8",
|
||||
timeout: 3_000,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,17 @@
|
||||
import { execFileSync, spawn, type ChildProcess } from "node:child_process";
|
||||
import * as FS from "node:fs";
|
||||
import { createServer, type AddressInfo } from "node:net";
|
||||
import * as OS from "node:os";
|
||||
import * as Path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import type { ChatAttachment, ProviderApprovalDecision, RuntimeMode } from "@t3tools/contracts";
|
||||
import type {
|
||||
ChatAttachment,
|
||||
ModelCapabilities,
|
||||
ProviderApprovalDecision,
|
||||
RuntimeMode,
|
||||
ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
createOpencodeClient,
|
||||
type Agent,
|
||||
@@ -11,79 +22,40 @@ import {
|
||||
type QuestionAnswer,
|
||||
type QuestionRequest,
|
||||
} from "@opencode-ai/sdk/v2";
|
||||
import {
|
||||
Cause,
|
||||
Context,
|
||||
Data,
|
||||
Deferred,
|
||||
Effect,
|
||||
Exit,
|
||||
Fiber,
|
||||
Layer,
|
||||
Option,
|
||||
Predicate as P,
|
||||
Ref,
|
||||
Result,
|
||||
Scope,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { isWindowsCommandNotFound } from "../processRunner.ts";
|
||||
import { collectStreamAsString } from "./providerSnapshot.ts";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
|
||||
const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 5_000;
|
||||
const DEFAULT_HOSTNAME = "127.0.0.1";
|
||||
|
||||
const OPENAI_VARIANTS = ["none", "minimal", "low", "medium", "high", "xhigh"];
|
||||
const ANTHROPIC_VARIANTS = ["high", "max"];
|
||||
const GOOGLE_VARIANTS = ["low", "high"];
|
||||
|
||||
export const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
};
|
||||
|
||||
export interface OpenCodeServerProcess {
|
||||
readonly url: string;
|
||||
readonly exitCode: Effect.Effect<number, never>;
|
||||
readonly process: ChildProcess;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
export interface OpenCodeServerConnection {
|
||||
readonly url: string;
|
||||
readonly exitCode: Effect.Effect<number, never> | null;
|
||||
readonly process: ChildProcess | null;
|
||||
readonly external: boolean;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError";
|
||||
export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{
|
||||
readonly operation: string;
|
||||
readonly cause?: unknown;
|
||||
readonly detail: string;
|
||||
}> {
|
||||
static readonly is = (u: unknown): u is OpenCodeRuntimeError =>
|
||||
P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);
|
||||
function buildOpenCodeBasicAuthorizationHeader(password: string): string {
|
||||
return `Basic ${Buffer.from(`opencode:${password}`, "utf8").toString("base64")}`;
|
||||
}
|
||||
|
||||
export function openCodeRuntimeErrorDetail(cause: unknown): string {
|
||||
if (OpenCodeRuntimeError.is(cause)) return cause.detail;
|
||||
if (cause instanceof Error && cause.message.trim().length > 0) return cause.message.trim();
|
||||
if (cause && typeof cause === "object") {
|
||||
// SDK v2 throws { response, request, error? } shapes — extract what's useful
|
||||
const anyCause = cause as Record<string, unknown>;
|
||||
const status = (anyCause.response as { status?: number } | undefined)?.status;
|
||||
const body = anyCause.error ?? anyCause.data ?? anyCause.body;
|
||||
try {
|
||||
return `status=${status ?? "?"} body=${JSON.stringify(body ?? cause)}`;
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
}
|
||||
return String(cause);
|
||||
}
|
||||
|
||||
export const runOpenCodeSdk = <A>(
|
||||
operation: string,
|
||||
fn: () => Promise<A>,
|
||||
): Effect.Effect<A, OpenCodeRuntimeError> =>
|
||||
Effect.tryPromise({
|
||||
try: fn,
|
||||
catch: (cause) =>
|
||||
new OpenCodeRuntimeError({ operation, detail: openCodeRuntimeErrorDetail(cause), cause }),
|
||||
}).pipe(Effect.withSpan(`opencode.${operation}`));
|
||||
|
||||
export interface OpenCodeCommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
@@ -100,43 +72,12 @@ export interface ParsedOpenCodeModelSlug {
|
||||
readonly modelID: string;
|
||||
}
|
||||
|
||||
export interface OpenCodeRuntimeShape {
|
||||
/**
|
||||
* Spawns a local OpenCode server process. Its lifetime is bound to the caller's
|
||||
* `Scope.Scope` — the child is killed automatically when that scope closes.
|
||||
* Consumers that want a long-lived server must create and hold a scope explicitly
|
||||
* (see {@link Scope.make}) and close it when done.
|
||||
*/
|
||||
readonly startOpenCodeServerProcess: (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly port?: number;
|
||||
readonly hostname?: string;
|
||||
readonly timeoutMs?: number;
|
||||
}) => Effect.Effect<OpenCodeServerProcess, OpenCodeRuntimeError, Scope.Scope>;
|
||||
/**
|
||||
* Returns a handle to either an externally-managed OpenCode server (when
|
||||
* `serverUrl` is provided — no lifetime is attached to the caller's scope) or a
|
||||
* freshly spawned local server whose lifetime is bound to the caller's scope.
|
||||
*/
|
||||
readonly connectToOpenCodeServer: (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly serverUrl?: string | null;
|
||||
readonly port?: number;
|
||||
readonly hostname?: string;
|
||||
readonly timeoutMs?: number;
|
||||
}) => Effect.Effect<OpenCodeServerConnection, OpenCodeRuntimeError, Scope.Scope>;
|
||||
readonly runOpenCodeCommand: (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) => Effect.Effect<OpenCodeCommandResult, OpenCodeRuntimeError>;
|
||||
readonly createOpenCodeSdkClient: (input: {
|
||||
readonly baseUrl: string;
|
||||
readonly directory: string;
|
||||
readonly serverPassword?: string;
|
||||
}) => OpencodeClient;
|
||||
readonly loadOpenCodeInventory: (
|
||||
client: OpencodeClient,
|
||||
) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
|
||||
function titleCaseSlug(value: string): string {
|
||||
return value
|
||||
.split(/[-_/]+/)
|
||||
.filter((segment) => segment.length > 0)
|
||||
.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function parseServerUrlFromOutput(output: string): string | null {
|
||||
@@ -150,6 +91,92 @@ function parseServerUrlFromOutput(output: string): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
function isPrimaryAgent(agent: Agent): boolean {
|
||||
return !agent.hidden && (agent.mode === "primary" || agent.mode === "all");
|
||||
}
|
||||
|
||||
function inferVariantValues(providerID: string): ReadonlyArray<string> {
|
||||
if (providerID === "anthropic") {
|
||||
return ANTHROPIC_VARIANTS;
|
||||
}
|
||||
if (providerID === "openai" || providerID === "opencode") {
|
||||
return OPENAI_VARIANTS;
|
||||
}
|
||||
if (providerID.startsWith("google")) {
|
||||
return GOOGLE_VARIANTS;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function inferDefaultVariant(
|
||||
providerID: string,
|
||||
variants: ReadonlyArray<string>,
|
||||
): string | undefined {
|
||||
if (variants.length === 1) {
|
||||
return variants[0];
|
||||
}
|
||||
if (providerID === "anthropic" || providerID.startsWith("google")) {
|
||||
return variants.includes("high") ? "high" : undefined;
|
||||
}
|
||||
if (providerID === "openai" || providerID === "opencode") {
|
||||
return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function buildVariantOptions(
|
||||
providerID: string,
|
||||
model: ProviderListResponse["all"][number]["models"][string],
|
||||
) {
|
||||
const variantValues = Object.keys(model.variants ?? {});
|
||||
const resolvedValues =
|
||||
variantValues.length > 0 ? variantValues : [...inferVariantValues(providerID)];
|
||||
const defaultVariant = inferDefaultVariant(providerID, resolvedValues);
|
||||
|
||||
return resolvedValues.map((value) => {
|
||||
const option: { value: string; label: string; isDefault?: boolean } = {
|
||||
value,
|
||||
label: titleCaseSlug(value),
|
||||
};
|
||||
if (defaultVariant === value) {
|
||||
option.isDefault = true;
|
||||
}
|
||||
return option;
|
||||
});
|
||||
}
|
||||
|
||||
function buildAgentOptions(agents: ReadonlyArray<Agent>) {
|
||||
const primaryAgents = agents.filter(isPrimaryAgent);
|
||||
const defaultAgent =
|
||||
primaryAgents.find((agent) => agent.name === "build")?.name ??
|
||||
primaryAgents[0]?.name ??
|
||||
undefined;
|
||||
return primaryAgents.map((agent) => {
|
||||
const option: { value: string; label: string; isDefault?: boolean } = {
|
||||
value: agent.name,
|
||||
label: titleCaseSlug(agent.name),
|
||||
};
|
||||
if (defaultAgent === agent.name) {
|
||||
option.isDefault = true;
|
||||
}
|
||||
return option;
|
||||
});
|
||||
}
|
||||
|
||||
function openCodeCapabilitiesForModel(input: {
|
||||
readonly providerID: string;
|
||||
readonly model: ProviderListResponse["all"][number]["models"][string];
|
||||
readonly agents: ReadonlyArray<Agent>;
|
||||
}): ModelCapabilities {
|
||||
const variantOptions = buildVariantOptions(input.providerID, input.model);
|
||||
const agentOptions = buildAgentOptions(input.agents);
|
||||
return {
|
||||
...DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
...(variantOptions.length > 0 ? { variantOptions } : {}),
|
||||
...(agentOptions.length > 0 ? { agentOptions } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseOpenCodeModelSlug(
|
||||
slug: string | null | undefined,
|
||||
): ParsedOpenCodeModelSlug | null {
|
||||
@@ -169,6 +196,10 @@ export function parseOpenCodeModelSlug(
|
||||
};
|
||||
}
|
||||
|
||||
export function toOpenCodeModelSlug(providerID: string, modelID: string): string {
|
||||
return `${providerID}/${modelID}`;
|
||||
}
|
||||
|
||||
export function openCodeQuestionId(
|
||||
index: number,
|
||||
question: QuestionRequest["questions"][number],
|
||||
@@ -255,268 +286,288 @@ export function toOpenCodeQuestionAnswers(
|
||||
});
|
||||
}
|
||||
|
||||
function ensureRuntimeError(
|
||||
operation: OpenCodeRuntimeError["operation"],
|
||||
detail: string,
|
||||
cause: unknown,
|
||||
): OpenCodeRuntimeError {
|
||||
return OpenCodeRuntimeError.is(cause)
|
||||
? cause
|
||||
: new OpenCodeRuntimeError({ operation, detail, cause });
|
||||
export async function findAvailablePort(): Promise<number> {
|
||||
const server = createServer();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, DEFAULT_HOSTNAME, () => resolve());
|
||||
});
|
||||
const address = server.address() as AddressInfo;
|
||||
const port = address.port;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => (error ? reject(error) : resolve()));
|
||||
});
|
||||
return port;
|
||||
}
|
||||
|
||||
const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const netService = yield* NetService;
|
||||
export function resolveOpenCodeBinaryPath(binaryPath: string): string {
|
||||
if (Path.isAbsolute(binaryPath)) {
|
||||
return binaryPath;
|
||||
}
|
||||
return execFileSync("which", [binaryPath], {
|
||||
encoding: "utf8",
|
||||
timeout: 3_000,
|
||||
}).trim();
|
||||
}
|
||||
|
||||
const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(input.binaryPath, [...input.args], {
|
||||
shell: process.platform === "win32",
|
||||
env: process.env,
|
||||
}),
|
||||
);
|
||||
const [stdout, stderr, code] = yield* Effect.all(
|
||||
[collectStreamAsString(child.stdout), collectStreamAsString(child.stderr), child.exitCode],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const exitCode = Number(code);
|
||||
if (isWindowsCommandNotFound(exitCode, stderr)) {
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "runOpenCodeCommand",
|
||||
detail: `spawn ${input.binaryPath} ENOENT`,
|
||||
});
|
||||
}
|
||||
return {
|
||||
stdout,
|
||||
stderr,
|
||||
code: exitCode,
|
||||
} satisfies OpenCodeCommandResult;
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.mapError((cause) =>
|
||||
ensureRuntimeError(
|
||||
"runOpenCodeCommand",
|
||||
`Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
|
||||
cause,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
// Bind this server's lifetime to the caller's scope. When the caller's
|
||||
// scope closes, the spawned child is killed and all associated fibers
|
||||
// are interrupted automatically — no `close()` method needed.
|
||||
const runtimeScope = yield* Scope.Scope;
|
||||
|
||||
const hostname = input.hostname ?? DEFAULT_HOSTNAME;
|
||||
const port =
|
||||
input.port ??
|
||||
(yield* netService.findAvailablePort(0).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "startOpenCodeServerProcess",
|
||||
detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
));
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
|
||||
const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
|
||||
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make(input.binaryPath, args, {
|
||||
env: {
|
||||
...process.env,
|
||||
OPENCODE_CONFIG_CONTENT: JSON.stringify({}),
|
||||
},
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.provideService(Scope.Scope, runtimeScope),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "startOpenCodeServerProcess",
|
||||
detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const stdoutRef = yield* Ref.make("");
|
||||
const stderrRef = yield* Ref.make("");
|
||||
const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
|
||||
|
||||
const setReadyFromStdoutChunk = (chunk: string) =>
|
||||
Ref.updateAndGet(stdoutRef, (stdout) => `${stdout}${chunk}`).pipe(
|
||||
Effect.flatMap((nextStdout) => {
|
||||
const parsed = parseServerUrlFromOutput(nextStdout);
|
||||
return parsed
|
||||
? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore)
|
||||
: Effect.void;
|
||||
}),
|
||||
);
|
||||
|
||||
const stdoutFiber = yield* child.stdout.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runForEach(setReadyFromStdoutChunk),
|
||||
Effect.ignore,
|
||||
Effect.forkIn(runtimeScope),
|
||||
);
|
||||
const stderrFiber = yield* child.stderr.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runForEach((chunk) => Ref.update(stderrRef, (stderr) => `${stderr}${chunk}`)),
|
||||
Effect.ignore,
|
||||
Effect.forkIn(runtimeScope),
|
||||
);
|
||||
|
||||
const exitFiber = yield* child.exitCode.pipe(
|
||||
Effect.flatMap((code) =>
|
||||
Effect.gen(function* () {
|
||||
const stdout = yield* Ref.get(stdoutRef);
|
||||
const stderr = yield* Ref.get(stderrRef);
|
||||
const exitCode = Number(code);
|
||||
yield* Deferred.fail(
|
||||
readyDeferred,
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "startOpenCodeServerProcess",
|
||||
detail: [
|
||||
`OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
|
||||
stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
|
||||
stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n"),
|
||||
cause: { exitCode, stdout, stderr },
|
||||
}),
|
||||
).pipe(Effect.ignore);
|
||||
}),
|
||||
),
|
||||
Effect.ignore,
|
||||
Effect.forkIn(runtimeScope),
|
||||
);
|
||||
|
||||
const readyExit = yield* Effect.exit(
|
||||
Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
|
||||
);
|
||||
|
||||
// Startup-time fibers are no longer needed once ready has resolved (either
|
||||
// way). The exit fiber is only interrupted on failure; on success it keeps
|
||||
// the caller's `exitCode` effect observable until the scope closes.
|
||||
yield* Fiber.interrupt(stdoutFiber).pipe(Effect.ignore);
|
||||
yield* Fiber.interrupt(stderrFiber).pipe(Effect.ignore);
|
||||
|
||||
if (Exit.isFailure(readyExit)) {
|
||||
yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
|
||||
const squashed = Cause.squash(readyExit.cause);
|
||||
return yield* ensureRuntimeError(
|
||||
"startOpenCodeServerProcess",
|
||||
`Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
|
||||
squashed,
|
||||
);
|
||||
}
|
||||
|
||||
const readyOption = readyExit.value;
|
||||
if (Option.isNone(readyOption)) {
|
||||
yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "startOpenCodeServerProcess",
|
||||
detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
url: readyOption.value,
|
||||
exitCode: child.exitCode.pipe(
|
||||
Effect.map(Number),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
),
|
||||
} satisfies OpenCodeServerProcess;
|
||||
export function detectMacosSigkillHint(binaryPath: string): string | null {
|
||||
try {
|
||||
// Check for quarantine xattr first.
|
||||
const resolvedPath = resolveOpenCodeBinaryPath(binaryPath);
|
||||
const xattr = execFileSync("xattr", ["-l", resolvedPath], {
|
||||
encoding: "utf8",
|
||||
timeout: 3_000,
|
||||
});
|
||||
|
||||
const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => {
|
||||
const serverUrl = input.serverUrl?.trim();
|
||||
if (serverUrl) {
|
||||
// We don't own externally-configured servers — no scope interaction.
|
||||
return Effect.succeed({
|
||||
url: serverUrl,
|
||||
exitCode: null,
|
||||
external: true,
|
||||
});
|
||||
if (xattr.includes("com.apple.quarantine")) {
|
||||
return (
|
||||
`macOS quarantine is blocking the OpenCode binary. ` +
|
||||
`Run: xattr -d com.apple.quarantine ${resolvedPath}`
|
||||
);
|
||||
}
|
||||
|
||||
return startOpenCodeServerProcess({
|
||||
binaryPath: input.binaryPath,
|
||||
...(input.port !== undefined ? { port: input.port } : {}),
|
||||
...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
|
||||
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
|
||||
}).pipe(
|
||||
Effect.map((server) => ({
|
||||
url: server.url,
|
||||
exitCode: server.exitCode,
|
||||
external: false,
|
||||
})),
|
||||
);
|
||||
// Look for a recent crash report with the termination reason.
|
||||
const crashDir = Path.join(OS.homedir(), "Library/Logs/DiagnosticReports");
|
||||
const binaryName = Path.basename(resolvedPath);
|
||||
const recentReports = FS.readdirSync(crashDir)
|
||||
.filter((f) => f.startsWith(binaryName) && f.endsWith(".ips"))
|
||||
.toSorted()
|
||||
.toReversed()
|
||||
.slice(0, 1);
|
||||
|
||||
for (const report of recentReports) {
|
||||
const content = FS.readFileSync(Path.join(crashDir, report), "utf8");
|
||||
if (content.includes('"namespace":"CODESIGNING"')) {
|
||||
return (
|
||||
"macOS killed the process due to an invalid code signature. " +
|
||||
"The binary may be corrupted — try reinstalling OpenCode."
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Best-effort detection — don't fail the original error path.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function startOpenCodeServerProcess(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly port?: number;
|
||||
readonly hostname?: string;
|
||||
readonly timeoutMs?: number;
|
||||
}): Promise<OpenCodeServerProcess> {
|
||||
const hostname = input.hostname ?? DEFAULT_HOSTNAME;
|
||||
const port = input.port ?? (await findAvailablePort());
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
|
||||
const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
|
||||
const child = spawn(input.binaryPath, args, {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: {
|
||||
...process.env,
|
||||
OPENCODE_CONFIG_CONTENT: JSON.stringify({}),
|
||||
},
|
||||
});
|
||||
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stderr.setEncoding("utf8");
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let closed = false;
|
||||
const close = () => {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
child.kill();
|
||||
};
|
||||
|
||||
const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) =>
|
||||
createOpencodeClient({
|
||||
baseUrl: input.baseUrl,
|
||||
directory: input.directory,
|
||||
...(input.serverPassword
|
||||
? {
|
||||
headers: {
|
||||
Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
throwOnError: true,
|
||||
});
|
||||
const url = await new Promise<string>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
close();
|
||||
reject(new Error(`Timed out waiting for OpenCode server start after ${timeoutMs}ms.`));
|
||||
}, timeoutMs);
|
||||
|
||||
const loadProviders = (client: OpencodeClient) =>
|
||||
runOpenCodeSdk("provider.list", () => client.provider.list()).pipe(
|
||||
Effect.filterMapOrFail(
|
||||
(list) =>
|
||||
list.data
|
||||
? Result.succeed(list.data)
|
||||
: Result.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "provider.list",
|
||||
detail: "OpenCode provider list was empty.",
|
||||
}),
|
||||
),
|
||||
(result) => result,
|
||||
),
|
||||
);
|
||||
const cleanup = () => {
|
||||
clearTimeout(timeout);
|
||||
child.stdout.off("data", onStdout);
|
||||
child.stderr.off("data", onStderr);
|
||||
child.off("error", onError);
|
||||
child.off("close", onClose);
|
||||
};
|
||||
|
||||
const loadAgents = (client: OpencodeClient) =>
|
||||
runOpenCodeSdk("app.agents", () => client.app.agents()).pipe(
|
||||
Effect.map((result) => result.data ?? []),
|
||||
);
|
||||
const onStdout = (chunk: string) => {
|
||||
stdout += chunk;
|
||||
const parsed = parseServerUrlFromOutput(stdout);
|
||||
if (!parsed) {
|
||||
return;
|
||||
}
|
||||
cleanup();
|
||||
resolve(parsed);
|
||||
};
|
||||
|
||||
const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (client) =>
|
||||
Effect.all([loadProviders(client), loadAgents(client)], { concurrency: "unbounded" }).pipe(
|
||||
Effect.map(([providerList, agents]) => ({ providerList, agents })),
|
||||
);
|
||||
const onStderr = (chunk: string) => {
|
||||
stderr += chunk;
|
||||
};
|
||||
|
||||
const onError = (error: Error) => {
|
||||
cleanup();
|
||||
reject(error);
|
||||
};
|
||||
|
||||
const onClose = (code: number | null, signal: NodeJS.Signals | null) => {
|
||||
cleanup();
|
||||
const exitReason = signal ? `signal: ${signal}` : `code: ${code ?? "unknown"}`;
|
||||
const hint =
|
||||
signal === "SIGKILL" && process.platform === "darwin"
|
||||
? detectMacosSigkillHint(input.binaryPath)
|
||||
: null;
|
||||
reject(
|
||||
new Error(
|
||||
[
|
||||
`OpenCode server exited before startup completed (${exitReason}).`,
|
||||
hint,
|
||||
stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
|
||||
stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n"),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
child.stdout.on("data", onStdout);
|
||||
child.stderr.on("data", onStderr);
|
||||
child.once("error", onError);
|
||||
child.once("close", onClose);
|
||||
});
|
||||
|
||||
return {
|
||||
startOpenCodeServerProcess,
|
||||
connectToOpenCodeServer,
|
||||
runOpenCodeCommand,
|
||||
createOpenCodeSdkClient,
|
||||
loadOpenCodeInventory,
|
||||
} satisfies OpenCodeRuntimeShape;
|
||||
});
|
||||
url,
|
||||
process: child,
|
||||
close,
|
||||
};
|
||||
}
|
||||
|
||||
export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
|
||||
"t3/provider/OpenCodeRuntime",
|
||||
) {}
|
||||
export async function connectToOpenCodeServer(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly serverUrl?: string | null;
|
||||
readonly port?: number;
|
||||
readonly hostname?: string;
|
||||
readonly timeoutMs?: number;
|
||||
}): Promise<OpenCodeServerConnection> {
|
||||
const serverUrl = input.serverUrl?.trim();
|
||||
if (serverUrl) {
|
||||
return {
|
||||
url: serverUrl,
|
||||
process: null,
|
||||
external: true,
|
||||
close() {},
|
||||
};
|
||||
}
|
||||
|
||||
export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
|
||||
Layer.provide(NetService.layer),
|
||||
);
|
||||
const server = await startOpenCodeServerProcess({
|
||||
binaryPath: input.binaryPath,
|
||||
...(input.port !== undefined ? { port: input.port } : {}),
|
||||
...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
|
||||
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
|
||||
});
|
||||
|
||||
return {
|
||||
url: server.url,
|
||||
process: server.process,
|
||||
external: false,
|
||||
close: () => server.close(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function runOpenCodeCommand(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}): Promise<OpenCodeCommandResult> {
|
||||
const child = spawn(input.binaryPath, [...input.args], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
shell: process.platform === "win32",
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
child.stdout?.setEncoding("utf8");
|
||||
child.stderr?.setEncoding("utf8");
|
||||
|
||||
const stdoutChunks: Array<string> = [];
|
||||
const stderrChunks: Array<string> = [];
|
||||
|
||||
child.stdout?.on("data", (chunk: string) => stdoutChunks.push(chunk));
|
||||
child.stderr?.on("data", (chunk: string) => stderrChunks.push(chunk));
|
||||
|
||||
const code = await new Promise<number>((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("exit", (exitCode) => resolve(exitCode ?? 0));
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: stdoutChunks.join(""),
|
||||
stderr: stderrChunks.join(""),
|
||||
code,
|
||||
};
|
||||
}
|
||||
|
||||
export function createOpenCodeSdkClient(input: {
|
||||
readonly baseUrl: string;
|
||||
readonly directory: string;
|
||||
readonly serverPassword?: string;
|
||||
}): OpencodeClient {
|
||||
return createOpencodeClient({
|
||||
baseUrl: input.baseUrl,
|
||||
directory: input.directory,
|
||||
...(input.serverPassword
|
||||
? {
|
||||
headers: {
|
||||
Authorization: buildOpenCodeBasicAuthorizationHeader(input.serverPassword),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
throwOnError: true,
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadOpenCodeInventory(client: OpencodeClient): Promise<OpenCodeInventory> {
|
||||
const [providerListResult, agentsResult] = await Promise.all([
|
||||
client.provider.list(),
|
||||
client.app.agents(),
|
||||
]);
|
||||
if (!providerListResult.data) {
|
||||
throw new Error("OpenCode provider inventory was empty.");
|
||||
}
|
||||
return {
|
||||
providerList: providerListResult.data,
|
||||
agents: agentsResult.data ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
export function flattenOpenCodeModels(
|
||||
input: OpenCodeInventory,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
const connected = new Set(input.providerList.connected);
|
||||
const models: Array<ServerProviderModel> = [];
|
||||
|
||||
for (const provider of input.providerList.all) {
|
||||
if (!connected.has(provider.id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const model of Object.values(provider.models)) {
|
||||
models.push({
|
||||
slug: toOpenCodeModelSlug(provider.id, model.id),
|
||||
name: `${provider.name} · ${model.name}`,
|
||||
isCustom: false,
|
||||
capabilities: openCodeCapabilitiesForModel({
|
||||
providerID: provider.id,
|
||||
model,
|
||||
agents: input.agents,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return models.toSorted((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
@@ -1,27 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ModelCapabilities } from "@t3tools/contracts";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
import { providerModelsFromSettings } from "./providerSnapshot.ts";
|
||||
|
||||
const OPENCODE_CUSTOM_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
{
|
||||
id: "variant",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
options: [{ id: "medium", label: "Medium", isDefault: true }],
|
||||
currentValue: "medium",
|
||||
},
|
||||
{
|
||||
id: "agent",
|
||||
label: "Agent",
|
||||
type: "select",
|
||||
options: [{ id: "build", label: "Build", isDefault: true }],
|
||||
currentValue: "build",
|
||||
},
|
||||
],
|
||||
});
|
||||
const OPENCODE_CUSTOM_MODEL_CAPABILITIES: ModelCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
variantOptions: [{ value: "medium", label: "Medium", isDefault: true }],
|
||||
agentOptions: [{ value: "build", label: "Build", isDefault: true }],
|
||||
};
|
||||
|
||||
describe("providerModelsFromSettings", () => {
|
||||
it("applies the provided capabilities to custom models", () => {
|
||||
|
||||
@@ -13,8 +13,6 @@ import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { isWindowsCommandNotFound } from "../processRunner.ts";
|
||||
|
||||
export const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
// Auth status checks involve disk/network lookups and can be slow on first run (especially Windows)
|
||||
export const AUTH_PROBE_TIMEOUT_MS = 10_000;
|
||||
|
||||
export interface CommandResult {
|
||||
readonly stdout: string;
|
||||
@@ -30,12 +28,6 @@ export interface ProviderProbeResult {
|
||||
readonly message?: string;
|
||||
}
|
||||
|
||||
export interface ServerProviderPresentation {
|
||||
readonly displayName: string;
|
||||
readonly badgeLabel?: string;
|
||||
readonly showInteractionModeToggle?: boolean;
|
||||
}
|
||||
|
||||
export function nonEmptyTrimmed(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.trim();
|
||||
@@ -135,52 +127,8 @@ export function providerModelsFromSettings(
|
||||
return [...resolvedBuiltInModels, ...customEntries];
|
||||
}
|
||||
|
||||
export function buildSelectOptionDescriptor(input: {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly options:
|
||||
| ReadonlyArray<{ value: string; label: string; isDefault?: boolean | undefined }>
|
||||
| undefined;
|
||||
readonly description?: string;
|
||||
readonly promptInjectedValues?: ReadonlyArray<string>;
|
||||
}) {
|
||||
const options = (input.options ?? []).map((option) =>
|
||||
option.isDefault
|
||||
? { id: option.value, label: option.label, isDefault: true }
|
||||
: { id: option.value, label: option.label },
|
||||
);
|
||||
const currentValue = options.find((option) => option.isDefault)?.id;
|
||||
return {
|
||||
id: input.id,
|
||||
label: input.label,
|
||||
type: "select" as const,
|
||||
options,
|
||||
...(currentValue ? { currentValue } : {}),
|
||||
...(input.description ? { description: input.description } : {}),
|
||||
...(input.promptInjectedValues && input.promptInjectedValues.length > 0
|
||||
? { promptInjectedValues: [...input.promptInjectedValues] }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildBooleanOptionDescriptor(input: {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly currentValue?: boolean;
|
||||
readonly description?: string;
|
||||
}) {
|
||||
return {
|
||||
id: input.id,
|
||||
label: input.label,
|
||||
type: "boolean" as const,
|
||||
...(input.description ? { description: input.description } : {}),
|
||||
...(typeof input.currentValue === "boolean" ? { currentValue: input.currentValue } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildServerProvider(input: {
|
||||
provider: ServerProvider["provider"];
|
||||
presentation: ServerProviderPresentation;
|
||||
enabled: boolean;
|
||||
checkedAt: string;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
@@ -190,11 +138,6 @@ export function buildServerProvider(input: {
|
||||
}): ServerProvider {
|
||||
return {
|
||||
provider: input.provider,
|
||||
displayName: input.presentation.displayName,
|
||||
...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
|
||||
...(typeof input.presentation.showInteractionModeToggle === "boolean"
|
||||
? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }
|
||||
: {}),
|
||||
enabled: input.enabled,
|
||||
installed: input.probe.installed,
|
||||
version: input.probe.version,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, FileSystem } from "effect";
|
||||
|
||||
@@ -11,8 +10,6 @@ import {
|
||||
writeProviderStatusCache,
|
||||
} from "./providerStatusCache.ts";
|
||||
|
||||
const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] });
|
||||
|
||||
const makeProvider = (
|
||||
provider: ServerProvider["provider"],
|
||||
overrides?: Partial<ServerProvider>,
|
||||
@@ -84,7 +81,13 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {
|
||||
slug: "gpt-5-mini",
|
||||
name: "GPT-5 Mini",
|
||||
isCustom: false,
|
||||
capabilities: emptyCapabilities,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
message: "Cached message",
|
||||
@@ -103,7 +106,13 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
capabilities: emptyCapabilities,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
message: "Pending refresh",
|
||||
@@ -122,7 +131,13 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {
|
||||
slug: "gpt-5-mini",
|
||||
name: "GPT-5 Mini",
|
||||
isCustom: false,
|
||||
capabilities: emptyCapabilities,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
installed: cachedCodex.installed,
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import * as nodePath from "node:path";
|
||||
import { type ServerProvider, ServerProvider as ServerProviderSchema } from "@t3tools/contracts";
|
||||
import { Cause, Effect, FileSystem, Schema } from "effect";
|
||||
|
||||
import { writeFileStringAtomically } from "../atomicWrite.ts";
|
||||
import { Cause, Effect, FileSystem, Path, Schema } from "effect";
|
||||
|
||||
export const PROVIDER_CACHE_IDS = [
|
||||
"codex",
|
||||
@@ -98,8 +96,22 @@ export const readProviderStatusCache = (filePath: string) =>
|
||||
export const writeProviderStatusCache = (input: {
|
||||
readonly filePath: string;
|
||||
readonly provider: ServerProvider;
|
||||
}) =>
|
||||
writeFileStringAtomically({
|
||||
filePath: input.filePath,
|
||||
contents: `${JSON.stringify(input.provider, null, 2)}\n`,
|
||||
});
|
||||
}) => {
|
||||
const tempPath = `${input.filePath}.${process.pid}.${Date.now()}.tmp`;
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const encoded = `${JSON.stringify(input.provider, null, 2)}\n`;
|
||||
|
||||
yield* fs.makeDirectory(path.dirname(input.filePath), { recursive: true });
|
||||
yield* fs.writeFileString(tempPath, encoded);
|
||||
yield* fs.rename(tempPath, input.filePath);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }));
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -1830,14 +1830,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
);
|
||||
|
||||
assertTrue(result._tag === "Failure");
|
||||
const failureMessage = String(result.failure);
|
||||
assertTrue(
|
||||
failureMessage.includes("SocketOpenError") || failureMessage.includes("SocketCloseError"),
|
||||
);
|
||||
assertTrue(
|
||||
failureMessage.includes("Unauthorized") ||
|
||||
failureMessage.includes("An error occurred during Open"),
|
||||
);
|
||||
assertInclude(String(result.failure), "SocketOpenError");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
@@ -3612,6 +3605,69 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("passes fetchLatestOrigin through bootstrap worktree creation when requested", () =>
|
||||
Effect.gen(function* () {
|
||||
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
branch: "t3code/bootstrap-branch",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
gitCore: {
|
||||
createWorktree,
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: () => Effect.succeed({ sequence: 1 }),
|
||||
readEvents: () => Stream.empty,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createdAt = new Date().toISOString();
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-bootstrap-turn-start-fetch-origin"),
|
||||
threadId: ThreadId.make("thread-bootstrap-fetch-origin"),
|
||||
message: {
|
||||
messageId: MessageId.make("msg-bootstrap-fetch-origin"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
bootstrap: {
|
||||
prepareWorktree: {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-branch",
|
||||
fetchLatestOrigin: true,
|
||||
},
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepEqual(createWorktree.mock.calls[0]?.[0], {
|
||||
cwd: "/tmp/project",
|
||||
branch: "main",
|
||||
newBranch: "t3code/bootstrap-branch",
|
||||
fetchLatestOrigin: true,
|
||||
path: null,
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("records setup-script failures without aborting bootstrap turn start", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
|
||||
@@ -76,7 +76,6 @@ import {
|
||||
orchestrationDispatchRouteLayer,
|
||||
orchestrationSnapshotRouteLayer,
|
||||
} from "./orchestration/http.ts";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
const PtyAdapterLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
@@ -244,7 +243,6 @@ const RuntimeDependenciesLive = ReactorLayerLive.pipe(
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(OpenLive),
|
||||
Layer.provideMerge(ServerLifecycleEventsLive),
|
||||
Layer.provide(NetService.layer),
|
||||
);
|
||||
|
||||
const RuntimeServicesLive = ServerRuntimeStartupLive.pipe(
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Effect, FileSystem, Option, Schema } from "effect";
|
||||
import { Effect, FileSystem, Option, Path, Schema } from "effect";
|
||||
|
||||
import { writeFileStringAtomically } from "./atomicWrite.ts";
|
||||
import { type ServerConfigShape } from "./config.ts";
|
||||
import { formatHostForUrl, isWildcardHost } from "./startupAccess.ts";
|
||||
|
||||
@@ -43,9 +42,15 @@ export const persistServerRuntimeState = (input: {
|
||||
readonly path: string;
|
||||
readonly state: PersistedServerRuntimeState;
|
||||
}) =>
|
||||
writeFileStringAtomically({
|
||||
filePath: input.path,
|
||||
contents: `${JSON.stringify(input.state)}\n`,
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
const tempPath = `${input.path}.${process.pid}.${Date.now()}.tmp`;
|
||||
return yield* fs.makeDirectory(pathService.dirname(input.path), { recursive: true }).pipe(
|
||||
Effect.flatMap(() => fs.writeFileString(tempPath, `${JSON.stringify(input.state)}\n`)),
|
||||
Effect.flatMap(() => fs.rename(tempPath, input.path)),
|
||||
Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
|
||||
);
|
||||
});
|
||||
|
||||
export const clearPersistedServerRuntimeState = (path: string) =>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { DEFAULT_SERVER_SETTINGS, ServerSettings, ServerSettingsPatch } from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { DEFAULT_SERVER_SETTINGS, ServerSettingsPatch } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Schema } from "effect";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
@@ -29,40 +28,22 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
assert.deepEqual(
|
||||
decodePatch({
|
||||
textGenerationModelSelection: {
|
||||
options: [{ id: "fastMode", value: false }],
|
||||
options: {
|
||||
fastMode: false,
|
||||
},
|
||||
},
|
||||
}),
|
||||
{
|
||||
textGenerationModelSelection: {
|
||||
options: [{ id: "fastMode", value: false }],
|
||||
options: {
|
||||
fastMode: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"decodes legacy object-shaped textGenerationModelSelection.options from settings.json",
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
const decode = Schema.decodeUnknownSync(ServerSettings);
|
||||
|
||||
const decoded = decode({
|
||||
textGenerationModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4-mini",
|
||||
options: { reasoningEffort: "low" },
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(decoded.textGenerationModelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4-mini",
|
||||
options: [{ id: "reasoningEffort", value: "low" }],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("deep merges nested settings updates without dropping siblings", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
@@ -81,14 +62,10 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
textGenerationModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
|
||||
options: createModelSelection(
|
||||
"codex",
|
||||
DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
|
||||
[
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
{ id: "fastMode", value: true },
|
||||
],
|
||||
).options!,
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -99,7 +76,9 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
},
|
||||
},
|
||||
textGenerationModelSelection: {
|
||||
options: [{ id: "fastMode", value: false }],
|
||||
options: {
|
||||
fastMode: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -115,13 +94,14 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
customModels: ["claude-custom"],
|
||||
launchArgs: "",
|
||||
});
|
||||
assert.deepEqual(
|
||||
next.textGenerationModelSelection,
|
||||
createModelSelection("codex", DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, [
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
{ id: "fastMode", value: false },
|
||||
]),
|
||||
);
|
||||
assert.deepEqual(next.textGenerationModelSelection, {
|
||||
provider: "codex",
|
||||
model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: false,
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
@@ -134,9 +114,9 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
textGenerationModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
|
||||
{ id: "effort", value: "high" },
|
||||
]).options!,
|
||||
options: {
|
||||
effort: "high",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -146,16 +126,19 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
textGenerationModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: createModelSelection("codex", "gpt-5.4", [
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
]).options!,
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
next.textGenerationModelSelection,
|
||||
createModelSelection("codex", "gpt-5.4", [{ id: "reasoningEffort", value: "high" }]),
|
||||
);
|
||||
assert.deepEqual(next.textGenerationModelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
@@ -167,14 +150,10 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
textGenerationModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
|
||||
options: createModelSelection(
|
||||
"codex",
|
||||
DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
|
||||
[
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
{ id: "fastMode", value: true },
|
||||
],
|
||||
).options!,
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -39,7 +39,6 @@ import {
|
||||
Cause,
|
||||
} from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { writeFileStringAtomically } from "./atomicWrite.ts";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
@@ -234,14 +233,14 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
const getSettingsFromCache = Cache.get(settingsCache, cacheKey);
|
||||
|
||||
const writeSettingsAtomically = (settings: ServerSettings) => {
|
||||
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
|
||||
|
||||
return writeFileStringAtomically({
|
||||
filePath: settingsPath,
|
||||
contents: `${JSON.stringify(sparseSettings, null, 2)}\n`,
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fs),
|
||||
Effect.provideService(Path.Path, pathService),
|
||||
return Effect.succeed(`${JSON.stringify(sparseSettings, null, 2)}\n`).pipe(
|
||||
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({
|
||||
|
||||
@@ -457,6 +457,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
cwd: bootstrap.prepareWorktree.projectCwd,
|
||||
branch: bootstrap.prepareWorktree.baseBranch,
|
||||
newBranch: bootstrap.prepareWorktree.branch,
|
||||
...(bootstrap.prepareWorktree.fetchLatestOrigin ? { fetchLatestOrigin: true } : {}),
|
||||
path: null,
|
||||
});
|
||||
targetWorktreePath = worktree.worktree.path;
|
||||
|
||||
@@ -3,39 +3,14 @@ import { useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import ThreadSidebar from "./Sidebar";
|
||||
import { Sidebar, SidebarProvider, SidebarRail } from "./ui/sidebar";
|
||||
import {
|
||||
clearShortcutModifierState,
|
||||
syncShortcutModifierStateFromKeyboardEvent,
|
||||
} from "../shortcutModifierState";
|
||||
|
||||
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 onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
syncShortcutModifierStateFromKeyboardEvent(event);
|
||||
};
|
||||
const onWindowKeyUp = (event: KeyboardEvent) => {
|
||||
syncShortcutModifierStateFromKeyboardEvent(event);
|
||||
};
|
||||
const onWindowBlur = () => {
|
||||
clearShortcutModifierState();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown, true);
|
||||
window.addEventListener("keyup", onWindowKeyUp, true);
|
||||
window.addEventListener("blur", onWindowBlur);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown, true);
|
||||
window.removeEventListener("keyup", onWindowKeyUp, true);
|
||||
window.removeEventListener("blur", onWindowBlur);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const onMenuAction = window.desktopBridge?.onMenuAction;
|
||||
if (typeof onMenuAction !== "function") {
|
||||
@@ -43,9 +18,8 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
const unsubscribe = onMenuAction((action) => {
|
||||
if (action === "open-settings") {
|
||||
void navigate({ to: "/settings" });
|
||||
}
|
||||
if (action !== "open-settings") return;
|
||||
void navigate({ to: "/settings" });
|
||||
});
|
||||
|
||||
return () => {
|
||||
|
||||
@@ -23,6 +23,8 @@ interface BranchToolbarProps {
|
||||
effectiveEnvModeOverride?: EnvMode;
|
||||
activeThreadBranchOverride?: string | null;
|
||||
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
|
||||
fetchLatestOriginOverride?: boolean;
|
||||
onFetchLatestOriginOverrideChange?: (fetchLatestOrigin: boolean) => void;
|
||||
envLocked: boolean;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
@@ -38,6 +40,8 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
effectiveEnvModeOverride,
|
||||
activeThreadBranchOverride,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
fetchLatestOriginOverride,
|
||||
onFetchLatestOriginOverrideChange,
|
||||
envLocked,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
@@ -109,6 +113,8 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
{...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})}
|
||||
{...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
|
||||
{...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
|
||||
{...(fetchLatestOriginOverride !== undefined ? { fetchLatestOriginOverride } : {})}
|
||||
{...(onFetchLatestOriginOverrideChange ? { onFetchLatestOriginOverrideChange } : {})}
|
||||
{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
|
||||
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
|
||||
/>
|
||||
|
||||
@@ -42,7 +42,8 @@ import {
|
||||
ComboboxStatus,
|
||||
ComboboxTrigger,
|
||||
} from "./ui/combobox";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { Switch } from "./ui/switch";
|
||||
import { toastManager } from "./ui/toast";
|
||||
|
||||
interface BranchToolbarBranchSelectorProps {
|
||||
environmentId: EnvironmentId;
|
||||
@@ -52,6 +53,8 @@ interface BranchToolbarBranchSelectorProps {
|
||||
effectiveEnvModeOverride?: "local" | "worktree";
|
||||
activeThreadBranchOverride?: string | null;
|
||||
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
|
||||
fetchLatestOriginOverride?: boolean;
|
||||
onFetchLatestOriginOverrideChange?: (fetchLatestOrigin: boolean) => void;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
}
|
||||
@@ -83,6 +86,8 @@ export function BranchToolbarBranchSelector({
|
||||
effectiveEnvModeOverride,
|
||||
activeThreadBranchOverride,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
fetchLatestOriginOverride,
|
||||
onFetchLatestOriginOverrideChange,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarBranchSelectorProps) {
|
||||
@@ -118,6 +123,10 @@ export function BranchToolbarBranchSelector({
|
||||
activeThreadBranchOverride !== undefined
|
||||
? activeThreadBranchOverride
|
||||
: (serverThread?.branch ?? draftThread?.branch ?? null);
|
||||
const fetchLatestOrigin =
|
||||
fetchLatestOriginOverride !== undefined
|
||||
? fetchLatestOriginOverride
|
||||
: (draftThread?.fetchLatestOriginOnWorktreeCreate ?? false);
|
||||
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const activeProjectCwd = activeProject?.cwd ?? null;
|
||||
const branchCwd = activeWorktreePath ?? activeProjectCwd;
|
||||
@@ -233,7 +242,6 @@ export function BranchToolbarBranchSelector({
|
||||
activeThreadBranch,
|
||||
currentGitBranch,
|
||||
});
|
||||
const branchNames = useMemo(() => branches.map((branch) => branch.name), [branches]);
|
||||
const branchByName = useMemo(
|
||||
() => new Map(branches.map((branch) => [branch.name, branch] as const)),
|
||||
[branches],
|
||||
@@ -249,6 +257,7 @@ export function BranchToolbarBranchSelector({
|
||||
const createBranchItemValue = canCreateBranch
|
||||
? `__create_new_branch__:${trimmedBranchQuery}`
|
||||
: null;
|
||||
const branchNames = useMemo(() => branches.map((branch) => branch.name), [branches]);
|
||||
const branchPickerItems = useMemo(() => {
|
||||
const items = [...branchNames];
|
||||
if (createBranchItemValue && !hasExactBranchMatch) {
|
||||
@@ -285,6 +294,16 @@ export function BranchToolbarBranchSelector({
|
||||
const [isBranchActionPending, startBranchActionTransition] = useTransition();
|
||||
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
|
||||
const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0;
|
||||
const hasOriginRemote =
|
||||
branchesSearchData?.pages[0]?.hasOriginRemote ??
|
||||
branchStatusQuery.data?.hasOriginRemote ??
|
||||
false;
|
||||
const selectedBaseBranch = resolvedActiveBranch ? branchByName.get(resolvedActiveBranch) : null;
|
||||
const shouldShowFetchLatestOriginToggle =
|
||||
isSelectingWorktreeBase &&
|
||||
hasOriginRemote &&
|
||||
resolvedActiveBranch !== null &&
|
||||
!(selectedBaseBranch?.isRemote ?? resolvedActiveBranch.startsWith("origin/"));
|
||||
const branchStatusText = isBranchesSearchPending
|
||||
? "Loading branches..."
|
||||
: isFetchingNextPage
|
||||
@@ -305,14 +324,32 @@ export function BranchToolbarBranchSelector({
|
||||
});
|
||||
};
|
||||
|
||||
const selectWorktreeBaseBranch = (branchName: string) => {
|
||||
if (!isSelectingWorktreeBase || isBranchActionPending) return;
|
||||
setThreadBranch(branchName, null);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
};
|
||||
|
||||
const setFetchLatestOriginForWorktreeCreate = useCallback(
|
||||
(nextFetchLatestOrigin: boolean) => {
|
||||
if (hasServerThread) {
|
||||
onFetchLatestOriginOverrideChange?.(nextFetchLatestOrigin);
|
||||
return;
|
||||
}
|
||||
setDraftThreadContext(draftId ?? threadRef, {
|
||||
fetchLatestOriginOnWorktreeCreate: nextFetchLatestOrigin,
|
||||
});
|
||||
},
|
||||
[draftId, hasServerThread, onFetchLatestOriginOverrideChange, setDraftThreadContext, threadRef],
|
||||
);
|
||||
|
||||
const selectBranch = (branch: GitBranch) => {
|
||||
const api = readEnvironmentApi(environmentId);
|
||||
if (!api || !branchCwd || !activeProjectCwd || isBranchActionPending) return;
|
||||
|
||||
if (isSelectingWorktreeBase) {
|
||||
setThreadBranch(branch.name, null);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
selectWorktreeBaseBranch(branch.name);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -351,13 +388,11 @@ export function BranchToolbarBranchSelector({
|
||||
setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
|
||||
} catch (error) {
|
||||
setOptimisticBranch(previousBranch);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to checkout branch.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to checkout branch.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -383,13 +418,11 @@ export function BranchToolbarBranchSelector({
|
||||
setThreadBranch(createBranchResult.branch, activeWorktreePath);
|
||||
} catch (error) {
|
||||
setOptimisticBranch(previousBranch);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to create and checkout branch.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to create and checkout branch.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -595,6 +628,17 @@ export function BranchToolbarBranchSelector({
|
||||
onChange={(event) => setBranchQuery(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{shouldShowFetchLatestOriginToggle ? (
|
||||
<label className="flex min-w-0 items-center justify-between gap-3 border-b px-3 py-2">
|
||||
<span className="min-w-0 truncate text-sm">Fetch latest origin before creation</span>
|
||||
<Switch
|
||||
className="shrink-0"
|
||||
checked={fetchLatestOrigin}
|
||||
aria-label="Fetch latest origin before creation"
|
||||
onCheckedChange={(checked) => setFetchLatestOriginForWorktreeCreate(Boolean(checked))}
|
||||
/>
|
||||
</label>
|
||||
) : null}
|
||||
<ComboboxEmpty>No branches found.</ComboboxEmpty>
|
||||
|
||||
{shouldVirtualizeBranchList ? (
|
||||
|
||||
@@ -20,7 +20,7 @@ import { defaultUrlTransform } from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { VscodeEntryIcon } from "./chat/VscodeEntryIcon";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { openInPreferredEditor } from "../editorPreferences";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
@@ -351,25 +351,21 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
}
|
||||
|
||||
void openInPreferredEditor(api, targetPath).catch((error) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open file",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open file",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
});
|
||||
}, [targetPath]);
|
||||
|
||||
const handleCopy = useCallback((value: string, title: string) => {
|
||||
if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Failed to copy ${title.toLowerCase()}`,
|
||||
description: "Clipboard API unavailable.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: `Failed to copy ${title.toLowerCase()}`,
|
||||
description: "Clipboard API unavailable.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -382,13 +378,11 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
});
|
||||
},
|
||||
(error) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Failed to copy ${title.toLowerCase()}`,
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: `Failed to copy ${title.toLowerCase()}`,
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
},
|
||||
);
|
||||
}, []);
|
||||
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
} from "@t3tools/contracts";
|
||||
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import { createModelCapabilities, createModelSelection } from "@t3tools/shared/model";
|
||||
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
|
||||
import { HttpResponse, http, ws } from "msw";
|
||||
import { setupWorker } from "msw/browser";
|
||||
@@ -1385,18 +1384,6 @@ function dispatchChatNewShortcut(): void {
|
||||
);
|
||||
}
|
||||
|
||||
function releaseModShortcut(key?: string): void {
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent("keyup", {
|
||||
key: key ?? (isMacPlatform(navigator.platform) ? "Meta" : "Control"),
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function triggerChatNewShortcutUntilPath(
|
||||
router: ReturnType<typeof getRouter>,
|
||||
predicate: (pathname: string) => boolean,
|
||||
@@ -2618,6 +2605,110 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("can fetch the latest origin ref before creating a worktree", async () => {
|
||||
const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID);
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: {
|
||||
...snapshot,
|
||||
threads: snapshot.threads.map((thread) =>
|
||||
thread.id === THREAD_ID ? Object.assign({}, thread, { session: null }) : thread,
|
||||
),
|
||||
},
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: 1,
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
originRef: "origin/main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
|
||||
return {
|
||||
sequence: fixture.snapshot.snapshotSequence + 1,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
(await waitForButtonByText("Current checkout")).click();
|
||||
await page.getByText("New worktree", { exact: true }).click();
|
||||
await page.getByText("From main", { exact: true }).click();
|
||||
await page.getByRole("switch", { name: "Fetch latest origin before creation" }).click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const turnStartRequest = wsRequests.find(
|
||||
(request) =>
|
||||
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
|
||||
request.type === "thread.turn.start",
|
||||
) as
|
||||
| {
|
||||
_tag: string;
|
||||
type?: string;
|
||||
bootstrap?: {
|
||||
prepareWorktree?: {
|
||||
baseBranch?: string;
|
||||
fetchLatestOrigin?: boolean;
|
||||
};
|
||||
};
|
||||
}
|
||||
| undefined;
|
||||
|
||||
expect(findButtonByText("From main")).toBeTruthy();
|
||||
expect(turnStartRequest?.bootstrap?.prepareWorktree?.fetchLatestOrigin).not.toBe(true);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it");
|
||||
await waitForLayout();
|
||||
|
||||
const sendButton = await waitForSendButton();
|
||||
expect(sendButton.disabled).toBe(false);
|
||||
sendButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const turnStartRequest = wsRequests.find(
|
||||
(request) =>
|
||||
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
|
||||
request.type === "thread.turn.start",
|
||||
) as
|
||||
| {
|
||||
_tag: string;
|
||||
type?: string;
|
||||
bootstrap?: {
|
||||
prepareWorktree?: {
|
||||
baseBranch?: string;
|
||||
fetchLatestOrigin?: boolean;
|
||||
};
|
||||
};
|
||||
}
|
||||
| undefined;
|
||||
|
||||
expect(turnStartRequest?.bootstrap?.prepareWorktree?.baseBranch).toBe("main");
|
||||
expect(turnStartRequest?.bootstrap?.prepareWorktree?.fetchLatestOrigin).toBe(true);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("clears pending worktree overrides when switching empty server threads", async () => {
|
||||
const secondThreadId = "thread-browser-test-second" as ThreadId;
|
||||
const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID);
|
||||
@@ -3778,10 +3869,14 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
it("snapshots sticky codex settings into a new draft thread", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModelSelectionByProvider: {
|
||||
codex: createModelSelection("codex", "gpt-5.3-codex", [
|
||||
{ id: "reasoningEffort", value: "medium" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
stickyActiveProvider: "codex",
|
||||
});
|
||||
@@ -3807,16 +3902,14 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
);
|
||||
const newDraftId = draftIdFromPath(newThreadPath);
|
||||
|
||||
// `toMatchObject` matches objects loosely (extras ignored) but compares
|
||||
// arrays strictly, so wrap `options` in `arrayContaining` to keep the
|
||||
// assertion focused on sticky `fastMode` carrying over without asserting
|
||||
// on exactly which other options are preserved.
|
||||
expect(composerDraftFor(newDraftId)).toMatchObject({
|
||||
modelSelectionByProvider: {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: expect.arrayContaining([{ id: "fastMode", value: true }]),
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
activeProvider: "codex",
|
||||
@@ -3829,10 +3922,14 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
it("hydrates the provider alongside a sticky claude model", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModelSelectionByProvider: {
|
||||
claudeAgent: createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||
{ id: "effort", value: "max" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
claudeAgent: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
stickyActiveProvider: "claudeAgent",
|
||||
});
|
||||
@@ -3860,10 +3957,14 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
expect(composerDraftFor(newDraftId)).toMatchObject({
|
||||
modelSelectionByProvider: {
|
||||
claudeAgent: createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||
{ id: "effort", value: "max" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
claudeAgent: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
activeProvider: "claudeAgent",
|
||||
});
|
||||
@@ -3903,10 +4004,14 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
it("prefers draft state over sticky composer settings and defaults", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModelSelectionByProvider: {
|
||||
codex: createModelSelection("codex", "gpt-5.3-codex", [
|
||||
{ id: "reasoningEffort", value: "medium" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
stickyActiveProvider: "codex",
|
||||
});
|
||||
@@ -3932,27 +4037,27 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
);
|
||||
const draftId = draftIdFromPath(threadPath);
|
||||
|
||||
// See the note on the sibling sticky-codex test: arrays match strictly
|
||||
// under `toMatchObject`, so use `arrayContaining` to keep the assertion
|
||||
// scoped to the sticky trait (`fastMode`) that must carry over.
|
||||
expect(composerDraftFor(draftId)).toMatchObject({
|
||||
modelSelectionByProvider: {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: expect.arrayContaining([{ id: "fastMode", value: true }]),
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
activeProvider: "codex",
|
||||
});
|
||||
|
||||
useComposerDraftStore.getState().setModelSelection(
|
||||
draftId,
|
||||
createModelSelection("codex", "gpt-5.4", [
|
||||
{ id: "reasoningEffort", value: "low" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
);
|
||||
useComposerDraftStore.getState().setModelSelection(draftId, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
|
||||
await newThreadButton.click();
|
||||
|
||||
@@ -3963,10 +4068,14 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
);
|
||||
expect(composerDraftFor(draftId)).toMatchObject({
|
||||
modelSelectionByProvider: {
|
||||
codex: createModelSelection("codex", "gpt-5.4", [
|
||||
{ id: "reasoningEffort", value: "low" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
activeProvider: "codex",
|
||||
});
|
||||
@@ -4001,29 +4110,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "thread.jump.1",
|
||||
shortcut: {
|
||||
key: "1",
|
||||
metaKey: true,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "modelPicker.jump.1",
|
||||
shortcut: {
|
||||
key: "1",
|
||||
metaKey: true,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: false,
|
||||
},
|
||||
whenAst: { type: "identifier", name: "modelPickerOpen" },
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
@@ -5538,202 +5624,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("opens the model picker when selecting /model", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-model-command-target" as MessageId,
|
||||
targetText: "model command thread",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForComposerEditor();
|
||||
await page.getByTestId("composer-editor").fill("/mod");
|
||||
|
||||
const menuItem = await waitForComposerMenuItem("slash:model");
|
||||
await menuItem.click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.querySelector(".model-picker-list")).not.toBeNull();
|
||||
expect(findComposerProviderModelPicker()?.textContent).not.toContain("/model");
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => resolve());
|
||||
});
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const searchInput = document.querySelector<HTMLInputElement>(
|
||||
'input[placeholder="Search models..."]',
|
||||
);
|
||||
expect(searchInput).not.toBeNull();
|
||||
expect(document.activeElement).toBe(searchInput);
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("toggles the model picker and shows jump keys immediately from the shortcut", async () => {
|
||||
const snapshot = createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-model-picker-shortcut-target" as MessageId,
|
||||
targetText: "model picker shortcut thread",
|
||||
});
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: {
|
||||
...snapshot,
|
||||
projects: snapshot.projects.map((project) =>
|
||||
project.id === PROJECT_ID
|
||||
? Object.assign({}, project, {
|
||||
defaultModelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
})
|
||||
: project,
|
||||
),
|
||||
threads: snapshot.threads.map((thread) =>
|
||||
thread.id === THREAD_ID
|
||||
? Object.assign({}, thread, {
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
})
|
||||
: thread,
|
||||
),
|
||||
},
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
keybindings: [
|
||||
{
|
||||
command: "modelPicker.toggle",
|
||||
shortcut: {
|
||||
key: "m",
|
||||
metaKey: false,
|
||||
ctrlKey: true,
|
||||
shiftKey: true,
|
||||
altKey: false,
|
||||
modKey: false,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "thread.jump.1",
|
||||
shortcut: {
|
||||
key: "1",
|
||||
metaKey: false,
|
||||
ctrlKey: true,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "modelPicker.jump.1",
|
||||
shortcut: {
|
||||
key: "1",
|
||||
metaKey: false,
|
||||
ctrlKey: true,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: false,
|
||||
},
|
||||
whenAst: { type: "identifier", name: "modelPickerOpen" },
|
||||
},
|
||||
],
|
||||
providers: [
|
||||
{
|
||||
...nextFixture.serverConfig.providers[0]!,
|
||||
provider: "codex",
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-5.1-codex-max",
|
||||
name: "GPT-5.1 Codex Max",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
{ id: "fastMode", label: "Fast Mode", type: "boolean" as const },
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex",
|
||||
name: "GPT-5.3 Codex",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
{ id: "fastMode", label: "Fast Mode", type: "boolean" as const },
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
{ id: "fastMode", label: "Fast Mode", type: "boolean" as const },
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
await waitForComposerEditor();
|
||||
|
||||
const initialPath = mounted.router.state.location.pathname;
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "m",
|
||||
ctrlKey: true,
|
||||
shiftKey: true,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.querySelector(".model-picker-list")).not.toBeNull();
|
||||
});
|
||||
|
||||
const jumpLabel = isMacPlatform(navigator.platform) ? "⌃1" : "Ctrl+1";
|
||||
await vi.waitFor(() => {
|
||||
expect(
|
||||
Array.from(
|
||||
document.querySelectorAll<HTMLElement>('.model-picker-list [data-slot="kbd"]'),
|
||||
).some((element) => element.textContent?.trim() === jumpLabel),
|
||||
).toBe(true);
|
||||
});
|
||||
expect(mounted.router.state.location.pathname).toBe(initialPath);
|
||||
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "m",
|
||||
ctrlKey: true,
|
||||
shiftKey: true,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.querySelector(".model-picker-list")).toBeNull();
|
||||
});
|
||||
} finally {
|
||||
releaseModShortcut("Control");
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows a tooltip with the skill description when hovering a skill pill", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
type ApprovalRequestId,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ClaudeAgentEffort,
|
||||
type EnvironmentId,
|
||||
type MessageId,
|
||||
type ModelSelection,
|
||||
@@ -25,11 +26,7 @@ import {
|
||||
scopeProjectRef,
|
||||
scopeThreadRef,
|
||||
} from "@t3tools/client-runtime";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
createModelSelection,
|
||||
resolvePromptInjectedEffort,
|
||||
} from "@t3tools/shared/model";
|
||||
import { applyClaudePromptEffortPrefix, createModelSelection } from "@t3tools/shared/model";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { truncate } from "@t3tools/shared/String";
|
||||
import { Debouncer } from "@tanstack/react-pacer";
|
||||
@@ -104,7 +101,7 @@ import PlanSidebar from "./PlanSidebar";
|
||||
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { cn, randomUUID } from "~/lib/utils";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
|
||||
import { type NewProjectScriptInput } from "./ProjectScriptsControl";
|
||||
import {
|
||||
@@ -309,8 +306,10 @@ function formatOutgoingPrompt(params: {
|
||||
text: string;
|
||||
}): string {
|
||||
const caps = getProviderModelCapabilities(params.models, params.model, params.provider);
|
||||
const promptEffort = resolvePromptInjectedEffort(caps, params.effort);
|
||||
return applyClaudePromptEffortPrefix(params.text, promptEffort);
|
||||
if (params.effort && caps.promptInjectedEffortLevels.includes(params.effort)) {
|
||||
return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeAgentEffort | null);
|
||||
}
|
||||
return params.text;
|
||||
}
|
||||
const SCRIPT_TERMINAL_COLS = 120;
|
||||
const SCRIPT_TERMINAL_ROWS = 30;
|
||||
@@ -701,6 +700,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const [pendingServerThreadEnvMode, setPendingServerThreadEnvMode] =
|
||||
useState<DraftThreadEnvMode | null>(null);
|
||||
const [pendingServerThreadBranch, setPendingServerThreadBranch] = useState<string | null>();
|
||||
const [pendingServerThreadFetchLatestOrigin, setPendingServerThreadFetchLatestOrigin] = useState<
|
||||
boolean | null
|
||||
>(null);
|
||||
const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useLocalStorage(
|
||||
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
|
||||
{},
|
||||
@@ -1856,13 +1858,11 @@ export default function ChatView(props: ChatViewProps) {
|
||||
title: `Deleted action "${deletedName ?? "Unknown"}"`,
|
||||
});
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not delete action",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not delete action",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
});
|
||||
}
|
||||
},
|
||||
[activeProject, persistProjectScripts],
|
||||
@@ -2104,6 +2104,11 @@ export default function ChatView(props: ChatViewProps) {
|
||||
canOverrideServerThreadEnvMode && pendingServerThreadBranch !== undefined
|
||||
? pendingServerThreadBranch
|
||||
: (activeThread?.branch ?? null);
|
||||
const activeThreadFetchLatestOrigin = canOverrideServerThreadEnvMode
|
||||
? (pendingServerThreadFetchLatestOrigin ?? false)
|
||||
: isLocalDraftThread
|
||||
? (draftThread?.fetchLatestOriginOnWorktreeCreate ?? false)
|
||||
: false;
|
||||
const sendEnvMode = resolveSendEnvMode({
|
||||
requestedEnvMode: envMode,
|
||||
isGitRepo,
|
||||
@@ -2112,6 +2117,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
useEffect(() => {
|
||||
setPendingServerThreadEnvMode(null);
|
||||
setPendingServerThreadBranch(undefined);
|
||||
setPendingServerThreadFetchLatestOrigin(null);
|
||||
}, [activeThread?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -2120,6 +2126,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}
|
||||
setPendingServerThreadEnvMode(null);
|
||||
setPendingServerThreadBranch(undefined);
|
||||
setPendingServerThreadFetchLatestOrigin(null);
|
||||
}, [canOverrideServerThreadEnvMode]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -2236,7 +2243,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const shortcutContext = {
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen: Boolean(terminalState.terminalOpen),
|
||||
modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false,
|
||||
};
|
||||
|
||||
const command = resolveShortcutCommand(event, keybindings, {
|
||||
@@ -2286,13 +2292,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (command === "modelPicker.toggle") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
composerRef.current?.toggleModelPicker();
|
||||
return;
|
||||
}
|
||||
|
||||
const scriptId = projectScriptIdFromCommand(command);
|
||||
if (!scriptId || !activeProject) return;
|
||||
const script = activeProject.scripts.find((entry) => entry.id === scriptId);
|
||||
@@ -2429,13 +2428,11 @@ export default function ChatView(props: ChatViewProps) {
|
||||
expiredTerminalContextCount,
|
||||
"empty",
|
||||
);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "warning",
|
||||
title: toastCopy.title,
|
||||
description: toastCopy.description,
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: toastCopy.title,
|
||||
description: toastCopy.description,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -2446,6 +2443,11 @@ export default function ChatView(props: ChatViewProps) {
|
||||
isFirstMessage && sendEnvMode === "worktree" && !activeThread.worktreePath
|
||||
? activeThreadBranch
|
||||
: null;
|
||||
const fetchLatestOriginForWorktree =
|
||||
isFirstMessage &&
|
||||
sendEnvMode === "worktree" &&
|
||||
!activeThread.worktreePath &&
|
||||
activeThreadFetchLatestOrigin;
|
||||
|
||||
// In worktree mode, require an explicit base branch so we don't silently
|
||||
// fall back to local execution when branch selection is missing.
|
||||
@@ -2517,13 +2519,11 @@ export default function ChatView(props: ChatViewProps) {
|
||||
expiredTerminalContextCount,
|
||||
"omitted",
|
||||
);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "warning",
|
||||
title: toastCopy.title,
|
||||
description: toastCopy.description,
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: toastCopy.title,
|
||||
description: toastCopy.description,
|
||||
});
|
||||
}
|
||||
promptRef.current = "";
|
||||
clearComposerDraftContent(composerDraftTarget);
|
||||
@@ -2601,6 +2601,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
projectCwd: activeProject.cwd,
|
||||
baseBranch: baseBranchForWorktree,
|
||||
branch: buildTemporaryWorktreeBranchName(),
|
||||
...(fetchLatestOriginForWorktree ? { fetchLatestOrigin: true } : {}),
|
||||
},
|
||||
runSetupScript: true,
|
||||
}
|
||||
@@ -3089,16 +3090,12 @@ export default function ChatView(props: ChatViewProps) {
|
||||
threadId: nextThreadId,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not start implementation thread",
|
||||
description:
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "An error occurred while creating the new thread.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not start implementation thread",
|
||||
description:
|
||||
err instanceof Error ? err.message : "An error occurred while creating the new thread.",
|
||||
});
|
||||
})
|
||||
.then(finish, finish);
|
||||
}, [
|
||||
@@ -3360,8 +3357,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
activeThreadActivities={activeThread?.activities}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
terminalOpen={Boolean(terminalState.terminalOpen)}
|
||||
gitCwd={gitCwd}
|
||||
promptRef={promptRef}
|
||||
composerImagesRef={composerImagesRef}
|
||||
@@ -3401,6 +3396,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
? {
|
||||
activeThreadBranchOverride: activeThreadBranch,
|
||||
onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
|
||||
fetchLatestOriginOverride: activeThreadFetchLatestOrigin,
|
||||
onFetchLatestOriginOverrideChange: (fetchLatestOrigin: boolean) =>
|
||||
setPendingServerThreadFetchLatestOrigin(fetchLatestOrigin),
|
||||
}
|
||||
: {})}
|
||||
envLocked={envLocked}
|
||||
|
||||
@@ -151,26 +151,22 @@ export function buildThreadActionItems<TThread extends BuildThreadActionItemsThr
|
||||
const leadingContent = input.renderLeadingContent?.(thread);
|
||||
const trailingContent = input.renderTrailingContent?.(thread);
|
||||
|
||||
return Object.assign(
|
||||
{
|
||||
kind: "action" as const,
|
||||
value: `thread:${thread.id}`,
|
||||
searchTerms: [thread.title, projectTitle ?? ``, thread.branch ?? ``],
|
||||
title: thread.title,
|
||||
description: descriptionParts.join(` · `),
|
||||
timestamp: formatRelativeTimeLabel(
|
||||
thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
|
||||
),
|
||||
icon: input.icon,
|
||||
return {
|
||||
kind: "action",
|
||||
value: `thread:${thread.id}`,
|
||||
searchTerms: [thread.title, projectTitle ?? "", thread.branch ?? ""],
|
||||
title: thread.title,
|
||||
description: descriptionParts.join(" · "),
|
||||
timestamp: formatRelativeTimeLabel(
|
||||
thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
|
||||
),
|
||||
icon: input.icon,
|
||||
...(leadingContent ? { titleLeadingContent: leadingContent } : {}),
|
||||
...(trailingContent ? { titleTrailingContent: trailingContent } : {}),
|
||||
run: async () => {
|
||||
await input.runThread(thread);
|
||||
},
|
||||
leadingContent ? { titleLeadingContent: leadingContent } : {},
|
||||
trailingContent ? { titleTrailingContent: trailingContent } : {},
|
||||
{
|
||||
run: async () => {
|
||||
await input.runThread(thread);
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -102,7 +102,7 @@ import {
|
||||
} from "./ui/command";
|
||||
import { Button } from "./ui/button";
|
||||
import { Kbd, KbdGroup } from "./ui/kbd";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
|
||||
import type { ChatComposerHandle } from "./chat/ChatComposer";
|
||||
|
||||
@@ -605,13 +605,11 @@ function OpenCommandPaletteDialog() {
|
||||
|
||||
const environmentId = defaultAddProjectEnvironmentId;
|
||||
if (!environmentId) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to browse projects",
|
||||
description: "No environment is available.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to browse projects",
|
||||
description: "No environment is available.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -726,24 +724,20 @@ function OpenCommandPaletteDialog() {
|
||||
if (!api) return;
|
||||
|
||||
if (isUnsupportedWindowsProjectPath(rawCwd.trim(), browseEnvironmentPlatform)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to add project",
|
||||
description: "Windows-style paths are only supported on Windows.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to add project",
|
||||
description: "Windows-style paths are only supported on Windows.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isExplicitRelativeProjectPath(rawCwd.trim()) && !currentProjectCwdForBrowse) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to add project",
|
||||
description: "Relative paths require an active project.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to add project",
|
||||
description: "Relative paths require an active project.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -796,13 +790,11 @@ function OpenCommandPaletteDialog() {
|
||||
}).catch(() => undefined);
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to add project",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to add project",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
}
|
||||
},
|
||||
[
|
||||
@@ -942,13 +934,11 @@ function OpenCommandPaletteDialog() {
|
||||
}
|
||||
|
||||
void item.run().catch((error: unknown) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to run command",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to run command",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -10,9 +10,9 @@ export type DiffPanelMode = "inline" | "sheet" | "sidebar";
|
||||
function getDiffPanelHeaderRowClassName(mode: DiffPanelMode) {
|
||||
const shouldUseDragRegion = isElectron && mode !== "sheet";
|
||||
return cn(
|
||||
"flex items-center justify-between gap-2 px-4",
|
||||
"flex items-center justify-between gap-2 px-4 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]",
|
||||
shouldUseDragRegion
|
||||
? "drag-region h-[52px] border-b border-border wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]"
|
||||
? "drag-region h-[52px] border-b border-border wco:h-[env(titlebar-area-height)]"
|
||||
: "h-12 wco:max-h-[env(titlebar-area-height)]",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -90,7 +90,6 @@ vi.mock("~/components/ui/toast", () => ({
|
||||
promise: toastPromiseSpy,
|
||||
update: toastUpdateSpy,
|
||||
},
|
||||
stackedThreadToast: vi.fn((options: unknown) => options),
|
||||
}));
|
||||
|
||||
vi.mock("~/editorPreferences", () => ({
|
||||
|
||||
@@ -38,7 +38,7 @@ import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
|
||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
||||
import { Textarea } from "~/components/ui/textarea";
|
||||
import { stackedThreadToast, toastManager, type ThreadToastData } from "~/components/ui/toast";
|
||||
import { toastManager, type ThreadToastData } from "~/components/ui/toast";
|
||||
import { openInPreferredEditor } from "~/editorPreferences";
|
||||
import {
|
||||
gitInitMutationOptions,
|
||||
@@ -474,14 +474,12 @@ export default function GitActionsControl({
|
||||
return;
|
||||
}
|
||||
void api.shell.openExternal(prUrl).catch((err: unknown) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open PR link",
|
||||
description: err instanceof Error ? err.message : "An error occurred.",
|
||||
...(threadToastData !== undefined ? { data: threadToastData } : {}),
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open PR link",
|
||||
description: err instanceof Error ? err.message : "An error occurred.",
|
||||
data: threadToastData,
|
||||
});
|
||||
});
|
||||
}, [gitStatusForActions, threadToastData]);
|
||||
|
||||
@@ -672,44 +670,33 @@ export default function GitActionsControl({
|
||||
};
|
||||
}
|
||||
|
||||
const successToastData = {
|
||||
...scopedToastData,
|
||||
dismissAfterVisibleMs: 10_000,
|
||||
};
|
||||
const successToastBase = {
|
||||
type: "success",
|
||||
title: result.toast.title,
|
||||
description: result.toast.description,
|
||||
timeout: 0,
|
||||
data: {
|
||||
...scopedToastData,
|
||||
dismissAfterVisibleMs: 10_000,
|
||||
},
|
||||
} as const;
|
||||
|
||||
if (toastActionProps) {
|
||||
toastManager.update(
|
||||
resolvedProgressToastId,
|
||||
stackedThreadToast({
|
||||
type: "success",
|
||||
title: result.toast.title,
|
||||
description: result.toast.description,
|
||||
timeout: 0,
|
||||
actionProps: toastActionProps,
|
||||
actionVariant: "outline",
|
||||
data: successToastData,
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
toastManager.update(resolvedProgressToastId, {
|
||||
type: "success",
|
||||
title: result.toast.title,
|
||||
description: result.toast.description,
|
||||
timeout: 0,
|
||||
data: successToastData,
|
||||
...successToastBase,
|
||||
actionProps: toastActionProps,
|
||||
});
|
||||
} else {
|
||||
toastManager.update(resolvedProgressToastId, successToastBase);
|
||||
}
|
||||
} catch (err) {
|
||||
activeGitActionProgressRef.current = null;
|
||||
toastManager.update(
|
||||
resolvedProgressToastId,
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Action failed",
|
||||
description: err instanceof Error ? err.message : "An error occurred.",
|
||||
...(scopedToastData !== undefined ? { data: scopedToastData } : {}),
|
||||
}),
|
||||
);
|
||||
toastManager.update(resolvedProgressToastId, {
|
||||
type: "error",
|
||||
title: "Action failed",
|
||||
description: err instanceof Error ? err.message : "An error occurred.",
|
||||
data: scopedToastData,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -766,10 +753,7 @@ export default function GitActionsControl({
|
||||
}
|
||||
if (quickAction.kind === "run_pull") {
|
||||
const promise = pullMutation.mutateAsync();
|
||||
void toastManager.promise<
|
||||
Awaited<ReturnType<typeof pullMutation.mutateAsync>>,
|
||||
ThreadToastData
|
||||
>(promise, {
|
||||
toastManager.promise(promise, {
|
||||
loading: { title: "Pulling...", data: threadToastData },
|
||||
success: (result) => ({
|
||||
title: result.status === "pulled" ? "Pulled" : "Already up to date",
|
||||
@@ -848,14 +832,12 @@ export default function GitActionsControl({
|
||||
}
|
||||
const target = resolvePathLinkTarget(filePath, gitCwd);
|
||||
void openInPreferredEditor(api, target).catch((error) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open file",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
...(threadToastData !== undefined ? { data: threadToastData } : {}),
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open file",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
data: threadToastData,
|
||||
});
|
||||
});
|
||||
},
|
||||
[gitCwd, threadToastData],
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { type SVGProps, useId } from "react";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
|
||||
|
||||
@@ -15,12 +14,8 @@ export const GitHubIcon: Icon = (props) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const CursorIcon: Icon = ({ className, ...props }) => (
|
||||
<svg
|
||||
{...props}
|
||||
viewBox="0 0 466.73 532.09"
|
||||
className={cn("fill-[#26251E] dark:fill-[#EDECEC]", className)}
|
||||
>
|
||||
export const CursorIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 466.73 532.09" fill="currentColor">
|
||||
<path d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z" />
|
||||
</svg>
|
||||
);
|
||||
@@ -295,25 +290,18 @@ export const Zed: Icon = (props) => {
|
||||
);
|
||||
};
|
||||
|
||||
export const OpenAI: Icon = ({ className, ...props }) => (
|
||||
<svg
|
||||
{...props}
|
||||
preserveAspectRatio="xMidYMid"
|
||||
viewBox="0 0 256 260"
|
||||
className={cn("fill-black dark:fill-white", className)}
|
||||
>
|
||||
export const OpenAI: Icon = (props) => (
|
||||
<svg {...props} preserveAspectRatio="xMidYMid" viewBox="0 0 256 260" fill="currentColor">
|
||||
<path d="M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87 51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921 51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69-1.535-.922-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58 28.138-16.217 28.188 16.218v32.434l-28.086 16.218-28.188-16.218-.052-32.434Z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const ClaudeAI: Icon = ({ className, ...props }) => (
|
||||
<svg
|
||||
{...props}
|
||||
preserveAspectRatio="xMidYMid"
|
||||
viewBox="0 0 256 257"
|
||||
className={cn("fill-[#d97757]", className)}
|
||||
>
|
||||
<path d="m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0 82.05 1.426l4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999-.064.065Z" />
|
||||
export const ClaudeAI: Icon = (props) => (
|
||||
<svg {...props} preserveAspectRatio="xMidYMid" viewBox="0 0 256 257">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0 82.05 1.426l4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999-.064.065Z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
@@ -577,14 +565,3 @@ export const OpenCodeIcon: Icon = (props) => (
|
||||
</defs>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const GithubCopilotIcon: Icon = ({ className, ...props }) => (
|
||||
<svg
|
||||
{...props}
|
||||
preserveAspectRatio="xMidYMid"
|
||||
viewBox="0 0 256 208"
|
||||
className={cn("fill-black dark:fill-white", className)}
|
||||
>
|
||||
<path d="M205.3 31.4c14 14.8 20 35.2 22.5 63.6 6.6 0 12.8 1.5 17 7.2l7.8 10.6c2.2 3 3.4 6.6 3.4 10.4v28.7a12 12 0 0 1-4.8 9.5C215.9 187.2 172.3 208 128 208c-49 0-98.2-28.3-123.2-46.6a12 12 0 0 1-4.8-9.5v-28.7c0-3.8 1.2-7.4 3.4-10.5l7.8-10.5c4.2-5.7 10.4-7.2 17-7.2 2.5-28.4 8.4-48.8 22.5-63.6C77.3 3.2 112.6 0 127.6 0h.4c14.7 0 50.4 2.9 77.3 31.4ZM128 78.7c-3 0-6.5.2-10.3.6a27.1 27.1 0 0 1-6 12.1 45 45 0 0 1-32 13c-6.8 0-13.9-1.5-19.7-5.2-5.5 1.9-10.8 4.5-11.2 11-.5 12.2-.6 24.5-.6 36.8 0 6.1 0 12.3-.2 18.5 0 3.6 2.2 6.9 5.5 8.4C79.9 185.9 105 192 128 192s48-6 74.5-18.1a9.4 9.4 0 0 0 5.5-8.4c.3-18.4 0-37-.8-55.3-.4-6.6-5.7-9.1-11.2-11-5.8 3.7-13 5.1-19.7 5.1a45 45 0 0 1-32-12.9 27.1 27.1 0 0 1-6-12.1c-3.4-.4-6.9-.5-10.3-.6Zm-27 44c5.8 0 10.5 4.6 10.5 10.4v19.2a10.4 10.4 0 0 1-20.8 0V133c0-5.8 4.6-10.4 10.4-10.4Zm53.4 0c5.8 0 10.4 4.6 10.4 10.4v19.2a10.4 10.4 0 0 1-20.8 0V133c0-5.8 4.7-10.4 10.4-10.4Zm-73-94.4c-11.2 1.1-20.6 4.8-25.4 10-10.4 11.3-8.2 40.1-2.2 46.2A31.2 31.2 0 0 0 75 91.7c6.8 0 19.6-1.5 30.1-12.2 4.7-4.5 7.5-15.7 7.2-27-.3-9.1-2.9-16.7-6.7-19.9-4.2-3.6-13.6-5.2-24.2-4.3Zm69 4.3c-3.8 3.2-6.4 10.8-6.7 19.9-.3 11.3 2.5 22.5 7.2 27a41.7 41.7 0 0 0 30 12.2c8.9 0 17-2.9 21.3-7.2 6-6.1 8.2-34.9-2.2-46.3-4.8-5-14.2-8.8-25.4-9.9-10.6-1-20 .7-24.2 4.3ZM128 56c-2.6 0-5.6.2-9 .5.4 1.7.5 3.7.7 5.7 0 1.5 0 3-.2 4.5 3.2-.3 6-.3 8.5-.3 2.6 0 5.3 0 8.5.3-.2-1.6-.2-3-.2-4.5.2-2 .3-4 .7-5.7-3.4-.3-6.4-.5-9-.5Z" />
|
||||
</svg>
|
||||
);
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
} from "../proposedPlan";
|
||||
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu";
|
||||
import { readEnvironmentApi } from "~/environmentApi";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
|
||||
function stepStatusIcon(status: string): React.ReactNode {
|
||||
@@ -112,13 +112,11 @@ const PlanSidebar = memo(function PlanSidebar({
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not save plan",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not save plan",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
})
|
||||
.then(
|
||||
() => setIsSavingToWorkspace(false),
|
||||
|
||||
@@ -309,42 +309,6 @@ describe("orderItemsByPreferredIds", () => {
|
||||
ProjectId.make("project-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("honors projectOrder physical keys via getProjectOrderKey", async () => {
|
||||
// Regression guard for #1904 / the regression introduced by #2055:
|
||||
// `projectOrder` is populated with physical keys (envId + cwd-derived)
|
||||
// by the store and by drag-end handlers. Readers must identify projects
|
||||
// with the same key format, or manual sort silently snaps back.
|
||||
const { getProjectOrderKey } = await import("../logicalProject");
|
||||
const projects = [
|
||||
{
|
||||
environmentId: EnvironmentId.make("environment-local"),
|
||||
id: ProjectId.make("id-alpha"),
|
||||
cwd: "/work/alpha",
|
||||
},
|
||||
{
|
||||
environmentId: EnvironmentId.make("environment-local"),
|
||||
id: ProjectId.make("id-beta"),
|
||||
cwd: "/work/beta",
|
||||
},
|
||||
{
|
||||
environmentId: EnvironmentId.make("environment-local"),
|
||||
id: ProjectId.make("id-gamma"),
|
||||
cwd: "/work/gamma",
|
||||
},
|
||||
];
|
||||
const ordered = orderItemsByPreferredIds({
|
||||
items: projects,
|
||||
preferredIds: [getProjectOrderKey(projects[2]!), getProjectOrderKey(projects[0]!)],
|
||||
getId: getProjectOrderKey,
|
||||
});
|
||||
|
||||
expect(ordered.map((project) => project.cwd)).toEqual([
|
||||
"/work/gamma",
|
||||
"/work/alpha",
|
||||
"/work/beta",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAdjacentThreadId", () => {
|
||||
|
||||
+235
-203
@@ -75,13 +75,11 @@ import { useUiStateStore } from "../uiStateStore";
|
||||
import {
|
||||
resolveShortcutCommand,
|
||||
shortcutLabelForCommand,
|
||||
shouldShowThreadJumpHintsForModifiers,
|
||||
shouldShowThreadJumpHints,
|
||||
threadJumpCommandForIndex,
|
||||
threadJumpIndexFromCommand,
|
||||
threadTraversalDirectionFromCommand,
|
||||
} from "../keybindings";
|
||||
import { useModelPickerOpen } from "../modelPickerOpenState";
|
||||
import { useShortcutModifierState } from "../shortcutModifierState";
|
||||
import { useGitStatus } from "../lib/gitStatusState";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
@@ -94,7 +92,7 @@ import {
|
||||
resolveThreadRouteRef,
|
||||
resolveThreadRouteTarget,
|
||||
} from "../threadRoutes";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { formatRelativeTimeLabel } from "../timestampFormat";
|
||||
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
|
||||
import { Kbd } from "./ui/kbd";
|
||||
@@ -168,11 +166,7 @@ import { CommandDialogTrigger } from "./ui/command";
|
||||
import { readEnvironmentApi } from "../environmentApi";
|
||||
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
|
||||
import { useServerKeybindings } from "../rpc/serverState";
|
||||
import {
|
||||
derivePhysicalProjectKey,
|
||||
deriveProjectGroupingOverrideKey,
|
||||
getProjectOrderKey,
|
||||
} from "../logicalProject";
|
||||
import { derivePhysicalProjectKey, deriveProjectGroupingOverrideKey } from "../logicalProject";
|
||||
import {
|
||||
useSavedEnvironmentRegistryStore,
|
||||
useSavedEnvironmentRuntimeStore,
|
||||
@@ -205,6 +199,24 @@ const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, string> =
|
||||
separate: "Keep separate",
|
||||
};
|
||||
|
||||
function threadJumpLabelMapsEqual(
|
||||
left: ReadonlyMap<string, string>,
|
||||
right: ReadonlyMap<string, string>,
|
||||
): boolean {
|
||||
if (left === right) {
|
||||
return true;
|
||||
}
|
||||
if (left.size !== right.size) {
|
||||
return false;
|
||||
}
|
||||
for (const [key, value] of left) {
|
||||
if (right.get(key) !== value) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function formatProjectMemberActionLabel(
|
||||
member: SidebarProjectGroupMember,
|
||||
groupedProjectCount: number,
|
||||
@@ -950,13 +962,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to copy thread ID",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to copy thread ID",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
},
|
||||
});
|
||||
const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{
|
||||
@@ -970,13 +980,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to copy path",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to copy path",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
},
|
||||
});
|
||||
const openPrLink = useCallback((event: React.MouseEvent<HTMLElement>, prUrl: string) => {
|
||||
@@ -993,13 +1001,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
}
|
||||
|
||||
void api.shell.openExternal(prUrl).catch((error) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open PR link",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open PR link",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
const sidebarThreads = useStore(
|
||||
@@ -1305,73 +1311,72 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
const memberProjectRef = scopeProjectRef(member.environmentId, member.id);
|
||||
const memberThreadCount = memberThreadCountByPhysicalKey.get(member.physicalProjectKey) ?? 0;
|
||||
if (memberThreadCount > 0) {
|
||||
const warningToastId = toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "warning",
|
||||
title: "Project is not empty",
|
||||
description: "Delete all threads in this project before removing it.",
|
||||
const warningToastId = toastManager.add({
|
||||
type: "warning",
|
||||
title: "Project is not empty",
|
||||
description: "Delete all threads in this project before removing it.",
|
||||
data: {
|
||||
actionLayout: "stacked-end",
|
||||
actionVariant: "destructive",
|
||||
actionProps: {
|
||||
children: "Delete anyway",
|
||||
onClick: () => {
|
||||
void (async () => {
|
||||
toastManager.close(warningToastId);
|
||||
await new Promise<void>((resolve) => {
|
||||
window.setTimeout(resolve, 180);
|
||||
});
|
||||
|
||||
const latestProjectThreads = selectSidebarThreadsForProjectRefs(
|
||||
useStore.getState(),
|
||||
[memberProjectRef],
|
||||
);
|
||||
const confirmed = await api.dialogs.confirm(
|
||||
latestProjectThreads.length > 0
|
||||
? [
|
||||
`Remove project "${member.name}" and delete its ${latestProjectThreads.length} thread${
|
||||
latestProjectThreads.length === 1 ? "" : "s"
|
||||
}?`,
|
||||
`Path: ${member.cwd}`,
|
||||
...(member.environmentLabel
|
||||
? [`Environment: ${member.environmentLabel}`]
|
||||
: []),
|
||||
"This permanently clears conversation history for those threads.",
|
||||
"This removes only this project entry.",
|
||||
"This action cannot be undone.",
|
||||
].join("\n")
|
||||
: [
|
||||
`Remove project "${member.name}"?`,
|
||||
`Path: ${member.cwd}`,
|
||||
...(member.environmentLabel
|
||||
? [`Environment: ${member.environmentLabel}`]
|
||||
: []),
|
||||
"This removes only this project entry.",
|
||||
].join("\n"),
|
||||
);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
await removeProject(member, { force: true });
|
||||
})().catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Unknown error removing project.";
|
||||
console.error("Failed to remove project", {
|
||||
projectId: member.id,
|
||||
environmentId: member.environmentId,
|
||||
error,
|
||||
});
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Failed to remove "${member.name}"`,
|
||||
description: message,
|
||||
}),
|
||||
);
|
||||
},
|
||||
actionProps: {
|
||||
children: "Delete anyway",
|
||||
onClick: () => {
|
||||
void (async () => {
|
||||
toastManager.close(warningToastId);
|
||||
await new Promise<void>((resolve) => {
|
||||
window.setTimeout(resolve, 180);
|
||||
});
|
||||
},
|
||||
|
||||
const latestProjectThreads = selectSidebarThreadsForProjectRefs(
|
||||
useStore.getState(),
|
||||
[memberProjectRef],
|
||||
);
|
||||
const confirmed = await api.dialogs.confirm(
|
||||
latestProjectThreads.length > 0
|
||||
? [
|
||||
`Remove project "${member.name}" and delete its ${latestProjectThreads.length} thread${
|
||||
latestProjectThreads.length === 1 ? "" : "s"
|
||||
}?`,
|
||||
`Path: ${member.cwd}`,
|
||||
...(member.environmentLabel
|
||||
? [`Environment: ${member.environmentLabel}`]
|
||||
: []),
|
||||
"This permanently clears conversation history for those threads.",
|
||||
"This removes only this project entry.",
|
||||
"This action cannot be undone.",
|
||||
].join("\n")
|
||||
: [
|
||||
`Remove project "${member.name}"?`,
|
||||
`Path: ${member.cwd}`,
|
||||
...(member.environmentLabel
|
||||
? [`Environment: ${member.environmentLabel}`]
|
||||
: []),
|
||||
"This removes only this project entry.",
|
||||
].join("\n"),
|
||||
);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
await removeProject(member, { force: true });
|
||||
})().catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Unknown error removing project.";
|
||||
console.error("Failed to remove project", {
|
||||
projectId: member.id,
|
||||
environmentId: member.environmentId,
|
||||
error,
|
||||
});
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: `Failed to remove "${member.name}"`,
|
||||
description: message,
|
||||
});
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1395,13 +1400,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
environmentId: member.environmentId,
|
||||
error,
|
||||
});
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Failed to remove "${member.name}"`,
|
||||
description: message,
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: `Failed to remove "${member.name}"`,
|
||||
description: message,
|
||||
});
|
||||
}
|
||||
},
|
||||
[memberThreadCountByPhysicalKey, removeProject],
|
||||
@@ -1714,13 +1717,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
try {
|
||||
await archiveThread(threadRef);
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to archive thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to archive thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
}
|
||||
},
|
||||
[archiveThread],
|
||||
@@ -1768,13 +1769,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
title: trimmed,
|
||||
});
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to rename thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to rename thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
}
|
||||
finishRename();
|
||||
},
|
||||
@@ -1807,13 +1806,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
|
||||
const api = readEnvironmentApi(projectRenameTarget.environmentId);
|
||||
if (!api) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to rename project",
|
||||
description: "Project API unavailable.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to rename project",
|
||||
description: "Project API unavailable.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1826,13 +1823,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
});
|
||||
closeProjectRenameDialog();
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to rename project",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to rename project",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
}
|
||||
}, [closeProjectRenameDialog, projectRenameTarget, projectRenameTitle]);
|
||||
|
||||
@@ -1902,13 +1897,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
}
|
||||
if (clicked === "copy-path") {
|
||||
if (!threadWorkspacePath) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Path unavailable",
|
||||
description: "This thread does not have a workspace path to copy.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Path unavailable",
|
||||
description: "This thread does not have a workspace path to copy.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath });
|
||||
@@ -2722,8 +2715,6 @@ export default function Sidebar() {
|
||||
const clearSelection = useThreadSelectionStore((s) => s.clearSelection);
|
||||
const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);
|
||||
const platform = navigator.platform;
|
||||
const shortcutModifiers = useShortcutModifierState();
|
||||
const modelPickerOpen = useModelPickerOpen();
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((s) => s.byId);
|
||||
const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((s) => s.byId);
|
||||
@@ -2731,7 +2722,7 @@ export default function Sidebar() {
|
||||
return orderItemsByPreferredIds({
|
||||
items: projects,
|
||||
preferredIds: projectOrder,
|
||||
getId: getProjectOrderKey,
|
||||
getId: (project) => scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
|
||||
});
|
||||
}, [projectOrder, projects]);
|
||||
|
||||
@@ -2831,9 +2822,8 @@ export default function Sidebar() {
|
||||
routeThreadRef,
|
||||
).terminalOpen
|
||||
: false,
|
||||
modelPickerOpen,
|
||||
}),
|
||||
[modelPickerOpen, routeThreadRef],
|
||||
[routeThreadRef],
|
||||
);
|
||||
const newThreadShortcutLabelOptions = useMemo(
|
||||
() => ({
|
||||
@@ -3026,37 +3016,12 @@ export default function Sidebar() {
|
||||
() => [...threadJumpCommandByKey.keys()],
|
||||
[threadJumpCommandByKey],
|
||||
);
|
||||
const sidebarShortcutContext = useMemo(
|
||||
() => ({
|
||||
terminalFocus: false,
|
||||
terminalOpen: routeThreadRef
|
||||
? selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
routeThreadRef,
|
||||
).terminalOpen
|
||||
: false,
|
||||
modelPickerOpen,
|
||||
}),
|
||||
[modelPickerOpen, routeThreadRef],
|
||||
);
|
||||
const threadJumpLabelByKey = useMemo(
|
||||
() =>
|
||||
buildThreadJumpLabelMap({
|
||||
keybindings,
|
||||
platform,
|
||||
terminalOpen: sidebarShortcutContext.terminalOpen,
|
||||
threadJumpCommandByKey,
|
||||
}),
|
||||
[keybindings, platform, sidebarShortcutContext.terminalOpen, threadJumpCommandByKey],
|
||||
);
|
||||
const shouldShowThreadJumpHintsNow = shouldShowThreadJumpHintsForModifiers(
|
||||
shortcutModifiers,
|
||||
keybindings,
|
||||
{
|
||||
platform,
|
||||
context: sidebarShortcutContext,
|
||||
},
|
||||
);
|
||||
const [threadJumpLabelByKey, setThreadJumpLabelByKey] =
|
||||
useState<ReadonlyMap<string, string>>(EMPTY_THREAD_JUMP_LABELS);
|
||||
const threadJumpLabelsRef = useRef<ReadonlyMap<string, string>>(EMPTY_THREAD_JUMP_LABELS);
|
||||
threadJumpLabelsRef.current = threadJumpLabelByKey;
|
||||
const showThreadJumpHintsRef = useRef(showThreadJumpHints);
|
||||
showThreadJumpHintsRef.current = showThreadJumpHints;
|
||||
const visibleThreadJumpLabelByKey = showThreadJumpHints
|
||||
? threadJumpLabelByKey
|
||||
: EMPTY_THREAD_JUMP_LABELS;
|
||||
@@ -3087,12 +3052,52 @@ export default function Sidebar() {
|
||||
}, [prewarmedSidebarThreadRefs]);
|
||||
|
||||
useEffect(() => {
|
||||
updateThreadJumpHintsVisibility(shouldShowThreadJumpHintsNow);
|
||||
}, [shouldShowThreadJumpHintsNow, updateThreadJumpHintsVisibility]);
|
||||
const clearThreadJumpHints = () => {
|
||||
setThreadJumpLabelByKey((current) =>
|
||||
current === EMPTY_THREAD_JUMP_LABELS ? current : EMPTY_THREAD_JUMP_LABELS,
|
||||
);
|
||||
updateThreadJumpHintsVisibility(false);
|
||||
};
|
||||
const shouldIgnoreThreadJumpHintUpdate = (event: globalThis.KeyboardEvent) =>
|
||||
!event.metaKey &&
|
||||
!event.ctrlKey &&
|
||||
!event.altKey &&
|
||||
!event.shiftKey &&
|
||||
event.key !== "Meta" &&
|
||||
event.key !== "Control" &&
|
||||
event.key !== "Alt" &&
|
||||
event.key !== "Shift" &&
|
||||
!showThreadJumpHintsRef.current &&
|
||||
threadJumpLabelsRef.current === EMPTY_THREAD_JUMP_LABELS;
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||
if (shouldIgnoreThreadJumpHintUpdate(event)) {
|
||||
return;
|
||||
}
|
||||
const shortcutContext = getCurrentSidebarShortcutContext();
|
||||
const shouldShowHints = shouldShowThreadJumpHints(event, keybindings, {
|
||||
platform,
|
||||
context: shortcutContext,
|
||||
});
|
||||
if (!shouldShowHints) {
|
||||
if (
|
||||
showThreadJumpHintsRef.current ||
|
||||
threadJumpLabelsRef.current !== EMPTY_THREAD_JUMP_LABELS
|
||||
) {
|
||||
clearThreadJumpHints();
|
||||
}
|
||||
} else {
|
||||
setThreadJumpLabelByKey((current) => {
|
||||
const nextLabelMap = buildThreadJumpLabelMap({
|
||||
keybindings,
|
||||
platform,
|
||||
terminalOpen: shortcutContext.terminalOpen,
|
||||
threadJumpCommandByKey,
|
||||
});
|
||||
return threadJumpLabelMapsEqual(current, nextLabelMap) ? current : nextLabelMap;
|
||||
});
|
||||
updateThreadJumpHintsVisibility(true);
|
||||
}
|
||||
|
||||
if (event.defaultPrevented || event.repeat) {
|
||||
return;
|
||||
@@ -3142,10 +3147,43 @@ export default function Sidebar() {
|
||||
navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id));
|
||||
};
|
||||
|
||||
const onWindowKeyUp = (event: globalThis.KeyboardEvent) => {
|
||||
if (shouldIgnoreThreadJumpHintUpdate(event)) {
|
||||
return;
|
||||
}
|
||||
const shortcutContext = getCurrentSidebarShortcutContext();
|
||||
const shouldShowHints = shouldShowThreadJumpHints(event, keybindings, {
|
||||
platform,
|
||||
context: shortcutContext,
|
||||
});
|
||||
if (!shouldShowHints) {
|
||||
clearThreadJumpHints();
|
||||
return;
|
||||
}
|
||||
setThreadJumpLabelByKey((current) => {
|
||||
const nextLabelMap = buildThreadJumpLabelMap({
|
||||
keybindings,
|
||||
platform,
|
||||
terminalOpen: shortcutContext.terminalOpen,
|
||||
threadJumpCommandByKey,
|
||||
});
|
||||
return threadJumpLabelMapsEqual(current, nextLabelMap) ? current : nextLabelMap;
|
||||
});
|
||||
updateThreadJumpHintsVisibility(true);
|
||||
};
|
||||
|
||||
const onWindowBlur = () => {
|
||||
clearThreadJumpHints();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown);
|
||||
window.addEventListener("keyup", onWindowKeyUp);
|
||||
window.addEventListener("blur", onWindowBlur);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown);
|
||||
window.removeEventListener("keyup", onWindowKeyUp);
|
||||
window.removeEventListener("blur", onWindowBlur);
|
||||
};
|
||||
}, [
|
||||
getCurrentSidebarShortcutContext,
|
||||
@@ -3155,7 +3193,9 @@ export default function Sidebar() {
|
||||
platform,
|
||||
routeThreadKey,
|
||||
sidebarThreadByKey,
|
||||
threadJumpCommandByKey,
|
||||
threadJumpThreadKeys,
|
||||
updateThreadJumpHintsVisibility,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -3239,22 +3279,18 @@ export default function Sidebar() {
|
||||
if (!shouldToastDesktopUpdateActionResult(result)) return;
|
||||
const actionError = getDesktopUpdateActionError(result);
|
||||
if (!actionError) return;
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not download update",
|
||||
description: actionError,
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not download update",
|
||||
description: actionError,
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not start update download",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not start update download",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -3270,22 +3306,18 @@ export default function Sidebar() {
|
||||
if (!shouldToastDesktopUpdateActionResult(result)) return;
|
||||
const actionError = getDesktopUpdateActionError(result);
|
||||
if (!actionError) return;
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not install update",
|
||||
description: actionError,
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not install update",
|
||||
description: actionError,
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not install update",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not install update",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
});
|
||||
});
|
||||
}
|
||||
}, [desktopUpdateButtonAction, desktopUpdateButtonDisabled, desktopUpdateState]);
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
useWsConnectionStatus,
|
||||
WS_RECONNECT_MAX_ATTEMPTS,
|
||||
} from "../rpc/wsConnectionState";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { getPrimaryEnvironmentConnection } from "../environments/runtime";
|
||||
|
||||
const FORCED_WS_RECONNECT_DEBOUNCE_MS = 5_000;
|
||||
@@ -75,34 +75,13 @@ function describeRecoveredToast(
|
||||
return "Connection restored.";
|
||||
}
|
||||
|
||||
function describeSlowRpcAckToast(requests: ReadonlyArray<SlowRpcAckRequest>): string {
|
||||
function describeSlowRpcAckToast(requests: ReadonlyArray<SlowRpcAckRequest>): ReactNode {
|
||||
const count = requests.length;
|
||||
const thresholdSeconds = Math.round((requests[0]?.thresholdMs ?? 0) / 1000);
|
||||
|
||||
return `${count} request${count === 1 ? "" : "s"} waiting longer than ${thresholdSeconds}s.`;
|
||||
}
|
||||
|
||||
function SlowRpcAckRequestDetails({ requests }: { requests: ReadonlyArray<SlowRpcAckRequest> }) {
|
||||
return (
|
||||
<ul className="space-y-2.5 text-xs text-muted-foreground">
|
||||
{requests.map((req) => (
|
||||
<li
|
||||
className="min-w-0 border-border/50 border-b pb-2 last:border-b-0 last:pb-0"
|
||||
key={req.requestId}
|
||||
>
|
||||
<div className="wrap-break-word font-medium text-foreground">{req.tag}</div>
|
||||
<div className="mt-0.5 font-mono text-[10px] leading-snug opacity-90">
|
||||
{req.requestId}
|
||||
</div>
|
||||
<div className="mt-0.5 text-[10px] opacity-75">
|
||||
Started {formatConnectionMoment(req.startedAt) ?? req.startedAt}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
export function shouldAutoReconnect(
|
||||
status: WsConnectionStatus,
|
||||
trigger: WsAutoReconnectTrigger,
|
||||
@@ -159,18 +138,15 @@ export function WebSocketConnectionCoordinator() {
|
||||
console.warn("Automatic WebSocket reconnect failed", { error });
|
||||
return;
|
||||
}
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Reconnect failed",
|
||||
description:
|
||||
error instanceof Error ? error.message : "Unable to restart the WebSocket.",
|
||||
data: {
|
||||
dismissAfterVisibleMs: 8_000,
|
||||
hideCopyButton: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Reconnect failed",
|
||||
description: error instanceof Error ? error.message : "Unable to restart the WebSocket.",
|
||||
data: {
|
||||
dismissAfterVisibleMs: 8_000,
|
||||
hideCopyButton: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
const syncBrowserOnlineStatus = useEffectEvent(() => {
|
||||
@@ -277,45 +253,45 @@ export function WebSocketConnectionCoordinator() {
|
||||
|
||||
if (shouldShowReconnectToast || shouldShowOfflineToast || shouldShowExhaustedToast) {
|
||||
const toastPayload = shouldShowOfflineToast
|
||||
? stackedThreadToast({
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
? {
|
||||
description: describeOfflineToast(),
|
||||
timeout: 0,
|
||||
title: "Offline",
|
||||
type: "warning",
|
||||
})
|
||||
type: "warning" as const,
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
}
|
||||
: shouldShowExhaustedToast
|
||||
? stackedThreadToast({
|
||||
? {
|
||||
actionProps: {
|
||||
children: "Retry",
|
||||
onClick: triggerManualReconnect,
|
||||
},
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
description: describeExhaustedToast(),
|
||||
timeout: 0,
|
||||
title: "Disconnected from T3 Server",
|
||||
type: "error",
|
||||
})
|
||||
: stackedThreadToast({
|
||||
type: "error" as const,
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
}
|
||||
: {
|
||||
actionProps: {
|
||||
children: "Retry now",
|
||||
onClick: triggerManualReconnect,
|
||||
},
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
description:
|
||||
status.nextRetryAt === null
|
||||
? `Reconnecting... ${formatReconnectAttemptLabel(status)}`
|
||||
: `Reconnecting in ${formatRetryCountdown(status.nextRetryAt, nowMs)}... ${formatReconnectAttemptLabel(status)}`,
|
||||
timeout: 0,
|
||||
title: buildReconnectTitle(status),
|
||||
type: "loading",
|
||||
});
|
||||
type: "loading" as const,
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
};
|
||||
|
||||
if (toastIdRef.current) {
|
||||
toastManager.update(toastIdRef.current, toastPayload);
|
||||
@@ -393,11 +369,6 @@ export function SlowRpcAckToastCoordinator() {
|
||||
}
|
||||
|
||||
const nextToast = {
|
||||
data: {
|
||||
expandableContent: <SlowRpcAckRequestDetails requests={slowRequests} />,
|
||||
expandableDescriptionTrigger: true,
|
||||
expandableLabels: { collapse: "Hide requests", expand: "Show requests" },
|
||||
},
|
||||
description: describeSlowRpcAckToast(slowRequests),
|
||||
timeout: 0,
|
||||
title: "Some requests are slow",
|
||||
|
||||
@@ -6,7 +6,6 @@ import type {
|
||||
ProviderApprovalDecision,
|
||||
ProviderInteractionMode,
|
||||
ProviderKind,
|
||||
ResolvedKeybindingsConfig,
|
||||
RuntimeMode,
|
||||
ScopedThreadRef,
|
||||
ServerProvider,
|
||||
@@ -60,7 +59,7 @@ import {
|
||||
shouldUseCompactComposerFooter,
|
||||
} from "../composerFooterLayout";
|
||||
import { type ComposerPromptEditorHandle, ComposerPromptEditor } from "../ComposerPromptEditor";
|
||||
import { ProviderModelPicker } from "./ProviderModelPicker";
|
||||
import { AVAILABLE_PROVIDER_OPTIONS, ProviderModelPicker } from "./ProviderModelPicker";
|
||||
import { type ComposerCommandItem, ComposerCommandMenu } from "./ComposerCommandMenu";
|
||||
import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions";
|
||||
import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
|
||||
@@ -71,10 +70,11 @@ import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
|
||||
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
|
||||
import { searchSlashCommandItems } from "./composerSlashCommandSearch";
|
||||
import {
|
||||
getComposerProviderControls,
|
||||
getComposerProviderState,
|
||||
renderProviderTraitsMenuContent,
|
||||
renderProviderTraitsPicker,
|
||||
} from "./composerProviderState";
|
||||
} from "./composerProviderRegistry";
|
||||
import { ContextWindowMeter } from "./ContextWindowMeter";
|
||||
import { buildExpandedImagePreview, type ExpandedImagePreview } from "./ExpandedImagePreview";
|
||||
import { basenameOfPath } from "../../vscode-icons";
|
||||
@@ -95,11 +95,7 @@ import {
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { proposedPlanTitle } from "../../proposedPlan";
|
||||
import {
|
||||
getProviderInteractionModeToggle,
|
||||
getProviderModels,
|
||||
resolveSelectableProvider,
|
||||
} from "../../providerModels";
|
||||
import { resolveSelectableProvider, getProviderModels } from "../../providerModels";
|
||||
import type { UnifiedSettings } from "@t3tools/contracts/settings";
|
||||
import type { SessionPhase, Thread } from "../../types";
|
||||
import type { PendingUserInputDraftAnswer } from "../../pendingUserInput";
|
||||
@@ -321,9 +317,6 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
|
||||
export interface ChatComposerHandle {
|
||||
focusAtEnd: () => void;
|
||||
focusAt: (cursor: number) => void;
|
||||
openModelPicker: () => void;
|
||||
toggleModelPicker: () => void;
|
||||
isModelPickerOpen: () => boolean;
|
||||
readSnapshot: () => {
|
||||
value: string;
|
||||
cursor: number;
|
||||
@@ -417,8 +410,6 @@ export interface ChatComposerProps {
|
||||
// Misc
|
||||
resolvedTheme: "light" | "dark";
|
||||
settings: UnifiedSettings;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
terminalOpen: boolean;
|
||||
gitCwd: string | null;
|
||||
|
||||
// Refs the parent needs kept in sync
|
||||
@@ -506,8 +497,6 @@ export const ChatComposer = memo(
|
||||
activeThreadActivities,
|
||||
resolvedTheme,
|
||||
settings,
|
||||
keybindings,
|
||||
terminalOpen,
|
||||
gitCwd,
|
||||
promptRef,
|
||||
composerImagesRef,
|
||||
@@ -598,7 +587,7 @@ export const ChatComposer = memo(
|
||||
model: selectedModel,
|
||||
models: selectedProviderModels,
|
||||
prompt,
|
||||
modelOptions: composerModelOptions?.[selectedProvider],
|
||||
modelOptions: composerModelOptions,
|
||||
}),
|
||||
[composerModelOptions, prompt, selectedModel, selectedProvider, selectedProviderModels],
|
||||
);
|
||||
@@ -606,13 +595,8 @@ export const ChatComposer = memo(
|
||||
const selectedPromptEffort = composerProviderState.promptEffort;
|
||||
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
|
||||
const composerProviderControls = useMemo(
|
||||
() => ({
|
||||
showInteractionModeToggle: getProviderInteractionModeToggle(
|
||||
providerStatuses,
|
||||
selectedProvider,
|
||||
),
|
||||
}),
|
||||
[providerStatuses, selectedProvider],
|
||||
() => getComposerProviderControls(selectedProvider),
|
||||
[selectedProvider],
|
||||
);
|
||||
const selectedModelSelection = useMemo<ModelSelection>(
|
||||
() => createModelSelection(selectedProvider, selectedModel, selectedModelOptionsForDispatch),
|
||||
@@ -638,6 +622,23 @@ export const ChatComposer = memo(
|
||||
? selectedModelForPicker
|
||||
: (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker);
|
||||
}, [modelOptionsByProvider, selectedModelForPicker, selectedProvider]);
|
||||
const searchableModelOptions = useMemo(
|
||||
() =>
|
||||
AVAILABLE_PROVIDER_OPTIONS.filter(
|
||||
(option) => lockedProvider === null || option.value === lockedProvider,
|
||||
).flatMap((option) =>
|
||||
modelOptionsByProvider[option.value].map(({ slug, name }) => ({
|
||||
provider: option.value,
|
||||
providerLabel: option.label,
|
||||
slug,
|
||||
name,
|
||||
searchSlug: slug.toLowerCase(),
|
||||
searchName: name.toLowerCase(),
|
||||
searchProvider: option.label.toLowerCase(),
|
||||
})),
|
||||
),
|
||||
[lockedProvider, modelOptionsByProvider],
|
||||
);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Context window
|
||||
@@ -663,7 +664,6 @@ export const ChatComposer = memo(
|
||||
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
|
||||
const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false);
|
||||
const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false);
|
||||
const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Refs
|
||||
@@ -782,8 +782,31 @@ export const ChatComposer = memo(
|
||||
(skill.scope ? `${skill.scope} skill` : "Run provider skill"),
|
||||
}));
|
||||
}
|
||||
return [];
|
||||
}, [composerTrigger, selectedProvider, selectedProviderStatus, workspaceEntries]);
|
||||
return searchableModelOptions
|
||||
.filter(({ searchSlug, searchName, searchProvider }) => {
|
||||
const query = composerTrigger.query.trim().toLowerCase();
|
||||
if (!query) return true;
|
||||
return (
|
||||
searchSlug.includes(query) ||
|
||||
searchName.includes(query) ||
|
||||
searchProvider.includes(query)
|
||||
);
|
||||
})
|
||||
.map(({ provider, providerLabel, slug, name }) => ({
|
||||
id: `model:${provider}:${slug}`,
|
||||
type: "model",
|
||||
provider,
|
||||
model: slug,
|
||||
label: name,
|
||||
description: `${providerLabel} · ${slug}`,
|
||||
}));
|
||||
}, [
|
||||
composerTrigger,
|
||||
searchableModelOptions,
|
||||
selectedProvider,
|
||||
selectedProviderStatus,
|
||||
workspaceEntries,
|
||||
]);
|
||||
|
||||
const composerMenuOpen = Boolean(composerTrigger);
|
||||
const composerMenuSearchKey = composerTrigger
|
||||
@@ -1253,7 +1276,7 @@ export const ChatComposer = memo(
|
||||
rangeStart: number,
|
||||
rangeEnd: number,
|
||||
replacement: string,
|
||||
options?: { expectedText?: string; focusEditorAfterReplace?: boolean },
|
||||
options?: { expectedText?: string },
|
||||
): boolean => {
|
||||
const currentText = promptRef.current;
|
||||
const safeStart = Math.max(0, Math.min(currentText.length, rangeStart));
|
||||
@@ -1282,11 +1305,9 @@ export const ChatComposer = memo(
|
||||
}
|
||||
setComposerCursor(nextCursor);
|
||||
setComposerTrigger(detectComposerTrigger(next.text, nextExpandedCursor));
|
||||
if (options?.focusEditorAfterReplace !== false) {
|
||||
window.requestAnimationFrame(() => {
|
||||
composerEditorRef.current?.focusAt(nextCursor);
|
||||
});
|
||||
}
|
||||
window.requestAnimationFrame(() => {
|
||||
composerEditorRef.current?.focusAt(nextCursor);
|
||||
});
|
||||
return true;
|
||||
},
|
||||
[
|
||||
@@ -1356,13 +1377,20 @@ export const ChatComposer = memo(
|
||||
}
|
||||
if (item.type === "slash-command") {
|
||||
if (item.command === "model") {
|
||||
const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
|
||||
expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),
|
||||
focusEditorAfterReplace: false,
|
||||
});
|
||||
const replacement = "/model ";
|
||||
const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
|
||||
snapshot.value,
|
||||
trigger.rangeEnd,
|
||||
replacement,
|
||||
);
|
||||
const applied = applyPromptReplacement(
|
||||
trigger.rangeStart,
|
||||
replacementRangeEnd,
|
||||
replacement,
|
||||
{ expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
|
||||
);
|
||||
if (applied) {
|
||||
setComposerHighlightedItemId(null);
|
||||
setIsComposerModelPickerOpen(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1411,8 +1439,20 @@ export const ChatComposer = memo(
|
||||
}
|
||||
return;
|
||||
}
|
||||
onProviderModelSelect(item.provider, item.model);
|
||||
const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
|
||||
expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),
|
||||
});
|
||||
if (applied) {
|
||||
setComposerHighlightedItemId(null);
|
||||
}
|
||||
},
|
||||
[applyPromptReplacement, handleInteractionModeChange, resolveActiveComposerTrigger],
|
||||
[
|
||||
applyPromptReplacement,
|
||||
handleInteractionModeChange,
|
||||
onProviderModelSelect,
|
||||
resolveActiveComposerTrigger,
|
||||
],
|
||||
);
|
||||
|
||||
const onComposerMenuItemHighlighted = useCallback(
|
||||
@@ -1593,13 +1633,6 @@ export const ChatComposer = memo(
|
||||
focusAt: (cursor: number) => {
|
||||
composerEditorRef.current?.focusAt(cursor);
|
||||
},
|
||||
openModelPicker: () => {
|
||||
setIsComposerModelPickerOpen(true);
|
||||
},
|
||||
toggleModelPicker: () => {
|
||||
setIsComposerModelPickerOpen((open) => !open);
|
||||
},
|
||||
isModelPickerOpen: () => isComposerModelPickerOpen,
|
||||
readSnapshot: () => {
|
||||
return readComposerSnapshot();
|
||||
},
|
||||
@@ -1677,7 +1710,6 @@ export const ChatComposer = memo(
|
||||
promptRef,
|
||||
composerImagesRef,
|
||||
composerTerminalContextsRef,
|
||||
isComposerModelPickerOpen,
|
||||
readComposerSnapshot,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
@@ -1893,19 +1925,13 @@ export const ChatComposer = memo(
|
||||
model={selectedModelForPickerWithCustomFallback}
|
||||
lockedProvider={lockedProvider}
|
||||
providers={providerStatuses}
|
||||
keybindings={keybindings}
|
||||
modelOptionsByProvider={modelOptionsByProvider}
|
||||
terminalOpen={terminalOpen}
|
||||
open={isComposerModelPickerOpen}
|
||||
{...(composerProviderState.modelPickerIconClassName
|
||||
? {
|
||||
activeProviderIconClassName:
|
||||
composerProviderState.modelPickerIconClassName,
|
||||
}
|
||||
: {})}
|
||||
onOpenChange={(open) => {
|
||||
setIsComposerModelPickerOpen(open);
|
||||
}}
|
||||
onProviderModelChange={onProviderModelSelect}
|
||||
/>
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ import "../../index.css";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
import { createModelCapabilities, createModelSelection } from "@t3tools/shared/model";
|
||||
|
||||
import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
|
||||
import { TraitsMenuContent } from "./TraitsPicker";
|
||||
@@ -18,34 +17,6 @@ import { useComposerDraftStore } from "../../composerDraftStore";
|
||||
|
||||
const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
|
||||
|
||||
function selectDescriptor(
|
||||
id: string,
|
||||
label: string,
|
||||
options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>,
|
||||
promptInjectedValues?: ReadonlyArray<string>,
|
||||
) {
|
||||
return {
|
||||
id,
|
||||
label,
|
||||
type: "select" as const,
|
||||
options: [...options],
|
||||
...(options.find((option) => option.isDefault)?.id
|
||||
? { currentValue: options.find((option) => option.isDefault)?.id }
|
||||
: {}),
|
||||
...(promptInjectedValues && promptInjectedValues.length > 0
|
||||
? { promptInjectedValues: [...promptInjectedValues] }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function booleanDescriptor(id: string, label: string) {
|
||||
return {
|
||||
id,
|
||||
label,
|
||||
type: "boolean" as const,
|
||||
};
|
||||
}
|
||||
|
||||
async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: string }) {
|
||||
const threadId = ThreadId.make("thread-compact-menu");
|
||||
const threadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId);
|
||||
@@ -62,7 +33,11 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
modelSelectionByProvider: {
|
||||
[provider]: createModelSelection(provider, model, props?.modelSelection?.options),
|
||||
[provider]: {
|
||||
provider,
|
||||
model,
|
||||
...(props?.modelSelection?.options ? { options: props.modelSelection.options } : {}),
|
||||
},
|
||||
},
|
||||
activeProvider: provider,
|
||||
runtimeMode: null,
|
||||
@@ -76,58 +51,74 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
document.body.append(host);
|
||||
const onPromptChange = vi.fn();
|
||||
const providerOptions = props?.modelSelection?.options;
|
||||
const models = [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Claude Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
selectDescriptor(
|
||||
"effort",
|
||||
"Reasoning",
|
||||
[
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium" },
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
{ id: "max", label: "Max" },
|
||||
{ id: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
["ultrathink"],
|
||||
),
|
||||
booleanDescriptor("fastMode", "Fast Mode"),
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "claude-haiku-4-5",
|
||||
name: "Claude Haiku 4.5",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [booleanDescriptor("thinking", "Thinking")],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
name: "Claude Sonnet 4.6",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
selectDescriptor(
|
||||
"effort",
|
||||
"Reasoning",
|
||||
[
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium" },
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
{ id: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
["ultrathink"],
|
||||
),
|
||||
],
|
||||
}),
|
||||
},
|
||||
];
|
||||
const models =
|
||||
provider === "claudeAgent"
|
||||
? [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Claude Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
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",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
]
|
||||
: [
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
];
|
||||
const screen = await render(
|
||||
<CompactComposerControlsMenu
|
||||
activePlan={false}
|
||||
@@ -178,7 +169,7 @@ describe("CompactComposerControlsMenu", () => {
|
||||
|
||||
it("shows fast mode controls for Opus", async () => {
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6"),
|
||||
modelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
|
||||
});
|
||||
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
@@ -186,14 +177,14 @@ describe("CompactComposerControlsMenu", () => {
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("On");
|
||||
expect(text).toContain("Off");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
});
|
||||
|
||||
it("hides fast mode controls for non-Opus Claude models", async () => {
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6"),
|
||||
modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
||||
});
|
||||
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
@@ -205,7 +196,7 @@ describe("CompactComposerControlsMenu", () => {
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6"),
|
||||
modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
||||
});
|
||||
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
@@ -222,9 +213,11 @@ describe("CompactComposerControlsMenu", () => {
|
||||
|
||||
it("shows a Claude thinking on/off section for Haiku", async () => {
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [
|
||||
{ id: "thinking", value: true },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
options: { thinking: true },
|
||||
},
|
||||
});
|
||||
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
@@ -232,16 +225,18 @@ describe("CompactComposerControlsMenu", () => {
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Thinking");
|
||||
expect(text).toContain("On");
|
||||
expect(text).toContain("On (default)");
|
||||
expect(text).toContain("Off");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows prompt-controlled Ultrathink state with selectable effort controls", async () => {
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||
{ id: "effort", value: "high" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: { effort: "high" },
|
||||
},
|
||||
prompt: "Ultrathink:\nInvestigate this",
|
||||
});
|
||||
|
||||
@@ -249,16 +244,18 @@ describe("CompactComposerControlsMenu", () => {
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Reasoning");
|
||||
expect(text).toContain("Effort");
|
||||
expect(text).not.toContain("ultrathink");
|
||||
});
|
||||
});
|
||||
|
||||
it("warns when ultrathink appears in prompt body text", async () => {
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
|
||||
{ id: "effort", value: "high" },
|
||||
]),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: { effort: "high" },
|
||||
},
|
||||
prompt: "Ultrathink:\nplease ultrathink about this problem",
|
||||
});
|
||||
|
||||
@@ -267,7 +264,7 @@ describe("CompactComposerControlsMenu", () => {
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain(
|
||||
'Your prompt contains "ultrathink" in the text. Remove it to change this option.',
|
||||
'Your prompt contains "ultrathink" in the text. Remove it to change effort.',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import { memo, useLayoutEffect, useMemo, useRef } from "react";
|
||||
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
|
||||
import { formatProviderSkillInstallSource } from "~/providerSkillPresentation";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Badge } from "../ui/badge";
|
||||
import {
|
||||
Command,
|
||||
CommandGroup,
|
||||
@@ -44,6 +45,14 @@ export type ComposerCommandItem =
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
type: "model";
|
||||
provider: ProviderKind;
|
||||
model: string;
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
type: "skill";
|
||||
@@ -246,6 +255,11 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
|
||||
<SkillGlyph className="size-3.5" />
|
||||
</span>
|
||||
) : null}
|
||||
{props.item.type === "model" ? (
|
||||
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
|
||||
model
|
||||
</Badge>
|
||||
) : null}
|
||||
<span className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<span className="shrink-0">{props.item.label}</span>
|
||||
<span className="min-w-0 flex-1 truncate text-muted-foreground/70 text-xs">
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
import { type ProviderKind } from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import { StarIcon } from "lucide-react";
|
||||
import {
|
||||
getDisplayModelName,
|
||||
getProviderLabel,
|
||||
getTriggerDisplayModelLabel,
|
||||
type ModelEsque,
|
||||
PROVIDER_ICON_BY_PROVIDER,
|
||||
} from "./providerIconUtils";
|
||||
import { ComboboxItem } from "../ui/combobox";
|
||||
import { Kbd } from "../ui/kbd";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
export const ModelListRow = memo(function ModelListRow(props: {
|
||||
index: number;
|
||||
model: ModelEsque;
|
||||
provider: ProviderKind;
|
||||
isFavorite: boolean;
|
||||
showProvider: boolean;
|
||||
preferShortName?: boolean;
|
||||
useTriggerLabel?: boolean;
|
||||
showNewBadge?: boolean;
|
||||
jumpLabel?: string | null;
|
||||
onToggleFavorite: () => void;
|
||||
}) {
|
||||
const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[props.provider];
|
||||
|
||||
return (
|
||||
<ComboboxItem
|
||||
hideIndicator
|
||||
index={props.index}
|
||||
value={`${props.provider}:${props.model.slug}`}
|
||||
contentClassName="flex w-full items-start gap-2"
|
||||
className={cn(
|
||||
"w-full cursor-pointer rounded px-3 py-2 transition-colors group",
|
||||
"data-highlighted:bg-muted data-selected:bg-accent data-selected:text-foreground",
|
||||
)}
|
||||
>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
className="mt-0.5 shrink-0 cursor-pointer opacity-40 transition-opacity group-hover:opacity-100"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
props.onToggleFavorite();
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
type="button"
|
||||
aria-label={props.isFavorite ? "Remove from favorites" : "Add to favorites"}
|
||||
>
|
||||
<StarIcon
|
||||
className={cn("size-4", props.isFavorite && "fill-current text-yellow-500")}
|
||||
/>
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top" align="center">
|
||||
{props.isFavorite ? "Remove from favorites" : "Add to favorites"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
|
||||
<div className="min-w-0 flex-1 text-left">
|
||||
<div className="flex items-center justify-between gap-2 min-w-0">
|
||||
<div className="text-xs font-medium leading-snug flex items-center gap-2 min-w-0">
|
||||
<span className="truncate">
|
||||
{props.useTriggerLabel
|
||||
? getTriggerDisplayModelLabel(props.model)
|
||||
: getDisplayModelName(
|
||||
props.model,
|
||||
props.preferShortName ? { preferShortName: true } : undefined,
|
||||
)}
|
||||
</span>
|
||||
{props.showNewBadge ? (
|
||||
<span
|
||||
className="shrink-0 rounded border border-amber-500/35 bg-amber-500/15 px-0.5 py-px text-[10px] font-bold uppercase leading-none tracking-wide text-amber-800 dark:border-amber-400/30 dark:bg-amber-400/12 dark:text-amber-200"
|
||||
aria-label="New model"
|
||||
>
|
||||
New
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{props.jumpLabel ? (
|
||||
<Kbd className="h-4 min-w-0 shrink-0 rounded-sm px-1.5 text-[10px]">
|
||||
{props.jumpLabel}
|
||||
</Kbd>
|
||||
) : null}
|
||||
</div>
|
||||
{props.showProvider && (
|
||||
<div className="flex items-center gap-1 mt-0.5">
|
||||
<ProviderIcon className="size-3 shrink-0" />
|
||||
<span className="text-xs font-normal leading-snug text-muted-foreground/70 truncate">
|
||||
{getProviderLabel(props.provider, props.model)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ComboboxItem>
|
||||
);
|
||||
});
|
||||
@@ -1,519 +0,0 @@
|
||||
import {
|
||||
type ProviderKind,
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveSelectableModel } from "@t3tools/shared/model";
|
||||
import { memo, useMemo, useState, useCallback, useEffect, useLayoutEffect, useRef } from "react";
|
||||
import { SearchIcon } from "lucide-react";
|
||||
import { ModelListRow } from "./ModelListRow";
|
||||
import { ModelPickerSidebar } from "./ModelPickerSidebar";
|
||||
import { isModelPickerNewModel } from "./modelPickerModelHighlights";
|
||||
import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch";
|
||||
import { Combobox, ComboboxEmpty, ComboboxInput, ComboboxList } from "../ui/combobox";
|
||||
import { ModelEsque, PROVIDER_ICON_BY_PROVIDER } from "./providerIconUtils";
|
||||
import {
|
||||
modelPickerJumpCommandForIndex,
|
||||
modelPickerJumpIndexFromCommand,
|
||||
resolveShortcutCommand,
|
||||
shortcutLabelForCommand,
|
||||
} from "../../keybindings";
|
||||
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { TooltipProvider } from "../ui/tooltip";
|
||||
|
||||
type ModelPickerItem = {
|
||||
slug: string;
|
||||
name: string;
|
||||
shortName?: string;
|
||||
subProvider?: string;
|
||||
provider: ProviderKind;
|
||||
};
|
||||
|
||||
const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();
|
||||
|
||||
export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
provider: ProviderKind;
|
||||
model: string;
|
||||
lockedProvider: ProviderKind | null;
|
||||
providers?: ReadonlyArray<ServerProvider>;
|
||||
keybindings?: ResolvedKeybindingsConfig;
|
||||
modelOptionsByProvider: Record<ProviderKind, ReadonlyArray<ModelEsque>>;
|
||||
terminalOpen: boolean;
|
||||
onRequestClose?: () => void;
|
||||
onProviderModelChange: (provider: ProviderKind, model: string) => void;
|
||||
}) {
|
||||
const { keybindings: providedKeybindings, modelOptionsByProvider, onProviderModelChange } = props;
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||
const listRegionRef = useRef<HTMLDivElement>(null);
|
||||
const highlightedModelKeyRef = useRef<string | null>(null);
|
||||
const favorites = useSettings((s) => s.favorites ?? []);
|
||||
const [selectedProvider, setSelectedProvider] = useState<ProviderKind | "favorites">(() => {
|
||||
if (props.lockedProvider !== null) {
|
||||
return props.lockedProvider;
|
||||
}
|
||||
return favorites.length > 0 ? "favorites" : props.provider;
|
||||
});
|
||||
const keybindings = useMemo<ResolvedKeybindingsConfig>(
|
||||
() => providedKeybindings ?? [],
|
||||
[providedKeybindings],
|
||||
);
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
|
||||
const focusSearchInput = useCallback(() => {
|
||||
searchInputRef.current?.focus({ preventScroll: true });
|
||||
}, []);
|
||||
|
||||
const handleSelectProvider = useCallback(
|
||||
(provider: ProviderKind | "favorites") => {
|
||||
setSelectedProvider(provider);
|
||||
window.requestAnimationFrame(() => {
|
||||
focusSearchInput();
|
||||
});
|
||||
},
|
||||
[focusSearchInput],
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
focusSearchInput();
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
focusSearchInput();
|
||||
});
|
||||
const timeout = window.setTimeout(() => {
|
||||
focusSearchInput();
|
||||
}, 0);
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frame);
|
||||
window.clearTimeout(timeout);
|
||||
};
|
||||
}, [focusSearchInput]);
|
||||
|
||||
// Create a Set for efficient lookup
|
||||
const favoritesSet = useMemo(() => {
|
||||
return new Set(favorites.map((fav) => `${fav.provider}:${fav.model}`));
|
||||
}, [favorites]);
|
||||
const favoriteOrder = useMemo(() => {
|
||||
return new Map(
|
||||
favorites.map((favorite, index) => [`${favorite.provider}:${favorite.model}`, index]),
|
||||
);
|
||||
}, [favorites]);
|
||||
|
||||
const readyProviderSet = useMemo(() => {
|
||||
if (!props.providers || props.providers.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return new Set(
|
||||
props.providers
|
||||
.filter((provider) => provider.status === "ready")
|
||||
.map((provider) => provider.provider),
|
||||
);
|
||||
}, [props.providers]);
|
||||
|
||||
// Flatten models into a searchable array
|
||||
const flatModels = useMemo(() => {
|
||||
return Object.entries(props.modelOptionsByProvider).flatMap(([providerKind, models]) => {
|
||||
if (readyProviderSet && !readyProviderSet.has(providerKind as ProviderKind)) {
|
||||
return [];
|
||||
}
|
||||
return models.map((m) => ({
|
||||
slug: m.slug,
|
||||
name: m.name,
|
||||
...(m.shortName ? { shortName: m.shortName } : {}),
|
||||
...(m.subProvider ? { subProvider: m.subProvider } : {}),
|
||||
provider: providerKind as ProviderKind,
|
||||
})) satisfies Array<ModelPickerItem>;
|
||||
});
|
||||
}, [props.modelOptionsByProvider, readyProviderSet]);
|
||||
|
||||
// Filter models based on search query and selected provider
|
||||
const filteredModels = useMemo(() => {
|
||||
let result = flatModels;
|
||||
|
||||
// Apply tokenized fuzzy search across the combined provider/model search fields.
|
||||
if (searchQuery.trim()) {
|
||||
const rankedMatches = result
|
||||
.map((model) => ({
|
||||
model,
|
||||
score: scoreModelPickerSearch(
|
||||
{
|
||||
...model,
|
||||
isFavorite: favoritesSet.has(`${model.provider}:${model.slug}`),
|
||||
},
|
||||
searchQuery,
|
||||
),
|
||||
isFavorite: favoritesSet.has(`${model.provider}:${model.slug}`),
|
||||
tieBreaker: buildModelPickerSearchText(model),
|
||||
}))
|
||||
.filter(
|
||||
(
|
||||
rankedModel,
|
||||
): rankedModel is {
|
||||
model: ModelPickerItem;
|
||||
score: number;
|
||||
isFavorite: boolean;
|
||||
tieBreaker: string;
|
||||
} => rankedModel.score !== null,
|
||||
);
|
||||
|
||||
// When searching, we only respect locked provider, ignoring sidebar selection
|
||||
if (props.lockedProvider !== null) {
|
||||
return rankedMatches
|
||||
.filter((rankedModel) => rankedModel.model.provider === props.lockedProvider)
|
||||
.toSorted((a, b) => {
|
||||
const scoreDelta = a.score - b.score;
|
||||
if (scoreDelta !== 0) {
|
||||
return scoreDelta;
|
||||
}
|
||||
if (a.isFavorite !== b.isFavorite) {
|
||||
return a.isFavorite ? -1 : 1;
|
||||
}
|
||||
return a.tieBreaker.localeCompare(b.tieBreaker);
|
||||
})
|
||||
.map((rankedModel) => rankedModel.model);
|
||||
}
|
||||
|
||||
return rankedMatches
|
||||
.toSorted((a, b) => {
|
||||
const scoreDelta = a.score - b.score;
|
||||
if (scoreDelta !== 0) {
|
||||
return scoreDelta;
|
||||
}
|
||||
if (a.isFavorite !== b.isFavorite) {
|
||||
return a.isFavorite ? -1 : 1;
|
||||
}
|
||||
return a.tieBreaker.localeCompare(b.tieBreaker);
|
||||
})
|
||||
.map((rankedModel) => rankedModel.model);
|
||||
}
|
||||
|
||||
// Locked provider mode always shows that provider's models, with favorites first.
|
||||
if (props.lockedProvider !== null) {
|
||||
result = result.filter((m) => m.provider === props.lockedProvider);
|
||||
} else if (selectedProvider === "favorites") {
|
||||
result = result.filter((m) => favoritesSet.has(`${m.provider}:${m.slug}`));
|
||||
} else {
|
||||
result = result.filter((m) => m.provider === selectedProvider);
|
||||
}
|
||||
|
||||
return result.toSorted((a, b) => {
|
||||
const aOrder = favoriteOrder.get(`${a.provider}:${a.slug}`);
|
||||
const bOrder = favoriteOrder.get(`${b.provider}:${b.slug}`);
|
||||
|
||||
if (aOrder !== undefined && bOrder !== undefined) {
|
||||
return aOrder - bOrder;
|
||||
}
|
||||
if (aOrder !== undefined) {
|
||||
return -1;
|
||||
}
|
||||
if (bOrder !== undefined) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}, [
|
||||
favoriteOrder,
|
||||
favoritesSet,
|
||||
flatModels,
|
||||
props.lockedProvider,
|
||||
searchQuery,
|
||||
selectedProvider,
|
||||
]);
|
||||
|
||||
const handleModelSelect = useCallback(
|
||||
(modelSlug: string, provider: ProviderKind) => {
|
||||
const resolvedModel = resolveSelectableModel(
|
||||
provider,
|
||||
modelSlug,
|
||||
modelOptionsByProvider[provider],
|
||||
);
|
||||
if (resolvedModel) {
|
||||
onProviderModelChange(provider, resolvedModel);
|
||||
}
|
||||
},
|
||||
[modelOptionsByProvider, onProviderModelChange],
|
||||
);
|
||||
|
||||
const toggleFavorite = useCallback(
|
||||
(provider: ProviderKind, model: string) => {
|
||||
const newFavorites = [...favorites];
|
||||
const index = newFavorites.findIndex((f) => f.provider === provider && f.model === model);
|
||||
if (index >= 0) {
|
||||
newFavorites.splice(index, 1);
|
||||
} else {
|
||||
newFavorites.push({ provider, model });
|
||||
}
|
||||
updateSettings({ favorites: newFavorites });
|
||||
},
|
||||
[favorites, updateSettings],
|
||||
);
|
||||
|
||||
const isLocked = props.lockedProvider !== null;
|
||||
const isSearching = searchQuery.trim().length > 0;
|
||||
const showSidebar = !isLocked && !isSearching;
|
||||
const LockedProviderIcon =
|
||||
isLocked && props.lockedProvider ? PROVIDER_ICON_BY_PROVIDER[props.lockedProvider] : null;
|
||||
const modelJumpCommandByKey = useMemo(() => {
|
||||
const mapping = new Map<
|
||||
string,
|
||||
NonNullable<ReturnType<typeof modelPickerJumpCommandForIndex>>
|
||||
>();
|
||||
for (const [visibleModelIndex, model] of filteredModels.entries()) {
|
||||
const jumpCommand = modelPickerJumpCommandForIndex(visibleModelIndex);
|
||||
if (!jumpCommand) {
|
||||
return mapping;
|
||||
}
|
||||
mapping.set(`${model.provider}:${model.slug}`, jumpCommand);
|
||||
}
|
||||
return mapping;
|
||||
}, [filteredModels]);
|
||||
const modelJumpModelKeys = useMemo(
|
||||
() => [...modelJumpCommandByKey.keys()],
|
||||
[modelJumpCommandByKey],
|
||||
);
|
||||
const allModelKeys = useMemo(
|
||||
(): string[] => flatModels.map((model) => `${model.provider}:${model.slug}`),
|
||||
[flatModels],
|
||||
);
|
||||
const filteredModelKeys = useMemo(
|
||||
(): string[] => filteredModels.map((model) => `${model.provider}:${model.slug}`),
|
||||
[filteredModels],
|
||||
);
|
||||
const filteredModelByKey = useMemo(
|
||||
(): ReadonlyMap<string, ModelPickerItem> =>
|
||||
new Map(filteredModels.map((model) => [`${model.provider}:${model.slug}`, model] as const)),
|
||||
[filteredModels],
|
||||
);
|
||||
const modelJumpShortcutContext = useMemo(
|
||||
() =>
|
||||
({
|
||||
terminalFocus: false,
|
||||
terminalOpen: props.terminalOpen,
|
||||
modelPickerOpen: true,
|
||||
}) as const,
|
||||
[props.terminalOpen],
|
||||
);
|
||||
const modelJumpLabelByKey = useMemo((): ReadonlyMap<string, string> => {
|
||||
if (modelJumpCommandByKey.size === 0) {
|
||||
return EMPTY_MODEL_JUMP_LABELS;
|
||||
}
|
||||
const shortcutLabelOptions = {
|
||||
platform: navigator.platform,
|
||||
context: modelJumpShortcutContext,
|
||||
};
|
||||
const mapping = new Map<string, string>();
|
||||
for (const [modelKey, command] of modelJumpCommandByKey) {
|
||||
const label = shortcutLabelForCommand(keybindings, command, shortcutLabelOptions);
|
||||
if (label) {
|
||||
mapping.set(modelKey, label);
|
||||
}
|
||||
}
|
||||
return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS;
|
||||
}, [keybindings, modelJumpCommandByKey, modelJumpShortcutContext]);
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.defaultPrevented || event.repeat) {
|
||||
return;
|
||||
}
|
||||
|
||||
const command = resolveShortcutCommand(event, keybindings, {
|
||||
platform: navigator.platform,
|
||||
context: modelJumpShortcutContext,
|
||||
});
|
||||
const jumpIndex = modelPickerJumpIndexFromCommand(command ?? "");
|
||||
if (jumpIndex === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetModelKey = modelJumpModelKeys[jumpIndex];
|
||||
if (!targetModelKey) {
|
||||
return;
|
||||
}
|
||||
const [provider, slug] = targetModelKey.split(":") as [ProviderKind, string];
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleModelSelect(slug, provider);
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown, true);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown, true);
|
||||
};
|
||||
}, [handleModelSelect, keybindings, modelJumpModelKeys, modelJumpShortcutContext]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const listRegion = listRegionRef.current;
|
||||
if (!listRegion) {
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
let frame = 0;
|
||||
let nestedFrame = 0;
|
||||
let timeout = 0;
|
||||
|
||||
const measureScrollArea = () => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
const viewport = listRegion.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]');
|
||||
if (!viewport || viewport.scrollHeight <= viewport.clientHeight) {
|
||||
return;
|
||||
}
|
||||
const originalScrollTop = viewport.scrollTop;
|
||||
const maxScrollTop = viewport.scrollHeight - viewport.clientHeight;
|
||||
if (maxScrollTop <= 0) {
|
||||
return;
|
||||
}
|
||||
viewport.scrollTop = Math.min(originalScrollTop + 1, maxScrollTop);
|
||||
viewport.scrollTop = originalScrollTop;
|
||||
};
|
||||
|
||||
queueMicrotask(measureScrollArea);
|
||||
frame = window.requestAnimationFrame(() => {
|
||||
measureScrollArea();
|
||||
nestedFrame = window.requestAnimationFrame(measureScrollArea);
|
||||
});
|
||||
timeout = window.setTimeout(measureScrollArea, 0);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.cancelAnimationFrame(frame);
|
||||
window.cancelAnimationFrame(nestedFrame);
|
||||
window.clearTimeout(timeout);
|
||||
};
|
||||
}, [filteredModelKeys]);
|
||||
|
||||
return (
|
||||
<TooltipProvider delay={0}>
|
||||
<div
|
||||
className={cn(
|
||||
"relative flex h-screen max-h-96 w-screen max-w-100 overflow-hidden rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
||||
isLocked ? "flex-col" : "flex-row",
|
||||
)}
|
||||
>
|
||||
{/* Locked provider header (only shown in locked mode) */}
|
||||
{isLocked && LockedProviderIcon && props.lockedProvider && (
|
||||
<div className="flex items-center gap-2 px-4 py-3 border-b">
|
||||
<LockedProviderIcon className="size-5 shrink-0" />
|
||||
<span className="font-medium text-sm">
|
||||
{PROVIDER_DISPLAY_NAMES[props.lockedProvider]}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Sidebar (only in unlocked mode) */}
|
||||
{showSidebar && (
|
||||
<ModelPickerSidebar
|
||||
selectedProvider={selectedProvider}
|
||||
onSelectProvider={handleSelectProvider}
|
||||
{...(props.providers && { providers: props.providers })}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Main content area */}
|
||||
<Combobox
|
||||
inline
|
||||
items={allModelKeys}
|
||||
filteredItems={filteredModelKeys}
|
||||
filter={null}
|
||||
autoHighlight
|
||||
open
|
||||
value={`${props.provider}:${props.model}`}
|
||||
onItemHighlighted={(modelKey) => {
|
||||
highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null;
|
||||
}}
|
||||
onValueChange={(modelKey) => {
|
||||
if (typeof modelKey !== "string") {
|
||||
return;
|
||||
}
|
||||
const [provider, slug] = modelKey.split(":") as [ProviderKind, string];
|
||||
handleModelSelect(slug, provider);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col overflow-hidden",
|
||||
isLocked ? "min-w-0" : showSidebar && "border-l",
|
||||
)}
|
||||
>
|
||||
{/* Search bar */}
|
||||
<div className="border-b px-3 py-2">
|
||||
<ComboboxInput
|
||||
ref={searchInputRef}
|
||||
className="[&_input]:font-sans rounded-md"
|
||||
inputClassName="border-0 shadow-none ring-0 focus-visible:ring-0"
|
||||
placeholder="Search models..."
|
||||
showTrigger={false}
|
||||
startAddon={<SearchIcon className="size-4 shrink-0 text-muted-foreground/50" />}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
props.onRequestClose?.();
|
||||
return;
|
||||
}
|
||||
if (e.key === "Enter" && highlightedModelKeyRef.current) {
|
||||
(
|
||||
e as typeof e & { preventBaseUIHandler?: () => void }
|
||||
).preventBaseUIHandler?.();
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const [provider, slug] = highlightedModelKeyRef.current.split(":") as [
|
||||
ProviderKind,
|
||||
string,
|
||||
];
|
||||
handleModelSelect(slug, provider);
|
||||
return;
|
||||
}
|
||||
e.stopPropagation();
|
||||
}}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onTouchStart={(e) => e.stopPropagation()}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Model list */}
|
||||
<div
|
||||
ref={listRegionRef}
|
||||
className="relative min-h-0 flex-1 before:pointer-events-none before:absolute before:inset-0 before:bg-muted/40"
|
||||
>
|
||||
<ComboboxList className="model-picker-list size-full divide-y px-2 py-1">
|
||||
{filteredModelKeys.map((modelKey, index) => {
|
||||
const model = filteredModelByKey.get(modelKey);
|
||||
if (!model) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<ModelListRow
|
||||
key={modelKey}
|
||||
index={index}
|
||||
model={model}
|
||||
provider={model.provider}
|
||||
isFavorite={favoritesSet.has(modelKey)}
|
||||
showProvider={!isLocked}
|
||||
preferShortName={!isLocked}
|
||||
useTriggerLabel={isLocked}
|
||||
showNewBadge={isModelPickerNewModel(model.provider, model.slug)}
|
||||
jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null}
|
||||
onToggleFavorite={() => toggleFavorite(model.provider, model.slug)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</ComboboxList>
|
||||
</div>
|
||||
<ComboboxEmpty className="not-empty:py-6 empty:h-0 text-xs font-normal leading-snug">
|
||||
No models found
|
||||
</ComboboxEmpty>
|
||||
</div>
|
||||
</Combobox>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
);
|
||||
});
|
||||
Loaded 100 of 187 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user