Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8c367df4a | ||
|
|
ea3e9987d7 | ||
|
|
12ecd648ba | ||
|
|
d8a485ea7e | ||
|
|
e980a2fd8f | ||
|
|
02989fe600 | ||
|
|
648f0676bd | ||
|
|
add5f34619 | ||
|
|
9403429a7a | ||
|
|
37cf0c1144 | ||
|
|
bf1f3e1c4f | ||
|
|
2aa11ae076 | ||
|
|
8888f6a0c9 |
No files matched your search
@@ -0,0 +1,245 @@
|
||||
import crypto from "node:crypto";
|
||||
import type { IncomingHttpHeaders } from "node:http";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path, Ref, Schema, ServiceMap } from "effect";
|
||||
|
||||
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
|
||||
const BOOTSTRAP_TOKEN_TTL_MS = 5 * 60 * 1_000;
|
||||
const AUTH_COOKIE_MAX_AGE_SECONDS = 30 * 24 * 60 * 60;
|
||||
const AUTH_COOKIE_NAME = "t3_auth";
|
||||
const BOOTSTRAP_HASH_KEY = "t3_bootstrap";
|
||||
const COOKIE_SECRET_FILENAME = "browser-auth-secret";
|
||||
|
||||
interface BootstrapState {
|
||||
readonly token: string;
|
||||
readonly expiresAt: number;
|
||||
readonly consumedAt: number | null;
|
||||
}
|
||||
|
||||
interface AuthCookiePayload {
|
||||
readonly v: 1;
|
||||
readonly purpose: "browser-auth";
|
||||
readonly iat: number;
|
||||
readonly exp: number;
|
||||
}
|
||||
|
||||
export class BrowserAuthError extends Schema.TaggedErrorClass<BrowserAuthError>()(
|
||||
"BrowserAuthError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
export interface BrowserAuthShape {
|
||||
readonly getPairingUrl: (baseUrl: string) => Effect.Effect<string, never>;
|
||||
readonly getAllowedOrigins: Effect.Effect<ReadonlySet<string>, never>;
|
||||
readonly isAllowedOrigin: (origin: string | undefined) => Effect.Effect<boolean, never>;
|
||||
readonly consumeBootstrapToken: (token: string) => Effect.Effect<boolean, never>;
|
||||
readonly isAuthenticatedRequest: (headers: IncomingHttpHeaders) => Effect.Effect<boolean, never>;
|
||||
readonly createAuthCookie: (isSecure: boolean) => Effect.Effect<string, never>;
|
||||
}
|
||||
|
||||
export class BrowserAuth extends ServiceMap.Service<BrowserAuth, BrowserAuthShape>()(
|
||||
"t3/browserAuth",
|
||||
) {}
|
||||
|
||||
function makeBootstrapToken(): string {
|
||||
return crypto.randomBytes(32).toString("base64url");
|
||||
}
|
||||
|
||||
function makeCookieSecret(): string {
|
||||
return crypto.randomBytes(32).toString("base64url");
|
||||
}
|
||||
|
||||
function toBase64Url(input: string): string {
|
||||
return Buffer.from(input, "utf8").toString("base64url");
|
||||
}
|
||||
|
||||
function fromBase64Url(input: string): string {
|
||||
return Buffer.from(input, "base64url").toString("utf8");
|
||||
}
|
||||
|
||||
function signCookie(payload: AuthCookiePayload, secret: string): string {
|
||||
const payloadEncoded = toBase64Url(JSON.stringify(payload));
|
||||
const signature = crypto.createHmac("sha256", secret).update(payloadEncoded).digest("base64url");
|
||||
return `${payloadEncoded}.${signature}`;
|
||||
}
|
||||
|
||||
function verifyCookie(cookie: string, secret: string, now = Date.now()): boolean {
|
||||
const separatorIndex = cookie.lastIndexOf(".");
|
||||
if (separatorIndex <= 0 || separatorIndex >= cookie.length - 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const payloadEncoded = cookie.slice(0, separatorIndex);
|
||||
const providedSignature = cookie.slice(separatorIndex + 1);
|
||||
const expectedSignature = crypto
|
||||
.createHmac("sha256", secret)
|
||||
.update(payloadEncoded)
|
||||
.digest("base64url");
|
||||
|
||||
const providedBuffer = Buffer.from(providedSignature, "utf8");
|
||||
const expectedBuffer = Buffer.from(expectedSignature, "utf8");
|
||||
if (providedBuffer.length !== expectedBuffer.length) {
|
||||
return false;
|
||||
}
|
||||
if (!crypto.timingSafeEqual(providedBuffer, expectedBuffer)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(fromBase64Url(payloadEncoded)) as Partial<AuthCookiePayload>;
|
||||
if (parsed.v !== 1 || parsed.purpose !== "browser-auth") {
|
||||
return false;
|
||||
}
|
||||
if (typeof parsed.exp !== "number" || !Number.isFinite(parsed.exp)) {
|
||||
return false;
|
||||
}
|
||||
return parsed.exp > now;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function parseCookies(cookieHeader: string | string[] | undefined): Map<string, string> {
|
||||
const raw = Array.isArray(cookieHeader) ? cookieHeader.join("; ") : cookieHeader;
|
||||
if (!raw) return new Map();
|
||||
|
||||
const cookies = new Map<string, string>();
|
||||
for (const segment of raw.split(";")) {
|
||||
const trimmed = segment.trim();
|
||||
if (trimmed.length === 0) continue;
|
||||
const separatorIndex = trimmed.indexOf("=");
|
||||
if (separatorIndex <= 0) continue;
|
||||
const key = trimmed.slice(0, separatorIndex).trim();
|
||||
const value = trimmed.slice(separatorIndex + 1).trim();
|
||||
if (key.length === 0 || value.length === 0) continue;
|
||||
cookies.set(key, value);
|
||||
}
|
||||
return cookies;
|
||||
}
|
||||
|
||||
function normalizeOriginSet(serverConfig: ServerConfigShape): ReadonlySet<string> {
|
||||
const origins = new Set<string>();
|
||||
origins.add(`http://localhost:${serverConfig.port}`);
|
||||
origins.add(`http://127.0.0.1:${serverConfig.port}`);
|
||||
origins.add(`http://[::1]:${serverConfig.port}`);
|
||||
|
||||
if (
|
||||
serverConfig.host &&
|
||||
serverConfig.host !== "0.0.0.0" &&
|
||||
serverConfig.host !== "::" &&
|
||||
serverConfig.host !== "[::]"
|
||||
) {
|
||||
const host =
|
||||
serverConfig.host.includes(":") && !serverConfig.host.startsWith("[")
|
||||
? `[${serverConfig.host}]`
|
||||
: serverConfig.host;
|
||||
origins.add(`http://${host}:${serverConfig.port}`);
|
||||
}
|
||||
|
||||
if (serverConfig.devUrl) {
|
||||
origins.add(serverConfig.devUrl.origin);
|
||||
}
|
||||
|
||||
return origins;
|
||||
}
|
||||
|
||||
function formatAuthCookie(cookieValue: string, isSecure: boolean): string {
|
||||
const attributes = [
|
||||
`${AUTH_COOKIE_NAME}=${cookieValue}`,
|
||||
"HttpOnly",
|
||||
"Path=/",
|
||||
"SameSite=Strict",
|
||||
`Max-Age=${AUTH_COOKIE_MAX_AGE_SECONDS}`,
|
||||
];
|
||||
if (isSecure) {
|
||||
attributes.push("Secure");
|
||||
}
|
||||
return attributes.join("; ");
|
||||
}
|
||||
|
||||
export const BrowserAuthLive = Layer.effect(
|
||||
BrowserAuth,
|
||||
Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const cookieSecretPath = path.join(serverConfig.stateDir, COOKIE_SECRET_FILENAME);
|
||||
|
||||
const existingSecret = yield* fileSystem
|
||||
.readFileString(cookieSecretPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
const cookieSecret =
|
||||
existingSecret && existingSecret.trim().length > 0
|
||||
? existingSecret.trim()
|
||||
: makeCookieSecret();
|
||||
|
||||
if (existingSecret === null || existingSecret.trim().length === 0) {
|
||||
yield* fileSystem.makeDirectory(path.dirname(cookieSecretPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(cookieSecretPath, `${cookieSecret}\n`);
|
||||
}
|
||||
|
||||
const bootstrapState = yield* Ref.make<BootstrapState>({
|
||||
token: makeBootstrapToken(),
|
||||
expiresAt: Date.now() + BOOTSTRAP_TOKEN_TTL_MS,
|
||||
consumedAt: null,
|
||||
});
|
||||
const allowedOrigins = normalizeOriginSet(serverConfig);
|
||||
|
||||
const getPairingUrl: BrowserAuthShape["getPairingUrl"] = (baseUrl) =>
|
||||
Ref.get(bootstrapState).pipe(
|
||||
Effect.map((state) => {
|
||||
const target = new URL(baseUrl);
|
||||
target.hash = `${BOOTSTRAP_HASH_KEY}=${state.token}`;
|
||||
return target.toString();
|
||||
}),
|
||||
);
|
||||
|
||||
const isAllowedOrigin: BrowserAuthShape["isAllowedOrigin"] = (origin) =>
|
||||
Effect.succeed(typeof origin === "string" && allowedOrigins.has(origin));
|
||||
|
||||
const consumeBootstrapToken: BrowserAuthShape["consumeBootstrapToken"] = (token) =>
|
||||
Ref.modify(bootstrapState, (state) => {
|
||||
const now = Date.now();
|
||||
const matches =
|
||||
token.length > 0 &&
|
||||
state.consumedAt === null &&
|
||||
state.expiresAt > now &&
|
||||
state.token === token;
|
||||
return [matches, matches ? { ...state, consumedAt: now } : state] as const;
|
||||
});
|
||||
|
||||
const isAuthenticatedRequest: BrowserAuthShape["isAuthenticatedRequest"] = (headers) =>
|
||||
Effect.succeed(
|
||||
verifyCookie(parseCookies(headers.cookie).get(AUTH_COOKIE_NAME) ?? "", cookieSecret),
|
||||
);
|
||||
|
||||
const createAuthCookie: BrowserAuthShape["createAuthCookie"] = (isSecure) =>
|
||||
Effect.succeed(
|
||||
formatAuthCookie(
|
||||
signCookie(
|
||||
{
|
||||
v: 1,
|
||||
purpose: "browser-auth",
|
||||
iat: Date.now(),
|
||||
exp: Date.now() + AUTH_COOKIE_MAX_AGE_SECONDS * 1_000,
|
||||
},
|
||||
cookieSecret,
|
||||
),
|
||||
isSecure,
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
getPairingUrl,
|
||||
getAllowedOrigins: Effect.succeed(allowedOrigins),
|
||||
isAllowedOrigin,
|
||||
consumeBootstrapToken,
|
||||
isAuthenticatedRequest,
|
||||
createAuthCookie,
|
||||
} satisfies BrowserAuthShape;
|
||||
}),
|
||||
);
|
||||
@@ -11,6 +11,7 @@ import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ClaudeModelSelection } from "@t3tools/contracts";
|
||||
import { resolveApiModelId } from "@t3tools/shared/model";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
@@ -103,7 +104,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
"--json-schema",
|
||||
jsonSchemaStr,
|
||||
"--model",
|
||||
modelSelection.model,
|
||||
resolveApiModelId(modelSelection),
|
||||
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
|
||||
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
|
||||
"--dangerously-skip-permissions",
|
||||
|
||||
@@ -674,6 +674,7 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
|
||||
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||
Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)),
|
||||
Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
|
||||
@@ -259,7 +259,7 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.port, 4666);
|
||||
assert.equal(resolvedConfig?.host, undefined);
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.1");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -301,6 +301,19 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses fixed loopback defaults in web mode", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([], {
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.1");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows overriding desktop host with --host", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--host", "0.0.0.0"], {
|
||||
|
||||
+37
-13
@@ -29,6 +29,7 @@ import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { readBootstrapEnvelope } from "./bootstrap";
|
||||
import { ServerSettingsLive } from "./serverSettings";
|
||||
import { BrowserAuth, BrowserAuthLive } from "./browserAuth";
|
||||
|
||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||
readonly message: string;
|
||||
@@ -268,7 +269,7 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
() => "127.0.0.1",
|
||||
);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
@@ -291,20 +292,28 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
);
|
||||
|
||||
const LayerLive = (input: CliInput) =>
|
||||
Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
(() => {
|
||||
const serverConfigLayer = ServerConfigLive(input);
|
||||
const browserAuthLayer = BrowserAuthLive.pipe(Layer.provide(serverConfigLayer));
|
||||
return Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(browserAuthLayer),
|
||||
);
|
||||
})();
|
||||
|
||||
const isWildcardHost = (host: string | undefined): boolean =>
|
||||
host === "0.0.0.0" || host === "::" || host === "[::]";
|
||||
|
||||
const isLoopbackHost = (host: string | undefined): boolean =>
|
||||
host === "127.0.0.1" || host === "::1" || host === "[::1]" || host === "localhost";
|
||||
|
||||
const formatHostForUrl = (host: string): string =>
|
||||
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
|
||||
@@ -337,6 +346,7 @@ const makeServerRuntimeProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const { start, stopSignal } = yield* Server;
|
||||
const openDeps = yield* Open;
|
||||
const browserAuth = yield* BrowserAuth;
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
|
||||
@@ -357,15 +367,29 @@ const makeServerRuntimeProgram = (input: CliInput) =>
|
||||
config.host && !isWildcardHost(config.host)
|
||||
? `http://${formatHostForUrl(config.host)}:${config.port}`
|
||||
: localUrl;
|
||||
const browserBaseUrl =
|
||||
config.host && !isWildcardHost(config.host) && !isLoopbackHost(config.host)
|
||||
? bindUrl
|
||||
: localUrl;
|
||||
const pairingUrl = yield* browserAuth.getPairingUrl(browserBaseUrl);
|
||||
const { authToken, devUrl, ...safeConfig } = config;
|
||||
yield* Effect.logInfo("T3 Code running", {
|
||||
...safeConfig,
|
||||
devUrl: devUrl?.toString(),
|
||||
authEnabled: Boolean(authToken),
|
||||
localUrl,
|
||||
pairingUrl,
|
||||
});
|
||||
|
||||
if (config.host && !isWildcardHost(config.host) && !isLoopbackHost(config.host)) {
|
||||
yield* Effect.logWarning("server is exposed beyond loopback", {
|
||||
host: config.host,
|
||||
bindUrl,
|
||||
});
|
||||
}
|
||||
|
||||
if (!config.noBrowser) {
|
||||
const target = config.devUrl?.toString() ?? bindUrl;
|
||||
const target = pairingUrl;
|
||||
yield* openDeps.openBrowser(target).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.logInfo("browser auto-open unavailable", {
|
||||
@@ -416,7 +440,7 @@ const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
||||
Flag.optional,
|
||||
);
|
||||
const authTokenFlag = Flag.string("auth-token").pipe(
|
||||
Flag.withDescription("Auth token required for WebSocket connections."),
|
||||
Flag.withDescription("Legacy auth token for non-browser WebSocket clients."),
|
||||
Flag.withAlias("token"),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
@@ -40,6 +40,24 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLaunch, {
|
||||
command: "code-insiders",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodiumLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLaunch, {
|
||||
command: "codium",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const zedLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
"darwin",
|
||||
@@ -80,6 +98,24 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLineAndColumn, {
|
||||
command: "code-insiders",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLineAndColumn, {
|
||||
command: "codium",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
"darwin",
|
||||
@@ -220,13 +256,14 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
|
||||
yield* fs.writeFileString(path.join(dir, "cursor.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["cursor", "file-manager"]);
|
||||
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -39,10 +39,8 @@ interface CommandAvailabilityOptions {
|
||||
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
|
||||
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
|
||||
return (
|
||||
(editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target)
|
||||
);
|
||||
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
|
||||
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
@@ -213,7 +211,7 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
}
|
||||
|
||||
if (editorDef.command) {
|
||||
return shouldUseGotoFlag(editorDef.id, input.cwd)
|
||||
return shouldUseGotoFlag(editorDef, input.cwd)
|
||||
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
||||
: { command: editorDef.command, args: [input.cwd] };
|
||||
}
|
||||
|
||||
@@ -424,43 +424,30 @@ const make = Effect.gen(function* () {
|
||||
const oldBranch = input.branch;
|
||||
const cwd = input.worktreePath;
|
||||
const attachments = input.attachments ?? [];
|
||||
yield* Effect.flatMap(
|
||||
Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.textGenerationModelSelection,
|
||||
),
|
||||
(modelSelection) =>
|
||||
textGeneration.generateBranchName({
|
||||
cwd,
|
||||
message: input.messageText,
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
modelSelection,
|
||||
}),
|
||||
).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
"provider command reactor failed to generate worktree branch name; skipping rename",
|
||||
{ threadId: input.threadId, cwd, oldBranch, reason: error.message },
|
||||
),
|
||||
),
|
||||
Effect.flatMap((generated) => {
|
||||
if (!generated) return Effect.void;
|
||||
yield* Effect.gen(function* () {
|
||||
const { textGenerationModelSelection: modelSelection } =
|
||||
yield* serverSettingsService.getSettings;
|
||||
|
||||
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
||||
if (targetBranch === oldBranch) return Effect.void;
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd,
|
||||
message: input.messageText,
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
modelSelection,
|
||||
});
|
||||
if (!generated) return;
|
||||
|
||||
return Effect.flatMap(
|
||||
git.renameBranch({ cwd, oldBranch, newBranch: targetBranch }),
|
||||
(renamed) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: serverCommandId("worktree-branch-rename"),
|
||||
threadId: input.threadId,
|
||||
branch: renamed.branch,
|
||||
worktreePath: cwd,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
||||
if (targetBranch === oldBranch) return;
|
||||
|
||||
const renamed = yield* git.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: serverCommandId("worktree-branch-rename"),
|
||||
threadId: input.threadId,
|
||||
branch: renamed.branch,
|
||||
worktreePath: cwd,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
|
||||
threadId: input.threadId,
|
||||
|
||||
@@ -347,7 +347,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("ignores unsupported max effort for Sonnet 4.6", () => {
|
||||
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
@@ -365,7 +365,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, undefined);
|
||||
assert.equal(createInput?.options.effort, "high");
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -532,7 +532,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, undefined);
|
||||
assert.equal(createInput?.options.effort, "high");
|
||||
const promptText = yield* Effect.promise(() => readFirstPromptText(createInput));
|
||||
assert.equal(promptText, "Ultrathink:\nInvestigate the edge cases");
|
||||
}).pipe(
|
||||
|
||||
@@ -40,7 +40,12 @@ import {
|
||||
type UserInputQuestion,
|
||||
ClaudeCodeEffort,
|
||||
} from "@t3tools/contracts";
|
||||
import { hasEffortLevel, applyClaudePromptEffortPrefix, trimOrNull } from "@t3tools/shared/model";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
resolveApiModelId,
|
||||
resolveEffort,
|
||||
trimOrNull,
|
||||
} from "@t3tools/shared/model";
|
||||
import {
|
||||
Cause,
|
||||
DateTime,
|
||||
@@ -506,16 +511,15 @@ const CLAUDE_SETTING_SOURCES = [
|
||||
function buildPromptText(input: ProviderSendTurnInput): string {
|
||||
const rawEffort =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.options?.effort : null;
|
||||
const requestedEffort = trimOrNull(rawEffort);
|
||||
const claudeModel =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined;
|
||||
const caps = getClaudeModelCapabilities(claudeModel);
|
||||
|
||||
// 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 =
|
||||
requestedEffort === "ultrathink" && caps.reasoningEffortLevels.length > 0
|
||||
? "ultrathink"
|
||||
: requestedEffort && hasEffortLevel(caps, requestedEffort)
|
||||
? requestedEffort
|
||||
: null;
|
||||
trimmedEffort && caps.promptInjectedEffortLevels.includes(trimmedEffort) ? trimmedEffort : null;
|
||||
return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort);
|
||||
}
|
||||
|
||||
@@ -2727,10 +2731,10 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
const claudeBinaryPath = claudeSettings.binaryPath;
|
||||
const modelSelection =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
|
||||
const requestedEffort = trimOrNull(modelSelection?.options?.effort ?? null);
|
||||
const caps = getClaudeModelCapabilities(modelSelection?.model);
|
||||
const effort =
|
||||
requestedEffort && hasEffortLevel(caps, requestedEffort) ? requestedEffort : null;
|
||||
const apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined;
|
||||
const effort = (resolveEffort(caps, modelSelection?.options?.effort) ??
|
||||
null) as ClaudeCodeEffort | null;
|
||||
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
|
||||
const thinking =
|
||||
typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
|
||||
@@ -2746,7 +2750,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
|
||||
const queryOptions: ClaudeQueryOptions = {
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(modelSelection?.model ? { model: modelSelection.model } : {}),
|
||||
...(apiModelId ? { model: apiModelId } : {}),
|
||||
pathToClaudeCodeExecutable: claudeBinaryPath,
|
||||
settingSources: [...CLAUDE_SETTING_SOURCES],
|
||||
...(effectiveEffort ? { effort: effectiveEffort } : {}),
|
||||
@@ -2840,7 +2844,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
threadId,
|
||||
payload: {
|
||||
config: {
|
||||
...(modelSelection?.model ? { model: modelSelection.model } : {}),
|
||||
...(apiModelId ? { model: apiModelId } : {}),
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(effectiveEffort ? { effort: effectiveEffort } : {}),
|
||||
...(permissionMode ? { permissionMode } : {}),
|
||||
@@ -2893,8 +2897,9 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
}
|
||||
|
||||
if (modelSelection?.model) {
|
||||
const apiModelId = resolveApiModelId(modelSelection);
|
||||
yield* Effect.tryPromise({
|
||||
try: () => context.query.setModel(modelSelection.model),
|
||||
try: () => context.query.setModel(apiModelId),
|
||||
catch: (cause) => toRequestError(input.threadId, "turn/setModel", cause),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Equal, Layer, Option, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { getDefaultEffort, hasEffortLevel, trimOrNull } from "@t3tools/shared/model";
|
||||
import { resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
@@ -42,6 +42,10 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
@@ -58,6 +62,10 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
@@ -69,6 +77,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
@@ -81,6 +90,7 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
}
|
||||
);
|
||||
@@ -91,23 +101,16 @@ export function normalizeClaudeModelOptions(
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): ClaudeModelOptions | undefined {
|
||||
const caps = getClaudeModelCapabilities(model);
|
||||
const defaultReasoningEffort = getDefaultEffort(caps);
|
||||
const resolvedEffort = trimOrNull(modelOptions?.effort);
|
||||
const isPromptInjected = caps.promptInjectedEffortLevels.includes(resolvedEffort ?? "");
|
||||
const effort =
|
||||
resolvedEffort &&
|
||||
!isPromptInjected &&
|
||||
hasEffortLevel(caps, resolvedEffort) &&
|
||||
resolvedEffort !== defaultReasoningEffort
|
||||
? resolvedEffort
|
||||
: undefined;
|
||||
const effort = resolveEffort(caps, modelOptions?.effort);
|
||||
const thinking =
|
||||
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
|
||||
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
|
||||
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
|
||||
const nextOptions: ClaudeModelOptions = {
|
||||
...(thinking === false ? { thinking: false } : {}),
|
||||
...(effort ? { effort } : {}),
|
||||
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(contextWindow ? { contextWindow } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Equal, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { getDefaultEffort, trimOrNull } from "@t3tools/shared/model";
|
||||
import { resolveEffort } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
@@ -48,6 +48,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -64,6 +65,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -80,6 +82,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -96,6 +99,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -112,6 +116,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -128,6 +133,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -140,6 +146,7 @@ export function getCodexModelCapabilities(model: string | null | undefined): Mod
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
}
|
||||
);
|
||||
@@ -150,11 +157,10 @@ export function normalizeCodexModelOptions(
|
||||
modelOptions: CodexModelOptions | null | undefined,
|
||||
): CodexModelOptions | undefined {
|
||||
const caps = getCodexModelCapabilities(model);
|
||||
const defaultReasoningEffort = getDefaultEffort(caps);
|
||||
const reasoningEffort = trimOrNull(modelOptions?.reasoningEffort) ?? defaultReasoningEffort;
|
||||
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
|
||||
const fastModeEnabled = modelOptions?.fastMode === true;
|
||||
const nextOptions: CodexModelOptions = {
|
||||
...(reasoningEffort && reasoningEffort !== defaultReasoningEffort
|
||||
...(reasoningEffort
|
||||
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
|
||||
: {}),
|
||||
...(fastModeEnabled ? { fastMode: true } : {}),
|
||||
|
||||
@@ -226,6 +226,7 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
Effect.tap(() => fs.makeDirectory(pathService.dirname(settingsPath), { recursive: true })),
|
||||
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||
Effect.flatMap(() => fs.rename(tempPath, settingsPath)),
|
||||
Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSettingsError({
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Http from "node:http";
|
||||
import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
@@ -56,6 +57,7 @@ import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
||||
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import { ServerSettingsService } from "./serverSettings.ts";
|
||||
import { BrowserAuth, BrowserAuthLive } from "./browserAuth.ts";
|
||||
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asProviderItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||
@@ -245,6 +247,8 @@ interface SocketChannels {
|
||||
}
|
||||
|
||||
const channelsBySocket = new WeakMap<WebSocket, SocketChannels>();
|
||||
let currentBootstrapToken: string | null = null;
|
||||
let currentBrowserCookie: string | null = null;
|
||||
|
||||
function enqueue<T>(channel: MessageChannel<T>, item: T) {
|
||||
const waiter = channel.waiters.shift();
|
||||
@@ -290,10 +294,46 @@ function asWebSocketResponse(message: unknown): WebSocketResponse | null {
|
||||
return message as WebSocketResponse;
|
||||
}
|
||||
|
||||
function connectWsOnce(port: number, token?: string): Promise<WebSocket> {
|
||||
interface ConnectWsOptions {
|
||||
readonly token?: string;
|
||||
readonly headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
async function pairBrowserSession(
|
||||
port: number,
|
||||
origin = `http://127.0.0.1:${port}`,
|
||||
): Promise<string> {
|
||||
if (!currentBootstrapToken) {
|
||||
throw new Error("Browser bootstrap token not initialized");
|
||||
}
|
||||
|
||||
const response = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: origin,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
if (response.statusCode !== 204) {
|
||||
throw new Error(`Browser bootstrap failed with status ${response.statusCode}`);
|
||||
}
|
||||
|
||||
const setCookie = response.headers["set-cookie"];
|
||||
const cookieHeader = Array.isArray(setCookie) ? setCookie[0] : setCookie;
|
||||
if (!cookieHeader) {
|
||||
throw new Error("Browser bootstrap missing auth cookie");
|
||||
}
|
||||
|
||||
return cookieHeader.split(";", 1)[0] ?? "";
|
||||
}
|
||||
|
||||
function connectWsOnce(port: number, options: ConnectWsOptions = {}): Promise<WebSocket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const query = token ? `?token=${encodeURIComponent(token)}` : "";
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`);
|
||||
const query = options.token ? `?token=${encodeURIComponent(options.token)}` : "";
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`, {
|
||||
headers: options.headers,
|
||||
});
|
||||
const channels: SocketChannels = {
|
||||
push: { queue: [], waiters: [] },
|
||||
response: { queue: [], waiters: [] },
|
||||
@@ -317,12 +357,25 @@ function connectWsOnce(port: number, token?: string): Promise<WebSocket> {
|
||||
});
|
||||
}
|
||||
|
||||
async function connectWs(port: number, token?: string, attempts = 5): Promise<WebSocket> {
|
||||
async function connectWs(
|
||||
port: number,
|
||||
options: ConnectWsOptions = {},
|
||||
attempts = 5,
|
||||
): Promise<WebSocket> {
|
||||
const normalizedOptions =
|
||||
options.token || options.headers
|
||||
? options
|
||||
: {
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
Cookie: (currentBrowserCookie ??= await pairBrowserSession(port)),
|
||||
},
|
||||
};
|
||||
let lastError: unknown = new Error("WebSocket connection failed");
|
||||
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
try {
|
||||
return await connectWsOnce(port, token);
|
||||
return await connectWsOnce(port, normalizedOptions);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (attempt < attempts - 1) {
|
||||
@@ -337,9 +390,9 @@ async function connectWs(port: number, token?: string, attempts = 5): Promise<We
|
||||
/** Connect and wait for the server.welcome push. Returns [ws, welcomeData]. */
|
||||
async function connectAndAwaitWelcome(
|
||||
port: number,
|
||||
token?: string,
|
||||
options: ConnectWsOptions = {},
|
||||
): Promise<[WebSocket, WsPushMessage<typeof WS_CHANNELS.serverWelcome>]> {
|
||||
const ws = await connectWs(port, token);
|
||||
const ws = await connectWs(port, options);
|
||||
const welcome = await waitForPush(ws, WS_CHANNELS.serverWelcome);
|
||||
return [ws, welcome];
|
||||
}
|
||||
@@ -411,14 +464,20 @@ async function rewriteKeybindingsAndWaitForPush(
|
||||
async function requestPath(
|
||||
port: number,
|
||||
requestPath: string,
|
||||
): Promise<{ statusCode: number; body: string }> {
|
||||
options: {
|
||||
readonly method?: string;
|
||||
readonly headers?: Record<string, string>;
|
||||
readonly body?: string;
|
||||
} = {},
|
||||
): Promise<{ statusCode: number; body: string; headers: Http.IncomingHttpHeaders }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = Http.request(
|
||||
{
|
||||
hostname: "127.0.0.1",
|
||||
port,
|
||||
path: requestPath,
|
||||
method: "GET",
|
||||
method: options.method ?? "GET",
|
||||
headers: options.headers,
|
||||
},
|
||||
(res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
@@ -429,11 +488,15 @@ async function requestPath(
|
||||
resolve({
|
||||
statusCode: res.statusCode ?? 0,
|
||||
body: Buffer.concat(chunks).toString("utf8"),
|
||||
headers: res.headers,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
req.once("error", reject);
|
||||
if (options.body) {
|
||||
req.write(options.body);
|
||||
}
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
@@ -483,6 +546,24 @@ describe("WebSocket Server", () => {
|
||||
return dir;
|
||||
}
|
||||
|
||||
async function reserveLoopbackPort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = net.createServer();
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
const port = typeof address === "object" && address !== null ? address.port : 0;
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve(port);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function createTestServer(
|
||||
options: {
|
||||
persistenceLayer?: Layer.Layer<
|
||||
@@ -512,6 +593,7 @@ describe("WebSocket Server", () => {
|
||||
const baseDir = options.baseDir ?? makeTempDir("t3code-ws-base-");
|
||||
const devUrl = options.devUrl ? new URL(options.devUrl) : undefined;
|
||||
const derivedPaths = deriveServerPathsSync(baseDir, devUrl);
|
||||
const reservedPort = await reserveLoopbackPort();
|
||||
const scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory;
|
||||
const providerLayer = options.providerLayer ?? makeServerProviderLayer();
|
||||
@@ -522,8 +604,8 @@ describe("WebSocket Server", () => {
|
||||
const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService);
|
||||
const serverConfigLayer = Layer.succeed(ServerConfig, {
|
||||
mode: "web",
|
||||
port: 0,
|
||||
host: undefined,
|
||||
port: reservedPort,
|
||||
host: "127.0.0.1",
|
||||
cwd: options.cwd ?? "/test/project",
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
@@ -534,6 +616,7 @@ describe("WebSocket Server", () => {
|
||||
autoBootstrapProjectFromCwd: options.autoBootstrapProjectFromCwd ?? false,
|
||||
logWebSocketEvents: options.logWebSocketEvents ?? Boolean(options.devUrl),
|
||||
} satisfies ServerConfigShape);
|
||||
const browserAuthLayer = BrowserAuthLive.pipe(Layer.provide(serverConfigLayer));
|
||||
const infrastructureLayer = providerLayer.pipe(Layer.provideMerge(persistenceLayer));
|
||||
const runtimeOverrides = Layer.mergeAll(
|
||||
options.gitManager ? Layer.succeed(GitManager, options.gitManager) : Layer.empty,
|
||||
@@ -558,12 +641,22 @@ describe("WebSocket Server", () => {
|
||||
Layer.provideMerge(openLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest(options.serverSettings)),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(browserAuthLayer),
|
||||
Layer.provideMerge(AnalyticsService.layerTest),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtimeServices = await Effect.runPromise(
|
||||
Layer.build(dependenciesLayer).pipe(Scope.provide(scope)),
|
||||
);
|
||||
currentBrowserCookie = null;
|
||||
currentBootstrapToken = null;
|
||||
currentBootstrapToken = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const browserAuth = yield* BrowserAuth;
|
||||
const pairingUrl = yield* browserAuth.getPairingUrl("http://pair.test");
|
||||
return new URL(pairingUrl).hash.replace(/^#t3_bootstrap=/, "");
|
||||
}).pipe(Effect.provide(runtimeServices)),
|
||||
);
|
||||
|
||||
try {
|
||||
const runtime = await Effect.runPromise(
|
||||
@@ -591,6 +684,8 @@ describe("WebSocket Server", () => {
|
||||
connections.length = 0;
|
||||
await closeTestServer();
|
||||
server = null;
|
||||
currentBootstrapToken = null;
|
||||
currentBrowserCookie = null;
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
@@ -1954,9 +2049,120 @@ describe("WebSocket Server", () => {
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
await expect(connectWs(port)).rejects.toThrow("WebSocket connection failed");
|
||||
await expect(
|
||||
connectWs(port, { headers: { Origin: `http://127.0.0.1:${port}` } }),
|
||||
).rejects.toThrow("WebSocket connection failed");
|
||||
|
||||
const [authorizedWs] = await connectAndAwaitWelcome(port, "secret-token");
|
||||
const [authorizedWs] = await connectAndAwaitWelcome(port, { token: "secret-token" });
|
||||
connections.push(authorizedWs);
|
||||
});
|
||||
|
||||
it("issues an auth cookie from a valid bootstrap token", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const response = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(204);
|
||||
expect(String(response.headers["set-cookie"])).toContain("t3_auth=");
|
||||
});
|
||||
|
||||
it("rejects bootstrap requests from foreign origins", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const response = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: "https://evil.example",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("consumes bootstrap tokens exactly once", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const first = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
const second = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
|
||||
expect(first.statusCode).toBe(204);
|
||||
expect(second.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("reports auth session state from the browser cookie", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const unauthenticated = await requestPath(port, "/api/auth/session");
|
||||
expect(unauthenticated.statusCode).toBe(200);
|
||||
expect(JSON.parse(unauthenticated.body)).toEqual({ authenticated: false });
|
||||
|
||||
const cookie = await pairBrowserSession(port);
|
||||
const authenticated = await requestPath(port, "/api/auth/session", {
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
Cookie: cookie,
|
||||
},
|
||||
});
|
||||
|
||||
expect(authenticated.statusCode).toBe(200);
|
||||
expect(JSON.parse(authenticated.body)).toEqual({ authenticated: true });
|
||||
});
|
||||
|
||||
it("rejects websocket connections without a browser origin", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const cookie = await pairBrowserSession(port);
|
||||
await expect(connectWs(port, { headers: { Cookie: cookie } })).rejects.toThrow(
|
||||
"WebSocket connection failed",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects websocket connections from a foreign origin even with a valid cookie", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const cookie = await pairBrowserSession(port);
|
||||
await expect(
|
||||
connectWs(port, {
|
||||
headers: {
|
||||
Origin: "https://evil.example",
|
||||
Cookie: cookie,
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("WebSocket connection failed");
|
||||
});
|
||||
});
|
||||
+197
-19
@@ -79,6 +79,7 @@ import { expandHomePath } from "./os-jank.ts";
|
||||
import { makeServerPushBus } from "./wsServer/pushBus.ts";
|
||||
import { makeServerReadiness } from "./wsServer/readiness.ts";
|
||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
import { BrowserAuth } from "./browserAuth";
|
||||
|
||||
/**
|
||||
* ServerShape - Service API for server lifecycle control.
|
||||
@@ -122,6 +123,27 @@ function rejectUpgrade(socket: Duplex, statusCode: number, message: string): voi
|
||||
);
|
||||
}
|
||||
|
||||
function readRequestBody(request: http.IncomingMessage): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
request.on("data", (chunk: Buffer | string) => {
|
||||
chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
|
||||
});
|
||||
request.once("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
||||
request.once("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
function corsHeaders(origin: string): Record<string, string> {
|
||||
return {
|
||||
"Access-Control-Allow-Origin": origin,
|
||||
"Access-Control-Allow-Credentials": "true",
|
||||
"Access-Control-Allow-Methods": "GET,POST,OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type",
|
||||
Vary: "Origin",
|
||||
};
|
||||
}
|
||||
|
||||
function websocketRawToString(raw: unknown): string | null {
|
||||
if (typeof raw === "string") {
|
||||
return raw;
|
||||
@@ -219,7 +241,8 @@ export type ServerRuntimeServices =
|
||||
| Keybindings
|
||||
| ServerSettingsService
|
||||
| Open
|
||||
| AnalyticsService;
|
||||
| AnalyticsService
|
||||
| BrowserAuth;
|
||||
|
||||
export class ServerLifecycleError extends Schema.TaggedErrorClass<ServerLifecycleError>()(
|
||||
"ServerLifecycleError",
|
||||
@@ -256,6 +279,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const keybindingsManager = yield* Keybindings;
|
||||
const serverSettingsManager = yield* ServerSettingsService;
|
||||
const browserAuth = yield* BrowserAuth;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const git = yield* GitCore;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -422,7 +446,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const httpServer = http.createServer((req, res) => {
|
||||
const respond = (
|
||||
statusCode: number,
|
||||
headers: Record<string, string>,
|
||||
headers: http.OutgoingHttpHeaders,
|
||||
body?: string | Uint8Array,
|
||||
) => {
|
||||
res.writeHead(statusCode, headers);
|
||||
@@ -436,6 +460,134 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
return;
|
||||
}
|
||||
|
||||
const requestOrigin = req.headers.origin;
|
||||
const authEndpointHeaders =
|
||||
typeof requestOrigin === "string" && (yield* browserAuth.isAllowedOrigin(requestOrigin))
|
||||
? corsHeaders(requestOrigin)
|
||||
: {};
|
||||
|
||||
if (url.pathname === "/api/auth/bootstrap") {
|
||||
if (req.method === "OPTIONS") {
|
||||
if (typeof requestOrigin !== "string") {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
respond(204, authEndpointHeaders);
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method !== "POST") {
|
||||
respond(405, { "Content-Type": "text/plain" }, "Method Not Allowed");
|
||||
return;
|
||||
}
|
||||
if (typeof requestOrigin !== "string") {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
respond(
|
||||
403,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Forbidden origin",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const bodyText = yield* Effect.tryPromise({
|
||||
try: () => readRequestBody(req),
|
||||
catch: () =>
|
||||
new RouteRequestError({ message: "Failed to read auth bootstrap request body." }),
|
||||
});
|
||||
|
||||
let parsedBody: unknown;
|
||||
try {
|
||||
parsedBody = JSON.parse(bodyText);
|
||||
} catch {
|
||||
respond(
|
||||
400,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Invalid JSON body",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const token =
|
||||
typeof parsedBody === "object" &&
|
||||
parsedBody !== null &&
|
||||
"token" in parsedBody &&
|
||||
typeof (parsedBody as { token?: unknown }).token === "string"
|
||||
? (parsedBody as { token: string }).token
|
||||
: null;
|
||||
if (!token) {
|
||||
respond(
|
||||
400,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Missing bootstrap token",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const consumed = yield* browserAuth.consumeBootstrapToken(token);
|
||||
if (!consumed) {
|
||||
respond(
|
||||
401,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Invalid bootstrap token",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const cookieHeader = yield* browserAuth.createAuthCookie(url.protocol === "https:");
|
||||
respond(204, {
|
||||
...authEndpointHeaders,
|
||||
"Set-Cookie": cookieHeader,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/auth/session") {
|
||||
if (req.method === "OPTIONS") {
|
||||
if (typeof requestOrigin !== "string") {
|
||||
respond(204, {});
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
respond(204, authEndpointHeaders);
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method !== "GET") {
|
||||
respond(405, { "Content-Type": "text/plain" }, "Method Not Allowed");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof requestOrigin === "string" &&
|
||||
!(yield* browserAuth.isAllowedOrigin(requestOrigin))
|
||||
) {
|
||||
respond(
|
||||
403,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Forbidden origin",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const authenticated = yield* browserAuth.isAuthenticatedRequest(req.headers);
|
||||
respond(
|
||||
200,
|
||||
{ "Content-Type": "application/json", ...authEndpointHeaders },
|
||||
JSON.stringify({ authenticated }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
||||
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
|
||||
@@ -916,6 +1068,12 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
};
|
||||
}
|
||||
|
||||
case WS_METHODS.serverRefreshProviders: {
|
||||
const providers = yield* providerRegistry.refresh();
|
||||
yield* Ref.set(providersRef, providers);
|
||||
return { providers };
|
||||
}
|
||||
|
||||
case WS_METHODS.serverUpsertKeybinding: {
|
||||
const body = stripRequestTag(request.body);
|
||||
const keybindingsConfig = yield* keybindingsManager.upsertKeybindingRule(body);
|
||||
@@ -980,25 +1138,45 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
httpServer.on("upgrade", (request, socket, head) => {
|
||||
socket.on("error", () => {}); // Prevent unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake
|
||||
|
||||
if (authToken) {
|
||||
let providedToken: string | null = null;
|
||||
try {
|
||||
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
|
||||
providedToken = url.searchParams.get("token");
|
||||
} catch {
|
||||
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
|
||||
return;
|
||||
}
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
let providedToken: string | null = null;
|
||||
try {
|
||||
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
|
||||
providedToken = url.searchParams.get("token");
|
||||
} catch {
|
||||
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
|
||||
return;
|
||||
}
|
||||
|
||||
if (providedToken !== authToken) {
|
||||
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
|
||||
return;
|
||||
}
|
||||
}
|
||||
const requestOrigin = request.headers.origin;
|
||||
const hasLegacyToken = Boolean(authToken && providedToken === authToken);
|
||||
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, request);
|
||||
});
|
||||
if (hasLegacyToken && !requestOrigin) {
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, request);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof requestOrigin !== "string") {
|
||||
rejectUpgrade(socket, 401, "Missing WebSocket origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
rejectUpgrade(socket, 401, "Forbidden WebSocket origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAuthenticatedRequest(request.headers))) {
|
||||
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
|
||||
return;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, request);
|
||||
});
|
||||
}).pipe(Effect.ignoreCause({ log: true })),
|
||||
);
|
||||
});
|
||||
|
||||
wss.on("connection", (ws) => {
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
clearBootstrapTokenFromUrl,
|
||||
consumeBootstrapTokenFromHash,
|
||||
ensureBrowserPairing,
|
||||
resolveServerHttpOrigin,
|
||||
} from "./browserAuth";
|
||||
|
||||
describe("browserAuth", () => {
|
||||
const fetchMock = vi.fn<typeof fetch>();
|
||||
const setTestWindow = (href: string) => {
|
||||
let currentUrl = new URL(href);
|
||||
const location = {
|
||||
get hash() {
|
||||
return currentUrl.hash;
|
||||
},
|
||||
get host() {
|
||||
return currentUrl.host;
|
||||
},
|
||||
get hostname() {
|
||||
return currentUrl.hostname;
|
||||
},
|
||||
get href() {
|
||||
return currentUrl.toString();
|
||||
},
|
||||
get origin() {
|
||||
return currentUrl.origin;
|
||||
},
|
||||
get pathname() {
|
||||
return currentUrl.pathname;
|
||||
},
|
||||
get port() {
|
||||
return currentUrl.port;
|
||||
},
|
||||
get protocol() {
|
||||
return currentUrl.protocol;
|
||||
},
|
||||
get search() {
|
||||
return currentUrl.search;
|
||||
},
|
||||
toString() {
|
||||
return currentUrl.toString();
|
||||
},
|
||||
};
|
||||
const history = {
|
||||
state: {} as unknown,
|
||||
replaceState: (state: unknown, _unused: string, nextUrl?: string | URL | null) => {
|
||||
history.state = state;
|
||||
if (!nextUrl) return;
|
||||
currentUrl = new URL(String(nextUrl));
|
||||
},
|
||||
};
|
||||
vi.stubGlobal("window", {
|
||||
location,
|
||||
history,
|
||||
nativeApi: undefined,
|
||||
desktopBridge: undefined,
|
||||
});
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
setTestWindow("http://localhost:3773/");
|
||||
fetchMock.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("reads and clears bootstrap tokens from the url hash", () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
|
||||
expect(consumeBootstrapTokenFromHash()).toBe("pair-me");
|
||||
|
||||
clearBootstrapTokenFromUrl();
|
||||
|
||||
expect(window.location.hash).toBe("");
|
||||
expect(consumeBootstrapTokenFromHash()).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves the server http origin from the current location when no ws override exists", () => {
|
||||
setTestWindow("http://localhost:4123/chat");
|
||||
|
||||
expect(resolveServerHttpOrigin()).toBe("http://localhost:4123");
|
||||
});
|
||||
|
||||
it("exchanges a bootstrap token before checking the auth session", async () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(
|
||||
new Response(null, {
|
||||
status: 204,
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: true }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(true);
|
||||
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://localhost:3773/api/auth/bootstrap",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
}),
|
||||
);
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"http://localhost:3773/api/auth/session",
|
||||
expect.objectContaining({
|
||||
credentials: "include",
|
||||
}),
|
||||
);
|
||||
expect(window.location.hash).toBe("");
|
||||
});
|
||||
|
||||
it("polls auth session after a successful bootstrap until the cookie is visible", async () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(
|
||||
new Response(null, {
|
||||
status: 204,
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: false }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: false }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: true }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(true);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(4);
|
||||
expect(window.location.hash).toBe("");
|
||||
});
|
||||
|
||||
it("returns false when bootstrap exchange fails", async () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response("nope", {
|
||||
status: 401,
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(false);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(window.location.hash).toBe("#t3_bootstrap=pair-me");
|
||||
});
|
||||
|
||||
it("checks the existing auth session when no bootstrap token is present", async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: false }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(false);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"http://localhost:3773/api/auth/session",
|
||||
expect.objectContaining({
|
||||
credentials: "include",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("bypasses browser pairing when the electron desktop bridge is available", async () => {
|
||||
vi.stubGlobal("window", {
|
||||
location: {
|
||||
href: "file:///app/index.html",
|
||||
origin: "file://",
|
||||
hash: "",
|
||||
},
|
||||
history: {
|
||||
state: undefined,
|
||||
replaceState: vi.fn(),
|
||||
},
|
||||
nativeApi: undefined,
|
||||
desktopBridge: {
|
||||
getWsUrl: () => "ws://127.0.0.1:3773",
|
||||
},
|
||||
});
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(true);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
const BOOTSTRAP_HASH_KEY = "t3_bootstrap";
|
||||
const AUTH_SESSION_POLL_ATTEMPTS = 50;
|
||||
const AUTH_SESSION_POLL_INTERVAL_MS = 100;
|
||||
|
||||
interface AuthSessionResponse {
|
||||
readonly authenticated: boolean;
|
||||
}
|
||||
|
||||
function normalizeServerHttpOrigin(rawUrl: string): string {
|
||||
const wsUrl = new URL(rawUrl);
|
||||
const protocol =
|
||||
wsUrl.protocol === "wss:" ? "https:" : wsUrl.protocol === "ws:" ? "http:" : wsUrl.protocol;
|
||||
return `${protocol}//${wsUrl.host}`;
|
||||
}
|
||||
|
||||
export function resolveServerHttpOrigin(): string {
|
||||
if (typeof window === "undefined") return "";
|
||||
|
||||
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsCandidate =
|
||||
typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
|
||||
? bridgeWsUrl
|
||||
: typeof envWsUrl === "string" && envWsUrl.length > 0
|
||||
? envWsUrl
|
||||
: null;
|
||||
|
||||
if (!wsCandidate) {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
try {
|
||||
return normalizeServerHttpOrigin(wsCandidate);
|
||||
} catch {
|
||||
return window.location.origin;
|
||||
}
|
||||
}
|
||||
|
||||
export function consumeBootstrapTokenFromHash(
|
||||
locationLike: Location = window.location,
|
||||
): string | null {
|
||||
const hash = locationLike.hash.startsWith("#") ? locationLike.hash.slice(1) : locationLike.hash;
|
||||
const params = new URLSearchParams(hash);
|
||||
const token = params.get(BOOTSTRAP_HASH_KEY);
|
||||
return token && token.length > 0 ? token : null;
|
||||
}
|
||||
|
||||
export function clearBootstrapTokenFromUrl(locationLike: Location = window.location): void {
|
||||
const currentUrl = new URL(locationLike.href);
|
||||
currentUrl.hash = "";
|
||||
window.history.replaceState(window.history.state, "", currentUrl.toString());
|
||||
}
|
||||
|
||||
async function exchangeBootstrapToken(serverOrigin: string, token: string): Promise<void> {
|
||||
const response = await fetch(`${serverOrigin}/api/auth/bootstrap`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
credentials: "include",
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Browser pairing failed with status ${response.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchSession(serverOrigin: string): Promise<boolean> {
|
||||
const response = await fetch(`${serverOrigin}/api/auth/session`, {
|
||||
credentials: "include",
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Auth session check failed with status ${response.status}`);
|
||||
}
|
||||
|
||||
const parsed = (await response.json()) as Partial<AuthSessionResponse>;
|
||||
return parsed.authenticated === true;
|
||||
}
|
||||
|
||||
async function waitForAuthenticatedSession(serverOrigin: string): Promise<boolean> {
|
||||
for (let attempt = 0; attempt < AUTH_SESSION_POLL_ATTEMPTS; attempt += 1) {
|
||||
if (await fetchSession(serverOrigin)) {
|
||||
return true;
|
||||
}
|
||||
if (attempt < AUTH_SESSION_POLL_ATTEMPTS - 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, AUTH_SESSION_POLL_INTERVAL_MS));
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function ensureBrowserPairing(): Promise<boolean> {
|
||||
if (typeof window === "undefined") return false;
|
||||
if (window.nativeApi || window.desktopBridge) return true;
|
||||
|
||||
const serverOrigin = resolveServerHttpOrigin();
|
||||
const bootstrapToken = consumeBootstrapTokenFromHash();
|
||||
|
||||
if (bootstrapToken) {
|
||||
try {
|
||||
await exchangeBootstrapToken(serverOrigin, bootstrapToken);
|
||||
clearBootstrapTokenFromUrl();
|
||||
return waitForAuthenticatedSession(serverOrigin);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return fetchSession(serverOrigin);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
resolveBranchSelectionTarget,
|
||||
resolveDraftEnvModeAfterBranchChange,
|
||||
resolveBranchToolbarValue,
|
||||
shouldIncludeBranchPickerItem,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
@@ -267,3 +268,38 @@ describe("resolveBranchSelectionTarget", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldIncludeBranchPickerItem", () => {
|
||||
it("keeps the synthetic checkout PR item visible for gh pr checkout input", () => {
|
||||
expect(
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue: "__checkout_pull_request__:1359",
|
||||
normalizedQuery: "gh pr checkout 1359",
|
||||
createBranchItemValue: "__create_new_branch__:gh pr checkout 1359",
|
||||
checkoutPullRequestItemValue: "__checkout_pull_request__:1359",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the synthetic create-branch item visible for arbitrary branch input", () => {
|
||||
expect(
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue: "__create_new_branch__:feature/demo",
|
||||
normalizedQuery: "feature/demo",
|
||||
createBranchItemValue: "__create_new_branch__:feature/demo",
|
||||
checkoutPullRequestItemValue: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("still filters ordinary branch items by query text", () => {
|
||||
expect(
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue: "main",
|
||||
normalizedQuery: "gh pr checkout 1359",
|
||||
createBranchItemValue: "__create_new_branch__:gh pr checkout 1359",
|
||||
checkoutPullRequestItemValue: "__checkout_pull_request__:1359",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -123,3 +123,26 @@ export function resolveBranchSelectionTarget(input: {
|
||||
reuseExistingWorktree: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function shouldIncludeBranchPickerItem(input: {
|
||||
itemValue: string;
|
||||
normalizedQuery: string;
|
||||
createBranchItemValue: string | null;
|
||||
checkoutPullRequestItemValue: string | null;
|
||||
}): boolean {
|
||||
const { itemValue, normalizedQuery, createBranchItemValue, checkoutPullRequestItemValue } = input;
|
||||
|
||||
if (normalizedQuery.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (createBranchItemValue && itemValue === createBranchItemValue) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return itemValue.toLowerCase().includes(normalizedQuery);
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
EnvMode,
|
||||
resolveBranchSelectionTarget,
|
||||
resolveBranchToolbarValue,
|
||||
shouldIncludeBranchPickerItem,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
@@ -134,11 +135,20 @@ export function BranchToolbarBranchSelector({
|
||||
() =>
|
||||
normalizedDeferredBranchQuery.length === 0
|
||||
? branchPickerItems
|
||||
: branchPickerItems.filter((itemValue) => {
|
||||
if (createBranchItemValue && itemValue === createBranchItemValue) return true;
|
||||
return itemValue.toLowerCase().includes(normalizedDeferredBranchQuery);
|
||||
}),
|
||||
[branchPickerItems, createBranchItemValue, normalizedDeferredBranchQuery],
|
||||
: branchPickerItems.filter((itemValue) =>
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue,
|
||||
normalizedQuery: normalizedDeferredBranchQuery,
|
||||
createBranchItemValue,
|
||||
checkoutPullRequestItemValue,
|
||||
}),
|
||||
),
|
||||
[
|
||||
branchPickerItems,
|
||||
checkoutPullRequestItemValue,
|
||||
createBranchItemValue,
|
||||
normalizedDeferredBranchQuery,
|
||||
],
|
||||
);
|
||||
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
|
||||
canonicalActiveBranch,
|
||||
|
||||
@@ -56,6 +56,7 @@ interface TestFixture {
|
||||
|
||||
let fixture: TestFixture;
|
||||
const wsRequests: WsRequestEnvelope["body"][] = [];
|
||||
let customWsRpcResolver: ((body: WsRequestEnvelope["body"]) => unknown | undefined) | null = null;
|
||||
const wsLink = ws.link(/ws(s)?:\/\/.*/);
|
||||
|
||||
interface ViewportSpec {
|
||||
@@ -356,6 +357,25 @@ function withProjectScripts(
|
||||
};
|
||||
}
|
||||
|
||||
function setDraftThreadWithoutWorktree(): void {
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadId: {
|
||||
[THREAD_ID]: {
|
||||
projectId: PROJECT_ID,
|
||||
createdAt: NOW_ISO,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
envMode: "local",
|
||||
},
|
||||
},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[PROJECT_ID]: THREAD_ID,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
|
||||
const snapshot = createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-plan-target" as MessageId,
|
||||
@@ -414,6 +434,10 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
|
||||
}
|
||||
|
||||
function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
|
||||
const customResult = customWsRpcResolver?.(body);
|
||||
if (customResult !== undefined) {
|
||||
return customResult;
|
||||
}
|
||||
const tag = body._tag;
|
||||
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
|
||||
return fixture.snapshot;
|
||||
@@ -748,9 +772,11 @@ async function mountChatView(options: {
|
||||
viewport: ViewportSpec;
|
||||
snapshot: OrchestrationReadModel;
|
||||
configureFixture?: (fixture: TestFixture) => void;
|
||||
resolveRpc?: (body: WsRequestEnvelope["body"]) => unknown | undefined;
|
||||
}): Promise<MountedChatView> {
|
||||
fixture = buildFixture(options.snapshot);
|
||||
options.configureFixture?.(fixture);
|
||||
customWsRpcResolver = options.resolveRpc ?? null;
|
||||
await setViewport(options.viewport);
|
||||
await waitForProductionStyles();
|
||||
|
||||
@@ -776,6 +802,7 @@ async function mountChatView(options: {
|
||||
await waitForLayout();
|
||||
|
||||
const cleanup = async () => {
|
||||
customWsRpcResolver = null;
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
};
|
||||
@@ -835,6 +862,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
localStorage.clear();
|
||||
document.body.innerHTML = "";
|
||||
wsRequests.length = 0;
|
||||
customWsRpcResolver = null;
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
@@ -850,6 +878,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
customWsRpcResolver = null;
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
@@ -1011,22 +1040,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
);
|
||||
|
||||
it("opens the project cwd for draft threads without a worktree path", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadId: {
|
||||
[THREAD_ID]: {
|
||||
projectId: PROJECT_ID,
|
||||
createdAt: NOW_ISO,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
envMode: "local",
|
||||
},
|
||||
},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[PROJECT_ID]: THREAD_ID,
|
||||
},
|
||||
});
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
@@ -1067,6 +1081,153 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("opens the project cwd with VS Code Insiders when it is the only available editor", async () => {
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
availableEditors: ["vscode-insiders"],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const openButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.trim() === "Open",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Open button.",
|
||||
);
|
||||
openButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.shellOpenInEditor,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.shellOpenInEditor,
|
||||
cwd: "/repo/project",
|
||||
editor: "vscode-insiders",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("filters the open picker menu and opens VSCodium from the menu", async () => {
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
availableEditors: ["vscode-insiders", "vscodium"],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const menuButton = await waitForElement(
|
||||
() => document.querySelector('button[aria-label="Copy options"]'),
|
||||
"Unable to find Open picker button.",
|
||||
);
|
||||
(menuButton as HTMLButtonElement).click();
|
||||
|
||||
await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) =>
|
||||
item.textContent?.includes("VS Code Insiders"),
|
||||
) ?? null,
|
||||
"Unable to find VS Code Insiders menu item.",
|
||||
);
|
||||
|
||||
expect(
|
||||
Array.from(document.querySelectorAll('[data-slot="menu-item"]')).some((item) =>
|
||||
item.textContent?.includes("Zed"),
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
const vscodiumItem = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) =>
|
||||
item.textContent?.includes("VSCodium"),
|
||||
) ?? null,
|
||||
"Unable to find VSCodium menu item.",
|
||||
);
|
||||
(vscodiumItem as HTMLElement).click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.shellOpenInEditor,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.shellOpenInEditor,
|
||||
cwd: "/repo/project",
|
||||
editor: "vscodium",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to the first installed editor when the stored favorite is unavailable", async () => {
|
||||
localStorage.setItem("t3code:last-editor", "vscodium");
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
availableEditors: ["vscode-insiders"],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const openButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.trim() === "Open",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Open button.",
|
||||
);
|
||||
openButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.shellOpenInEditor,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.shellOpenInEditor,
|
||||
cwd: "/repo/project",
|
||||
editor: "vscode-insiders",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("runs project scripts from local draft threads at the project cwd", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadId: {
|
||||
@@ -1206,6 +1367,154 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("runs setup scripts after preparing a pull request worktree thread", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadId: {
|
||||
[THREAD_ID]: {
|
||||
projectId: PROJECT_ID,
|
||||
createdAt: NOW_ISO,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
envMode: "local",
|
||||
},
|
||||
},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[PROJECT_ID]: THREAD_ID,
|
||||
},
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
]),
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.gitResolvePullRequest) {
|
||||
return {
|
||||
pullRequest: {
|
||||
number: 1359,
|
||||
title: "Add thread archiving and settings navigation",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/1359",
|
||||
baseBranch: "main",
|
||||
headBranch: "archive-settings-overhaul",
|
||||
state: "open",
|
||||
},
|
||||
};
|
||||
}
|
||||
if (body._tag === WS_METHODS.gitPreparePullRequestThread) {
|
||||
return {
|
||||
pullRequest: {
|
||||
number: 1359,
|
||||
title: "Add thread archiving and settings navigation",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/1359",
|
||||
baseBranch: "main",
|
||||
headBranch: "archive-settings-overhaul",
|
||||
state: "open",
|
||||
},
|
||||
branch: "archive-settings-overhaul",
|
||||
worktreePath: "/repo/worktrees/pr-1359",
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const branchButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.trim() === "main",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find branch selector button.",
|
||||
);
|
||||
branchButton.click();
|
||||
|
||||
const branchInput = await waitForElement(
|
||||
() => document.querySelector<HTMLInputElement>('input[placeholder="Search branches..."]'),
|
||||
"Unable to find branch search input.",
|
||||
);
|
||||
branchInput.focus();
|
||||
await page.getByPlaceholder("Search branches...").fill("1359");
|
||||
|
||||
const checkoutItem = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("span")).find(
|
||||
(element) => element.textContent?.trim() === "Checkout Pull Request",
|
||||
) as HTMLSpanElement | null,
|
||||
"Unable to find checkout pull request option.",
|
||||
);
|
||||
checkoutItem.click();
|
||||
|
||||
const worktreeButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.trim() === "Worktree",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Worktree button.",
|
||||
);
|
||||
worktreeButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const prepareRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.gitPreparePullRequestThread,
|
||||
);
|
||||
expect(prepareRequest).toMatchObject({
|
||||
_tag: WS_METHODS.gitPreparePullRequestThread,
|
||||
cwd: "/repo/project",
|
||||
reference: "1359",
|
||||
mode: "worktree",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) =>
|
||||
request._tag === WS_METHODS.terminalOpen && request.cwd === "/repo/worktrees/pr-1359",
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.terminalOpen,
|
||||
threadId: expect.any(String),
|
||||
cwd: "/repo/worktrees/pr-1359",
|
||||
env: {
|
||||
T3CODE_PROJECT_ROOT: "/repo/project",
|
||||
T3CODE_WORKTREE_PATH: "/repo/worktrees/pr-1359",
|
||||
},
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const writeRequest = wsRequests.find(
|
||||
(request) =>
|
||||
request._tag === WS_METHODS.terminalWrite && request.data === "bun install\r",
|
||||
);
|
||||
expect(writeRequest).toMatchObject({
|
||||
_tag: WS_METHODS.terminalWrite,
|
||||
threadId: expect.any(String),
|
||||
data: "bun install\r",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("toggles plan mode with Shift+Tab only while the composer is focused", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
type MessageId,
|
||||
type ModelSelection,
|
||||
type ProjectScript,
|
||||
type ModelSlug,
|
||||
type ProviderKind,
|
||||
type ProjectEntry,
|
||||
type ProjectId,
|
||||
@@ -240,6 +239,12 @@ interface ChatViewProps {
|
||||
threadId: ThreadId;
|
||||
}
|
||||
|
||||
interface PendingPullRequestSetupRequest {
|
||||
threadId: ThreadId;
|
||||
worktreePath: string;
|
||||
scriptId: string;
|
||||
}
|
||||
|
||||
export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const threads = useStore((store) => store.threads);
|
||||
const projects = useStore((store) => store.projects);
|
||||
@@ -351,6 +356,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
|
||||
const [pullRequestDialogState, setPullRequestDialogState] =
|
||||
useState<PullRequestDialogState | null>(null);
|
||||
const [pendingPullRequestSetupRequest, setPendingPullRequestSetupRequest] =
|
||||
useState<PendingPullRequestSetupRequest | null>(null);
|
||||
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
|
||||
Record<string, string[]>
|
||||
>({});
|
||||
@@ -528,14 +535,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
params: { threadId: storedDraftThread.threadId },
|
||||
});
|
||||
}
|
||||
return;
|
||||
return storedDraftThread.threadId;
|
||||
}
|
||||
|
||||
const activeDraftThread = getDraftThread(threadId);
|
||||
if (!isServerThread && activeDraftThread?.projectId === activeProject.id) {
|
||||
setDraftThreadContext(threadId, input);
|
||||
setProjectDraftThreadId(activeProject.id, threadId, input);
|
||||
return;
|
||||
return threadId;
|
||||
}
|
||||
|
||||
clearProjectDraftThreadId(activeProject.id);
|
||||
@@ -550,6 +557,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
to: "/$threadId",
|
||||
params: { threadId: nextThreadId },
|
||||
});
|
||||
return nextThreadId;
|
||||
},
|
||||
[
|
||||
activeProject,
|
||||
@@ -566,13 +574,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
const handlePreparedPullRequestThread = useCallback(
|
||||
async (input: { branch: string; worktreePath: string | null }) => {
|
||||
await openOrReuseProjectDraftThread({
|
||||
const targetThreadId = await openOrReuseProjectDraftThread({
|
||||
branch: input.branch,
|
||||
worktreePath: input.worktreePath,
|
||||
envMode: input.worktreePath ? "worktree" : "local",
|
||||
});
|
||||
const setupScript =
|
||||
input.worktreePath && activeProject ? setupProjectScript(activeProject.scripts) : null;
|
||||
if (targetThreadId && input.worktreePath && setupScript) {
|
||||
setPendingPullRequestSetupRequest({
|
||||
threadId: targetThreadId,
|
||||
worktreePath: input.worktreePath,
|
||||
scriptId: setupScript.id,
|
||||
});
|
||||
} else {
|
||||
setPendingPullRequestSetupRequest(null);
|
||||
}
|
||||
},
|
||||
[openOrReuseProjectDraftThread],
|
||||
[activeProject, openOrReuseProjectDraftThread],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -1419,6 +1438,45 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
terminalState.terminalIds,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingPullRequestSetupRequest || !activeProject || !activeThreadId || !activeThread) {
|
||||
return;
|
||||
}
|
||||
if (pendingPullRequestSetupRequest.threadId !== activeThreadId) {
|
||||
return;
|
||||
}
|
||||
if (activeThread.worktreePath !== pendingPullRequestSetupRequest.worktreePath) {
|
||||
return;
|
||||
}
|
||||
|
||||
const setupScript =
|
||||
activeProject.scripts.find(
|
||||
(script) => script.id === pendingPullRequestSetupRequest.scriptId,
|
||||
) ?? null;
|
||||
setPendingPullRequestSetupRequest(null);
|
||||
if (!setupScript) {
|
||||
return;
|
||||
}
|
||||
|
||||
void runProjectScript(setupScript, {
|
||||
cwd: pendingPullRequestSetupRequest.worktreePath,
|
||||
worktreePath: pendingPullRequestSetupRequest.worktreePath,
|
||||
rememberAsLastInvoked: false,
|
||||
}).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to run setup script.",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
});
|
||||
}, [
|
||||
activeProject,
|
||||
activeThread,
|
||||
activeThreadId,
|
||||
pendingPullRequestSetupRequest,
|
||||
runProjectScript,
|
||||
]);
|
||||
const persistProjectScripts = useCallback(
|
||||
async (input: {
|
||||
projectId: ProjectId;
|
||||
@@ -3105,7 +3163,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
]);
|
||||
|
||||
const onProviderModelSelect = useCallback(
|
||||
(provider: ProviderKind, model: ModelSlug) => {
|
||||
(provider: ProviderKind, model: string) => {
|
||||
if (!activeThread) return;
|
||||
if (lockedProvider !== null && provider !== lockedProvider) {
|
||||
scheduleComposerFocus();
|
||||
@@ -3616,7 +3674,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-[20px] border bg-card transition-colors duration-200 focus-within:border-ring/45",
|
||||
"rounded-[20px] border bg-card transition-colors duration-200 has-focus-visible:border-ring/45",
|
||||
isDragOverComposer ? "border-primary/70 bg-accent/30" : "border-border",
|
||||
composerProviderState.composerSurfaceClassName,
|
||||
)}
|
||||
@@ -4034,7 +4092,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
) : (
|
||||
<button
|
||||
type="submit"
|
||||
className="flex h-9 w-9 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
|
||||
className="flex h-9 w-9 enabled:cursor-pointer items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:pointer-events-none disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
|
||||
disabled={
|
||||
isSendBusy || isConnecting || !composerSendState.hasSendableContent
|
||||
}
|
||||
|
||||
@@ -750,7 +750,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
{initMutation.isPending ? "Initializing..." : "Initialize Git"}
|
||||
</Button>
|
||||
) : (
|
||||
<Group aria-label="Git actions">
|
||||
<Group aria-label="Git actions" className="shrink-0">
|
||||
{quickActionDisabledReason ? (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
@@ -765,7 +765,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
}
|
||||
>
|
||||
<GitQuickActionIcon quickAction={quickAction} />
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
{quickAction.label}
|
||||
</span>
|
||||
</PopoverTrigger>
|
||||
@@ -781,12 +781,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
onClick={runQuickAction}
|
||||
>
|
||||
<GitQuickActionIcon quickAction={quickAction} />
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
{quickAction.label}
|
||||
</span>
|
||||
</Button>
|
||||
)}
|
||||
<GroupSeparator className="hidden @sm/header-actions:block" />
|
||||
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
||||
<Menu
|
||||
onOpenChange={(open) => {
|
||||
if (open) void invalidateGitQueries(queryClient);
|
||||
|
||||
@@ -277,11 +277,11 @@ export default function ProjectScriptsControl({
|
||||
title={`Run ${primaryScript.name}`}
|
||||
>
|
||||
<ScriptIcon icon={primaryScript.icon} />
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
{primaryScript.name}
|
||||
</span>
|
||||
</Button>
|
||||
<GroupSeparator className="hidden @sm/header-actions:block" />
|
||||
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
||||
<Menu highlightItemOnHover={false}>
|
||||
<MenuTrigger
|
||||
render={<Button size="icon-xs" variant="outline" aria-label="Script actions" />}
|
||||
@@ -342,7 +342,7 @@ export default function ProjectScriptsControl({
|
||||
) : (
|
||||
<Button size="xs" variant="outline" onClick={openAddDialog} title="Add action">
|
||||
<PlusIcon className="size-3.5" />
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
Add action
|
||||
</span>
|
||||
</Button>
|
||||
|
||||
@@ -153,9 +153,9 @@ export function PullRequestThreadDialog({
|
||||
const validationMessage = !referenceDirty
|
||||
? null
|
||||
: reference.trim().length === 0
|
||||
? "Paste a GitHub pull request URL or enter 123 / #123."
|
||||
? "Paste a GitHub pull request URL, `gh pr checkout 123`, or enter 123 / #123."
|
||||
: parsedReference === null
|
||||
? "Use a GitHub pull request URL, 123, or #123."
|
||||
? "Use a GitHub pull request URL, `gh pr checkout 123`, 123, or #123."
|
||||
: null;
|
||||
const errorMessage =
|
||||
validationMessage ??
|
||||
@@ -191,7 +191,7 @@ export function PullRequestThreadDialog({
|
||||
<span className="text-xs font-medium text-foreground">Pull request</span>
|
||||
<Input
|
||||
ref={referenceInputRef}
|
||||
placeholder="https://github.com/owner/repo/pull/42 or #42"
|
||||
placeholder="https://github.com/owner/repo/pull/42, gh pr checkout 42, or #42"
|
||||
value={reference}
|
||||
onChange={(event) => {
|
||||
setReferenceDirty(true);
|
||||
|
||||
@@ -62,7 +62,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
onToggleDiff,
|
||||
}: ChatHeaderProps) {
|
||||
return (
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
|
||||
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
|
||||
<h2
|
||||
@@ -72,8 +72,8 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
{activeThreadTitle}
|
||||
</h2>
|
||||
{activeProjectName && (
|
||||
<Badge variant="outline" className="min-w-0 shrink truncate">
|
||||
{activeProjectName}
|
||||
<Badge variant="outline" className="min-w-0 shrink overflow-hidden">
|
||||
<span className="min-w-0 truncate">{activeProjectName}</span>
|
||||
</Badge>
|
||||
)}
|
||||
{activeProjectName && !isGitRepo && (
|
||||
@@ -82,7 +82,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 items-center justify-end gap-2 @sm/header-actions:gap-3">
|
||||
<div className="flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3">
|
||||
{activeProjectScripts && (
|
||||
<ProjectScriptsControl
|
||||
scripts={activeProjectScripts}
|
||||
|
||||
@@ -60,6 +60,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
@@ -71,6 +72,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -87,6 +89,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
@@ -103,6 +106,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ProjectEntry, type ModelSlug, type ProviderKind } from "@t3tools/contracts";
|
||||
import { type ProjectEntry, type ProviderKind } from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
|
||||
import { BotIcon } from "lucide-react";
|
||||
@@ -27,7 +27,7 @@ export type ComposerCommandItem =
|
||||
id: string;
|
||||
type: "model";
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
label: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
@@ -22,6 +22,16 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
|
||||
Icon: VisualStudioCode,
|
||||
value: "vscode",
|
||||
},
|
||||
{
|
||||
label: "VS Code Insiders",
|
||||
Icon: VisualStudioCode,
|
||||
value: "vscode-insiders",
|
||||
},
|
||||
{
|
||||
label: "VSCodium",
|
||||
Icon: VisualStudioCode,
|
||||
value: "vscodium",
|
||||
},
|
||||
{
|
||||
label: "Zed",
|
||||
Icon: Zed,
|
||||
@@ -101,11 +111,11 @@ export const OpenInPicker = memo(function OpenInPicker({
|
||||
onClick={() => openInEditor(preferredEditor)}
|
||||
>
|
||||
{primaryOption?.Icon && <primaryOption.Icon aria-hidden="true" className="size-3.5" />}
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
Open
|
||||
</span>
|
||||
</Button>
|
||||
<GroupSeparator className="hidden @sm/header-actions:block" />
|
||||
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
||||
<Menu>
|
||||
<MenuTrigger render={<Button aria-label="Copy options" size="icon-xs" variant="outline" />}>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-4" />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ModelSlug, type ProviderKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { type ProviderKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
@@ -33,6 +33,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -44,6 +45,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -71,6 +73,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -87,6 +90,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -98,6 +102,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -107,7 +112,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
|
||||
async function mountPicker(props: {
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
lockedProvider: ProviderKind | null;
|
||||
providers?: ReadonlyArray<ServerProvider>;
|
||||
triggerVariant?: "ghost" | "outline";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ModelSlug, type ProviderKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { type ProviderKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { resolveSelectableModel } from "@t3tools/shared/model";
|
||||
import { memo, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
@@ -52,7 +52,7 @@ function providerIconClassName(
|
||||
|
||||
export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
lockedProvider: ProviderKind | null;
|
||||
providers?: ReadonlyArray<ServerProvider>;
|
||||
modelOptionsByProvider: Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>>;
|
||||
@@ -61,7 +61,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
disabled?: boolean;
|
||||
triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
|
||||
triggerClassName?: string;
|
||||
onProviderModelChange: (provider: ProviderKind, model: ModelSlug) => void;
|
||||
onProviderModelChange: (provider: ProviderKind, model: string) => void;
|
||||
}) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const activeProvider = props.lockedProvider ?? props.provider;
|
||||
|
||||
@@ -49,6 +49,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -77,6 +78,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
@@ -93,6 +95,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
@@ -104,6 +107,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
|
||||
@@ -11,7 +11,9 @@ import {
|
||||
isClaudeUltrathinkPrompt,
|
||||
trimOrNull,
|
||||
getDefaultEffort,
|
||||
hasEffortLevel,
|
||||
getDefaultContextWindow,
|
||||
hasContextWindowOption,
|
||||
resolveEffort,
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
@@ -53,6 +55,16 @@ function getRawEffort(
|
||||
return trimOrNull((modelOptions as ClaudeModelOptions | undefined)?.effort);
|
||||
}
|
||||
|
||||
function getRawContextWindow(
|
||||
provider: ProviderKind,
|
||||
modelOptions: ProviderOptions | null | undefined,
|
||||
): string | null {
|
||||
if (provider === "claudeAgent") {
|
||||
return trimOrNull((modelOptions as ClaudeModelOptions | undefined)?.contextWindow);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildNextOptions(
|
||||
provider: ProviderKind,
|
||||
modelOptions: ProviderOptions | null | undefined,
|
||||
@@ -78,21 +90,10 @@ function getSelectedTraits(
|
||||
: caps.reasoningEffortLevels.filter(
|
||||
(option) => !caps.promptInjectedEffortLevels.includes(option.value),
|
||||
);
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
|
||||
// Resolve effort from options (provider-specific key)
|
||||
const resolvedEffort = getRawEffort(provider, modelOptions);
|
||||
|
||||
// Filter out prompt-injected efforts from the "current effort" display
|
||||
const isPromptInjected = resolvedEffort
|
||||
? caps.promptInjectedEffortLevels.includes(resolvedEffort)
|
||||
: false;
|
||||
const effort =
|
||||
resolvedEffort && !isPromptInjected && hasEffortLevel(caps, resolvedEffort)
|
||||
? resolvedEffort
|
||||
: defaultEffort && hasEffortLevel(caps, defaultEffort)
|
||||
? defaultEffort
|
||||
: null;
|
||||
const rawEffort = getRawEffort(provider, modelOptions);
|
||||
const effort = resolveEffort(caps, rawEffort) ?? null;
|
||||
|
||||
// Thinking toggle (only for models that support it)
|
||||
const thinkingEnabled = caps.supportsThinkingToggle
|
||||
@@ -104,6 +105,15 @@ function getSelectedTraits(
|
||||
caps.supportsFastMode &&
|
||||
(modelOptions as { fastMode?: boolean } | undefined)?.fastMode === true;
|
||||
|
||||
// Context window
|
||||
const contextWindowOptions = caps.contextWindowOptions;
|
||||
const rawContextWindow = getRawContextWindow(provider, modelOptions);
|
||||
const defaultContextWindow = getDefaultContextWindow(caps);
|
||||
const contextWindow =
|
||||
rawContextWindow && hasContextWindowOption(caps, rawContextWindow)
|
||||
? rawContextWindow
|
||||
: defaultContextWindow;
|
||||
|
||||
// Prompt-controlled effort (e.g. ultrathink in prompt text)
|
||||
const ultrathinkPromptControlled =
|
||||
allowPromptInjectedEffort &&
|
||||
@@ -116,6 +126,9 @@ function getSelectedTraits(
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
contextWindowOptions,
|
||||
contextWindow,
|
||||
defaultContextWindow,
|
||||
ultrathinkPromptControlled,
|
||||
};
|
||||
}
|
||||
@@ -159,6 +172,9 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
contextWindowOptions,
|
||||
contextWindow,
|
||||
defaultContextWindow,
|
||||
ultrathinkPromptControlled,
|
||||
} = getSelectedTraits(provider, models, model, prompt, modelOptions, allowPromptInjectedEffort);
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
@@ -194,7 +210,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
],
|
||||
);
|
||||
|
||||
if (effort === null && thinkingEnabled === null) {
|
||||
if (effort === null && thinkingEnabled === null && contextWindowOptions.length <= 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -258,6 +274,33 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
{contextWindowOptions.length > 1 ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
Context Window
|
||||
</div>
|
||||
<MenuRadioGroup
|
||||
value={contextWindow ?? defaultContextWindow ?? ""}
|
||||
onValueChange={(value) => {
|
||||
updateModelOptions(
|
||||
buildNextOptions(provider, modelOptions, {
|
||||
contextWindow: value,
|
||||
}),
|
||||
);
|
||||
}}
|
||||
>
|
||||
{contextWindowOptions.map((option) => (
|
||||
<MenuRadioItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
{option.value === defaultContextWindow ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
});
|
||||
@@ -281,12 +324,19 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
contextWindowOptions,
|
||||
contextWindow,
|
||||
defaultContextWindow,
|
||||
ultrathinkPromptControlled,
|
||||
} = getSelectedTraits(provider, models, model, prompt, modelOptions, allowPromptInjectedEffort);
|
||||
|
||||
const effortLabel = effort
|
||||
? (effortLevels.find((l) => l.value === effort)?.label ?? effort)
|
||||
: null;
|
||||
const contextWindowLabel =
|
||||
contextWindowOptions.length > 1 && contextWindow !== defaultContextWindow
|
||||
? (contextWindowOptions.find((o) => o.value === contextWindow)?.label ?? null)
|
||||
: null;
|
||||
const triggerLabel = [
|
||||
ultrathinkPromptControlled
|
||||
? "Ultrathink"
|
||||
@@ -296,6 +346,7 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
? null
|
||||
: `Thinking ${thinkingEnabled ? "On" : "Off"}`,
|
||||
...(caps.supportsFastMode && fastModeEnabled ? ["Fast"] : []),
|
||||
...(contextWindowLabel ? [contextWindowLabel] : []),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
@@ -16,6 +16,7 @@ const CODEX_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -35,6 +36,7 @@ const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
@@ -51,6 +53,7 @@ const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
@@ -62,6 +65,7 @@ const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
@@ -80,7 +84,9 @@ describe("getComposerProviderState", () => {
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
modelOptionsForDispatch: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -125,12 +131,13 @@ describe("getComposerProviderState", () => {
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("drops explicit codex default/off overrides from dispatch while keeping the selected effort label", () => {
|
||||
it("preserves codex default effort explicitly in dispatch options", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
@@ -147,7 +154,9 @@ describe("getComposerProviderState", () => {
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
modelOptionsForDispatch: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -163,7 +172,9 @@ describe("getComposerProviderState", () => {
|
||||
expect(state).toEqual({
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
modelOptionsForDispatch: {
|
||||
effort: "high",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -232,12 +243,13 @@ describe("getComposerProviderState", () => {
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
effort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("drops explicit Claude default/off overrides from dispatch while keeping the selected effort label", () => {
|
||||
it("preserves Claude default effort explicitly in dispatch options", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
@@ -254,7 +266,9 @@ describe("getComposerProviderState", () => {
|
||||
expect(state).toEqual({
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
modelOptionsForDispatch: {
|
||||
effort: "high",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,16 +1,10 @@
|
||||
import {
|
||||
type ModelSlug,
|
||||
type ProviderKind,
|
||||
type ProviderModelOptions,
|
||||
type ServerProviderModel,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
isClaudeUltrathinkPrompt,
|
||||
trimOrNull,
|
||||
getDefaultEffort,
|
||||
hasEffortLevel,
|
||||
} from "@t3tools/shared/model";
|
||||
import { isClaudeUltrathinkPrompt, resolveEffort } from "@t3tools/shared/model";
|
||||
import type { ReactNode } from "react";
|
||||
import {
|
||||
getProviderModelCapabilities,
|
||||
@@ -21,7 +15,7 @@ import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
|
||||
|
||||
export type ComposerProviderStateInput = {
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
prompt: string;
|
||||
modelOptions: ProviderModelOptions | null | undefined;
|
||||
@@ -40,7 +34,7 @@ type ProviderRegistryEntry = {
|
||||
getState: (input: ComposerProviderStateInput) => ComposerProviderState;
|
||||
renderTraitsMenuContent: (input: {
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
@@ -48,7 +42,7 @@ type ProviderRegistryEntry = {
|
||||
}) => ReactNode;
|
||||
renderTraitsPicker: (input: {
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
@@ -72,17 +66,7 @@ function getProviderStateFromCapabilities(
|
||||
: null
|
||||
: null;
|
||||
|
||||
const draftEffort = trimOrNull(rawEffort);
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
const isPromptInjected = draftEffort
|
||||
? caps.promptInjectedEffortLevels.includes(draftEffort)
|
||||
: false;
|
||||
const promptEffort =
|
||||
draftEffort && !isPromptInjected && hasEffortLevel(caps, draftEffort)
|
||||
? draftEffort
|
||||
: defaultEffort && hasEffortLevel(caps, defaultEffort)
|
||||
? defaultEffort
|
||||
: null;
|
||||
const promptEffort = resolveEffort(caps, rawEffort) ?? null;
|
||||
|
||||
// Normalize options for dispatch
|
||||
const normalizedOptions =
|
||||
@@ -180,7 +164,7 @@ export function getComposerProviderState(input: ComposerProviderStateInput): Com
|
||||
export function renderProviderTraitsMenuContent(input: {
|
||||
provider: ProviderKind;
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
@@ -199,7 +183,7 @@ export function renderProviderTraitsMenuContent(input: {
|
||||
export function renderProviderTraitsPicker(input: {
|
||||
provider: ProviderKind;
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
|
||||
@@ -5,8 +5,10 @@ import { useEffect, type CSSProperties } from "react";
|
||||
import { useParams } from "@tanstack/react-router";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CheckIcon,
|
||||
CircleAlertIcon,
|
||||
CircleCheckIcon,
|
||||
CopyIcon,
|
||||
InfoIcon,
|
||||
LoaderCircleIcon,
|
||||
TriangleAlertIcon,
|
||||
@@ -14,6 +16,7 @@ import {
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { buttonVariants } from "~/components/ui/button";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { buildVisibleToastLayout, shouldHideCollapsedToastContent } from "./toast.logic";
|
||||
|
||||
type ThreadToastData = {
|
||||
@@ -35,6 +38,25 @@ const TOAST_ICONS = {
|
||||
warning: TriangleAlertIcon,
|
||||
} as const;
|
||||
|
||||
function CopyErrorButton({ text }: { text: string }) {
|
||||
const { copyToClipboard, isCopied } = useCopyToClipboard();
|
||||
|
||||
return (
|
||||
<button
|
||||
className="shrink-0 cursor-pointer rounded-md p-1 text-muted-foreground opacity-60 transition-opacity hover:opacity-100"
|
||||
onClick={() => copyToClipboard(text)}
|
||||
title="Copy error"
|
||||
type="button"
|
||||
>
|
||||
{isCopied ? (
|
||||
<CheckIcon className="size-3.5 text-success" />
|
||||
) : (
|
||||
<CopyIcon className="size-3.5" />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
type ToastPosition =
|
||||
| "top-left"
|
||||
| "top-center"
|
||||
@@ -284,12 +306,17 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
)}
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
<div className="flex items-center justify-between gap-1">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
{toast.type === "error" && typeof toast.description === "string" && (
|
||||
<CopyErrorButton text={toast.description} />
|
||||
)}
|
||||
</div>
|
||||
<Toast.Description
|
||||
className="min-w-0 break-words text-muted-foreground"
|
||||
className="min-w-0 select-text break-words text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
@@ -373,12 +400,17 @@ function AnchoredToasts() {
|
||||
)}
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
<div className="flex items-center gap-1">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
{toast.type === "error" && typeof toast.description === "string" && (
|
||||
<CopyErrorButton text={toast.description} />
|
||||
)}
|
||||
</div>
|
||||
<Toast.Description
|
||||
className="min-w-0 break-words text-muted-foreground"
|
||||
className="min-w-0 select-text break-words text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
CODEX_REASONING_EFFORT_OPTIONS,
|
||||
type ClaudeCodeEffort,
|
||||
type CodexReasoningEffort,
|
||||
type ModelSlug,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
ModelSelection,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Equal from "effect/Equal";
|
||||
import { DeepMutable } from "effect/Types";
|
||||
import { getDefaultModel, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { useMemo } from "react";
|
||||
import { getLocalStorageItem } from "./hooks/useLocalStorage";
|
||||
import { resolveAppModelSelection } from "./modelSelection";
|
||||
@@ -263,7 +263,7 @@ interface ComposerDraftStoreState {
|
||||
}
|
||||
|
||||
export interface EffectiveComposerModelState {
|
||||
selectedModel: ModelSlug;
|
||||
selectedModel: string;
|
||||
modelOptions: ProviderModelOptions | null;
|
||||
}
|
||||
|
||||
@@ -475,12 +475,20 @@ function normalizeProviderModelOptions(
|
||||
: claudeCandidate?.fastMode === false
|
||||
? false
|
||||
: undefined;
|
||||
const claudeContextWindow =
|
||||
typeof claudeCandidate?.contextWindow === "string" && claudeCandidate.contextWindow.length > 0
|
||||
? claudeCandidate.contextWindow
|
||||
: undefined;
|
||||
const claude =
|
||||
claudeThinking !== undefined || claudeEffort !== undefined || claudeFastMode !== undefined
|
||||
claudeThinking !== undefined ||
|
||||
claudeEffort !== undefined ||
|
||||
claudeFastMode !== undefined ||
|
||||
claudeContextWindow !== undefined
|
||||
? {
|
||||
...(claudeThinking !== undefined ? { thinking: claudeThinking } : {}),
|
||||
...(claudeEffort !== undefined ? { effort: claudeEffort } : {}),
|
||||
...(claudeFastMode !== undefined ? { fastMode: claudeFastMode } : {}),
|
||||
...(claudeContextWindow !== undefined ? { contextWindow: claudeContextWindow } : {}),
|
||||
}
|
||||
: undefined;
|
||||
|
||||
@@ -594,7 +602,7 @@ function legacyToModelSelectionByProvider(
|
||||
model:
|
||||
modelSelection?.provider === provider
|
||||
? modelSelection.model
|
||||
: getDefaultModel(provider),
|
||||
: DEFAULT_MODEL_BY_PROVIDER[provider],
|
||||
options,
|
||||
};
|
||||
}
|
||||
@@ -1676,7 +1684,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (opts) {
|
||||
nextMap[provider] = {
|
||||
provider,
|
||||
model: current?.model ?? getDefaultModel(provider),
|
||||
model: current?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider],
|
||||
options: opts,
|
||||
};
|
||||
} else if (current?.options) {
|
||||
@@ -1726,7 +1734,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (providerOpts) {
|
||||
nextMap[normalizedProvider] = {
|
||||
provider: normalizedProvider,
|
||||
model: currentForProvider?.model ?? getDefaultModel(normalizedProvider),
|
||||
model: currentForProvider?.model ?? DEFAULT_MODEL_BY_PROVIDER[normalizedProvider],
|
||||
options: providerOpts,
|
||||
};
|
||||
} else if (currentForProvider?.options) {
|
||||
@@ -1744,7 +1752,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
base.modelSelectionByProvider[normalizedProvider] ??
|
||||
({
|
||||
provider: normalizedProvider,
|
||||
model: getDefaultModel(normalizedProvider),
|
||||
model: DEFAULT_MODEL_BY_PROVIDER[normalizedProvider],
|
||||
} as ModelSelection);
|
||||
if (providerOpts) {
|
||||
nextStickyMap[normalizedProvider] = {
|
||||
|
||||
+114
-1
@@ -9,6 +9,8 @@ import "./index.css";
|
||||
import { isElectron } from "./env";
|
||||
import { getRouter } from "./router";
|
||||
import { APP_DISPLAY_NAME } from "./branding";
|
||||
import { ensureBrowserPairing } from "./browserAuth";
|
||||
import { initializeNativeApi } from "./nativeApi";
|
||||
|
||||
// Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
|
||||
const history = isElectron ? createHashHistory() : createBrowserHistory();
|
||||
@@ -16,9 +18,120 @@ const history = isElectron ? createHashHistory() : createBrowserHistory();
|
||||
const router = getRouter(history);
|
||||
|
||||
document.title = APP_DISPLAY_NAME;
|
||||
const UNPAIRED_RETRY_INTERVAL_MS = 1_000;
|
||||
|
||||
function PairingRequiredScreen() {
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
|
||||
<div className="pointer-events-none absolute inset-0 opacity-80">
|
||||
<div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(42rem_16rem_at_top,color-mix(in_srgb,var(--color-amber-500)_16%,transparent),transparent)]" />
|
||||
<div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_92%,var(--color-black))_0%,var(--background)_56%)]" />
|
||||
</div>
|
||||
|
||||
<section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
|
||||
<p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
|
||||
{APP_DISPLAY_NAME}
|
||||
</p>
|
||||
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
|
||||
Browser pairing required
|
||||
</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
|
||||
This browser is not paired with the local T3 session.
|
||||
</p>
|
||||
<p className="mt-3 text-sm leading-relaxed text-muted-foreground">
|
||||
Restart <code>t3</code> to open a paired browser, or open the pairing URL printed in the
|
||||
CLI.
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BootstrappedApp() {
|
||||
const [state, setState] = React.useState<"loading" | "ready" | "unpaired">("loading");
|
||||
|
||||
React.useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
void ensureBrowserPairing()
|
||||
.then((authenticated) => {
|
||||
if (!active) return;
|
||||
if (!authenticated) {
|
||||
setState("unpaired");
|
||||
return;
|
||||
}
|
||||
initializeNativeApi();
|
||||
setState("ready");
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) {
|
||||
setState("unpaired");
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (state !== "unpaired") {
|
||||
return;
|
||||
}
|
||||
|
||||
let active = true;
|
||||
let retryTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const retry = () => {
|
||||
void ensureBrowserPairing()
|
||||
.then((authenticated) => {
|
||||
if (!active || !authenticated) {
|
||||
if (active) {
|
||||
retryTimeout = setTimeout(retry, UNPAIRED_RETRY_INTERVAL_MS);
|
||||
}
|
||||
return;
|
||||
}
|
||||
initializeNativeApi();
|
||||
setState("ready");
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) {
|
||||
retryTimeout = setTimeout(retry, UNPAIRED_RETRY_INTERVAL_MS);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
retryTimeout = setTimeout(retry, UNPAIRED_RETRY_INTERVAL_MS);
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
if (retryTimeout !== null) {
|
||||
clearTimeout(retryTimeout);
|
||||
}
|
||||
};
|
||||
}, [state]);
|
||||
|
||||
if (state === "loading") {
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-background text-foreground">
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Connecting to {APP_DISPLAY_NAME} server...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (state === "unpaired") {
|
||||
return <PairingRequiredScreen />;
|
||||
}
|
||||
|
||||
return <RouterProvider router={router} />;
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<RouterProvider router={router} />
|
||||
<BootstrappedApp />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
@@ -4,6 +4,21 @@ import { createWsNativeApi } from "./wsNativeApi";
|
||||
|
||||
let cachedApi: NativeApi | undefined;
|
||||
|
||||
export function initializeNativeApi(): NativeApi {
|
||||
if (typeof window === "undefined") {
|
||||
throw new Error("Native API not available outside the browser");
|
||||
}
|
||||
if (cachedApi) return cachedApi;
|
||||
|
||||
if (window.nativeApi) {
|
||||
cachedApi = window.nativeApi;
|
||||
return cachedApi;
|
||||
}
|
||||
|
||||
cachedApi = createWsNativeApi();
|
||||
return cachedApi;
|
||||
}
|
||||
|
||||
export function readNativeApi(): NativeApi | undefined {
|
||||
if (typeof window === "undefined") return undefined;
|
||||
if (cachedApi) return cachedApi;
|
||||
|
||||
@@ -7,17 +7,13 @@ import {
|
||||
type ServerProvider,
|
||||
type ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getDefaultEffort,
|
||||
hasEffortLevel,
|
||||
normalizeModelSlug,
|
||||
trimOrNull,
|
||||
} from "@t3tools/shared/model";
|
||||
import { normalizeModelSlug, resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
|
||||
|
||||
const EMPTY_CAPABILITIES: ModelCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
};
|
||||
|
||||
@@ -78,11 +74,10 @@ export function normalizeCodexModelOptionsWithCapabilities(
|
||||
caps: ModelCapabilities,
|
||||
modelOptions: CodexModelOptions | null | undefined,
|
||||
): CodexModelOptions | undefined {
|
||||
const defaultReasoningEffort = getDefaultEffort(caps);
|
||||
const reasoningEffort = trimOrNull(modelOptions?.reasoningEffort) ?? defaultReasoningEffort;
|
||||
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
|
||||
const fastModeEnabled = modelOptions?.fastMode === true;
|
||||
const nextOptions: CodexModelOptions = {
|
||||
...(reasoningEffort && reasoningEffort !== defaultReasoningEffort
|
||||
...(reasoningEffort
|
||||
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
|
||||
: {}),
|
||||
...(fastModeEnabled ? { fastMode: true } : {}),
|
||||
@@ -94,23 +89,16 @@ export function normalizeClaudeModelOptionsWithCapabilities(
|
||||
caps: ModelCapabilities,
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): ClaudeModelOptions | undefined {
|
||||
const defaultReasoningEffort = getDefaultEffort(caps);
|
||||
const resolvedEffort = trimOrNull(modelOptions?.effort);
|
||||
const isPromptInjected = caps.promptInjectedEffortLevels.includes(resolvedEffort ?? "");
|
||||
const effort =
|
||||
resolvedEffort &&
|
||||
!isPromptInjected &&
|
||||
hasEffortLevel(caps, resolvedEffort) &&
|
||||
resolvedEffort !== defaultReasoningEffort
|
||||
? resolvedEffort
|
||||
: undefined;
|
||||
const effort = resolveEffort(caps, modelOptions?.effort);
|
||||
const thinking =
|
||||
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
|
||||
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
|
||||
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
|
||||
const nextOptions: ClaudeModelOptions = {
|
||||
...(thinking === false ? { thinking: false } : {}),
|
||||
...(effort ? { effort } : {}),
|
||||
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(contextWindow ? { contextWindow } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
@@ -17,6 +17,20 @@ describe("parsePullRequestReference", () => {
|
||||
expect(parsePullRequestReference("#42")).toBe("#42");
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with raw numbers", () => {
|
||||
expect(parsePullRequestReference("gh pr checkout 42")).toBe("42");
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with #number references", () => {
|
||||
expect(parsePullRequestReference("gh pr checkout #42")).toBe("#42");
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with GitHub pull request URLs", () => {
|
||||
expect(
|
||||
parsePullRequestReference("gh pr checkout https://github.com/pingdotgg/t3code/pull/42"),
|
||||
).toBe("https://github.com/pingdotgg/t3code/pull/42");
|
||||
});
|
||||
|
||||
it("rejects non-pull-request input", () => {
|
||||
expect(parsePullRequestReference("feature/my-branch")).toBeNull();
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const GITHUB_PULL_REQUEST_URL_PATTERN =
|
||||
/^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)(?:[/?#].*)?$/i;
|
||||
const PULL_REQUEST_NUMBER_PATTERN = /^#?(\d+)$/;
|
||||
const GITHUB_CLI_PR_CHECKOUT_PATTERN = /^gh\s+pr\s+checkout\s+(.+)$/i;
|
||||
|
||||
export function parsePullRequestReference(input: string): string | null {
|
||||
const trimmed = input.trim();
|
||||
@@ -8,14 +9,20 @@ export function parsePullRequestReference(input: string): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
const urlMatch = GITHUB_PULL_REQUEST_URL_PATTERN.exec(trimmed);
|
||||
if (urlMatch?.[1]) {
|
||||
return trimmed;
|
||||
const ghCliCheckoutMatch = GITHUB_CLI_PR_CHECKOUT_PATTERN.exec(trimmed);
|
||||
const normalizedInput = ghCliCheckoutMatch?.[1]?.trim() ?? trimmed;
|
||||
if (normalizedInput.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const numberMatch = PULL_REQUEST_NUMBER_PATTERN.exec(trimmed);
|
||||
const urlMatch = GITHUB_PULL_REQUEST_URL_PATTERN.exec(normalizedInput);
|
||||
if (urlMatch?.[1]) {
|
||||
return normalizedInput;
|
||||
}
|
||||
|
||||
const numberMatch = PULL_REQUEST_NUMBER_PATTERN.exec(normalizedInput);
|
||||
if (numberMatch?.[1]) {
|
||||
return trimmed.startsWith("#") ? trimmed : numberMatch[1];
|
||||
return normalizedInput.startsWith("#") ? normalizedInput : numberMatch[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { ChevronDownIcon, InfoIcon, PlusIcon, RotateCcwIcon, Undo2Icon, XIcon } from "lucide-react";
|
||||
import { type ReactNode, useCallback, useRef, useState } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
InfoIcon,
|
||||
LoaderIcon,
|
||||
PlusIcon,
|
||||
RefreshCwIcon,
|
||||
RotateCcwIcon,
|
||||
Undo2Icon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { type ReactNode, useCallback, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
type ProviderKind,
|
||||
@@ -35,8 +44,9 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../components/ui/tooltip"
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
|
||||
import { cn } from "../lib/utils";
|
||||
import { formatRelativeTime } from "../timestampFormat";
|
||||
import { ensureNativeApi, readNativeApi } from "../nativeApi";
|
||||
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import { Equal } from "effect";
|
||||
@@ -173,12 +183,33 @@ function getProviderVersionLabel(version: string | null | undefined): string | n
|
||||
return version.startsWith("v") ? version : `v${version}`;
|
||||
}
|
||||
|
||||
function SettingsSection({ title, children }: { title: string; children: ReactNode }) {
|
||||
/** Returns a timestamp that updates on an interval, forcing re-renders to keep relative times fresh. */
|
||||
function useRelativeTimeTick(intervalMs = 1_000): number {
|
||||
const [tick, setTick] = useState(() => Date.now());
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setTick(Date.now()), intervalMs);
|
||||
return () => clearInterval(id);
|
||||
}, [intervalMs]);
|
||||
return tick;
|
||||
}
|
||||
|
||||
function SettingsSection({
|
||||
title,
|
||||
headerAction,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
headerAction?: ReactNode;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground">
|
||||
{title}
|
||||
</h2>
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground">
|
||||
{title}
|
||||
</h2>
|
||||
{headerAction}
|
||||
</div>
|
||||
<div className="relative overflow-hidden rounded-2xl border bg-card not-dark:bg-clip-padding text-card-foreground shadow-xs/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]">
|
||||
{children}
|
||||
</div>
|
||||
@@ -280,6 +311,27 @@ function SettingsRouteView() {
|
||||
const [customModelErrorByProvider, setCustomModelErrorByProvider] = useState<
|
||||
Partial<Record<ProviderKind, string | null>>
|
||||
>({});
|
||||
const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
|
||||
const refreshingRef = useRef(false);
|
||||
const queryClient = useQueryClient();
|
||||
useRelativeTimeTick();
|
||||
|
||||
const refreshProviders = useCallback(() => {
|
||||
if (refreshingRef.current) return;
|
||||
refreshingRef.current = true;
|
||||
setIsRefreshingProviders(true);
|
||||
const api = ensureNativeApi();
|
||||
api.server
|
||||
.refreshProviders()
|
||||
.then(() => queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() }))
|
||||
.catch((error: unknown) => {
|
||||
console.warn("Failed to refresh providers", error);
|
||||
})
|
||||
.finally(() => {
|
||||
refreshingRef.current = false;
|
||||
setIsRefreshingProviders(false);
|
||||
});
|
||||
}, [queryClient]);
|
||||
|
||||
const modelListRefs = useRef<Partial<Record<ProviderKind, HTMLDivElement | null>>>({});
|
||||
|
||||
@@ -832,7 +884,55 @@ function SettingsRouteView() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="Providers">
|
||||
<SettingsSection
|
||||
title="Providers"
|
||||
headerAction={
|
||||
<div className="flex items-center gap-1.5">
|
||||
{serverProviders.length > 0 ? (
|
||||
<span className="text-[11px] text-muted-foreground/60">
|
||||
{(() => {
|
||||
const rel = formatRelativeTime(
|
||||
serverProviders.reduce(
|
||||
(latest, provider) =>
|
||||
provider.checkedAt > latest ? provider.checkedAt : latest,
|
||||
serverProviders[0]!.checkedAt,
|
||||
),
|
||||
);
|
||||
return rel.suffix ? (
|
||||
<>
|
||||
Checked <span className="font-mono tabular-nums">{rel.value}</span>{" "}
|
||||
{rel.suffix}
|
||||
</>
|
||||
) : (
|
||||
<>Checked {rel.value}</>
|
||||
);
|
||||
})()}
|
||||
</span>
|
||||
) : null}
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
|
||||
disabled={isRefreshingProviders}
|
||||
onClick={() => void refreshProviders()}
|
||||
aria-label="Refresh provider status"
|
||||
>
|
||||
{isRefreshingProviders ? (
|
||||
<LoaderIcon className="size-3 animate-spin" />
|
||||
) : (
|
||||
<RefreshCwIcon className="size-3" />
|
||||
)}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Refresh provider status</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{providerCards.map((providerCard) => {
|
||||
const customModelInput = customModelInputByProvider[providerCard.provider];
|
||||
const customModelError = customModelErrorByProvider[providerCard.provider] ?? null;
|
||||
|
||||
+2
-22
@@ -9,6 +9,7 @@ import { resolveModelSlugForProvider } from "@t3tools/shared/model";
|
||||
import { create } from "zustand";
|
||||
import { type ChatMessage, type Project, type Thread } from "./types";
|
||||
import { Debouncer } from "@tanstack/react-pacer";
|
||||
import { resolveServerHttpOrigin } from "./browserAuth";
|
||||
|
||||
// ── State ────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -199,30 +200,9 @@ function toLegacyProvider(providerName: string | null): ProviderKind {
|
||||
return "codex";
|
||||
}
|
||||
|
||||
function resolveWsHttpOrigin(): string {
|
||||
if (typeof window === "undefined") return "";
|
||||
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsCandidate =
|
||||
typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
|
||||
? bridgeWsUrl
|
||||
: typeof envWsUrl === "string" && envWsUrl.length > 0
|
||||
? envWsUrl
|
||||
: null;
|
||||
if (!wsCandidate) return window.location.origin;
|
||||
try {
|
||||
const wsUrl = new URL(wsCandidate);
|
||||
const protocol =
|
||||
wsUrl.protocol === "wss:" ? "https:" : wsUrl.protocol === "ws:" ? "http:" : wsUrl.protocol;
|
||||
return `${protocol}//${wsUrl.host}`;
|
||||
} catch {
|
||||
return window.location.origin;
|
||||
}
|
||||
}
|
||||
|
||||
function toAttachmentPreviewUrl(rawUrl: string): string {
|
||||
if (rawUrl.startsWith("/")) {
|
||||
return `${resolveWsHttpOrigin()}${rawUrl}`;
|
||||
return `${resolveServerHttpOrigin()}${rawUrl}`;
|
||||
}
|
||||
return rawUrl;
|
||||
}
|
||||
|
||||
@@ -47,3 +47,22 @@ export function formatTimestamp(isoDate: string, timestampFormat: TimestampForma
|
||||
export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
|
||||
return getTimestampFormatter(timestampFormat, false).format(new Date(isoDate));
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a relative time string from an ISO date.
|
||||
* Returns `{ value: "20s", suffix: "ago" }` or `{ value: "just now", suffix: null }`
|
||||
* so callers can style the numeric portion independently.
|
||||
*/
|
||||
export function formatRelativeTime(isoDate: string): { value: string; suffix: string | null } {
|
||||
const diffMs = Date.now() - new Date(isoDate).getTime();
|
||||
if (diffMs < 0) return { value: "just now", suffix: null };
|
||||
const seconds = Math.floor(diffMs / 1000);
|
||||
if (seconds < 5) return { value: "just now", suffix: null };
|
||||
if (seconds < 60) return { value: `${seconds}s`, suffix: "ago" };
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24) return { value: `${hours}h`, suffix: "ago" };
|
||||
const days = Math.floor(hours / 24);
|
||||
return { value: `${days}d`, suffix: "ago" };
|
||||
}
|
||||
@@ -210,6 +210,7 @@ export function createWsNativeApi(): NativeApi {
|
||||
},
|
||||
server: {
|
||||
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
||||
refreshProviders: () => transport.request(WS_METHODS.serverRefreshProviders),
|
||||
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
|
||||
getSettings: () => transport.request(WS_METHODS.serverGetSettings),
|
||||
updateSettings: (patch) => transport.request(WS_METHODS.serverUpdateSettings, { patch }),
|
||||
|
||||
@@ -2,11 +2,18 @@ import { Schema } from "effect";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||
|
||||
export const EDITORS = [
|
||||
{ id: "cursor", label: "Cursor", command: "cursor" },
|
||||
{ id: "vscode", label: "VS Code", command: "code" },
|
||||
{ id: "zed", label: "Zed", command: "zed" },
|
||||
{ id: "antigravity", label: "Antigravity", command: "agy" },
|
||||
{ id: "file-manager", label: "File Manager", command: null },
|
||||
{ id: "cursor", label: "Cursor", command: "cursor", supportsGoto: true },
|
||||
{ id: "vscode", label: "VS Code", command: "code", supportsGoto: true },
|
||||
{
|
||||
id: "vscode-insiders",
|
||||
label: "VS Code Insiders",
|
||||
command: "code-insiders",
|
||||
supportsGoto: true,
|
||||
},
|
||||
{ id: "vscodium", label: "VSCodium", command: "codium", supportsGoto: true },
|
||||
{ id: "zed", label: "Zed", command: "zed", supportsGoto: false },
|
||||
{ id: "antigravity", label: "Antigravity", command: "agy", supportsGoto: false },
|
||||
{ id: "file-manager", label: "File Manager", command: null, supportsGoto: false },
|
||||
] as const;
|
||||
|
||||
export const EditorId = Schema.Literals(EDITORS.map((e) => e.id));
|
||||
|
||||
@@ -25,7 +25,11 @@ import type {
|
||||
ProjectWriteFileInput,
|
||||
ProjectWriteFileResult,
|
||||
} from "./project";
|
||||
import type { ServerConfig, ServerUpsertKeybindingResult } from "./server";
|
||||
import type {
|
||||
ServerConfig,
|
||||
ServerProviderUpdatedPayload,
|
||||
ServerUpsertKeybindingResult,
|
||||
} from "./server";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
@@ -161,6 +165,7 @@ export interface NativeApi {
|
||||
};
|
||||
server: {
|
||||
getConfig: () => Promise<ServerConfig>;
|
||||
refreshProviders: () => Promise<ServerProviderUpdatedPayload>;
|
||||
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
|
||||
getSettings: () => Promise<ServerSettings>;
|
||||
updateSettings: (patch: ServerSettingsPatch) => Promise<ServerSettings>;
|
||||
|
||||
@@ -18,6 +18,7 @@ export const ClaudeModelOptions = Schema.Struct({
|
||||
thinking: Schema.optional(Schema.Boolean),
|
||||
effort: Schema.optional(Schema.Literals(CLAUDE_CODE_EFFORT_OPTIONS)),
|
||||
fastMode: Schema.optional(Schema.Boolean),
|
||||
contextWindow: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ClaudeModelOptions = typeof ClaudeModelOptions.Type;
|
||||
|
||||
@@ -34,17 +35,23 @@ export const EffortOption = Schema.Struct({
|
||||
});
|
||||
export type EffortOption = typeof EffortOption.Type;
|
||||
|
||||
export const ContextWindowOption = Schema.Struct({
|
||||
value: TrimmedNonEmptyString,
|
||||
label: TrimmedNonEmptyString,
|
||||
isDefault: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type ContextWindowOption = typeof ContextWindowOption.Type;
|
||||
|
||||
export const ModelCapabilities = Schema.Struct({
|
||||
reasoningEffortLevels: Schema.Array(EffortOption),
|
||||
supportsFastMode: Schema.Boolean,
|
||||
supportsThinkingToggle: Schema.Boolean,
|
||||
contextWindowOptions: Schema.Array(ContextWindowOption),
|
||||
promptInjectedEffortLevels: Schema.Array(TrimmedNonEmptyString),
|
||||
});
|
||||
export type ModelCapabilities = typeof ModelCapabilities.Type;
|
||||
|
||||
export type ModelSlug = string & {};
|
||||
|
||||
export const DEFAULT_MODEL_BY_PROVIDER: Record<ProviderKind, ModelSlug> = {
|
||||
export const DEFAULT_MODEL_BY_PROVIDER: Record<ProviderKind, string> = {
|
||||
codex: "gpt-5.4",
|
||||
claudeAgent: "claude-sonnet-4-6",
|
||||
};
|
||||
@@ -57,7 +64,7 @@ export const DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER: Record<ProviderKind,
|
||||
claudeAgent: "claude-haiku-4-5",
|
||||
};
|
||||
|
||||
export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string, ModelSlug>> = {
|
||||
export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string, string>> = {
|
||||
codex: {
|
||||
"5.4": "gpt-5.4",
|
||||
"5.3": "gpt-5.3-codex",
|
||||
|
||||
@@ -76,6 +76,7 @@ export const WS_METHODS = {
|
||||
|
||||
// Server meta
|
||||
serverGetConfig: "server.getConfig",
|
||||
serverRefreshProviders: "server.refreshProviders",
|
||||
serverUpsertKeybinding: "server.upsertKeybinding",
|
||||
serverGetSettings: "server.getSettings",
|
||||
serverUpdateSettings: "server.updateSettings",
|
||||
@@ -144,6 +145,7 @@ const WebSocketRequestBody = Schema.Union([
|
||||
|
||||
// Server meta
|
||||
tagRequestBody(WS_METHODS.serverGetConfig, Schema.Struct({})),
|
||||
tagRequestBody(WS_METHODS.serverRefreshProviders, Schema.Struct({})),
|
||||
tagRequestBody(WS_METHODS.serverUpsertKeybinding, KeybindingRule),
|
||||
tagRequestBody(WS_METHODS.serverGetSettings, Schema.Struct({})),
|
||||
tagRequestBody(WS_METHODS.serverUpdateSettings, Schema.Struct({ patch: ServerSettingsPatch })),
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ModelCapabilities,
|
||||
} from "@t3tools/contracts";
|
||||
import { DEFAULT_MODEL_BY_PROVIDER, type ModelCapabilities } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getDefaultContextWindow,
|
||||
getDefaultEffort,
|
||||
hasContextWindowOption,
|
||||
hasEffortLevel,
|
||||
isClaudeUltrathinkPrompt,
|
||||
normalizeModelSlug,
|
||||
resolveApiModelId,
|
||||
resolveContextWindow,
|
||||
resolveEffort,
|
||||
resolveModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
resolveSelectableModel,
|
||||
@@ -24,6 +25,7 @@ const codexCaps: ModelCapabilities = {
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
};
|
||||
|
||||
@@ -35,6 +37,10 @@ const claudeCaps: ModelCapabilities = {
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
};
|
||||
|
||||
@@ -54,14 +60,15 @@ describe("normalizeModelSlug", () => {
|
||||
|
||||
describe("resolveModelSlug", () => {
|
||||
it("returns defaults when the model is missing", () => {
|
||||
expect(resolveModelSlug(undefined)).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug(undefined, "codex")).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
|
||||
expect(resolveModelSlugForProvider("claudeAgent", undefined)).toBe(
|
||||
DEFAULT_MODEL_BY_PROVIDER.claudeAgent,
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves normalized unknown models", () => {
|
||||
expect(resolveModelSlug("custom/internal-model")).toBe("custom/internal-model");
|
||||
expect(resolveModelSlug("custom/internal-model", "codex")).toBe("custom/internal-model");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -89,6 +96,42 @@ describe("capability helpers", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveEffort", () => {
|
||||
it("returns the explicit value when supported and not prompt-injected", () => {
|
||||
expect(resolveEffort(codexCaps, "xhigh")).toBe("xhigh");
|
||||
expect(resolveEffort(codexCaps, "high")).toBe("high");
|
||||
expect(resolveEffort(claudeCaps, "medium")).toBe("medium");
|
||||
});
|
||||
|
||||
it("falls back to default when value is unsupported", () => {
|
||||
expect(resolveEffort(codexCaps, "bogus")).toBe("high");
|
||||
expect(resolveEffort(claudeCaps, "bogus")).toBe("high");
|
||||
});
|
||||
|
||||
it("returns the default when no value is provided", () => {
|
||||
expect(resolveEffort(codexCaps, undefined)).toBe("high");
|
||||
expect(resolveEffort(codexCaps, null)).toBe("high");
|
||||
expect(resolveEffort(codexCaps, "")).toBe("high");
|
||||
expect(resolveEffort(codexCaps, " ")).toBe("high");
|
||||
});
|
||||
|
||||
it("excludes prompt-injected efforts and falls back to default", () => {
|
||||
expect(resolveEffort(claudeCaps, "ultrathink")).toBe("high");
|
||||
});
|
||||
|
||||
it("returns undefined for models with no effort levels", () => {
|
||||
const noCaps: ModelCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
};
|
||||
expect(resolveEffort(noCaps, undefined)).toBeUndefined();
|
||||
expect(resolveEffort(noCaps, "high")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("misc helpers", () => {
|
||||
it("detects ultrathink prompts", () => {
|
||||
expect(isClaudeUltrathinkPrompt("Ultrathink:\nInvestigate")).toBe(true);
|
||||
@@ -109,3 +152,77 @@ describe("misc helpers", () => {
|
||||
expect(trimOrNull(" ")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("context window helpers", () => {
|
||||
it("reads default context window", () => {
|
||||
expect(getDefaultContextWindow(claudeCaps)).toBe("1m");
|
||||
});
|
||||
|
||||
it("returns null for models without context window options", () => {
|
||||
expect(getDefaultContextWindow(codexCaps)).toBeNull();
|
||||
});
|
||||
|
||||
it("checks context window support", () => {
|
||||
expect(hasContextWindowOption(claudeCaps, "1m")).toBe(true);
|
||||
expect(hasContextWindowOption(claudeCaps, "200k")).toBe(true);
|
||||
expect(hasContextWindowOption(claudeCaps, "bogus")).toBe(false);
|
||||
expect(hasContextWindowOption(codexCaps, "1m")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveContextWindow", () => {
|
||||
it("returns the explicit value when supported", () => {
|
||||
expect(resolveContextWindow(claudeCaps, "200k")).toBe("200k");
|
||||
expect(resolveContextWindow(claudeCaps, "1m")).toBe("1m");
|
||||
});
|
||||
|
||||
it("falls back to default when value is unsupported", () => {
|
||||
expect(resolveContextWindow(claudeCaps, "bogus")).toBe("1m");
|
||||
});
|
||||
|
||||
it("returns the default when no value is provided", () => {
|
||||
expect(resolveContextWindow(claudeCaps, undefined)).toBe("1m");
|
||||
expect(resolveContextWindow(claudeCaps, null)).toBe("1m");
|
||||
expect(resolveContextWindow(claudeCaps, "")).toBe("1m");
|
||||
});
|
||||
|
||||
it("returns undefined for models with no context window options", () => {
|
||||
expect(resolveContextWindow(codexCaps, undefined)).toBeUndefined();
|
||||
expect(resolveContextWindow(codexCaps, "1m")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveApiModelId", () => {
|
||||
it("appends [1m] suffix for 1m context window", () => {
|
||||
expect(
|
||||
resolveApiModelId({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: { contextWindow: "1m" },
|
||||
}),
|
||||
).toBe("claude-opus-4-6[1m]");
|
||||
});
|
||||
|
||||
it("returns the model as-is for 200k context window", () => {
|
||||
expect(
|
||||
resolveApiModelId({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: { contextWindow: "200k" },
|
||||
}),
|
||||
).toBe("claude-opus-4-6");
|
||||
});
|
||||
|
||||
it("returns the model as-is when no context window is set", () => {
|
||||
expect(resolveApiModelId({ provider: "claudeAgent", model: "claude-opus-4-6" })).toBe(
|
||||
"claude-opus-4-6",
|
||||
);
|
||||
expect(
|
||||
resolveApiModelId({ provider: "claudeAgent", model: "claude-opus-4-6", options: {} }),
|
||||
).toBe("claude-opus-4-6");
|
||||
});
|
||||
|
||||
it("returns the model as-is for Codex selections", () => {
|
||||
expect(resolveApiModelId({ provider: "codex", model: "gpt-5.4" })).toBe("gpt-5.4");
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
MODEL_SLUG_ALIASES_BY_PROVIDER,
|
||||
type ClaudeCodeEffort,
|
||||
type ModelCapabilities,
|
||||
type ModelSlug,
|
||||
type ModelSelection,
|
||||
type ProviderKind,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
@@ -12,10 +12,6 @@ export interface SelectableModelOption {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export function getDefaultModel(provider: ProviderKind = "codex"): ModelSlug {
|
||||
return DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
// ── Effort helpers ────────────────────────────────────────────────────
|
||||
|
||||
/** Check whether a capabilities object includes a given effort value. */
|
||||
@@ -28,6 +24,65 @@ export function getDefaultEffort(caps: ModelCapabilities): string | null {
|
||||
return caps.reasoningEffortLevels.find((l) => l.isDefault)?.value ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a raw effort option against capabilities.
|
||||
*
|
||||
* Returns the effective effort value — the explicit value if supported and not
|
||||
* prompt-injected, otherwise the model's default. Returns `undefined` only
|
||||
* when the model has no effort levels at all.
|
||||
*
|
||||
* Prompt-injected efforts (e.g. "ultrathink") are excluded because they are
|
||||
* applied via prompt text, not the effort API parameter.
|
||||
*/
|
||||
export function resolveEffort(
|
||||
caps: ModelCapabilities,
|
||||
raw: string | null | undefined,
|
||||
): string | undefined {
|
||||
const defaultValue = getDefaultEffort(caps);
|
||||
const trimmed = typeof raw === "string" ? raw.trim() : null;
|
||||
if (
|
||||
trimmed &&
|
||||
!caps.promptInjectedEffortLevels.includes(trimmed) &&
|
||||
hasEffortLevel(caps, trimmed)
|
||||
) {
|
||||
return trimmed;
|
||||
}
|
||||
return defaultValue ?? undefined;
|
||||
}
|
||||
|
||||
// ── Context window helpers ───────────────────────────────────────────
|
||||
|
||||
/** Check whether a capabilities object includes a given context window value. */
|
||||
export function hasContextWindowOption(caps: ModelCapabilities, value: string): boolean {
|
||||
return caps.contextWindowOptions.some((o) => o.value === value);
|
||||
}
|
||||
|
||||
/** Return the default context window value, or `null` if none is defined. */
|
||||
export function getDefaultContextWindow(caps: ModelCapabilities): string | null {
|
||||
return caps.contextWindowOptions.find((o) => o.isDefault)?.value ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a raw `contextWindow` option against capabilities.
|
||||
*
|
||||
* Returns the effective context window value — the explicit value if supported,
|
||||
* otherwise the model's default. Returns `undefined` only when the model has
|
||||
* no context window options at all.
|
||||
*
|
||||
* Unlike effort levels (where the API has matching defaults), the context
|
||||
* window requires an explicit API suffix (e.g. `[1m]`), so we always preserve
|
||||
* the resolved value to avoid ambiguity between "user chose the default" and
|
||||
* "not specified".
|
||||
*/
|
||||
export function resolveContextWindow(
|
||||
caps: ModelCapabilities,
|
||||
raw: string | null | undefined,
|
||||
): string | undefined {
|
||||
const defaultValue = getDefaultContextWindow(caps);
|
||||
if (!raw) return defaultValue ?? undefined;
|
||||
return hasContextWindowOption(caps, raw) ? raw : (defaultValue ?? undefined);
|
||||
}
|
||||
|
||||
export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {
|
||||
return typeof text === "string" && /\bultrathink\b/i.test(text);
|
||||
}
|
||||
@@ -35,7 +90,7 @@ export function isClaudeUltrathinkPrompt(text: string | null | undefined): boole
|
||||
export function normalizeModelSlug(
|
||||
model: string | null | undefined,
|
||||
provider: ProviderKind = "codex",
|
||||
): ModelSlug | null {
|
||||
): string | null {
|
||||
if (typeof model !== "string") {
|
||||
return null;
|
||||
}
|
||||
@@ -45,18 +100,18 @@ export function normalizeModelSlug(
|
||||
return null;
|
||||
}
|
||||
|
||||
const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] as Record<string, ModelSlug>;
|
||||
const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] as Record<string, string>;
|
||||
const aliased = Object.prototype.hasOwnProperty.call(aliases, trimmed)
|
||||
? aliases[trimmed]
|
||||
: undefined;
|
||||
return typeof aliased === "string" ? aliased : (trimmed as ModelSlug);
|
||||
return typeof aliased === "string" ? aliased : trimmed;
|
||||
}
|
||||
|
||||
export function resolveSelectableModel(
|
||||
provider: ProviderKind,
|
||||
value: string | null | undefined,
|
||||
options: ReadonlyArray<SelectableModelOption>,
|
||||
): ModelSlug | null {
|
||||
): string | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
@@ -85,10 +140,7 @@ export function resolveSelectableModel(
|
||||
return resolved ? resolved.slug : null;
|
||||
}
|
||||
|
||||
export function resolveModelSlug(
|
||||
model: string | null | undefined,
|
||||
provider: ProviderKind = "codex",
|
||||
): ModelSlug {
|
||||
export function resolveModelSlug(model: string | null | undefined, provider: ProviderKind): string {
|
||||
const normalized = normalizeModelSlug(model, provider);
|
||||
if (!normalized) {
|
||||
return DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
@@ -99,7 +151,7 @@ export function resolveModelSlug(
|
||||
export function resolveModelSlugForProvider(
|
||||
provider: ProviderKind,
|
||||
model: string | null | undefined,
|
||||
): ModelSlug {
|
||||
): string {
|
||||
return resolveModelSlug(model, provider);
|
||||
}
|
||||
|
||||
@@ -110,6 +162,33 @@ export function trimOrNull<T extends string>(value: T | null | undefined): T | n
|
||||
return trimmed || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the actual API model identifier from a model selection.
|
||||
*
|
||||
* Provider-aware: each provider can map `contextWindow` (or other options)
|
||||
* to whatever the API requires — a model-id suffix, a separate parameter, etc.
|
||||
* The canonical slug stored in the selection stays unchanged so the
|
||||
* capabilities system keeps working.
|
||||
*
|
||||
* Expects `contextWindow` to already be resolved (via `resolveContextWindow`)
|
||||
* to the effective value, not stripped to `undefined` for defaults.
|
||||
*/
|
||||
export function resolveApiModelId(modelSelection: ModelSelection): string {
|
||||
switch (modelSelection.provider) {
|
||||
case "claudeAgent": {
|
||||
switch (modelSelection.options?.contextWindow) {
|
||||
case "1m":
|
||||
return `${modelSelection.model}[1m]`;
|
||||
default:
|
||||
return modelSelection.model;
|
||||
}
|
||||
}
|
||||
default: {
|
||||
return modelSelection.model;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function applyClaudePromptEffortPrefix(
|
||||
text: string,
|
||||
effort: ClaudeCodeEffort | null | undefined,
|
||||
|
||||
Reference in new issue
Block a user