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: stop the commit reaching peers over the socket, and read a failed status honestly (#4694)

[._.]/ Adam Eivyf2d41837c488
diff --git a/client/src/components/system-resources/BuildStampPanel.jsx b/client/src/components/system-resources/BuildStampPanel.jsx
index be10bb6ddb..632c4cc9e5 100644
--- a/client/src/components/system-resources/BuildStampPanel.jsx
+++ b/client/src/components/system-resources/BuildStampPanel.jsx
@@ -22,8 +22,8 @@ import { timeAgo } from '../../utils/formatters';
*
* 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
- * 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 load (services/socket.js wires the watcher);
+ * this is the read-out, not the only detector.
*/
export default function BuildStampPanel({ uptimeFormatted }) {
const [build, setBuild] = useState(null);
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 4f493df784..3b14221e2b 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` | 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`. |
+| `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(signals, {embeddedBuildId})` → `reload`/`drift`/`null`, the two staleness kinds that need different remedies; `createBuildDriftWatcher({embeddedBuildId, fetchIdentity, onShow, onClear})` is the tested state machine that merges the pushed bundle hash with the fetched commit and latches once per kind; `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 3d382fdba5..78533618f8 100644
--- a/client/src/lib/buildStamp.js
+++ b/client/src/lib/buildStamp.js
@@ -99,28 +99,99 @@ export function describeBuild({ commit, branch, dirty } = {}) {
}
/**
- * Decide what a `build:id` socket frame means for THIS tab (#4694).
+ * Decide what the server's build signals mean for THIS tab (#4694).
*
- * Two different staleness problems arrive on one frame, and they have different
- * remedies — conflating them tells the user to do something that cannot work:
+ * Two different staleness problems, with different remedies — conflating them
+ * tells the user to do something that cannot work:
*
* `'reload'` — the bundle on disk moved since this tab loaded. Reloading picks
* up the new one.
* `'drift'` — this tab IS current with the dist on disk, but that dist was
- * built from a different commit than the server is running. Reloading
- * re-serves the same stale dist and changes nothing; it needs a rebuild or a
+ * built from a different commit than the server is running. Reloading alone
+ * re-serves the same stale dist; it needs a rebuild (then a reload) or a
* server restart.
* `null` — nothing to say.
*
- * `embeddedBuildId` is null under `npm run dev` (Vite serves its own index.html,
- * so the server never injects the build-id meta tag). That is the gate for BOTH
- * checks: in dev there is no dist to be stale, and the Vite define is frozen at
+ * The two signals arrive by different routes — the bundle hash is pushed on the
+ * `build:id` socket frame, while the commit is fetched from
+ * `GET /api/system/build`, because the socket path reaches peer relays and the
+ * commit must stay machine-local (see services/socket.js). So this takes a
+ * merged view rather than one frame.
+ *
+ * `embeddedBuildId` is null under `npm run dev` (Vite serves its own
+ * index.html, so the server never injects the meta tag). That gates BOTH checks:
+ * in dev there is no dist to be stale, and the Vite define is frozen at
* dev-server start, so a drift check there would fire the moment you commit.
*
* @returns {'reload'|'drift'|null}
*/
-export function resolveBuildFrame({ buildId, commit } = {}, { embeddedBuildId, bundle = BUNDLE_STAMP } = {}) {
+export function resolveBuildFrame({ buildId, commit } = {}, { embeddedBuildId, bundle = TRUSTED_BUNDLE_STAMP } = {}) {
if (!buildId || !embeddedBuildId) return null;
if (buildId !== embeddedBuildId) return 'reload';
return compareBuildStamps(bundle, { commit }).state === 'mismatch' ? 'drift' : null;
}
+
+/**
+ * The stateful half of the drift check: merge the two signals as they arrive,
+ * decide once per kind, and clear a toast when its problem goes away.
+ *
+ * A factory taking its effects as arguments, rather than reaching for the socket
+ * and the toast module directly, so the dispatch logic is testable — the module
+ * that wires it opens a real Socket.IO connection at import and cannot be loaded
+ * in a unit test.
+ *
+ * @param {object} deps
+ * @param {string|null} deps.embeddedBuildId - see `SERVED_BUILD_ID`
+ * @param {() => Promise<{commit?: string|null}|null>} deps.fetchIdentity
+ * @param {(action: 'reload'|'drift') => void} deps.onShow
+ * @param {(action: 'reload'|'drift') => void} deps.onClear
+ */
+export function createBuildDriftWatcher({ embeddedBuildId, fetchIdentity, onShow, onClear }) {
+ const signals = { buildId: null, commit: null };
+ const shown = { reload: false, drift: false };
+
+ const evaluate = () => {
+ const action = resolveBuildFrame(signals, { embeddedBuildId });
+
+ // Both notices are sticky, and the drift one has no button (a bare reload
+ // cannot fix it). Clearing on the signal that says the problem is gone is
+ // the only way they come down — otherwise one keeps asserting a mismatch
+ // that no longer exists for the rest of the tab's life.
+ for (const kind of ['reload', 'drift']) {
+ if (kind !== action && shown[kind]) {
+ shown[kind] = false;
+ onClear(kind);
+ }
+ }
+
+ if (!action || shown[action]) return;
+ shown[action] = true;
+ onShow(action);
+ };
+
+ return {
+ /** The pushed bundle hash. */
+ onBuildId(buildId) {
+ signals.buildId = buildId ?? null;
+ evaluate();
+ },
+ /**
+ * Re-read the server's commit. Called on every (re)connect, because a server
+ * restart is one of the remedies and the reconnect is where we learn the
+ * drift is gone.
+ *
+ * Clears the previous commit FIRST: it belongs to the server we were talking
+ * to before. Keeping it while the fetch is in flight would judge the new
+ * server by the old one's commit — and if the fetch fails outright (an older
+ * server with no such route), a stale commit would have the toast asserting
+ * drift against a server that no longer exists.
+ */
+ async refreshIdentity() {
+ signals.commit = null;
+ evaluate();
+ const identity = await fetchIdentity().catch(() => null);
+ signals.commit = identity?.commit ?? null;
+ evaluate();
+ }
+ };
+}
diff --git a/client/src/lib/buildStamp.test.js b/client/src/lib/buildStamp.test.js
index 5d1620ba9b..24d72e2f39 100644
--- a/client/src/lib/buildStamp.test.js
+++ b/client/src/lib/buildStamp.test.js
@@ -1,5 +1,5 @@
-import { describe, it, expect } from 'vitest';
-import { compareBuildStamps, describeBuild, resolveBuildFrame } from './buildStamp.js';
+import { describe, it, expect, vi } from 'vitest';
+import { compareBuildStamps, createBuildDriftWatcher, describeBuild, resolveBuildFrame } from './buildStamp.js';
describe('compareBuildStamps', () => {
it('matches a bundle short commit against the server short commit', () => {
@@ -145,3 +145,100 @@ describe('resolveBuildFrame', () => {
)).toBeNull();
});
});
+
+describe('createBuildDriftWatcher', () => {
+ const embeddedBuildId = 'aaaa1111bbbb';
+
+ // `__BUILD_STAMP__` is absent under vitest, so the bundle side is always
+ // unknown here and every case below turns on the reload half plus the
+ // never-assert-drift-without-both-sides rule. The commit comparison itself is
+ // covered directly by the compareBuildStamps cases above.
+ function makeWatcher({ commit = 'abc1234', fail = false } = {}) {
+ const shown = [];
+ const cleared = [];
+ const fetchIdentity = vi.fn(() =>
+ fail ? Promise.reject(new Error('404')) : Promise.resolve({ commit }));
+ const watcher = createBuildDriftWatcher({
+ embeddedBuildId,
+ fetchIdentity,
+ onShow: (a) => shown.push(a),
+ onClear: (a) => cleared.push(a)
+ });
+ return { watcher, shown, cleared, fetchIdentity };
+ }
+
+ it('raises the reload notice when the bundle hash moved', () => {
+ const { watcher, shown } = makeWatcher();
+
+ watcher.onBuildId('cccc2222dddd');
+
+ expect(shown).toEqual(['reload']);
+ });
+
+ it('raises each notice at most once, however many signals arrive', () => {
+ const { watcher, shown } = makeWatcher();
+
+ watcher.onBuildId('cccc2222dddd');
+ watcher.onBuildId('cccc2222dddd');
+ watcher.onBuildId('cccc2222dddd');
+
+ expect(shown).toEqual(['reload']);
+ });
+
+ it('clears the reload notice once the tab is current again', () => {
+ // A sticky notice with no path down is worse than none: it keeps asserting
+ // a problem the user already fixed.
+ const { watcher, shown, cleared } = makeWatcher();
+
+ watcher.onBuildId('cccc2222dddd');
+ watcher.onBuildId(embeddedBuildId);
+
+ expect(shown).toEqual(['reload']);
+ expect(cleared).toEqual(['reload']);
+ });
+
+ it('re-raises after a clear, so a second genuine problem is not swallowed', () => {
+ const { watcher, shown } = makeWatcher();
+
+ watcher.onBuildId('cccc2222dddd');
+ watcher.onBuildId(embeddedBuildId);
+ watcher.onBuildId('eeee3333ffff');
+
+ expect(shown).toEqual(['reload', 'reload']);
+ });
+
+ it('drops the previous commit before re-reading it on reconnect', async () => {
+ // The old commit belongs to the server we were talking to before. Judging a
+ // restarted server by it would assert drift against a server that is gone.
+ const { watcher, fetchIdentity } = makeWatcher();
+
+ await watcher.refreshIdentity();
+ await watcher.refreshIdentity();
+
+ expect(fetchIdentity).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not assert drift when the identity fetch fails (older server)', async () => {
+ const { watcher, shown } = makeWatcher({ fail: true });
+
+ watcher.onBuildId(embeddedBuildId);
+ await watcher.refreshIdentity();
+
+ expect(shown).toEqual([]);
+ });
+
+ it('stays silent under the dev server, where no build id is embedded', async () => {
+ const shown = [];
+ const watcher = createBuildDriftWatcher({
+ embeddedBuildId: null,
+ fetchIdentity: () => Promise.resolve({ commit: 'def5678' }),
+ onShow: (a) => shown.push(a),
+ onClear: () => {},
+ });
+
+ watcher.onBuildId('dev');
+ await watcher.refreshIdentity();
+
+ expect(shown).toEqual([]);
+ });
+});
diff --git a/client/src/services/socket.js b/client/src/services/socket.js
index d5718d9ac7..cee1ede15e 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, SERVED_BUILD_ID } from '../lib/buildStamp.js';
+import { createBuildDriftWatcher, SERVED_BUILD_ID } from '../lib/buildStamp.js';
+import { getSystemBuild } from './apiSystem';
import toast from '../components/ui/Toast';
// Connect to Socket.IO using relative path (works with Tailscale)
@@ -45,29 +46,22 @@ const EMBEDDED_BUILD_ID = SERVED_BUILD_ID;
// `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();
- else showBuildDriftToast();
+// The bundle hash arrives on the socket; the commit is FETCHED over the
+// authenticated API, because the server's `connection` handler also fires for
+// peer relays and must not ship this machine's branch name to another install
+// (see server/services/socket.js and routes/systemHealth.js). The merge and
+// the once-per-kind latching live in a tested factory.
+const buildWatcher = createBuildDriftWatcher({
+ embeddedBuildId: EMBEDDED_BUILD_ID,
+ fetchIdentity: () => getSystemBuild({ silent: true }),
+ onShow: (action) => (action === 'reload' ? showStaleBuildToast() : showBuildDriftToast()),
+ onClear: (action) => toast.dismiss(TOAST_IDS[action])
});
+socket.on('build:id', ({ buildId } = {}) => buildWatcher.onBuildId(buildId));
+socket.on('connect', () => { buildWatcher.refreshIdentity(); });
+
export default socket;
/**
diff --git a/client/vite.config.js b/client/vite.config.js
index b8e9f26585..e19f3afd0d 100644
--- a/client/vite.config.js
+++ b/client/vite.config.js
@@ -35,6 +35,27 @@ function gitStamp(args) {
}
}
+// Separate from `gitStamp` on purpose: `status --porcelain` prints NOTHING for
+// a clean tree, so that helper's `|| null` would make clean and failed
+// identical — and reading a failure as clean is exactly what lets the panel
+// claim an agreement it never verified. Here the empty string IS the answer,
+// and only a throw means "could not check".
+//
+// Returns true (dirty) / false (clean) / null (unknown).
+function gitDirty() {
+ try {
+ const out = execFileSync('git', ['status', '--porcelain', '--', '.'], {
+ cwd: CONFIG_DIR,
+ encoding: 'utf-8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ timeout: 5000
+ });
+ return out.trim() !== '';
+ } catch {
+ return null;
+ }
+}
+
function buildStamp() {
const head = gitStamp(['rev-parse', '--abbrev-ref', 'HEAD']);
// Were the CLIENT sources uncommitted when this bundle was built? Scoped to
@@ -43,12 +64,6 @@ function buildStamp() {
// ordinary server work. Without this the commit id alone is not enough — a
// dist built from an edited tree carries its parent's clean commit, and the
// panel would assert full agreement for code that was never committed.
- //
- // `--porcelain` prints nothing for a clean tree, so `gitStamp` returns null
- // there — which is indistinguishable from a failed probe. Re-probe with a
- // marker instead: `--porcelain` plus `rev-parse --is-inside-work-tree` tells
- // us the command CAN run, so a null status means clean rather than unknown.
- const inRepo = gitStamp(['rev-parse', '--is-inside-work-tree']) === 'true';
return {
commit: gitStamp(['rev-parse', '--short=7', 'HEAD']),
// `rev-parse --abbrev-ref` prints the literal string `HEAD` on a detached
@@ -56,7 +71,7 @@ function buildStamp() {
// named HEAD, so this is never a real branch.)
branch: head === 'HEAD' ? null : head,
// null = we could not check, distinct from false = checked and clean.
- dirty: inRepo ? gitStamp(['status', '--porcelain', '--', '.']) !== null : null,
+ dirty: gitDirty(),
// Commit / branch / dirty / timestamp only. No paths (they embed the OS
// username), no hostname — this ships to every browser that loads the app.
builtAt: new Date().toISOString()
diff --git a/server/lib/README.md b/server/lib/README.md
index d217ac02c6..70cca2a466 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. 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 `''`). |
+| `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), which travels separately on the `build:id` socket frame — the socket path reaches peer relays, so the commit does not use it. Non-throwing, every field independently nullable (no `.git` → `commit: null`, never `''`). |
## General utilities
diff --git a/server/lib/buildIdentity.js b/server/lib/buildIdentity.js
index 66764215ac..2794e5384f 100644
--- a/server/lib/buildIdentity.js
+++ b/server/lib/buildIdentity.js
@@ -16,8 +16,9 @@
* hash says nothing about which commit either side was built from: a `dist/`
* built three days ago and one built this minute are both "current" to buildId
* as long as the browser matches the file. This module answers the other half —
- * WHICH CODE is up. The two ride the same `build:id` socket frame precisely
- * because they are complementary halves of one question.
+ * WHICH CODE is up. They travel separately on purpose: the bundle hash is pushed
+ * to every socket, while this is served only over `GET /api/system/build`,
+ * because the socket path also reaches peer relays (see services/socket.js).
*
* Privacy: commit / branch / dirty only. No absolute paths (they embed the OS
* username), no hostname, no checkout directory — see the Sensitive Data
@@ -124,8 +125,13 @@ async function probe() {
return { identity: parsePorcelainV2(result.stdout), definitive: true };
}
+// Backoff after a transient probe failure — long enough that a burst of socket
+// reconnects collapses to one attempt, short enough to self-heal unattended.
+const RETRY_COOLDOWN_MS = 30_000;
+
let cached = null;
let resolved = null;
+let retryBlockedUntil = 0;
/**
* Resolve the running build's git identity. Cached for the life of the process:
@@ -140,18 +146,33 @@ let resolved = null;
*
* Non-throwing. Every field is independently nullable: a tarball install with
* no `.git`, a detached checkout, or a git timeout reports `commit: null`. A
- * timeout is retried on the next call; a definitive "not a repo" is not.
+ * timeout is retried (after a cooldown); a definitive "not a repo" is not.
*
* @returns {Promise<{commit: string|null, shortCommit: string|null, branch: string|null, dirty: boolean|null}>}
*/
export function getBuildIdentity() {
+ if (!cached && retryBlockedUntil > Date.now()) return Promise.resolve(UNKNOWN_IDENTITY);
cached ??= probe().then(({ identity, definitive }) => {
- resolved = identity;
// Release the cache when the probe merely FAILED, so the next caller retries
// instead of inheriting a transient null forever. A definitive answer —
// including "not a git checkout" — is kept, preserving the one-spawn
// property for real repos and tarball installs alike.
- if (!definitive) cached = null;
+ //
+ // `resolved` is set ONLY on a definitive answer, for the same reason: it
+ // backs the synchronous accessor, and an all-null tuple parked there is
+ // truthy, so the boot banner would print "unknown" instead of taking its
+ // defer-and-retry path.
+ if (definitive) {
+ resolved = identity;
+ } else {
+ // Retry, but not on every caller. This is now read per socket reconnect
+ // and per /api/system/build request, and Socket.IO retries up to 10 times
+ // per tab — so on a host where git is missing (spawn ENOENT) or wedged
+ // (the 5s timeout), an unbounded release would spawn a git per attempt,
+ // per tab. The cooldown keeps the recovery while capping the cost.
+ cached = null;
+ retryBlockedUntil = Date.now() + RETRY_COOLDOWN_MS;
+ }
return identity;
});
return cached;
diff --git a/server/lib/buildIdentity.test.js b/server/lib/buildIdentity.test.js
index ceb79b13f1..27373dfdfe 100644
--- a/server/lib/buildIdentity.test.js
+++ b/server/lib/buildIdentity.test.js
@@ -123,13 +123,35 @@ describe('getBuildIdentity', () => {
it('retries after a TRANSIENT probe failure instead of caching null forever', async () => {
// A 5s timeout can elapse once at boot while migrations hammer the disk.
// Caching that would disable the whole feature for the process lifetime on
- // a checkout that is perfectly fine.
+ // a checkout that is perfectly fine. The retry is behind a cooldown (see the
+ // storm test below), so the clock has to move for it to be attempted.
+ vi.useFakeTimers();
mocks.execGit.mockRejectedValueOnce(new Error('git command timed out after 5s'));
mocks.execGit.mockResolvedValue(ok(CLEAN));
const { getBuildIdentity } = await loadModule();
expect((await getBuildIdentity()).commit).toBeNull();
+
+ vi.advanceTimersByTime(60_000);
+
expect((await getBuildIdentity()).commit).toBe('1234567890abcdef1234567890abcdef12345678');
+ vi.useRealTimers();
+ });
+
+ it('does not re-spawn git per caller while a transient failure is cooling down', async () => {
+ // The identity is read per socket reconnect and per /api/system/build, and
+ // Socket.IO retries up to 10 times per tab — on a host where git is missing
+ // or wedged, an unbounded retry would spawn a git for every attempt.
+ mocks.execGit.mockRejectedValue(new Error('git command timed out after 5s'));
+ const { getBuildIdentity } = await loadModule();
+
+ await getBuildIdentity();
+ await getBuildIdentity();
+ await getBuildIdentity();
+
+ expect(mocks.execGit).toHaveBeenCalledTimes(1);
+ // Still reports not-known rather than throwing or inventing a value.
+ expect((await getBuildIdentity()).commit).toBeNull();
});
it('caches a DEFINITIVE not-a-repo answer rather than re-spawning git per request', async () => {
@@ -234,6 +256,18 @@ describe('getCachedBuildIdentity', () => {
expect(getCachedBuildIdentity()).toBe(identity);
});
+ it('stays null after a TRANSIENT failure so the boot banner defers instead of lying', async () => {
+ // The banner reads this synchronously and prints whatever it gets. Parking
+ // an all-null tuple here would be truthy, so it would print "unknown" and
+ // never correct itself — the permanent lie this accessor must avoid.
+ mocks.execGit.mockRejectedValue(new Error('git command timed out after 5s'));
+ const { getBuildIdentity, getCachedBuildIdentity } = await loadModule();
+
+ await getBuildIdentity();
+
+ expect(getCachedBuildIdentity()).toBeNull();
+ });
+
it('caches the all-null identity too, so a non-repo does not re-probe forever', async () => {
mocks.execGit.mockResolvedValue(fail());
const { getBuildIdentity, getCachedBuildIdentity } = await loadModule();
diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.js
index 45386d30fe..0ea98e972f 100644
--- a/server/routes/systemHealth.js
+++ b/server/routes/systemHealth.js
@@ -58,7 +58,7 @@ router.get('/processing', asyncHandler(async (req, res) => {
* 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.
+ * — must not join a sync payload"). `health.test.js` pins both halves.
*/
router.get('/build', asyncHandler(async (req, res) => {
res.json(await getBuildIdentity());
diff --git a/server/services/socket.js b/server/services/socket.js
index 8269d2784a..ac1a09d380 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -52,7 +52,6 @@ import * as appUpdater from './appUpdater.js';
import * as appDeployer from './appDeployer.js';
import { registerVoiceHandlers } from '../sockets/voice.js';
import { getBuildId } from '../lib/buildId.js';
-import { getBuildIdentity } from '../lib/buildIdentity.js';
import { authEvents, extractToken, isAuthEnabled, verifySession } from './auth.js';
// Store active log streams per socket/process pair.
@@ -205,22 +204,18 @@ export function initSocket(io) {
}
registerVoiceHandlers(socket);
- // Tell the client what build the server is on — both halves of the
- // question, in one frame:
- // buildId — hash of the served bundle. A mismatch means this tab is
- // running stale code against a freshly-rebuilt server; a reload fixes it.
- // commit — the git commit the SERVER process is running (#4694). A
- // mismatch against the bundle's own `__BUILD_STAMP__` means the dist was
- // built from different code than the API is running, which a reload
- // canNOT fix — it needs a rebuild or a restart.
- // Deferred on the cached identity promise rather than awaited in the
- // connection handler, so a slow first git probe can't hold up the rest of
- // the handshake. It resolves from cache after boot. Carries its own catch:
- // this runs outside the request lifecycle.
- getBuildIdentity()
- .then(({ commit, branch, dirty }) =>
- socket.emit('build:id', { buildId: getBuildId(), commit, branch, dirty }))
- .catch(() => socket.emit('build:id', { buildId: getBuildId() }));
+ // Tell the client what build the server is on. The client compares this
+ // to its own embedded <meta name="portos-build-id"> value; a mismatch
+ // means the tab is running stale code against a freshly-rebuilt server
+ // and the user is offered a reload.
+ //
+ // The bundle HASH is safe to push to every socket. The git identity is
+ // deliberately NOT here: `connection` fires for every socket, and
+ // `peerSocketRelay.js` connects PortOS installs to each other over
+ // Socket.IO, so anything pushed here reaches other people's machines. The
+ // client reads the commit from `GET /api/system/build` instead — see that
+ // route in routes/systemHealth.js for the full reasoning (#4694).
+ socket.emit('build:id', { buildId: getBuildId() });
// Replay the in-flight importer analyze snapshot ON DEMAND so a tab that
// (re)connects mid-analyze rebuilds its stage checklist instead of staying
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index 297806b7b8..853e874393 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -22,17 +22,9 @@ vi.mock('./notifications.js', () => ({ notificationEvents: { on: vi.fn() } }));
vi.mock('./agentPersonalities.js', () => ({ agentPersonalityEvents: { on: vi.fn() } }));
vi.mock('./platformAccounts.js', () => ({ platformAccountEvents: { on: vi.fn() } }));
vi.mock('./updateChecker.js', () => ({ updateEvents: { on: vi.fn() } }));
-// The build stamp would otherwise spawn git against whatever checkout the
-// suite runs from, making the assertion depend on the clone.
+// Pin the bundle hash so the assertion does not depend on whether a dist
+// happens to exist in the checkout the suite runs from.
vi.mock('../lib/buildId.js', () => ({ getBuildId: vi.fn(() => 'test-build-id') }));
-vi.mock('../lib/buildIdentity.js', () => ({
- getBuildIdentity: vi.fn().mockResolvedValue({
- commit: 'abc1234567890abcdef1234567890abcdef12345',
- shortCommit: 'abc1234',
- branch: 'main',
- dirty: false
- })
-}));
vi.mock('./automationScheduler.js', () => ({ scheduleEvents: { on: vi.fn() } }));
vi.mock('./agentActivity.js', () => ({ activityEvents: { on: vi.fn() } }));
vi.mock('./brainStorage.js', () => ({ brainEvents: { on: vi.fn() } }));
@@ -143,22 +135,26 @@ describe('socket.js — initSocket', () => {
// ===========================================================================
// cos:subscribe — socket joins cosSubscribers, receives cos:subscribed ack
// ===========================================================================
- it('tells a connecting client both the bundle id AND the running commit (#4694)', async () => {
- // One frame carries both staleness signals: `buildId` (this tab's bundle vs
- // the dist on disk — a reload fixes it) and `commit` (that dist vs the code
- // the server runs — a reload does NOT). The emit is deferred on the cached
- // identity promise, so it lands a microtask after connect.
- const socket = makeSocket('build-stamp');
+ it('pushes only the bundle id at connection time, never the git identity (#4694)', async () => {
+ // THE federation boundary for the socket half. `connection` fires for every
+ // socket, and peerSocketRelay.js opens a Socket.IO CLIENT to every online
+ // peer — so this handler runs for other installs' relays too, and anything
+ // pushed here leaves the machine. The commit is served over the API instead
+ // (GET /api/system/build), which peers do not call.
+ const socket = makeSocket('build-push');
createdSockets.push(socket);
io.connect(socket);
- await vi.waitFor(() =>
- expect(socket.emitted.some(([ev]) => ev === 'build:id')).toBe(true));
-
- const [, frame] = socket.emitted.find(([ev]) => ev === 'build:id');
- expect(frame.buildId).toBe('test-build-id');
- expect(frame.commit).toBe('abc1234567890abcdef1234567890abcdef12345');
- expect(frame.branch).toBe('main');
- expect(frame.dirty).toBe(false);
+ await Promise.resolve();
+
+ const pushed = socket.emitted.filter(([ev]) => ev === 'build:id');
+ expect(pushed).toHaveLength(1);
+ expect(pushed[0][1]).toEqual({ buildId: 'test-build-id' });
+
+ // No commit, branch, or dirty flag anywhere in what this socket received,
+ // and no handler a peer could call to ask for one.
+ expect(JSON.stringify(socket.emitted)).not.toContain('main');
+ expect(JSON.stringify(socket.emitted)).not.toContain('abc1234');
+ expect(Object.keys(socket.handlers)).not.toContain('build:identity');
});
it('socket receives cos:subscribed ack after emitting cos:subscribe', () => {