:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): add generic on-disk cache (#90679)
Charles Vien8575cccc497c
diff --git a/products/desktop/apps/code/src/main/bootstrap.ts b/products/desktop/apps/code/src/main/bootstrap.tsindex 7b7a12b6122b..166c1328f773 100644--- a/products/desktop/apps/code/src/main/bootstrap.ts+++ b/products/desktop/apps/code/src/main/bootstrap.ts@@ -124,6 +124,15 @@ protocol.registerSchemesAsPrivileged([corsEnabled: false,},},+ {+ scheme: "posthog-cache",+ privileges: {+ standard: true,+ secure: true,+ supportFetchAPI: true,+ corsEnabled: false,+ },+ },]);// Now dynamically import the rest of the application.diff --git a/products/desktop/apps/code/src/main/di/bindings.ts b/products/desktop/apps/code/src/main/di/bindings.tsindex 5654d04a9960..3d80c5653a3c 100644--- a/products/desktop/apps/code/src/main/di/bindings.ts+++ b/products/desktop/apps/code/src/main/di/bindings.ts@@ -118,6 +118,7 @@ import type { CRYPTO_SERVICE } from "@posthog/platform/crypto";import type { DEEP_LINK_SERVICE } from "@posthog/platform/deep-link";import type { DEV_HOST_ACTIONS_SERVICE } from "@posthog/platform/dev-host-actions";import type { DIALOG_SERVICE } from "@posthog/platform/dialog";+import type { DISK_CACHE_SERVICE } from "@posthog/platform/disk-cache";import type { FILE_ICON_SERVICE } from "@posthog/platform/file-icon";import type { IMAGE_PROCESSOR_SERVICE } from "@posthog/platform/image-processor";import type { MAIN_WINDOW_SERVICE } from "@posthog/platform/main-window";@@ -257,6 +258,7 @@ import type { DevLogsService } from "../services/dev-logs/service";import type { DevMetricsService } from "../services/dev-metrics/service";import type { DevNetworkService } from "../services/dev-network/service";import type { DiscordPresenceService } from "../services/discord-presence/service";+import type { DiskCache } from "../services/disk-cache/service";import type { EncryptionService } from "../services/encryption/service";import type { SecureStoreService } from "../services/secure-store/service";import type { settingsStore } from "../services/settingsStore";@@ -335,6 +337,7 @@ export interface MainBindings {[WORKSPACE_SETTINGS_SERVICE]: ElectronWorkspaceSettings;[APP_METRICS_SERVICE]: ElectronAppMetrics;[DEV_HOST_ACTIONS_SERVICE]: ElectronDevHostActions;+ [DISK_CACHE_SERVICE]: DiskCache;// Database (main aliases + ws-server source tokens via toService)[MAIN_DATABASE_SERVICE]: DatabaseService;diff --git a/products/desktop/apps/code/src/main/di/container.ts b/products/desktop/apps/code/src/main/di/container.tsindex 327c09377100..bd315058bb24 100644--- a/products/desktop/apps/code/src/main/di/container.ts+++ b/products/desktop/apps/code/src/main/di/container.ts@@ -1,6 +1,7 @@import "reflect-metadata";import { readFile as fsReadFile, stat as fsStat } from "node:fs/promises";+import { join } from "node:path";import { TypedContainer } from "@inversifyjs/strongly-typed";import { DEFAULT_GATEWAY_MODEL } from "@posthog/agent/gateway-models";import {@@ -107,6 +108,7 @@ import { CRYPTO_SERVICE } from "@posthog/platform/crypto";import { DEEP_LINK_SERVICE } from "@posthog/platform/deep-link";import { DEV_HOST_ACTIONS_SERVICE } from "@posthog/platform/dev-host-actions";import { DIALOG_SERVICE } from "@posthog/platform/dialog";+import { DISK_CACHE_SERVICE } from "@posthog/platform/disk-cache";import { FILE_ICON_SERVICE } from "@posthog/platform/file-icon";import { IMAGE_PROCESSOR_SERVICE } from "@posthog/platform/image-processor";import { MAIN_WINDOW_SERVICE } from "@posthog/platform/main-window";@@ -266,6 +268,7 @@ import { DevLogsService } from "../services/dev-logs/service";import { DevMetricsService } from "../services/dev-metrics/service";import { DevNetworkService } from "../services/dev-network/service";import { DiscordPresenceService } from "../services/discord-presence/service";+import { DiskCache } from "../services/disk-cache/service";import { EncryptionService } from "../services/encryption/service";import { SecureStoreService } from "../services/secure-store/service";import { settingsStore } from "../services/settingsStore";@@ -734,6 +737,21 @@ container.to(SecureStoreService).inSingletonScope();container.bind(SECURE_STORE_SERVICE).toService(MAIN_SECURE_STORE_SERVICE);+container+ .bind(DISK_CACHE_SERVICE)+ .toDynamicValue(+ (ctx) =>+ new DiskCache({+ // Not "cache": userData already holds Chromium's "Cache" directory, and+ // case-insensitive file systems (default macOS, Windows) treat the two+ // as one path, so clear() would delete the live browser cache.+ rootDir: join(+ ctx.get<ElectronStoragePaths>(STORAGE_PATHS_SERVICE).appDataPath,+ "disk-cache",+ ),+ }),+ )+ .inSingletonScope();container.bind(SPEECH_SYNTHESIZER_SERVICE).to(ElevenLabsSpeechService)diff --git a/products/desktop/apps/code/src/main/index.ts b/products/desktop/apps/code/src/main/index.tsindex ed391c1e8648..f1adfd5fd4ff 100644--- a/products/desktop/apps/code/src/main/index.ts+++ b/products/desktop/apps/code/src/main/index.ts@@ -37,6 +37,7 @@ import type { UpdatesService } from "@posthog/core/updates/updates";import { CONNECTIVITY_CLIENT } from "@posthog/host-router/ports/connectivity-client";import { ENVIRONMENT_CLIENT } from "@posthog/host-router/ports/environment-client";import { FILE_WATCHER_CONTROL } from "@posthog/host-router/ports/file-watcher-control";+import { DISK_CACHE_SERVICE } from "@posthog/platform/disk-cache";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import type { DatabaseService } from "@posthog/workspace-server/db/service";import type { ExternalAppsService } from "@posthog/workspace-server/services/external-apps/external-apps";@@ -74,6 +75,7 @@ import {} from "./di/tokens";import { setupExternalLinkPermissionHandlers } from "./external-links";import { posthogNodeAnalytics } from "./platform-adapters/posthog-analytics";+import { registerDiskCacheProtocol } from "./protocols/disk-cache";import { registerMcpSandboxProtocol } from "./protocols/mcp-sandbox";import { destroyQuickAskWindow, setupQuickAsk } from "./quick-ask";import type { AppLifecycleService } from "./services/app-lifecycle/service";@@ -375,6 +377,7 @@ async function boot(): Promise<void> {ensureClaudeConfigDir();setupExternalLinkPermissionHandlers(session.fromPartition("persist:main"));registerMcpSandboxProtocol();+ registerDiskCacheProtocol(container.get(DISK_CACHE_SERVICE));installRendererNetworkLogging(session.fromPartition("persist:main").webRequest,container.get<DevNetworkService>(DEV_NETWORK_SERVICE),diff --git a/products/desktop/apps/code/src/main/protocols/disk-cache.ts b/products/desktop/apps/code/src/main/protocols/disk-cache.tsnew file mode 100644index 000000000000..5befcfc644c0--- /dev/null+++ b/products/desktop/apps/code/src/main/protocols/disk-cache.ts@@ -0,0 +1,20 @@+import { electronNetFetch } from "@main/platform-adapters/electron-net-fetch";+import {+ CACHED_IMAGE_NAMESPACE_MAX_BYTES,+ createCachedImageHandler,+} from "@main/services/disk-cache/images";+import type { DiskCache } from "@main/services/disk-cache/service";+import { DISK_CACHE_SCHEME } from "@shared/disk-cache-protocol";+import { session } from "electron";++export function registerDiskCacheProtocol(diskCache: DiskCache): void {+ session.fromPartition("persist:main").protocol.handle(+ DISK_CACHE_SCHEME,+ createCachedImageHandler(+ diskCache.namespace("images", {+ maxBytes: CACHED_IMAGE_NAMESPACE_MAX_BYTES,+ }),+ electronNetFetch,+ ),+ );+}diff --git a/products/desktop/apps/code/src/main/services/disk-cache/images.test.ts b/products/desktop/apps/code/src/main/services/disk-cache/images.test.tsnew file mode 100644index 000000000000..03c0a44e5ccc--- /dev/null+++ b/products/desktop/apps/code/src/main/services/disk-cache/images.test.ts@@ -0,0 +1,189 @@+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import type { FetchLike } from "@posthog/core/auth/auth";+import { toCachedImageUrl } from "@shared/disk-cache-protocol";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createCachedImageHandler } from "./images";+import { DiskCache, type DiskCacheNamespace } from "./service";++const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);+const OLD_PNG = new Uint8Array([0x01, 0x02]);+const REMOTE = "https://example.com/a.png";+const MAX_AGE_MS = 100;++function imageResponse(bytes: Uint8Array, contentType = "image/png"): Response {+ return new Response(bytes as BodyInit, {+ headers: { "content-type": contentType },+ });+}++function request(remoteUrl: string): Request {+ return new Request(toCachedImageUrl(remoteUrl));+}++describe("createCachedImageHandler", () => {+ let rootDir: string;+ let clock: number;+ let images: DiskCacheNamespace;++ beforeEach(async () => {+ rootDir = await mkdtemp(join(tmpdir(), "disk-cache-images-"));+ clock = 1_000;+ images = new DiskCache({ rootDir, now: () => clock }).namespace("images");+ });++ afterEach(async () => {+ await rm(rootDir, { recursive: true, force: true });+ });++ async function seedStaleCopy(): Promise<void> {+ await images.set(REMOTE, OLD_PNG, "image/png");+ clock += MAX_AGE_MS + 1;+ }++ it("fetches once and serves later requests from disk", async () => {+ const fetch = vi.fn<FetchLike>(async () => imageResponse(PNG));+ const handler = createCachedImageHandler(images, fetch, MAX_AGE_MS);++ const first = await handler(request(REMOTE));+ const second = await handler(request(REMOTE));++ expect(fetch).toHaveBeenCalledTimes(1);+ expect(first.status).toBe(200);+ expect(second.headers.get("content-type")).toBe("image/png");+ expect(new Uint8Array(await second.arrayBuffer())).toEqual(PNG);+ });++ it("accepts an image whose media type is not lowercase", async () => {+ const fetch = vi.fn<FetchLike>(async () => imageResponse(PNG, "Image/PNG"));+ const handler = createCachedImageHandler(images, fetch, MAX_AGE_MS);++ const response = await handler(request(REMOTE));++ expect(response.status).toBe(200);+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(PNG);+ });++ it("shares one fetch between concurrent requests for the same URL", async () => {+ const fetch = vi.fn<FetchLike>(async () => imageResponse(PNG));+ const handler = createCachedImageHandler(images, fetch, MAX_AGE_MS);++ const responses = await Promise.all([+ handler(request(REMOTE)),+ handler(request(REMOTE)),+ handler(request(REMOTE)),+ ]);++ expect(fetch).toHaveBeenCalledTimes(1);+ expect(responses.map((response) => response.status)).toEqual([+ 200, 200, 200,+ ]);+ });++ it("refreshes a stale copy from the remote", async () => {+ await seedStaleCopy();+ const fetch = vi.fn<FetchLike>(async () => imageResponse(PNG));+ const handler = createCachedImageHandler(images, fetch, MAX_AGE_MS);++ const response = await handler(request(REMOTE));++ expect(fetch).toHaveBeenCalledTimes(1);+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(PNG);+ });++ it("responds 404 when the remote has no image and forgets the stale copy", async () => {+ await seedStaleCopy();+ const fetch = vi.fn<FetchLike>(+ async () => new Response(null, { status: 404 }),+ );+ const handler = createCachedImageHandler(images, fetch, MAX_AGE_MS);++ const response = await handler(request(REMOTE));++ expect(response.status).toBe(404);+ expect(await images.get(REMOTE, { maxAgeMs: Infinity })).toBeNull();+ });++ it.each([+ [+ "the fetch throws",+ async (): Promise<Response> => {+ throw new Error("offline");+ },+ ],+ [+ "the remote returns 500",+ async (): Promise<Response> => new Response(null, { status: 500 }),+ ],+ [+ "the remote returns a non-image",+ async (): Promise<Response> =>+ new Response("<html>", { headers: { "content-type": "text/html" } }),+ ],+ [+ "the remote declares a length past the cap",+ async (): Promise<Response> =>+ new Response(PNG as BodyInit, {+ headers: {+ "content-type": "image/png",+ "content-length": String(6 * 1024 * 1024),+ },+ }),+ ],+ [+ "the remote streams past the cap without declaring a length",+ async (): Promise<Response> =>+ imageResponse(new Uint8Array(6 * 1024 * 1024)),+ ],+ [+ "the remote redirects onto a private address",+ async (): Promise<Response> => {+ const response = imageResponse(PNG);+ Object.defineProperty(response, "url", {+ value: "https://169.254.169.254/latest/meta-data",+ });+ return response;+ },+ ],+ ])("serves the stale copy when %s", async (_label, fetch) => {+ await seedStaleCopy();+ const handler = createCachedImageHandler(images, fetch, MAX_AGE_MS);++ const response = await handler(request(REMOTE));++ expect(response.status).toBe(200);+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(OLD_PNG);+ // A stale copy that claimed the full max age would sit in Chromium's cache+ // past the point where the disk layer could replace it.+ expect(response.headers.get("cache-control")).toBe("no-cache");+ });++ it("still serves the image when it cannot be written to disk", async () => {+ vi.spyOn(images, "set").mockRejectedValue(new Error("disk full"));+ const handler = createCachedImageHandler(+ images,+ async () => imageResponse(PNG),+ MAX_AGE_MS,+ );++ const response = await handler(request(REMOTE));++ expect(response.status).toBe(200);+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(PNG);+ });++ it("responds 400 to a URL outside the cache scheme without fetching", async () => {+ const fetch = vi.fn<FetchLike>(async () => imageResponse(PNG));+ const handler = createCachedImageHandler(images, fetch, MAX_AGE_MS);++ const response = await handler(+ new Request(+ "posthog-cache://images/?src=http%3A%2F%2Fexample.com%2Fa.png",+ ),+ );++ expect(response.status).toBe(400);+ expect(fetch).not.toHaveBeenCalled();+ });+});diff --git a/products/desktop/apps/code/src/main/services/disk-cache/images.ts b/products/desktop/apps/code/src/main/services/disk-cache/images.tsnew file mode 100644index 000000000000..28cbc5a365ac--- /dev/null+++ b/products/desktop/apps/code/src/main/services/disk-cache/images.ts@@ -0,0 +1,181 @@+import type { DiskCacheNamespace } from "@main/services/disk-cache/service";+import { logger } from "@main/utils/logger";+import { redactUrl } from "@main/utils/network-log";+import type { FetchLike } from "@posthog/core/auth/auth";+import {+ fromCachedImageUrl,+ isCacheableImageUrl,+} from "@shared/disk-cache-protocol";++const log = logger.scope("diskCache images");++export const CACHED_IMAGE_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;++const MAX_IMAGE_BYTES = 5 * 1024 * 1024;++/** Ceiling for the whole images namespace, well past what avatars and icons need. */+export const CACHED_IMAGE_NAMESPACE_MAX_BYTES = 100 * 1024 * 1024;++/**+ * A refresh holds every waiting request for this URL, and an unsettled one+ * would pin them forever, so the fetch needs its own deadline.+ */+const FETCH_TIMEOUT_MS = 30_000;++/** Each running refresh holds its own buffer, so bound how many there can be. */+const MAX_CONCURRENT_FETCHES = 16;++interface CachedImage {+ bytes: Uint8Array;+ contentType: string;+ /** True when this is the fallback copy served because a refresh failed. */+ stale: boolean;+}++/**+ * Reads a body up to `maxBytes` and gives up as soon as the cap is passed.+ * `content-length` is only a hint here: a chunked response omits it, so a+ * server could otherwise stream forever into the main process.+ */+async function readCapped(+ response: Response,+ maxBytes: number,+): Promise<Uint8Array | null> {+ const declared = Number(response.headers.get("content-length"));+ if (Number.isFinite(declared) && declared > maxBytes) return null;++ if (!response.body) {+ const bytes = new Uint8Array(await response.arrayBuffer());+ return bytes.byteLength > maxBytes ? null : bytes;+ }++ const reader = response.body.getReader();+ const chunks: Uint8Array[] = [];+ let total = 0;+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ if (!value) continue;+ total += value.byteLength;+ if (total > maxBytes) {+ await reader.cancel("image too large").catch(() => {});+ return null;+ }+ chunks.push(value);+ }+ } finally {+ reader.releaseLock();+ }++ const bytes = new Uint8Array(total);+ let offset = 0;+ for (const chunk of chunks) {+ bytes.set(chunk, offset);+ offset += chunk.byteLength;+ }+ return bytes;+}++export function createCachedImageHandler(+ images: DiskCacheNamespace,+ fetch: FetchLike,+ maxAgeMs: number = CACHED_IMAGE_MAX_AGE_MS,+): (request: Request) => Promise<Response> {+ const inFlight = new Map<string, Promise<CachedImage | null>>();++ async function refresh(+ remoteUrl: string,+ stale: CachedImage | null,+ ): Promise<CachedImage | null> {+ const safeUrl = redactUrl(remoteUrl);+ try {+ const response = await fetch(remoteUrl, {+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),+ });+ if (response.status === 404) {+ await images.delete(remoteUrl);+ return null;+ }+ if (!response.ok) {+ log.warn("Image fetch failed", { safeUrl, status: response.status });+ return stale;+ }+ // The network stack follows redirects for us, so check where the bytes+ // came from: a public host can bounce the request onto an intranet+ // address or downgrade it to http.+ const finalUrl = response.url || remoteUrl;+ if (finalUrl !== remoteUrl && !isCacheableImageUrl(finalUrl)) {+ log.warn("Image redirected off-limits", {+ safeUrl,+ finalUrl: redactUrl(finalUrl),+ });+ return stale;+ }+ const contentType = response.headers.get("content-type") ?? "";+ // Media types are case-insensitive (RFC 9110), so a valid header like+ // "Image/PNG" must pass. Normalize for the check; store the original.+ if (!contentType.trim().toLowerCase().startsWith("image/")) return stale;++ const bytes = await readCapped(response, MAX_IMAGE_BYTES);+ if (!bytes) {+ log.warn("Image too large", { safeUrl, max: MAX_IMAGE_BYTES });+ return stale;+ }++ // The bytes are already good, so a failed write costs a later cache miss+ // and nothing more. Failing here instead would render nothing at all.+ await images+ .set(remoteUrl, bytes, contentType)+ .catch((error: unknown) => {+ log.warn("Could not store image", { safeUrl, error });+ });+ return { bytes, contentType, stale: false };+ } catch (error) {+ log.warn("Image fetch threw", { safeUrl, error });+ return stale;+ }+ }++ async function resolve(remoteUrl: string): Promise<CachedImage | null> {+ const cached = await images.get(remoteUrl, { maxAgeMs });+ if (cached && !cached.stale) return cached;++ const pending = inFlight.get(remoteUrl);+ if (pending) return pending;++ // Coalescing only helps repeats of one URL. Distinct URLs each hold their+ // own buffer, so cap how many can run at once and let the rest wait for a+ // later render rather than growing main-process memory without limit.+ if (inFlight.size >= MAX_CONCURRENT_FETCHES) {+ log.warn("Too many image fetches in flight", { size: inFlight.size });+ return cached;+ }++ const refreshed = refresh(remoteUrl, cached).finally(() => {+ inFlight.delete(remoteUrl);+ });+ inFlight.set(remoteUrl, refreshed);+ return refreshed;+ }++ return async (request) => {+ const remoteUrl = fromCachedImageUrl(request.url);+ if (!remoteUrl) return new Response(null, { status: 400 });++ const image = await resolve(remoteUrl);+ if (!image) return new Response(null, { status: 404 });++ return new Response(image.bytes as BodyInit, {+ headers: {+ "Content-Type": image.contentType,+ // The scheme is standard and secure, so Chromium caches these like any+ // other resource. Letting a stale copy claim the full max age would put+ // it beyond reach of the next refresh.+ "Cache-Control": image.stale+ ? "no-cache"+ : `max-age=${Math.floor(maxAgeMs / 1000)}`,+ },+ });+ };+}diff --git a/products/desktop/apps/code/src/main/services/disk-cache/service.test.ts b/products/desktop/apps/code/src/main/services/disk-cache/service.test.tsnew file mode 100644index 000000000000..b734ebc7159b--- /dev/null+++ b/products/desktop/apps/code/src/main/services/disk-cache/service.test.ts@@ -0,0 +1,127 @@+import { createHash } from "node:crypto";+import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { DiskCache } from "./service";++const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);++describe("DiskCache", () => {+ let rootDir: string;+ let now: number;++ beforeEach(async () => {+ rootDir = await mkdtemp(join(tmpdir(), "disk-cache-"));+ now = 1_000;+ });++ afterEach(async () => {+ await rm(rootDir, { recursive: true, force: true });+ });++ function makeCache(): DiskCache {+ return new DiskCache({ rootDir, now: () => now });+ }++ it("round-trips bytes and content type by key", async () => {+ const images = makeCache().namespace("images");+ await images.set("https://example.com/a.png", PNG, "image/png");++ const entry = await images.get("https://example.com/a.png", {+ maxAgeMs: 100,+ });++ expect(entry).not.toBeNull();+ expect(new Uint8Array(entry?.bytes ?? [])).toEqual(PNG);+ expect(entry?.contentType).toBe("image/png");+ expect(entry?.stale).toBe(false);+ });++ it("returns null for a key never stored", async () => {+ const images = makeCache().namespace("images");+ expect(await images.get("missing", { maxAgeMs: 100 })).toBeNull();+ });++ it.each([+ [50, false],+ [100, false],+ [101, true],+ ])(+ "after %d ms with a 100 ms max age, stale is %s",+ async (elapsedMs, stale) => {+ const images = makeCache().namespace("images");+ await images.set("key", PNG, "image/png");+ now += elapsedMs;++ const entry = await images.get("key", { maxAgeMs: 100 });+ expect(entry?.stale).toBe(stale);+ },+ );++ it.each([+ ["{not json", "unparseable"],+ // Parses, but a missing storedAt makes the staleness arithmetic NaN, which+ // reads as fresh — the entry would never expire and never refresh.+ ['{"contentType":"image/png"}', "missing storedAt"],+ ['{"storedAt":1000}', "missing contentType"],+ ])("drops an entry whose sidecar is %s (%s)", async (sidecar) => {+ const images = makeCache().namespace("images");+ await images.set("key", PNG, "image/png");+ const hash = createHash("sha256").update("key").digest("hex");+ await writeFile(join(rootDir, "images", `${hash}.json`), sidecar);++ expect(await images.get("key", { maxAgeMs: 100 })).toBeNull();+ expect(await readdir(join(rootDir, "images"))).toEqual([]);+ });++ it("returns null when an unreadable entry cannot be deleted", async () => {+ const images = makeCache().namespace("images");+ const hash = createHash("sha256").update("key").digest("hex");+ await mkdir(join(rootDir, "images"), { recursive: true });+ await writeFile(join(rootDir, "images", `${hash}.json`), "{not json");+ // A directory at the bytes path makes the cleanup rm reject, so deletion+ // fails after the unreadable sidecar. get() must still resolve to null.+ await mkdir(join(rootDir, "images", hash));++ expect(await images.get("key", { maxAgeMs: 100 })).toBeNull();+ });++ it("keeps namespaces apart under one key", async () => {+ const cache = makeCache();+ await cache.namespace("images").set("key", PNG, "image/png");++ expect(+ await cache.namespace("other").get("key", { maxAgeMs: 100 }),+ ).toBeNull();+ });++ it("evicts the oldest entries once the namespace passes its byte budget", async () => {+ const big = new Uint8Array(1024);+ const images = makeCache().namespace("images", { maxBytes: 2048 });++ for (const key of ["a", "b", "c"]) {+ await images.set(key, big, "image/png");+ now += 1;+ }++ expect(await images.get("a", { maxAgeMs: Infinity })).toBeNull();+ expect(await images.get("c", { maxAgeMs: Infinity })).not.toBeNull();+ });++ it("clear removes every namespace", async () => {+ const cache = makeCache();+ await cache.namespace("images").set("a", PNG, "image/png");+ await cache.namespace("other").set("b", PNG, "image/png");++ await cache.clear();++ expect(+ await cache.namespace("images").get("a", { maxAgeMs: 100 }),+ ).toBeNull();+ expect(+ await cache.namespace("other").get("b", { maxAgeMs: 100 }),+ ).toBeNull();+ await expect(readdir(rootDir)).rejects.toMatchObject({ code: "ENOENT" });+ });+});diff --git a/products/desktop/apps/code/src/main/services/disk-cache/service.ts b/products/desktop/apps/code/src/main/services/disk-cache/service.tsnew file mode 100644index 000000000000..b7be3f70b942--- /dev/null+++ b/products/desktop/apps/code/src/main/services/disk-cache/service.ts@@ -0,0 +1,211 @@+import { createHash, randomUUID } from "node:crypto";+import {+ mkdir,+ readdir,+ readFile,+ rename,+ rm,+ stat,+ writeFile,+} from "node:fs/promises";+import { join } from "node:path";+import { logger } from "@main/utils/logger";+import type { IDiskCache } from "@posthog/platform/disk-cache";++const log = logger.scope("diskCache");++export interface DiskCacheEntry {+ bytes: Buffer;+ contentType: string;+ stale: boolean;+}++interface DiskCacheSidecar {+ contentType: string;+ storedAt: number;+}++export interface DiskCacheOptions {+ rootDir: string;+ now?: () => number;+}++export interface DiskCacheNamespaceOptions {+ /** Total bytes the namespace may hold. Oldest entries go first once passed. */+ maxBytes?: number;+}++function isNotFound(error: unknown): boolean {+ return (error as NodeJS.ErrnoException | null)?.code === "ENOENT";+}++/**+ * A sidecar that parses but has the wrong shape must not pass. A missing+ * `storedAt` makes the staleness arithmetic NaN, which reads as fresh, so the+ * entry would never expire and never refresh.+ */+function parseSidecar(raw: string): DiskCacheSidecar {+ const parsed = JSON.parse(raw) as Partial<DiskCacheSidecar>;+ if (+ typeof parsed?.contentType !== "string" ||+ typeof parsed?.storedAt !== "number" ||+ !Number.isFinite(parsed.storedAt)+ ) {+ throw new Error("Malformed cache sidecar");+ }+ return { contentType: parsed.contentType, storedAt: parsed.storedAt };+}++export class DiskCache implements IDiskCache {+ private readonly now: () => number;++ constructor(private readonly options: DiskCacheOptions) {+ this.now = options.now ?? Date.now;+ }++ namespace(+ name: string,+ options: DiskCacheNamespaceOptions = {},+ ): DiskCacheNamespace {+ return new DiskCacheNamespace(+ join(this.options.rootDir, name),+ this.now,+ options.maxBytes,+ );+ }++ async clear(): Promise<void> {+ await rm(this.options.rootDir, { recursive: true, force: true });+ }+}++export class DiskCacheNamespace {+ constructor(+ private readonly dir: string,+ private readonly now: () => number,+ private readonly maxBytes?: number,+ ) {}++ async get(+ key: string,+ options: { maxAgeMs: number },+ ): Promise<DiskCacheEntry | null> {+ const base = this.pathFor(key);+ try {+ const sidecar = parseSidecar(await readFile(`${base}.json`, "utf8"));+ const bytes = await readFile(base);+ return {+ bytes,+ contentType: sidecar.contentType,+ stale: this.now() - sidecar.storedAt > options.maxAgeMs,+ };+ } catch (error) {+ if (!isNotFound(error)) {+ // Log the hashed on-disk path, not the raw key: a key can be a signed+ // URL, and this logger exports off-device. The path still points at the+ // exact file to inspect.+ log.warn("Dropping unreadable cache entry", { path: base, error });+ // Cleanup is best effort. A locked file or bad permissions must not+ // reject get(), or the caller loses its network fallback and the+ // image request hard-fails.+ await this.delete(key).catch((deleteError) => {+ log.warn("Could not delete unreadable cache entry", {+ path: base,+ error: deleteError,+ });+ });+ }+ return null;+ }+ }++ async set(+ key: string,+ bytes: Uint8Array,+ contentType: string,+ ): Promise<void> {+ const base = this.pathFor(key);+ const sidecar: DiskCacheSidecar = { contentType, storedAt: this.now() };+ await mkdir(this.dir, { recursive: true });+ await writeAtomic(base, bytes);+ await writeAtomic(`${base}.json`, JSON.stringify(sidecar));+ await this.evictOverBudget();+ }++ /**+ * Keeps the namespace under its byte budget, oldest first. Entries expire by+ * age on read but nothing removes them, so without this a caller that reaches+ * for many distinct keys grows the directory until the disk is full.+ */+ private async evictOverBudget(): Promise<void> {+ const budget = this.maxBytes;+ if (budget === undefined) return;++ try {+ const names = await readdir(this.dir);+ const sized = await Promise.all(+ names+ .filter((name) => !name.endsWith(".json") && !name.endsWith(".tmp"))+ .map(async (name) => ({+ name,+ bytes: (await stat(join(this.dir, name))).size,+ })),+ );++ let total = sized.reduce((sum, entry) => sum + entry.bytes, 0);+ if (total <= budget) return;++ // Ages come from the sidecars, so only read them once eviction is on:+ // every write would otherwise pay for the whole namespace.+ const entries = await Promise.all(+ sized.map(async (entry) => ({+ ...entry,+ storedAt: await this.storedAtOf(join(this.dir, entry.name)),+ })),+ );++ entries.sort((a, b) => a.storedAt - b.storedAt);+ for (const entry of entries) {+ if (total <= budget) break;+ const base = join(this.dir, entry.name);+ await Promise.all([+ rm(base, { force: true }),+ rm(`${base}.json`, { force: true }),+ ]);+ total -= entry.bytes;+ }+ } catch (error) {+ log.warn("Could not trim cache namespace", { dir: this.dir, error });+ }+ }++ /** Age from the sidecar. An entry with no readable sidecar is junk, so it goes first. */+ private async storedAtOf(base: string): Promise<number> {+ try {+ return parseSidecar(await readFile(`${base}.json`, "utf8")).storedAt;+ } catch {+ return Number.NEGATIVE_INFINITY;+ }+ }++ async delete(key: string): Promise<void> {+ const base = this.pathFor(key);+ await Promise.all([+ rm(base, { force: true }),+ rm(`${base}.json`, { force: true }),+ ]);+ }++ private pathFor(key: string): string {+ return join(this.dir, createHash("sha256").update(key).digest("hex"));+ }+}++async function writeAtomic(+ path: string,+ contents: Uint8Array | string,+): Promise<void> {+ const tmp = `${path}.${randomUUID()}.tmp`;+ await writeFile(tmp, contents);+ await rename(tmp, path);+}diff --git a/products/desktop/apps/code/src/main/trpc/router.ts b/products/desktop/apps/code/src/main/trpc/router.tsindex 27428905086a..0ef26792fa1c 100644--- a/products/desktop/apps/code/src/main/trpc/router.ts+++ b/products/desktop/apps/code/src/main/trpc/router.ts@@ -15,6 +15,7 @@ import { connectivityRouter } from "@posthog/host-router/routers/connectivity.roimport { contextMenuRouter } from "@posthog/host-router/routers/context-menu.router";import { dashboardsRouter } from "@posthog/host-router/routers/dashboards.router";import { deepLinkRouter } from "@posthog/host-router/routers/deep-link.router";+import { diskCacheRouter } from "@posthog/host-router/routers/disk-cache.router";import { enrichmentRouter } from "@posthog/host-router/routers/enrichment.router";import { environmentRouter } from "@posthog/host-router/routers/environment.router";import { externalAppsRouter } from "@posthog/host-router/routers/external-apps.router";@@ -114,6 +115,7 @@ export const trpcRouter = router({updates: updatesRouter,usageMonitor: usageMonitorRouter,deepLink: deepLinkRouter,+ diskCache: diskCacheRouter,workspace: workspaceRouter,workspaceServer: workspaceServerRouter,});diff --git a/products/desktop/apps/code/src/renderer/desktop-services.ts b/products/desktop/apps/code/src/renderer/desktop-services.tsindex a8477f9b0b08..c4816cf07d97 100644--- a/products/desktop/apps/code/src/renderer/desktop-services.ts+++ b/products/desktop/apps/code/src/renderer/desktop-services.ts@@ -50,6 +50,7 @@ import {} from "@posthog/core/speech/identifiers";import { resolveService } from "@posthog/di/container";import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";+import { DISK_CACHE_IMAGES } from "@posthog/platform/disk-cache";import {HOST_CAPABILITIES,type HostCapabilities,@@ -123,6 +124,7 @@ import {import { ELEVENLABS_API_KEY_STORE_KEY } from "@posthog/workspace-server/services/speech/identifiers";import { container } from "@renderer/di/container";import { RendererAuthSideEffects } from "@renderer/platform-adapters/auth-side-effects";+import { desktopDiskCacheImages } from "@renderer/platform-adapters/desktop-disk-cache-images";import { gitCacheKeyProvider } from "@renderer/platform-adapters/git-cache-keys";import { RendererHedgehogModeHost } from "@renderer/platform-adapters/hedgehog-mode-host";import { setupStore } from "@renderer/platform-adapters/setup";@@ -443,3 +445,5 @@ container.bind(SETUP_STORE).toConstantValue(setupStore);container.bind(HOST_CAPABILITIES).toConstantValue({ localWorkspaces: true } satisfies HostCapabilities);++container.bind(DISK_CACHE_IMAGES).toConstantValue(desktopDiskCacheImages);diff --git a/products/desktop/apps/code/src/renderer/di/bindings.ts b/products/desktop/apps/code/src/renderer/di/bindings.tsindex f96aebe4b409..454d90018b26 100644--- a/products/desktop/apps/code/src/renderer/di/bindings.ts+++ b/products/desktop/apps/code/src/renderer/di/bindings.ts@@ -153,6 +153,10 @@ import {HOST_TRPC_CLIENT,type HostTrpcClient,} from "@posthog/host-router/client";+import {+ DISK_CACHE_IMAGES,+ type IDiskCacheImages,+} from "@posthog/platform/disk-cache";import {HOST_CAPABILITIES,type HostCapabilities,@@ -375,6 +379,7 @@ export interface RendererBindings {[AUTH_SIDE_EFFECTS]: IAuthSideEffects;[SETUP_STORE]: ISetupStore;[HOST_CAPABILITIES]: HostCapabilities;+ [DISK_CACHE_IMAGES]: IDiskCacheImages;// --- desktop-contributions.ts ---[CONTRIBUTION]: Contribution;diff --git a/products/desktop/apps/code/src/renderer/platform-adapters/desktop-disk-cache-images.ts b/products/desktop/apps/code/src/renderer/platform-adapters/desktop-disk-cache-images.tsnew file mode 100644index 000000000000..aec98084788f--- /dev/null+++ b/products/desktop/apps/code/src/renderer/platform-adapters/desktop-disk-cache-images.ts@@ -0,0 +1,10 @@+import type { IDiskCacheImages } from "@posthog/platform/disk-cache";+import {+ isCacheableImageUrl,+ toCachedImageUrl,+} from "@shared/disk-cache-protocol";++export const desktopDiskCacheImages: IDiskCacheImages = {+ imageUrl: (remoteUrl) =>+ isCacheableImageUrl(remoteUrl) ? toCachedImageUrl(remoteUrl) : remoteUrl,+};diff --git a/products/desktop/apps/code/src/shared/disk-cache-protocol.test.ts b/products/desktop/apps/code/src/shared/disk-cache-protocol.test.tsnew file mode 100644index 000000000000..01cb96047fc4--- /dev/null+++ b/products/desktop/apps/code/src/shared/disk-cache-protocol.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from "vitest";+import {+ fromCachedImageUrl,+ isCacheableImageUrl,+ toCachedImageUrl,+} from "./disk-cache-protocol";++describe("disk-cache-protocol", () => {+ it.each([+ "https://www.gravatar.com/avatar/abc?s=96&d=404",+ "https://avatars.githubusercontent.com/u/1?v=4",+ "https://example.com/a b/%C3%A4.png?x=1&y=%2F#frag",+ ])("round-trips %s through the cache URL", (remoteUrl) => {+ expect(fromCachedImageUrl(toCachedImageUrl(remoteUrl))).toBe(remoteUrl);+ });++ it.each([+ ["http://example.com/a.png", "plain http"],+ ["file:///etc/passwd", "file scheme"],+ ["not a url", "malformed"],+ ["https://localhost/a.png", "loopback name"],+ ["https://127.0.0.1/a.png", "loopback address"],+ ["https://169.254.169.254/latest/meta-data", "link-local address"],+ ["https://10.1.2.3/a.png", "private address"],+ ["https://192.168.0.1/a.png", "private address"],+ ["https://[::1]/a.png", "ipv6 loopback"],+ ["https://nas/a.png", "bare intranet name"],+ ["https://printer.local/a.png", "mdns name"],+ ["https://user:[email protected]/a.png", "embedded credentials"],+ ])("refuses to cache %s (%s)", (remoteUrl) => {+ expect(isCacheableImageUrl(remoteUrl)).toBe(false);+ });++ it.each([+ [+ "posthog-cache://images/?src=http%3A%2F%2Fexample.com%2Fa.png",+ "http source",+ ],+ [+ "posthog-cache://other/?src=https%3A%2F%2Fexample.com%2Fa.png",+ "unknown namespace",+ ],+ [+ "https://example.com/?src=https%3A%2F%2Fexample.com%2Fa.png",+ "wrong scheme",+ ],+ ["posthog-cache://images/", "missing src"],+ [+ "posthog-cache://images/?src=https%3A%2F%2F169.254.169.254%2Flatest",+ "link-local source",+ ],+ ])("rejects %s (%s)", (protocolUrl) => {+ expect(fromCachedImageUrl(protocolUrl)).toBeNull();+ });+});diff --git a/products/desktop/apps/code/src/shared/disk-cache-protocol.ts b/products/desktop/apps/code/src/shared/disk-cache-protocol.tsnew file mode 100644index 000000000000..dc34ae43dcef--- /dev/null+++ b/products/desktop/apps/code/src/shared/disk-cache-protocol.ts@@ -0,0 +1,39 @@+import { isPrivateHostname } from "@posthog/core/local-mcp/localMcpImport";++export const DISK_CACHE_SCHEME = "posthog-cache";++const CACHED_IMAGE_ORIGIN = `${DISK_CACHE_SCHEME}://images/`;++/**+ * The scheme is registered on the session that also renders untrusted artifact+ * HTML, so any preview can name a source and make the main process fetch it.+ * Public https only: an intranet address would let the preview reach hosts its+ * own sandbox cannot, and embedded credentials would have the main process+ * present them to a host the preview chose.+ */+export function isCacheableImageUrl(remoteUrl: string): boolean {+ try {+ const url = new URL(remoteUrl);+ if (url.username || url.password) return false;+ return url.protocol === "https:" && !isPrivateHostname(url.hostname);+ } catch {+ return false;+ }+}++export function toCachedImageUrl(remoteUrl: string): string {+ return `${CACHED_IMAGE_ORIGIN}?src=${encodeURIComponent(remoteUrl)}`;+}++export function fromCachedImageUrl(protocolUrl: string): string | null {+ try {+ const url = new URL(protocolUrl);+ if (url.protocol !== `${DISK_CACHE_SCHEME}:` || url.host !== "images") {+ return null;+ }+ const remoteUrl = url.searchParams.get("src");+ return remoteUrl && isCacheableImageUrl(remoteUrl) ? remoteUrl : null;+ } catch {+ return null;+ }+}diff --git a/products/desktop/docs/ARCHITECTURE.md b/products/desktop/docs/ARCHITECTURE.mdindex 461ee8eca25a..c415d8a15181 100644--- a/products/desktop/docs/ARCHITECTURE.md+++ b/products/desktop/docs/ARCHITECTURE.md@@ -149,6 +149,21 @@ The renderer imports `HostRouter` as a type and uses `useHostTRPC`. `trpcClient`It exposes colocated tRPC routers. `@posthog/workspace-client` is the typed client. `core` services inject narrow workspace-client slices and call those procedures.+## Disk Cache++The Electron main process owns one on-disk cache at `userData/disk-cache/<namespace>/` (`apps/code/src/main/services/disk-cache/service.ts`). An entry is bytes plus a content type and a stored-at time. Readers pass a max age and get stale entries back flagged, so a consumer can serve them when a refresh fails. "Clear application storage" removes the whole directory, which is why the directory is not named `cache`: `userData` is also Electron's `sessionData`, and on a case-insensitive filesystem that would be Chromium's own `Cache`.++A namespace can take a `maxBytes` budget.+Nothing else removes entries, so a namespace without one grows for as long as callers reach for new keys.+With one, a write that passes the budget drops the oldest entries until the namespace fits again.++Consumers take a namespace and serve it over the `posthog-cache://` protocol (`apps/code/src/main/protocols/disk-cache.ts`). Today `images/` serves remote images: the renderer rewrites an `https:` URL with `cachedImageUrl()` from `@posthog/ui/shell/cachedImageUrl`, backed by the `IDiskCacheImages` platform interface. Hosts without a disk cache leave the URL unchanged.++The protocol is registered on the session that also renders untrusted artifact HTML, so treat every source as attacker-chosen.+A source must be public `https:` with no embedded credentials: intranet and loopback addresses are refused, and a response that redirected onto one is thrown away.+Bodies are read against a size cap while they stream, refreshes carry a deadline and a concurrency limit, and the namespace budget bounds what one preview can put on disk.+A stale copy is served with `no-cache` so Chromium cannot hold it past the point where the disk layer would replace it.+## SchemasUse Zod at runtime boundaries. Infer TypeScript types from schemas.diff --git a/products/desktop/packages/host-router/src/router.ts b/products/desktop/packages/host-router/src/router.tsindex 7df718e58ee9..06fd5b661516 100644--- a/products/desktop/packages/host-router/src/router.ts+++ b/products/desktop/packages/host-router/src/router.ts@@ -14,6 +14,7 @@ import { connectivityRouter } from "./routers/connectivity.router";import { contextMenuRouter } from "./routers/context-menu.router";import { dashboardsRouter } from "./routers/dashboards.router";import { deepLinkRouter } from "./routers/deep-link.router";+import { diskCacheRouter } from "./routers/disk-cache.router";import { enrichmentRouter } from "./routers/enrichment.router";import { environmentRouter } from "./routers/environment.router";import { externalAppsRouter } from "./routers/external-apps.router";@@ -66,6 +67,7 @@ export const hostRouter = router({contextMenu: contextMenuRouter,dashboards: dashboardsRouter,deepLink: deepLinkRouter,+ diskCache: diskCacheRouter,enrichment: enrichmentRouter,environment: environmentRouter,externalApps: externalAppsRouter,diff --git a/products/desktop/packages/host-router/src/routers/disk-cache.router.ts b/products/desktop/packages/host-router/src/routers/disk-cache.router.tsnew file mode 100644index 000000000000..212736685934--- /dev/null+++ b/products/desktop/packages/host-router/src/routers/disk-cache.router.ts@@ -0,0 +1,11 @@+import { publicProcedure, router } from "@posthog/host-trpc/trpc";+import {+ DISK_CACHE_SERVICE,+ type IDiskCache,+} from "@posthog/platform/disk-cache";++export const diskCacheRouter = router({+ clear: publicProcedure.mutation(({ ctx }) =>+ ctx.container.get<IDiskCache>(DISK_CACHE_SERVICE).clear(),+ ),+});diff --git a/products/desktop/packages/platform/package.json b/products/desktop/packages/platform/package.jsonindex d59ff4b010e5..7f5b6ff85a36 100644--- a/products/desktop/packages/platform/package.json+++ b/products/desktop/packages/platform/package.json@@ -99,6 +99,10 @@"./dev-host-actions": {"types": "./dist/dev-host-actions.d.ts","import": "./dist/dev-host-actions.js"+ },+ "./disk-cache": {+ "types": "./dist/disk-cache.d.ts",+ "import": "./dist/disk-cache.js"}},"scripts": {diff --git a/products/desktop/packages/platform/src/disk-cache.ts b/products/desktop/packages/platform/src/disk-cache.tsnew file mode 100644index 000000000000..1745b2511df2--- /dev/null+++ b/products/desktop/packages/platform/src/disk-cache.ts@@ -0,0 +1,11 @@+export interface IDiskCache {+ clear(): Promise<void>;+}++export const DISK_CACHE_SERVICE = Symbol.for("posthog.platform.diskCache");++export interface IDiskCacheImages {+ imageUrl(remoteUrl: string): string;+}++export const DISK_CACHE_IMAGES = Symbol.for("posthog.platform.diskCacheImages");diff --git a/products/desktop/packages/platform/tsup.config.ts b/products/desktop/packages/platform/tsup.config.tsindex 2caee254ae6d..05315800e4e8 100644--- a/products/desktop/packages/platform/tsup.config.ts+++ b/products/desktop/packages/platform/tsup.config.ts@@ -26,6 +26,7 @@ export default defineConfig({"src/deep-link.ts","src/app-metrics.ts","src/dev-host-actions.ts",+ "src/disk-cache.ts",],format: ["esm"],dts: true,diff --git a/products/desktop/packages/ui/src/shell/cachedImageUrl.ts b/products/desktop/packages/ui/src/shell/cachedImageUrl.tsnew file mode 100644index 000000000000..d1029b1d5b02--- /dev/null+++ b/products/desktop/packages/ui/src/shell/cachedImageUrl.ts@@ -0,0 +1,13 @@+import { resolveServiceOptional } from "@posthog/di/container";+import {+ DISK_CACHE_IMAGES,+ type IDiskCacheImages,+} from "@posthog/platform/disk-cache";++export function cachedImageUrl(remoteUrl: string): string {+ return (+ resolveServiceOptional<IDiskCacheImages>(DISK_CACHE_IMAGES)?.imageUrl(+ remoteUrl,+ ) ?? remoteUrl+ );+}diff --git a/products/desktop/packages/ui/src/utils/clearStorage.ts b/products/desktop/packages/ui/src/utils/clearStorage.tsindex 9ef2b4b14844..37b6bafc4367 100644--- a/products/desktop/packages/ui/src/utils/clearStorage.ts+++ b/products/desktop/packages/ui/src/utils/clearStorage.ts@@ -9,7 +9,7 @@ const log = logger.scope("clear-storage");export function clearApplicationStorage(): void {const confirmed = window.confirm(- "Are you sure you want to clear all application storage?\n\nThis will remove:\n• All registered folders\n• UI state (sidebar preferences, etc.)\n• Task directory mappings\n\nYour files will not be deleted from your computer.",+ "Are you sure you want to clear all application storage?\n\nThis will remove:\n• All registered folders\n• UI state (sidebar preferences, etc.)\n• Task directory mappings\n• Cached images\n\nYour files will not be deleted from your computer.",);if (!confirmed) return;@@ -19,6 +19,7 @@ export function clearApplicationStorage(): void {Promise.allSettled([client.folders.clearAllData.mutate(),client.secureStore.clear.query(),+ client.diskCache.clear.mutate(),]).then((results) => {const rejected = results.filter((result): result is PromiseRejectedResult => result.status === "rejected",