Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ac9c0321d | ||
|
|
f0e4ec40ed | ||
|
|
d3c4644759 | ||
|
|
b8f0110d4c | ||
|
|
30c9622806 | ||
|
|
69dfb7f09a | ||
|
|
e60821f0e0 | ||
|
|
64bf016191 |
No files matched your search
@@ -17,6 +17,7 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
import * as DesktopShutdown from "./DesktopShutdown.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
@@ -220,6 +221,7 @@ const startup = Effect.gen(function* () {
|
||||
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
@@ -248,6 +250,7 @@ const startup = Effect.gen(function* () {
|
||||
yield* appIdentity.configure;
|
||||
yield* applicationMenu.configure;
|
||||
yield* updates.configure;
|
||||
yield* linuxUrlHandler.register;
|
||||
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
|
||||
}).pipe(Effect.withSpan("desktop.startup"));
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ const compactEnv = (env: Readonly<Record<string, string | undefined>>): Record<s
|
||||
export const DesktopConfig = Config.all({
|
||||
appDataDirectory: trimmedString("APPDATA"),
|
||||
xdgConfigHome: trimmedString("XDG_CONFIG_HOME"),
|
||||
xdgDataHome: trimmedString("XDG_DATA_HOME"),
|
||||
t3Home: trimmedString("T3CODE_HOME"),
|
||||
devServerUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option),
|
||||
appUserModelIdOverride: trimmedString("T3CODE_DESKTOP_APP_USER_MODEL_ID"),
|
||||
|
||||
@@ -66,6 +66,8 @@ export class DesktopEnvironment extends Context.Service<
|
||||
readonly appUserModelId: string;
|
||||
readonly linuxDesktopEntryName: string;
|
||||
readonly linuxWmClass: string;
|
||||
readonly linuxApplicationsDir: string;
|
||||
readonly appImagePath: Option.Option<string>;
|
||||
readonly userDataDirName: string;
|
||||
readonly legacyUserDataDirName: string;
|
||||
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
|
||||
@@ -162,6 +164,10 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
);
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const linuxApplicationsDir = path.join(
|
||||
Option.getOrElse(config.xdgDataHome, () => path.join(homeDirectory, ".local", "share")),
|
||||
"applications",
|
||||
);
|
||||
const resourcesPath = input.resourcesPath;
|
||||
|
||||
return DesktopEnvironment.of({
|
||||
@@ -205,6 +211,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
),
|
||||
linuxDesktopEntryName: isDevelopment ? "t3code-dev.desktop" : "t3code.desktop",
|
||||
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
|
||||
linuxApplicationsDir,
|
||||
appImagePath: config.appImagePath,
|
||||
userDataDirName,
|
||||
legacyUserDataDirName,
|
||||
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
|
||||
|
||||
interface RecordedRegistration {
|
||||
readonly directories: string[];
|
||||
readonly files: Array<{ readonly path: string; readonly content: string }>;
|
||||
readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
|
||||
}
|
||||
|
||||
const makeEnvironment = (overrides: Record<string, unknown> = {}) =>
|
||||
DesktopEnvironment.DesktopEnvironment.of({
|
||||
platform: "linux",
|
||||
isPackaged: true,
|
||||
isDevelopment: false,
|
||||
displayName: "T3 Code (Alpha)",
|
||||
linuxWmClass: "t3code",
|
||||
linuxApplicationsDir: "/home/alice/.local/share/applications",
|
||||
appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
|
||||
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
|
||||
...overrides,
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
const mockProcess = (exitCode: number) =>
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.empty,
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
|
||||
const makeHandlerLayer = (
|
||||
recorded: RecordedRegistration,
|
||||
input: {
|
||||
readonly environment?: Record<string, unknown>;
|
||||
readonly xdgMimeExitCode?: number;
|
||||
readonly writeError?: PlatformError.PlatformError;
|
||||
} = {},
|
||||
) =>
|
||||
DesktopLinuxUrlHandler.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(DesktopEnvironment.DesktopEnvironment, makeEnvironment(input.environment)),
|
||||
FileSystem.layerNoop({
|
||||
makeDirectory: (path) =>
|
||||
Effect.sync(() => {
|
||||
recorded.directories.push(path);
|
||||
}),
|
||||
writeFileString: (path, content) =>
|
||||
input.writeError
|
||||
? Effect.fail(input.writeError)
|
||||
: Effect.sync(() => {
|
||||
recorded.files.push({ path, content });
|
||||
}),
|
||||
}),
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
recorded.commands.push({
|
||||
command: childProcess.command,
|
||||
args: childProcess.args,
|
||||
});
|
||||
return Effect.succeed(mockProcess(input.xdgMimeExitCode ?? 0));
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const runRegister = (
|
||||
recorded: RecordedRegistration,
|
||||
input: Parameters<typeof makeHandlerLayer>[1] = {},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
|
||||
yield* handler.register;
|
||||
}).pipe(Effect.provide(makeHandlerLayer(recorded, input)));
|
||||
|
||||
const emptyRecording = (): RecordedRegistration => ({
|
||||
directories: [],
|
||||
files: [],
|
||||
commands: [],
|
||||
});
|
||||
|
||||
describe("DesktopLinuxUrlHandler", () => {
|
||||
it("renders a scheme-handler desktop entry with freedesktop Exec quoting", () => {
|
||||
const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
|
||||
displayName: "T3 Code (Nightly)",
|
||||
execTarget: '/home/al ice/Apps/T3 "100%" $HOME\\x.AppImage',
|
||||
scheme: "t3code",
|
||||
});
|
||||
|
||||
assert.include(entry, "[Desktop Entry]");
|
||||
assert.include(entry, "Name=T3 Code (Nightly)");
|
||||
// Exec composes both escaping layers: a literal backslash becomes four
|
||||
// backslashes in the file, a quote three characters, a dollar sign two
|
||||
// backslashes plus the sign.
|
||||
assert.include(
|
||||
entry,
|
||||
'Exec="/home/al ice/Apps/T3 \\\\"100%%\\\\" \\\\$HOME\\\\\\\\x.AppImage" %U',
|
||||
);
|
||||
assert.include(entry, "NoDisplay=true");
|
||||
assert.notInclude(entry, "StartupWMClass=");
|
||||
assert.include(entry, "MimeType=x-scheme-handler/t3code;");
|
||||
});
|
||||
|
||||
it("carries structured context on registration errors", () => {
|
||||
const writeError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "write-desktop-entry",
|
||||
scheme: "t3code",
|
||||
desktopEntryPath: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
cause: new Error("boom"),
|
||||
});
|
||||
assert.equal(
|
||||
writeError.message,
|
||||
"Failed to register the t3code:// URL handler (step: write-desktop-entry).",
|
||||
);
|
||||
assert.equal(
|
||||
writeError.desktopEntryPath,
|
||||
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
);
|
||||
|
||||
const exitError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme: "t3code",
|
||||
exitCode: 4,
|
||||
});
|
||||
assert.equal(
|
||||
exitError.message,
|
||||
"Failed to register the t3code:// URL handler (step: set-default-handler, xdg-mime exit code 4).",
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("writes the handler entry and claims the scheme default via xdg-mime", () => {
|
||||
const recorded = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(recorded);
|
||||
|
||||
assert.deepEqual(recorded.directories, ["/home/alice/.local/share/applications"]);
|
||||
assert.equal(recorded.files.length, 1);
|
||||
assert.equal(
|
||||
recorded.files[0]?.path,
|
||||
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
);
|
||||
assert.include(
|
||||
recorded.files[0]?.content,
|
||||
'Exec="/home/alice/Applications/T3-Code.AppImage" %U',
|
||||
);
|
||||
assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;");
|
||||
assert.deepEqual(recorded.commands, [
|
||||
{
|
||||
command: "xdg-mime",
|
||||
args: ["default", "t3code-url-handler.desktop", "x-scheme-handler/t3code"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("falls back to the process executable outside an AppImage", () => {
|
||||
const recorded = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(recorded, { environment: { appImagePath: Option.none() } });
|
||||
|
||||
assert.include(
|
||||
recorded.files[0]?.content,
|
||||
`Exec=${DesktopLinuxUrlHandler.escapeDesktopEntryExecArgument(process.execPath)} %U`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("does nothing on other platforms or unpackaged builds", () => {
|
||||
const nonLinux = emptyRecording();
|
||||
const unpackaged = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
|
||||
yield* runRegister(unpackaged, { environment: { isPackaged: false } });
|
||||
|
||||
for (const recorded of [nonLinux, unpackaged]) {
|
||||
assert.deepEqual(recorded.directories, []);
|
||||
assert.deepEqual(recorded.files, []);
|
||||
assert.deepEqual(recorded.commands, []);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("never fails startup when registration cannot complete", () => {
|
||||
const xdgMimeFailed = emptyRecording();
|
||||
const writeFailed = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(xdgMimeFailed, { xdgMimeExitCode: 1 });
|
||||
yield* runRegister(writeFailed, {
|
||||
writeError: PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "writeFileString",
|
||||
description: "read-only filesystem",
|
||||
pathOrDescriptor: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(xdgMimeFailed.files.length, 1);
|
||||
assert.deepEqual(writeFailed.commands, []);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import { makeComponentLogger } from "./DesktopObservability.ts";
|
||||
|
||||
// Linux ships as an AppImage, so the .desktop entry users end up with is
|
||||
// created by whatever integration tool they use (AppImageLauncher names it
|
||||
// appimagekit_<hash>-….desktop) and its filename is not under our control.
|
||||
// Electron's app.setAsDefaultProtocolClient resolves the desktop id from
|
||||
// setDesktopName, which cannot match those files — so the browser keeps
|
||||
// prompting "Choose an application" for every OAuth callback. Instead, write
|
||||
// our own handler entry pointing at the current AppImage and claim the
|
||||
// scheme default via xdg-mime, exactly what the file manager's "set as
|
||||
// default" checkbox would record in mimeapps.list.
|
||||
export const URL_HANDLER_DESKTOP_ENTRY_NAME = "t3code-url-handler.desktop";
|
||||
|
||||
const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
|
||||
|
||||
export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedErrorClass<DesktopLinuxUrlHandlerRegistrationError>()(
|
||||
"DesktopLinuxUrlHandlerRegistrationError",
|
||||
{
|
||||
step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
|
||||
scheme: Schema.String,
|
||||
desktopEntryPath: Schema.optionalKey(Schema.String),
|
||||
exitCode: Schema.optionalKey(Schema.Number),
|
||||
cause: Schema.optionalKey(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
|
||||
return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
|
||||
}
|
||||
}
|
||||
|
||||
const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
|
||||
|
||||
const escapeDesktopEntryString = (value: string): string =>
|
||||
value
|
||||
.replaceAll("\\", "\\\\")
|
||||
.replaceAll("\n", "\\n")
|
||||
.replaceAll("\r", "\\r")
|
||||
.replaceAll("\t", "\\t");
|
||||
|
||||
// Exec values are unescaped twice by implementations: first the general
|
||||
// string-value rules, then the Exec quoting rules — so writing composes the
|
||||
// layers in reverse. The argument is double-quoted with reserved characters
|
||||
// backslash-escaped and literal percent signs doubled (field codes), and the
|
||||
// general string escaping is applied on top: a literal backslash ends up as
|
||||
// four backslashes in the file, a quote as \\", a dollar sign as \\$.
|
||||
export function escapeDesktopEntryExecArgument(value: string): string {
|
||||
const quoted = value
|
||||
.replaceAll("\\", () => "\\\\")
|
||||
.replaceAll("`", () => "\\`")
|
||||
.replaceAll("$", () => "\\$")
|
||||
.replaceAll('"', () => '\\"')
|
||||
.replaceAll("%", () => "%%");
|
||||
return escapeDesktopEntryString(`"${quoted}"`);
|
||||
}
|
||||
|
||||
// The AppImage integration entry owns the window identity and icon. This
|
||||
// hidden URL-only entry must not compete with it for StartupWMClass matching.
|
||||
export function renderUrlHandlerDesktopEntry(input: {
|
||||
readonly displayName: string;
|
||||
readonly execTarget: string;
|
||||
readonly scheme: string;
|
||||
}): string {
|
||||
return [
|
||||
"[Desktop Entry]",
|
||||
"Type=Application",
|
||||
`Name=${escapeDesktopEntryString(input.displayName)}`,
|
||||
`Exec=${escapeDesktopEntryExecArgument(input.execTarget)} %U`,
|
||||
"Terminal=false",
|
||||
"NoDisplay=true",
|
||||
"StartupNotify=false",
|
||||
`MimeType=x-scheme-handler/${input.scheme};`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export class DesktopLinuxUrlHandler extends Context.Service<
|
||||
DesktopLinuxUrlHandler,
|
||||
{
|
||||
readonly register: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
|
||||
const desktopEntryPath = environment.path.join(
|
||||
environment.linuxApplicationsDir,
|
||||
URL_HANDLER_DESKTOP_ENTRY_NAME,
|
||||
);
|
||||
|
||||
const writeDesktopEntry = Effect.gen(function* () {
|
||||
// Inside the mounted AppImage, process.execPath points at a transient
|
||||
// /tmp/.mount_* path — the handler must launch the AppImage itself.
|
||||
const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
|
||||
yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(
|
||||
desktopEntryPath,
|
||||
renderUrlHandlerDesktopEntry({
|
||||
displayName: environment.displayName,
|
||||
execTarget,
|
||||
scheme,
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "write-desktop-entry",
|
||||
scheme,
|
||||
desktopEntryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const setDefaultHandler = Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const command = ChildProcess.make(
|
||||
"xdg-mime",
|
||||
["default", URL_HANDLER_DESKTOP_ENTRY_NAME, `x-scheme-handler/${scheme}`],
|
||||
{
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
);
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) {
|
||||
return yield* new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme,
|
||||
exitCode: Number(exitCode),
|
||||
});
|
||||
}
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError((error) =>
|
||||
isRegistrationError(error)
|
||||
? error
|
||||
: new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const register = Effect.gen(function* () {
|
||||
if (environment.platform !== "linux" || !environment.isPackaged) {
|
||||
return;
|
||||
}
|
||||
yield* writeDesktopEntry;
|
||||
yield* setDefaultHandler;
|
||||
yield* logInfo("registered URL scheme handler", { scheme });
|
||||
}).pipe(
|
||||
// Registration is best-effort: a missing xdg-mime or read-only home must
|
||||
// never block startup — the OS chooser remains as fallback.
|
||||
Effect.catch((error) =>
|
||||
logWarning("URL scheme handler registration failed", {
|
||||
scheme,
|
||||
step: error.step,
|
||||
message: error.message,
|
||||
...(error.desktopEntryPath === undefined
|
||||
? {}
|
||||
: { desktopEntryPath: error.desktopEntryPath }),
|
||||
...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("desktop.linuxUrlHandler.register"),
|
||||
);
|
||||
|
||||
return DesktopLinuxUrlHandler.of({ register });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopLinuxUrlHandler, make);
|
||||
@@ -43,6 +43,7 @@ import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentA
|
||||
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
|
||||
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./app/DesktopLinuxUrlHandler.ts";
|
||||
import * as DesktopShutdown from "./app/DesktopShutdown.ts";
|
||||
import * as DesktopObservability from "./app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
|
||||
@@ -181,6 +182,7 @@ const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
const desktopApplicationLayer = Layer.mergeAll(
|
||||
DesktopLifecycle.layer,
|
||||
DesktopApplicationMenu.layer,
|
||||
DesktopLinuxUrlHandler.layer,
|
||||
DesktopShellEnvironment.layer,
|
||||
desktopSshLayer,
|
||||
).pipe(
|
||||
|
||||
@@ -43,7 +43,7 @@ import {
|
||||
type ComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
|
||||
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
|
||||
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
|
||||
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
@@ -543,27 +543,7 @@ export function NewTaskDraftScreen(props: {
|
||||
);
|
||||
|
||||
const modelMenuActions = useMemo(
|
||||
() =>
|
||||
flow.providerGroups.map((group) => ({
|
||||
id: `provider:${group.providerKey}`,
|
||||
title: group.providerLabel,
|
||||
subtitle: group.models.find(
|
||||
(model) =>
|
||||
flow.selectedModel &&
|
||||
model.selection.instanceId === flow.selectedModel.instanceId &&
|
||||
model.selection.model === flow.selectedModel.model,
|
||||
)?.label,
|
||||
subactions: group.models.map((option) => ({
|
||||
id: `model:${option.key}`,
|
||||
title: option.label,
|
||||
state:
|
||||
flow.selectedModel &&
|
||||
option.selection.instanceId === flow.selectedModel.instanceId &&
|
||||
option.selection.model === flow.selectedModel.model
|
||||
? ("on" as const)
|
||||
: undefined,
|
||||
})),
|
||||
})),
|
||||
() => buildModelMenuActions(flow.providerGroups, flow.selectedModel),
|
||||
[flow.providerGroups, flow.selectedModel],
|
||||
);
|
||||
const providerOptionDescriptors = useMemo(
|
||||
|
||||
@@ -53,7 +53,7 @@ import {
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
import { buildModelMenuActions, buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
|
||||
import type { RemoteClientConnectionState } from "../../lib/connection";
|
||||
import {
|
||||
@@ -606,25 +606,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
[providerOptionDescriptors],
|
||||
);
|
||||
const modelMenuActions = useMemo(
|
||||
() =>
|
||||
providerGroups.map((group) => ({
|
||||
id: `provider:${group.providerKey}`,
|
||||
title: group.providerLabel,
|
||||
subtitle: group.models.find(
|
||||
(model) =>
|
||||
model.selection.instanceId === currentModelSelection.instanceId &&
|
||||
model.selection.model === currentModelSelection.model,
|
||||
)?.label,
|
||||
subactions: group.models.map((option) => ({
|
||||
id: `model:${option.key}`,
|
||||
title: option.label,
|
||||
state:
|
||||
option.selection.instanceId === currentModelSelection.instanceId &&
|
||||
option.selection.model === currentModelSelection.model
|
||||
? ("on" as const)
|
||||
: undefined,
|
||||
})),
|
||||
})),
|
||||
() => buildModelMenuActions(providerGroups, currentModelSelection),
|
||||
[providerGroups, currentModelSelection],
|
||||
);
|
||||
|
||||
|
||||
@@ -2,9 +2,92 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ProviderInstanceId, type ServerConfig } from "@t3tools/contracts";
|
||||
|
||||
import { buildModelOptions, resolveSelectableModelSelection } from "./modelOptions";
|
||||
import {
|
||||
buildModelMenuActions,
|
||||
buildModelOptions,
|
||||
groupByProvider,
|
||||
resolveSelectableModelSelection,
|
||||
} from "./modelOptions";
|
||||
|
||||
describe("mobile model options", () => {
|
||||
it("folds legacy models into a provider-scoped menu", () => {
|
||||
const config = {
|
||||
providers: [
|
||||
{
|
||||
instanceId: "codex",
|
||||
driver: "codex",
|
||||
displayName: "Codex",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-5.6-sol",
|
||||
name: "GPT-5.6 Sol",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
isLegacy: true,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
} as unknown as ServerConfig;
|
||||
|
||||
const actions = buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null);
|
||||
|
||||
expect(actions).toMatchObject([
|
||||
{
|
||||
title: "Codex",
|
||||
subactions: [{ id: "model:codex:gpt-5.6-sol", title: "GPT-5.6 Sol" }],
|
||||
},
|
||||
{
|
||||
id: "legacy-models:codex",
|
||||
title: "Codex legacy models",
|
||||
subactions: [{ id: "model:codex:gpt-5.4", title: "GPT-5.4" }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("omits an empty provider menu when every model is legacy", () => {
|
||||
const config = {
|
||||
providers: [
|
||||
{
|
||||
instanceId: "codex",
|
||||
driver: "codex",
|
||||
displayName: "Codex",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
isLegacy: true,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
} as unknown as ServerConfig;
|
||||
|
||||
expect(
|
||||
buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null),
|
||||
).toMatchObject([
|
||||
{
|
||||
id: "legacy-models:codex",
|
||||
title: "Codex legacy models",
|
||||
subactions: [{ id: "model:codex:gpt-5.4" }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("normalizes a legacy fallback selection against current capabilities", () => {
|
||||
const config = {
|
||||
providers: [
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
ModelSelection,
|
||||
ServerConfig as T3ServerConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import {
|
||||
buildProviderOptionSelectionsFromDescriptors,
|
||||
getProviderOptionDescriptors,
|
||||
@@ -16,6 +17,7 @@ export type ModelOption = {
|
||||
readonly providerLabel: string;
|
||||
readonly providerDriver: string;
|
||||
readonly isDefault: boolean;
|
||||
readonly isLegacy: boolean;
|
||||
readonly capabilities: ModelCapabilities | null;
|
||||
readonly selection: ModelSelection;
|
||||
};
|
||||
@@ -105,6 +107,7 @@ export function buildModelOptions(
|
||||
providerLabel,
|
||||
providerDriver: provider.driver,
|
||||
isDefault: model.isDefault === true,
|
||||
isLegacy: model.isLegacy === true,
|
||||
capabilities: model.capabilities,
|
||||
selection: normalizeSelectionOptions(
|
||||
{
|
||||
@@ -135,6 +138,7 @@ export function buildModelOptions(
|
||||
providerLabel,
|
||||
providerDriver: fallbackModelSelection.instanceId,
|
||||
isDefault: false,
|
||||
isLegacy: false,
|
||||
capabilities: null,
|
||||
selection: fallbackModelSelection,
|
||||
});
|
||||
@@ -164,3 +168,53 @@ export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyAr
|
||||
models: group.models,
|
||||
}));
|
||||
}
|
||||
|
||||
function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
|
||||
return {
|
||||
id: `model:${option.key}`,
|
||||
title: option.label,
|
||||
state:
|
||||
option.selection.instanceId === selectedModel?.instanceId &&
|
||||
option.selection.model === selectedModel.model
|
||||
? "on"
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildModelMenuActions(
|
||||
groups: ReadonlyArray<ProviderGroup>,
|
||||
selectedModel: ModelSelection | null,
|
||||
): MenuAction[] {
|
||||
return groups.flatMap((group) => {
|
||||
const currentModels = group.models.filter((model) => !model.isLegacy);
|
||||
const legacyModels = group.models.filter((model) => model.isLegacy);
|
||||
const selected = group.models.find(
|
||||
(model) =>
|
||||
model.selection.instanceId === selectedModel?.instanceId &&
|
||||
model.selection.model === selectedModel.model,
|
||||
);
|
||||
|
||||
return [
|
||||
...(currentModels.length > 0
|
||||
? [
|
||||
{
|
||||
id: `provider:${group.providerKey}`,
|
||||
title: group.providerLabel,
|
||||
subtitle: selected && !selected.isLegacy ? selected.label : undefined,
|
||||
subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(legacyModels.length > 0
|
||||
? [
|
||||
{
|
||||
id: `legacy-models:${group.providerKey}`,
|
||||
title: `${group.providerLabel} legacy models`,
|
||||
subtitle: selected?.isLegacy ? selected.label : undefined,
|
||||
subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
});
|
||||
}
|
||||
@@ -33,6 +33,7 @@ it("keeps systemd pinned to the stable launcher rather than a versioned server",
|
||||
|
||||
const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
|
||||
platform: NodeJS.Platform = "linux",
|
||||
usePinnedLauncher = false,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -44,6 +45,10 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
|
||||
const runtime = pinnedRuntimePaths(path, baseDir, "1.2.3");
|
||||
yield* fs.makeDirectory(path.dirname(runtime.entryPath), { recursive: true });
|
||||
yield* fs.writeFileString(runtime.entryPath, "export {};\n");
|
||||
yield* fs.writeFileString(
|
||||
path.join(path.dirname(runtime.entryPath), "service-launcher.mjs"),
|
||||
"export const source = 'pinned runtime';\n",
|
||||
);
|
||||
yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
|
||||
|
||||
const commands: string[] = [];
|
||||
@@ -69,8 +74,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
|
||||
cliVersion: "1.2.3",
|
||||
host: {
|
||||
execPath: "/usr/bin/node",
|
||||
cliEntryPath: path.join(home, "bin.mjs"),
|
||||
launcherSourcePath: sourceLauncher,
|
||||
...(usePinnedLauncher ? {} : { launcherSourcePath: sourceLauncher }),
|
||||
},
|
||||
}).pipe(
|
||||
Effect.provideService(ProcessRunner.ProcessRunner, runner),
|
||||
@@ -109,6 +113,17 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("copies the launcher from the prepared pinned runtime", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service, fs } = yield* makeHarness("linux", true);
|
||||
const plan = yield* service.install;
|
||||
|
||||
expect(yield* fs.readFileString(plan.launcherPath)).toBe(
|
||||
"export const source = 'pinned runtime';\n",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restarts an installed service when repair fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service, commands, control } = yield* makeHarness();
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
HostProcessArguments,
|
||||
HostProcessExecutablePath,
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -138,7 +134,6 @@ export class BootService extends Context.Service<
|
||||
|
||||
export interface BootServiceHost {
|
||||
readonly execPath: string;
|
||||
readonly cliEntryPath: string;
|
||||
readonly launcherSourcePath?: string;
|
||||
}
|
||||
|
||||
@@ -148,26 +143,23 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
|
||||
readonly cliVersion: string;
|
||||
readonly host?: BootServiceHost;
|
||||
}) {
|
||||
const hostArguments = yield* HostProcessArguments;
|
||||
const hostExecPath = yield* HostProcessExecutablePath;
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const runner = yield* ProcessRunner.ProcessRunner;
|
||||
const host = input.host ?? {
|
||||
execPath: hostExecPath,
|
||||
cliEntryPath: hostArguments[1] ?? "",
|
||||
};
|
||||
const host = input.host ?? { execPath: hostExecPath };
|
||||
|
||||
const unitDir = path.join(homeDir, ".config", "systemd", "user");
|
||||
const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
|
||||
const logPath = path.join(input.logsDir, "boot-service.log");
|
||||
const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
|
||||
const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
|
||||
const launcherSourcePath =
|
||||
host.launcherSourcePath ?? path.join(path.dirname(host.cliEntryPath), SERVICE_LAUNCHER_FILE);
|
||||
const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
|
||||
const launcherSourcePath =
|
||||
host.launcherSourcePath ??
|
||||
path.join(path.dirname(runtimePaths.entryPath), SERVICE_LAUNCHER_FILE);
|
||||
const writeDurably = (filePath: string, contents: string) =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -9,11 +9,27 @@ import * as Schema from "effect/Schema";
|
||||
import {
|
||||
buildClaudeCapabilitiesProbeQueryOptions,
|
||||
CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES,
|
||||
isLegacyClaudeModel,
|
||||
probeClaudeCapabilities,
|
||||
} from "./ClaudeProvider.ts";
|
||||
|
||||
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
|
||||
|
||||
it("keeps only the Claude 5 family out of legacy models", () => {
|
||||
assert.deepStrictEqual(
|
||||
["claude-fable-5", "claude-opus-5", "claude-sonnet-5", "claude-opus-4-8"].map((model) => [
|
||||
model,
|
||||
isLegacyClaudeModel(model),
|
||||
]),
|
||||
[
|
||||
["claude-fable-5", false],
|
||||
["claude-opus-5", false],
|
||||
["claude-sonnet-5", false],
|
||||
["claude-opus-4-8", true],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
it("isolates Claude capability probes without dropping workspace setting sources", () => {
|
||||
const abortController = new AbortController();
|
||||
const options = buildClaudeCapabilitiesProbeQueryOptions({
|
||||
|
||||
@@ -56,7 +56,13 @@ const MINIMUM_CLAUDE_FABLE_5_VERSION = "2.1.169";
|
||||
const MINIMUM_CLAUDE_OPUS_4_8_VERSION = "2.1.154";
|
||||
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
|
||||
|
||||
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
const CURRENT_CLAUDE_MODELS = new Set(["claude-fable-5", "claude-opus-5", "claude-sonnet-5"]);
|
||||
|
||||
export function isLegacyClaudeModel(model: string): boolean {
|
||||
return !CURRENT_CLAUDE_MODELS.has(model);
|
||||
}
|
||||
|
||||
const CLAUDE_MODEL_CATALOG: ReadonlyArray<ServerProviderModel> = [
|
||||
{
|
||||
slug: "claude-fable-5",
|
||||
name: "Claude Fable 5",
|
||||
@@ -309,6 +315,10 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
},
|
||||
];
|
||||
|
||||
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = CLAUDE_MODEL_CATALOG.map((model) =>
|
||||
isLegacyClaudeModel(model.slug) ? { ...model, isLegacy: true } : model,
|
||||
);
|
||||
|
||||
function supportsClaudeOpus5(version: string | null | undefined): boolean {
|
||||
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_5_VERSION) >= 0 : false;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,25 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts";
|
||||
import {
|
||||
applyPreferredCodexDefaultModel,
|
||||
isLegacyCodexModel,
|
||||
mapCodexModelCapabilities,
|
||||
} from "./CodexProvider.ts";
|
||||
|
||||
it("keeps only the GPT-5.6 Codex family out of legacy models", () => {
|
||||
assert.deepStrictEqual(
|
||||
["gpt-5.6-luna", "gpt-5.6-terra", "gpt-5.6-sol", "gpt-5.4"].map((model) => [
|
||||
model,
|
||||
isLegacyCodexModel(model),
|
||||
]),
|
||||
[
|
||||
["gpt-5.6-luna", false],
|
||||
["gpt-5.6-terra", false],
|
||||
["gpt-5.6-sol", false],
|
||||
["gpt-5.4", true],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
it("maps current Codex model capability fields", () => {
|
||||
const capabilities = mapCodexModelCapabilities({
|
||||
|
||||
@@ -62,6 +62,11 @@ const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
|
||||
};
|
||||
|
||||
const DEFAULT_SERVICE_TIER_ID = "default";
|
||||
const CURRENT_CODEX_MODELS = new Set(["gpt-5.6-luna", "gpt-5.6-terra", "gpt-5.6-sol"]);
|
||||
|
||||
export function isLegacyCodexModel(model: string): boolean {
|
||||
return !CURRENT_CODEX_MODELS.has(model);
|
||||
}
|
||||
|
||||
function reasoningEffortLabel(reasoningEffort: string): string {
|
||||
return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;
|
||||
@@ -190,6 +195,7 @@ function parseCodexModelListResponse(
|
||||
name: toDisplayName(model),
|
||||
isCustom: false,
|
||||
...(model.isDefault ? { isDefault: true } : {}),
|
||||
...(isLegacyCodexModel(model.model) ? { isLegacy: true } : {}),
|
||||
capabilities: mapCodexModelCapabilities(model),
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -16,6 +16,37 @@
|
||||
const LIGHT_BACKGROUND = "#ffffff";
|
||||
const DARK_BACKGROUND = "#161616";
|
||||
const themeColorMeta = document.querySelector('meta[name="theme-color"]');
|
||||
try {
|
||||
const storedColors = window.localStorage.getItem("t3code:theme-colors");
|
||||
const colors = storedColors ? JSON.parse(storedColors) : null;
|
||||
const isHexColor = (value) =>
|
||||
typeof value === "string" && /^#[0-9a-f]{6}$/i.test(value.trim());
|
||||
if (isHexColor(colors?.accentColor)) {
|
||||
document.documentElement.style.setProperty(
|
||||
"--theme-accent-seed",
|
||||
colors.accentColor.trim().toLowerCase(),
|
||||
);
|
||||
}
|
||||
if (isHexColor(colors?.neutralColor)) {
|
||||
document.documentElement.style.setProperty(
|
||||
"--theme-neutral-seed",
|
||||
colors.neutralColor.trim().toLowerCase(),
|
||||
);
|
||||
}
|
||||
if (typeof colors?.contrast === "number" && Number.isFinite(colors.contrast)) {
|
||||
const contrast = Math.min(100, Math.max(0, colors.contrast));
|
||||
const properties = {
|
||||
"--theme-background-strength": `${4 + contrast * 0.12}%`,
|
||||
"--theme-surface-strength": `${6 + contrast * 0.16}%`,
|
||||
"--theme-control-strength": `${3 + contrast * 0.08}%`,
|
||||
"--theme-accent-strength": `${6 + contrast * 0.2}%`,
|
||||
"--theme-border-strength": `${8 + contrast * 0.16}%`,
|
||||
};
|
||||
for (const [property, value] of Object.entries(properties)) {
|
||||
document.documentElement.style.setProperty(property, value);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
try {
|
||||
const storedTheme = window.localStorage.getItem("t3code:theme");
|
||||
const theme =
|
||||
|
||||
@@ -304,7 +304,7 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
if (!hasActiveThread || !activeProject) return null;
|
||||
|
||||
return (
|
||||
<div className="chat-composer-context-strip -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 px-1 pt-5 pb-1">
|
||||
<div className="chat-composer-context-strip -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 ps-1 pe-2 pt-5 pb-1">
|
||||
{isMobile ? (
|
||||
<MobileRunContextSelector
|
||||
envLocked={envLocked}
|
||||
|
||||
@@ -5643,7 +5643,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
/>
|
||||
);
|
||||
const panelLayoutControls = (
|
||||
<div className="workspace-titlebar-controls z-50 gap-1 [-webkit-app-region:no-drag]">
|
||||
<div className="workspace-titlebar-controls z-50 mr-px gap-1 [-webkit-app-region:no-drag]">
|
||||
{rightPanelOpen && !shouldUsePlanSidebarSheet ? (
|
||||
<RightPanelMaximizeControl
|
||||
maximized={rightPanelMaximized}
|
||||
|
||||
@@ -1693,7 +1693,7 @@ export default function GitActionsControl({
|
||||
render={
|
||||
<Button
|
||||
aria-disabled="true"
|
||||
className="cursor-not-allowed rounded-e-none border-e-0 opacity-64 before:rounded-e-none"
|
||||
className="cursor-not-allowed rounded-e-none border-e-0 ps-[8.5px] opacity-64 before:rounded-e-none"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
/>
|
||||
@@ -1715,6 +1715,7 @@ export default function GitActionsControl({
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
className="ps-[8.5px]"
|
||||
disabled={isGitActionRunning || quickAction.disabled}
|
||||
onClick={runQuickAction}
|
||||
>
|
||||
|
||||
@@ -2674,7 +2674,7 @@ export default function SidebarV2() {
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
aria-label="Filter threads by project"
|
||||
className="min-w-0 flex-1 focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
className="min-w-0 flex-1 ps-[calc(var(--sidebar-row-content-inset)-1px)] focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
/>
|
||||
}
|
||||
>
|
||||
@@ -2765,7 +2765,7 @@ export default function SidebarV2() {
|
||||
</SidebarGroup>
|
||||
}
|
||||
>
|
||||
<SidebarGroup className="px-[var(--sidebar-content-inset)] pb-1 pt-0">
|
||||
<SidebarGroup className="ps-[calc(var(--sidebar-content-inset)+1px)] pe-[var(--sidebar-content-inset)] pb-1 pt-0">
|
||||
{isSearchingThreads ? (
|
||||
threadSearchResults.length > 0 ? (
|
||||
<TooltipProvider
|
||||
|
||||
@@ -3104,7 +3104,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
|
||||
{/* Bottom toolbar */}
|
||||
{isComposerCollapsedMobile ? null : activePendingApproval ? (
|
||||
<div className="flex items-center justify-end gap-2 px-2.5 pb-2.5 sm:px-3 sm:pb-3">
|
||||
<div className="flex items-center justify-end gap-2 px-3 pb-3 sm:px-4 sm:pb-4">
|
||||
<ComposerPendingApprovalActions
|
||||
requestId={activePendingApproval.requestId}
|
||||
isResponding={respondingRequestIds.includes(activePendingApproval.requestId)}
|
||||
@@ -3116,7 +3116,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
data-chat-composer-footer="true"
|
||||
data-chat-composer-footer-compact={isComposerFooterCompact ? "true" : "false"}
|
||||
className={cn(
|
||||
"flex min-w-0 flex-nowrap items-center justify-between gap-2 overflow-visible px-2.5 pb-2.5 sm:px-3 sm:pb-3",
|
||||
"flex min-w-0 flex-nowrap items-center justify-between gap-2 overflow-visible px-3 pb-3 sm:px-4 sm:pb-4",
|
||||
pendingUserInputs.length > 0 && "pt-2",
|
||||
isComposerFooterCompact ? "gap-1.5" : "gap-2 sm:gap-0",
|
||||
showMobilePendingAnswerActions && "hidden sm:flex",
|
||||
@@ -3145,6 +3145,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
instanceEntries={providerInstanceEntries}
|
||||
keybindings={keybindings}
|
||||
modelOptionsByInstance={modelOptionsByInstance}
|
||||
triggerClassName="-ms-px ps-0"
|
||||
terminalOpen={terminalOpen}
|
||||
open={isComposerModelPickerOpen}
|
||||
{...(composerProviderState.modelPickerIconClassName
|
||||
|
||||
@@ -21,7 +21,7 @@ export function ContextWindowMeter(props: {
|
||||
const normalizedPercentage = Math.max(0, Math.min(100, usage.usedPercentage ?? 0));
|
||||
const radius = 9.75;
|
||||
const circumference = 2 * Math.PI * radius;
|
||||
const dashOffset = circumference - (normalizedPercentage / 100) * circumference;
|
||||
const dashOffset = circumference * (1 - normalizedPercentage / 100);
|
||||
const totalProcessedTokens = usage.totalProcessedTokens ?? null;
|
||||
const showTotalProcessed = totalProcessedTokens !== null && totalProcessedTokens > 0;
|
||||
const isOverloaded = normalizedPercentage > 90;
|
||||
@@ -73,7 +73,7 @@ export function ContextWindowMeter(props: {
|
||||
strokeLinecap="round"
|
||||
strokeDasharray={circumference}
|
||||
strokeDashoffset={dashOffset}
|
||||
className="transition-[stroke-dashoffset] duration-500 ease-out motion-reduce:transition-none"
|
||||
className="transition-[stroke-dashoffset,stroke] duration-500 ease-out motion-reduce:transition-none"
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
@@ -84,9 +84,10 @@ export function ContextWindowMeter(props: {
|
||||
tooltipStyle
|
||||
side="top"
|
||||
align="end"
|
||||
className="dropdown-glass w-64 max-w-none border-0! bg-secondary! p-0 shadow-none! before:hidden"
|
||||
viewportClassName="p-0"
|
||||
className="w-64 max-w-none text-left whitespace-normal"
|
||||
>
|
||||
<div className="flex flex-col gap-2 p-3">
|
||||
<div className="flex flex-col gap-2 p-[var(--floating-content-inset)]">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="font-medium text-muted-foreground text-xs">Context Window</div>
|
||||
{usage.maxTokens !== null && usedPercentage ? (
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Button } from "../ui/button";
|
||||
import { Kbd } from "../ui/kbd";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { modelPickerModelKey } from "./modelPickerKeys";
|
||||
|
||||
export const ModelListRow = memo(function ModelListRow(props: {
|
||||
index: number;
|
||||
@@ -46,7 +47,7 @@ export const ModelListRow = memo(function ModelListRow(props: {
|
||||
<ComboboxItem
|
||||
hideIndicator
|
||||
index={props.index}
|
||||
value={`${props.instanceId}:${props.model.slug}`}
|
||||
value={modelPickerModelKey(props.instanceId, props.model.slug)}
|
||||
disabled={Boolean(props.disabledReason)}
|
||||
contentClassName="flex w-full items-center gap-3"
|
||||
className={cn(
|
||||
|
||||
@@ -6,12 +6,24 @@ import {
|
||||
import { resolveSelectableModel } from "@t3tools/shared/model";
|
||||
import { LegendList, type LegendListRef } from "@legendapp/list/react";
|
||||
import { memo, useMemo, useState, useCallback, useEffect, useLayoutEffect, useRef } from "react";
|
||||
import { SearchIcon } from "lucide-react";
|
||||
import { ChevronRightIcon, SearchIcon } from "lucide-react";
|
||||
import { ModelListRow } from "./ModelListRow";
|
||||
import { ModelPickerSidebar } from "./ModelPickerSidebar";
|
||||
import {
|
||||
modelPickerLegacySectionKey,
|
||||
modelPickerModelKey,
|
||||
parseModelPickerLegacySectionKey,
|
||||
parseModelPickerModelKey,
|
||||
} from "./modelPickerKeys";
|
||||
import { isModelPickerNewModel } from "./modelPickerModelHighlights";
|
||||
import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch";
|
||||
import { Combobox, ComboboxEmpty, ComboboxInput, ComboboxListVirtualized } from "../ui/combobox";
|
||||
import {
|
||||
Combobox,
|
||||
ComboboxEmpty,
|
||||
ComboboxInput,
|
||||
ComboboxItem,
|
||||
ComboboxListVirtualized,
|
||||
} from "../ui/combobox";
|
||||
import { ModelEsque } from "./providerIconUtils";
|
||||
import {
|
||||
modelPickerJumpCommandForIndex,
|
||||
@@ -39,6 +51,7 @@ type ModelPickerItem = {
|
||||
instanceDisplayName: string;
|
||||
instanceAccentColor?: string | undefined;
|
||||
continuationGroupKey?: string | undefined;
|
||||
isLegacy?: boolean | undefined;
|
||||
};
|
||||
|
||||
const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();
|
||||
@@ -47,20 +60,6 @@ function ModelListSeparator() {
|
||||
return <div className="h-0.5" />;
|
||||
}
|
||||
|
||||
// Split a `${instanceId}:${slug}` combobox key back into its pieces. Slugs
|
||||
// can contain colons (e.g. some vendor model ids), so we only split on the
|
||||
// first colon — anything after that is the slug.
|
||||
function splitInstanceModelKey(key: string): { instanceId: ProviderInstanceId; slug: string } {
|
||||
const colonIndex = key.indexOf(":");
|
||||
if (colonIndex === -1) {
|
||||
return { instanceId: key as ProviderInstanceId, slug: "" };
|
||||
}
|
||||
return {
|
||||
instanceId: key.slice(0, colonIndex) as ProviderInstanceId,
|
||||
slug: key.slice(colonIndex + 1),
|
||||
};
|
||||
}
|
||||
|
||||
export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
/** The instance currently selected in the composer (combobox "value"). */
|
||||
activeInstanceId: ProviderInstanceId;
|
||||
@@ -117,6 +116,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
return favorites.length > 0 ? "favorites" : props.activeInstanceId;
|
||||
},
|
||||
);
|
||||
const [expandedLegacyInstances, setExpandedLegacyInstances] = useState(
|
||||
() =>
|
||||
new Set<ProviderInstanceId>(
|
||||
modelOptionsByInstance
|
||||
.get(props.activeInstanceId)
|
||||
?.some((model) => model.slug === props.model && model.isLegacy)
|
||||
? [props.activeInstanceId]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
const keybindings = useMemo<ResolvedKeybindingsConfig>(
|
||||
() => providedKeybindings ?? [],
|
||||
[providedKeybindings],
|
||||
@@ -211,6 +220,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
name: model.name,
|
||||
...(model.shortName ? { shortName: model.shortName } : {}),
|
||||
...(model.subProvider ? { subProvider: model.subProvider } : {}),
|
||||
...(model.isLegacy ? { isLegacy: true } : {}),
|
||||
instanceId,
|
||||
driverKind: entry.driverKind,
|
||||
instanceDisplayName: entry.displayName,
|
||||
@@ -366,6 +376,45 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
selectedInstanceId,
|
||||
]);
|
||||
|
||||
const legacySection = useMemo(() => {
|
||||
if (isSearching || selectedInstanceId === "favorites") {
|
||||
return null;
|
||||
}
|
||||
const currentModels = filteredModels.filter((model) => !model.isLegacy);
|
||||
const legacyModels = filteredModels.filter((model) => model.isLegacy);
|
||||
if (legacyModels.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
key: modelPickerLegacySectionKey(selectedInstanceId),
|
||||
currentModels,
|
||||
legacyModels,
|
||||
isExpanded: expandedLegacyInstances.has(selectedInstanceId),
|
||||
};
|
||||
}, [expandedLegacyInstances, filteredModels, isSearching, selectedInstanceId]);
|
||||
|
||||
const visibleModels = useMemo(() => {
|
||||
if (!legacySection) {
|
||||
return filteredModels;
|
||||
}
|
||||
return [
|
||||
...legacySection.currentModels,
|
||||
...(legacySection.isExpanded ? legacySection.legacyModels : []),
|
||||
];
|
||||
}, [filteredModels, legacySection]);
|
||||
|
||||
const toggleLegacySection = useCallback((instanceId: ProviderInstanceId) => {
|
||||
setExpandedLegacyInstances((expanded) => {
|
||||
const next = new Set(expanded);
|
||||
if (next.has(instanceId)) {
|
||||
next.delete(instanceId);
|
||||
} else {
|
||||
next.add(instanceId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleModelSelect = useCallback(
|
||||
(modelSlug: string, instanceId: ProviderInstanceId) => {
|
||||
if (getModelDisabledReason?.(instanceId, modelSlug)) {
|
||||
@@ -410,7 +459,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
NonNullable<ReturnType<typeof modelPickerJumpCommandForIndex>>
|
||||
>();
|
||||
let selectableModelIndex = 0;
|
||||
for (const model of filteredModels) {
|
||||
for (const model of visibleModels) {
|
||||
if (getModelDisabledReason?.(model.instanceId, model.slug)) {
|
||||
continue;
|
||||
}
|
||||
@@ -418,27 +467,44 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
if (!jumpCommand) {
|
||||
return mapping;
|
||||
}
|
||||
mapping.set(`${model.instanceId}:${model.slug}`, jumpCommand);
|
||||
mapping.set(modelPickerModelKey(model.instanceId, model.slug), jumpCommand);
|
||||
selectableModelIndex += 1;
|
||||
}
|
||||
return mapping;
|
||||
}, [filteredModels, getModelDisabledReason]);
|
||||
}, [getModelDisabledReason, visibleModels]);
|
||||
const modelJumpModelKeys = useMemo(
|
||||
() => [...modelJumpCommandByKey.keys()],
|
||||
[modelJumpCommandByKey],
|
||||
);
|
||||
const allModelKeys = useMemo(
|
||||
(): string[] => flatModels.map((model) => `${model.instanceId}:${model.slug}`),
|
||||
const allItemKeys = useMemo(
|
||||
(): string[] => [
|
||||
...flatModels.map((model) => modelPickerModelKey(model.instanceId, model.slug)),
|
||||
...new Set(
|
||||
flatModels
|
||||
.filter((model) => model.isLegacy)
|
||||
.map((model) => modelPickerLegacySectionKey(model.instanceId)),
|
||||
),
|
||||
],
|
||||
[flatModels],
|
||||
);
|
||||
const filteredModelKeys = useMemo(
|
||||
(): string[] => filteredModels.map((model) => `${model.instanceId}:${model.slug}`),
|
||||
[filteredModels],
|
||||
);
|
||||
const filteredItemKeys = useMemo((): string[] => {
|
||||
const modelKeys = visibleModels.map((model) =>
|
||||
modelPickerModelKey(model.instanceId, model.slug),
|
||||
);
|
||||
if (!legacySection) {
|
||||
return modelKeys;
|
||||
}
|
||||
modelKeys.splice(legacySection.currentModels.length, 0, legacySection.key);
|
||||
return modelKeys;
|
||||
}, [legacySection, visibleModels]);
|
||||
const filteredModelByKey = useMemo(
|
||||
(): ReadonlyMap<string, ModelPickerItem> =>
|
||||
new Map(filteredModels.map((model) => [`${model.instanceId}:${model.slug}`, model] as const)),
|
||||
[filteredModels],
|
||||
new Map(
|
||||
visibleModels.map(
|
||||
(model) => [modelPickerModelKey(model.instanceId, model.slug), model] as const,
|
||||
),
|
||||
),
|
||||
[visibleModels],
|
||||
);
|
||||
const updateModelListScrollFades = useCallback(() => {
|
||||
const scrollElement = modelListRef.current?.getScrollableNode();
|
||||
@@ -495,10 +561,13 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
if (!targetModelKey) {
|
||||
return;
|
||||
}
|
||||
const { instanceId, slug } = splitInstanceModelKey(targetModelKey);
|
||||
const model = parseModelPickerModelKey(targetModelKey);
|
||||
if (!model) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleModelSelect(slug, instanceId);
|
||||
handleModelSelect(model.slug, model.instanceId);
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown, true);
|
||||
@@ -510,7 +579,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setShowTopScrollFade(false);
|
||||
setShowBottomScrollFade(filteredModelKeys.length > 5);
|
||||
setShowBottomScrollFade(filteredItemKeys.length > 5);
|
||||
let nestedFrame = 0;
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
updateModelListScrollFades();
|
||||
@@ -520,7 +589,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
window.cancelAnimationFrame(frame);
|
||||
window.cancelAnimationFrame(nestedFrame);
|
||||
};
|
||||
}, [filteredModelKeys, updateModelListScrollFades]);
|
||||
}, [filteredItemKeys, updateModelListScrollFades]);
|
||||
|
||||
return (
|
||||
<TooltipProvider delay={0}>
|
||||
@@ -548,13 +617,13 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
{/* Main content area */}
|
||||
<Combobox
|
||||
inline
|
||||
items={allModelKeys}
|
||||
filteredItems={filteredModelKeys}
|
||||
items={allItemKeys}
|
||||
filteredItems={filteredItemKeys}
|
||||
filter={null}
|
||||
autoHighlight
|
||||
open
|
||||
virtualized
|
||||
value={`${props.activeInstanceId}:${props.model}`}
|
||||
value={modelPickerModelKey(props.activeInstanceId, props.model)}
|
||||
onItemHighlighted={(modelKey, eventDetails) => {
|
||||
highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null;
|
||||
if (eventDetails.reason === "keyboard" && eventDetails.index >= 0) {
|
||||
@@ -568,8 +637,15 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
if (typeof modelKey !== "string") {
|
||||
return;
|
||||
}
|
||||
const { instanceId, slug } = splitInstanceModelKey(modelKey);
|
||||
handleModelSelect(slug, instanceId);
|
||||
const legacyInstanceId = parseModelPickerLegacySectionKey(modelKey);
|
||||
if (legacyInstanceId) {
|
||||
toggleLegacySection(legacyInstanceId);
|
||||
return;
|
||||
}
|
||||
const model = parseModelPickerModelKey(modelKey);
|
||||
if (model) {
|
||||
handleModelSelect(model.slug, model.instanceId);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div
|
||||
@@ -605,10 +681,17 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
).preventBaseUIHandler?.();
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const { instanceId, slug } = splitInstanceModelKey(
|
||||
const legacyInstanceId = parseModelPickerLegacySectionKey(
|
||||
highlightedModelKeyRef.current,
|
||||
);
|
||||
handleModelSelect(slug, instanceId);
|
||||
if (legacyInstanceId) {
|
||||
toggleLegacySection(legacyInstanceId);
|
||||
return;
|
||||
}
|
||||
const model = parseModelPickerModelKey(highlightedModelKeyRef.current);
|
||||
if (model) {
|
||||
handleModelSelect(model.slug, model.instanceId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
e.stopPropagation();
|
||||
@@ -626,10 +709,35 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
<ComboboxListVirtualized className="size-full min-w-0 p-0 not-empty:p-0">
|
||||
<LegendList<string>
|
||||
ref={modelListRef}
|
||||
data={filteredModelKeys}
|
||||
data={filteredItemKeys}
|
||||
extraData={favoritesSet}
|
||||
keyExtractor={(modelKey) => modelKey}
|
||||
renderItem={({ item: modelKey, index }) => {
|
||||
if (legacySection?.key === modelKey) {
|
||||
return (
|
||||
<ComboboxItem
|
||||
hideIndicator
|
||||
index={index}
|
||||
value={modelKey}
|
||||
aria-expanded={legacySection.isExpanded}
|
||||
className="group w-full cursor-pointer rounded-md px-2 py-2"
|
||||
contentClassName="flex w-full items-center gap-3"
|
||||
>
|
||||
<div className="min-w-0 flex-1 text-left">
|
||||
<div className="text-xs font-medium leading-snug">Legacy models</div>
|
||||
<div className="mt-1 text-xs font-normal leading-snug text-muted-foreground/70">
|
||||
{legacySection.legacyModels.length} models
|
||||
</div>
|
||||
</div>
|
||||
<ChevronRightIcon
|
||||
className={cn(
|
||||
"size-4 transition-transform",
|
||||
legacySection.isExpanded && "rotate-90",
|
||||
)}
|
||||
/>
|
||||
</ComboboxItem>
|
||||
);
|
||||
}
|
||||
const model = filteredModelByKey.get(modelKey);
|
||||
if (!model) {
|
||||
return null;
|
||||
@@ -645,8 +753,12 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
driverKind={model.driverKind}
|
||||
providerDisplayName={model.instanceDisplayName}
|
||||
providerAccentColor={model.instanceAccentColor}
|
||||
isFavorite={favoritesSet.has(modelKey)}
|
||||
isSelected={modelKey === `${props.activeInstanceId}:${props.model}`}
|
||||
isFavorite={favoritesSet.has(
|
||||
providerModelKey(model.instanceId, model.slug),
|
||||
)}
|
||||
isSelected={
|
||||
modelKey === modelPickerModelKey(props.activeInstanceId, props.model)
|
||||
}
|
||||
showProvider
|
||||
preferShortName={!isLocked}
|
||||
useTriggerLabel={false}
|
||||
@@ -657,7 +769,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
/>
|
||||
);
|
||||
}}
|
||||
estimatedItemSize={60}
|
||||
estimatedItemSize={52}
|
||||
drawDistance={480}
|
||||
recycleItems
|
||||
contentContainerClassName="pl-2 pr-px"
|
||||
|
||||
@@ -260,6 +260,7 @@ export const OpenInPicker = memo(function OpenInPicker({
|
||||
<Group aria-label="Open in editor">
|
||||
<Button
|
||||
aria-label={compact ? "Open file in preferred editor" : undefined}
|
||||
className="ps-[8.5px]"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={!preferredEditor || !openInCwd}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
modelPickerLegacySectionKey,
|
||||
modelPickerModelKey,
|
||||
parseModelPickerLegacySectionKey,
|
||||
parseModelPickerModelKey,
|
||||
} from "./modelPickerKeys";
|
||||
|
||||
describe("model picker item keys", () => {
|
||||
it("keeps model and legacy section keys distinct for colliding instance names", () => {
|
||||
const modelKey = modelPickerModelKey(ProviderInstanceId.make("legacy-models"), "codex");
|
||||
const sectionKey = modelPickerLegacySectionKey(ProviderInstanceId.make("codex"));
|
||||
|
||||
expect(modelKey).not.toBe(sectionKey);
|
||||
expect(parseModelPickerLegacySectionKey(modelKey)).toBeNull();
|
||||
expect(parseModelPickerModelKey(modelKey)).toEqual({
|
||||
instanceId: "legacy-models",
|
||||
slug: "codex",
|
||||
});
|
||||
});
|
||||
|
||||
it("round-trips arbitrary strings without throwing", () => {
|
||||
const instanceId = ProviderInstanceId.make("custom");
|
||||
const slug = "model:\udfff";
|
||||
|
||||
const key = modelPickerModelKey(instanceId, slug);
|
||||
|
||||
expect(parseModelPickerModelKey(key)).toEqual({ instanceId, slug });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { ProviderInstanceId } from "@t3tools/contracts";
|
||||
|
||||
const MODEL_KEY_PREFIX = "model:";
|
||||
const LEGACY_SECTION_KEY_PREFIX = "legacy-models:";
|
||||
|
||||
export function modelPickerModelKey(instanceId: ProviderInstanceId, slug: string): string {
|
||||
return `${MODEL_KEY_PREFIX}${instanceId.length}:${instanceId}${slug}`;
|
||||
}
|
||||
|
||||
export function parseModelPickerModelKey(
|
||||
key: string,
|
||||
): { instanceId: ProviderInstanceId; slug: string } | null {
|
||||
if (!key.startsWith(MODEL_KEY_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
const encoded = key.slice(MODEL_KEY_PREFIX.length);
|
||||
const separatorIndex = encoded.indexOf(":");
|
||||
if (separatorIndex === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const instanceIdLengthText = encoded.slice(0, separatorIndex);
|
||||
if (!/^\d+$/.test(instanceIdLengthText)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const instanceIdLength = Number(instanceIdLengthText);
|
||||
const value = encoded.slice(separatorIndex + 1);
|
||||
if (!Number.isSafeInteger(instanceIdLength) || instanceIdLength > value.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
instanceId: value.slice(0, instanceIdLength) as ProviderInstanceId,
|
||||
slug: value.slice(instanceIdLength),
|
||||
};
|
||||
}
|
||||
|
||||
export function modelPickerLegacySectionKey(instanceId: ProviderInstanceId): string {
|
||||
return `${LEGACY_SECTION_KEY_PREFIX}${instanceId}`;
|
||||
}
|
||||
|
||||
export function parseModelPickerLegacySectionKey(key: string): ProviderInstanceId | null {
|
||||
return key.startsWith(LEGACY_SECTION_KEY_PREFIX)
|
||||
? (key.slice(LEGACY_SECTION_KEY_PREFIX.length) as ProviderInstanceId)
|
||||
: null;
|
||||
}
|
||||
@@ -26,6 +26,7 @@ export type ModelEsque = {
|
||||
name: string;
|
||||
shortName?: string | undefined;
|
||||
subProvider?: string | undefined;
|
||||
isLegacy?: boolean | undefined;
|
||||
};
|
||||
|
||||
function escapeRegExp(value: string): string {
|
||||
|
||||
@@ -64,6 +64,7 @@ import {
|
||||
import { isElectron } from "../../env";
|
||||
import { buildHostedChannelSelectionUrl, type HostedAppChannel } from "../../hostedPairing";
|
||||
import { useTheme } from "../../hooks/useTheme";
|
||||
import { DEFAULT_THEME_COLORS, type ThemeColors, useThemeColors } from "../../hooks/useThemeColors";
|
||||
import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
|
||||
import { useThreadActions } from "../../hooks/useThreadActions";
|
||||
import { useDesktopUpdateState } from "../../state/desktopUpdate";
|
||||
@@ -155,6 +156,129 @@ const THEME_OPTIONS = [
|
||||
},
|
||||
] as const;
|
||||
|
||||
const THEME_COLOR_SWATCHES = [
|
||||
"#3b5bdb",
|
||||
"#7c3aed",
|
||||
"#db2777",
|
||||
"#dc2626",
|
||||
"#ea580c",
|
||||
"#16a34a",
|
||||
"#0891b2",
|
||||
] as const;
|
||||
|
||||
const THEME_NEUTRAL_SWATCHES = ["#737373", "#78716c", "#64748b", "#71717a"] as const;
|
||||
|
||||
type ThemeOption = (typeof THEME_OPTIONS)[number];
|
||||
|
||||
function ThemeModePreview({
|
||||
option,
|
||||
selected,
|
||||
accentColor,
|
||||
onSelect,
|
||||
}: {
|
||||
option: ThemeOption;
|
||||
selected: boolean;
|
||||
accentColor: string;
|
||||
onSelect: () => void;
|
||||
}) {
|
||||
const previewBackground =
|
||||
option.value === "system"
|
||||
? "bg-[linear-gradient(to_right,#fafafa_0_50%,#18181b_50%)]"
|
||||
: option.value === "light"
|
||||
? "bg-zinc-50"
|
||||
: "bg-zinc-900";
|
||||
const previewForeground = option.value === "light" ? "bg-zinc-400" : "bg-zinc-500";
|
||||
const cardBackground =
|
||||
option.value === "system"
|
||||
? "bg-[linear-gradient(to_right,rgba(255,255,255,0.9)_0_32%,rgba(39,39,42,0.95)_32%)]"
|
||||
: option.value === "light"
|
||||
? "bg-white/90"
|
||||
: "bg-zinc-800/95";
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Use ${option.label.toLowerCase()} theme`}
|
||||
aria-pressed={selected}
|
||||
className="group min-w-0 cursor-pointer text-left"
|
||||
onClick={onSelect}
|
||||
>
|
||||
<span
|
||||
className={`relative block h-24 overflow-hidden rounded-xl border transition group-hover:border-primary/60 ${
|
||||
selected ? "border-primary ring-2 ring-primary/20" : "border-border"
|
||||
} ${previewBackground}`}
|
||||
>
|
||||
<span className="absolute inset-y-0 left-0 w-[31%] border-r border-black/10 bg-black/[0.04] dark:border-white/10" />
|
||||
<span
|
||||
className="absolute top-4 left-3 h-1.5 w-8 rounded-full"
|
||||
style={{ backgroundColor: accentColor }}
|
||||
/>
|
||||
<span className={`absolute top-8 left-3 h-1 w-10 rounded-full ${previewForeground}`} />
|
||||
<span className="absolute top-4 right-4 h-2 w-16 rounded-full bg-zinc-400/60" />
|
||||
<span
|
||||
className={`absolute right-3 bottom-3 h-14 w-[60%] rounded-lg border border-black/10 shadow-sm ${cardBackground}`}
|
||||
>
|
||||
<span className="absolute top-3 left-3 h-1.5 w-12 rounded-full bg-zinc-400/60" />
|
||||
<span className="absolute top-7 left-3 h-1 w-[70%] rounded-full bg-zinc-400/30" />
|
||||
<span
|
||||
className="absolute bottom-2 left-3 h-1.5 w-8 rounded-full"
|
||||
style={{ backgroundColor: accentColor }}
|
||||
/>
|
||||
</span>
|
||||
{option.value === "system" ? (
|
||||
<span className="absolute inset-y-0 left-1/2 border-l border-white/50" />
|
||||
) : null}
|
||||
</span>
|
||||
<span
|
||||
className={`mt-2 block text-center text-xs font-medium ${
|
||||
selected ? "text-foreground" : "text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{option.label}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function ThemeColorControl({
|
||||
label,
|
||||
value,
|
||||
swatches,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
swatches: readonly string[];
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<fieldset className="grid min-w-0 gap-2">
|
||||
<legend className="mb-2 text-xs font-medium text-foreground">{label}</legend>
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={value}
|
||||
onChange={(event) => onChange(event.currentTarget.value)}
|
||||
aria-label={`Custom ${label.toLowerCase()}`}
|
||||
className="h-8 w-10 cursor-pointer rounded-lg border border-input bg-background p-0.5"
|
||||
/>
|
||||
{swatches.map((swatch) => (
|
||||
<button
|
||||
key={swatch}
|
||||
type="button"
|
||||
className="size-6 cursor-pointer rounded-full border border-black/10 ring-offset-2 ring-offset-background transition hover:scale-105 data-[selected=true]:ring-2 data-[selected=true]:ring-ring dark:border-white/20"
|
||||
style={{ backgroundColor: swatch }}
|
||||
data-selected={value === swatch}
|
||||
aria-pressed={value === swatch}
|
||||
onClick={() => onChange(swatch)}
|
||||
aria-label={`Use ${swatch} for ${label.toLowerCase()}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
||||
const ENVIRONMENT_IDENTIFICATION_LABELS: Record<EnvironmentIdentificationMode, string> = {
|
||||
artwork: "Artwork",
|
||||
pill: "Version pill",
|
||||
@@ -558,6 +682,7 @@ function AboutVersionSection() {
|
||||
|
||||
export function useSettingsRestore(onRestored?: () => void) {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const { colors, setThemeColors } = useThemeColors();
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
|
||||
@@ -570,6 +695,10 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
const changedSettingLabels = useMemo(
|
||||
() => [
|
||||
...(theme !== "system" ? ["Theme"] : []),
|
||||
...(colors.accentColor !== DEFAULT_THEME_COLORS.accentColor ||
|
||||
colors.neutralColor !== DEFAULT_THEME_COLORS.neutralColor
|
||||
? ["Theme colors"]
|
||||
: []),
|
||||
...(settings.glassOpacity !== DEFAULT_UNIFIED_SETTINGS.glassOpacity ? ["Glass opacity"] : []),
|
||||
...(settings.environmentIdentificationMode !==
|
||||
DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode
|
||||
@@ -637,6 +766,8 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.timestampFormat,
|
||||
settings.wordWrap,
|
||||
theme,
|
||||
colors.accentColor,
|
||||
colors.neutralColor,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -651,6 +782,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
if (!confirmed) return;
|
||||
|
||||
setTheme("system");
|
||||
setThemeColors(DEFAULT_THEME_COLORS);
|
||||
updateSettings({
|
||||
timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
|
||||
wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,
|
||||
@@ -674,7 +806,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
textGenerationModelSelection: DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
|
||||
});
|
||||
onRestored?.();
|
||||
}, [changedSettingLabels, onRestored, setTheme, updateSettings]);
|
||||
}, [changedSettingLabels, onRestored, setTheme, setThemeColors, updateSettings]);
|
||||
|
||||
return {
|
||||
changedSettingLabels,
|
||||
@@ -950,6 +1082,7 @@ function BackgroundActivityAdvancedDialog({
|
||||
|
||||
export function AppearanceSettingsPanel() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const { colors, setThemeColors } = useThemeColors();
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
const environmentStageLabel = useEnvironmentStageLabel();
|
||||
@@ -967,36 +1100,86 @@ export function AppearanceSettingsPanel() {
|
||||
<SettingsSection id="appearance" title="Appearance">
|
||||
<SettingsRow
|
||||
{...searchableSetting("theme")}
|
||||
description="Choose how T3 Code looks across the app."
|
||||
description="Choose a mode with a quick preview of the workspace."
|
||||
resetAction={
|
||||
theme !== "system" ? (
|
||||
<SettingResetButton label="theme" onClick={() => setTheme("system")} />
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Select
|
||||
value={theme}
|
||||
onValueChange={(value) => {
|
||||
if (value === "system" || value === "light" || value === "dark") {
|
||||
setTheme(value);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-40" aria-label="Theme preference">
|
||||
<SelectValue>
|
||||
{THEME_OPTIONS.find((option) => option.value === theme)?.label ?? "System"}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
{THEME_OPTIONS.map((option) => (
|
||||
<SelectItem hideIndicator key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
>
|
||||
<div className="mt-4 grid grid-cols-3 gap-3 pb-3">
|
||||
{THEME_OPTIONS.map((option) => (
|
||||
<ThemeModePreview
|
||||
key={option.value}
|
||||
option={option}
|
||||
selected={theme === option.value}
|
||||
accentColor={colors.accentColor}
|
||||
onSelect={() => setTheme(option.value)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow
|
||||
{...searchableSetting("theme-colors")}
|
||||
description="Pick two color seeds, then tune how strongly they separate surfaces and controls."
|
||||
resetAction={
|
||||
colors.accentColor !== DEFAULT_THEME_COLORS.accentColor ||
|
||||
colors.neutralColor !== DEFAULT_THEME_COLORS.neutralColor ||
|
||||
colors.contrast !== DEFAULT_THEME_COLORS.contrast ? (
|
||||
<SettingResetButton
|
||||
label="theme colors"
|
||||
onClick={() => setThemeColors(DEFAULT_THEME_COLORS)}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
>
|
||||
<div className="mt-4 grid gap-4 pb-2 sm:grid-cols-2">
|
||||
<ThemeColorControl
|
||||
label="Accent color"
|
||||
value={colors.accentColor}
|
||||
swatches={THEME_COLOR_SWATCHES}
|
||||
onChange={(accentColor) =>
|
||||
setThemeColors({ ...colors, accentColor } satisfies ThemeColors)
|
||||
}
|
||||
/>
|
||||
<ThemeColorControl
|
||||
label="Surface tint"
|
||||
value={colors.neutralColor}
|
||||
swatches={THEME_NEUTRAL_SWATCHES}
|
||||
onChange={(neutralColor) =>
|
||||
setThemeColors({ ...colors, neutralColor } satisfies ThemeColors)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 border-t border-border/70 py-4">
|
||||
<label htmlFor="theme-contrast" className="text-xs font-medium text-foreground">
|
||||
Interface contrast
|
||||
</label>
|
||||
<input
|
||||
id="theme-contrast"
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
step={5}
|
||||
value={colors.contrast}
|
||||
style={{ accentColor: colors.accentColor }}
|
||||
onChange={(event) =>
|
||||
setThemeColors({
|
||||
...colors,
|
||||
contrast: Number(event.currentTarget.value),
|
||||
} satisfies ThemeColors)
|
||||
}
|
||||
className="min-w-0 flex-1 cursor-pointer"
|
||||
/>
|
||||
<output
|
||||
htmlFor="theme-contrast"
|
||||
className="w-8 text-right font-mono text-xs tabular-nums text-muted-foreground"
|
||||
>
|
||||
{colors.contrast}
|
||||
</output>
|
||||
</div>
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow
|
||||
{...searchableSetting("setting-glass-opacity")}
|
||||
|
||||
@@ -248,6 +248,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
|
||||
</p>
|
||||
) : null}
|
||||
<SidebarMenu
|
||||
className="ps-px"
|
||||
id={isSearching && hasResults ? "settings-search-results" : undefined}
|
||||
role={isSearching && hasResults ? "listbox" : undefined}
|
||||
aria-label={isSearching && hasResults ? "Settings search results" : undefined}
|
||||
|
||||
@@ -42,6 +42,11 @@ export const SETTINGS_SEARCH_ITEMS = [
|
||||
title: "Theme",
|
||||
to: "/settings/appearance",
|
||||
},
|
||||
{
|
||||
id: "theme-colors",
|
||||
title: "Theme colors",
|
||||
to: "/settings/appearance",
|
||||
},
|
||||
{
|
||||
// Prefixed because the slider control already owns the `glass-opacity` id.
|
||||
id: "setting-glass-opacity",
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
const THEME_COLOR_META_NAME = "theme-color";
|
||||
const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data-dynamic-theme-color="true"]`;
|
||||
|
||||
function ensureThemeColorMetaTag(): HTMLMetaElement {
|
||||
let element = document.querySelector<HTMLMetaElement>(DYNAMIC_THEME_COLOR_SELECTOR);
|
||||
if (element) return element;
|
||||
|
||||
element = document.createElement("meta");
|
||||
element.name = THEME_COLOR_META_NAME;
|
||||
element.setAttribute("data-dynamic-theme-color", "true");
|
||||
document.head.append(element);
|
||||
return element;
|
||||
}
|
||||
|
||||
function normalizeThemeColor(value: string | null | undefined): string | null {
|
||||
const normalizedValue = value?.trim().toLowerCase();
|
||||
if (
|
||||
!normalizedValue ||
|
||||
normalizedValue === "transparent" ||
|
||||
normalizedValue === "rgba(0, 0, 0, 0)" ||
|
||||
normalizedValue === "rgba(0 0 0 / 0)"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return value?.trim() ?? null;
|
||||
}
|
||||
|
||||
function resolveBrowserChromeSurface(): HTMLElement {
|
||||
return (
|
||||
document.querySelector<HTMLElement>("main[data-slot='sidebar-inset']") ??
|
||||
document.querySelector<HTMLElement>("[data-slot='sidebar-inner']") ??
|
||||
document.body
|
||||
);
|
||||
}
|
||||
|
||||
export function syncBrowserChromeTheme(): void {
|
||||
if (typeof document === "undefined" || typeof getComputedStyle === "undefined") return;
|
||||
const surfaceColor = normalizeThemeColor(
|
||||
getComputedStyle(resolveBrowserChromeSurface()).backgroundColor,
|
||||
);
|
||||
const fallbackColor = normalizeThemeColor(getComputedStyle(document.body).backgroundColor);
|
||||
const backgroundColor = surfaceColor ?? fallbackColor;
|
||||
if (!backgroundColor) return;
|
||||
|
||||
document.documentElement.style.backgroundColor = backgroundColor;
|
||||
document.body.style.backgroundColor = backgroundColor;
|
||||
ensureThemeColorMetaTag().setAttribute("content", backgroundColor);
|
||||
}
|
||||
@@ -2,6 +2,9 @@ import type { DesktopBridge } from "@t3tools/contracts";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
import { syncBrowserChromeTheme } from "./browserChromeTheme";
|
||||
|
||||
export { syncBrowserChromeTheme } from "./browserChromeTheme";
|
||||
|
||||
const ThemePreference = Schema.Literals(["light", "dark", "system"]);
|
||||
type Theme = typeof ThemePreference.Type;
|
||||
@@ -18,8 +21,6 @@ const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {
|
||||
theme: "system",
|
||||
systemDark: false,
|
||||
};
|
||||
const THEME_COLOR_META_NAME = "theme-color";
|
||||
const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data-dynamic-theme-color="true"]`;
|
||||
|
||||
export class ThemeStorageError extends Schema.TaggedErrorClass<ThemeStorageError>()(
|
||||
"ThemeStorageError",
|
||||
@@ -124,55 +125,6 @@ function getStored(): Theme {
|
||||
}
|
||||
}
|
||||
|
||||
function ensureThemeColorMetaTag(): HTMLMetaElement {
|
||||
let element = document.querySelector<HTMLMetaElement>(DYNAMIC_THEME_COLOR_SELECTOR);
|
||||
if (element) {
|
||||
return element;
|
||||
}
|
||||
|
||||
element = document.createElement("meta");
|
||||
element.name = THEME_COLOR_META_NAME;
|
||||
element.setAttribute("data-dynamic-theme-color", "true");
|
||||
document.head.append(element);
|
||||
return element;
|
||||
}
|
||||
|
||||
function normalizeThemeColor(value: string | null | undefined): string | null {
|
||||
const normalizedValue = value?.trim().toLowerCase();
|
||||
if (
|
||||
!normalizedValue ||
|
||||
normalizedValue === "transparent" ||
|
||||
normalizedValue === "rgba(0, 0, 0, 0)" ||
|
||||
normalizedValue === "rgba(0 0 0 / 0)"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return value?.trim() ?? null;
|
||||
}
|
||||
|
||||
function resolveBrowserChromeSurface(): HTMLElement {
|
||||
return (
|
||||
document.querySelector<HTMLElement>("main[data-slot='sidebar-inset']") ??
|
||||
document.querySelector<HTMLElement>("[data-slot='sidebar-inner']") ??
|
||||
document.body
|
||||
);
|
||||
}
|
||||
|
||||
export function syncBrowserChromeTheme() {
|
||||
if (typeof document === "undefined" || typeof getComputedStyle === "undefined") return;
|
||||
const surfaceColor = normalizeThemeColor(
|
||||
getComputedStyle(resolveBrowserChromeSurface()).backgroundColor,
|
||||
);
|
||||
const fallbackColor = normalizeThemeColor(getComputedStyle(document.body).backgroundColor);
|
||||
const backgroundColor = surfaceColor ?? fallbackColor;
|
||||
if (!backgroundColor) return;
|
||||
|
||||
document.documentElement.style.backgroundColor = backgroundColor;
|
||||
document.body.style.backgroundColor = backgroundColor;
|
||||
ensureThemeColorMetaTag().setAttribute("content", backgroundColor);
|
||||
}
|
||||
|
||||
function applyTheme(theme: Theme, suppressTransitions = false) {
|
||||
if (typeof document === "undefined" || typeof window === "undefined") return;
|
||||
const systemDark = theme === "system" ? getSystemDark() : false;
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
function createStorage(initial: Record<string, string> = {}): Storage {
|
||||
const store = new Map(Object.entries(initial));
|
||||
return {
|
||||
clear: () => store.clear(),
|
||||
getItem: (key) => store.get(key) ?? null,
|
||||
key: (index) => [...store.keys()][index] ?? null,
|
||||
get length() {
|
||||
return store.size;
|
||||
},
|
||||
removeItem: (key) => store.delete(key),
|
||||
setItem: (key, value) => store.set(key, value),
|
||||
};
|
||||
}
|
||||
|
||||
function createWindow(initial: Record<string, string> = {}) {
|
||||
return { addEventListener: vi.fn(), localStorage: createStorage(initial) };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.resetModules();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("theme colors", () => {
|
||||
it("normalizes valid colors and falls back per invalid color", async () => {
|
||||
vi.stubGlobal("window", createWindow());
|
||||
const { normalizeThemeColors } = await import("./useThemeColors");
|
||||
|
||||
expect(
|
||||
normalizeThemeColors({
|
||||
accentColor: " #DB2777 ",
|
||||
neutralColor: "not-a-color",
|
||||
contrast: 120,
|
||||
}),
|
||||
).toEqual({ accentColor: "#db2777", neutralColor: "#737373", contrast: 100 });
|
||||
});
|
||||
|
||||
it("reads a valid palette from storage", async () => {
|
||||
vi.stubGlobal(
|
||||
"window",
|
||||
createWindow({
|
||||
"t3code:theme-colors": JSON.stringify({
|
||||
accentColor: "#0891b2",
|
||||
neutralColor: "#57534e",
|
||||
contrast: 30,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const { readThemeColors } = await import("./useThemeColors");
|
||||
|
||||
expect(readThemeColors()).toEqual({
|
||||
accentColor: "#0891b2",
|
||||
neutralColor: "#57534e",
|
||||
contrast: 30,
|
||||
});
|
||||
});
|
||||
|
||||
it("migrates palettes saved before contrast was configurable", async () => {
|
||||
vi.stubGlobal(
|
||||
"window",
|
||||
createWindow({
|
||||
"t3code:theme-colors": JSON.stringify({
|
||||
accentColor: "#0891b2",
|
||||
neutralColor: "#57534e",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const { readThemeColors } = await import("./useThemeColors");
|
||||
|
||||
expect(readThemeColors()).toEqual({
|
||||
accentColor: "#0891b2",
|
||||
neutralColor: "#57534e",
|
||||
contrast: 50,
|
||||
});
|
||||
});
|
||||
|
||||
it("applies the palette and contrast properties to the document root", async () => {
|
||||
const setProperty = vi.fn();
|
||||
vi.stubGlobal("window", createWindow());
|
||||
vi.stubGlobal("document", { documentElement: { style: { setProperty } } });
|
||||
const { applyThemeColors } = await import("./useThemeColors");
|
||||
|
||||
applyThemeColors({ accentColor: "#16a34a", neutralColor: "#78716c", contrast: 50 });
|
||||
|
||||
expect(setProperty).toHaveBeenCalledWith("--theme-accent-seed", "#16a34a");
|
||||
expect(setProperty).toHaveBeenCalledWith("--theme-neutral-seed", "#78716c");
|
||||
expect(setProperty).toHaveBeenCalledWith("--theme-accent-strength", "16%");
|
||||
expect(setProperty).toHaveBeenCalledWith("--theme-border-strength", "16%");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import { syncBrowserChromeTheme } from "./browserChromeTheme";
|
||||
|
||||
export type ThemeColors = {
|
||||
accentColor: string;
|
||||
neutralColor: string;
|
||||
contrast: number;
|
||||
};
|
||||
|
||||
export const DEFAULT_THEME_COLORS: ThemeColors = {
|
||||
accentColor: "#3b5bdb",
|
||||
neutralColor: "#737373",
|
||||
contrast: 50,
|
||||
};
|
||||
|
||||
export const THEME_COLORS_STORAGE_KEY = "t3code:theme-colors";
|
||||
|
||||
const HEX_COLOR_PATTERN = /^#[0-9a-f]{6}$/iu;
|
||||
const listeners = new Set<() => void>();
|
||||
let currentColors = readThemeColors();
|
||||
|
||||
export function normalizeThemeColor(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") return undefined;
|
||||
const normalized = value.trim().toLowerCase();
|
||||
return HEX_COLOR_PATTERN.test(normalized) ? normalized : undefined;
|
||||
}
|
||||
|
||||
export function normalizeThemeColors(value: unknown): ThemeColors {
|
||||
const colors = value && typeof value === "object" ? (value as Partial<ThemeColors>) : {};
|
||||
return {
|
||||
accentColor: normalizeThemeColor(colors.accentColor) ?? DEFAULT_THEME_COLORS.accentColor,
|
||||
neutralColor: normalizeThemeColor(colors.neutralColor) ?? DEFAULT_THEME_COLORS.neutralColor,
|
||||
contrast:
|
||||
typeof colors.contrast === "number" && Number.isFinite(colors.contrast)
|
||||
? Math.round(Math.min(100, Math.max(0, colors.contrast)))
|
||||
: DEFAULT_THEME_COLORS.contrast,
|
||||
};
|
||||
}
|
||||
|
||||
function getThemeContrastProperties(contrast: number): Record<string, string> {
|
||||
return {
|
||||
"--theme-background-strength": `${4 + contrast * 0.12}%`,
|
||||
"--theme-surface-strength": `${6 + contrast * 0.16}%`,
|
||||
"--theme-control-strength": `${3 + contrast * 0.08}%`,
|
||||
"--theme-accent-strength": `${6 + contrast * 0.2}%`,
|
||||
"--theme-border-strength": `${8 + contrast * 0.16}%`,
|
||||
};
|
||||
}
|
||||
|
||||
export function readThemeColors(): ThemeColors {
|
||||
if (typeof window === "undefined") return DEFAULT_THEME_COLORS;
|
||||
try {
|
||||
const stored = window.localStorage.getItem(THEME_COLORS_STORAGE_KEY);
|
||||
return stored ? normalizeThemeColors(JSON.parse(stored)) : DEFAULT_THEME_COLORS;
|
||||
} catch {
|
||||
return DEFAULT_THEME_COLORS;
|
||||
}
|
||||
}
|
||||
|
||||
export function applyThemeColors(colors: ThemeColors): void {
|
||||
if (typeof document === "undefined") return;
|
||||
const rootStyle = document.documentElement.style;
|
||||
rootStyle.setProperty("--theme-accent-seed", colors.accentColor);
|
||||
rootStyle.setProperty("--theme-neutral-seed", colors.neutralColor);
|
||||
for (const [property, value] of Object.entries(getThemeContrastProperties(colors.contrast))) {
|
||||
rootStyle.setProperty(property, value);
|
||||
}
|
||||
syncBrowserChromeTheme();
|
||||
}
|
||||
|
||||
function emitChange(): void {
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
function persistThemeColors(colors: ThemeColors): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
window.localStorage.setItem(THEME_COLORS_STORAGE_KEY, JSON.stringify(colors));
|
||||
} catch {
|
||||
// The colors still apply for this session when storage is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
function setCurrentColors(colors: ThemeColors): void {
|
||||
currentColors = colors;
|
||||
applyThemeColors(colors);
|
||||
emitChange();
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
applyThemeColors(currentColors);
|
||||
window.addEventListener("storage", (event) => {
|
||||
if (event.key === THEME_COLORS_STORAGE_KEY) setCurrentColors(readThemeColors());
|
||||
});
|
||||
}
|
||||
|
||||
export function useThemeColors() {
|
||||
const colors = useSyncExternalStore(
|
||||
subscribe,
|
||||
() => currentColors,
|
||||
() => DEFAULT_THEME_COLORS,
|
||||
);
|
||||
|
||||
const setThemeColors = useCallback((value: ThemeColors) => {
|
||||
const normalized = normalizeThemeColors(value);
|
||||
persistThemeColors(normalized);
|
||||
setCurrentColors(normalized);
|
||||
}, []);
|
||||
|
||||
return { colors, setThemeColors } as const;
|
||||
}
|
||||
+130
-70
@@ -853,42 +853,59 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--radius: 0.625rem;
|
||||
--background: var(--color-zinc-25);
|
||||
--theme-accent-seed: #3b5bdb;
|
||||
--theme-neutral-seed: #737373;
|
||||
--theme-background-strength: 10%;
|
||||
--theme-surface-strength: 14%;
|
||||
--theme-control-strength: 7%;
|
||||
--theme-accent-strength: 16%;
|
||||
--theme-border-strength: 16%;
|
||||
--background: color-mix(
|
||||
in srgb,
|
||||
var(--theme-neutral-seed) var(--theme-background-strength),
|
||||
var(--color-zinc-25)
|
||||
);
|
||||
--app-chrome-background: var(--background);
|
||||
--surface-raised: color-mix(in srgb, var(--card) 20%, transparent);
|
||||
--foreground: var(--color-zinc-800);
|
||||
--card: var(--color-white);
|
||||
--card-foreground: var(--color-zinc-800);
|
||||
--popover: var(--color-white);
|
||||
--popover-foreground: var(--color-zinc-800);
|
||||
--primary: oklch(0.488 0.217 264);
|
||||
--card: color-mix(in srgb, var(--theme-neutral-seed) 2%, var(--color-white));
|
||||
--card-foreground: var(--foreground);
|
||||
--popover: var(--card);
|
||||
--popover-foreground: var(--foreground);
|
||||
/* Keep text, rings, and translucent primary controls readable for any seed.
|
||||
Raw seed color still drives the more expressive accent surfaces below. */
|
||||
--primary: color-mix(in oklch, var(--theme-accent-seed) 46%, var(--color-black));
|
||||
--primary-foreground: var(--color-white);
|
||||
--secondary: var(--color-zinc-50);
|
||||
--secondary-foreground: var(--color-zinc-800);
|
||||
--muted: var(--color-zinc-50);
|
||||
--secondary: color-mix(
|
||||
in srgb,
|
||||
var(--theme-neutral-seed) var(--theme-control-strength),
|
||||
transparent
|
||||
);
|
||||
--secondary-foreground: var(--foreground);
|
||||
--muted: color-mix(in srgb, var(--theme-neutral-seed) var(--theme-control-strength), transparent);
|
||||
--muted-foreground: var(--color-zinc-500);
|
||||
--accent: var(--color-zinc-100);
|
||||
--accent-foreground: var(--color-zinc-900);
|
||||
--accent: color-mix(in srgb, var(--theme-accent-seed) var(--theme-accent-strength), transparent);
|
||||
--accent-foreground: var(--foreground);
|
||||
--destructive: var(--color-red-500);
|
||||
--border: var(--color-zinc-200);
|
||||
--input: var(--color-zinc-300);
|
||||
--ring: oklch(0.488 0.217 264);
|
||||
--border: color-mix(in srgb, var(--theme-neutral-seed) var(--theme-border-strength), transparent);
|
||||
--input: color-mix(in srgb, var(--theme-neutral-seed) var(--theme-border-strength), transparent);
|
||||
--ring: var(--primary);
|
||||
--destructive-foreground: var(--color-red-700);
|
||||
--info: var(--color-blue-500);
|
||||
--info-foreground: var(--color-blue-700);
|
||||
--info: var(--primary);
|
||||
--info-foreground: var(--primary);
|
||||
--success: var(--color-emerald-500);
|
||||
--success-foreground: var(--color-emerald-700);
|
||||
--warning: var(--color-amber-500);
|
||||
--warning-foreground: var(--color-amber-700);
|
||||
/* Keep every sidebar primitive on the same light surface hierarchy, including
|
||||
portaled mobile sheets and settings navigation outside the app sidebar. */
|
||||
--sidebar: var(--color-zinc-50);
|
||||
/* Keep portaled mobile sheets and settings navigation on the generated palette,
|
||||
even when they render outside the main app sidebar. */
|
||||
--sidebar: var(--background);
|
||||
--sidebar-foreground: var(--foreground);
|
||||
--sidebar-muted-foreground: var(--muted-foreground);
|
||||
--sidebar-control-surface: var(--color-zinc-100);
|
||||
--sidebar-row-hover: var(--color-zinc-25);
|
||||
--sidebar-row-active: var(--color-white);
|
||||
--sidebar-row-selected: var(--color-white);
|
||||
--sidebar-control-surface: var(--muted);
|
||||
--sidebar-row-hover: var(--accent);
|
||||
--sidebar-row-active: var(--card);
|
||||
--sidebar-row-selected: var(--card);
|
||||
--sidebar-border: var(--border);
|
||||
--sidebar-stage-fade: var(--sidebar);
|
||||
|
||||
@@ -896,29 +913,61 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
color-scheme: dark;
|
||||
/* Keep the workspace in the same neutral-black family as sidebar v2.
|
||||
Surfaces lift from this base instead of starting from a milky gray. */
|
||||
--background: var(--color-neutral-950);
|
||||
--background: color-mix(
|
||||
in srgb,
|
||||
var(--theme-neutral-seed) var(--theme-background-strength),
|
||||
var(--color-neutral-950)
|
||||
);
|
||||
--app-chrome-background: var(--background);
|
||||
--surface-raised: var(--secondary);
|
||||
--foreground: var(--color-neutral-100);
|
||||
--card: color-mix(in srgb, var(--background) 97%, var(--color-white));
|
||||
--card-foreground: var(--color-neutral-100);
|
||||
--popover: color-mix(in srgb, var(--background) 94%, var(--color-white));
|
||||
--popover-foreground: var(--color-neutral-100);
|
||||
--primary: oklch(0.588 0.217 264);
|
||||
--primary-foreground: var(--color-white);
|
||||
--secondary: --alpha(var(--color-white) / 4%);
|
||||
--secondary-foreground: var(--color-neutral-100);
|
||||
--muted: --alpha(var(--color-white) / 4%);
|
||||
--card: color-mix(
|
||||
in srgb,
|
||||
var(--theme-neutral-seed) var(--theme-surface-strength),
|
||||
var(--background)
|
||||
);
|
||||
--card-foreground: var(--foreground);
|
||||
--popover: color-mix(
|
||||
in srgb,
|
||||
var(--theme-neutral-seed) var(--theme-border-strength),
|
||||
var(--background)
|
||||
);
|
||||
--popover-foreground: var(--foreground);
|
||||
--primary: color-mix(in oklch, var(--theme-accent-seed) 40%, var(--color-white));
|
||||
--primary-foreground: var(--color-black);
|
||||
--secondary: color-mix(
|
||||
in srgb,
|
||||
var(--theme-neutral-seed) var(--theme-surface-strength),
|
||||
transparent
|
||||
);
|
||||
--secondary-foreground: var(--foreground);
|
||||
--muted: color-mix(
|
||||
in srgb,
|
||||
var(--theme-neutral-seed) var(--theme-surface-strength),
|
||||
transparent
|
||||
);
|
||||
--muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-white));
|
||||
--accent: --alpha(var(--color-white) / 4%);
|
||||
--accent-foreground: var(--color-neutral-100);
|
||||
--accent: color-mix(
|
||||
in srgb,
|
||||
var(--theme-accent-seed) var(--theme-accent-strength),
|
||||
transparent
|
||||
);
|
||||
--accent-foreground: var(--foreground);
|
||||
--destructive: color-mix(in srgb, var(--color-red-500) 90%, var(--color-white));
|
||||
--border: --alpha(var(--color-white) / 6%);
|
||||
--input: --alpha(var(--color-white) / 8%);
|
||||
--ring: oklch(0.588 0.217 264);
|
||||
--border: color-mix(
|
||||
in srgb,
|
||||
var(--theme-neutral-seed) var(--theme-border-strength),
|
||||
transparent
|
||||
);
|
||||
--input: color-mix(
|
||||
in srgb,
|
||||
var(--theme-neutral-seed) var(--theme-border-strength),
|
||||
transparent
|
||||
);
|
||||
--ring: var(--primary);
|
||||
--destructive-foreground: var(--color-red-400);
|
||||
--info: var(--color-blue-500);
|
||||
--info-foreground: var(--color-blue-400);
|
||||
--info: var(--primary);
|
||||
--info-foreground: var(--primary);
|
||||
--success: var(--color-emerald-500);
|
||||
--success-foreground: var(--color-emerald-400);
|
||||
--warning: var(--color-amber-500);
|
||||
@@ -935,53 +984,64 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
}
|
||||
}
|
||||
|
||||
/* Keep both navigation implementations on the same quiet zinc hierarchy:
|
||||
zinc-50 navigation, zinc-25 hover, and white selected/raised surfaces.
|
||||
/* Keep both navigation implementations on the same generated hierarchy.
|
||||
The version attribute remains useful for layout-specific styling without
|
||||
changing the color system when the beta is toggled. */
|
||||
[data-sidebar-version="v1"],
|
||||
[data-sidebar-version="v2"] {
|
||||
--background: var(--color-zinc-25);
|
||||
--background: color-mix(
|
||||
in srgb,
|
||||
var(--theme-neutral-seed) var(--theme-background-strength),
|
||||
var(--color-zinc-25)
|
||||
);
|
||||
--foreground: var(--color-zinc-800);
|
||||
--card: var(--color-white);
|
||||
--card-foreground: var(--color-zinc-800);
|
||||
--accent: var(--color-zinc-100);
|
||||
--accent-foreground: var(--color-zinc-900);
|
||||
--muted: var(--color-zinc-50);
|
||||
--card: color-mix(in srgb, var(--theme-neutral-seed) 2%, var(--color-white));
|
||||
--card-foreground: var(--foreground);
|
||||
--accent: color-mix(in srgb, var(--theme-accent-seed) var(--theme-accent-strength), transparent);
|
||||
--accent-foreground: var(--foreground);
|
||||
--muted: color-mix(in srgb, var(--theme-neutral-seed) var(--theme-control-strength), transparent);
|
||||
--muted-foreground: var(--color-zinc-500);
|
||||
--border: var(--color-zinc-200);
|
||||
--input: var(--color-zinc-300);
|
||||
--sidebar: var(--color-zinc-50);
|
||||
--sidebar-foreground: var(--color-zinc-800);
|
||||
--sidebar-muted-foreground: var(--color-zinc-500);
|
||||
--sidebar-control-surface: var(--color-zinc-100);
|
||||
--sidebar-row-hover: var(--color-zinc-25);
|
||||
--sidebar-row-active: var(--color-white);
|
||||
--sidebar-row-selected: var(--color-white);
|
||||
--sidebar-border: var(--color-zinc-200);
|
||||
--border: color-mix(in srgb, var(--theme-neutral-seed) var(--theme-border-strength), transparent);
|
||||
--input: var(--border);
|
||||
--sidebar: var(--background);
|
||||
--sidebar-foreground: var(--foreground);
|
||||
--sidebar-muted-foreground: var(--muted-foreground);
|
||||
--sidebar-control-surface: var(--muted);
|
||||
--sidebar-row-hover: var(--accent);
|
||||
--sidebar-row-active: var(--card);
|
||||
--sidebar-row-selected: var(--card);
|
||||
--sidebar-border: var(--border);
|
||||
--sidebar-stage-fade: var(--sidebar);
|
||||
background-color: var(--sidebar);
|
||||
}
|
||||
|
||||
.dark [data-sidebar-version="v1"],
|
||||
.dark [data-sidebar-version="v2"] {
|
||||
--background: #000;
|
||||
--foreground: #f1f3f7;
|
||||
--card: #000;
|
||||
--background: color-mix(
|
||||
in srgb,
|
||||
var(--theme-neutral-seed) var(--theme-background-strength),
|
||||
var(--color-neutral-950)
|
||||
);
|
||||
--foreground: var(--color-neutral-100);
|
||||
--card: color-mix(
|
||||
in srgb,
|
||||
var(--theme-neutral-seed) var(--theme-surface-strength),
|
||||
var(--background)
|
||||
);
|
||||
--card-foreground: var(--foreground);
|
||||
--accent: #191a1d;
|
||||
--accent-foreground: #f7f9ff;
|
||||
--muted: #0a0a0a;
|
||||
--muted-foreground: #a3a3a3;
|
||||
--border: rgb(255 255 255 / 8%);
|
||||
--input: rgb(255 255 255 / 18%);
|
||||
--accent: color-mix(in srgb, var(--theme-accent-seed) var(--theme-accent-strength), transparent);
|
||||
--accent-foreground: var(--foreground);
|
||||
--muted: color-mix(in srgb, var(--theme-neutral-seed) var(--theme-surface-strength), transparent);
|
||||
--muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-white));
|
||||
--border: color-mix(in srgb, var(--theme-neutral-seed) var(--theme-border-strength), transparent);
|
||||
--input: var(--border);
|
||||
--sidebar: var(--card);
|
||||
--sidebar-foreground: var(--foreground);
|
||||
--sidebar-muted-foreground: var(--muted-foreground);
|
||||
--sidebar-control-surface: var(--muted);
|
||||
--sidebar-row-hover: color-mix(in srgb, var(--foreground) 8%, transparent);
|
||||
--sidebar-row-active: color-mix(in srgb, var(--foreground) 11%, transparent);
|
||||
--sidebar-row-selected: color-mix(in srgb, var(--foreground) 7%, transparent);
|
||||
--sidebar-row-hover: var(--accent);
|
||||
--sidebar-row-active: var(--accent);
|
||||
--sidebar-row-selected: var(--muted);
|
||||
--sidebar-border: var(--border);
|
||||
/* The stage-channel header art must ramp to THIS panel's surface, not the
|
||||
global chrome background, or the fade shows a seam (same rule as the
|
||||
|
||||
@@ -9,6 +9,7 @@ import "@fontsource-variable/dm-sans/index.css";
|
||||
import "@fontsource/jetbrains-mono/400.css";
|
||||
import "@fontsource/jetbrains-mono/500.css";
|
||||
import "./index.css";
|
||||
import "./hooks/useThemeColors";
|
||||
|
||||
import { isElectron } from "./env";
|
||||
import { ManagedRelayAuthProvider } from "./cloud/managedAuth";
|
||||
|
||||
@@ -55,6 +55,24 @@ function settingsWithProviderInstances(): UnifiedSettings {
|
||||
}
|
||||
|
||||
describe("instance-scoped model selection", () => {
|
||||
it("preserves server-provided legacy model metadata", () => {
|
||||
const baseProvider = provider({
|
||||
instanceId: "claudeAgent",
|
||||
models: ["claude-opus-4-8"],
|
||||
});
|
||||
const providers = [
|
||||
{
|
||||
...baseProvider,
|
||||
models: [{ ...baseProvider.models[0]!, isLegacy: true }],
|
||||
},
|
||||
];
|
||||
const stock = deriveProviderInstanceEntries(providers)[0]!;
|
||||
|
||||
expect(getAppModelOptionsForInstance(settingsWithProviderInstances(), stock)[0]?.isLegacy).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps custom models on the provider instance that declared them", () => {
|
||||
const providers = [
|
||||
provider({
|
||||
|
||||
@@ -76,6 +76,7 @@ export interface AppModelOption {
|
||||
subProvider?: string;
|
||||
isCustom: boolean;
|
||||
isDefault?: boolean;
|
||||
isLegacy?: boolean;
|
||||
}
|
||||
|
||||
function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
|
||||
@@ -87,6 +88,7 @@ function toAppModelOption(model: ServerProvider["models"][number]): AppModelOpti
|
||||
if (model.shortName) option.shortName = model.shortName;
|
||||
if (model.subProvider) option.subProvider = model.subProvider;
|
||||
if (model.isDefault) option.isDefault = true;
|
||||
if (model.isLegacy) option.isLegacy = true;
|
||||
return option;
|
||||
}
|
||||
|
||||
|
||||
@@ -73,6 +73,30 @@ describe("ServerProvider", () => {
|
||||
|
||||
expect(parsed.continuation?.groupKey).toBe("codex:home:/Users/julius/.codex");
|
||||
});
|
||||
|
||||
it("decodes optional legacy model metadata", () => {
|
||||
const parsed = decodeServerProvider({
|
||||
instanceId: "codex",
|
||||
driver: "codex",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-10T00:00:00.000Z",
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
isLegacy: true,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(parsed.models[0]?.isLegacy).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("server config forward compatibility", () => {
|
||||
|
||||
@@ -68,6 +68,7 @@ export const ServerProviderModel = Schema.Struct({
|
||||
subProvider: Schema.optional(TrimmedNonEmptyString),
|
||||
isCustom: Schema.Boolean,
|
||||
isDefault: Schema.optional(Schema.Boolean),
|
||||
isLegacy: Schema.optional(Schema.Boolean),
|
||||
capabilities: Schema.NullOr(ModelCapabilities),
|
||||
});
|
||||
export type ServerProviderModel = typeof ServerProviderModel.Type;
|
||||
|
||||
Reference in new issue
Block a user