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

refactor: detect build drift on every page, not just System Resources (#4694)

[._.]/ Adam Eivy27ac6d6386e9
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 72180d1a5f..9ef02dd024 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -109,6 +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 Logo from './Logo';
import { useErrorNotifications } from '../hooks/useErrorNotifications';
import { useNotifications } from '../hooks/useNotifications';
@@ -1201,7 +1202,15 @@ export default function Layout() {
{/* Footer with version and notifications */}
<div className={`border-t border-port-border ${collapsed ? 'lg:flex lg:justify-center lg:p-2 p-4' : 'p-4'}`}>
<div className={`flex flex-col items-center gap-2 sm:flex-row sm:gap-0 ${collapsed ? 'lg:flex-col lg:justify-center lg:gap-1' : 'sm:justify-between'}`}>
- <span className={`text-sm text-gray-500 ${collapsed ? 'lg:hidden' : ''}`}>
+ <span
+ className={`text-sm text-gray-500 ${collapsed ? 'lg:hidden' : ''}`}
+ // The version is identical across every development commit (it
+ // reflects the last RELEASE), so hovering it gives the one fact it
+ // 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}
+ >
v{__APP_VERSION__}
</span>
<div className={`flex items-center gap-1 ${collapsed ? 'lg:flex-col' : ''}`}>
diff --git a/client/src/components/system-resources/BuildStampPanel.jsx b/client/src/components/system-resources/BuildStampPanel.jsx
index 354cf922ee..2740f94d0f 100644
--- a/client/src/components/system-resources/BuildStampPanel.jsx
+++ b/client/src/components/system-resources/BuildStampPanel.jsx
@@ -1,41 +1,37 @@
import { AlertTriangle, GitCommitHorizontal } from 'lucide-react';
import Pill from '../ui/Pill';
import Banner from '../ui/Banner';
-import { compareBuildStamps, describeBuild } from '../../lib/buildStamp.js';
+import { BUNDLE_STAMP, compareBuildStamps, describeBuild } from '../../lib/buildStamp.js';
import { timeAgo } from '../../utils/formatters';
-// `__BUILD_STAMP__` is a Vite build-time define (see client/vite.config.js).
-// It is genuinely absent under vitest and under any non-bundled consumer, so it
-// is read through `typeof` rather than referenced bare — a bare reference throws
-// a ReferenceError instead of degrading to the 'unknown' state.
-function readBundleStamp() {
- return typeof __BUILD_STAMP__ === 'undefined' ? null : __BUILD_STAMP__;
-}
-
/**
* Which code is actually running — the git commit of the server process, and of
- * the bundle this browser loaded (#4694).
+ * the bundle this browser loaded (#4694). Why `version` cannot answer this: see
+ * the module header of `server/lib/buildIdentity.js`.
*
- * `version` cannot answer this: by project rule package.json's version reflects
- * the last release and is identical across every development commit and every
- * worktree, so a server restarted from a stale checkout looks exactly like a
- * current one. 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 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.
*/
-export default function BuildStampPanel({ build }) {
- const bundle = readBundleStamp();
- const { state, bundleCommit, serverCommit } = compareBuildStamps(bundle, build);
+export default function BuildStampPanel({ build, uptimeFormatted }) {
+ const { state, bundleCommit, serverCommit } = compareBuildStamps(BUNDLE_STAMP, build);
const serverLabel = describeBuild({
- commit: build?.shortCommit || build?.commit,
+ commit: serverCommit,
branch: build?.branch,
dirty: build?.dirty
});
- const bundleLabel = describeBuild({ commit: bundle?.commit, branch: bundle?.branch });
+ 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;
- // Nothing to say at all — a tarball install with no git on either side. Render
- // the panel anyway rather than hiding it, so "we could not tell" is visible
- // instead of looking like the feature is missing.
return (
<section className="rounded-xl border border-port-border bg-port-card p-4">
<h3 className="mb-3 flex items-center gap-2 text-sm font-semibold text-white">
@@ -58,26 +54,19 @@ export default function BuildStampPanel({ build }) {
<StampRow
label="Server"
value={serverLabel}
- hint={build?.builtAt ? `started ${timeAgo(build.builtAt)}` : null}
+ // 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.
+ hint={uptimeFormatted ? `at start · up ${uptimeFormatted}` : 'at start'}
/>
<StampRow
label="This page"
value={bundleLabel}
- hint={bundle?.builtAt ? `built ${timeAgo(bundle.builtAt)}` : null}
+ hint={BUNDLE_STAMP?.builtAt ? `built ${timeAgo(BUNDLE_STAMP.builtAt)}` : null}
/>
</dl>
- {state === 'match' && (
- <p className="mt-3 text-xs text-gray-500">
- Bundle and server agree — what you are looking at is the code that is running.
- </p>
- )}
- {state === 'unknown' && (
- <p className="mt-3 text-xs text-gray-500">
- Commit unknown on at least one side (no git metadata), so bundle/server drift cannot be
- checked here.
- </p>
- )}
+ {footnote && <p className="mt-3 text-xs text-gray-500">{footnote}</p>}
</section>
);
}
diff --git a/client/src/components/system-resources/BuildStampPanel.test.jsx b/client/src/components/system-resources/BuildStampPanel.test.jsx
index 8549f47a70..5098d2efde 100644
--- a/client/src/components/system-resources/BuildStampPanel.test.jsx
+++ b/client/src/components/system-resources/BuildStampPanel.test.jsx
@@ -1,73 +1,82 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
-import BuildStampPanel from './BuildStampPanel.jsx';
const serverBuild = (overrides = {}) => ({
commit: 'abc1234567890abcdef1234567890abcdef12345',
shortCommit: 'abc1234',
branch: 'main',
dirty: false,
- builtAt: new Date().toISOString(),
...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 } = {}) {
+ vi.resetModules();
+ if (stamp === undefined) vi.unstubAllGlobals();
+ else vi.stubGlobal('__BUILD_STAMP__', stamp);
+ const Panel = (await import('./BuildStampPanel.jsx')).default;
+ return render(<Panel {...props} />);
+}
+
afterEach(() => {
vi.unstubAllGlobals();
});
describe('BuildStampPanel', () => {
- it('renders the server commit and branch', () => {
- render(<BuildStampPanel build={serverBuild()} />);
+ it('renders the server commit and branch', async () => {
+ await renderPanel({ build: serverBuild() });
expect(screen.getByText('abc1234 · main')).toBeInTheDocument();
});
- it('flags a stale bundle when the page and the API were built from different commits', () => {
- vi.stubGlobal('__BUILD_STAMP__', { commit: 'def5678', branch: 'main', builtAt: new Date().toISOString() });
-
- render(<BuildStampPanel build={serverBuild()} />);
+ 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() });
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', () => {
- vi.stubGlobal('__BUILD_STAMP__', { commit: 'abc1234', branch: 'main', builtAt: new Date().toISOString() });
-
- render(<BuildStampPanel build={serverBuild()} />);
+ it('confirms agreement when the bundle and the server share a commit', async () => {
+ await renderPanel({ stamp: { commit: 'abc1234', branch: 'main' }, build: serverBuild() });
expect(screen.getByText(/bundle and server agree/i)).toBeInTheDocument();
expect(screen.queryByText(/stale relative to the server/i)).not.toBeInTheDocument();
});
- it('never claims agreement when the bundle stamp is unavailable', () => {
- // `__BUILD_STAMP__` is a Vite define — genuinely absent here, which is the
- // same shape a source-tarball build produces. Reading it must not throw a
- // ReferenceError, and must not report a match nobody verified.
- render(<BuildStampPanel build={serverBuild()} />);
+ 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() });
expect(screen.getByText(/commit unknown on at least one side/i)).toBeInTheDocument();
expect(screen.queryByText(/bundle and server agree/i)).not.toBeInTheDocument();
expect(screen.queryByText(/stale relative to the server/i)).not.toBeInTheDocument();
});
- it('renders "unknown" rather than blank rows when the server has no git metadata', () => {
- render(<BuildStampPanel build={{ commit: null, shortCommit: null, branch: null, dirty: null }} />);
+ 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);
});
- it('surfaces an uncommitted-changes server tree', () => {
- render(<BuildStampPanel build={serverBuild({ dirty: true })} />);
+ 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();
+ expect(screen.getByText('at start · up 3h 12m')).toBeInTheDocument();
});
- it('survives a missing build block entirely (older server, no build field)', () => {
+ 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.
- render(<BuildStampPanel build={undefined} />);
+ await renderPanel({ build: undefined });
expect(screen.getByText('Running build')).toBeInTheDocument();
});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 69421643a8..28efdfb653 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` | `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-or-`unknown` on either side is always `unknown` (never a claimed match, never a false alarm). Answers the rebuild-and-restart drift the socket build-id check cannot see, since that compares bundle hashes rather than commits. Rendered by `components/system-resources/BuildStampPanel.jsx`. |
+| `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). |
| `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 e3bb2ed580..2478d9db32 100644
--- a/client/src/lib/buildStamp.js
+++ b/client/src/lib/buildStamp.js
@@ -5,74 +5,103 @@
* The failure this catches: the dashboard is served from a `client/dist` built
* from one commit while `portos-server` was restarted from a different checkout
* at a different commit. Both halves look perfectly healthy, so a UI change that
- * "isn't working" can be a UI that was never rebuilt — an entire debugging
- * session spent judging code that was not running.
- *
- * Distinct from the socket's build-id check (`server/lib/buildId.js`), which
- * compares the browser's loaded bundle against the bundle on disk RIGHT NOW.
- * That answers "should I reload?"; this answers "was this bundle built from the
- * same commit the API is running?" — a rebuild-and-restart mismatch the id hash
- * cannot see, because both sides agree on a `dist/` that is simply old.
+ * "isn't working" can be a UI that was never rebuilt. Why `version` can't answer
+ * this, and how it differs from the bundle-hash check: see the module header of
+ * `server/lib/buildIdentity.js`.
*/
-// `__BUILD_STAMP__` is a Vite define, so it is absent under vitest and in any
-// consumer that renders these helpers without the bundler. Every unknown input
-// resolves to `state: 'unknown'` — never to `'match'` (which would claim a
-// verification we did not perform) and never to `'mismatch'` (which would cry
-// wolf on every dev run).
-const UNKNOWN = 'unknown';
+/**
+ * The `__BUILD_STAMP__` Vite define, or null where it does not exist (vitest,
+ * or any consumer rendered without the bundler).
+ *
+ * Read through `typeof` — a bare reference to an undefined define throws a
+ * ReferenceError at module load rather than degrading. Resolved once at module
+ * scope so the value has a stable identity: it is a compile-time constant, and
+ * re-evaluating the define per render would hand a fresh object to every
+ * `useMemo`/`React.memo` dependency list that ever includes it.
+ */
+export const BUNDLE_STAMP = typeof __BUILD_STAMP__ === 'undefined' ? null : __BUILD_STAMP__;
-function normalizeCommit(value) {
+/**
+ * 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 —
+ * never a placeholder string, which would swallow a branch that genuinely
+ * carries that name.
+ */
+function normalizeStamp(value) {
if (typeof value !== 'string') return null;
- const trimmed = value.trim().toLowerCase();
- // '' and the literal 'unknown' placeholder both mean "not known". Collapsing
- // them to null keeps absent from ever comparing equal-or-unequal to a real
- // commit (root CLAUDE.md's absent-vs-empty rule).
- if (trimmed === '' || trimmed === UNKNOWN) return null;
- return trimmed;
+ return value.trim() || null;
}
+// Commits compare case-insensitively; branch names do not.
+const normalizeCommit = (value) => normalizeStamp(value)?.toLowerCase() ?? null;
+
/**
* Compare a bundle stamp against the server's build identity.
*
- * @param {{commit?: string, branch?: string, builtAt?: string}|null|undefined} bundle
- * The `__BUILD_STAMP__` define, or null/undefined when unavailable.
+ * @param {{commit?: string|null, branch?: string|null, builtAt?: string}|null|undefined} bundle
* @param {{commit?: string|null, shortCommit?: string|null, branch?: string|null, dirty?: boolean|null}|null|undefined} server
- * The `build` block from GET /api/system/health/details.
* @returns {{state: 'match'|'mismatch'|'unknown', bundleCommit: string|null, serverCommit: string|null}}
- * `bundleCommit` / `serverCommit` are the SHORT forms, for display.
+ * `serverCommit` is the short form when the server sent one, for display.
*/
export function compareBuildStamps(bundle, server) {
const bundleCommit = normalizeCommit(bundle?.commit);
- // The server sends both forms; the bundle only ever has the short one, so the
- // comparison is done on a common prefix rather than on full-vs-short (which
- // would never be equal).
const serverCommit = normalizeCommit(server?.shortCommit) ?? normalizeCommit(server?.commit);
+ // Absent on either side is `unknown` — never `match` (which would claim a
+ // verification nobody performed) and never `mismatch` (which would cry wolf
+ // on every source-tarball install).
if (!bundleCommit || !serverCommit) {
- return { state: UNKNOWN, bundleCommit, serverCommit };
+ return { state: 'unknown', bundleCommit, serverCommit };
}
- const width = Math.min(bundleCommit.length, serverCommit.length);
- const same = bundleCommit.slice(0, width) === serverCommit.slice(0, width);
+ // Prefix comparison, not equality: the bundle carries a 7-char commit while
+ // the server may only have sent the full sha, and those are never equal.
+ const same = bundleCommit.startsWith(serverCommit) || serverCommit.startsWith(bundleCommit);
return { state: same ? 'match' : 'mismatch', bundleCommit, serverCommit };
}
/**
- * One-line human summary of a build identity — `abc1234 · main · dirty`.
+ * One-line human summary of a build — `abc1234 · main · uncommitted changes`.
* Returns null when there is nothing worth rendering, so a caller can drop the
* row entirely instead of printing a line of em-dashes.
*/
export function describeBuild({ commit, branch, dirty } = {}) {
- const shortCommit = normalizeCommit(commit);
const parts = [];
+ const shortCommit = normalizeStamp(commit);
if (shortCommit) parts.push(shortCommit.slice(0, 7));
- const cleanBranch = typeof branch === 'string' && branch.trim() && branch.trim().toLowerCase() !== UNKNOWN
- ? branch.trim()
- : null;
+ const cleanBranch = normalizeStamp(branch);
if (cleanBranch) parts.push(cleanBranch);
// Only `true` earns a badge: `null` means the check itself did not run, and
- // rendering that as "clean" would be a claim we cannot make.
+ // rendering that as "clean" would be a claim we cannot make. The server's
+ // `dirty` is a boot-time snapshot, so the caller labels it as such.
if (dirty === true) parts.push('uncommitted changes');
return parts.length > 0 ? parts.join(' · ') : null;
}
+
+/**
+ * Decide what a `build:id` socket frame means 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:
+ *
+ * `'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
+ * 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
+ * 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 } = {}) {
+ if (!buildId || !embeddedBuildId) return null;
+ if (buildId !== embeddedBuildId) return 'reload';
+ return compareBuildStamps(bundle, { commit }).state === 'mismatch' ? 'drift' : null;
+}
diff --git a/client/src/lib/buildStamp.test.js b/client/src/lib/buildStamp.test.js
index b4912cc934..5d1620ba9b 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 } from './buildStamp.js';
+import { compareBuildStamps, describeBuild, resolveBuildFrame } from './buildStamp.js';
describe('compareBuildStamps', () => {
it('matches a bundle short commit against the server short commit', () => {
@@ -10,8 +10,8 @@ describe('compareBuildStamps', () => {
});
it('matches a short bundle commit against a full server commit on the common prefix', () => {
- // The server may send only the full sha; comparing full-vs-short verbatim
- // would report a permanent false mismatch.
+ // The server may have sent only the full sha; comparing full-vs-short
+ // verbatim would report a permanent false mismatch.
const result = compareBuildStamps(
{ commit: 'abc1234' },
{ shortCommit: null, commit: 'abc1234567890abcdef1234567890abcdef1234' }
@@ -33,19 +33,19 @@ describe('compareBuildStamps', () => {
[null, { shortCommit: 'abc1234' }],
[{ commit: 'abc1234' }, null],
[undefined, undefined],
+ [{ commit: null }, { shortCommit: 'abc1234' }],
[{ commit: 'abc1234' }, { shortCommit: null, commit: null }],
+ [{ commit: '' }, { shortCommit: 'abc1234' }],
]) {
expect(compareBuildStamps(bundle, server).state).toBe('unknown');
}
});
- it('treats the empty string and the literal "unknown" placeholder as absent, not as a commit', () => {
- // A source-tarball build stamps 'unknown'; an empty string would otherwise
- // compare unequal to every real commit and cry wolf on every page load.
- expect(compareBuildStamps({ commit: '' }, { shortCommit: 'abc1234' }).state).toBe('unknown');
- expect(compareBuildStamps({ commit: 'unknown' }, { shortCommit: 'abc1234' }).state).toBe('unknown');
- expect(compareBuildStamps({ commit: 'abc1234' }, { shortCommit: 'unknown' }).state).toBe('unknown');
- expect(compareBuildStamps({ commit: 'unknown' }, { shortCommit: 'abc1234' }).bundleCommit).toBeNull();
+ it('treats a branch or commit literally named "unknown" as a real value', () => {
+ // The absent sentinel is `null` on both halves, so no placeholder string is
+ // reserved — a real ref named "unknown" must not be swallowed as absent.
+ expect(compareBuildStamps({ commit: 'unknown' }, { shortCommit: 'unknown' }).state).toBe('match');
+ expect(describeBuild({ commit: 'abc1234', branch: 'unknown' })).toBe('abc1234 · unknown');
});
it('ignores a non-string commit rather than coercing it', () => {
@@ -67,14 +67,81 @@ describe('describeBuild', () => {
.toBe('abc1234 · main');
});
- it('drops unknown/blank parts instead of printing placeholder text', () => {
- expect(describeBuild({ commit: 'abc1234', branch: 'unknown' })).toBe('abc1234');
+ it('drops blank parts instead of printing placeholder text', () => {
expect(describeBuild({ commit: 'abc1234', branch: ' ' })).toBe('abc1234');
+ expect(describeBuild({ commit: 'abc1234', branch: null })).toBe('abc1234');
});
it('returns null when there is nothing worth rendering', () => {
expect(describeBuild({})).toBeNull();
expect(describeBuild()).toBeNull();
- expect(describeBuild({ commit: 'unknown', branch: 'unknown', dirty: null })).toBeNull();
+ expect(describeBuild({ commit: null, branch: null, dirty: null })).toBeNull();
+ });
+});
+
+describe('resolveBuildFrame', () => {
+ const embeddedBuildId = 'aaaa1111bbbb';
+ const bundle = { commit: 'abc1234', branch: 'main' };
+
+ it('asks for a reload when the bundle on disk moved since this tab loaded', () => {
+ expect(resolveBuildFrame(
+ { buildId: 'cccc2222dddd', commit: 'abc1234' },
+ { embeddedBuildId, bundle }
+ )).toBe('reload');
+ });
+
+ it('reports drift when the tab is current but the dist was built from another commit', () => {
+ // Reloading would re-serve the same stale dist, so this must NOT be 'reload'.
+ expect(resolveBuildFrame(
+ { buildId: embeddedBuildId, commit: 'def5678' },
+ { embeddedBuildId, bundle }
+ )).toBe('drift');
+ });
+
+ it('prefers reload over drift when the bundle is stale on both counts', () => {
+ // A reload is the prerequisite: once the tab is current, the drift check
+ // becomes meaningful. Showing both at once would be two contradictory asks.
+ expect(resolveBuildFrame(
+ { buildId: 'cccc2222dddd', commit: 'def5678' },
+ { embeddedBuildId, bundle }
+ )).toBe('reload');
+ });
+
+ it('says nothing when the tab and the server agree', () => {
+ expect(resolveBuildFrame(
+ { buildId: embeddedBuildId, commit: 'abc1234' },
+ { embeddedBuildId, bundle }
+ )).toBeNull();
+ });
+
+ it('stays silent under `npm run dev`, where there is no dist to be stale', () => {
+ // Vite serves its own index.html, so the server never injects the build-id
+ // meta tag — and the Vite define is frozen at dev-server start, so a drift
+ // check would fire the moment the developer commits.
+ expect(resolveBuildFrame(
+ { buildId: 'dev', commit: 'def5678' },
+ { embeddedBuildId: null, bundle }
+ )).toBeNull();
+ });
+
+ it('stays silent on a malformed or empty frame', () => {
+ expect(resolveBuildFrame(undefined, { embeddedBuildId, bundle })).toBeNull();
+ expect(resolveBuildFrame({}, { embeddedBuildId, bundle })).toBeNull();
+ });
+
+ it('stays silent when the server sent no commit (older server)', () => {
+ // A newer client talking to a server that predates the field must not read
+ // "absent" as "different".
+ expect(resolveBuildFrame(
+ { buildId: embeddedBuildId },
+ { embeddedBuildId, bundle }
+ )).toBeNull();
+ });
+
+ it('stays silent when this bundle has no commit of its own (source tarball)', () => {
+ expect(resolveBuildFrame(
+ { buildId: embeddedBuildId, commit: 'def5678' },
+ { embeddedBuildId, bundle: { commit: null } }
+ )).toBeNull();
});
});
diff --git a/client/src/pages/SystemHealthPage.jsx b/client/src/pages/SystemHealthPage.jsx
index 49895ebbe0..31ca6b7821 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} />
+ <BuildStampPanel build={health.build} 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/services/socket.js b/client/src/services/socket.js
index 1189a24047..8d18a41a2f 100644
--- a/client/src/services/socket.js
+++ b/client/src/services/socket.js
@@ -1,5 +1,6 @@
import { io } from 'socket.io-client';
-import { showStaleBuildToast } from './staleBuildToast';
+import { showStaleBuildToast, showBuildDriftToast } from './staleBuildToast';
+import { resolveBuildFrame } from '../lib/buildStamp.js';
// Connect to Socket.IO using relative path (works with Tailscale)
// The connection will use the same host the page was loaded from
@@ -42,12 +43,16 @@ const EMBEDDED_BUILD_ID = (() => {
return el ? el.getAttribute('content') : null;
})();
-let staleToastShown = false;
-socket.on('build:id', ({ buildId } = {}) => {
- if (!buildId || !EMBEDDED_BUILD_ID || buildId === EMBEDDED_BUILD_ID) return;
- if (staleToastShown) return;
- staleToastShown = true;
- showStaleBuildToast();
+// 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 shown = { reload: false, drift: false };
+socket.on('build:id', (frame) => {
+ const action = resolveBuildFrame(frame, { embeddedBuildId: EMBEDDED_BUILD_ID });
+ if (!action || shown[action]) return;
+ shown[action] = true;
+ if (action === 'reload') showStaleBuildToast();
+ else showBuildDriftToast();
});
export default socket;
diff --git a/client/src/services/staleBuildToast.jsx b/client/src/services/staleBuildToast.jsx
index 05e418e520..6cd3ae6aef 100644
--- a/client/src/services/staleBuildToast.jsx
+++ b/client/src/services/staleBuildToast.jsx
@@ -20,3 +20,22 @@ export function showStaleBuildToast() {
{ id: 'portos-stale-build', duration: Infinity, label: 'New build available' },
);
}
+
+/**
+ * Sticky toast for the OTHER staleness: this tab matches the bundle on disk,
+ * but that bundle was built from a different git commit than the server process
+ * is running (#4694). Deliberately offers no Reload button — reloading re-serves
+ * the same stale dist and changes nothing. The remedy is a rebuild or a restart,
+ * so the toast names it instead of offering an action that would not work.
+ */
+export function showBuildDriftToast() {
+ toast(
+ <div className="flex flex-col gap-0.5">
+ <span>UI and server were built from different commits.</span>
+ <span className="text-xs opacity-80">
+ Rebuild the client or restart the server — reloading will not help.
+ </span>
+ </div>,
+ { id: 'portos-build-drift', duration: Infinity, label: 'UI and server built from different commits' },
+ );
+}
diff --git a/client/vite.config.js b/client/vite.config.js
index f66213c684..dcc4a241e1 100644
--- a/client/vite.config.js
+++ b/client/vite.config.js
@@ -13,39 +13,39 @@ const rootPkg = JSON.parse(readFileSync(resolve(CONFIG_DIR, '../package.json'),
// Which commit this BUNDLE was built from (#4694). package.json's version cannot
// answer that — by project rule it reflects the last RELEASE and is identical
// across every development commit — so a dist/ built three days ago looks exactly
-// like one built this minute. The client compares this against the server's
-// /api/system/health/details `build.commit` and flags a mismatch, which is the
-// "I spent an hour debugging a UI that was not talking to the code I edited"
-// failure mode.
+// like one built this minute. Full rationale: server/lib/buildIdentity.js.
//
// Fail-soft: a source-tarball build has no .git and must still build, so every
-// probe degrades to 'unknown' rather than throwing.
+// probe degrades to `null` — the SAME absent sentinel the server sends, so the
+// client comparison has one vocabulary to understand rather than two. Never `''`
+// and never a placeholder string: a blank commit compares unequal to every real
+// commit, and a branch literally named "unknown" would be swallowed as absent.
function gitStamp(args) {
- const out = execFileSync('git', args, {
- cwd: CONFIG_DIR,
- encoding: 'utf-8',
- stdio: ['ignore', 'pipe', 'ignore'],
- timeout: 5000
- });
- return out.trim() || 'unknown';
-}
-
-function buildStamp() {
- // 'unknown' rather than '' or null: this value is inlined into the bundle as a
- // literal, and an empty string would compare unequal to every real commit and
- // report a permanent false "stale bundle" (root CLAUDE.md's absent-vs-empty rule).
- let commit = 'unknown';
- let branch = 'unknown';
try {
- commit = gitStamp(['rev-parse', '--short=7', 'HEAD']);
- const head = gitStamp(['rev-parse', '--abbrev-ref', 'HEAD']);
- branch = head === 'HEAD' ? 'unknown' : head;
+ const out = execFileSync('git', args, {
+ cwd: CONFIG_DIR,
+ encoding: 'utf-8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ timeout: 5000
+ });
+ return out.trim() || null;
} catch {
- // No git, no repo, or a timeout — keep the 'unknown' defaults.
+ // No git, no repo, or a timeout.
+ return null;
}
- // Commit / branch / timestamp only. No paths (they embed the OS username), no
- // hostname — this string ships to every browser that loads the app.
- return { commit, branch, builtAt: new Date().toISOString() };
+}
+
+function buildStamp() {
+ const head = gitStamp(['rev-parse', '--abbrev-ref', 'HEAD']);
+ return {
+ commit: gitStamp(['rev-parse', '--short=7', 'HEAD']),
+ // `rev-parse --abbrev-ref` prints the literal string `HEAD` on a detached
+ // checkout, which is not a branch name.
+ branch: head === 'HEAD' ? null : head,
+ // Commit / branch / timestamp only. No paths (they embed the OS username),
+ // no hostname — this string ships to every browser that loads the app.
+ builtAt: new Date().toISOString()
+ };
}
// Dev proxy target: probe for the self-signed/LE cert under data/certs/. If the
diff --git a/server/index.js b/server/index.js
index cf0321beb2..8b3dca07e6 100644
--- a/server/index.js
+++ b/server/index.js
@@ -8,7 +8,7 @@ import { existsSync } from 'fs';
import { createTailscaleServers } from '../lib/tailscale-https.js';
import { certPaths } from '../lib/certPaths.js';
import { getBuildId, getStampedIndexHtml } from './lib/buildId.js';
-import { getBuildIdentity, formatBuildIdentity } from './lib/buildIdentity.js';
+import { getBuildIdentity } from './lib/buildIdentity.js';
import { PORTS } from './lib/ports.js';
import alertsRoutes from './routes/alerts.js';
@@ -443,15 +443,11 @@ app.use((req, res) => {
// Error middleware (must be last)
app.use(errorMiddleware);
-// Which code is up. One PM2-managed portos-server serves :5555 for the whole
-// machine while any number of worktrees hold different code, so `pm2 logs
-// portos-server` should be able to answer "which commit is this?" without a
-// request (#4694). Fire-and-forget: this is outside the request lifecycle, so
-// it carries its own catch — an unhandled rejection here would take the process
-// down over a diagnostic log line.
-getBuildIdentity()
- .then((identity) => console.log(`🧬 Running build ${formatBuildIdentity(identity)}`))
- .catch((err) => console.error(`❌ Build identity probe failed: ${err.message}`));
+// Warm the build-identity cache (one git spawn, no output) so the boot banner
+// and the first socket handshake read it synchronously rather than waiting on
+// git (#4694). Fire-and-forget and outside the request lifecycle, so it carries
+// its own catch; nothing downstream depends on when it lands.
+getBuildIdentity().catch((err) => console.error(`❌ Build identity probe failed: ${err.message}`));
// Post-route boot: background service inits + schedulers, then the ordered
// instance/sync/media-queue/DB chain that ends in httpServer.listen(). Not
diff --git a/server/lib/README.md b/server/lib/README.md
index 577e5940ae..325a2872c0 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()` / `formatBuildIdentity()` — which git commit the RUNNING server process was started from (#4694): `{ commit, shortCommit, branch, dirty, builtAt }`, cached once per process. 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` (which compares the served BUNDLE hash, not the commit either side was built from). Non-throwing, every field independently nullable (no `.git` → `commit: null`, never `''`). Commit/branch/dirty/timestamp only — no paths, hostname, or username. |
+| `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). |
## General utilities
diff --git a/server/lib/buildIdentity.js b/server/lib/buildIdentity.js
index 3aa6643b63..6c284781dd 100644
--- a/server/lib/buildIdentity.js
+++ b/server/lib/buildIdentity.js
@@ -16,11 +16,15 @@
* 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 — and the two are complementary, not redundant.
+ * WHICH CODE is up. The two ride the same `build:id` socket frame precisely
+ * because they are complementary halves of one question.
*
- * Privacy: commit / branch / dirty / timestamp only. No absolute paths (they
- * embed the OS username), no hostname, no checkout directory — see the
- * Sensitive Data section of the root CLAUDE.md.
+ * Privacy: commit / branch / dirty only. No absolute paths (they embed the OS
+ * username), no hostname, no checkout directory — see the Sensitive Data
+ * section of the root CLAUDE.md. Deliberately no timestamp either: "how long
+ * has this process been up" is already `system.uptime` on the health payload,
+ * and a second spelling of it here would drift (uptime is recomputed per
+ * request; this tuple is frozen at first read).
*/
import { execGit } from './execGit.js';
@@ -32,80 +36,114 @@ import { PATHS } from './fileUtils.js';
// and the code tree diverge, and the commit that matters is the code's.
const CODE_ROOT = PATHS.root;
-// Probe-shaped git calls, per the house convention (`gitCommitProbe.js`):
-// `ignoreExitCode` so a non-repo resolves to a readable non-zero exit rather
-// than rejecting, and a short `timeout` so a git wedged on a locked index or a
-// slow network mount can't hold boot (or a health request) open for execGit's
-// 30s default.
+// A short bound, not execGit's 30s default: this runs at boot and behind a
+// health route, and a git wedged on a locked index or a slow network mount must
+// not hold either open.
const GIT_TIMEOUT_MS = 5000;
+// git's own "there is no value here" spellings in the porcelain-v2 header:
+// `(initial)` for a repo with no commits yet, `(detached)` for a detached HEAD.
+// Both must read as absent — a branch literally named "detached" is not what
+// git means here, and `(initial)` is not a commit.
+const NO_COMMIT = '(initial)';
+const NO_BRANCH = '(detached)';
+
/**
- * Run one probe-shaped git command and return its trimmed stdout, or null.
- * Every failure mode — missing `.git`, broken checkout, timeout, non-zero exit,
- * empty output — collapses to `null`, never `''`. An empty-string commit reads
- * downstream as "a commit whose value is blank" and would compare unequal to
- * every real commit, silently reporting a false mismatch; `null` says "not
- * known" (root CLAUDE.md's absent-vs-empty rule).
+ * Parse `git status --porcelain=v2 --branch` into the identity tuple.
+ *
+ * One command answers all three questions: `# branch.oid` is HEAD,
+ * `# branch.head` is the branch, and any non-`#` line is a change in the tree.
+ * That is also why `dirty` can be read honestly here — a clean tree emits the
+ * header and nothing else, which a bare `--porcelain` (no header) could not
+ * distinguish from a command that failed and printed nothing.
+ *
+ * Exported for the test suite, which pins the parse against real git output
+ * rather than re-implementing this logic in the assertions.
*/
-async function gitProbe(args) {
- const result = await execGit(args, CODE_ROOT, {
+export function parsePorcelainV2(stdout) {
+ const lines = String(stdout).split('\n');
+ let commit = null;
+ let branch = null;
+ let dirty = false;
+
+ for (const line of lines) {
+ if (line.startsWith('# branch.oid ')) {
+ const value = line.slice('# branch.oid '.length).trim();
+ // Empty stays null rather than becoming '': an empty-string commit
+ // compares unequal to every real commit and would report a permanent
+ // false mismatch downstream (root CLAUDE.md's absent-vs-empty rule).
+ if (value && value !== NO_COMMIT) commit = value;
+ } else if (line.startsWith('# branch.head ')) {
+ const value = line.slice('# branch.head '.length).trim();
+ if (value && value !== NO_BRANCH) branch = value;
+ } else if (line.trim() !== '' && !line.startsWith('#')) {
+ dirty = true;
+ }
+ }
+
+ return { commit, shortCommit: commit ? commit.slice(0, 7) : null, branch, dirty };
+}
+
+// Every field null, and `dirty` null rather than false — "we could not check"
+// must stay distinguishable from "we checked and the tree is clean".
+const UNKNOWN_IDENTITY = { commit: null, shortCommit: null, branch: null, dirty: null };
+
+async function probe() {
+ // `ignoreExitCode` so a non-repo resolves to a readable non-zero exit rather
+ // than rejecting — the house convention for probe-shaped git calls, see
+ // `gitCommitProbe.js`.
+ const result = await execGit(['status', '--porcelain=v2', '--branch'], CODE_ROOT, {
ignoreExitCode: true,
timeout: GIT_TIMEOUT_MS
}).catch(() => null);
- if (!result || result.exitCode !== 0) return null;
- const value = result.stdout.trim();
- return value === '' ? null : value;
+
+ // No `.git`, a broken checkout, or a timeout — report not-known, never a
+ // fabricated value.
+ if (!result || result.exitCode !== 0) return UNKNOWN_IDENTITY;
+ return parsePorcelainV2(result.stdout);
}
let cached = null;
+let resolved = null;
/**
* Resolve the running build's git identity. Cached for the life of the process:
* the code a running process loaded cannot change under it, so re-probing git
- * on every health request would spend three subprocesses to re-learn a constant.
- * (`dirty` CAN change on disk — but it describes the tree the process booted
- * from, and a mid-run edit is not code this process is executing.)
+ * per health request would spend a subprocess to re-learn a constant. The cache
+ * holds the PROMISE, so concurrent first callers (the boot log and an early
+ * request) share one spawn instead of racing to fire their own.
+ *
+ * `dirty` describes the tree this process booted FROM — a later edit on disk is
+ * not code this process is executing, so freezing it is the honest reading, and
+ * the UI labels it as an at-start fact.
*
* Non-throwing. Every field is independently nullable: a tarball install with
- * no `.git`, a detached checkout, or a git timeout reports `commit: null`
- * rather than a fabricated or empty value.
+ * no `.git`, a detached checkout, or a git timeout reports `commit: null`.
*
- * @returns {Promise<{commit: string|null, shortCommit: string|null, branch: string|null, dirty: boolean|null, builtAt: string}>}
+ * @returns {Promise<{commit: string|null, shortCommit: string|null, branch: string|null, dirty: boolean|null}>}
*/
-export async function getBuildIdentity() {
- if (cached) return cached;
-
- const [commit, branch, status] = await Promise.all([
- gitProbe(['rev-parse', 'HEAD']),
- // `--abbrev-ref HEAD` prints the literal string `HEAD` on a detached
- // checkout, which is not a branch name. Report that as null rather than
- // handing the UI a branch called "HEAD".
- gitProbe(['rev-parse', '--abbrev-ref', 'HEAD']),
- // `--porcelain` prints one line per changed path and NOTHING when clean —
- // so a clean tree trims to '' and `gitProbe` returns null, which is
- // indistinguishable from a failed probe. That ambiguity is why dirty is
- // resolved from the raw result below instead of through `gitProbe`.
- execGit(['status', '--porcelain'], CODE_ROOT, {
- ignoreExitCode: true,
- timeout: GIT_TIMEOUT_MS
- }).catch(() => null)
- ]);
-
- const dirty = status && status.exitCode === 0 ? status.stdout.trim() !== '' : null;
-
- cached = {
- commit,
- shortCommit: commit ? commit.slice(0, 7) : null,
- branch: branch === 'HEAD' ? null : branch,
- dirty,
- // When this process started — the honest reading of "how old is the code
- // that is answering me". Distinct from the client's `__BUILD_STAMP__`,
- // which is stamped when the bundle was built.
- builtAt: new Date(Date.now() - process.uptime() * 1000).toISOString()
- };
+export function getBuildIdentity() {
+ cached ??= probe().then((identity) => {
+ resolved = identity;
+ return identity;
+ });
return cached;
}
+/**
+ * The identity if it has already resolved, else null — for callers that must
+ * log synchronously and cannot introduce an await.
+ *
+ * `announceListening` in `services/bootstrap.js` is the case: its caller does
+ * not await it, so an await inside would let the rest of the boot banner print
+ * around the yield. Boot primes the cache long before `listen()` fires, so this
+ * is populated by then; if it somehow is not, `formatBuildIdentity(null)`
+ * degrades to "unknown" rather than blocking or printing a placeholder.
+ */
+export function getCachedBuildIdentity() {
+ return resolved;
+}
+
/**
* Single-line, human-readable summary for the boot log — `abc1234 (main, dirty)`.
* Falls back to `unknown` rather than printing an empty parenthetical when git
@@ -118,8 +156,3 @@ export function formatBuildIdentity(identity) {
if (identity.dirty === null) parts.push('cleanliness unknown');
return `${identity.shortCommit} (${parts.join(', ')})`;
}
-
-/** Test-only: drop the process-lifetime cache. */
-export function resetBuildIdentityCache() {
- cached = null;
-}
diff --git a/server/lib/buildIdentity.test.js b/server/lib/buildIdentity.test.js
index c4f10010e7..86c4927b6d 100644
--- a/server/lib/buildIdentity.test.js
+++ b/server/lib/buildIdentity.test.js
@@ -7,32 +7,84 @@ vi.mock('./execGit.js', () => ({ execGit: mocks.execGit }));
const ok = (stdout) => ({ stdout, stderr: '', exitCode: 0 });
const fail = (stderr = 'not a git repository') => ({ stdout: '', stderr, exitCode: 128 });
-// Route each probe by its git subcommand so a test can fail one call without
-// caring what order the module fires them in.
-function routeGit({ head, branch, status }) {
- mocks.execGit.mockImplementation(async (args) => {
- if (args[0] === 'status') return status;
- if (args.includes('--abbrev-ref')) return branch;
- return head;
- });
-}
+// Real `git status --porcelain=v2 --branch` output, captured from git itself —
+// the parse is pinned against the actual format rather than an invented one.
+const CLEAN = [
+ '# branch.oid 1234567890abcdef1234567890abcdef12345678',
+ '# branch.head main',
+ '# branch.upstream origin/main',
+ '# branch.ab +0 -0',
+ ''
+].join('\n');
+
+const DIRTY = [
+ '# branch.oid 1234567890abcdef1234567890abcdef12345678',
+ '# branch.head main',
+ '1 .M N... 100644 100644 100644 0289925 0289925 server/index.js',
+ '? scratch.txt',
+ ''
+].join('\n');
async function loadModule() {
vi.resetModules();
return import('./buildIdentity.js');
}
-describe('buildIdentity', () => {
+describe('parsePorcelainV2', () => {
+ it('reads commit, short commit, and branch from the header', async () => {
+ const { parsePorcelainV2 } = await loadModule();
+
+ expect(parsePorcelainV2(CLEAN)).toEqual({
+ commit: '1234567890abcdef1234567890abcdef12345678',
+ shortCommit: '1234567',
+ branch: 'main',
+ dirty: false
+ });
+ });
+
+ it('treats any non-header line as a dirty tree', async () => {
+ const { parsePorcelainV2 } = await loadModule();
+
+ expect(parsePorcelainV2(DIRTY).dirty).toBe(true);
+ });
+
+ it('maps git\'s own absent spellings to null, not to a branch or commit', async () => {
+ const { parsePorcelainV2 } = await loadModule();
+
+ // `(initial)` is a repo with no commits; `(detached)` is not a branch name.
+ const initial = parsePorcelainV2('# branch.oid (initial)\n# branch.head main\n');
+ expect(initial.commit).toBeNull();
+ expect(initial.shortCommit).toBeNull();
+
+ const detached = parsePorcelainV2('# branch.oid abc1234\n# branch.head (detached)\n');
+ expect(detached.branch).toBeNull();
+ expect(detached.commit).toBe('abc1234');
+ });
+
+ it('reports null rather than an empty string for a blank header value', async () => {
+ const { parsePorcelainV2 } = await loadModule();
+
+ // An empty-string commit would compare unequal to every real commit and
+ // make the client's stale-bundle check report a permanent false mismatch.
+ const parsed = parsePorcelainV2('# branch.oid \n# branch.head \n');
+ expect(parsed.commit).toBeNull();
+ expect(parsed.branch).toBeNull();
+ });
+
+ it('does not mistake a header-only clean tree for dirty', async () => {
+ const { parsePorcelainV2 } = await loadModule();
+
+ expect(parsePorcelainV2('# branch.oid abc1234\n# branch.head main\n\n').dirty).toBe(false);
+ });
+});
+
+describe('getBuildIdentity', () => {
beforeEach(() => {
mocks.execGit.mockReset();
});
- it('reports commit, short commit, branch, and a clean tree', async () => {
- routeGit({
- head: ok('1234567890abcdef1234567890abcdef12345678\n'),
- branch: ok('main\n'),
- status: ok('')
- });
+ it('resolves the identity from a single git spawn', async () => {
+ mocks.execGit.mockResolvedValue(ok(CLEAN));
const { getBuildIdentity } = await loadModule();
const identity = await getBuildIdentity();
@@ -41,22 +93,11 @@ describe('buildIdentity', () => {
expect(identity.shortCommit).toBe('1234567');
expect(identity.branch).toBe('main');
expect(identity.dirty).toBe(false);
- expect(Number.isNaN(Date.parse(identity.builtAt))).toBe(false);
- });
-
- it('detects a dirty working tree', async () => {
- routeGit({
- head: ok('abc1234\n'),
- branch: ok('feature\n'),
- status: ok(' M server/index.js\n?? scratch.txt\n')
- });
- const { getBuildIdentity } = await loadModule();
-
- expect((await getBuildIdentity()).dirty).toBe(true);
+ expect(mocks.execGit).toHaveBeenCalledTimes(1);
});
- it('reports every git field null outside a repo, and never throws', async () => {
- routeGit({ head: fail(), branch: fail(), status: fail() });
+ it('reports every field null outside a repo, and never throws', async () => {
+ mocks.execGit.mockResolvedValue(fail());
const { getBuildIdentity } = await loadModule();
const identity = await getBuildIdentity();
@@ -67,20 +108,6 @@ describe('buildIdentity', () => {
// `null`, not `false` — "we could not tell" must stay distinguishable from
// "we checked and the tree is clean".
expect(identity.dirty).toBeNull();
- expect(typeof identity.builtAt).toBe('string');
- });
-
- it('reports null (never an empty string) when git resolves but prints nothing', async () => {
- routeGit({ head: ok(' \n'), branch: ok(''), status: ok('') });
- const { getBuildIdentity } = await loadModule();
-
- const identity = await getBuildIdentity();
-
- // An empty-string commit would compare unequal to every real commit and
- // make the client's stale-bundle check report a permanent false mismatch.
- expect(identity.commit).toBeNull();
- expect(identity.shortCommit).toBeNull();
- expect(identity.branch).toBeNull();
});
it('survives a rejecting execGit (timeout / spawn failure) without throwing', async () => {
@@ -93,56 +120,50 @@ describe('buildIdentity', () => {
expect(identity.dirty).toBeNull();
});
- it('maps a detached HEAD to a null branch rather than a branch named HEAD', async () => {
- routeGit({ head: ok('deadbeefdeadbeefdeadbeefdeadbeefdeadbeef\n'), branch: ok('HEAD\n'), status: ok('') });
+ it('shares one spawn across concurrent first callers', async () => {
+ // The boot log and an early health request can both land before the first
+ // probe resolves; caching the PROMISE (not the value) keeps that to one spawn.
+ mocks.execGit.mockResolvedValue(ok(CLEAN));
const { getBuildIdentity } = await loadModule();
- const identity = await getBuildIdentity();
+ const [a, b] = await Promise.all([getBuildIdentity(), getBuildIdentity()]);
- expect(identity.branch).toBeNull();
- expect(identity.commit).toBe('deadbeefdeadbeefdeadbeefdeadbeefdeadbeef');
+ expect(mocks.execGit).toHaveBeenCalledTimes(1);
+ expect(a).toBe(b);
});
- it('caches for the life of the process instead of re-probing git per call', async () => {
- routeGit({ head: ok('abc1234\n'), branch: ok('main\n'), status: ok('') });
- const { getBuildIdentity, resetBuildIdentityCache } = await loadModule();
-
- const first = await getBuildIdentity();
- const callsAfterFirst = mocks.execGit.mock.calls.length;
- const second = await getBuildIdentity();
-
- expect(second).toBe(first);
- expect(mocks.execGit.mock.calls.length).toBe(callsAfterFirst);
+ it('does not re-probe git on later calls', async () => {
+ mocks.execGit.mockResolvedValue(ok(CLEAN));
+ const { getBuildIdentity } = await loadModule();
- // And the cache is droppable, or no suite could exercise a second shape.
- resetBuildIdentityCache();
await getBuildIdentity();
- expect(mocks.execGit.mock.calls.length).toBeGreaterThan(callsAfterFirst);
+ await getBuildIdentity();
+
+ expect(mocks.execGit).toHaveBeenCalledTimes(1);
});
- it('probes git with ignoreExitCode and a bounded timeout, never the 30s default', async () => {
- routeGit({ head: ok('abc1234\n'), branch: ok('main\n'), status: ok('') });
+ it('probes with ignoreExitCode and a bounded timeout, never the 30s default', async () => {
+ mocks.execGit.mockResolvedValue(ok(CLEAN));
const { getBuildIdentity } = await loadModule();
await getBuildIdentity();
- expect(mocks.execGit.mock.calls.length).toBeGreaterThan(0);
- for (const [, cwd, options] of mocks.execGit.mock.calls) {
- expect(typeof cwd).toBe('string');
- expect(cwd.trim()).not.toBe('');
- expect(options.ignoreExitCode).toBe(true);
- expect(options.timeout).toBeLessThanOrEqual(10_000);
- }
+ const [args, cwd, options] = mocks.execGit.mock.calls[0];
+ expect(args).toEqual(['status', '--porcelain=v2', '--branch']);
+ expect(typeof cwd).toBe('string');
+ expect(cwd.trim()).not.toBe('');
+ expect(options.ignoreExitCode).toBe(true);
+ expect(options.timeout).toBeLessThanOrEqual(10_000);
});
- it('never reports a path, hostname, or username field', async () => {
- routeGit({ head: ok('abc1234\n'), branch: ok('main\n'), status: ok('') });
+ it('never reports a path, hostname, username, or timestamp field', async () => {
+ mocks.execGit.mockResolvedValue(ok(CLEAN));
const { getBuildIdentity } = await loadModule();
- // Privacy contract: the payload rides an API response, so its shape is
- // pinned exactly rather than merely spot-checked for known-bad keys.
+ // Privacy contract: the payload rides an API response and a socket frame,
+ // so its shape is pinned exactly rather than spot-checked for known-bad keys.
expect(Object.keys(await getBuildIdentity()).sort()).toEqual(
- ['branch', 'builtAt', 'commit', 'dirty', 'shortCommit']
+ ['branch', 'commit', 'dirty', 'shortCommit']
);
});
});
@@ -169,3 +190,35 @@ describe('formatBuildIdentity', () => {
.toBe('unknown (no git metadata)');
});
});
+
+describe('getCachedBuildIdentity', () => {
+ beforeEach(() => {
+ mocks.execGit.mockReset();
+ });
+
+ it('is null until the probe resolves, then returns the identity', async () => {
+ // The boot banner reads this synchronously — it must never block, and must
+ // degrade to null rather than to a half-built tuple.
+ mocks.execGit.mockResolvedValue(ok(CLEAN));
+ const { getBuildIdentity, getCachedBuildIdentity } = await loadModule();
+
+ expect(getCachedBuildIdentity()).toBeNull();
+
+ const identity = await getBuildIdentity();
+
+ expect(getCachedBuildIdentity()).toBe(identity);
+ });
+
+ 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();
+
+ await getBuildIdentity();
+
+ expect(getCachedBuildIdentity()).toEqual({
+ commit: null, shortCommit: null, branch: null, dirty: null
+ });
+ await getBuildIdentity();
+ expect(mocks.execGit).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 0289925fc7..c7c0ce4f56 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -317,7 +317,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.loops', path: '/loops', label: 'Loops', section: 'Dev Tools', aliases: ['loops'] },
{ id: 'nav.devtools.processes', path: '/devtools/processes', label: 'Processes', section: 'Dev Tools', aliases: ['devtools-processes', 'processes'] },
{ id: 'nav.security', path: '/security', label: 'Security', section: 'Dev Tools', aliases: ['security'] },
- { id: 'nav.system-health', path: '/system-resources/overview', label: 'System Resources', section: 'Dev Tools', aliases: ['system-resources', 'system-health', 'system-status', 'memory-usage', 'cpu-usage'], keywords: ['health', 'memory', 'cpu', 'disk', 'thresholds', 'top processes', 'resource usage'] },
+ { id: 'nav.system-health', path: '/system-resources/overview', label: 'System Resources', section: 'Dev Tools', aliases: ['system-resources', 'system-health', 'system-status', 'memory-usage', 'cpu-usage'], keywords: ['health', 'memory', 'cpu', 'disk', 'thresholds', 'top processes', 'resource usage', 'build', 'commit', 'running build', 'stale build', 'which code is running'] },
{ id: 'nav.system-resources.storage', path: '/system-resources/storage', label: 'Storage Report', section: 'Dev Tools', aliases: ['disk-usage', 'storage-report', 'disk-cleanup'], keywords: ['disk', 'storage', 'space', 'cleanup', 'cache', 'data usage', 'ai triage'] },
{ id: 'nav.system-resources.queues', path: '/system-resources/queues', label: 'Active Queues', section: 'Dev Tools', aliases: ['active-queues', 'job-queues', 'pending-jobs', 'render-queue'], keywords: ['media jobs', 'agent tasks', 'pending', 'running', 'cancel', 'run now'] },
{ id: 'nav.cos.jobs', path: '/cos/jobs', label: 'System Tasks', section: 'Chief of Staff', aliases: ['cos-jobs', 'system-tasks'] },
diff --git a/server/routes/health.test.js b/server/routes/health.test.js
index 7fe65a05a2..1aed9732d7 100644
--- a/server/routes/health.test.js
+++ b/server/routes/health.test.js
@@ -72,8 +72,7 @@ vi.mock('../lib/buildIdentity.js', () => ({
commit: 'abc1234567890abcdef1234567890abcdef12345',
shortCommit: 'abc1234',
branch: 'main',
- dirty: false,
- builtAt: '2026-01-01T00:00:00.000Z'
+ dirty: false
})
}));
@@ -155,8 +154,7 @@ describe('System Health Routes', () => {
commit: 'abc1234567890abcdef1234567890abcdef12345',
shortCommit: 'abc1234',
branch: 'main',
- dirty: false,
- builtAt: '2026-01-01T00:00:00.000Z'
+ dirty: false
});
});
@@ -179,13 +177,6 @@ describe('System Health Routes', () => {
expect(response.body).toHaveProperty('overallHealth');
});
- it('never leaks a path, hostname, or username through the build stamp', async () => {
- const response = await request(app).get('/api/system/health/details');
-
- expect(Object.keys(response.body.build).sort()).toEqual(
- ['branch', 'builtAt', 'commit', 'dirty', 'shortCommit']
- );
- });
it('does not warn on cumulative restart_time (developer-driven restarts)', async () => {
listProcesses.mockResolvedValueOnce([
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 967225ec73..9ae3b724d8 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -26,6 +26,7 @@ import { join } from 'path';
import { resolveInstallRoot } from '../lib/dataRoot.js';
import { PORTS } from '../lib/ports.js';
import { getSelfHost } from '../lib/peerSelfHost.js';
+import { getCachedBuildIdentity, formatBuildIdentity } from '../lib/buildIdentity.js';
import { setupProcessErrorHandlers, asyncHandler, ServerError, errorEvents } from '../lib/errorHandler.js';
import { ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';
import { createAIToolkit } from '../lib/aiToolkit/index.js';
@@ -624,6 +625,15 @@ const announceListening = ({ io, httpServer, localHttpServer, httpsEnabled, port
// (HTTP or HTTPS), :PORTOS_HTTP_PORT (default 5553) is the loopback HTTP
// mirror that only spawns when HTTPS is active. See docs/PORTS.md.
console.log(`🚀 PortOS listening on :${port} (${httpsEnabled ? 'https' : 'http'})`);
+ // Which code is up. One PM2-managed portos-server serves :5555 for the whole
+ // machine while any number of worktrees hold different code, so `pm2 logs
+ // portos-server` should answer "which commit is this?" without a request
+ // (#4694). Logged here rather than fire-and-forget at module scope so it
+ // lands at a DETERMINISTIC position in the banner instead of racing it.
+ // Read synchronously from the cache primed at boot: this function's caller
+ // does not await it, so an await here would let the lines below print around
+ // the yield and scramble the banner.
+ console.log(` 🧬 build ${formatBuildIdentity(getCachedBuildIdentity())}`);
if (!httpsEnabled) {
console.log(` 🌐 http://localhost:${port}`);
console.log(`⚠️ HTTP only — getUserMedia (mic) won't work over Tailscale IP. Run "npm run setup:cert" to enable HTTPS.`);
diff --git a/server/services/socket.js b/server/services/socket.js
index a294bd6c1e..8269d2784a 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -52,6 +52,7 @@ 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.
@@ -204,11 +205,22 @@ export function initSocket(io) {
}
registerVoiceHandlers(socket);
- // 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.
- socket.emit('build:id', { buildId: getBuildId() });
+ // 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() }));
// 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 f6eeb84807..297806b7b8 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -22,6 +22,17 @@ 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.
+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() } }));
@@ -132,6 +143,24 @@ 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');
+ 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);
+ });
+
it('socket receives cos:subscribed ack after emitting cos:subscribe', () => {
const socket = makeSocket('sub-1');
io.connect(socket);