Skip to content

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

perf: compress API and built client responses (#8407)

[._.]/ Adam Eivyac51bd26162d
diff --git a/docs/DEPS.md b/docs/DEPS.md
index 9d02e2a0ed..2f7ae2f081 100644
--- a/docs/DEPS.md
+++ b/docs/DEPS.md
@@ -30,6 +30,7 @@ Before removing a Tier 3 candidate, run a transitive-dep check (`npm ls <pkg>`).
| `@googleapis/calendar` | 1 | KEEP | Calendar integration | Scoped official Google SDK (replaced monolithic `googleapis`) |
| `@googleapis/gmail` | 1 | KEEP | Messages/Gmail integration | Scoped official Google SDK |
| `chokidar` | 1 | KEEP | server file watching | Mature cross-platform file-system watcher used by server services |
+| `compression` | 1 | KEEP | server HTTP responses | Express-maintained Brotli and gzip negotiation for API and built client responses; preserves streaming and backpressure |
| `express` | 1 | KEEP | `server/index.js` + routes | Framework |
| `google-auth-library` | — | REMOVED (direct) | Google OAuth | Consolidated under `@googleapis/calendar`'s transitive `googleapis-common` dependency |
| `kokoro-js` | 2 | REMOVED | Former in-process TTS | Replaced by the in-tree Piper backend; existing settings migrate |
diff --git a/server/index.js b/server/index.js
index 6e72ec6002..808309d194 100644
--- a/server/index.js
+++ b/server/index.js
@@ -9,6 +9,7 @@ import { createTailscaleServers } from '../lib/tailscale-https.js';
import { certPaths } from '../lib/certPaths.js';
import { getBuildId, getStampedIndexHtml } from './lib/buildId.js';
import { getBuildIdentity } from './lib/buildIdentity.js';
+import { httpCompression } from './lib/httpCompression.js';
import { PORTS } from './lib/ports.js';
import { isSmokeBoot } from './lib/runtimeEnv.js';
@@ -254,6 +255,7 @@ app.use((req, res, next) => {
next();
});
// Make io available to routes
+app.use(httpCompression);
app.set('io', io);
// Auth gate runs BEFORE the body parsers so unauthenticated requests to
diff --git a/server/lib/README.md b/server/lib/README.md
index 2debb99d4d..5420c8ac44 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -393,6 +393,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows reaches the same place through a powershell supervisor started by a launcher that exits (never `detached:true`, which there means DETACHED_PROCESS and leaves a console host no console to run in), writing the same control files — so both platforms survive the restart AND take the runner's children down on cancel (`taskkill /T /F` there, the process group on POSIX). Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart, `isDetachedRunning(controlDir, expectedProcess?)` with optional executable/argument validation for fixed-command control dirs, and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |
| `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. |
| `httpDrain.js` | `createHttpDrain(servers)` tracks every ordinary request the HTTP listeners accept; `begin(windowMs)` is the synchronous shutdown step that stops intake on all of them (`server.close()` plus a 503 `Connection: close` gate for requests arriving on still-open keep-alive sockets), turns off keep-alive on in-flight responses, drops open SSE streams, and resolves `{ remaining }` once accepted requests finish or the window ends (#8323). |
+| `httpCompression.js` | `httpCompression` negotiates Brotli/gzip for API and static responses while preserving streaming, ranges, existing encodings, and `no-transform`. |
| `execGit.js` | `execGit(args, cwd, options)` and `execGitSafe(args, cwd, options)` shared process boundary for Git operations, worktrees, and `services/forgeAuth.js` credential resolution. The safe variant converts rejections into `{ exitCode: 1, stdout: '', stderr }`; `services/git.js` re-exports both for compatibility. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). |
| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. |
| `forgeAccessErrors.js` | `isForgeNoAccessError(err)` / `isForgeNoAccessMessage(text)` / `logForgeNoAccessOnce(scope, repoSpec, detail)` / `forgeNoAccessRemedy(repoSpec)` — tells a PERMANENT `gh` no-access 404 (`Could not resolve to a Repository`, `HTTP 404`) apart from a transient blip. `execGh` stamps `ghNoAccess` on the rejection and keeps it OUT of the consecutive-failure backoff (which caps at 15 min and then re-fires forever), and the polling jobs (`branchReconcile`, `prWatcher`) narrate it exactly once per scope+repo per process with a remedy line instead of once per tick. `__resetForgeNoAccessLog()` is the test seam. |
diff --git a/server/lib/httpCompression.js b/server/lib/httpCompression.js
new file mode 100644
index 0000000000..ba07d31403
--- /dev/null
+++ b/server/lib/httpCompression.js
@@ -0,0 +1,16 @@
+import compression from 'compression';
+import { constants } from 'node:zlib';
+
+const isStreamingType = (contentType = '') => /^(?:text\/event-stream|application\/x-ndjson|multipart\/x-mixed-replace)(?:\s*;|$)/i.test(contentType);
+
+export const httpCompression = compression({
+ threshold: 1024,
+ brotli: { params: { [constants.BROTLI_PARAM_QUALITY]: 4 } },
+ level: 6,
+ filter(req, res) {
+ if (req.headers.range || res.getHeader('Content-Encoding')) return false;
+ if (/(?:^|,)\s*no-transform\s*(?:,|$)/i.test(res.getHeader('Cache-Control') || '')) return false;
+ if (isStreamingType(res.getHeader('Content-Type'))) return false;
+ return compression.filter(req, res);
+ },
+});
diff --git a/server/lib/httpCompression.test.js b/server/lib/httpCompression.test.js
new file mode 100644
index 0000000000..4a1524ef0d
--- /dev/null
+++ b/server/lib/httpCompression.test.js
@@ -0,0 +1,96 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import express from 'express';
+import http from 'node:http';
+import { brotliDecompressSync, gunzipSync } from 'node:zlib';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { httpCompression } from './httpCompression.js';
+import { mountClientDist } from '../services/assetMounts.js';
+
+const payload = JSON.stringify({ providers: Array.from({ length: 200 }, (_, i) => ({ id: i, name: `Provider ${i}` })) });
+const chunk = 'export const data = ' + payload;
+let server;
+let port;
+const dist = mkdtempSync(join(tmpdir(), 'portos-compression-'));
+
+const get = (path, headers = {}) => new Promise((resolve, reject) => {
+ http.get({ host: '127.0.0.1', port, path, headers }, (res) => {
+ const chunks = [];
+ res.on('data', (part) => chunks.push(part));
+ res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks) }));
+ res.on('error', reject);
+ }).on('error', reject);
+});
+
+beforeAll(async () => {
+ const app = express();
+ app.use((_req, res, next) => { res.set('Vary', 'Origin'); next(); });
+ app.use(httpCompression);
+ app.get('/api/providers', (_req, res) => res.json(JSON.parse(payload)));
+ mkdirSync(join(dist, 'assets'));
+ writeFileSync(join(dist, 'assets', 'app.123abc.js'), chunk);
+ mountClientDist(app, dist);
+ app.get('/no-transform', (_req, res) => res.set('Cache-Control', 'no-transform').type('js').send(chunk));
+ app.get('/encoded', (_req, res) => res.set('Content-Encoding', 'custom').type('js').send(chunk));
+ app.get('/range', (req, res) => {
+ if (req.headers.range) return res.status(206).set('Content-Range', 'bytes 0-9/100').type('js').send(chunk.slice(0, 10));
+ return res.type('js').send(chunk);
+ });
+ app.get('/events', (_req, res) => res.set('Content-Type', 'text/event-stream').write('data: first\n\n'));
+ app.get('/frames', (_req, res) => res.set('Content-Type', 'application/x-ndjson').write('{"frame":1}\n'));
+ server = http.createServer(app);
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ port = server.address().port;
+});
+
+afterAll(async () => {
+ server.closeAllConnections();
+ await new Promise((resolve) => server.close(resolve));
+ rmSync(dist, { recursive: true, force: true });
+});
+
+describe('HTTP compression', () => {
+ it('negotiates Brotli for JSON and gzip for immutable JavaScript without losing Vary or cache policy', async () => {
+ const api = await get('/api/providers', { 'Accept-Encoding': 'br, gzip' });
+ expect(api.headers['content-encoding']).toBe('br');
+ expect(api.headers.vary).toMatch(/Origin/i);
+ expect(api.headers.vary).toMatch(/Accept-Encoding/i);
+ expect(brotliDecompressSync(api.body).toString()).toBe(payload);
+
+ const asset = await get('/assets/app.123abc.js', { 'Accept-Encoding': 'gzip' });
+ expect(asset.headers['content-encoding']).toBe('gzip');
+ expect(asset.headers['cache-control']).toBe('public, max-age=31536000, immutable');
+ expect(gunzipSync(asset.body).toString()).toBe(chunk);
+
+ const identity = await get('/api/providers');
+ expect(identity.headers['content-encoding']).toBeUndefined();
+ expect(identity.body.toString()).toBe(payload);
+ });
+
+ it('preserves no-transform, existing encodings, and range bytes', async () => {
+ for (const path of ['/no-transform', '/encoded']) {
+ const response = await get(path, { 'Accept-Encoding': 'br, gzip' });
+ expect(response.body.toString()).toBe(chunk);
+ }
+ const range = await get('/range', { 'Accept-Encoding': 'br, gzip', Range: 'bytes=0-9' });
+ expect(range.status).toBe(206);
+ expect(range.headers['content-encoding']).toBeUndefined();
+ expect(range.body.toString()).toBe(chunk.slice(0, 10));
+ });
+
+ it.each([['/events', 'data: first\n\n'], ['/frames', '{"frame":1}\n']])('delivers the first %s frame before stream completion', async (path, frame) => {
+ const response = await new Promise((resolve, reject) => {
+ http.get({ host: '127.0.0.1', port, path, headers: { 'Accept-Encoding': 'br, gzip' } }, (res) => {
+ res.once('data', (data) => {
+ resolve({ headers: res.headers, data: data.toString(), ended: res.complete });
+ res.destroy();
+ });
+ res.once('error', reject);
+ }).once('error', reject);
+ });
+ expect(response.headers['content-encoding']).toBeUndefined();
+ expect(response.data).toBe(frame);
+ expect(response.ended).toBe(false);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 89d1cedd51..29cb200c6b 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -712,6 +712,7 @@ export * from './videoTimelineFades.js';
// `tokenize` collides with `bm25.js`'s own tokenizer — namespaced like `runners`.
export * as voiceEcho from './voiceEcho.js';
export * from './voiceEngines.js';
+export * from './httpCompression.js';
export * from './auditQuality.js';
diff --git a/server/package-lock.json b/server/package-lock.json
index b4112cea1c..9c3ab09601 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -13,6 +13,7 @@
"@googleapis/gmail": "22.0.0",
"@novnc/novnc": "1.7.0",
"chokidar": "5.0.0",
+ "compression": "1.8.2",
"express": "5.2.1",
"node-pty": "1.2.0-beta.15",
"pg": "8.23.0",
@@ -1632,6 +1633,65 @@
"integrity": "sha512-VlfT9F3V0v+jr4yxPc5gg9s62/fIVWsd2Bk2iD435um1NlGMYdVCq+MjcXnhYq2icNOizHr1kK+5TI6H0Hy0ag==",
"license": "MIT"
},
+ "node_modules/compressible": {
+ "version": "2.0.18",
+ "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz",
+ "integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": ">= 1.43.0 < 2"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/compression": {
+ "version": "1.8.2",
+ "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.2.tgz",
+ "integrity": "sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ==",
+ "license": "MIT",
+ "dependencies": {
+ "bytes": "3.1.2",
+ "compressible": "~2.0.18",
+ "debug": "2.6.9",
+ "destroy": "1.2.0",
+ "negotiator": "~0.6.4",
+ "on-headers": "~1.1.0",
+ "safe-buffer": "5.2.1",
+ "vary": "~1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.8.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/compression/node_modules/debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "2.0.0"
+ }
+ },
+ "node_modules/compression/node_modules/ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
+ "license": "MIT"
+ },
+ "node_modules/compression/node_modules/negotiator": {
+ "version": "0.6.4",
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.4.tgz",
+ "integrity": "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/content-disposition": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz",
@@ -1759,6 +1819,16 @@
"node": ">= 0.8"
}
},
+ "node_modules/destroy": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
+ "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8",
+ "npm": "1.2.8000 || >= 1.4.16"
+ }
+ },
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -3207,6 +3277,15 @@
"node": ">= 0.8"
}
},
+ "node_modules/on-headers": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz",
+ "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
diff --git a/server/package.json b/server/package.json
index 38640b57bd..0c9b163293 100644
--- a/server/package.json
+++ b/server/package.json
@@ -26,6 +26,7 @@
"@googleapis/gmail": "22.0.0",
"@novnc/novnc": "1.7.0",
"chokidar": "5.0.0",
+ "compression": "1.8.2",
"express": "5.2.1",
"node-pty": "1.2.0-beta.15",
"pg": "8.23.0",