Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
perf: serve app icons at display sizes (#8408)
[._.]/ Adam Eivy3916ec387795
diff --git a/client/public/portos-logo.png b/client/public/portos-logo.pngindex 64242d62e0..4daefc5632 100644Binary files a/client/public/portos-logo.png and b/client/public/portos-logo.png differdiff --git a/server/lib/validation.js b/server/lib/validation.jsindex e8f614df57..da316679ff 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1659,6 +1659,10 @@ export const SYSTEM_HEALTH_WARNING_TYPES = ['memory', 'cpu', 'disk', 'process',export const systemHealthWarningParamsSchema = z.object({ type: z.enum(SYSTEM_HEALTH_WARNING_TYPES) });export const systemHealthWarningDismissSchema = z.object({ message: z.string().trim().min(1).max(500) });+export const appIconQuerySchema = z.object({+ size: z.enum(['64', '128', '256']).default('128').transform(Number),+});+/*** Validate data against a Zod schema, throwing on failure.* Returns parsed data on success, throws ServerError on failure.diff --git a/server/routes/apps/icons.js b/server/routes/apps/icons.jsindex cc132a6533..d461c28a97 100644--- a/server/routes/apps/icons.js+++ b/server/routes/apps/icons.js@@ -9,17 +9,38 @@import { Router } from 'express';import { readFile, stat } from 'fs/promises';import { extname } from 'path';+import sharp from 'sharp';import * as appsService from '../../services/apps.js';import { notifyAppsChanged } from '../../services/apps.js';import { asyncHandler, ServerError } from '../../lib/errorHandler.js';import { detectAppIcon, getIconContentType, isUsableSvg } from '../../services/appIconDetect.js';import { loadApp, pathExists } from './shared.js';+import { appIconQuerySchema, validateRequest } from '../../lib/validation.js';const router = Router();+const rasterIconCache = new Map();++const getRasterIcon = (appId, iconPath, iconStat, size, iconData) => {+ const variant = 'png';+ const key = `${iconPath}:${iconStat.mtimeMs}:${size}:${variant}`;+ for (const [cachedKey, value] of rasterIconCache) {+ if (value.appId === appId && value.size === size && cachedKey !== key) rasterIconCache.delete(cachedKey);+ }+ if (!rasterIconCache.has(key)) {+ const rendered = sharp(iconData).resize(size, size, { fit: 'cover', withoutEnlargement: true }).png().toBuffer()+ .catch((error) => {+ rasterIconCache.delete(key);+ throw error;+ });+ rasterIconCache.set(key, { appId, size, rendered });+ }+ return rasterIconCache.get(key).rendered;+};// GET /api/apps/:id/icon - Serve the app's detected icon imagerouter.get('/:id/icon', loadApp, asyncHandler(async (req, res) => {const app = req.loadedApp;+ const { size } = validateRequest(appIconQuerySchema, req.query);// Use stored appIconPath, or detect on-the-fly. Stored SVGs that embed an// external <image href="..."> render blank under the route's `default-src@@ -46,9 +67,11 @@ router.get('/:id/icon', loadApp, asyncHandler(async (req, res) => {const contentType = getIconContentType(iconPath);const iconStat = await stat(iconPath).catch(e => e.code === 'ENOENT' ? null : Promise.reject(e));if (!iconStat) throw new ServerError('No app icon found', { status: 404 });- const etag = `W/"${iconStat.mtimeMs.toString(36)}-${iconStat.size.toString(36)}"`;+ const extension = extname(iconPath).toLowerCase();+ const isRaster = ['.png', '.jpg', '.jpeg', '.webp'].includes(extension);+ const etag = `W/"${iconStat.mtimeMs.toString(36)}-${iconStat.size.toString(36)}${isRaster ? `-${size}` : ''}"`;- res.set('Content-Type', contentType);+ res.set('Content-Type', isRaster ? 'image/png' : contentType);res.set('Cache-Control', 'public, max-age=3600');res.set('ETag', etag);res.set('X-Content-Type-Options', 'nosniff');@@ -67,7 +90,7 @@ router.get('/:id/icon', loadApp, asyncHandler(async (req, res) => {const iconData = await readFile(iconPath).catch(e => e.code === 'ENOENT' ? null : Promise.reject(e));if (!iconData) throw new ServerError('No app icon found', { status: 404 });- res.send(iconData);+ res.send(isRaster ? await getRasterIcon(app.id, iconPath, iconStat, size, iconData) : iconData);}));// POST /api/apps/detect-icons - Detect and persist app icons for all appsdiff --git a/server/routes/apps/icons.test.js b/server/routes/apps/icons.test.jsindex d235d80e2e..d10132bbe4 100644--- a/server/routes/apps/icons.test.js+++ b/server/routes/apps/icons.test.js@@ -1,7 +1,8 @@import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';import express from 'express';-import { request } from '../../lib/testHelper.js';+import { closeLoopbackServer, request, startLoopbackServer } from '../../lib/testHelper.js';import iconRoutes from './icons.js';+import sharp from 'sharp';vi.mock('../../services/apps.js', () => ({getAllApps: vi.fn(),@@ -19,10 +20,24 @@ vi.mock('../../services/appIconDetect.js', () => ({import * as appsService from '../../services/apps.js';import { detectAppIcon, getIconContentType, isUsableSvg } from '../../services/appIconDetect.js';-import { writeFileSync, mkdirSync, rmSync } from 'fs';+import { writeFileSync, mkdirSync, rmSync, utimesSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';+async function requestBinary(app, path) {+ const server = await startLoopbackServer(app);+ try {+ const response = await fetch(`http://127.0.0.1:${server.address().port}${path}`);+ return {+ status: response.status,+ body: Buffer.from(await response.arrayBuffer()),+ headers: Object.fromEntries(response.headers.entries()),+ };+ } finally {+ await closeLoopbackServer(server);+ }+}+describe('Apps Icon Routes', () => {let app;@@ -38,11 +53,11 @@ describe('Apps Icon Routes', () => {const iconPath = join(iconDir, 'icon.png');const mockApp = { id: 'app-001', name: 'Test App', appIconPath: iconPath, repoPath: '/tmp/test', pm2ProcessNames: [] };- beforeEach(() => {+ beforeEach(async () => {mkdirSync(iconDir, { recursive: true });- writeFileSync(iconPath, 'fake-png-data');+ await sharp({ create: { width: 512, height: 512, channels: 3, background: '#ff0000' } }).png().toFile(iconPath);appsService.getAppById.mockResolvedValue(mockApp);- getIconContentType.mockReturnValue('image/png');+ getIconContentType.mockImplementation((path) => path.endsWith('.svg') ? 'image/svg+xml' : 'image/png');});afterAll(() => {@@ -50,12 +65,53 @@ describe('Apps Icon Routes', () => {});it('should return icon with ETag header', async () => {- const response = await request(app).get('/api/apps/app-001/icon');+ const response = await requestBinary(app, '/api/apps/app-001/icon');expect(response.status).toBe(200);expect(response.headers['etag']).toBeDefined();expect(response.headers['etag']).toMatch(/^W\//);expect(response.headers['cache-control']).toBe('public, max-age=3600');+ expect(response.headers['content-type']).toMatch(/^image\/png/);+ expect(await sharp(response.body).metadata()).toMatchObject({ width: 128, height: 128 });+ });++ it('serves requested raster sizes with distinct ETags', async () => {+ const defaultResponse = await requestBinary(app, '/api/apps/app-001/icon');+ const sizedResponse = await requestBinary(app, '/api/apps/app-001/icon?size=64');++ expect(sizedResponse.status).toBe(200);+ expect(sizedResponse.headers.etag).not.toBe(defaultResponse.headers.etag);+ expect(await sharp(sizedResponse.body).metadata()).toMatchObject({ width: 64, height: 64 });+ });++ it('rejects unsupported raster sizes', async () => {+ const response = await request(app).get('/api/apps/app-001/icon?size=999');++ expect(response.status).toBe(400);+ });++ it('refreshes a cached raster derivative when the source file changes', async () => {+ const first = await requestBinary(app, '/api/apps/app-001/icon');+ await sharp({ create: { width: 512, height: 512, channels: 3, background: '#0000ff' } }).png().toFile(iconPath);+ const future = new Date(Date.now() + 2_000);+ utimesSync(iconPath, future, future);+ const second = await requestBinary(app, '/api/apps/app-001/icon');++ expect(second.headers.etag).not.toBe(first.headers.etag);+ expect(second.body).not.toEqual(first.body);+ });++ it('passes SVG icons through unchanged with the restrictive CSP', async () => {+ const svgPath = join(iconDir, 'icon.svg');+ const svg = '<svg xmlns="http://www.w3.org/2000/svg"><circle cx="4" cy="4" r="3"/></svg>';+ writeFileSync(svgPath, svg);+ appsService.getAppById.mockResolvedValue({ ...mockApp, appIconPath: svgPath });++ const response = await request(app).get('/api/apps/app-001/icon?size=64');++ expect(response.status).toBe(200);+ expect(response.text).toBe(svg);+ expect(response.headers['content-security-policy']).toBe("default-src 'none'; style-src 'unsafe-inline'");});it('should return 304 when If-None-Match matches ETag', async () => {@@ -87,7 +143,7 @@ describe('Apps Icon Routes', () => {const badSvgPath = join(iconDir, 'favicon.svg');const goodPngPath = join(iconDir, 'redetected.png');writeFileSync(badSvgPath, '<svg><image href="/logo.png"/></svg>');- writeFileSync(goodPngPath, 'fake-png-data');+ await sharp({ create: { width: 64, height: 64, channels: 3, background: '#00ff00' } }).png().toFile(goodPngPath);appsService.getAppById.mockResolvedValue({...mockApp,appIconPath: badSvgPath,