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

fix: keep the build stamp off the payload peers scrape and persist (#4694)

[._.]/ Adam Eivy4a13c24a04b9
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 9ef02dd024..f4e65dc4c6 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -109,7 +109,7 @@ import {
// not honour ESLint-style "global" block comments, so it is declared in
// biome.jsonc's `javascript.globals` instead.
import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage';
-import { BUNDLE_STAMP, describeBuild } from '../lib/buildStamp.js';
+import { TRUSTED_BUNDLE_STAMP, describeBuild } from '../lib/buildStamp.js';
import Logo from './Logo';
import { useErrorNotifications } from '../hooks/useErrorNotifications';
import { useNotifications } from '../hooks/useNotifications';
@@ -1209,7 +1209,10 @@ export default function Layout() {
// cannot carry: which commit is actually running (#4694). This is
// the zero-navigation surface — the full read-out, including
// bundle/server drift, is on /system-resources/overview.
- title={BUNDLE_STAMP ? `v${__APP_VERSION__} · ${describeBuild(BUNDLE_STAMP) ?? 'commit unknown'}` : undefined}
+ // TRUSTED_, not BUNDLE_: under `npm run dev` the Vite define is
+ // frozen at dev-server start while HMR serves every commit since,
+ // so a tooltip there would confidently report the wrong commit.
+ title={TRUSTED_BUNDLE_STAMP ? `v${__APP_VERSION__} · ${describeBuild(TRUSTED_BUNDLE_STAMP) ?? 'commit unknown'}` : undefined}
>
v{__APP_VERSION__}
</span>
diff --git a/client/src/components/system-resources/BuildStampPanel.jsx b/client/src/components/system-resources/BuildStampPanel.jsx
index 2740f94d0f..6335248916 100644
--- a/client/src/components/system-resources/BuildStampPanel.jsx
+++ b/client/src/components/system-resources/BuildStampPanel.jsx
@@ -1,7 +1,14 @@
+import { useEffect, useState } from 'react';
import { AlertTriangle, GitCommitHorizontal } from 'lucide-react';
import Pill from '../ui/Pill';
import Banner from '../ui/Banner';
-import { BUNDLE_STAMP, compareBuildStamps, describeBuild } from '../../lib/buildStamp.js';
+import * as api from '../../services/api';
+import {
+ SERVED_BUILD_ID,
+ TRUSTED_BUNDLE_STAMP,
+ compareBuildStamps,
+ describeBuild
+} from '../../lib/buildStamp.js';
import { timeAgo } from '../../utils/formatters';
/**
@@ -9,28 +16,40 @@ import { timeAgo } from '../../utils/formatters';
* the bundle this browser loaded (#4694). Why `version` cannot answer this: see
* the module header of `server/lib/buildIdentity.js`.
*
- * The mismatch banner is the point of the panel: it turns "my change isn't
+ * Fetched from `/api/system/build` rather than read off the health payload: peers
+ * scrape `/health/details` and persist it verbatim, so the stamp deliberately
+ * does not ride it (see that route's comment).
+ *
+ * The mismatch banner is the point of the panel — it turns "my change isn't
* showing up" from a debugging session into a visible fact. The same comparison
- * also runs unprompted on every page via the `build:id` socket frame — this is
- * the read-out, not the only detector.
+ * runs unprompted on every page via the `build:id` socket frame; this is the
+ * read-out, not the only detector.
*/
-export default function BuildStampPanel({ build, uptimeFormatted }) {
- const { state, bundleCommit, serverCommit } = compareBuildStamps(BUNDLE_STAMP, build);
+export default function BuildStampPanel({ uptimeFormatted }) {
+ const [build, setBuild] = useState(null);
+
+ // One fetch on mount, not on the page's 15s health poll: the commit a running
+ // process was started from cannot change without a restart, and a restart
+ // drops the socket and reloads the page anyway.
+ useEffect(() => {
+ let live = true;
+ api.getSystemBuild({ silent: true })
+ .then((data) => { if (live) setBuild(data); })
+ .catch(() => {});
+ return () => { live = false; };
+ }, []);
+
+ const { state, bundleCommit, serverCommit } = compareBuildStamps(TRUSTED_BUNDLE_STAMP, build);
const serverLabel = describeBuild({
commit: serverCommit,
branch: build?.branch,
dirty: build?.dirty
});
- const bundleLabel = describeBuild({ commit: BUNDLE_STAMP?.commit, branch: BUNDLE_STAMP?.branch });
-
- // Rendered even when both sides are unknown (a tarball install with no git),
- // so "we could not tell" is visible rather than looking like a missing feature.
- const footnote = state === 'match'
- ? 'Bundle and server agree — what you are looking at is the code that is running.'
- : state === 'unknown'
- ? 'Commit unknown on at least one side (no git metadata), so bundle/server drift cannot be checked here.'
- : null;
+ const bundleLabel = describeBuild({
+ commit: TRUSTED_BUNDLE_STAMP?.commit,
+ branch: TRUSTED_BUNDLE_STAMP?.branch
+ });
return (
<section className="rounded-xl border border-port-border bg-port-card p-4">
@@ -54,23 +73,45 @@ export default function BuildStampPanel({ build, uptimeFormatted }) {
<StampRow
label="Server"
value={serverLabel}
- // The server's `dirty` is read once at boot, so the whole row
- // describes the tree the process STARTED from — labelled as such
- // rather than implying a live read of the working tree.
+ // `dirty` is read once at boot, so the whole row describes the tree the
+ // process STARTED from — said plainly rather than implying a live read.
hint={uptimeFormatted ? `at start · up ${uptimeFormatted}` : 'at start'}
/>
<StampRow
label="This page"
value={bundleLabel}
- hint={BUNDLE_STAMP?.builtAt ? `built ${timeAgo(BUNDLE_STAMP.builtAt)}` : null}
+ hint={bundleHint()}
/>
</dl>
- {footnote && <p className="mt-3 text-xs text-gray-500">{footnote}</p>}
+ <p className="mt-3 text-xs text-gray-500">{footnote(state, build)}</p>
</section>
);
}
+function bundleHint() {
+ // Under `npm run dev` the Vite define is frozen at dev-server start while HMR
+ // serves every commit since, so reporting it would be actively misleading.
+ if (!SERVED_BUILD_ID) return 'dev server — no fixed bundle';
+ return TRUSTED_BUNDLE_STAMP?.builtAt ? `built ${timeAgo(TRUSTED_BUNDLE_STAMP.builtAt)}` : null;
+}
+
+function footnote(state, build) {
+ if (state === 'mismatch') return null;
+ if (state === 'unknown') {
+ return !SERVED_BUILD_ID
+ ? 'Running from the Vite dev server, so there is no built bundle to compare against the server.'
+ : 'Commit unknown on at least one side (no git metadata), so bundle/server drift cannot be checked here.';
+ }
+ // Matching commits are not the whole story: the comparison is commit-only, and
+ // the server tree can carry uncommitted edits that no commit id reflects.
+ // Claiming "this is the code that is running" there would be a false assurance
+ // in exactly the debugging session this panel exists to end.
+ return build?.dirty === false
+ ? 'Bundle and server agree — what you are looking at is the code that is running.'
+ : 'Bundle and server are on the same commit, but the server tree has changes that commit does not include.';
+}
+
function StampRow({ label, value, hint }) {
return (
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
diff --git a/client/src/components/system-resources/BuildStampPanel.test.jsx b/client/src/components/system-resources/BuildStampPanel.test.jsx
index 5098d2efde..7f43d5b8b3 100644
--- a/client/src/components/system-resources/BuildStampPanel.test.jsx
+++ b/client/src/components/system-resources/BuildStampPanel.test.jsx
@@ -1,5 +1,8 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { render, screen } from '@testing-library/react';
+import { render, screen, waitFor } from '@testing-library/react';
+
+const api = vi.hoisted(() => ({ getSystemBuild: vi.fn() }));
+vi.mock('../../services/api', () => api);
const serverBuild = (overrides = {}) => ({
commit: 'abc1234567890abcdef1234567890abcdef12345',
@@ -9,74 +12,101 @@ const serverBuild = (overrides = {}) => ({
...overrides,
});
-// `__BUILD_STAMP__` is a Vite define read once at module scope (so its identity
-// is stable across renders), which means a stub has to be in place BEFORE the
-// module graph loads — hence the re-import per case rather than a bare
-// `vi.stubGlobal` against an already-imported module.
-async function renderPanel({ stamp, ...props } = {}) {
+// `__BUILD_STAMP__` is a Vite define read once at module scope, and the trusted
+// form is additionally gated on the server-injected build-id meta tag — so both
+// have to be in place BEFORE the module graph loads.
+async function renderPanel({ stamp, served = 'aaaa1111bbbb', build = serverBuild(), ...props } = {}) {
vi.resetModules();
- if (stamp === undefined) vi.unstubAllGlobals();
- else vi.stubGlobal('__BUILD_STAMP__', stamp);
+ vi.unstubAllGlobals();
+ if (stamp !== undefined) vi.stubGlobal('__BUILD_STAMP__', stamp);
+ document.head.innerHTML = served
+ ? `<meta name="portos-build-id" content="${served}">`
+ : '';
+ api.getSystemBuild.mockResolvedValue(build);
const Panel = (await import('./BuildStampPanel.jsx')).default;
- return render(<Panel {...props} />);
+ const result = render(<Panel {...props} />);
+ await waitFor(() => expect(api.getSystemBuild).toHaveBeenCalled());
+ return result;
}
afterEach(() => {
vi.unstubAllGlobals();
+ document.head.innerHTML = '';
+ api.getSystemBuild.mockReset();
});
describe('BuildStampPanel', () => {
- it('renders the server commit and branch', async () => {
- await renderPanel({ build: serverBuild() });
+ it('reads the stamp from its own route, not the peer-scraped health payload', async () => {
+ await renderPanel();
- expect(screen.getByText('abc1234 · main')).toBeInTheDocument();
+ expect(api.getSystemBuild).toHaveBeenCalledWith({ silent: true });
+ await waitFor(() => expect(screen.getByText('abc1234 · main')).toBeInTheDocument());
});
it('flags a stale bundle when the page and the API were built from different commits', async () => {
- await renderPanel({ stamp: { commit: 'def5678', branch: 'main' }, build: serverBuild() });
+ await renderPanel({ stamp: { commit: 'def5678', branch: 'main' } });
- expect(screen.getByText(/stale relative to the server/i)).toBeInTheDocument();
+ await waitFor(() => expect(screen.getByText(/stale relative to the server/i)).toBeInTheDocument());
expect(screen.getByText('def5678')).toBeInTheDocument();
expect(screen.getByText('abc1234')).toBeInTheDocument();
});
- it('confirms agreement when the bundle and the server share a commit', async () => {
- await renderPanel({ stamp: { commit: 'abc1234', branch: 'main' }, build: serverBuild() });
+ it('confirms agreement only when the server tree is also clean', async () => {
+ await renderPanel({ stamp: { commit: 'abc1234', branch: 'main' } });
- expect(screen.getByText(/bundle and server agree/i)).toBeInTheDocument();
- expect(screen.queryByText(/stale relative to the server/i)).not.toBeInTheDocument();
+ await waitFor(() => expect(screen.getByText(/what you are looking at is the code that is running/i)).toBeInTheDocument());
+ });
+
+ it('does not claim the running code matches when the server tree has uncommitted changes', async () => {
+ // Commit-only comparison cannot see working-tree edits — asserting a match
+ // here would be a false assurance in the exact session this panel ends.
+ await renderPanel({
+ stamp: { commit: 'abc1234', branch: 'main' },
+ build: serverBuild({ dirty: true }),
+ });
+
+ await waitFor(() => expect(screen.getByText(/changes that commit does not include/i)).toBeInTheDocument());
+ expect(screen.queryByText(/what you are looking at is the code that is running/i)).not.toBeInTheDocument();
});
it('never claims agreement when the bundle stamp is unavailable', async () => {
- // The define is genuinely absent under vitest, and in a source-tarball
- // build. Reading it must not throw, and must not report a match nobody
- // verified.
- await renderPanel({ build: serverBuild() });
+ await renderPanel();
- expect(screen.getByText(/commit unknown on at least one side/i)).toBeInTheDocument();
- expect(screen.queryByText(/bundle and server agree/i)).not.toBeInTheDocument();
+ await waitFor(() => expect(screen.getByText(/commit unknown on at least one side/i)).toBeInTheDocument());
+ expect(screen.queryByText(/what you are looking at is the code that is running/i)).not.toBeInTheDocument();
expect(screen.queryByText(/stale relative to the server/i)).not.toBeInTheDocument();
});
+ it('distrusts the bundle stamp under the dev server, where it is frozen at startup', async () => {
+ // No injected meta tag = Vite is serving index.html. The define still holds
+ // the commit the dev server STARTED at while HMR serves everything since.
+ await renderPanel({ stamp: { commit: 'def5678', branch: 'main' }, served: null });
+
+ await waitFor(() => expect(screen.getByText(/no built bundle to compare/i)).toBeInTheDocument());
+ expect(screen.queryByText(/stale relative to the server/i)).not.toBeInTheDocument();
+ expect(screen.queryByText('def5678')).not.toBeInTheDocument();
+ });
+
it('renders "unknown" rather than blank rows when the server has no git metadata', async () => {
await renderPanel({ build: { commit: null, shortCommit: null, branch: null, dirty: null } });
- expect(screen.getAllByText('unknown').length).toBeGreaterThan(0);
+ await waitFor(() => expect(screen.getAllByText('unknown').length).toBeGreaterThan(0));
});
it('labels the server row as a boot-time snapshot, not a live tree read', async () => {
- // `dirty` is probed once per process, so presenting it as present-tense
- // would be a claim the data cannot support.
await renderPanel({ build: serverBuild({ dirty: true }), uptimeFormatted: '3h 12m' });
- expect(screen.getByText(/uncommitted changes/)).toBeInTheDocument();
+ await waitFor(() => expect(screen.getByText(/uncommitted changes/)).toBeInTheDocument());
expect(screen.getByText('at start · up 3h 12m')).toBeInTheDocument();
});
- it('survives a missing build block entirely (older server, no build field)', async () => {
- // A newer client can talk to an older server whose /health/details predates
- // this field — the panel must degrade, not crash the whole overview.
- await renderPanel({ build: undefined });
+ it('survives a failed build fetch (older server with no such route)', async () => {
+ vi.resetModules();
+ document.head.innerHTML = '';
+ api.getSystemBuild.mockRejectedValue(new Error('404'));
+ const Panel = (await import('./BuildStampPanel.jsx')).default;
+
+ render(<Panel />);
expect(screen.getByText('Running build')).toBeInTheDocument();
});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 28efdfb653..4f493df784 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -97,7 +97,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `bareUrl.js` | `parseBareUrl(text)` — the normalized URL when a capture's entire text is a URL, else null. Client mirror of the authoritative `server/lib/bareUrl.js` (parity enforced by `server/lib/bareUrl.mirror.test.js`), so the brain capture boxes preview the exact filing decision the server will make. Use this — not the looser `utils/urlNormalize.js` `isUrl` — anywhere the answer must match the server. |
| `youtubeUrl.js` | `isYoutubeVideoUrl(text)` / `youtubeVideoId(url)` — single-video YouTube URL detection. Client mirror of `YOUTUBE_INGEST_URL_RE` in `server/services/youtubeIngest.js` (behavioral parity pinned by `server/lib/youtubeUrl.mirror.test.js`); deliberately excludes playlists and channels. Quick Capture uses it to swap to the ingest submit path and reveal the ingest options panel. Also `INGEST_OPTIONS` — the single table of the three ingest artifacts (`key` / `settingKey` / `fallback` / `label` / `hint`) — plus `defaultIngestOptions()` and `ingestOptionsFromSettings(settings)`. Everything that enumerates the switches derives from that table; add an artifact there, not at each call site. |
| `boundedMap.js` | `evictOldest(map, max, onEvict?)` — evict oldest-first (`map.keys().next().value`) until a Map is within `max`, with an optional per-evicted-key teardown callback for a companion timer map; `ORPHAN_BUFFER_MAX` (64), the shared cap for the orphan-event race-buffers. The one home for the "stash an unmatched event in a `jobId → …` Map, evict the oldest on overflow" idiom shared by `useSceneRenderLifecycle`, `useImageGenQueue`, and `clientErrorReporter`. |
-| `buildStamp.js` | `BUNDLE_STAMP` (the `__BUILD_STAMP__` Vite define, read once through `typeof` so a missing define degrades instead of throwing) plus `compareBuildStamps(bundle, server)` / `describeBuild({commit, branch, dirty})` — does the bundle this browser loaded come from the same git commit the API is running (#4694)? Returns `match` / `mismatch` / `unknown`, where absent on either side is always `unknown` (never a claimed match, never a false alarm). Both halves use `null` as the absent sentinel, so a ref literally named "unknown" is a real value. Consumed by `services/socket.js` (unprompted drift toast on every page) and `components/system-resources/BuildStampPanel.jsx` (the read-out). |
+| `buildStamp.js` | Does the bundle this browser loaded come from the same git commit the API is running (#4694)? `SERVED_BUILD_ID` (the server-injected build-id meta tag; null under `npm run dev`) is the trust gate — `BUNDLE_STAMP` is the raw `__BUILD_STAMP__` Vite define, `TRUSTED_BUNDLE_STAMP` is it only when the page came from a real build, since the define is frozen at dev-server start while HMR serves every commit since. **Display or compare `TRUSTED_BUNDLE_STAMP`, never `BUNDLE_STAMP`.** `compareBuildStamps(bundle, server)` → `match`/`mismatch`/`unknown` (absent on either side is always `unknown`); `resolveBuildFrame(frame, {embeddedBuildId})` → `reload`/`drift`/`null`, the two staleness kinds that share the `build:id` socket frame and need different remedies; `describeBuild({commit, branch, dirty})` renders one line. Consumed by `services/socket.js`, `components/Layout.jsx`, and `components/system-resources/BuildStampPanel.jsx`. |
| `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup, dropping browser-extension errors (see `extensionErrors.js`) before either gate. Wired from `main.jsx`; never call directly from React components. |
| `clinicianReport.js` | Pure builders for the MeatSpace clinician-export view (`/meatspace/export`). `buildClinicianReport({ tests, config })` → structured report model (blood panels grouped by category with reference ranges + out-of-range flags, plus a lifestyle summary); `reportToMarkdown(report)` → copy-paste markdown. Reuses the Blood tab's `REFERENCE_RANGES` / `getBloodValueStatus` so printed flags match the UI. Also exports `buildBloodTestModel`, `buildLifestyleModel`, `getCategoryForKey`, `formatRange`. |
| `quotaBurnPatch.js` | `mergeQuotaBurnPatch(base, patch)` — mirrors the server's quota-burn config merge (top-level + per-family keys merge, a family's `jobs` array replaces) so the Quota Burn page can apply an edit optimistically and accumulate debounced edits into one PUT body. `applyQuotaBurnPreset(job, preset)` / `jobFromPreset(preset, { id, appId })` — copy a catalog prompt preset into a job, preserving the user's own step name and app choice. `quotaBurnJobIsSpent(job, ranAt)` — whether a `run once` step has had its one dispatch, gated on the optimistic config's own `runOnce` so a just-ticked checkbox reads as spent before the save round-trips (the client mirror of the server's `jobIsSpent`). `UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap(cap)` / `dispatchCapInput(value)` — the -1 "no dispatch cap" sentinel (the default), mirrored from the server. |
diff --git a/client/src/lib/buildStamp.js b/client/src/lib/buildStamp.js
index 2478d9db32..3d382fdba5 100644
--- a/client/src/lib/buildStamp.js
+++ b/client/src/lib/buildStamp.js
@@ -22,6 +22,25 @@
*/
export const BUNDLE_STAMP = typeof __BUILD_STAMP__ === 'undefined' ? null : __BUILD_STAMP__;
+/**
+ * The build id the server stamped into the served index.html, or null.
+ *
+ * Null means the page did NOT come from a built `client/dist` — i.e. `npm run
+ * dev`, where Vite serves its own index.html and the server never injects the
+ * meta tag. That is the single gate for trusting `BUNDLE_STAMP` at all: the
+ * Vite define is frozen when the dev server starts, so under HMR it reports the
+ * commit you started at while serving code from every commit since. Anything
+ * that displays or compares the bundle stamp must check this first.
+ */
+export const SERVED_BUILD_ID = (() => {
+ if (typeof document === 'undefined') return null;
+ const el = document.querySelector('meta[name="portos-build-id"]');
+ return el ? el.getAttribute('content') : null;
+})();
+
+/** The bundle stamp only when it can be trusted — see `SERVED_BUILD_ID`. */
+export const TRUSTED_BUNDLE_STAMP = SERVED_BUILD_ID ? BUNDLE_STAMP : null;
+
/**
* Trim a stamp field to a usable value, or null. Both halves of the feature emit
* `null` for "not known", so this only has to reject blanks and non-strings —
diff --git a/client/src/pages/SystemHealthPage.jsx b/client/src/pages/SystemHealthPage.jsx
index 31ca6b7821..2e8804d664 100644
--- a/client/src/pages/SystemHealthPage.jsx
+++ b/client/src/pages/SystemHealthPage.jsx
@@ -274,7 +274,7 @@ function SystemHealthOverview() {
<MediaCapacityPanel media={health.media} />
- <BuildStampPanel build={health.build} uptimeFormatted={health.system.uptimeFormatted} />
+ <BuildStampPanel uptimeFormatted={health.system.uptimeFormatted} />
<section className="bg-port-card border border-port-border rounded-xl p-4">
<h3 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
diff --git a/client/src/pages/SystemHealthPage.test.jsx b/client/src/pages/SystemHealthPage.test.jsx
index 949aa05710..9adbb313e8 100644
--- a/client/src/pages/SystemHealthPage.test.jsx
+++ b/client/src/pages/SystemHealthPage.test.jsx
@@ -31,6 +31,9 @@ vi.mock('../services/api', () => ({
// provider readiness (#4348). No peers keeps this page's assertions about
// local metrics unaffected.
getInstances: vi.fn(() => Promise.resolve({ peers: [] })),
+ // The overview's build-stamp panel fetches its own route (#4694) — the stamp
+ // deliberately does not ride the peer-scraped health payload.
+ getSystemBuild: vi.fn(() => Promise.resolve({ commit: null, shortCommit: null, branch: null, dirty: null })),
}));
vi.mock('../hooks/useProviderModels', () => ({
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 1587ace6d1..d2f513bc72 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -24,6 +24,9 @@ export const getCharacter = ({ skills = true, metrics = true, ...options } = {})
// Health
export const checkHealth = (options) => request('/system/health', options);
export const getSystemHealth = (options) => request('/system/health/details', options);
+// Its own route, not a field on health/details — peers scrape that payload and
+// persist it verbatim, and the build stamp must stay machine-local (#4694).
+export const getSystemBuild = (options) => request('/system/build', options);
export const runSystemResourceReport = (options = {}) => request('/system-resources/report', {
method: 'POST',
...options,
diff --git a/client/src/services/socket.js b/client/src/services/socket.js
index 8d18a41a2f..d5718d9ac7 100644
--- a/client/src/services/socket.js
+++ b/client/src/services/socket.js
@@ -1,6 +1,7 @@
import { io } from 'socket.io-client';
import { showStaleBuildToast, showBuildDriftToast } from './staleBuildToast';
-import { resolveBuildFrame } from '../lib/buildStamp.js';
+import { resolveBuildFrame, SERVED_BUILD_ID } from '../lib/buildStamp.js';
+import toast from '../components/ui/Toast';
// Connect to Socket.IO using relative path (works with Tailscale)
// The connection will use the same host the page was loaded from
@@ -33,22 +34,34 @@ socket.on('connect_error', (err) => {
// Other connection errors: Socket.IO will retry automatically.
});
-// Embedded build id from the served index.html. The server injects a
-// <meta name="portos-build-id" content="..."> tag into index.html at boot;
-// a freshly-rebuilt-and-restarted server will have a different id, and the
-// `build:id` socket event below catches the mismatch so the tab can reload.
-const EMBEDDED_BUILD_ID = (() => {
- if (typeof document === 'undefined') return null;
- const el = document.querySelector('meta[name="portos-build-id"]');
- return el ? el.getAttribute('content') : null;
-})();
+// Embedded build id from the served index.html — the server injects a
+// <meta name="portos-build-id"> tag at boot, and a freshly-rebuilt-and-restarted
+// server carries a different one. Defined in lib/buildStamp.js so the drift
+// check here and the surfaces that DISPLAY the bundle stamp share one answer to
+// "was this page served from a real build?".
+const EMBEDDED_BUILD_ID = SERVED_BUILD_ID;
// One frame, two different staleness problems with two different remedies —
// `resolveBuildFrame` owns that decision (it is pure and tested); this just
// dispatches, once per kind per tab.
+const TOAST_IDS = { reload: 'portos-stale-build', drift: 'portos-build-drift' };
const shown = { reload: false, drift: false };
socket.on('build:id', (frame) => {
const action = resolveBuildFrame(frame, { embeddedBuildId: EMBEDDED_BUILD_ID });
+
+ // Both toasts are sticky, and the drift one deliberately offers no button
+ // (its remedy is a rebuild or a server restart, which reloading cannot do).
+ // A server restart drops and re-establishes this socket, so the reconnect
+ // frame is exactly where we learn the drift is gone — clear the toast and the
+ // latch there, or the pill keeps asserting a mismatch that no longer exists
+ // for the rest of the tab's life.
+ for (const [kind, id] of Object.entries(TOAST_IDS)) {
+ if (kind !== action && shown[kind]) {
+ shown[kind] = false;
+ toast.dismiss(id);
+ }
+ }
+
if (!action || shown[action]) return;
shown[action] = true;
if (action === 'reload') showStaleBuildToast();
diff --git a/server/lib/README.md b/server/lib/README.md
index 325a2872c0..d217ac02c6 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -363,7 +363,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `tribeMatch.js` | Pure, deterministic matcher mapping a calendar attendee / message counterpart (`{ email, phone, name }`) to a tracked Tribe person for auto-logged touchpoints (#2033, #2151): `buildPersonMatchIndex(people)` → `{ byIdentifier, byPhone, byName }`, `matchPerson(identity, index)` (email/handle authoritative, then E.164 phone, then exact unique name fallback — no fuzzy matching), `matchPeople(identities, index)` → de-duplicated Set of personIds, `normalizeIdentifier(value)`, `normalizePhone(value)` (E.164 normalization for iMessage/Signal handles), `identityFromHandle(handle)` (classify a raw `chat.db` handle into email-or-phone). Consumed by `autoLogTouchpoints` in `services/tribe.js` from the calendar, message, and iMessage sync producers. |
| `viteAllowedHosts.js` | Detect and remediate a managed app's Vite `server.allowedHosts`. `findViteConfig(repoPath)` locates the config; `parseAllowedHosts(src)` / `hostIsAllowed(parsed, host)` decide whether a Tailscale/IP host would be accepted (mirrors Vite's localhost+IP-always-allowed and leading-dot-suffix rules); `rewriteAllowedHosts(src)` deterministically injects `allowedHosts: true` (or bails `ok:false` on ambiguous shapes so the caller can fall back to an LLM fix); `checkViteHost(repoPath, host)` is the one-shot status used by `GET /api/apps/:id/vite-host-check`. |
| `buildId.js` | Build-ID derived from the built client bundle. |
-| `buildIdentity.js` | `getBuildIdentity()` / `getCachedBuildIdentity()` / `formatBuildIdentity()` / `parsePorcelainV2()` — which git commit the RUNNING server process was started from (#4694): `{ commit, shortCommit, branch, dirty }` from ONE `git status --porcelain=v2 --branch` spawn, cached per process (the promise, so concurrent first callers share it). Answers "is this the code I am testing?" on a machine where one PM2 server serves :5555 while many worktrees hold different code — `version` cannot, since package.json's version is identical across every development commit. Complements `buildId.js` (bundle hash, not commit); both ride the same `build:id` socket frame. Non-throwing, every field independently nullable (no `.git` → `commit: null`, never `''`). Commit/branch/dirty only — no paths, hostname, username, or timestamp (uptime already lives on the health payload). |
+| `buildIdentity.js` | `getBuildIdentity()` / `getCachedBuildIdentity()` / `formatBuildIdentity()` / `parsePorcelainV2()` — which git commit the RUNNING server process was started from (#4694): `{ commit, shortCommit, branch, dirty }` from ONE `git status --porcelain=v2 --branch` spawn, cached per process (the promise, so concurrent first callers share it). Answers "is this the code I am testing?" on a machine where one PM2 server serves :5555 while many worktrees hold different code — `version` cannot, since package.json's version is identical across every development commit. Served on its own `GET /api/system/build`, NOT on `/health/details`: peers scrape that payload and persist it verbatim, and this stays machine-local. Complements `buildId.js` (bundle hash, not commit); both ride the same `build:id` socket frame. Non-throwing, every field independently nullable (no `.git` → `commit: null`, never `''`). |
## General utilities
diff --git a/server/routes/health.test.js b/server/routes/health.test.js
index 1aed9732d7..5b3f46d407 100644
--- a/server/routes/health.test.js
+++ b/server/routes/health.test.js
@@ -146,11 +146,11 @@ describe('System Health Routes', () => {
expect(response.body).toHaveProperty('overallHealth');
});
- it('stamps the running build on health details (#4694)', async () => {
- const response = await request(app).get('/api/system/health/details');
+ it('serves the running build on its own route (#4694)', async () => {
+ const response = await request(app).get('/api/system/build');
expect(response.status).toBe(200);
- expect(response.body.build).toEqual({
+ expect(response.body).toEqual({
commit: 'abc1234567890abcdef1234567890abcdef12345',
shortCommit: 'abc1234',
branch: 'main',
@@ -158,23 +158,27 @@ describe('System Health Routes', () => {
});
});
- it('keeps the build stamp OFF the always-public /health payload', async () => {
- // /api/system/health is in PUBLIC_API_PATHS (lib/authGate.js) — a branch
- // name can carry an issue title, so the stamp stays behind the auth gate.
- const response = await request(app).get('/api/system/health');
-
- expect(response.status).toBe(200);
- expect(response.body).not.toHaveProperty('build');
+ it('keeps the build stamp OFF every payload peers scrape (#4694)', async () => {
+ // THE federation boundary for this feature, and the reason /build is its
+ // own route. `probePeer` (services/instances.js) fetches /health/details
+ // from every configured peer and persists the whole JSON verbatim as
+ // `peer.lastHealth` — so a `build` field there would ship the branch name
+ // (which can carry an issue title) to someone else's install and land on
+ // their disk. /health is additionally in the always-public set.
+ for (const path of ['/api/system/health', '/api/system/health/details']) {
+ const response = await request(app).get(path);
+ expect(response.status).toBe(200);
+ expect(response.body).not.toHaveProperty('build');
+ expect(JSON.stringify(response.body)).not.toContain('abc1234');
+ }
});
- it('degrades the build stamp to null instead of failing the whole health report', async () => {
- getBuildIdentity.mockRejectedValueOnce(new Error('git exploded'));
-
- const response = await request(app).get('/api/system/health/details');
+ it('never leaks a path, hostname, or username through the build route', async () => {
+ const response = await request(app).get('/api/system/build');
- expect(response.status).toBe(200);
- expect(response.body.build).toBeNull();
- expect(response.body).toHaveProperty('overallHealth');
+ expect(Object.keys(response.body).sort()).toEqual(
+ ['branch', 'commit', 'dirty', 'shortCommit']
+ );
});
diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.js
index f1fb84b371..45386d30fe 100644
--- a/server/routes/systemHealth.js
+++ b/server/routes/systemHealth.js
@@ -47,6 +47,23 @@ router.get('/processing', asyncHandler(async (req, res) => {
res.json(await getActiveProcessing());
}));
+/**
+ * GET /api/system/build — which git commit THIS server process is running (#4694).
+ *
+ * Deliberately its OWN route rather than a field on /health/details, which
+ * looks auth-gated but is not private: `probePeer` in services/instances.js
+ * fetches /health/details from every configured peer and persists the whole
+ * JSON verbatim as `peer.lastHealth`. Anything added there therefore leaves
+ * the machine and is written to disk on someone else's install — and a branch
+ * name can carry an issue title. Peers do not probe this path, so the stamp
+ * stays local by construction rather than by a promise nobody can enforce.
+ * See the root CLAUDE.md privacy rules and #4694 ("local-only diagnostic data
+ * — must not join a sync payload"). `systemHealth.test.js` pins both halves.
+ */
+router.get('/build', asyncHandler(async (req, res) => {
+ res.json(await getBuildIdentity());
+}));
+
router.get('/health', asyncHandler(async (req, res) => {
const [self, version, authRequired] = await Promise.all([
getSelf().catch(() => null),
@@ -84,7 +101,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {
const startTime = Date.now();
// Gather data in parallel
- const [pm2Processes, appStatusSummary, cosStatus, self, dbHealth, version, diskStats, memStats, thresholds, forgeHealth, mediaCapacity, build] = await Promise.all([
+ const [pm2Processes, appStatusSummary, cosStatus, self, dbHealth, version, diskStats, memStats, thresholds, forgeHealth, mediaCapacity] = await Promise.all([
listProcesses().catch(() => []),
apps.getAppStatusSummary().catch(() => ({ total: 0, online: 0, stopped: 0, notStarted: 0, unknown: 0, degraded: false, unmanaged: 0 })),
cos.getStatus().catch(() => null),
@@ -97,13 +114,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {
checkGhHealth().catch(() => ({ status: 'error', ok: false, detail: 'Health check failed', remedy: null, checkedAt: null })),
// Media-lane capacity never fails the health report: an unreadable GPU probe
// degrades to `null`, which the UI renders as unknown rather than as idle.
- getMediaCapacity().catch(() => null),
- // Which git commit THIS server process is running (#4694). Details-only:
- // /api/system/health is in the always-public set (lib/authGate.js), and a
- // branch name can carry an issue title, so the stamp stays behind the auth
- // gate. `getBuildIdentity` is non-throwing by contract; the catch keeps a
- // future change to it from being able to fail the whole health report.
- getBuildIdentity().catch(() => null)
+ getMediaCapacity().catch(() => null)
]);
const memUsagePercent = Math.round((memStats.used / memStats.total) * 100);
@@ -298,7 +309,6 @@ router.get('/health/details', asyncHandler(async (req, res) => {
apps: appStats,
cos: cosInfo,
media: mediaCapacity,
- build,
database: dbHealth,
forge: forgeHealth,
thresholds,