Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions apps/server/src/assets/AssetAccess.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,30 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(layerTest)),
);

it.effect("serves the background image published beside an environment theme", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
yield* fs.makeDirectory(environmentThemesDir, { recursive: true });
const imagePath = `${environmentThemesDir}/frieren.png`;
yield* fs.writeFile(imagePath, screenshotPng);
const result = yield* issueAssetUrl({
resource: { _tag: "environment-theme-background", themeId: "frieren" },
});
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separator = suffix.indexOf("/");
const token = suffix.slice(0, separator);
const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
expect(asset).toMatchObject({ kind: "file", path: yield* fs.realPath(imagePath) });
if (asset?.kind !== "file") return;
const response = yield* assetFileResponse(asset);
expect(response.headers["content-type"]).toBe("image/png");

yield* fs.remove(imagePath);
expect(yield* resolveAsset(token, suffix.slice(separator + 1))).toBeNull();
}).pipe(Effect.scoped, Effect.provide(layerTest)),
);

it.effect("issues exact URLs for media and browser documents outside the workspace", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
Expand Down
37 changes: 37 additions & 0 deletions apps/server/src/assets/AssetAccess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
ThreadId,
NativeAppIconReference,
TurnItemId,
EnvironmentThemeId,
} from "@t3tools/contracts";
import {
hostPreviewMimeTypeFromExtension,
Expand Down Expand Up @@ -52,6 +53,7 @@ import * as AssetSigner from "./AssetSigner.ts";
import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
import * as ServerConfig from "../config.ts";
import { findThemeBackground } from "../environmentTheme.ts";
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
Expand Down Expand Up @@ -168,6 +170,12 @@ const AssetClaimsSchema = Schema.Union([
app: NativeAppIconReference,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("environment-theme-background"),
themeId: EnvironmentThemeId,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("tool-output-image"),
Expand Down Expand Up @@ -834,6 +842,17 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
imageDimensions = readImageDimensions(image.bytes);
break;
}
case "environment-theme-background": {
// Published themes go to every client, so any client may read their backgrounds.
claims = {
version: 1,
kind: "environment-theme-background",
themeId: input.resource.themeId,
expiresAt,
};
fileName = `${input.resource.themeId}-background`;
break;
}
case "native-app-icon": {
claims = {
version: 1,
Expand Down Expand Up @@ -982,6 +1001,24 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
return image ? ({ kind: "bytes", ...image } satisfies ResolvedAsset) : null;
}

if (claims.kind === "environment-theme-background") {
const config = yield* ServerConfig.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
// The themes directory may be a symlink; openMediaFile refuses any path that is not canonical.
const themesDir = yield* fileSystem
.realPath(config.environmentThemesDir)
.pipe(Effect.orElseSucceed(() => null));
const background = themesDir === null ? null : findThemeBackground(themesDir, claims.themeId);
if (background === null) return null;
const file = yield* openMediaFile(background.path).pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to open theme background.", { path: background.path, cause }),
),
Effect.orElseSucceed(() => null),
);
return file ? ({ kind: "file", path: background.path, file } satisfies ResolvedAsset) : null;
}

if (claims.kind === "native-app-icon") {
const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver;
const iconPath = yield* nativeAppIconResolver.resolve(claims.app);
Expand Down
29 changes: 29 additions & 0 deletions apps/server/src/environmentTheme.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,35 @@ it.layer(NodeServices.layer)("environment theme", (it) => {
);
});

it.effect(
"reports the image beside a theme as its background, with a new revision per file",
() =>
withEnvironmentThemes(
{ "look.json": encodeThemeFile(NIGHTFALL_THEME), "look.png": "first" },
Effect.gen(function* () {
const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const background = Effect.map(currentThemes, (themes) => themes[0]?.background);
const image = path.join(environmentThemesDir, "look.png");

const first = yield* background;
assert.isDefined(first);
yield* fs.writeFileString(image, "a longer second image");
assert.notStrictEqual(yield* background, first);

yield* fs.remove(image);
assert.isUndefined(yield* background);
if (symlinksSupported) {
const outside = path.join(environmentThemesDir, "..", "outside.png");
yield* fs.writeFileString(outside, "outside");
yield* fs.symlink(outside, image);
assert.isUndefined(yield* background);
}
}),
),
);

it.effect("keeps the served theme when an update does not fit the size limit", () => {
const large = (name: string): EnvironmentThemeFile => ({
...NIGHTFALL_THEME,
Expand Down
45 changes: 42 additions & 3 deletions apps/server/src/environmentTheme.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off - the guarded file read needs open
// flags (O_NOFOLLOW, O_NONBLOCK) the FileSystem service does not expose.
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";

import {
type DefaultAppearancePreference,
Expand Down Expand Up @@ -52,6 +53,10 @@ const MAX_THEME_FILES = 32;
export const MAX_THEME_FILE_BYTES = 6 * THEME_CSS_MAX_LENGTH + 16 * 1024;
const MAX_THEME_TOTAL_BYTES = 6 * MAX_THEME_FILE_BYTES;

/** A theme's background is `<id>.<extension>` beside `<id>.json`; earlier extensions win. */
const THEME_BACKGROUND_EXTENSIONS = ["webp", "png", "jpg", "jpeg"] as const;
const MAX_THEME_BACKGROUND_BYTES = 16 * 1024 * 1024;

interface PublishedThemes {
readonly seq: number;
readonly themes: ReadonlyArray<EnvironmentTheme>;
Expand Down Expand Up @@ -101,6 +106,8 @@ export class EnvironmentThemeService extends Context.Service<
readonly read: (themeId?: string) => Effect.Effect<
{
readonly current: string;
/** Where theme files and their background images live. */
readonly themesDir: string;
readonly themes: ReadonlyArray<EnvironmentTheme>;
readonly theme?: EnvironmentTheme;
},
Expand Down Expand Up @@ -173,13 +180,43 @@ export const readThemeFileGuarded = (filePath: string, maxBytes: number): string
}
};

/**
* The background image published beside `themeId`, if any. Symlinks and oversized files are
* skipped. `entries` lets a directory scan skip lookups for names it did not list.
*/
export function findThemeBackground(
themesDir: string,
themeId: string,
entries?: ReadonlySet<string>,
): { readonly path: string; readonly revision: string } | null {
for (const extension of THEME_BACKGROUND_EXTENSIONS) {
const name = `${themeId}.${extension}`;
if (entries !== undefined && !entries.has(name)) continue;
// Native separators: the asset route refuses a path that differs from its canonical form.
const filePath = NodePath.join(themesDir, name);
let info: NodeFS.BigIntStats;
try {
info = NodeFS.lstatSync(filePath, { bigint: true });
} catch {
continue;
}
if (!info.isFile() || info.size > MAX_THEME_BACKGROUND_BYTES) continue;
return {
path: filePath,
revision: [info.ino, info.size, info.mtimeNs].map((part) => part.toString(36)).join("-"),
};
}
return null;
}

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> = [];
const entryNames = new Set(entries);
let examined = 0;
let totalBytes = 0;
for (const entry of entries.toSorted()) {
Expand Down Expand Up @@ -232,7 +269,8 @@ export const readPublishedThemes = Effect.fn(function* (themesDir: string) {
break;
}

themes.push({ id, ...file });
const background = findThemeBackground(themesDir, id, entryNames);
themes.push({ id, ...file, ...(background ? { background: background.revision } : {}) });
}
return themes;
});
Expand Down Expand Up @@ -406,7 +444,8 @@ const make = Effect.gen(function* () {
)(function* (themeId) {
const { themes } = yield* refresh;
const { defaultTheme } = yield* settings.getSettings;
if (themeId === undefined) return { current: defaultTheme, themes };
const themesDir = environmentThemesDir;
if (themeId === undefined) return { current: defaultTheme, themesDir, themes };
const theme = themes.find((candidate) => candidate.id === themeId);
if (theme === undefined) {
return yield* new EnvironmentThemeRefusedError({
Expand All @@ -415,7 +454,7 @@ const make = Effect.gen(function* () {
known: themes.map(({ id }) => id),
});
}
return { current: defaultTheme, themes, theme };
return { current: defaultTheme, themesDir, themes, theme };
});

return {
Expand Down
11 changes: 9 additions & 2 deletions apps/server/src/mcp/toolkits/theme/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const layer = McpToolAccess.toLayer(ThemeToolkit, {
const themes = yield* EnvironmentTheme.EnvironmentThemeService;
const {
current,
themesDir,
themes: published,
theme,
} = yield* themes.read(themeId).pipe(
Expand All @@ -30,8 +31,14 @@ export const layer = McpToolAccess.toLayer(ThemeToolkit, {
return {
current,
builtIn: BUILT_IN_THEME_IDS,
published: published.map(({ id, name, css }) => ({ id, name, hasCss: Boolean(css) })),
...(theme === undefined ? {} : { theme: Struct.omit(theme, ["id"]) }),
published: published.map(({ id, name, css, background }) => ({
id,
name,
hasCss: Boolean(css),
hasBackground: background !== undefined,
})),
...(theme === undefined ? {} : { theme: Struct.omit(theme, ["id", "background"]) }),
themesDir,
guide: THEME_GUIDE,
};
}),
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/mcp/toolkits/theme/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@ const ThemeReadTool = Tool.make("t3_theme_read", {
id: EnvironmentThemeId,
name: Schema.String,
hasCss: Schema.Boolean,
hasBackground: Schema.Boolean,
}),
),
theme: Schema.optionalKey(EnvironmentThemeFile),
themesDir: Schema.String,
guide: Schema.String,
}),
})
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3031,6 +3031,7 @@ export const layerWsRpc = (
if (
input.resource._tag === "attachment" ||
input.resource._tag === "native-app-icon" ||
input.resource._tag === "environment-theme-background" ||
input.resource._tag === "tool-output-image" ||
input.resource._tag === SOURCE_CONTROL_MEDIA_ASSET ||
// A network path is served only from the thread's project, looked up below.
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/appInit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
} from "./composerDraftStore";
import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme";
import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme";
import { startThemeBackground } from "./themeBackground";
import { readLocalStorageValue, subscribeLocalStorageKey } from "./hooks/useLocalStorage";
import { startHostEnvironmentLookup } from "./state/primaryEnvironment";
import {
Expand Down Expand Up @@ -264,6 +265,7 @@ export function startAppServices(): AppRouter {
startDocumentTitle(router);
startHostEnvironmentLookup();
startEnvironmentThemeRepaint();
startThemeBackground();
startBrowserChromeThemeSync(router);
startDefaultThemeAdoption();
startModelPreferencesMigration();
Expand Down
96 changes: 96 additions & 0 deletions apps/web/src/themeBackground.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";

import { appAtomRegistry, subscribeAtomChanges } from "./rpc/atomRegistry";
import { assetEnvironment } from "./state/assets";
import { themeEnvironmentIdAtom } from "./state/primaryEnvironment";
import { themeServerEnvironmentThemesAtom } from "./state/server";
import { environmentSession } from "./state/session";

const THEME_BACKGROUND_VARIABLE = "--theme-background-image";

let shownKey: string | null = null;
let loading: AbortController | null = null;
let objectUrl: string | null = null;

function show(nextUrl: string | null): void {
const root = document.documentElement;
if (nextUrl === null) root.style.removeProperty(THEME_BACKGROUND_VARIABLE);
else root.style.setProperty(THEME_BACKGROUND_VARIABLE, `url("${nextUrl}")`);
if (objectUrl !== null) URL.revokeObjectURL(objectUrl);
objectUrl = nextUrl;
}

async function loadBackground(
environmentId: EnvironmentId,
themeId: string,
signal: AbortSignal,
): Promise<string | null> {
const minted = await executeAtomQuery(
appAtomRegistry,
assetEnvironment.createUrl({
environmentId,
input: { resource: { _tag: "environment-theme-background", themeId } },
}),
{ label: "theme background", reportFailure: false, refresh: true, signal },
);
const connection = appAtomRegistry.get(
environmentSession.preparedConnectionValueAtom(environmentId),
);
if (minted._tag !== "Success" || connection._tag === "None") return null;
const url = resolveAssetUrl(connection.value.httpBaseUrl, minted.value.relativeUrl);
if (url === null) return null;
const response = await fetch(url, { signal });
if (!response.ok) return null;
const image = await response.blob();
return image.type.startsWith("image/") ? URL.createObjectURL(image) : null;
}

/**
* Sets `--theme-background-image` to the image published beside `themeId`, or clears it.
* The image is copied into a blob URL once per revision, so the signed URL may expire.
*/
export function applyThemeBackground(themeId: string | undefined): void {
if (typeof document === "undefined") return;
const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom);
const revision =
themeId === undefined
? undefined
: appAtomRegistry.get(themeServerEnvironmentThemesAtom)?.find((theme) => theme.id === themeId)
?.background;
const key =
environmentId === null || themeId === undefined || revision === undefined
? null
: JSON.stringify([environmentId, themeId, revision]);
if (key === shownKey) return;
shownKey = key;
loading?.abort();
loading = null;
// The previous image must not show under the next theme while it loads.
show(null);
if (environmentId === null || themeId === undefined || key === null) return;
const controller = new AbortController();
loading = controller;
const failed = () => {
if (controller.signal.aborted) return;
// Lets the next repaint try again.
shownKey = null;
};
loadBackground(environmentId, themeId, controller.signal).then((url) => {
if (controller.signal.aborted) {
if (url !== null) URL.revokeObjectURL(url);
return;
}
loading = null;
if (url === null) failed();
else show(url);
}, failed);
}

/** A new image revision does not change the palette, so it does not repaint the theme. */
export function startThemeBackground(): () => void {
return subscribeAtomChanges(themeServerEnvironmentThemesAtom, () =>
applyThemeBackground(document.documentElement.dataset.themeId),
);
}
Loading
Loading