feat: let an environment publish themes as a file #8569
Mergedryanrhughes(GitHub profile, opens in a new tab)merged 16 commits into
main fromrefs/pull/8569/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/cli/theme.ts lines 48 to 52OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +32,21 @@32+33+import { writeFileStringAtomically } from "../atomicWrite.ts";34+import * as ServerConfig from "../config.ts";35+import { expandHomePath, resolveBaseDir } from "../os-jank.ts";36+import { baseDirFlag } from "./config.ts";37+38+/** Settings files outlive the build that reads them, so the object is carried39+ * as-is and only the theme keys are touched. */40+const SparseSettings = Schema.Record(Schema.String, Schema.Unknown);41+const decodeSettingsJson = Schema.decodeUnknownEffect(fromLenientJson(SparseSettings));42+const encodeSettingsJson = Schema.encodeEffect(fromJsonStringPretty(SparseSettings));43+const decodeThemeFileJsonExit = Schema.decodeUnknownExit(44+ Schema.fromJsonString(EnvironmentThemeFile),45+);46+const isEnvironmentThemeId = Schema.is(EnvironmentThemeId);47+48+class ThemeSettingsError extends CliError.UserError {49+ override get message() {50+ return String(this.cause);51+ }52+}apps/server/src/cli/theme.ts lines 120 to 124OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +104,21 @@104+ ),105+ );106+107+ const contents = yield* encodeSettingsJson(next);108+ yield* writeFileStringAtomically({ filePath: input.settingsPath, contents: `${contents}\n` });109+});110+111+/** Publishes a theme file into the environment's themes directory and returns112+ * the id it published under. */113+const publishThemeFile = Effect.fn(function* (input: {114+ readonly themesDir: string;115+ readonly filePath: string;116+ readonly explicitId: Option.Option<string>;117+}) {118+ const fs = yield* FileSystem.FileSystem;119+ const path = yield* Path.Path;120+ const raw = yield* fs121+ .readFileString(input.filePath)122+ .pipe(123+ Effect.mapError(() => new ThemeSettingsError({ cause: `Could not read ${input.filePath}.` })),124+ );
- apps/web/src/components/settings/ThemeSettings.tsx line 836OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -811,0 +816,21 @@816+ // A saved theme with the same id wins resolution, so its card is817+ // the one that must show; rendering both would also collide keys.818+ (environmentTheme) => !customThemes.some((theme) => theme.id === environmentTheme.id),819+ )820+ .map((environmentTheme) => (821+ // No edit or remove: the environment republishes these palettes on822+ // every change, so anything saved here would be overwritten.823+ // Duplicating is the way to keep a copy.824+ <ThemeLibraryCard825+ activeModes={pickedModesFor(environmentTheme.id)}826+ isActive={false}827+ key={environmentTheme.id}828+ onDuplicate={() =>829+ openThemeEditor({830+ editingThemeId: null,831+ seedThemeId: environmentTheme.id,832+ seedName: `${environmentTheme.label} copy`,833+ initialAppearance,834+ })835+ }836+ onUse={() => persistTheme(environmentTheme.id)}apps/server/src/cli/theme.ts line 75OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +55,21 @@55+56+const resolveThemePaths = Effect.fn(function* (explicitBaseDir: Option.Option<string>) {57+ // Same precedence as the rest of the CLI: --base-dir, then T3CODE_HOME,58+ // then the default home. A provisioning script exporting T3CODE_HOME must59+ // not have this one command silently target the default install.60+ const envHome = Option.filter(yield* envT3Home, (value) => value.trim().length > 0);61+ const configuredBaseDir = Option.orElse(explicitBaseDir, () => envHome);62+ const baseDir = yield* resolveBaseDir(Option.getOrUndefined(configuredBaseDir));63+ const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {64+ baseDirIsExplicit: Option.isSome(configuredBaseDir),65+ });66+ return {67+ settingsPath: derivedPaths.settingsPath,68+ themesDir: derivedPaths.environmentThemesDir,69+ };70+});71+72+/** Reads the sparse settings object, tolerating a missing or empty file. */73+const readSettingsObject = Effect.fn(function* (settingsPath: string) {74+ const fs = yield* FileSystem.FileSystem;75+ const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));apps/server/src/cli/theme.ts line 108OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +88,21 @@88+const writeDefaultTheme = Effect.fn(function* (input: {89+ readonly settingsPath: string;90+ readonly themeId: string;91+}) {92+ const settings = yield* readSettingsObject(input.settingsPath);93+ const setAt = DateTime.formatIso(yield* DateTime.now);94+ const next =95+ input.themeId.length > 096+ ? // The timestamp is the set-generation: it lets clients apply a re-set97+ // of the same value they already applied once.98+ { ...settings, defaultTheme: input.themeId, defaultThemeSetAt: setAt }99+ : // Clearing removes the keys rather than storing empty strings, so the100+ // file reads the same as one that never set a theme.101+ Object.fromEntries(102+ Object.entries(settings).filter(103+ ([key]) => key !== "defaultTheme" && key !== "defaultThemeSetAt",104+ ),105+ );106+107+ const contents = yield* encodeSettingsJson(next);108+ yield* writeFileStringAtomically({ filePath: input.settingsPath, contents: `${contents}\n` });
- apps/web/src/hooks/useEnvironmentTheme.ts lines 61 to 61OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +41,21 @@41+ * exported theme file the Download button produces — so any theme someone42+ * shared can be dropped into the machine's themes directory as-is.43+ */44+export function environmentThemeDefinition(theme: EnvironmentTheme): ThemeDefinition {45+ const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};46+ for (const [variantAppearance, variantColors] of Object.entries(theme.variants ?? {})) {47+ if (variantAppearance === theme.appearance) continue;48+ variants[variantAppearance as ThemeAppearance] = publishedThemeColors(49+ theme,50+ variantAppearance as ThemeAppearance,51+ variantColors,52+ );53+ }54+55+ return {56+ id: theme.id,57+ label: theme.name,58+ appearance: theme.appearance,59+ colors: publishedThemeColors(theme, theme.appearance, theme.colors),60+ ...(Object.keys(variants).length > 0 ? { variants } : {}),61+ managed: true,apps/web/src/components/settings/ThemeSettings.tsx lines 836 to 836OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -811,0 +816,21 @@816+ // A saved theme with the same id wins resolution, so its card is817+ // the one that must show; rendering both would also collide keys.818+ (environmentTheme) => !customThemes.some((theme) => theme.id === environmentTheme.id),819+ )820+ .map((environmentTheme) => (821+ // No edit or remove: the environment republishes these palettes on822+ // every change, so anything saved here would be overwritten.823+ // Duplicating is the way to keep a copy.824+ <ThemeLibraryCard825+ activeModes={pickedModesFor(environmentTheme.id)}826+ isActive={false}827+ key={environmentTheme.id}828+ onDuplicate={() =>829+ openThemeEditor({830+ editingThemeId: null,831+ seedThemeId: environmentTheme.id,832+ seedName: `${environmentTheme.label} copy`,833+ initialAppearance,834+ })835+ }836+ onUse={() => persistTheme(environmentTheme.id)}
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/cli/theme.ts lines 296 to 297OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +277,21 @@277+ return yield* Effect.fail(new ThemeTargetMissingError());278+ }279+ const paths = yield* resolveThemePaths(flags.baseDir);280+281+ // An existing file publishes; anything path-shaped that does not exist282+ // is a mistake to surface, not an id to store; everything else must be283+ // a well-formed id, so a typo cannot be written as a theme no client284+ // will ever resolve.285+ const targetIsFile = yield* fs.exists(target).pipe(Effect.orElseSucceed(() => false));286+ const looksLikePath =287+ target.endsWith(".json") || target.includes("/") || target.includes("\\");288+ let themeId: string;289+ if (targetIsFile) {290+ themeId = yield* publishThemeFile({291+ themesDir: paths.themesDir,292+ filePath: target,293+ explicitId: flags.id,294+ });295+ } else if (looksLikePath) {296+ return yield* Effect.fail(297+ new ThemeFileUnreadableError({ filePath: target, cause: "no such file" }),apps/server/src/cli/theme.ts lines 153 to 170Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +98,21 @@98+ }99+}100+101+export class ThemePublishError extends Schema.TaggedErrorClass<ThemePublishError>()(102+ "ThemePublishError",103+ { themesDir: Schema.String, cause: Schema.Defect() },104+) {105+ override get message(): string {106+ return `Could not publish the theme into ${this.themesDir}.`;107+ }108+}109+110+export class ThemeIdInvalidError extends Schema.TaggedErrorClass<ThemeIdInvalidError>()(111+ "ThemeIdInvalidError",112+ { themeId: Schema.String, fromFile: Schema.Boolean },113+) {114+ override get message(): string {115+ const remedy = this.fromFile ? " Pass one with --id." : "";116+ return `"${this.themeId}" is not a valid theme id (lowercase letters, digits, and hyphens; not an appearance keyword).${remedy}`;117+ }118+}
- apps/server/src/environmentTheme.ts line 141OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +121,21 @@121+122+ // Debounced for the same reason settings watching is: a theme script emits123+ // several events per save and `fs.watch` can fire before the content is124+ // flushed. Every event triggers a full re-read, so no event needs filtering.125+ const watchEvents = fs.watch(environmentThemesDir).pipe(Stream.debounce(Duration.millis(100)));126+127+ // Seeds the dedupe so a watch event that reports no actual change (a touch,128+ // a rewrite with identical contents) does not retint every client.129+ yield* Ref.set(lastPublished, yield* readThemes);130+ yield* Stream.runForEach(watchEvents, () =>131+ publishIfChanged.pipe(Effect.ignoreCause({ log: true })),132+ ).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(watcherScope), Effect.asVoid);133+134+ return {135+ current: readThemes,136+ get streamChanges() {137+ return Stream.unwrap(138+ Effect.gen(function* () {139+ const subscription = yield* PubSub.subscribe(changes);140+ const current = yield* readThemes;141+ return Stream.concat(Stream.make(current), Stream.fromSubscription(subscription));
- apps/server/src/cli/theme.ts line 518Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +291,21 @@291+ return yield* Effect.fail(new ThemeTargetMissingError());292+ }293+ const paths = yield* resolveThemePaths(flags.baseDir);294+295+ // An existing file publishes; anything path-shaped that does not exist296+ // is a mistake to surface, not an id to store; everything else must be297+ // a well-formed id, so a typo cannot be written as a theme no client298+ // will ever resolve.299+ const targetIsFile = yield* fs.exists(target).pipe(Effect.orElseSucceed(() => false));300+ const looksLikePath =301+ target.endsWith(".json") || target.includes("/") || target.includes("\\");302+ let themeId: string;303+ if (targetIsFile) {304+ themeId = yield* publishThemeFile({305+ themesDir: paths.themesDir,306+ filePath: target,307+ explicitId: flags.id,308+ });309+ } else if (looksLikePath) {310+ return yield* Effect.fail(new ThemeFileUnreadableError({ filePath: target }));311+ } else if (isEnvironmentThemeId(target)) {apps/server/src/environmentTheme.ts line 125OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +105,21 @@105+ });106+ continue;107+ }108+ const file = decoded.value;109+ if (!environmentThemeFileHasColors(file)) {110+ yield* Effect.logWarning("ignoring environment theme without colors", { path: filePath });111+ continue;112+ }113+ themes.push({ id, ...file });114+ }115+ return themes;116+ });117+118+ /**119+ * Reads the directory and folds it into the sequenced state, publishing only120+ * a genuine change. Every reader goes through here, so the snapshot a client121+ * connects on and the events it then receives come from one ordered source122+ * rather than from disk and the queue independently.123+ */124+ const refresh = Effect.gen(function* () {125+ const themes = yield* readThemes;
- apps/server/src/environmentTheme.ts line 137OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +117,21 @@117+118+ /**119+ * Reads the directory and folds it into the sequenced state, publishing only120+ * a genuine change. Every reader goes through here, so the snapshot a client121+ * connects on and the events it then receives come from one ordered source122+ * rather than from disk and the queue independently.123+ */124+ const refresh = Effect.gen(function* () {125+ const themes = yield* readThemes;126+ // Structural equality over the whole decoded value: a hand-rolled field127+ // list here silently drops republishes for any field it forgets.128+ const [changed, next] = yield* Ref.modify(129+ published,130+ (previous): readonly [readonly [boolean, PublishedThemes], PublishedThemes] => {131+ if (Equal.equals(previous.themes, themes)) return [[false, previous], previous];132+ const updated: PublishedThemes = { seq: previous.seq + 1, themes };133+ return [[true, updated], updated];134+ },135+ );136+ if (changed) yield* PubSub.publish(changes, next).pipe(Effect.asVoid);137+ return next;
- apps/server/src/cli/theme.ts line 294OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +274,21 @@274+ }275+276+ yield* writeFileStringAtomically({277+ filePath: path.join(input.themesDir, `${themeId}.json`),278+ contents: raw.endsWith("\n") ? raw : `${raw}\n`,279+ }).pipe(Effect.mapError((cause) => new ThemePublishError({ themesDir: input.themesDir, cause })));280+ return themeId;281+});282+283+/**284+ * Ids a client can actually resolve: this build's built-ins plus whatever the285+ * machine publishes. A syntactically valid id that names nothing would be286+ * written as the environment's theme and then silently ignored by every287+ * client, with the command having reported success.288+ */289+const resolvableThemeIds = Effect.fn(function* (themesDir: string) {290+ const fs = yield* FileSystem.FileSystem;291+ const entries = yield* fs292+ .readDirectory(themesDir)293+ .pipe(Effect.orElseSucceed((): Array<string> => []));294+ const publishedIds = entries
- apps/server/src/cli/theme.ts line 298OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +278,21 @@278+ contents: raw.endsWith("\n") ? raw : `${raw}\n`,279+ }).pipe(Effect.mapError((cause) => new ThemePublishError({ themesDir: input.themesDir, cause })));280+ return themeId;281+});282+283+/**284+ * Ids a client can actually resolve: this build's built-ins plus whatever the285+ * machine publishes. A syntactically valid id that names nothing would be286+ * written as the environment's theme and then silently ignored by every287+ * client, with the command having reported success.288+ */289+const resolvableThemeIds = Effect.fn(function* (themesDir: string) {290+ const fs = yield* FileSystem.FileSystem;291+ const entries = yield* fs292+ .readDirectory(themesDir)293+ .pipe(Effect.orElseSucceed((): Array<string> => []));294+ const publishedIds = entries295+ .filter((entry) => entry.endsWith(".json"))296+ .map((entry) => entry.slice(0, -".json".length))297+ .filter(isEnvironmentThemeId);298+ return [MOBILE_DEFAULT_THEME_ID, ...BUILT_IN_THEME_IDS, ...publishedIds].toSorted();apps/server/src/cli/theme.ts line 298OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +278,21 @@278+ contents: raw.endsWith("\n") ? raw : `${raw}\n`,279+ }).pipe(Effect.mapError((cause) => new ThemePublishError({ themesDir: input.themesDir, cause })));280+ return themeId;281+});282+283+/**284+ * Ids a client can actually resolve: this build's built-ins plus whatever the285+ * machine publishes. A syntactically valid id that names nothing would be286+ * written as the environment's theme and then silently ignored by every287+ * client, with the command having reported success.288+ */289+const resolvableThemeIds = Effect.fn(function* (themesDir: string) {290+ const fs = yield* FileSystem.FileSystem;291+ const entries = yield* fs292+ .readDirectory(themesDir)293+ .pipe(Effect.orElseSucceed((): Array<string> => []));294+ const publishedIds = entries295+ .filter((entry) => entry.endsWith(".json"))296+ .map((entry) => entry.slice(0, -".json".length))297+ .filter(isEnvironmentThemeId);298+ return [MOBILE_DEFAULT_THEME_ID, ...BUILT_IN_THEME_IDS, ...publishedIds].toSorted();
- apps/web/src/hooks/useDefaultTheme.ts lines 66 to 67OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +47,21 @@47+ * until the environment's theme is set again. The environment's own published48+ * themes are valid targets, which is why this waits for an id that does not49+ * resolve yet — the setting and the palette it names arrive independently.50+ */51+export function useDefaultThemeAdoption(): void {52+ const environmentId = useAtomValue(primaryEnvironmentIdAtom);53+ const settings = useAtomValue(primaryServerSettingsAtom);54+ const { defaultTheme, defaultThemeSetAt } = settings;55+ const { setTheme } = useTheme();56+ // Re-runs adoption when a late-arriving published theme makes the57+ // requested id resolvable.58+ const environmentThemes = useEnvironmentThemeDefinitions();59+60+ useEffect(() => {61+ if (typeof window === "undefined") return;62+ if (environmentId === null || defaultTheme.length === 0) return;63+ const storageKey = `${APPLIED_DEFAULT_THEME_STORAGE_PREFIX}${environmentId}`;64+ const generation = defaultThemeGeneration(defaultTheme, defaultThemeSetAt);65+ if (readAppliedGeneration(storageKey) === generation) return;66+ if (getThemeDefinition(defaultTheme) === null) return;67+ if (setTheme(defaultTheme)) writeAppliedGeneration(storageKey, generation);
- apps/server/src/environmentTheme.ts line 201OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +181,21 @@181+ return themes;182+});183+184+/**185+ * Reads the directory and folds it into the sequenced state, publishing only186+ * a genuine change. Every reader goes through here, so the snapshot a client187+ * connects on and the events it then receives come from one ordered source188+ * rather than from disk and the queue independently.189+ */190+191+const make = Effect.gen(function* () {192+ const { environmentThemesDir } = yield* ServerConfig.ServerConfig;193+ const fs = yield* FileSystem.FileSystem;194+ const pathService = yield* Path.Path;195+ /**196+ * Every observed set carries a sequence number, so a subscriber can drop197+ * queued events that predate the snapshot it started from. Without it a198+ * publish landing between subscribing and reading replays after the newer199+ * value and walks clients backwards onto stale colors.200+ */201+ const changes = yield* PubSub.unbounded<PublishedThemes>();apps/web/src/hooks/useDefaultTheme.ts lines 100 to 106Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +83,21 @@83+ if (typeof window === "undefined" || environmentId === null) return;84+ const storageKey = `${APPLIED_DEFAULT_THEME_STORAGE_PREFIX}${environmentId}`;85+ const definition = getThemeDefinition(defaultTheme);86+ const generation = defaultThemeToApply({87+ environmentId,88+ defaultTheme,89+ defaultThemeSetAt,90+ appliedGeneration: readAppliedGeneration(storageKey),91+ resolves: definition !== null,92+ });93+ if (generation === null || definition === null) return;94+95+ // Deliberately not the card's rule. Clicking a card is a user choosing one96+ // half of their own mix; a set theme is the environment saying what this97+ // client opens on, so it takes the base preference and, for a98+ // single-appearance theme, the matching mode -- otherwise a dark-only99+ // theme on a light client is recorded as applied while nothing changes.100+ if (!setTheme(defaultTheme)) return;101+ const half = singleAppearanceOf(definition);102+ if (half !== null) setAppearanceMode(half);103+ writeAppliedGeneration(storageKey, generation);apps/server/src/environmentTheme.ts line 151OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +131,21 @@131+ // link pointing anywhere on the machine. Requiring the resolved target to132+ // stay in this directory is what actually confines it; the type check then133+ // stops a FIFO or device node from blocking the read forever.134+ const resolved = yield* fs.realPath(filePath).pipe(Effect.option);135+ const info = yield* fs.stat(filePath).pipe(Effect.option);136+ const usable =137+ Option.isSome(resolvedDir) &&138+ Option.isSome(resolved) &&139+ resolved.value === path.join(resolvedDir.value, entry) &&140+ Option.isSome(info) &&141+ info.value.type === "File" &&142+ Number(info.value.size) <= MAX_THEME_FILE_BYTES;143+ if (!usable) {144+ yield* Effect.logWarning("ignoring unusable environment theme file", {145+ path: filePath,146+ limit: MAX_THEME_FILE_BYTES,147+ });148+ continue;149+ }150+151+ const raw = yield* fs.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));apps/server/src/cli/theme.ts line 301OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +281,21 @@281+ readonly explicitId: Option.Option<string>;282+}) {283+ const fs = yield* FileSystem.FileSystem;284+ const path = yield* Path.Path;285+ // Checked before reading, not after: a FIFO or device node would block the286+ // command forever, and a huge file would be pulled into memory first.287+ const info = yield* fs288+ .stat(input.filePath)289+ .pipe(290+ Effect.mapError((cause) => new ThemeFileUnreadableError({ filePath: input.filePath, cause })),291+ );292+ if (info.type !== "File") {293+ return yield* Effect.fail(new ThemeFileUnreadableError({ filePath: input.filePath }));294+ }295+ if (Number(info.size) > MAX_THEME_FILE_BYTES) {296+ return yield* Effect.fail(297+ new ThemeFileTooLargeError({ filePath: input.filePath, limit: MAX_THEME_FILE_BYTES }),298+ );299+ }300+301+ const raw = yield* fs
- apps/web/src/components/settings/ThemeSettings.tsx lines 843 to 846Resolvedby ryanrhughes(GitHub profile, opens in a new tab)@@ -811,0 +820,21 @@820+ )821+ .map((environmentTheme) => (822+ // No edit or remove: the environment republishes these palettes on823+ // every change, so anything saved here would be overwritten.824+ // Duplicating is the way to keep a copy.825+ <ThemeLibraryCard826+ activeModes={pickedModesFor(environmentTheme.id)}827+ isActive={false}828+ key={environmentTheme.id}829+ onDuplicate={() =>830+ openThemeEditor({831+ editingThemeId: null,832+ seedThemeId: environmentTheme.id,833+ seedName: `${environmentTheme.label} copy`,834+ initialAppearance,835+ })836+ }837+ onUse={() => {838+ const half = singleAppearanceOf(environmentTheme);839+ if (half === null) persistTheme(environmentTheme.id);840+ else assignHalf(half, environmentTheme.id);
- apps/server/src/cli/theme.ts line 388OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +368,21 @@368+ // An existing file publishes; anything path-shaped that does not exist369+ // is a mistake to surface, not an id to store; everything else must be370+ // a well-formed id, so a typo cannot be written as a theme no client371+ // will ever resolve.372+ // Path-shaped first, existence second. Deciding on existence alone would373+ // make `t3 theme set ocean` publish ./ocean whenever the cwd happens to374+ // hold a file by that name, instead of selecting the built-in.375+ const looksLikePath =376+ target.endsWith(".json") ||377+ target.includes("/") ||378+ target.includes("\\") ||379+ target.startsWith("~");380+ const targetIsFile =381+ looksLikePath && (yield* fs.exists(target).pipe(Effect.orElseSucceed(() => false)));382+ let themeId: string;383+ if (targetIsFile) {384+ // Settings are preflighted before publishing, so a settings file the385+ // set step cannot read or parse fails the command before it mutates386+ // the themes directory.387+ yield* readSettingsObject(paths.settingsPath);388+ themeId = yield* publishThemeFile({
- apps/server/src/cli/theme.ts line 354OutdatedResolvedby ryanrhughes(GitHub profile, opens in a new tab)@@ -0,0 +334,21 @@334+ const themeId = Option.getOrElse(input.explicitId, () => fileBasename);335+ // The same rules the watcher applies when it reads the directory back, so a336+ // publish cannot report success for a file that will then be skipped.337+ if (!isEnvironmentThemeId(themeId) || UNPUBLISHABLE_THEME_IDS.has(themeId)) {338+ return yield* Effect.fail(new ThemeFileIdInvalidError({ themeId, filePath: input.filePath }));339+ }340+341+ const destinationPath = path.join(input.themesDir, `${themeId}.json`);342+ // Captured for rollback: publish-and-set is one command, so a failure after343+ // this write must put the directory back rather than leave a half-applied344+ // publish, or a clobbered previous theme, behind.345+ const previous = readThemeFileGuarded(destinationPath, MAX_THEME_FILE_BYTES);346+ // An occupied destination the rollback could not faithfully restore -- a347+ // symlink, an oversized file, anything unreadable -- is refused rather than348+ // clobbered, since a failed set would then delete it.349+ if (previous === null && themeEntryExists(destinationPath)) {350+ return yield* Effect.fail(new ThemeDestinationBlockedError({ destinationPath }));351+ }352+ // Written verbatim: appending so much as a newline could push a file at353+ // the size limit past it and have the watcher skip what was just accepted.354+ yield* writeFileStringAtomically({
- @@ -0,0 +301,21 @@301+ const info = yield* fs302+ .stat(input.filePath)303+ .pipe(304+ Effect.mapError((cause) => new ThemeFileUnreadableError({ filePath: input.filePath, cause })),305+ );306+ if (info.type !== "File") {307+ return yield* Effect.fail(new ThemeFileUnreadableError({ filePath: input.filePath }));308+ }309+ if (Number(info.size) > MAX_THEME_FILE_BYTES) {310+ return yield* Effect.fail(311+ new ThemeFileTooLargeError({ filePath: input.filePath, limit: MAX_THEME_FILE_BYTES }),312+ );313+ }314+315+ // The stat above is diagnostic, naming the failure precisely. The read goes316+ // through one opened handle, so its type and size checks bind to the file317+ // actually read even if the path was swapped since the stat.318+ const raw = readThemeFileGuarded(input.filePath, MAX_THEME_FILE_BYTES);319+ if (raw === null) {320+ return yield* Effect.fail(new ThemeFileUnreadableError({ filePath: input.filePath }));321+ }
- apps/server/src/cli/theme.ts line 366Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +344,21 @@344+ const destinationPath = path.join(input.themesDir, `${themeId}.json`);345+ // Neither ends in `.json`, so the watcher never mistakes them for themes.346+ const backupPath = `${destinationPath}.rollback`;347+ const stagingPath = `${destinationPath}.staging`;348+ yield* fs349+ .makeDirectory(input.themesDir, { recursive: true })350+ .pipe(Effect.mapError((cause) => new ThemePublishError({ themesDir: input.themesDir, cause })));351+352+ const publishFailure = (cause: unknown) =>353+ new ThemePublishError({ themesDir: input.themesDir, cause });354+355+ // Staged in full before anything moves, so the commit below is two adjacent356+ // renames with no I/O between them. The staging entry is created O_EXCL357+ // after clearing any stale leftover, so a symlink or file already at that358+ // predictable name is never followed or written through. Written verbatim:359+ // appending so much as a newline could push a file at the size limit past360+ // it and have the watcher skip what was just accepted.361+ yield* Effect.try({362+ try: () => {363+ try {364+ NodeFS.unlinkSync(stagingPath);
- apps/server/src/cli/theme.ts line 413OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +393,21 @@393+ const hadPrevious = yield* Effect.try({394+ try: () => {395+ try {396+ NodeFS.renameSync(destinationPath, backupPath);397+ return true;398+ } catch (error) {399+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;400+ throw error;401+ }402+ },403+ catch: publishFailure,404+ });405+406+ const revert = Effect.sync(() => {407+ try {408+ NodeFS.unlinkSync(stagingPath);409+ } catch {410+ // Usually already renamed away; a stray staging file is watcher-inert.411+ }412+ try {413+ if (hadPrevious) NodeFS.renameSync(backupPath, destinationPath);
- apps/web/src/components/settings/ThemeSettings.tsx lines 843 to 846Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -811,0 +820,21 @@820+ )821+ .map((environmentTheme) => (822+ // No edit or remove: the environment republishes these palettes on823+ // every change, so anything saved here would be overwritten.824+ // Duplicating is the way to keep a copy.825+ <ThemeLibraryCard826+ activeModes={pickedModesFor(environmentTheme.id)}827+ isActive={false}828+ key={environmentTheme.id}829+ onDuplicate={() =>830+ openThemeEditor({831+ editingThemeId: null,832+ seedThemeId: environmentTheme.id,833+ seedName: `${environmentTheme.label} copy`,834+ initialAppearance,835+ })836+ }837+ onUse={() => {838+ const half = singleAppearanceOf(environmentTheme);839+ if (half === null) persistTheme(environmentTheme.id);840+ else assignHalf(half, environmentTheme.id);
github-actions[bot](GitHub profile, opens in a new tab) removed labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
- @@ -419,0 +433,21 @@433+ * Matches the client-side theme id rule, so a published id is selectable.434+ * The appearance keywords are excluded outright: a published `dark.json`435+ * would otherwise capture every client whose stored preference is the stock436+ * `"dark"`, retinting people who never chose it.437+ */438+export const EnvironmentThemeId = Schema.String.check(439+ Schema.isPattern(/^(?!(?:system|light|dark)$)[a-z0-9](?:[a-z0-9-]{0,47})$/),440+);441+export type EnvironmentThemeId = typeof EnvironmentThemeId.Type;442+443+/**444+ * Role colors as published. Values are any CSS color the client's theme445+ * parser accepts (exported theme files use oklch), canonicalized client-side;446+ * roles a build does not know are dropped there, so a machine may publish447+ * roles a newer client added without breaking an older one. Keys must still448+ * be role-shaped and values color-sized, so the record stays open to future449+ * vocabulary without being an arbitrary-payload channel.450+ */451+const EnvironmentThemeColors = Schema.Record(452+ Schema.String.check(Schema.isPattern(/^[a-zA-Z][a-zA-Z0-9]{0,63}$/)),453+ TrimmedNonEmptyString.check(Schema.isMaxLength(64)),
- apps/server/src/environmentTheme.ts line 247Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +227,21 @@227+ * order and a slower read of an older set would publish under a higher228+ * sequence -- which the subscriber filter, ordering publications rather than229+ * observations, could not then drop.230+ */231+ const refreshSemaphore = yield* Semaphore.make(1);232+ const watcherScope = yield* Scope.make("sequential");233+ yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));234+235+ const refresh = refreshSemaphore.withPermits(1)(236+ Effect.gen(function* () {237+ const themes = yield* readPublishedThemes(environmentThemesDir).pipe(238+ Effect.provideService(FileSystem.FileSystem, fs),239+ );240+ // Structural equality over the whole decoded value: a hand-rolled field241+ // list here silently drops republishes for any field it forgets.242+ const [changed, next] = yield* Ref.modify(243+ published,244+ (previous): readonly [readonly [boolean, PublishedThemes], PublishedThemes] => {245+ if (Equal.equals(previous.themes, themes)) return [[false, previous], previous];246+ const updated: PublishedThemes = { seq: previous.seq + 1, themes };247+ return [[true, updated], updated];
- apps/server/src/environmentTheme.ts line 135Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +115,21 @@115+ const read = NodeFS.readSync(fd, contents, offset, contents.length - offset, offset);116+ if (read <= 0) break;117+ offset += read;118+ }119+ return contents.subarray(0, offset).toString("utf8");120+ } catch {121+ return null;122+ } finally {123+ NodeFS.closeSync(fd);124+ }125+};126+127+/**128+ * Every theme the directory actually publishes. A file that is missing,129+ * unreadable, malformed, colorless, or misnamed is simply skipped; the rest of130+ * the set is unaffected. The one place that decides what "published" means, so131+ * a caller validating an id cannot disagree with the watcher serving it.132+ */133+export const readPublishedThemes = Effect.fn(function* (themesDir: string) {134+ const fs = yield* FileSystem.FileSystem;135+ const entries = yield* fs
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
4f8db60d-703d-45f1-81b0-7a8df0dd2671You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Comment `@coderabbitai help` to get the list of available commands.