feat: let an environment publish themes as a file (#8569)

Co-authored-by: Theo Browne <[email protected]>
This commit is contained in:
Ryan HughesandTheo Browne authored and GitHub committed 2026-08-28 22:46:09 -07:00
1 parent be218ac768
commit c1c2d5401d
32 files changed
+3121 -76

No files matched your search

+2
View File
@@ -17,6 +17,7 @@ import { projectCommand } from "./cli/project.ts";
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
import { serviceCommand } from "./cli/service.ts";
import { servicePreflightCommand } from "./cli/servicePreflight.ts";
import { themeCommand } from "./cli/theme.ts";
import { triageCommand } from "./cli/triage.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
@@ -57,6 +58,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
projectCommand,
serviceCommand,
servicePreflightCommand,
themeCommand,
triageCommand,
cloudEnabled ? connectCommand : connectUnavailableCommand,
]),
+478
View File
@@ -0,0 +1,478 @@
// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises the filesystem boundary.
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as ConfigProvider from "effect/ConfigProvider";
import * as NetService from "@t3tools/shared/Net";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/unstable/cli";
import { cli } from "../bin.ts";
const runCli = (args: ReadonlyArray<string>) =>
Command.runWith(cli, { version: "0.0.0" })(args).pipe(
Effect.provide(Layer.mergeAll(NodeServices.layer, NetService.layer, TestConsole.layer)),
);
const makeBaseDir = () => NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-theme-cli-"));
const settingsPathFor = (baseDir: string) => NodePath.join(baseDir, "userdata", "settings.json");
const NIGHTFALL_THEME_JSON = `${JSON.stringify({
name: "Nightfall",
appearance: "dark",
canvas: "#1a1b26",
accent: "#7aa2f7",
})}\n`;
const JUNK_THEME_JSON = `${JSON.stringify({ name: "Junk" })}\n`;
const readSettings = (baseDir: string): Record<string, unknown> => {
const raw = NodeFS.readFileSync(settingsPathFor(baseDir), "utf8");
return JSON.parse(raw) as Record<string, unknown>;
};
const writeSettings = (baseDir: string, settings: Record<string, unknown>) => {
NodeFS.mkdirSync(NodePath.dirname(settingsPathFor(baseDir)), { recursive: true });
NodeFS.writeFileSync(settingsPathFor(baseDir), `${JSON.stringify(settings, null, 2)}\n`);
};
describe("t3 theme", () => {
it.effect("writes a default theme when no settings file exists yet", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
yield* runCli(["theme", "set", "ocean", "--base-dir", baseDir]);
assert.equal(readSettings(baseDir).defaultTheme, "ocean");
}),
);
// A provisioning command runs against settings written by whatever version
// happens to be installed, so it must not drop what it cannot interpret.
it.effect("preserves settings it does not recognise", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
writeSettings(baseDir, {
enableProviderUpdateChecks: false,
somethingFromANewerBuild: { nested: true },
});
yield* runCli(["theme", "set", "ocean", "--base-dir", baseDir]);
const settings = readSettings(baseDir);
assert.equal(settings.defaultTheme, "ocean");
assert.equal(settings.enableProviderUpdateChecks, false);
assert.deepEqual(settings.somethingFromANewerBuild, { nested: true });
}),
);
it.effect("clears the default back to leaving fresh clients alone", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
writeSettings(baseDir, { enableProviderUpdateChecks: false });
yield* runCli(["theme", "set", "ocean", "--base-dir", baseDir]);
yield* runCli(["theme", "clear", "--base-dir", baseDir]);
const settings = readSettings(baseDir);
assert.equal(Object.hasOwn(settings, "defaultTheme"), false);
assert.equal(settings.enableProviderUpdateChecks, false);
}),
);
// Publishing a file and pointing at it are one step, so an integration
// (a desktop's theme hook) needs no knowledge of the themes directory.
it.effect("publishes a theme file under its filename and sets it", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
const themeFile = NodePath.join(baseDir, "nightfall.json");
NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]);
const published = NodePath.join(baseDir, "userdata", "themes", "nightfall.json");
assert.equal(NodeFS.existsSync(published), true);
assert.equal(readSettings(baseDir).defaultTheme, "nightfall");
// No rollback or staging residue after a successful set.
const residue = NodeFS.readdirSync(NodePath.dirname(published)).filter(
(entry) => !entry.endsWith(".json"),
);
assert.deepEqual(residue, []);
}),
);
it.effect("publishes a theme file under an explicit id", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
const themeFile = NodePath.join(baseDir, "t3code.json");
NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
yield* runCli(["theme", "set", "--id", "nightfall", themeFile, "--base-dir", baseDir]);
assert.equal(
NodeFS.existsSync(NodePath.join(baseDir, "userdata", "themes", "nightfall.json")),
true,
);
assert.equal(readSettings(baseDir).defaultTheme, "nightfall");
}),
);
it.effect("rejects a file that is not a theme and sets nothing", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
const themeFile = NodePath.join(baseDir, "junk.json");
NodeFS.writeFileSync(themeFile, JUNK_THEME_JSON);
const failure = yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
Effect.flip,
);
assert.include(String(failure), "not a valid theme file");
assert.equal(NodeFS.existsSync(NodePath.join(baseDir, "userdata", "themes")), false);
assert.equal(NodeFS.existsSync(settingsPathFor(baseDir)), false);
}),
);
// Publish and set are one command, so a settings file the set step cannot
// use must fail it before the themes directory is mutated -- not after,
// with a half-applied publish left behind.
it.effect("publishes nothing when the settings file cannot be used", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
NodeFS.mkdirSync(NodePath.dirname(settingsPathFor(baseDir)), { recursive: true });
NodeFS.writeFileSync(settingsPathFor(baseDir), "{ not json");
const themeFile = NodePath.join(baseDir, "nightfall.json");
NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
const failure = yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
Effect.flip,
);
assert.include(String(failure), "not a JSON object");
assert.equal(NodeFS.existsSync(NodePath.join(baseDir, "userdata", "themes")), false);
}),
);
// set means set: a publish that rode along with a failed default write is
// rolled back rather than left mutating the environment's theme set. The
// userdata directory is made read-only while themes stays writable, so the
// failure lands after the publish -- the case the rollback exists for.
it.effect("rolls back a publish when the default cannot be written", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
writeSettings(baseDir, {});
const userdataDir = NodePath.dirname(settingsPathFor(baseDir));
const themesDir = NodePath.join(userdataDir, "themes");
NodeFS.mkdirSync(themesDir, { recursive: true });
const themeFile = NodePath.join(baseDir, "nightfall.json");
NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
NodeFS.chmodSync(userdataDir, 0o555);
try {
const failure = yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
Effect.flip,
);
assert.include(String(failure), "Could not write");
assert.equal(NodeFS.existsSync(NodePath.join(themesDir, "nightfall.json")), false);
} finally {
NodeFS.chmodSync(userdataDir, 0o755);
}
}),
);
// A symlink is a normal way to hand this command a theme -- desktop hooks
// symlink the current palette -- so the source is resolved, not refused.
it.effect("publishes a theme file through a symlinked source path", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
const realFile = NodePath.join(baseDir, "real-nightfall.json");
NodeFS.writeFileSync(realFile, NIGHTFALL_THEME_JSON);
const linkPath = NodePath.join(baseDir, "nightfall.json");
NodeFS.symlinkSync(realFile, linkPath);
yield* runCli(["theme", "set", linkPath, "--base-dir", baseDir]);
assert.equal(
NodeFS.existsSync(NodePath.join(baseDir, "userdata", "themes", "nightfall.json")),
true,
);
assert.equal(readSettings(baseDir).defaultTheme, "nightfall");
}),
);
// The staging entry is created fresh with O_EXCL, so a symlink planted at
// its predictable name is cleared, never followed and written through.
it.effect("never writes through a symlink at the staging path", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
const themesDir = NodePath.join(baseDir, "userdata", "themes");
NodeFS.mkdirSync(themesDir, { recursive: true });
const victim = NodePath.join(baseDir, "victim.txt");
NodeFS.writeFileSync(victim, "precious");
NodeFS.symlinkSync(victim, NodePath.join(themesDir, `nightfall.json.staging-${process.pid}`));
const themeFile = NodePath.join(baseDir, "nightfall.json");
NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]);
assert.equal(NodeFS.readFileSync(victim, "utf8"), "precious");
assert.equal(readSettings(baseDir).defaultTheme, "nightfall");
}),
);
// Rollback moves the previous directory entry aside and back, so even an
// entry the watcher would never publish -- here a symlink -- comes back
// exactly as it was when the set fails.
it.effect("restores a non-theme destination entry when the set fails", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
writeSettings(baseDir, {});
const userdataDir = NodePath.dirname(settingsPathFor(baseDir));
const themesDir = NodePath.join(userdataDir, "themes");
NodeFS.mkdirSync(themesDir, { recursive: true });
const outside = NodePath.join(baseDir, "outside.json");
NodeFS.writeFileSync(outside, NIGHTFALL_THEME_JSON);
const destination = NodePath.join(themesDir, "nightfall.json");
NodeFS.symlinkSync(outside, destination);
const themeFile = NodePath.join(baseDir, "nightfall.json");
NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
NodeFS.chmodSync(userdataDir, 0o555);
try {
yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(Effect.flip);
assert.equal(NodeFS.lstatSync(destination).isSymbolicLink(), true);
} finally {
NodeFS.chmodSync(userdataDir, 0o755);
}
}),
);
it.effect("restores the previous theme when a re-publish fails to set", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
writeSettings(baseDir, {});
const userdataDir = NodePath.dirname(settingsPathFor(baseDir));
const themesDir = NodePath.join(userdataDir, "themes");
NodeFS.mkdirSync(themesDir, { recursive: true });
const publishedPath = NodePath.join(themesDir, "nightfall.json");
const previous =
'{ "name": "Old Nightfall", "appearance": "dark", "canvas": "#000000", "accent": "#ffffff" }\n';
NodeFS.writeFileSync(publishedPath, previous);
const themeFile = NodePath.join(baseDir, "nightfall.json");
NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
NodeFS.chmodSync(userdataDir, 0o555);
try {
yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(Effect.flip);
assert.equal(NodeFS.readFileSync(publishedPath, "utf8"), previous);
} finally {
NodeFS.chmodSync(userdataDir, 0o755);
}
}),
);
// A typo'd id written as the theme would silently never resolve anywhere;
// the id branch is as strict as the filename rule.
it.effect("rejects an id no client could resolve", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
const failure = yield* runCli(["theme", "set", "Nightfall", "--base-dir", baseDir]).pipe(
Effect.flip,
);
assert.include(String(failure), "not a valid theme id");
assert.equal(NodeFS.existsSync(settingsPathFor(baseDir)), false);
}),
);
it.effect("rejects a path that does not exist instead of storing it as an id", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
const failure = yield* runCli([
"theme",
"set",
`${baseDir}/missing.json`,
"--base-dir",
baseDir,
]).pipe(Effect.flip);
assert.include(String(failure), "Could not read");
}),
);
// File-ness is decided by existence, not extension, so a generated file
// named for its target app still publishes.
it.effect("publishes an extensionless file", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
const themeFile = NodePath.join(baseDir, "brand");
NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]);
assert.equal(
NodeFS.existsSync(NodePath.join(baseDir, "userdata", "themes", "brand.json")),
true,
);
assert.equal(readSettings(baseDir).defaultTheme, "brand");
}),
);
it.effect("records a set generation and clears it with the theme", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
yield* runCli(["theme", "set", "ocean", "--base-dir", baseDir]);
const setAt = readSettings(baseDir).defaultThemeSetAt;
assert.equal(typeof setAt, "string");
yield* runCli(["theme", "clear", "--base-dir", baseDir]);
const cleared = readSettings(baseDir);
assert.equal(Object.hasOwn(cleared, "defaultTheme"), false);
assert.equal(Object.hasOwn(cleared, "defaultThemeSetAt"), false);
}),
);
it.effect("honors T3CODE_HOME like the rest of the CLI", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
yield* runCli(["theme", "set", "ocean"]).pipe(
Effect.provide(
ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_HOME: baseDir } })),
),
);
assert.equal(readSettings(baseDir).defaultTheme, "ocean");
}),
);
// An unreadable settings file must never read as "no settings": writing a
// fresh sparse file over it would discard every key the user had.
it.effect("refuses to write when the settings file cannot be read", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
writeSettings(baseDir, { enableProviderUpdateChecks: false });
NodeFS.chmodSync(settingsPathFor(baseDir), 0o000);
const failure = yield* runCli(["theme", "set", "ocean", "--base-dir", baseDir]).pipe(
Effect.flip,
);
NodeFS.chmodSync(settingsPathFor(baseDir), 0o644);
assert.include(String(failure), "Could not read");
assert.equal(readSettings(baseDir).enableProviderUpdateChecks, false);
assert.equal(Object.hasOwn(readSettings(baseDir), "defaultTheme"), false);
}),
);
// A typo is syntactically a valid id, so shape validation alone would write
// a theme no client can resolve and report success.
it.effect("rejects an id that names no theme", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
const failure = yield* runCli(["theme", "set", "ocian", "--base-dir", baseDir]).pipe(
Effect.flip,
);
assert.include(String(failure), "No theme named");
assert.equal(NodeFS.existsSync(settingsPathFor(baseDir)), false);
}),
);
it.effect("accepts an id a published file provides", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
const themeFile = NodePath.join(baseDir, "nightfall.json");
NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]);
// Now resolvable by bare id, because the file published it.
yield* runCli(["theme", "clear", "--base-dir", baseDir]);
yield* runCli(["theme", "set", "nightfall", "--base-dir", baseDir]);
assert.equal(readSettings(baseDir).defaultTheme, "nightfall");
}),
);
// The watcher skips files it cannot use, so accepting their filename would
// set a theme no client ever receives.
it.effect("rejects an id whose published file the watcher would skip", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
const themesDir = NodePath.join(baseDir, "userdata", "themes");
NodeFS.mkdirSync(themesDir, { recursive: true });
NodeFS.writeFileSync(NodePath.join(themesDir, "broken.json"), "{ not json\n");
const failure = yield* runCli(["theme", "set", "broken", "--base-dir", baseDir]).pipe(
Effect.flip,
);
assert.include(String(failure), "No theme named");
}),
);
// Web and desktop cannot resolve the mobile default, and mobile does not
// follow this setting, so naming it would be a silent no-op.
it.effect("rejects the mobile default theme id", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
const failure = yield* runCli(["theme", "set", "t3-code", "--base-dir", baseDir]).pipe(
Effect.flip,
);
assert.include(String(failure), "No theme named");
}),
);
// Deciding on existence alone would publish ./ocean instead of selecting the
// built-in, purely because of what happens to be in the working directory.
it.effect("treats a bare id as an id even when a file shares its name", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
const cwdFile = NodePath.join(baseDir, "ocean");
NodeFS.writeFileSync(cwdFile, NIGHTFALL_THEME_JSON);
const previous = process.cwd();
process.chdir(baseDir);
try {
yield* runCli(["theme", "set", "ocean", "--base-dir", baseDir]);
} finally {
process.chdir(previous);
}
assert.equal(readSettings(baseDir).defaultTheme, "ocean");
assert.equal(
NodeFS.existsSync(NodePath.join(baseDir, "userdata", "themes", "ocean.json")),
false,
);
}),
);
// The watcher would skip an oversized file, so publishing one must not
// report success for a theme no client receives.
it.effect("rejects a theme file larger than the watcher will read", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
const themeFile = NodePath.join(baseDir, "huge.json");
const padding = "x".repeat(40 * 1024);
NodeFS.writeFileSync(
themeFile,
`{ "name": "Huge", "appearance": "dark", "canvas": "#1a1b26", "accent": "#7aa2f7", "note": "${padding}" }\n`,
);
const failure = yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
Effect.flip,
);
assert.include(String(failure), "larger than");
}),
);
it.effect("refuses a settings file that is not a JSON object", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
NodeFS.mkdirSync(NodePath.dirname(settingsPathFor(baseDir)), { recursive: true });
NodeFS.writeFileSync(settingsPathFor(baseDir), "[1, 2, 3]\n");
const failure = yield* runCli(["theme", "set", "ocean", "--base-dir", baseDir]).pipe(
Effect.flip,
);
assert.include(String(failure), "not a JSON object");
}),
);
});
+587
View File
@@ -0,0 +1,587 @@
// @effect-diagnostics nodeBuiltinImport:off - publish commits and rollbacks
// move exact directory entries with rename, which the FileSystem service does
// not expose atomically.
/**
* `t3 theme` - inspect and set the environment's theme. Connected web and
* desktop clients switch when it is set; mobile keeps its own appearance
* settings. Each client applies one set once, so a theme the user picks in
* Settings afterwards sticks until the next `t3 theme set`.
*
* Writes `defaultTheme` (and `defaultThemeSetAt`, so a re-set of the same
* value still acts) into the environment's `settings.json`. A running server
* watches that file and pushes the change, so this works before the first
* launch and on a live server alike.
*
* The edit is deliberately a minimal one on the parsed JSON object rather than
* a schema round-trip. Settings files outlive the build that reads them, and a
* provisioning command must not drop keys this version does not recognise.
*/
import * as NodeFS from "node:fs";
import {
EnvironmentThemeFile,
EnvironmentThemeId,
environmentThemeFileHasColors,
} from "@t3tools/contracts";
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
import { BUILT_IN_THEME_IDS, UNPUBLISHABLE_THEME_IDS } from "@t3tools/shared/themePalettes";
import * as Config from "effect/Config";
import * as Console from "effect/Console";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { Argument, Command, Flag } from "effect/unstable/cli";
import { writeFileStringAtomically } from "../atomicWrite.ts";
import * as ServerConfig from "../config.ts";
import {
MAX_THEME_FILE_BYTES,
readPublishedThemes,
readThemeFileGuarded,
} from "../environmentTheme.ts";
import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
import { baseDirFlag } from "./config.ts";
/** Settings files outlive the build that reads them, so the object is carried
* as-is and only the theme keys are touched. */
const SparseSettings = Schema.Record(Schema.String, Schema.Unknown);
const decodeSettingsJson = Schema.decodeUnknownEffect(fromLenientJson(SparseSettings));
const encodeSettingsJson = Schema.encodeEffect(fromJsonStringPretty(SparseSettings));
const decodeThemeFileJsonExit = Schema.decodeUnknownExit(
Schema.fromJsonString(EnvironmentThemeFile),
);
const isEnvironmentThemeId = Schema.is(EnvironmentThemeId);
export class ThemeSettingsUnreadableError extends Schema.TaggedErrorClass<ThemeSettingsUnreadableError>()(
"ThemeSettingsUnreadableError",
{ settingsPath: Schema.String, cause: Schema.Defect() },
) {
override get message(): string {
return `Could not read ${this.settingsPath}. Fix its permissions, then run this again.`;
}
}
export class ThemeSettingsMalformedError extends Schema.TaggedErrorClass<ThemeSettingsMalformedError>()(
"ThemeSettingsMalformedError",
{ settingsPath: Schema.String, cause: Schema.Defect() },
) {
override get message(): string {
return `${this.settingsPath} is not a JSON object. Fix or remove it, then run this again.`;
}
}
export class ThemeSettingsBusyError extends Schema.TaggedErrorClass<ThemeSettingsBusyError>()(
"ThemeSettingsBusyError",
{ settingsPath: Schema.String, attempts: Schema.Number },
) {
override get message(): string {
return `${this.settingsPath} kept changing while writing (gave up after ${this.attempts} attempts). Try again.`;
}
}
export class ThemeSettingsWriteError extends Schema.TaggedErrorClass<ThemeSettingsWriteError>()(
"ThemeSettingsWriteError",
{ settingsPath: Schema.String, cause: Schema.Defect() },
) {
override get message(): string {
return `Could not write ${this.settingsPath}.`;
}
}
export class ThemeFileUnreadableError extends Schema.TaggedErrorClass<ThemeFileUnreadableError>()(
"ThemeFileUnreadableError",
// Optional: a path that never existed has no underlying failure to carry,
// and a manufactured string there would only look like a real one.
{ filePath: Schema.String, cause: Schema.optional(Schema.Defect()) },
) {
override get message(): string {
return `Could not read ${this.filePath}.`;
}
}
export class ThemeFileInvalidError extends Schema.TaggedErrorClass<ThemeFileInvalidError>()(
"ThemeFileInvalidError",
{ filePath: Schema.String, cause: Schema.Defect() },
) {
override get message(): string {
return `${this.filePath} is not a valid theme file. Use a theme exported from T3 Code, or a seeded file with name, appearance, canvas, and accent.`;
}
}
export class ThemeFileTooLargeError extends Schema.TaggedErrorClass<ThemeFileTooLargeError>()(
"ThemeFileTooLargeError",
{ filePath: Schema.String, limit: Schema.Number },
) {
override get message(): string {
return `${this.filePath} is larger than ${this.limit} bytes, which is more than a theme can publish.`;
}
}
export class ThemeFileColorlessError extends Schema.TaggedErrorClass<ThemeFileColorlessError>()(
"ThemeFileColorlessError",
{ filePath: Schema.String },
) {
override get message(): string {
return `${this.filePath} has no colors to publish.`;
}
}
export class ThemePublishError extends Schema.TaggedErrorClass<ThemePublishError>()(
"ThemePublishError",
{ themesDir: Schema.String, cause: Schema.Defect() },
) {
override get message(): string {
return `Could not publish the theme into ${this.themesDir}.`;
}
}
const INVALID_THEME_ID_REASON =
"is not a valid theme id (lowercase letters, digits, and hyphens; not an appearance keyword)";
export class ThemeIdUnknownError extends Schema.TaggedErrorClass<ThemeIdUnknownError>()(
"ThemeIdUnknownError",
{ themeId: Schema.String, known: Schema.Array(Schema.String) },
) {
override get message(): string {
return `No theme named "${this.themeId}". Available: ${this.known.join(", ")}. Publish one by passing a theme file instead of an id.`;
}
}
export class ThemeIdInvalidError extends Schema.TaggedErrorClass<ThemeIdInvalidError>()(
"ThemeIdInvalidError",
{ themeId: Schema.String },
) {
override get message(): string {
return `"${this.themeId}" ${INVALID_THEME_ID_REASON}.`;
}
}
/** A filename that cannot be a theme id, where --id is the way out. */
export class ThemeFileIdInvalidError extends Schema.TaggedErrorClass<ThemeFileIdInvalidError>()(
"ThemeFileIdInvalidError",
{ themeId: Schema.String, filePath: Schema.String },
) {
override get message(): string {
return `"${this.themeId}" ${INVALID_THEME_ID_REASON}. Pass one with --id.`;
}
}
export class ThemeTargetMissingError extends Schema.TaggedErrorClass<ThemeTargetMissingError>()(
"ThemeTargetMissingError",
{},
) {
override get message(): string {
return "Provide a theme id or file, or run `t3 theme clear` to remove the theme.";
}
}
const envT3Home = Config.string("T3CODE_HOME").pipe(Config.option);
const resolveThemePaths = Effect.fn(function* (explicitBaseDir: Option.Option<string>) {
// Same precedence as the rest of the CLI: --base-dir, then T3CODE_HOME,
// then the default home. A provisioning script exporting T3CODE_HOME must
// not have this one command silently target the default install.
const envHome = Option.filter(yield* envT3Home, (value) => value.trim().length > 0);
const configuredBaseDir = Option.orElse(explicitBaseDir, () => envHome);
const baseDir = yield* resolveBaseDir(Option.getOrUndefined(configuredBaseDir));
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {
baseDirIsExplicit: Option.isSome(configuredBaseDir),
});
return {
settingsPath: derivedPaths.settingsPath,
themesDir: derivedPaths.environmentThemesDir,
};
});
/**
* Reads the sparse settings object, treating only a genuinely absent file as
* empty. A permission or I/O error must propagate: reading it as "no settings"
* would have the caller write a fresh sparse file over settings it never saw.
*/
const readSettingsObject = Effect.fn(function* (settingsPath: string) {
const fs = yield* FileSystem.FileSystem;
const exists = yield* fs
.exists(settingsPath)
.pipe(Effect.mapError((cause) => new ThemeSettingsUnreadableError({ settingsPath, cause })));
if (!exists) return { raw: "", settings: {} };
const raw = yield* fs
.readFileString(settingsPath)
.pipe(Effect.mapError((cause) => new ThemeSettingsUnreadableError({ settingsPath, cause })));
if (raw.trim().length === 0) return { raw, settings: {} };
const settings = yield* decodeSettingsJson(raw).pipe(
Effect.mapError((cause) => new ThemeSettingsMalformedError({ settingsPath, cause })),
);
return { raw, settings };
});
/**
* A running server owns this file too, and its write path is an in-process
* semaphore that cannot serialize against another process. So the document is
* re-read immediately before the rename and the whole edit is retried when it
* moved underneath us, which is what turns "last writer wins" into "last
* writer merges", and an edit that keeps losing the race fails loudly rather
* than overwriting. A write landing inside the remaining rename window is
* still possible; the server's own watcher reconciles the file either way.
*/
const CONCURRENT_WRITE_ATTEMPTS = 5;
const writeDefaultTheme = Effect.fn(function* (input: {
readonly settingsPath: string;
readonly themeId: string;
}) {
const fs = yield* FileSystem.FileSystem;
for (let attempt = 1; ; attempt++) {
const { raw, settings } = yield* readSettingsObject(input.settingsPath);
const setAt = DateTime.formatIso(yield* DateTime.now);
const next =
input.themeId.length > 0
? // The timestamp is the set-generation: it lets clients apply a re-set
// of the same value they already applied once.
{ ...settings, defaultTheme: input.themeId, defaultThemeSetAt: setAt }
: // Clearing removes the keys rather than storing empty strings, so the
// file reads the same as one that never set a theme.
Object.fromEntries(
Object.entries(settings).filter(
([key]) => key !== "defaultTheme" && key !== "defaultThemeSetAt",
),
);
const contents = yield* encodeSettingsJson(next);
const current = yield* fs
.readFileString(input.settingsPath)
.pipe(Effect.orElseSucceed(() => ""));
if (current !== raw) {
// Falling through here would overwrite whatever landed in between, which
// is exactly the loss this loop exists to prevent.
if (attempt >= CONCURRENT_WRITE_ATTEMPTS) {
return yield* Effect.fail(
new ThemeSettingsBusyError({
settingsPath: input.settingsPath,
attempts: CONCURRENT_WRITE_ATTEMPTS,
}),
);
}
continue;
}
yield* writeFileStringAtomically({
filePath: input.settingsPath,
contents: `${contents}\n`,
}).pipe(
Effect.mapError(
(cause) => new ThemeSettingsWriteError({ settingsPath: input.settingsPath, cause }),
),
);
return;
}
});
/** Publishes a theme file into the environment's themes directory and returns
* the id it published under. */
const publishThemeFile = Effect.fn(function* (input: {
readonly themesDir: string;
readonly filePath: string;
readonly explicitId: Option.Option<string>;
}) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
// A preflight for error quality only: it tells a FIFO from an oversized
// file. Enforcement happens at the guarded read below.
const info = yield* fs
.stat(input.filePath)
.pipe(
Effect.mapError((cause) => new ThemeFileUnreadableError({ filePath: input.filePath, cause })),
);
if (info.type !== "File") {
return yield* Effect.fail(new ThemeFileUnreadableError({ filePath: input.filePath }));
}
if (Number(info.size) > MAX_THEME_FILE_BYTES) {
return yield* Effect.fail(
new ThemeFileTooLargeError({ filePath: input.filePath, limit: MAX_THEME_FILE_BYTES }),
);
}
// An explicit source path is the user's own input, and a symlink there is a
// normal way to point at a theme (desktop hooks symlink the current
// palette), so it is resolved before the guarded read. The read still goes
// through one opened handle whose type and size checks bind to the file
// actually read, so a FIFO cannot hang the command and an oversized target
// is refused.
const resolvedSource = yield* fs
.realPath(input.filePath)
.pipe(
Effect.mapError((cause) => new ThemeFileUnreadableError({ filePath: input.filePath, cause })),
);
const raw = readThemeFileGuarded(resolvedSource, MAX_THEME_FILE_BYTES);
if (raw === null) {
return yield* Effect.fail(new ThemeFileUnreadableError({ filePath: input.filePath }));
}
const decoded = decodeThemeFileJsonExit(raw);
if (decoded._tag === "Failure") {
return yield* Effect.fail(
new ThemeFileInvalidError({ filePath: input.filePath, cause: decoded.cause }),
);
}
if (!environmentThemeFileHasColors(decoded.value)) {
return yield* Effect.fail(new ThemeFileColorlessError({ filePath: input.filePath }));
}
const fileBasename = path.basename(input.filePath, ".json");
const themeId = Option.getOrElse(input.explicitId, () => fileBasename);
// The same rules the watcher applies when it reads the directory back, so a
// publish cannot report success for a file that will then be skipped.
if (!isEnvironmentThemeId(themeId) || UNPUBLISHABLE_THEME_IDS.has(themeId)) {
return yield* Effect.fail(new ThemeFileIdInvalidError({ themeId, filePath: input.filePath }));
}
const destinationPath = path.join(input.themesDir, `${themeId}.json`);
// Neither ends in `.json`, so the watcher never mistakes them for themes.
// Both names carry the pid, so concurrent publishers of one id cannot
// unlink or restore over each other's staging and rollback copies.
const backupPath = `${destinationPath}.rollback-${process.pid}`;
const stagingPath = `${destinationPath}.staging-${process.pid}`;
yield* fs
.makeDirectory(input.themesDir, { recursive: true })
.pipe(Effect.mapError((cause) => new ThemePublishError({ themesDir: input.themesDir, cause })));
const publishFailure = (cause: unknown) =>
new ThemePublishError({ themesDir: input.themesDir, cause });
// Staged in full before anything moves, so the commit below is two adjacent
// renames with no I/O between them. The staging entry is created O_EXCL
// after clearing any stale leftover, so a symlink or file already at that
// predictable name is never followed or written through. Written verbatim:
// appending so much as a newline could push a file at the size limit past
// it and have the watcher skip what was just accepted.
const stagedIno = yield* Effect.try({
try: () => {
try {
NodeFS.unlinkSync(stagingPath);
} catch {
// Nothing stale to clear.
}
const fd = NodeFS.openSync(
stagingPath,
NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | NodeFS.constants.O_EXCL,
0o644,
);
try {
NodeFS.writeFileSync(fd, raw);
// Rename preserves the inode, so this identifies our published file
// at the destination for as long as it is actually ours.
return NodeFS.fstatSync(fd).ino;
} finally {
NodeFS.closeSync(fd);
}
},
catch: publishFailure,
});
// Whatever occupies the destination -- a theme, a symlink, anything -- is
// moved aside in one atomic step rather than inspected and then replaced:
// there is no window between a check and the commit, and rollback restores
// that exact directory entry instead of a re-read of it. Only "nothing
// there" continues; any other rename failure aborts before the destination
// is touched.
const hadPrevious = yield* Effect.try({
try: () => {
try {
NodeFS.renameSync(destinationPath, backupPath);
return true;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
throw error;
}
},
catch: publishFailure,
});
const revert = Effect.sync(() => {
try {
NodeFS.unlinkSync(stagingPath);
} catch {
// Usually already renamed away; a stray staging file is watcher-inert.
}
try {
// The destination is touched only while it is empty or still holds
// the exact file this process put there; a concurrent publisher's
// newer file wins, and this process's obsolete copy is discarded.
const destinationIno = (() => {
try {
return NodeFS.lstatSync(destinationPath).ino;
} catch {
return null;
}
})();
if (hadPrevious) {
if (destinationIno === null || destinationIno === stagedIno) {
NodeFS.renameSync(backupPath, destinationPath);
} else {
NodeFS.unlinkSync(backupPath);
}
} else if (destinationIno === stagedIno) {
NodeFS.unlinkSync(destinationPath);
}
} catch {
// Best effort; the failure that triggered the revert still surfaces.
}
});
const cleanup = Effect.sync(() => {
try {
if (hadPrevious) NodeFS.unlinkSync(backupPath);
} catch {
// A stray backup is inert: it is not `.json`, so nothing serves it.
}
});
yield* Effect.try({
try: () => NodeFS.renameSync(stagingPath, destinationPath),
catch: publishFailure,
}).pipe(Effect.onError(() => revert));
return { themeId, revert, cleanup };
});
/**
* Ids a client can actually resolve: this build's built-ins plus what the
* machine publishes, read through the same function the watcher uses so a file
* it would skip can never be accepted here. The mobile default is absent on
* purpose -- web and desktop cannot resolve it and mobile does not follow this
* setting, so naming it would be the silent no-op this check exists to stop.
*/
const resolvableThemeIds = Effect.fn(function* (themesDir: string) {
const published = yield* readPublishedThemes(themesDir);
return [...BUILT_IN_THEME_IDS, ...published.map((theme) => theme.id)].toSorted();
});
const themeSetCommand = Command.make("set", {
baseDir: baseDirFlag,
id: Flag.string("id").pipe(
Flag.withDescription("Theme id to publish a file under, instead of its filename."),
Flag.optional,
),
theme: Argument.string("theme").pipe(
Argument.withDescription(
'A theme id (a built-in, or one this machine publishes — themes/nightfall.json is "nightfall"), or a path to a theme JSON file to publish and set in one step.',
),
),
}).pipe(
Command.withDescription("Set the environment's theme; connected clients switch to it."),
Command.withHandler((flags) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const target = yield* expandHomePath(flags.theme.trim());
if (target.length === 0) {
return yield* Effect.fail(new ThemeTargetMissingError());
}
const paths = yield* resolveThemePaths(flags.baseDir);
// An existing file publishes; anything path-shaped that does not exist
// is a mistake to surface, not an id to store; everything else must be
// a well-formed id, so a typo cannot be written as a theme no client
// will ever resolve.
// Path-shaped first, existence second. Deciding on existence alone would
// make `t3 theme set ocean` publish ./ocean whenever the cwd happens to
// hold a file by that name, instead of selecting the built-in.
const looksLikePath =
target.endsWith(".json") ||
target.includes("/") ||
target.includes("\\") ||
target.startsWith("~");
const targetIsFile =
looksLikePath && (yield* fs.exists(target).pipe(Effect.orElseSucceed(() => false)));
let themeId: string;
let revertPublish: Effect.Effect<void> = Effect.void;
let cleanupPublish: Effect.Effect<void> = Effect.void;
if (targetIsFile) {
// Settings are preflighted before publishing, so a settings file the
// set step cannot read or parse fails the command before it mutates
// the themes directory.
yield* readSettingsObject(paths.settingsPath);
const published = yield* publishThemeFile({
themesDir: paths.themesDir,
filePath: target,
explicitId: flags.id,
});
themeId = published.themeId;
revertPublish = published.revert;
cleanupPublish = published.cleanup;
} else if (looksLikePath) {
return yield* Effect.fail(new ThemeFileUnreadableError({ filePath: target }));
} else if (isEnvironmentThemeId(target)) {
const known = yield* resolvableThemeIds(paths.themesDir);
if (!known.includes(target)) {
return yield* Effect.fail(new ThemeIdUnknownError({ themeId: target, known }));
}
themeId = target;
} else {
return yield* Effect.fail(new ThemeIdInvalidError({ themeId: target }));
}
// set means set: if the default cannot be written, the publish that
// rode along with it is undone rather than left as a side effect of a
// command that reported failure.
yield* writeDefaultTheme({ settingsPath: paths.settingsPath, themeId }).pipe(
Effect.onError(() => revertPublish),
);
yield* cleanupPublish;
yield* Console.log(
targetIsFile
? `Published ${target} as "${themeId}" and set it as the environment theme.\n`
: `Environment theme set to "${themeId}" in ${paths.settingsPath}.\n`,
);
}),
),
);
const themeClearCommand = Command.make("clear", { baseDir: baseDirFlag }).pipe(
Command.withDescription("Remove the environment's theme; clients keep what they have."),
Command.withHandler((flags) =>
Effect.gen(function* () {
const paths = yield* resolveThemePaths(flags.baseDir);
yield* writeDefaultTheme({ settingsPath: paths.settingsPath, themeId: "" });
yield* Console.log(`Environment theme cleared in ${paths.settingsPath}.\n`);
}),
),
);
const themeShowCommand = Command.make("show", { baseDir: baseDirFlag }).pipe(
Command.withDescription("Show the environment's theme and its published themes."),
Command.withHandler((flags) =>
Effect.gen(function* () {
const paths = yield* resolveThemePaths(flags.baseDir);
const { settings } = yield* readSettingsObject(paths.settingsPath);
const defaultTheme =
typeof settings.defaultTheme === "string" && settings.defaultTheme.length > 0
? settings.defaultTheme
: null;
const published = (yield* readPublishedThemes(paths.themesDir))
.map((theme) => theme.id)
.toSorted();
yield* Console.log(
defaultTheme === null
? "Environment theme: not set.\n"
: `Environment theme: "${defaultTheme}".\n`,
);
yield* Console.log(
published.length === 0
? `Published themes: none (publish into ${paths.themesDir}).\n`
: `Published themes: ${published.join(", ")}.\n`,
);
}),
),
);
export const themeCommand = Command.make("theme").pipe(
Command.withDescription("Inspect and set environment-wide theme defaults."),
Command.withSubcommands([themeSetCommand, themeClearCommand, themeShowCommand]),
);
+3
View File
@@ -33,6 +33,8 @@ export interface ServerDerivedPaths {
readonly dbPath: string;
readonly keybindingsConfigPath: string;
readonly settingsPath: string;
/** Palettes this machine publishes for clients to follow, one file per theme. */
readonly environmentThemesDir: string;
readonly providerStatusCacheDir: string;
readonly worktreesDir: string;
readonly attachmentsDir: string;
@@ -119,6 +121,7 @@ export const deriveServerPaths = Effect.fn(function* (
dbPath,
keybindingsConfigPath: join(stateDir, "keybindings.json"),
settingsPath: join(stateDir, "settings.json"),
environmentThemesDir: join(stateDir, "themes"),
providerStatusCacheDir,
worktreesDir: join(baseDir, "worktrees"),
attachmentsDir,
@@ -155,6 +155,7 @@ export const make = Effect.gen(function* () {
pullRequests: true,
threadSettlement: true,
threadSnooze: true,
environmentThemes: true,
threadPinning: true,
threadPinReorder: true,
threadTitleRegeneration: true,
+272
View File
@@ -0,0 +1,272 @@
import { EnvironmentThemeFile } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
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 Path from "effect/Path";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as ServerConfig from "./config.ts";
import * as EnvironmentTheme from "./environmentTheme.ts";
const encodeThemeFile = Schema.encodeSync(Schema.fromJsonString(EnvironmentThemeFile));
const NIGHTFALL_THEME: EnvironmentThemeFile = {
name: "Nightfall",
appearance: "dark",
canvas: "#1a1b26",
accent: "#7aa2f7",
};
/** The standard exported form: a full palette, no seeds. */
const SHARED_THEME: EnvironmentThemeFile = {
version: 1,
name: "Shared Light",
appearance: "light",
colors: { canvas: "#eff1f5", accent: "#1e66f5" },
};
/** Seeds theme files before the service starts, as a real machine would. */
const withEnvironmentThemes = <A, E>(
seeds: Readonly<Record<string, string>>,
body: Effect.Effect<
A,
E,
| EnvironmentTheme.EnvironmentThemeService
| ServerConfig.ServerConfig
| FileSystem.FileSystem
| Path.Path
| Scope.Scope
>,
) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-environment-theme-" });
const themesDir = path.join(baseDir, "userdata", "themes");
yield* fs.makeDirectory(themesDir, { recursive: true });
for (const [filename, contents] of Object.entries(seeds)) {
yield* fs.writeFileString(path.join(themesDir, filename), contents);
}
return yield* body.pipe(
Effect.provide(
EnvironmentTheme.layer.pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
),
),
);
}).pipe(Effect.scoped);
const currentThemes = Effect.gen(function* () {
const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;
return yield* environmentTheme.current;
});
it.layer(NodeServices.layer)("environment theme", (it) => {
it.effect("publishes nothing when the machine has no theme files", () =>
withEnvironmentThemes(
{},
Effect.gen(function* () {
assert.deepEqual(yield* currentThemes, []);
}),
),
);
it.effect("publishes each file under its filename as the id", () =>
withEnvironmentThemes(
{
"nightfall.json": encodeThemeFile(NIGHTFALL_THEME),
"shared-light.json": encodeThemeFile(SHARED_THEME),
},
Effect.gen(function* () {
const themes = yield* currentThemes;
assert.deepEqual(
themes.map((theme) => theme.id),
["nightfall", "shared-light"],
);
assert.deepEqual(themes[0], { id: "nightfall", ...NIGHTFALL_THEME });
assert.deepEqual(themes[1], { id: "shared-light", ...SHARED_THEME });
}),
),
);
// Read from disk rather than from the watcher's last observation, so a
// client connecting after a missed filesystem event still sees the truth.
it.effect("follows the directory rather than the set read at start", () =>
withEnvironmentThemes(
{ "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
Effect.gen(function* () {
const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fs.writeFileString(
path.join(environmentThemesDir, "shared-light.json"),
encodeThemeFile(SHARED_THEME),
);
assert.equal((yield* currentThemes).length, 2);
yield* fs.remove(path.join(environmentThemesDir, "nightfall.json"));
assert.deepEqual(
(yield* currentThemes).map((theme) => theme.id),
["shared-light"],
);
}),
),
);
// One bad file must not take down the machine's other themes: a theme
// script that leaves a template placeholder unresolved, a half-written
// file, or a stray name are each that file's problem alone.
// The subscription is acquired before the current set is read, so nothing
// published while a client connects can fall between snapshot and stream.
it.effect("streams the current set first", () =>
withEnvironmentThemes(
{ "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
Effect.gen(function* () {
const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;
const first = yield* environmentTheme.streamChanges.pipe(Stream.runHead);
assert.deepEqual(Option.getOrNull(first), [{ id: "nightfall", ...NIGHTFALL_THEME }]);
}),
),
);
// Subscribing happens before the snapshot read, so a publish landing in
// between is queued. It must not replay after the newer snapshot and walk
// clients back onto colors the machine has already moved past.
it.effect("never replays a set older than the snapshot it started from", () =>
withEnvironmentThemes(
{ "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
Effect.gen(function* () {
const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;
const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
// Advance the directory twice without the watcher running, so the
// second read is strictly newer than anything already observed.
yield* fs.writeFileString(
path.join(environmentThemesDir, "shared-light.json"),
encodeThemeFile(SHARED_THEME),
);
const first = yield* environmentTheme.streamChanges.pipe(Stream.runHead);
assert.deepEqual(
Option.getOrNull(first)?.map((theme) => theme.id),
["nightfall", "shared-light"],
);
}),
),
);
it.effect("skips invalid files while keeping valid ones", () =>
withEnvironmentThemes(
{
"nightfall.json": encodeThemeFile(NIGHTFALL_THEME),
"unresolved.json":
'{ "name": "X", "appearance": "dark", "canvas": "{{ background }}", "accent": "#7aa2f7" }',
"malformed.json": "{ not json",
"no-colors.json": '{ "name": "Empty", "appearance": "dark" }',
"Bad Name.json": encodeThemeFile(SHARED_THEME),
"ocean.json": encodeThemeFile(SHARED_THEME),
"dark.json": encodeThemeFile(SHARED_THEME),
"notes.txt": "not a theme",
},
Effect.gen(function* () {
assert.deepEqual(
(yield* currentThemes).map((theme) => theme.id),
["nightfall"],
);
}),
),
);
// A symlinked themes directory stays usable, but a symlinked file inside it
// must not publish whatever it points at.
it.effect("ignores a symlinked theme file", () =>
withEnvironmentThemes(
{},
Effect.gen(function* () {
const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const outside = path.join(environmentThemesDir, "..", "outside.json");
yield* fs.writeFileString(outside, encodeThemeFile(NIGHTFALL_THEME));
yield* fs.symlink(outside, path.join(environmentThemesDir, "nightfall.json"));
assert.deepEqual(yield* currentThemes, []);
}),
),
);
// The aggregate size cap charges only accepted themes, so a pile of
// malformed files cannot spend the budget and hide a valid theme sorted
// after them.
it.effect("does not charge skipped files against the total size limit", () =>
withEnvironmentThemes(
{
...Object.fromEntries(
Array.from({ length: 7 }, (_, index) => [`junk-${index}.json`, "{".repeat(30_000)]),
),
"zz-valid.json": encodeThemeFile(NIGHTFALL_THEME),
},
Effect.gen(function* () {
assert.deepEqual(
(yield* currentThemes).map((theme) => theme.id),
["zz-valid"],
);
}),
),
);
});
// The feature's headline claim: rewrite a file and connected clients retint
// without a restart. Live clock and a real filesystem event, so this proves
// the watcher rather than a direct read. Kept outside the it.layer block above
// because only the top-level `it` exposes `live`.
describe("environment theme watching", () => {
it.live("streams a set for every change to the directory", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-theme-watch-" });
const themesDir = path.join(baseDir, "userdata", "themes");
yield* fs.makeDirectory(themesDir, { recursive: true });
yield* Effect.gen(function* () {
const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;
const seen = yield* Queue.unbounded<ReadonlyArray<{ readonly id: string }>>();
yield* Stream.runForEach(environmentTheme.streamChanges, (themes) =>
Queue.offer(seen, themes),
).pipe(Effect.forkScoped);
// Empty to start.
assert.deepEqual(yield* Queue.take(seen), []);
// Published atomically, the way a theme hook writes it.
const staging = path.join(baseDir, "staged.json");
yield* fs.writeFileString(staging, encodeThemeFile(NIGHTFALL_THEME));
yield* fs.rename(staging, path.join(themesDir, "nightfall.json"));
assert.deepEqual(
(yield* Queue.take(seen)).map((theme) => theme.id),
["nightfall"],
);
// Removed again, and the set empties without a restart.
yield* fs.remove(path.join(themesDir, "nightfall.json"));
assert.deepEqual(yield* Queue.take(seen), []);
}).pipe(
Effect.provide(
EnvironmentTheme.layer.pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
),
),
Effect.timeout("30 seconds"),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
+297
View File
@@ -0,0 +1,297 @@
// @effect-diagnostics nodeBuiltinImport:off - the guarded file read needs open
// flags (O_NOFOLLOW, O_NONBLOCK) the FileSystem service does not expose.
/**
* EnvironmentTheme - palettes this machine publishes for clients to follow.
*
* A desktop that retints its apps when the user switches system theme writes
* `<stateDir>/themes/<id>.json`; this service watches that directory and
* streams the published set to connected clients so a theme change lands
* without a restart. The filename is the theme id: it stays stable while the
* machine rewrites the colors underneath, so `defaultTheme` and a client\'s
* selection keep pointing at the same theme across recolors. Theming is
* cosmetic, so every failure here degrades to "not published" rather than
* propagating.
*
* @module EnvironmentTheme
*/
import * as NodeFS from "node:fs";
import {
EnvironmentTheme,
EnvironmentThemeFile,
EnvironmentThemeId,
environmentThemeFileHasColors,
} from "@t3tools/contracts";
import { UNPUBLISHABLE_THEME_IDS } from "@t3tools/shared/themePalettes";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as ServerConfig from "./config.ts";
const decodeEnvironmentThemeFileJsonExit = Schema.decodeUnknownExit(
Schema.fromJsonString(EnvironmentThemeFile),
);
const isEnvironmentThemeId = Schema.is(EnvironmentThemeId);
const THEME_FILE_SUFFIX = ".json";
/**
* Bounds on what a machine can publish. The directory is local, so this is not
* a trust boundary -- but an accidental dump of large files there would
* otherwise be read in full, streamed to every client, and repainted, so the
* cost of a mistake is capped rather than unbounded.
*/
const MAX_THEME_FILES = 32;
/** Exported so the publish path cannot accept a file the watcher will skip. */
export const MAX_THEME_FILE_BYTES = 32 * 1024;
/**
* The set travels whole in a websocket event to every subscriber, so the sum
* matters more than any single file. An exported theme runs a few KB, leaving
* this far above any real directory while keeping a mistake off the wire.
*/
const MAX_THEME_TOTAL_BYTES = 192 * 1024;
/** The published set with the sequence number it was observed at. */
interface PublishedThemes {
readonly seq: number;
readonly themes: ReadonlyArray<EnvironmentTheme>;
}
export class EnvironmentThemeService extends Context.Service<
EnvironmentThemeService,
{
/**
* The set published right now, read from disk rather than from the
* watcher\'s last observation: a client connecting must see what the
* machine actually publishes even if it missed a filesystem event.
*/
readonly current: Effect.Effect<ReadonlyArray<EnvironmentTheme>>;
/**
* The current set followed by every change, with repeats dropped. The
* subscription is acquired before the current set is read, so a publish
* landing while a client connects is delivered rather than lost.
*/
readonly streamChanges: Stream.Stream<ReadonlyArray<EnvironmentTheme>>;
}
>()("t3/environmentTheme/EnvironmentThemeService") {}
/**
* Reads a theme file through one opened handle, so every check binds to the
* file actually read rather than to a path that may have been swapped since:
* O_NOFOLLOW rejects a symlink outright (a symlinked themes directory stays
* usable, a symlinked file inside it does not), O_NONBLOCK keeps a FIFO from
* blocking the open, and the fstat type and size gate examines the open
* descriptor. Returns null for anything that is not a small regular file.
*/
export const readThemeFileGuarded = (filePath: string, maxBytes: number): string | null => {
let fd: number;
try {
fd = NodeFS.openSync(
filePath,
NodeFS.constants.O_RDONLY | NodeFS.constants.O_NOFOLLOW | NodeFS.constants.O_NONBLOCK,
);
} catch {
return null;
}
try {
const info = NodeFS.fstatSync(fd);
if (!info.isFile() || info.size > maxBytes) return null;
const contents = Buffer.alloc(info.size);
let offset = 0;
while (offset < contents.length) {
const read = NodeFS.readSync(fd, contents, offset, contents.length - offset, offset);
if (read <= 0) break;
offset += read;
}
return contents.subarray(0, offset).toString("utf8");
} catch {
return null;
} finally {
NodeFS.closeSync(fd);
}
};
/**
* Every theme the directory actually publishes. A file that is missing,
* unreadable, malformed, colorless, or misnamed is simply skipped; the rest of
* the set is unaffected. The one place that decides what "published" means, so
* a caller validating an id cannot disagree with the watcher serving it.
*/
export const readPublishedThemes = Effect.fn(function* (themesDir: string) {
const fs = yield* FileSystem.FileSystem;
const entries = yield* fs
.readDirectory(themesDir)
.pipe(Effect.orElseSucceed((): Array<string> => []));
const themes: Array<EnvironmentTheme> = [];
let examined = 0;
let totalBytes = 0;
for (const entry of entries.toSorted()) {
if (!entry.endsWith(THEME_FILE_SUFFIX)) continue;
const id = entry.slice(0, -THEME_FILE_SUFFIX.length);
// A reserved id is either shadowed by a built-in on the client or captures
// clients that never chose it, so it is not publishable.
if (!isEnvironmentThemeId(id) || UNPUBLISHABLE_THEME_IDS.has(id)) continue;
// Counts files examined, not themes accepted: capping the output would
// let a directory of malformed files be opened, read, and decoded in full
// on every refresh and every client connect.
examined += 1;
if (examined > MAX_THEME_FILES) {
yield* Effect.logWarning("ignoring environment theme files past the limit", {
path: themesDir,
limit: MAX_THEME_FILES,
});
break;
}
const filePath = `${themesDir}/${entry}`;
const raw = readThemeFileGuarded(filePath, MAX_THEME_FILE_BYTES);
if (raw === null) {
yield* Effect.logWarning("ignoring unusable environment theme file", {
path: filePath,
limit: MAX_THEME_FILE_BYTES,
});
continue;
}
if (raw.trim().length === 0) continue;
const decoded = decodeEnvironmentThemeFileJsonExit(raw);
if (decoded._tag === "Failure") {
yield* Effect.logWarning("ignoring invalid environment theme", {
path: filePath,
detail: Cause.pretty(decoded.cause),
});
continue;
}
const file = decoded.value;
if (!environmentThemeFileHasColors(file)) {
yield* Effect.logWarning("ignoring environment theme without colors", { path: filePath });
continue;
}
// Counted only once accepted: the cap bounds what travels to clients, so
// a skipped file must not eat the budget of valid themes sorted after it.
// Bytes, not string length -- the cap describes wire weight.
totalBytes += Buffer.byteLength(raw);
if (totalBytes > MAX_THEME_TOTAL_BYTES) {
yield* Effect.logWarning("ignoring environment themes past the total size limit", {
path: themesDir,
limit: MAX_THEME_TOTAL_BYTES,
});
break;
}
themes.push({ id, ...file });
}
return themes;
});
/**
* Reads the directory and folds it into the sequenced state, publishing only
* a genuine change. Every reader goes through here, so the snapshot a client
* connects on and the events it then receives come from one ordered source
* rather than from disk and the queue independently.
*/
const make = Effect.gen(function* () {
const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
const fs = yield* FileSystem.FileSystem;
/**
* Sliding with capacity 1: every update carries the complete set, so a
* subscriber that stops consuming holds at most the newest set rather than
* an unbounded backlog. Every observed set carries a sequence number, so a
* subscriber can drop queued events that predate the snapshot it started
* from. Without it a publish landing between subscribing and reading
* replays after the newer value and walks clients backwards onto stale
* colors.
*/
const changes = yield* PubSub.sliding<PublishedThemes>(1);
const published = yield* Ref.make<PublishedThemes>({ seq: 0, themes: [] });
/**
* Guards the whole read/compare/publish, not just the state update. The
* directory read is async, so two concurrent refreshes can finish out of
* order and a slower read of an older set would publish under a higher
* sequence -- which the subscriber filter, ordering publications rather than
* observations, could not then drop.
*/
const refreshSemaphore = yield* Semaphore.make(1);
const watcherScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
const refresh = refreshSemaphore.withPermits(1)(
Effect.gen(function* () {
const themes = yield* readPublishedThemes(environmentThemesDir).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
);
// Structural equality over the whole decoded value: a hand-rolled field
// list here silently drops republishes for any field it forgets.
const [changed, next] = yield* Ref.modify(
published,
(previous): readonly [readonly [boolean, PublishedThemes], PublishedThemes] => {
if (Equal.equals(previous.themes, themes)) return [[false, previous], previous];
const updated: PublishedThemes = { seq: previous.seq + 1, themes };
return [[true, updated], updated];
},
);
if (changed) yield* PubSub.publish(changes, next).pipe(Effect.asVoid);
return next;
}),
);
// The directory is created up front so the watcher has something to attach
// to before the first publisher writes into it.
yield* fs
.makeDirectory(environmentThemesDir, { recursive: true })
.pipe(Effect.ignoreCause({ log: true }));
// Debounced for the same reason settings watching is: a theme script emits
// several events per save and `fs.watch` can fire before the content is
// flushed. Every event triggers a full re-read, so no event needs filtering.
const watchEvents = fs.watch(environmentThemesDir).pipe(Stream.debounce(Duration.millis(100)));
// Seeds the dedupe so a watch event that reports no actual change (a touch,
// a rewrite with identical contents) does not retint every client.
yield* refresh;
yield* Stream.runForEach(watchEvents, () => refresh.pipe(Effect.ignoreCause({ log: true }))).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkIn(watcherScope),
Effect.asVoid,
);
return {
current: Effect.map(refresh, (state) => state.themes),
get streamChanges() {
return Stream.unwrap(
Effect.gen(function* () {
// Subscribe first so nothing published during the read is missed,
// then drop anything the snapshot already accounts for.
const subscription = yield* PubSub.subscribe(changes);
const snapshot = yield* refresh;
return Stream.concat(
Stream.make(snapshot.themes),
Stream.fromSubscription(subscription).pipe(
Stream.filter((update) => update.seq > snapshot.seq),
Stream.map((update) => update.themes),
),
);
}),
);
},
} satisfies EnvironmentThemeService["Service"];
});
export const layer = Layer.effect(EnvironmentThemeService, make);
+94 -7
View File
@@ -111,6 +111,7 @@ import {
} from "./ws.ts";
import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
import * as GitManager from "./git/GitManager.ts";
import * as EnvironmentTheme from "./environmentTheme.ts";
import * as Keybindings from "./keybindings.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
@@ -395,6 +396,7 @@ const buildAppUnderTest = (options?: {
config?: Partial<ServerConfig.ServerConfig["Service"]>;
layers?: {
keybindings?: Partial<Keybindings.Keybindings["Service"]>;
environmentTheme?: Partial<EnvironmentTheme.EnvironmentThemeService["Service"]>;
providerRegistry?: Partial<ProviderRegistry.ProviderRegistry["Service"]>;
providerService?: Partial<ProviderService.ProviderService["Service"]>;
serverSettings?: Partial<ServerSettings.ServerSettingsService["Service"]>;
@@ -630,14 +632,21 @@ const buildAppUnderTest = (options?: {
},
).pipe(
Layer.provide(
Layer.mock(Keybindings.Keybindings)({
loadConfigState: Effect.succeed({
keybindings: [],
issues: [],
Layer.mergeAll(
Layer.mock(Keybindings.Keybindings)({
loadConfigState: Effect.succeed({
keybindings: [],
issues: [],
}),
streamChanges: Stream.empty,
...options?.layers?.keybindings,
}),
streamChanges: Stream.empty,
...options?.layers?.keybindings,
}),
Layer.mock(EnvironmentTheme.EnvironmentThemeService)({
current: Effect.succeed([]),
streamChanges: Stream.empty,
...options?.layers?.environmentTheme,
}),
),
),
Layer.provide(
Layer.mergeAll(
@@ -4981,6 +4990,84 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
// An already-shipped client decodes this stream against an event union
// without environmentThemesUpdated, so an ungated emit would kill its whole
// config subscription. Opting in is the only way to receive them.
it.effect("subscribeServerConfig sends published themes to an opt-in subscriber", () =>
Effect.gen(function* () {
const themes = [
{
id: "nightfall",
name: "Nightfall",
appearance: "dark" as const,
canvas: "#1a1b26",
accent: "#7aa2f7",
},
] as const;
yield* buildAppUnderTest({
layers: {
environmentTheme: {
current: Effect.succeed(themes),
streamChanges: Stream.succeed(themes),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const events = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.subscribeServerConfig]({ environmentThemes: true }).pipe(
Stream.take(2),
Stream.runCollect,
),
),
);
const [first, second] = Array.from(events);
assert.equal(first?.type, "snapshot");
// Not in the snapshot as well, or every opt-in client receives the same
// array twice on every connect.
if (first?.type === "snapshot") assert.equal(first.config.environmentThemes, undefined);
assert.equal(second?.type, "environmentThemesUpdated");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("subscribeServerConfig withholds published themes from other subscribers", () =>
Effect.gen(function* () {
const themes = [
{
id: "nightfall",
name: "Nightfall",
appearance: "dark" as const,
canvas: "#1a1b26",
accent: "#7aa2f7",
},
] as const;
yield* buildAppUnderTest({
layers: {
environmentTheme: {
current: Effect.succeed(themes),
streamChanges: Stream.succeed(themes),
},
providerRegistry: { streamChanges: Stream.empty },
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const events = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.take(1), Stream.runCollect),
),
);
const first = Array.from(events)[0];
assert.equal(first?.type, "snapshot");
if (first?.type === "snapshot") assert.equal(first.config.environmentThemes, undefined);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("routes websocket rpc subscribeServerConfig emits provider status updates", () =>
Effect.gen(function* () {
const nextProviders = [
+4 -1
View File
@@ -53,6 +53,7 @@ import * as PreviewManager from "./preview/Manager.ts";
import * as PortScanner from "./preview/PortScanner.ts";
import * as ProcessRunner from "./processRunner.ts";
import * as GitManager from "./git/GitManager.ts";
import * as EnvironmentTheme from "./environmentTheme.ts";
import * as Keybindings from "./keybindings.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor.ts";
@@ -383,7 +384,9 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(ProviderRuntimeLayerLive),
Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive)),
Layer.provideMerge(PersistenceLayerLive),
Layer.provideMerge(Keybindings.layer),
// Both read a user-owned file out of the state directory and stream changes
// to clients; neither depends on the other.
Layer.provideMerge(Layer.mergeAll(Keybindings.layer, EnvironmentTheme.layer)),
Layer.provideMerge(ProviderRegistryLive),
// The instance registry is the new routing keystone — text generation,
// adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`
+24 -2
View File
@@ -73,6 +73,7 @@ import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
import * as ServerConfig from "./config.ts";
import * as EnvironmentTheme from "./environmentTheme.ts";
import * as Keybindings from "./keybindings.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import {
@@ -492,6 +493,7 @@ const makeWsRpcLayer = (
};
const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery;
const keybindings = yield* Keybindings.Keybindings;
const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
const remoteOpenTargets = yield* RemoteOpenTargets.RemoteOpenTargets;
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
@@ -2378,7 +2380,7 @@ const makeWsRpcLayer = (
),
{ "rpc.aggregate": "preview" },
),
[WS_METHODS.subscribeServerConfig]: (_input) =>
[WS_METHODS.subscribeServerConfig]: (input) =>
observeRpcStreamEffect(
WS_METHODS.subscribeServerConfig,
Effect.gen(function* () {
@@ -2400,6 +2402,23 @@ const makeWsRpcLayer = (
})),
Stream.debounce(Duration.millis(PROVIDER_STATUS_DEBOUNCE_MS)),
);
// The only source of published themes: the stream emits the
// current set before any change, so the snapshot carrying it too
// would just send every client the same array twice per connect.
// Gated on the subscriber's capability flag because an
// already-shipped client decodes this stream against the old
// event union and its whole config subscription dies on an
// unknown member.
const environmentThemeUpdates =
input.environmentThemes === true
? environmentTheme.streamChanges.pipe(
Stream.map((themes) => ({
version: 1 as const,
type: "environmentThemesUpdated" as const,
payload: { themes },
})),
)
: Stream.empty;
const settingsUpdates = serverSettings.streamChanges.pipe(
Stream.map((settings) => ServerSettings.redactServerSettingsForClient(settings)),
Stream.map((settings) => ({
@@ -2415,7 +2434,10 @@ const makeWsRpcLayer = (
const liveUpdates = Stream.merge(
keybindingsUpdates,
Stream.merge(providerStatuses, settingsUpdates),
Stream.merge(
providerStatuses,
Stream.merge(settingsUpdates, environmentThemeUpdates),
),
);
return Stream.concat(
@@ -10,9 +10,12 @@ import {
UploadIcon,
} from "lucide-react";
import { useCallback, useEffect, useState, type ReactElement } from "react";
import { useEnvironmentThemeDefinitions } from "../../hooks/useEnvironmentTheme";
import { readThemeHalvesRaw } from "../../hooks/useTheme";
import { cn } from "../../lib/utils";
import {
getThemeDefinition,
singleAppearanceOf,
getThemeModes,
removeCustomThemes,
serializeThemeFile,
@@ -523,6 +526,7 @@ export function ThemeLibrary({
setThemeHalf: (appearance: ThemeAppearance, themeId: string | null) => boolean;
}) {
const openThemeEditor = useThemeEditorStore((store) => store.openThemeEditor);
const environmentThemes = useEnvironmentThemeDefinitions();
const [themeRemovalTarget, setThemeRemovalTarget] = useState<{
theme: ThemeDefinition;
collectionThemes: ReadonlyArray<ThemeDefinition>;
@@ -581,13 +585,17 @@ export function ThemeLibrary({
const removedIds = new Set(themeIdsToRemove);
if (removedIds.size === 0) return;
const removesBase = removedIds.has(getThemeDefinition(theme)?.id ?? "");
// Captured raw before persistTheme clears the mix: a half naming a
// published theme whose set has not streamed in yet is pruned from the
// `themeHalves` prop, and rebuilding from that would drop it.
const storedHalves = readThemeHalvesRaw();
// Keep the themes installed if we cannot move the selection off one of
// them; the dialog stays open so the user can retry or cancel.
if (removesBase && !persistTheme(appearanceMode === "system" ? "system" : appearanceMode)) {
return;
}
for (const appearance of ["light", "dark"] as const) {
const half = themeHalves?.[appearance];
const half = storedHalves[appearance];
if (half === undefined) continue;
// Writing a base preference clears the whole mix, so halves that name
// a surviving theme are written back; removed halves fall back to base.
@@ -610,7 +618,6 @@ export function ThemeLibrary({
persistTheme,
setThemeHalf,
theme,
themeHalves,
themeIdsToRemove,
themeRemovalTarget,
]);
@@ -629,7 +636,10 @@ export function ThemeLibrary({
// the base would still own that appearance. Convert the base into an
// explicit half on the other side so this side falls back to default.
if (cardId === null && baseCardId !== null) {
const otherOwner = themeHalves?.[otherAppearance] ?? baseCardId;
// Read raw, before persistTheme clears the mix: the other half may
// name a published theme that has not streamed in yet, and falling
// back to the base would silently rewrite it.
const otherOwner = readThemeHalvesRaw()[otherAppearance] ?? baseCardId;
if (!persistTheme(appearanceMode === "system" ? "system" : appearanceMode)) return;
if (!setThemeHalf(otherAppearance, otherOwner)) {
// Best-effort rollback: restore the whole-theme selection rather
@@ -651,7 +661,6 @@ export function ThemeLibrary({
setTheme,
setThemeHalf,
theme,
themeHalves,
],
);
@@ -809,6 +818,37 @@ export function ThemeLibrary({
/>
);
})}
{environmentThemes
.filter(
// A saved theme with the same id wins resolution, so its card is
// the one that must show; rendering both would also collide keys.
(environmentTheme) => !customThemes.some((theme) => theme.id === environmentTheme.id),
)
.map((environmentTheme) => (
// No edit or remove: the environment republishes these palettes on
// every change, so anything saved here would be overwritten.
// Duplicating is the way to keep a copy.
<ThemeLibraryCard
activeModes={pickedModesFor(environmentTheme.id)}
isActive={false}
key={environmentTheme.id}
onDuplicate={() =>
openThemeEditor({
editingThemeId: null,
seedThemeId: environmentTheme.id,
seedName: `${environmentTheme.label} copy`,
initialAppearance,
})
}
onUse={() => {
const half = singleAppearanceOf(environmentTheme);
if (half === null) persistTheme(environmentTheme.id);
else assignHalf(half, environmentTheme.id);
}}
onUseMode={handlePairPick(environmentTheme.id)}
theme={getThemeCardDefinition(environmentTheme)}
/>
))}
{customThemeCollections.map(([collectionId, themes]) => (
<CustomThemeCollectionCard
activeModesFor={pickedModesFor}
@@ -0,0 +1,58 @@
import { describe, expect, it } from "vite-plus/test";
import { defaultThemeGeneration, defaultThemeToApply } from "./useDefaultTheme";
const BASE = {
environmentId: "env-1",
defaultTheme: "nightfall",
defaultThemeSetAt: "2026-08-28T00:00:00.000Z",
appliedGeneration: null,
resolves: true,
} as const;
describe("default theme adoption", () => {
it("applies a set this client has not seen", () => {
expect(defaultThemeToApply(BASE)).toBe(
defaultThemeGeneration(BASE.defaultTheme, BASE.defaultThemeSetAt),
);
});
it("does not replay a generation it already applied", () => {
const generation = defaultThemeGeneration(BASE.defaultTheme, BASE.defaultThemeSetAt);
expect(defaultThemeToApply({ ...BASE, appliedGeneration: generation })).toBe(null);
});
// `t3 theme set` of a theme this client already wears must still act, which
// is why the generation carries the set time and not just the value.
it("applies the same theme again when the environment re-sets it", () => {
const applied = defaultThemeGeneration(BASE.defaultTheme, "2026-08-28T00:00:00.000Z");
const next = defaultThemeToApply({
...BASE,
defaultThemeSetAt: "2026-08-29T00:00:00.000Z",
appliedGeneration: applied,
});
expect(next).not.toBe(null);
expect(next).not.toBe(applied);
});
// Environments provisioned before the timestamp existed.
it("falls back to once-per-value without a set time", () => {
const generation = defaultThemeGeneration("nightfall", "");
expect(defaultThemeToApply({ ...BASE, defaultThemeSetAt: "", appliedGeneration: null })).toBe(
generation,
);
expect(
defaultThemeToApply({ ...BASE, defaultThemeSetAt: "", appliedGeneration: generation }),
).toBe(null);
});
// The setting and the palette it names arrive independently.
it("waits for a theme that has not arrived yet", () => {
expect(defaultThemeToApply({ ...BASE, resolves: false })).toBe(null);
});
it("leaves a client alone with no environment or no theme set", () => {
expect(defaultThemeToApply({ ...BASE, environmentId: null })).toBe(null);
expect(defaultThemeToApply({ ...BASE, defaultTheme: "" })).toBe(null);
});
});
+115
View File
@@ -0,0 +1,115 @@
import { useAtomValue } from "@effect/atom-react";
import { useEffect } from "react";
import { primaryEnvironmentIdAtom } from "../state/primaryEnvironment";
import { primaryServerSettingsAtom } from "../state/server";
import { getThemeDefinition, singleAppearanceOf } from "../themePalette";
import { useEnvironmentThemeDefinitions } from "./useEnvironmentTheme";
import { useTheme } from "./useTheme";
/**
* Scoped per environment: each machine's `t3 theme set` is its own act, so
* hopping between primary environments neither replays one environment's
* theme over the user's pick nor swallows another's.
*/
const APPLIED_DEFAULT_THEME_STORAGE_PREFIX = "t3code:default-theme-applied:v2:";
/**
* One generation per set: keyed on when the theme was set, not just its
* value, so re-asserting the same theme still acts. Environments provisioned
* by builds without the timestamp degrade to applying once per value.
*/
export function defaultThemeGeneration(theme: string, setAt: string): string {
return setAt.length > 0 ? `${theme}@${setAt}` : theme;
}
/**
* The generation to apply, or null to leave this client alone. Pure so the
* rule -- apply once per set, never replay one already applied, wait for a
* theme that has not arrived yet -- can be tested without a renderer.
*/
export function defaultThemeToApply(input: {
readonly environmentId: string | null;
readonly defaultTheme: string;
readonly defaultThemeSetAt: string;
readonly appliedGeneration: string | null;
readonly resolves: boolean;
}): string | null {
if (input.environmentId === null || input.defaultTheme.length === 0) return null;
const generation = defaultThemeGeneration(input.defaultTheme, input.defaultThemeSetAt);
if (input.appliedGeneration === generation) return null;
// The setting and the palette it names arrive independently, so an id that
// does not resolve yet is not a failure -- the effect runs again when the
// published set changes.
if (!input.resolves) return null;
return generation;
}
function readAppliedGeneration(storageKey: string): string | null {
if (typeof window === "undefined") return null;
try {
return window.localStorage.getItem(storageKey);
} catch {
return null;
}
}
function writeAppliedGeneration(storageKey: string, generation: string): void {
try {
window.localStorage.setItem(storageKey, generation);
} catch {
// Unrecordable means the next config event applies again; harmless.
}
}
/**
* Applies the environment's theme (`t3 theme set <id>`). Each set switches
* this client once — live when connected, on the next connect otherwise —
* and then steps aside: a theme the user picks in Settings afterwards wins
* until the environment's theme is set again. The environment's own published
* themes are valid targets, which is why this waits for an id that does not
* resolve yet — the setting and the palette it names arrive independently.
*/
export function useDefaultThemeAdoption(): void {
const environmentId = useAtomValue(primaryEnvironmentIdAtom);
const settings = useAtomValue(primaryServerSettingsAtom);
const { defaultTheme, defaultThemeSetAt } = settings;
const { setTheme, setAppearanceMode } = useTheme();
// Re-runs adoption when a late-arriving published theme makes the
// requested id resolvable.
const environmentThemes = useEnvironmentThemeDefinitions();
useEffect(() => {
if (typeof window === "undefined" || environmentId === null) return;
const storageKey = `${APPLIED_DEFAULT_THEME_STORAGE_PREFIX}${environmentId}`;
const definition = getThemeDefinition(defaultTheme);
const generation = defaultThemeToApply({
environmentId,
defaultTheme,
defaultThemeSetAt,
appliedGeneration: readAppliedGeneration(storageKey),
resolves: definition !== null,
});
if (generation === null || definition === null) return;
// Deliberately not the card's rule. Clicking a card is a user choosing one
// half of their own mix; a set theme is the environment saying what this
// client opens on, so it takes the base preference and, for a
// single-appearance theme, the matching mode -- otherwise a dark-only
// theme on a light client is recorded as applied while nothing changes.
if (!setTheme(defaultTheme)) return;
const half = singleAppearanceOf(definition);
// Recorded only once both land: marking the generation applied while the
// appearance switch failed would leave a dark-only theme rendering its
// light half with no retry.
if (half !== null && !setAppearanceMode(half)) return;
writeAppliedGeneration(storageKey, generation);
}, [
environmentId,
defaultTheme,
defaultThemeSetAt,
environmentThemes,
setTheme,
setAppearanceMode,
]);
}
@@ -0,0 +1,212 @@
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { environmentThemeDefinition, publishedThemeDefinitions } from "./useEnvironmentTheme";
import {
getDefaultThemeColors,
getThemeDefinition,
installCustomTheme,
invalidateCustomThemes,
setEnvironmentThemes,
THEME_COLOR_ROLES,
} from "../themePalette";
const NIGHTFALL_THEME = {
id: "nightfall",
name: "Nightfall",
appearance: "dark",
canvas: "#1a1b26",
accent: "#7aa2f7",
} as const;
afterEach(() => {
setEnvironmentThemes([]);
});
describe("environment themes", () => {
it("generates every role from the two published seeds", () => {
const theme = environmentThemeDefinition(NIGHTFALL_THEME);
expect(theme.id).toBe("nightfall");
expect(theme.label).toBe("Nightfall");
expect(theme.appearance).toBe("dark");
for (const role of THEME_COLOR_ROLES) {
expect(theme.colors[role], `missing ${role}`).toBeTruthy();
}
});
it("layers published roles over the generated palette", () => {
const generated = environmentThemeDefinition(NIGHTFALL_THEME);
const overridden = environmentThemeDefinition({
...NIGHTFALL_THEME,
colors: { terminalSelection: "#292e42", error: "#f7768e" },
});
expect(overridden.colors.terminalSelection).not.toBe(generated.colors.terminalSelection);
expect(overridden.colors.error).not.toBe(generated.colors.error);
// Roles the machine did not publish keep the generated value.
expect(overridden.colors.sidebar).toBe(generated.colors.sidebar);
});
// The standard exported theme file — the Download button's output — is a
// valid published theme, so any shared theme can be dropped into the
// machine's themes directory as-is.
it("renders an exported theme file on the stock defaults", () => {
const theme = environmentThemeDefinition({
id: "shared-light",
version: 1,
name: "Shared Light",
appearance: "light",
colors: { canvas: "oklch(0.95 0.01 250)", accent: "#1e66f5" },
variants: { dark: { canvas: "#1a1b26" } },
});
expect(theme.label).toBe("Shared Light");
expect(theme.colors.accent).toBeTruthy();
expect(theme.variants?.dark?.canvas).toBeTruthy();
for (const role of THEME_COLOR_ROLES) {
expect(theme.colors[role], `missing ${role}`).toBeTruthy();
expect(theme.variants?.dark?.[role], `missing dark ${role}`).toBeTruthy();
}
});
// The generator follows the seed canvas's luminance, so a dark theme's
// seeds must never produce its light variant: the variant builds on that
// appearance's stock defaults instead.
it("builds a seeded theme's variant on the variant appearance's defaults", () => {
const theme = environmentThemeDefinition({
...NIGHTFALL_THEME,
variants: { light: { canvas: "#eff1f5" } },
});
const lightDefaults = getDefaultThemeColors("light");
expect(theme.variants?.light?.text).toBe(lightDefaults.text);
expect(theme.variants?.light?.canvas).not.toBe(theme.colors.canvas);
});
// A published `t3-iris.json` would show its palette on a card that applies
// the built-in, and a published `dark.json` would capture everyone whose
// stored preference is the stock "dark". Reserved ids never become cards.
it("drops published themes with reserved ids", () => {
const definitions = publishedThemeDefinitions([
NIGHTFALL_THEME,
{ ...NIGHTFALL_THEME, id: "t3-iris", name: "Impostor Iris" },
{ ...NIGHTFALL_THEME, id: "ocean", name: "Impostor Ocean" },
{ ...NIGHTFALL_THEME, id: "dark", name: "Impostor Dark" },
]);
expect(definitions.map((definition) => definition.id)).toEqual(["nightfall"]);
});
it("drops published palettes with no usable colors", () => {
const theme = { id: "invalid", name: "Invalid", appearance: "dark" } as const;
const definitions = publishedThemeDefinitions([
{ ...theme, colors: { canvas: "not-a-color" } },
{ ...theme, id: "unknown-roles", colors: { futureRole: "#ffffff" } },
{
...theme,
id: "ignored-variant",
colors: { canvas: "not-a-color" },
variants: { dark: { canvas: "#112233" } },
},
]);
expect(definitions).toEqual([]);
});
it("keeps seeds, partial palettes, and usable alternate appearances", () => {
const theme = { name: "Shared", appearance: "dark" } as const;
const definitions = publishedThemeDefinitions([
NIGHTFALL_THEME,
{
...theme,
id: "partial",
colors: { canvas: "not-a-color", text: "#ffffff", futureRole: "#ffffff" },
},
{
...theme,
id: "light-variant",
colors: { canvas: "not-a-color" },
variants: { light: { canvas: "#eff1f5" } },
},
]);
expect(definitions.map((definition) => definition.id)).toEqual([
"nightfall",
"partial",
"light-variant",
]);
});
// A machine may publish roles a newer client added; an older one has to
// ignore them rather than render a broken palette.
it("ignores published roles this build does not render", () => {
const theme = environmentThemeDefinition({
...NIGHTFALL_THEME,
colors: { notARole: "#ff0000", text: "#ffffff" },
});
expect(theme.colors).not.toHaveProperty("notARole");
for (const role of THEME_COLOR_ROLES) {
expect(theme.colors[role], `missing ${role}`).toBeTruthy();
}
});
// ThemeEditorPanel opens Duplicate in the guided editor for managed themes,
// and the guided editor regenerates from canvas and accent -- which would
// discard any role the machine tuned by hand.
it("marks only the pure seeded form as managed", () => {
expect(environmentThemeDefinition(NIGHTFALL_THEME).managed).toBe(true);
expect(
environmentThemeDefinition({ ...NIGHTFALL_THEME, colors: { error: "#f7768e" } }).managed,
).toBeUndefined();
expect(
environmentThemeDefinition({
id: "shared-light",
version: 1,
name: "Shared Light",
appearance: "light",
colors: { canvas: "#eff1f5", accent: "#1e66f5" },
}).managed,
).toBeUndefined();
});
it("resolves published ids only while the machine publishes them", () => {
expect(getThemeDefinition("nightfall")).toBe(null);
setEnvironmentThemes([environmentThemeDefinition(NIGHTFALL_THEME)]);
expect(getThemeDefinition("nightfall")?.label).toBe("Nightfall");
// The palettes are never saved, so they have to disappear with the
// machine that published them rather than linger as stale entries.
setEnvironmentThemes([]);
expect(getThemeDefinition("nightfall")).toBe(null);
});
// Published ids share one namespace with the user's saved themes, and the
// user was here first: their theme keeps working even if the machine later
// publishes under the same id.
it("lets a theme the user saved win an id collision", () => {
const store = new Map<string, string>();
vi.stubGlobal("window", {
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
localStorage: {
getItem: (key: string) => store.get(key) ?? null,
setItem: (key: string, value: string) => store.set(key, value),
removeItem: (key: string) => store.delete(key),
},
});
invalidateCustomThemes();
try {
const environment = environmentThemeDefinition(NIGHTFALL_THEME);
setEnvironmentThemes([environment]);
installCustomTheme({ ...environment, label: "My Nightfall" });
expect(getThemeDefinition("nightfall")?.label).toBe("My Nightfall");
} finally {
vi.unstubAllGlobals();
invalidateCustomThemes();
}
expect(getThemeDefinition("nightfall")?.label).toBe("Nightfall");
});
});
+125
View File
@@ -0,0 +1,125 @@
import type { EnvironmentTheme } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import * as Equal from "effect/Equal";
import { useEffect, useRef, useSyncExternalStore } from "react";
import { primaryServerEnvironmentThemesAtom } from "../state/server";
import {
createVividThemeColors,
getDefaultThemeColors,
getEnvironmentThemes,
isReservedThemeId,
lenientThemeColorOverrides,
setEnvironmentThemes,
subscribeToCustomThemes,
type ThemeAppearance,
type ThemeColors,
type ThemeDefinition,
} from "../themePalette";
import { useTheme } from "./useTheme";
function publishedThemeColors(
theme: EnvironmentTheme,
appearance: ThemeAppearance,
colors: Readonly<Record<string, string>> | undefined,
): ThemeColors {
// Seeds generate the base with the guided theme editor's generator, so a
// desktop theme arrives as a coherent T3 Code palette rather than a foreign
// one — but only for the appearance they describe. A variant builds on that
// appearance's stock defaults: the generator follows the seed canvas's
// luminance, so dark seeds would give a light variant unreadable colors.
const base =
appearance === theme.appearance && theme.canvas !== undefined && theme.accent !== undefined
? createVividThemeColors(appearance, theme.canvas, theme.accent)
: getDefaultThemeColors(appearance);
return { ...base, ...lenientThemeColorOverrides(colors ?? {}) };
}
/**
* A published theme as the theme library renders it. Both published forms are
* accepted: the seeded short form a desktop generates, and the standard
* exported theme file the Download button produces — so any theme someone
* shared can be dropped into the machine's themes directory as-is.
*/
export function environmentThemeDefinition(theme: EnvironmentTheme): ThemeDefinition {
const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};
for (const [variantAppearance, variantColors] of Object.entries(theme.variants ?? {})) {
if (variantAppearance === theme.appearance) continue;
variants[variantAppearance as ThemeAppearance] = publishedThemeColors(
theme,
variantAppearance as ThemeAppearance,
variantColors,
);
}
return {
id: theme.id,
label: theme.name,
appearance: theme.appearance,
colors: publishedThemeColors(theme, theme.appearance, theme.colors),
...(Object.keys(variants).length > 0 ? { variants } : {}),
// Only the pure seeded form is guided-generator output. An exported file,
// or seeds carrying explicit role overrides, must open Duplicate in the
// advanced editor -- the guided one regenerates from canvas and accent and
// would discard whatever the machine hand-tuned.
...(theme.canvas !== undefined &&
theme.accent !== undefined &&
theme.colors === undefined &&
theme.variants === undefined
? { managed: true }
: {}),
};
}
/**
* Published palettes this client can render. Reserved ids are dropped here rather
* than rendered: a published `t3-iris.json` would show this palette on its
* card while "Use" resolved the built-in, and a published `dark.json` would
* capture everyone whose stored preference is the stock `"dark"`.
*/
export function publishedThemeDefinitions(
themes: ReadonlyArray<EnvironmentTheme>,
): ReadonlyArray<ThemeDefinition> {
return themes
.filter((theme) => {
if (isReservedThemeId(theme.id)) return false;
if (theme.canvas !== undefined && theme.accent !== undefined) return true;
const otherAppearance = theme.appearance === "dark" ? "light" : "dark";
return [theme.colors, theme.variants?.[otherAppearance]].some(
(colors) =>
colors !== undefined && Object.keys(lenientThemeColorOverrides(colors)).length > 0,
);
})
.map(environmentThemeDefinition);
}
/** The published themes as library entries; empty while none are published. */
export function useEnvironmentThemeDefinitions(): ReadonlyArray<ThemeDefinition> {
return useSyncExternalStore(subscribeToCustomThemes, getEnvironmentThemes, () => []);
}
/**
* Keeps the machine's published themes in the theme library for as long as
* the primary environment publishes them. A client with a published theme
* selected retints the moment the machine rewrites it; everyone else just
* gains cards in the theme library.
*/
export function useEnvironmentThemeSync(): void {
const published = useAtomValue(primaryServerEnvironmentThemesAtom);
const { refreshTheme } = useTheme();
const lastPublished = useRef<ReadonlyArray<EnvironmentTheme> | null>(null);
useEffect(() => {
// Every reconnect snapshot delivers a fresh but usually identical array;
// regenerating palettes and repainting the document for it is exactly the
// wasted-frame class this codebase audits for.
if (lastPublished.current !== null && Equal.equals(lastPublished.current, published)) return;
lastPublished.current = published;
// The palette is painted from a snapshot taken when the theme last
// changed, so new colors only land if the active theme is re-applied.
if (setEnvironmentThemes(publishedThemeDefinitions(published))) {
refreshTheme({ preservePreview: true });
}
}, [published, refreshTheme]);
}
@@ -0,0 +1,181 @@
import type { EnvironmentTheme } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
const NIGHTFALL_THEME = {
id: "nightfall",
name: "Nightfall",
appearance: "dark",
canvas: "#1a1b26",
accent: "#7aa2f7",
} as const satisfies EnvironmentTheme;
const LIGHT_THEME = {
...NIGHTFALL_THEME,
appearance: "light",
canvas: "#eff1f5",
} as const satisfies EnvironmentTheme;
async function setupThemeSync(mode: "dark" | "system" = "dark") {
const storage = new Map<string, string>([["t3code:theme", NIGHTFALL_THEME.id]]);
const styles = new Map<string, string>();
const classes = new Set<string>();
const root = {
dataset: {} as Record<string, string>,
style: {
setProperty: (name: string, value: string) => styles.set(name, value),
removeProperty: (name: string) => styles.delete(name),
},
classList: {
add: (name: string) => classes.add(name),
remove: (name: string) => classes.delete(name),
toggle: (name: string, enabled: boolean) =>
enabled ? classes.add(name) : classes.delete(name),
contains: (name: string) => classes.has(name),
},
};
vi.stubGlobal("document", { documentElement: root });
vi.stubGlobal("window", {
localStorage: {
getItem: (key: string) => storage.get(key) ?? null,
setItem: (key: string, value: string) => storage.set(key, value),
removeItem: (key: string) => storage.delete(key),
},
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
matchMedia: () => ({
matches: true,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
}),
});
vi.stubGlobal("requestAnimationFrame", vi.fn());
let published: ReadonlyArray<EnvironmentTheme> = [NIGHTFALL_THEME];
let readSnapshot: (() => unknown) | undefined;
const effects: Array<() => void> = [];
const lastPublished: { current: ReadonlyArray<EnvironmentTheme> | null } = { current: null };
vi.doMock("react", () => ({
useCallback: <A>(callback: A) => callback,
useEffect: (effect: () => void) => effects.push(effect),
useRef: () => lastPublished,
useSyncExternalStore: (_subscribe: unknown, getSnapshot: () => unknown) => {
readSnapshot = getSnapshot;
return getSnapshot();
},
}));
vi.doMock("@effect/atom-react", () => ({ useAtomValue: () => published }));
vi.doMock("../state/server", () => ({ primaryServerEnvironmentThemesAtom: {} }));
const palette = await import("../themePalette");
storage.set(palette.THEME_APPEARANCE_MODE_STORAGE_KEY, mode);
const { useTheme } = await import("./useTheme");
const { useEnvironmentThemeSync } = await import("./useEnvironmentTheme");
const flushEffects = () => {
for (const effect of effects.splice(0)) effect();
};
const publish = (themes: ReadonlyArray<EnvironmentTheme>) => {
published = themes;
useEnvironmentThemeSync();
flushEffects();
// A changed store snapshot also runs the consumer's passive theme effect.
const theme = useTheme();
flushEffects();
return theme;
};
publish(published);
return { publish, palette, root, styles, readSnapshot: () => readSnapshot?.() };
}
afterEach(() => {
vi.doUnmock("react");
vi.doUnmock("@effect/atom-react");
vi.doUnmock("../state/server");
vi.resetModules();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
describe("published theme refresh", () => {
it.each(["dark", "system"] as const)(
"updates the React snapshot when appearance changes in %s mode",
async (mode) => {
const { publish, root, readSnapshot } = await setupThemeSync(mode);
const darkSnapshot = readSnapshot();
expect(publish([LIGHT_THEME]).resolvedTheme).toBe("light");
expect(root.classList.contains("dark")).toBe(false);
const lightSnapshot = readSnapshot();
expect(lightSnapshot).not.toBe(darkSnapshot);
expect(publish([NIGHTFALL_THEME]).resolvedTheme).toBe("dark");
expect(root.classList.contains("dark")).toBe(true);
expect(readSnapshot()).not.toBe(lightSnapshot);
},
);
it("keeps the React snapshot stable for color-only changes", async () => {
const { publish, palette, styles, readSnapshot } = await setupThemeSync();
const before = readSnapshot();
const accentVariable = palette.getThemeColorVariable("accent");
const previousAccent = styles.get(accentVariable);
publish([{ ...NIGHTFALL_THEME, accent: "#ff0000" }]);
expect(styles.get(accentVariable)).not.toBe(previousAccent);
expect(readSnapshot()).toBe(before);
});
it("keeps a draft visible while updating the stored selection underneath it", async () => {
const { publish, palette, root, styles } = await setupThemeSync();
const draft = { ...palette.getDefaultThemeColors("light"), canvas: "#234567" };
palette.applyThemeColorPreview(draft, "light");
const canvasVariable = palette.getThemeColorVariable("canvas");
const expectPreview = () => {
expect(root.dataset.themeId).toBe(palette.THEME_PREVIEW_ID);
expect(styles.get(canvasVariable)).toBe(draft.canvas);
expect(root.classList.contains("dark")).toBe(false);
};
expect(publish([LIGHT_THEME]).resolvedTheme).toBe("light");
expectPreview();
publish([LIGHT_THEME, { ...NIGHTFALL_THEME, id: "unused-theme" }]);
expectPreview();
expect(publish([]).theme).toBe("system");
expectPreview();
const current = publish([{ ...NIGHTFALL_THEME, canvas: "#112233" }]);
expect(current.theme).toBe(NIGHTFALL_THEME.id);
expect(current.resolvedTheme).toBe("dark");
expectPreview();
current.refreshTheme();
expect(root.dataset.themeId).toBe(NIGHTFALL_THEME.id);
expect(styles.get(canvasVariable)).toBe(
palette.getThemeDefinition(NIGHTFALL_THEME.id)?.colors.canvas,
);
expect(root.classList.contains("dark")).toBe(true);
expect(palette.getThemePreviewSidebarArtwork()).toBeNull();
});
it("keeps a draft visible when default adoption changes the theme and appearance", async () => {
const { publish, palette, root, readSnapshot } = await setupThemeSync();
const current = publish([NIGHTFALL_THEME]);
palette.applyThemeColorPreview(palette.getDefaultThemeColors("dark"), "dark");
expect(current.setTheme("ocean")).toBe(true);
expect(current.setAppearanceMode("light")).toBe(true);
expect(readSnapshot()).toMatchObject({
theme: "ocean",
appearanceMode: "light",
resolvedTheme: "light",
});
expect(root.dataset.themeId).toBe(palette.THEME_PREVIEW_ID);
expect(root.classList.contains("dark")).toBe(true);
current.refreshTheme();
expect(root.dataset.themeId).toBe("ocean");
expect(root.classList.contains("dark")).toBe(false);
expect(palette.getThemePreviewSidebarArtwork()).toBeNull();
});
});
+65 -24
View File
@@ -13,6 +13,7 @@ import {
resolveDesktopTheme,
resolveThemeAppearance,
resolveThemeHalf,
THEME_PREVIEW_ID,
THEME_APPEARANCE_MODE_STORAGE_KEY,
THEME_FOLLOW_SYSTEM_STORAGE_KEY,
THEME_HALVES_STORAGE_KEY,
@@ -25,6 +26,7 @@ import {
type Theme = ThemePreference;
type ThemeSnapshot = {
theme: Theme;
resolvedTheme: ThemeAppearance;
systemDark: boolean;
followSystem: boolean;
appearanceMode: ThemePreferenceMode;
@@ -37,6 +39,7 @@ const STORAGE_KEY = "t3code:theme";
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {
theme: "system",
resolvedTheme: "light",
systemDark: false,
followSystem: true,
appearanceMode: "system",
@@ -49,6 +52,17 @@ export function readThemeHalves(): ThemeHalves | null {
return readStoredThemeHalves();
}
/**
* The stored mix as written, without resolvability pruning. Flows that
* rebuild the whole mix must capture this before a `setTheme` clears it: a
* published id resolves only once its set has streamed in, and treating "not
* resolvable yet" as "absent" silently rewrites that half.
*/
export function readThemeHalvesRaw(): { light?: string; dark?: string } {
if (typeof window === "undefined") return {};
return readStoredThemeHalvesRaw();
}
function readStoredThemeHalves(): ThemeHalves | null {
if (typeof window === "undefined") return null;
try {
@@ -58,6 +72,29 @@ function readStoredThemeHalves(): ThemeHalves | null {
}
}
/**
* The stored mix as written, without resolvability pruning. An environment
* published id resolves only once its set has streamed in, so a write that
* merged over the pruned parse would silently erase that half whenever the
* other one changed before the set arrived.
*/
function readStoredThemeHalvesRaw(): { light?: string; dark?: string } {
try {
const value: unknown = JSON.parse(
window.localStorage.getItem(THEME_HALVES_STORAGE_KEY) ?? "null",
);
if (value === null || typeof value !== "object") return {};
const halves: { light?: string; dark?: string } = {};
for (const appearance of ["light", "dark"] as const) {
const themeId = (value as Record<string, unknown>)[appearance];
if (typeof themeId === "string") halves[appearance] = themeId;
}
return halves;
} catch {
return {};
}
}
function themeHalvesSignature(halves: ThemeHalves | null): string {
return `${halves?.light ?? ""}|${halves?.dark ?? ""}`;
}
@@ -98,7 +135,7 @@ let listeners: Array<() => void> = [];
let lastSnapshot: ThemeSnapshot | null = null;
let snapshotStale = true;
let lastDesktopTheme: "light" | "dark" | "system" | null = null;
let lastAppliedTheme: ThemeSnapshot | null = null;
let lastAppliedTheme: Omit<ThemeSnapshot, "resolvedTheme"> | null = null;
let themeStorageReadFailure: ThemeStorageError | null = null;
function emitChange() {
@@ -282,8 +319,10 @@ export function syncBrowserChromeTheme() {
}
}
function applyTheme(theme: Theme, suppressTransitions = false) {
function applyTheme(theme: Theme, { suppressTransitions = false, preservePreview = true } = {}) {
if (typeof document === "undefined" || typeof window === "undefined") return;
// Keep the editor's draft visible until an explicit refresh restores the selection.
if (preservePreview && document.documentElement.dataset?.themeId === THEME_PREVIEW_ID) return;
const appearanceMode = readAppearanceModePreference(theme);
const followSystem = appearanceMode === "system";
const systemDark = followSystem ? getSystemDark() : false;
@@ -386,9 +425,17 @@ function getSnapshot(): ThemeSnapshot {
const systemDark = followSystem ? getSystemDark() : false;
const themeHalves = readStoredThemeHalves();
const resolvedTheme = resolveThemeAppearance(
theme,
systemDark,
followSystem,
appearanceMode,
themeHalves,
);
if (
lastSnapshot &&
lastSnapshot.theme === theme &&
lastSnapshot.resolvedTheme === resolvedTheme &&
lastSnapshot.systemDark === systemDark &&
lastSnapshot.followSystem === followSystem &&
lastSnapshot.appearanceMode === appearanceMode &&
@@ -397,7 +444,7 @@ function getSnapshot(): ThemeSnapshot {
return lastSnapshot;
}
lastSnapshot = { theme, systemDark, followSystem, appearanceMode, themeHalves };
lastSnapshot = { theme, resolvedTheme, systemDark, followSystem, appearanceMode, themeHalves };
return lastSnapshot;
}
@@ -407,26 +454,28 @@ function getServerSnapshot() {
function handleSystemAppearanceChange() {
const storedTheme = getStored();
if (readAppearanceModePreference(storedTheme) === "system") applyTheme(storedTheme, true);
if (readAppearanceModePreference(storedTheme) === "system") {
applyTheme(storedTheme, { suppressTransitions: true });
}
emitChange();
}
function handleStorageChange(e: StorageEvent) {
if (e.key === STORAGE_KEY) {
themeStorageReadFailure = null;
applyTheme(getStored(), true);
applyTheme(getStored(), { suppressTransitions: true });
emitChange();
} else if (e.key === THEME_FOLLOW_SYSTEM_STORAGE_KEY) {
applyTheme(getStored(), true);
applyTheme(getStored(), { suppressTransitions: true });
emitChange();
} else if (e.key === THEME_APPEARANCE_MODE_STORAGE_KEY || e.key === THEME_HALVES_STORAGE_KEY) {
applyTheme(getStored(), true);
applyTheme(getStored(), { suppressTransitions: true });
emitChange();
} else if (e.key === CUSTOM_THEMES_STORAGE_KEY || e.key === null) {
if (e.key === null) themeStorageReadFailure = null;
invalidateCustomThemes();
lastAppliedTheme = null;
applyTheme(getStored(), true);
applyTheme(getStored(), { suppressTransitions: true });
emitChange();
}
}
@@ -460,15 +509,7 @@ function subscribe(listener: () => void): () => void {
export function useTheme() {
const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
const theme = snapshot.theme;
const resolvedTheme: "light" | "dark" = resolveThemeAppearance(
theme,
snapshot.systemDark,
snapshot.followSystem,
snapshot.appearanceMode,
snapshot.themeHalves,
);
const { theme, resolvedTheme } = snapshot;
const setTheme = useCallback((next: Theme): boolean => {
if (typeof window === "undefined") return false;
@@ -511,7 +552,7 @@ export function useTheme() {
});
return false;
}
applyTheme(next, true);
applyTheme(next, { suppressTransitions: true });
emitChange();
return true;
}, []);
@@ -536,7 +577,7 @@ export function useTheme() {
return false;
}
themeStorageReadFailure = null;
applyTheme(getStored(), true);
applyTheme(getStored(), { suppressTransitions: true });
emitChange();
return true;
}, []);
@@ -558,7 +599,7 @@ export function useTheme() {
(appearance: ThemeAppearance, themeId: string | null): boolean => {
if (typeof window === "undefined") return false;
try {
const current = readStoredThemeHalves() ?? {};
const current = readStoredThemeHalvesRaw();
const next: { light?: string; dark?: string } = { ...current };
if (themeId === null) delete next[appearance];
else next[appearance] = themeId;
@@ -580,7 +621,7 @@ export function useTheme() {
});
return false;
}
applyTheme(getStored(), true);
applyTheme(getStored(), { suppressTransitions: true });
emitChange();
return true;
},
@@ -604,15 +645,15 @@ export function useTheme() {
});
return false;
}
applyTheme(getStored(), true);
applyTheme(getStored(), { suppressTransitions: true });
emitChange();
return true;
}, []);
const refreshTheme = useCallback(() => {
const refreshTheme = useCallback(({ preservePreview = false } = {}) => {
if (typeof window === "undefined") return;
lastAppliedTheme = null;
applyTheme(getStored(), true);
applyTheme(getStored(), { suppressTransitions: true, preservePreview });
emitChange();
}, []);
+12
View File
@@ -21,6 +21,8 @@ import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPrompt
import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
import { useDefaultThemeAdoption } from "../hooks/useDefaultTheme";
import { useEnvironmentThemeSync } from "../hooks/useEnvironmentTheme";
import { Button } from "../components/ui/button";
import {
AnchoredToastProvider,
@@ -133,6 +135,7 @@ function RootRouteView() {
<AnchoredToastProvider>
<DocumentTitleSync />
<ContrastAppearanceSync />
<EnvironmentThemeSync />
<GlassAppearanceSync />
<FontAppearanceSync />
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
@@ -154,6 +157,15 @@ function RootRouteView() {
);
}
/** Follows the palette the primary environment's machine publishes, if any. */
function EnvironmentThemeSync() {
useEnvironmentThemeSync();
// Ordered after the palette sync so a first-run client adopting the
// environment's own theme finds it already in the library.
useDefaultThemeAdoption();
return null;
}
function ContrastAppearanceSync() {
const appearanceContrast = useClientSettings((settings) => settings.appearanceContrast);
+20
View File
@@ -1,6 +1,7 @@
import {
DEFAULT_SERVER_SETTINGS,
type EditorId,
type EnvironmentTheme,
type ServerConfig,
type ServerConfigStreamEvent,
type ServerLifecycleWelcomePayload,
@@ -18,8 +19,15 @@ import { connectionAtomRuntime } from "../connection/runtime";
import { primaryEnvironmentIdAtom } from "./primaryEnvironment";
import { environmentSession } from "./session";
// Opted in for every environment, not just the primary one. Only the primary
// environment's themes are rendered, but which environment is primary changes
// at runtime and the subscription payload is fixed when it is established --
// gating on "primary right now" would leave a newly promoted environment with
// no themes until it reconnected. The set is capped server-side and stripped
// before caching, so following all of them costs a few KB per environment.
export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRuntime, {
initialConfigValueAtom: environmentSession.initialConfigValueAtom,
environmentThemes: true,
});
export const environmentServerConfigsAtom = createEnvironmentServerConfigsAtom({
catalogValueAtom: environmentCatalog.catalogValueAtom,
@@ -94,6 +102,18 @@ export const primaryServerKeybindingsConfigPathAtom = Atom.make(
(get): string | null => get(primaryServerConfigAtom)?.keybindingsConfigPath ?? null,
).pipe(Atom.withLabel("web-primary-server-keybindings-config-path"));
const EMPTY_ENVIRONMENT_THEMES: ReadonlyArray<EnvironmentTheme> = [];
/**
* Palettes published by the primary environment's machine. Only the primary
* environment: a client follows the machine it is anchored to, not every
* environment it happens to be connected to.
*/
export const primaryServerEnvironmentThemesAtom = Atom.make(
(get): ReadonlyArray<EnvironmentTheme> =>
get(primaryServerConfigAtom)?.environmentThemes ?? EMPTY_ENVIRONMENT_THEMES,
).pipe(Atom.withLabel("web-primary-server-environment-themes"));
export const primaryServerObservabilityAtom = Atom.make(
(get): ServerConfig["observability"] | null =>
get(primaryServerConfigAtom)?.observability ?? null,
+9
View File
@@ -39,6 +39,7 @@ import {
themeColorToHex,
toCanonicalThemeColor,
THEME_FILE_VERSION,
singleAppearanceOf,
} from "./themePalette";
function asHex(value: string): string {
@@ -1072,3 +1073,11 @@ describe("stored theme preferences", () => {
invalidateCustomThemes();
});
});
describe("singleAppearanceOf", () => {
it("reports the only half a theme can claim, and null for a pair", () => {
const { variants: _pair, ...base } = T3_CHAT_THEME;
expect(singleAppearanceOf({ ...base, id: "x", appearance: "dark" })).toBe("dark");
expect(singleAppearanceOf(T3_CHAT_THEME)).toBe(null);
});
});
+64 -25
View File
@@ -1,3 +1,4 @@
import * as Equal from "effect/Equal";
import * as Schema from "effect/Schema";
import "culori/css";
import { converter, parse } from "culori/fn";
@@ -8,6 +9,7 @@ import {
IRIS_THEME,
OCEAN_THEME,
T3_CHAT_THEME,
RESERVED_THEME_IDS,
THEME_COLOR_ROLES,
type ThemeAppearance,
type ThemeColorRole,
@@ -56,21 +58,16 @@ export type ThemeFile = Readonly<{
managed?: boolean;
}>;
const RESERVED_THEME_IDS = new Set([
"system",
"light",
"dark",
T3_CHAT_THEME_ID,
GROVE_THEME_ID,
OCEAN_THEME_ID,
EMBER_THEME_ID,
IRIS_THEME_ID,
LEGACY_T3_CHAT_DARK_THEME_ID,
"t3-grove",
"t3-ocean",
"t3-ember",
"t3-iris",
]);
// Reserved ids come from shared so the CLI, the server watcher, and this
// library cannot drift on what a published theme may be called.
/**
* The environment's palettes are not saved: they are republished by the
* server on every change and would go stale the moment the machine's theme
* moved on. They ride the custom-theme listeners so every theme consumer
* already re-reads when they change.
*/
let environmentThemeDefinitions: ReadonlyArray<ThemeDefinition> = [];
const customThemeListeners = new Set<() => void>();
type CustomThemeLibrarySnapshot =
@@ -130,21 +127,28 @@ function parseThemeCollection(value: unknown): ThemeCollection | undefined {
: undefined;
}
function parseStoredThemeColors(value: unknown, appearance: ThemeAppearance): ThemeColors | null {
if (!isRecord(value)) return null;
const colors: Partial<Record<ThemeColorRole, string>> = {
...getDefaultThemeColors(appearance),
};
// Tolerate unknown roles and malformed values so themes saved by other
// builds (for example one that adds a new role) keep their remaining colors.
/**
* Tolerates unknown roles and malformed values so themes written by other
* builds (for example one that adds a new role) keep their remaining colors.
* The one canonicalization path for every externally supplied color record:
* stored themes, imported files, and environment-published themes.
*/
export function lenientThemeColorOverrides(
value: Readonly<Record<string, unknown>>,
): Partial<Record<ThemeColorRole, string>> {
const overrides: Partial<Record<ThemeColorRole, string>> = {};
for (const [role, color] of Object.entries(value)) {
const normalized = toCanonicalThemeColor(color);
if (THEME_COLOR_ROLE_SET.has(role) && normalized) {
colors[role as ThemeColorRole] = normalized;
overrides[role as ThemeColorRole] = normalized;
}
}
return colors as ThemeColors;
return overrides;
}
function parseStoredThemeColors(value: unknown, appearance: ThemeAppearance): ThemeColors | null {
if (!isRecord(value)) return null;
return { ...getDefaultThemeColors(appearance), ...lenientThemeColorOverrides(value) };
}
function parseStoredThemeVariants(
@@ -244,6 +248,27 @@ export function getCustomThemes(): ReadonlyArray<ThemeDefinition> {
return snapshot.status === "ready" ? snapshot.themes : [];
}
export function getEnvironmentThemes(): ReadonlyArray<ThemeDefinition> {
return environmentThemeDefinitions;
}
/**
* Returns whether anything changed, structurally: config snapshots arrive as
* fresh arrays on every reconnect, and a repaint for identical colors is the
* kind of wasted work users of this product notice.
*/
export function setEnvironmentThemes(themes: ReadonlyArray<ThemeDefinition>): boolean {
if (Equal.equals(environmentThemeDefinitions, themes)) return false;
environmentThemeDefinitions = themes;
notifyCustomThemeListeners();
return true;
}
/** Ids no published theme may occupy: appearance keywords and built-in ids. */
export function isReservedThemeId(themeId: string): boolean {
return RESERVED_THEME_IDS.has(themeId);
}
export function getStoredCustomThemeCollection(
collectionId: string,
): ReadonlyArray<ThemeDefinition> {
@@ -1424,6 +1449,9 @@ export function getThemeDefinition(theme: ThemePreference): ThemeDefinition | nu
return (
BUILT_IN_THEME_DEFINITIONS.find((definition) => definition.id === themeId) ??
getCustomThemes().find((definition) => definition.id === themeId) ??
// Resolved last so a theme the user saved always wins over one the
// machine happens to publish under the same id.
environmentThemeDefinitions.find((definition) => definition.id === themeId) ??
null
);
}
@@ -1437,6 +1465,17 @@ export function themeAllowsSidebarArtwork(theme: ThemePreference): boolean {
);
}
/**
* Which half a theme can claim, or null when it renders both appearances.
* Selecting a single-appearance theme as the base preference would clear the
* light/dark mix and leave the appearance tiles disagreeing with what is on
* screen, so every path that selects a theme has to make the same call.
*/
export function singleAppearanceOf(theme: ThemeDefinition): ThemeAppearance | null {
const modes = getThemeModes(theme);
return modes.length === 1 ? modes[0]! : null;
}
export function getThemeColorsForMode(
theme: ThemeDefinition,
mode: ThemeAppearance,
+1
View File
@@ -9,6 +9,7 @@
- [Review usage](./user/usage.md)
- [Customize a project icon](./user/project-settings.md)
- [Mobile appearance](./user/mobile-appearance.md)
- [Environment themes](./user/environment-theme.md)
- [Remote access](./user/remote-access.md)
- [Keeping app and server in sync](./user/updating.md)
- [Source control integrations](./user/source-control.md)
+18
View File
@@ -11,6 +11,7 @@ This is a living glossary for T3 Code. It explains what common terms mean in thi
- [Orchestration](#orchestration)
- [Provider runtime](#provider-runtime)
- [Checkpointing](#checkpointing)
- [Appearance](#appearance)
## Concepts
@@ -144,6 +145,21 @@ The patch difference between two checkpoints. Query logic lives in [CheckpointDi
The file patch and changed-file summary for one turn. It is usually computed in [CheckpointDiffQuery.ts][20], represented in [the contracts][1], and recorded into thread state by [projector.ts][4].
### Appearance
#### Environment theme
A theme an environment's machine publishes for clients to follow, one file per theme under `themes/` in that environment's state directory; the filename is the theme id. [environmentTheme.ts][25] watches the directory and streams the set over `subscribeServerConfig`; clients render each as a library card, generating a full palette when the file carries seed colors and using the palette directly when it is a standard exported theme file. A desktop that retints its apps when the system theme changes rewrites its file, so T3 Code follows along without a restart. See [environment-theme.md][26].
#### Default theme
The environment's theme, held in its `settings.json` as `defaultTheme` (with `defaultThemeSetAt`
as the set-generation) and set with `t3 theme set <id>`. Web and desktop clients apply each set
once — live when connected, on the next connect otherwise — so setting it switches them, while a
theme a user picks in Settings afterwards sticks until the next set; mobile keeps its own
appearance settings. Naming a published [environment theme](#environment-theme) is how a desktop
ships T3 Code already matching it.
## Practical Shortcuts
- If you see `requested`, think "intent recorded".
@@ -183,3 +199,5 @@ The file patch and changed-file summary for one turn. It is usually computed in
[22]: ../../apps/server/src/checkpointing/Utils.ts
[23]: ../../apps/server/src/checkpointing/Diffs.ts
[24]: ./overview.md
[25]: ../../apps/server/src/environmentTheme.ts
[26]: ../user/environment-theme.md
+92
View File
@@ -0,0 +1,92 @@
# Environment theme
Some desktops publish the palette they are currently wearing so that apps can match it. When the
machine running your T3 Code server does that, its themes appear in the theme library alongside
your own, and T3 Code follows them: change the desktop theme and T3 Code retints with it, without
a restart.
To use one:
1. Open **Settings**.
2. Select **Appearance**.
3. Choose the theme published by your environment.
Like every theme, this is a per-client choice: picking it on your desktop does not change what your
phone or another browser shows.
The machine can also set the environment's theme:
```bash
t3 theme set nightfall
```
Web and desktop clients switch to it — immediately when connected, on their next connect
otherwise — and a fresh client opens with it. Each client applies a set once, so picking a
different theme in Settings afterwards sticks until the next `t3 theme set`, and running the same
set again is how you bring clients back. `t3 theme clear` removes the setting without changing
what anyone currently has, and `t3 theme show` prints the current theme and everything the
machine publishes. Only the environment you are anchored to publishes themes, so a remote client
follows the machine it is connected to, not the device it runs on. T3 Code Mobile keeps its own
appearance settings and does not follow environment themes.
Select **Duplicate** on a published theme's card to keep a copy you can edit. The published theme
itself cannot be edited or removed, because the environment rewrites it whenever its own theme
changes. If the machine stops publishing it, the card disappears and clients using it fall back to
the standard T3 Code look. A theme you saved always wins over a published one with the same id.
When the theme editor is open, its draft stays visible while published themes change.
Close the editor to show the latest selected theme.
## Publishing themes
A machine publishes themes by writing files into the `themes` directory of the T3 Code state
directory (`~/.t3/userdata/themes/` by default). The filename is the theme id — `nightfall.json`
appears as `nightfall` — and stays stable while the machine rewrites the colors underneath, so
selections and defaults keep pointing at it.
The filename may not be an appearance keyword (`system`, `light`, `dark`) or a built-in theme's
id — those names already mean something on every client. Two formats are accepted. A theme
exported from T3 Code (the **Download** button's output) works as-is, so any theme someone shared
can be dropped in unchanged. Or, for a desktop that only knows
its own palette, a short seeded form:
```json
{
"name": "Nightfall",
"appearance": "dark",
"canvas": "#1a1b26",
"accent": "#7aa2f7"
}
```
`appearance` is `light` or `dark`, and `canvas` and `accent` are hex colors. T3 Code generates the
rest of the palette from those two, the same way the guided theme editor does, so the result reads
as a T3 Code theme wearing your desktop's colors rather than a transplant of another app's.
A machine that knows a role better than a derivation can guess — its terminal palette, its
semantic colors — can publish that role directly under `colors`, layered over the generated
palette:
```json
{
"name": "Nightfall",
"appearance": "dark",
"canvas": "#1a1b26",
"accent": "#7aa2f7",
"colors": {
"terminalSelection": "#292e42",
"error": "#f7768e"
}
}
```
Any of the roles shown in the theme editor's advanced view can be published this way; roles left
out keep their generated value. A role this version of T3 Code does not know is ignored rather
than rejected, so publishing a role added by a newer release is safe. An `id` inside the file is
ignored — the filename decides.
A theme with no usable colors is not listed on that client.
Write each file atomically — write a temporary file beside it and rename — so T3 Code never reads
a half-written theme. An unreadable or invalid file is simply not published; the machine's other
themes are unaffected.
@@ -51,6 +51,9 @@ const CONFIG = {
observability: null,
providers: [],
settings: {},
// Capabilities drive version-skew behaviour in the projection, so the
// fixture carries them rather than leaving the field absent.
environment: { capabilities: { environmentThemes: true } },
} as unknown as ServerConfig;
const snapshotEvent = (config: ServerConfig): ServerConfigStreamEvent => ({
@@ -306,6 +309,78 @@ describe("server state projection", () => {
expect(result.latestEvent.type).toBe("settingsUpdated");
});
it("carries published environment themes in and out of the projected snapshot", () => {
const snapshot = applyServerConfigProjection(Option.none(), {
version: 1,
type: "snapshot",
config: CONFIG,
});
const themes = [
{
id: "nightfall",
name: "Nightfall",
appearance: "dark",
canvas: "#1a1b26",
accent: "#7aa2f7",
},
] as const;
const published = applyServerConfigProjection(snapshot, {
version: 1,
type: "environmentThemesUpdated",
payload: { themes },
});
expect(Option.getOrThrow(published).config.environmentThemes).toEqual(themes);
// A machine that stops publishing has to clear the palettes, not freeze
// clients on the last set it sent.
const unpublished = applyServerConfigProjection(published, {
version: 1,
type: "environmentThemesUpdated",
payload: { themes: [] },
});
expect(Option.getOrThrow(unpublished).config.environmentThemes).toBeUndefined();
});
// A snapshot never carries published themes, so taking it wholesale would
// clear them on every reconnect and repaint anyone wearing one.
it("keeps published themes across a reconnect snapshot", () => {
const themes = [
{
id: "nightfall",
name: "Nightfall",
appearance: "dark",
canvas: "#1a1b26",
accent: "#7aa2f7",
},
] as const;
const withThemes = applyServerConfigProjection(
applyServerConfigProjection(Option.none(), { version: 1, type: "snapshot", config: CONFIG }),
{ version: 1, type: "environmentThemesUpdated", payload: { themes } },
);
expect(Option.getOrThrow(withThemes).config.environmentThemes).toEqual(themes);
const afterReconnect = applyServerConfigProjection(withThemes, {
version: 1,
type: "snapshot",
config: CONFIG,
});
expect(Option.getOrThrow(afterReconnect).config.environmentThemes).toEqual(themes);
// A server that predates the feature never sends another theme event, so
// carrying the set forward would leave a palette nothing can update.
const downgraded = applyServerConfigProjection(withThemes, {
version: 1,
type: "snapshot",
config: {
...CONFIG,
environment: { capabilities: {} },
} as unknown as ServerConfig,
});
expect(Option.getOrThrow(downgraded).config.environmentThemes).toBeUndefined();
});
it("retains welcome when a ready event follows in the same stream chunk", () => {
const welcome = {
environment: {} as ServerLifecycleWelcomePayload["environment"],
+58 -12
View File
@@ -273,12 +273,24 @@ export function applyServerConfigProjection(
event: ServerConfigStreamEvent,
): Option.Option<ServerConfigProjection> {
switch (event.type) {
case "snapshot":
case "snapshot": {
// A snapshot never carries published themes -- the theme stream owns
// them -- so taking it wholesale would clear the set on every reconnect
// and repaint anyone wearing one until the follow-up event landed.
// Only from a server that still streams them. Reconnecting to one that
// predates the feature must drop the set rather than leave a palette on
// screen that nothing will ever update again.
const carried =
event.config.environment.capabilities.environmentThemes === true && Option.isSome(current)
? current.value.config.environmentThemes
: undefined;
return Option.some({
config: event.config,
config:
carried === undefined ? event.config : { ...event.config, environmentThemes: carried },
latestEvent: event,
source: "live",
source: "live" as const,
});
}
case "keybindingsUpdated":
return Option.map(current, (projection) => ({
config: {
@@ -307,6 +319,15 @@ export function applyServerConfigProjection(
latestEvent: event,
source: "live",
}));
case "environmentThemesUpdated":
return Option.map(current, (projection) => ({
config: {
...projection.config,
environmentThemes: event.payload.themes.length > 0 ? event.payload.themes : undefined,
},
latestEvent: event,
source: "live",
}));
}
}
@@ -329,8 +350,19 @@ const cachedConfigSnapshotEvent = (config: ServerConfig): ServerConfigStreamEven
* config carries the provider/model catalogue used by task creation, so it is
* useful—and safe—to retain after a transport session ends.
*/
/**
* Published themes live only as long as the machine publishes them, so they
* must not survive in the config cache: a restart or an offline load would
* otherwise hand clients palettes the environment has already dropped.
*/
function withoutEnvironmentThemes(config: ServerConfig): ServerConfig {
if (config.environmentThemes === undefined) return config;
const { environmentThemes: _ephemeral, ...rest } = config;
return rest;
}
export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfigState.make")(
function* () {
function* (environmentThemes?: boolean) {
const supervisor = yield* EnvironmentSupervisor;
const cache = yield* EnvironmentCacheStore;
const environmentId = supervisor.target.environmentId;
@@ -346,9 +378,11 @@ export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConf
),
);
const state = yield* SubscriptionRef.make<Option.Option<ServerConfigProjection>>(
Option.map(cachedConfig, (config) => ({
config,
latestEvent: cachedConfigSnapshotEvent(config),
// Stripped on load as well as on save: a cache written by an earlier
// build can still carry published themes.
Option.map(cachedConfig, (cached) => ({
config: withoutEnvironmentThemes(cached),
latestEvent: cachedConfigSnapshotEvent(withoutEnvironmentThemes(cached)),
source: "cache" as const,
})),
);
@@ -358,7 +392,7 @@ export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConf
const persist = Effect.fn("EnvironmentServerConfigState.persist")(function* (
config: ServerConfig,
) {
return yield* cache.saveServerConfig(environmentId, config).pipe(
return yield* cache.saveServerConfig(environmentId, withoutEnvironmentThemes(config)).pipe(
Effect.as(true),
Effect.catch((error) =>
Effect.logWarning("Could not persist cached server configuration.").pipe(
@@ -389,7 +423,10 @@ export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConf
Effect.forkScoped,
);
yield* subscribe(WS_METHODS.subscribeServerConfig, {}).pipe(
yield* subscribe(
WS_METHODS.subscribeServerConfig,
environmentThemes === true ? { environmentThemes: true } : {},
).pipe(
Stream.runForEach((event) =>
Effect.gen(function* () {
const next = applyServerConfigProjection(yield* SubscriptionRef.get(state), event);
@@ -419,11 +456,14 @@ export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConf
},
);
export function serverConfigStateChanges(environmentId: EnvironmentId) {
export function serverConfigStateChanges(
environmentId: EnvironmentId,
environmentThemes?: boolean,
) {
return followStreamInEnvironment(
environmentId,
Stream.unwrap(
makeEnvironmentServerConfigState().pipe(
makeEnvironmentServerConfigState(environmentThemes).pipe(
Effect.map((state) =>
SubscriptionRef.changes(state).pipe(
Stream.filterMap((projection) =>
@@ -476,6 +516,12 @@ export function createServerEnvironmentAtoms<R, E>(
readonly initialConfigValueAtom: (
environmentId: EnvironmentId,
) => Atom.Atom<ServerConfig | null>;
/**
* Whether this surface renders themes the environment publishes. Mobile
* keeps its own appearance settings, so it neither asks for the stream nor
* receives the payload.
*/
readonly environmentThemes?: boolean;
},
) {
const configScheduler = createAtomCommandScheduler();
@@ -487,7 +533,7 @@ export function createServerEnvironmentAtoms<R, E>(
};
const configProjectionFamily = Atom.family((environmentId: EnvironmentId) =>
runtime
.atom(serverConfigStateChanges(environmentId))
.atom(serverConfigStateChanges(environmentId, options.environmentThemes))
.pipe(
Atom.setIdleTTL(5 * 60_000),
Atom.withLabel(`environment-data:server:config-projection:${environmentId}`),
+5
View File
@@ -66,6 +66,11 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
/** Server understands thread.snooze / thread.unsnooze commands. Same
version-skew contract as threadSettlement. */
threadSnooze: Schema.optionalKey(Schema.Boolean),
/** Server streams themes an environment publishes. Absent on servers from
before environment themes shipped, which never emit the events -- so a
client reconnecting to one must drop published themes rather than keep
showing a set nothing will ever update. */
environmentThemes: Schema.optionalKey(Schema.Boolean),
/** Server understands thread.pin / thread.unpin commands. Same
version-skew contract as threadSettlement. */
threadPinning: Schema.optionalKey(Schema.Boolean),
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vite-plus/test";
import * as Exit from "effect/Exit";
import * as Schema from "effect/Schema";
import { WsSubscribeServerConfigRpc } from "./rpc.ts";
/**
* The client always sends `environmentThemes`, including to servers built
* before the field existed, whose payload schema was an empty struct. What
* makes that safe is that such a schema accepts the request rather than
* rejecting it -- an error here would take down the config subscription.
*/
describe("subscribeServerConfig payload compatibility", () => {
it("is accepted by a server whose schema predates the field", () => {
const oldServerPayload = Schema.Struct({});
const decoded = Schema.decodeUnknownExit(oldServerPayload)({ environmentThemes: true });
expect(Exit.isSuccess(decoded)).toBe(true);
});
it("is carried by a server that declares it", () => {
const decoded = Schema.decodeUnknownSync(WsSubscribeServerConfigRpc.payloadSchema)({
environmentThemes: true,
});
expect(decoded).toEqual({ environmentThemes: true });
});
it("stays optional, so a client that never sends it still subscribes", () => {
const decoded = Schema.decodeUnknownSync(WsSubscribeServerConfigRpc.payloadSchema)({});
expect(decoded).toEqual({});
});
});
+10 -1
View File
@@ -983,7 +983,16 @@ export const WsSubscribeTerminalMetadataRpc = Rpc.make(WS_METHODS.subscribeTermi
});
export const WsSubscribeServerConfigRpc = Rpc.make(WS_METHODS.subscribeServerConfig, {
payload: Schema.Struct({}),
payload: Schema.Struct({
/**
* Whether this client understands `environmentThemesUpdated` events.
* Already-shipped clients decode the stream against the old event union
* and would die on an unknown member, so the server emits the theme
* stream only to subscribers that ask for it. Absent on old clients;
* dropped by old servers.
*/
environmentThemes: Schema.optional(Schema.Boolean),
}),
success: ServerConfigStreamEvent,
error: Schema.Union([KeybindingsConfigError, ServerSettingsError, EnvironmentAuthorizationError]),
stream: true,
+111
View File
@@ -417,6 +417,93 @@ export const ServerSignalProcessResult = Schema.Struct({
});
export type ServerSignalProcessResult = typeof ServerSignalProcessResult.Type;
/**
* A palette the environment's machine publishes for T3 Code to follow, read
* from a theme file next to the rest of the environment's state. Two seed
* colors rather than a full palette: clients derive the remaining roles with
* the same generator the guided theme editor uses, so a desktop theme carries
* over as a coherent T3 Code palette instead of a foreign one.
*/
export const EnvironmentThemeColor = Schema.String.check(
Schema.isPattern(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/),
);
export type EnvironmentThemeColor = typeof EnvironmentThemeColor.Type;
/**
* Matches the client-side theme id rule, so a published id is selectable.
* The appearance keywords are excluded outright: a published `dark.json`
* would otherwise capture every client whose stored preference is the stock
* `"dark"`, retinting people who never chose it.
*/
export const EnvironmentThemeId = Schema.String.check(
Schema.isPattern(/^(?!(?:system|light|dark)$)[a-z0-9](?:[a-z0-9-]{0,47})$/),
);
export type EnvironmentThemeId = typeof EnvironmentThemeId.Type;
/**
* Role colors as published. Values are any CSS color the client's theme
* parser accepts (exported theme files use oklch), canonicalized client-side;
* roles a build does not know are dropped there, so a machine may publish
* roles a newer client added without breaking an older one. Keys must still
* be role-shaped and values color-sized, so the record stays open to future
* vocabulary without being an arbitrary-payload channel.
*/
const EnvironmentThemeColors = Schema.Record(
Schema.String.check(Schema.isPattern(/^[a-zA-Z][a-zA-Z0-9]{0,63}$/)),
TrimmedNonEmptyString.check(Schema.isMaxLength(64)),
);
const environmentThemeFields = {
/**
* Standard exported theme files (the Download button's output) carry
* `version: 1`; the seeded short form a desktop generates has no version.
*/
version: Schema.optional(Schema.Literal(1)),
/** Shown on the theme card, e.g. the desktop theme's own name. */
name: TrimmedNonEmptyString.check(Schema.isMaxLength(48)),
appearance: Schema.Literals(["light", "dark"]),
/**
* Seed colors. When present, clients derive the full palette from them with
* the guided theme editor's generator and layer `colors` on top; when
* absent, `colors` is the palette, as in an exported theme file.
*/
canvas: Schema.optional(EnvironmentThemeColor),
accent: Schema.optional(EnvironmentThemeColor),
colors: Schema.optional(EnvironmentThemeColors),
/** The other appearance's palette, as exported theme files carry it. */
variants: Schema.optional(
Schema.Struct({
light: Schema.optional(EnvironmentThemeColors),
dark: Schema.optional(EnvironmentThemeColors),
}),
),
};
/** One published theme file. The id is the filename, not part of the content,
* so a file cannot claim another file's identity; an embedded `id` is ignored. */
export const EnvironmentThemeFile = Schema.Struct(environmentThemeFields);
export type EnvironmentThemeFile = typeof EnvironmentThemeFile.Type;
export const EnvironmentTheme = Schema.Struct({
/** The publishing filename without its extension, stable across recolors. */
id: EnvironmentThemeId,
...environmentThemeFields,
});
export type EnvironmentTheme = typeof EnvironmentTheme.Type;
/**
* Whether a theme file carries anything to render. A file with neither seeds
* nor colors would show as the stock palette wearing a name, which reads as a
* bug rather than a theme — the CLI and the server watcher both reject it,
* through this one predicate so they cannot drift.
*/
export function environmentThemeFileHasColors(file: EnvironmentThemeFile): boolean {
return (
(file.canvas !== undefined && file.accent !== undefined) ||
(file.colors !== undefined && Object.keys(file.colors).length > 0)
);
}
export const ServerConfig = Schema.Struct({
environment: ExecutionEnvironmentDescriptor,
auth: ServerAuthDescriptor,
@@ -451,6 +538,14 @@ export const ServerConfig = Schema.Struct({
* fields to servers that don't advertise this.
*/
threadSnapshotPagination: Schema.optionalKey(Schema.Boolean),
/**
* Palettes published by this environment's machine. Never sent in a config
* snapshot: the theme stream emits the current set before any change, so a
* snapshot carrying it too would hand every subscriber the same array twice
* per connect. Clients populate this by projecting `environmentThemesUpdated`,
* and it stays absent for subscribers that did not opt in.
*/
environmentThemes: Schema.optional(Schema.Array(EnvironmentTheme)),
});
export type ServerConfig = typeof ServerConfig.Type;
@@ -535,11 +630,27 @@ export const ServerConfigStreamSettingsUpdatedEvent = Schema.Struct({
export type ServerConfigStreamSettingsUpdatedEvent =
typeof ServerConfigStreamSettingsUpdatedEvent.Type;
export const ServerConfigEnvironmentThemesUpdatedPayload = Schema.Struct({
/** The full published set; empty once the machine publishes none. */
themes: Schema.Array(EnvironmentTheme),
});
export type ServerConfigEnvironmentThemesUpdatedPayload =
typeof ServerConfigEnvironmentThemesUpdatedPayload.Type;
export const ServerConfigStreamEnvironmentThemesUpdatedEvent = Schema.Struct({
version: Schema.Literal(1),
type: Schema.Literal("environmentThemesUpdated"),
payload: ServerConfigEnvironmentThemesUpdatedPayload,
});
export type ServerConfigStreamEnvironmentThemesUpdatedEvent =
typeof ServerConfigStreamEnvironmentThemesUpdatedEvent.Type;
export const ServerConfigStreamEvent = Schema.Union([
ServerConfigStreamSnapshotEvent,
ServerConfigStreamKeybindingsUpdatedEvent,
ServerConfigStreamProviderStatusesEvent,
ServerConfigStreamSettingsUpdatedEvent,
ServerConfigStreamEnvironmentThemesUpdatedEvent,
]);
export type ServerConfigStreamEvent = typeof ServerConfigStreamEvent.Type;
+24
View File
@@ -131,6 +131,19 @@ export const DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE: EnvironmentIdentificationM
export const FontFamilyPreference = Schema.String.check(Schema.isMaxLength(200));
export type FontFamilyPreference = typeof FontFamilyPreference.Type;
/**
* The environment's theme, set with `t3 theme set <id>`. Each client applies
* it once per value — live when connected, on its next connect otherwise — so
* setting it switches every client, while a theme a user picks in Settings
* afterwards sticks until the next set. Empty means "no environment theme",
* which is also how it is cleared.
*/
export const DefaultThemePreference = Schema.String.check(Schema.isMaxLength(64));
// Deliberately absent from ServerSettingsPatch: `t3 theme set` checks that an
// id is syntactically valid and actually resolvable, and a generic RPC patch
// would let a client write a theme no client can resolve, bypassing both.
export type DefaultThemePreference = typeof DefaultThemePreference.Type;
/**
* Defaults for the in-app preview browser, applied whenever a tab is opened
* without an explicit viewport/zoom/appearance — by the user opening a browser
@@ -653,6 +666,17 @@ export const ServerSettings = Schema.Struct({
backgroundActivityProfile: BackgroundActivityProfile.pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
),
defaultTheme: DefaultThemePreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
/**
* When the environment's theme was last set, so clients can tell a re-set
* of the same value from one they already applied: `t3 theme set` must act
* even when it names the theme it named before. Empty on environments
* provisioned by builds that predate it, where clients fall back to
* applying once per value.
*/
defaultThemeSetAt: Schema.String.check(Schema.isMaxLength(64)).pipe(
Schema.withDecodingDefault(Effect.succeed("")),
),
defaultThreadEnvMode: ThreadEnvMode.pipe(
Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
),
+29
View File
@@ -10,6 +10,35 @@ export const MOBILE_DEFAULT_THEME_ID = "t3-code";
*/
export const MOBILE_THEME_IDS = [MOBILE_DEFAULT_THEME_ID, ...BUILT_IN_THEME_IDS] as const;
/**
* Ids a theme may not take: the appearance keywords a stored preference uses,
* every built-in, and the legacy aliases older saves still carry. Taking one
* would either be shadowed by the built-in or capture clients that never chose
* it, so the client library and the publish path both consult this set.
*/
export const RESERVED_THEME_IDS: ReadonlySet<string> = new Set([
"system",
"light",
"dark",
...BUILT_IN_THEME_IDS,
"t3-chat-dark",
"t3-grove",
"t3-ocean",
"t3-ember",
"t3-iris",
]);
/**
* Additionally closed to a machine publishing a theme: the mobile default is
* not a web or desktop built-in, so a saved theme may legitimately carry that
* id, but no client that follows published themes can resolve it -- publishing
* it would report success and change nothing.
*/
export const UNPUBLISHABLE_THEME_IDS: ReadonlySet<string> = new Set([
...RESERVED_THEME_IDS,
MOBILE_DEFAULT_THEME_ID,
]);
export type BuiltInThemeId = (typeof BUILT_IN_THEME_IDS)[number];
export type MobileThemeId = (typeof MOBILE_THEME_IDS)[number];
export type ThemeAppearance = "light" | "dark";