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

address review (codex): count in-flight spawns; keep safe update actions

[._.]/ Adam Eivy7936873e4556
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f209a33eee..f4121ef0ce 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -61,7 +61,7 @@
## Fixed
-- **Updating/reconciling no longer severs a live CoS agent.** The update page's "Update Now", "Reconcile Now", and every fork variant run `update.sh`, which pm2-restarts PortOS — killing any CoS agent mid-task (each agent's PTY/child process is a child of the server process). The Update tab now suppresses the "Install out of sync" reconcile prompt and the update actions while agents are running, showing a "Update paused — CoS agents running" notice that clears automatically once the last agent finishes (the tab polls status every 4s while agents are live). Defense-in-depth on the server: `POST /api/update/execute` hard-rejects with `409 AGENTS_ACTIVE` when live agents exist, so a race, a stale client, or a direct API call can't restart out from under a running agent. The active-agent signal reads the in-memory live-process maps (direct + runner spawns) via `getActiveAgentIds()`, so a stale persisted `status: 'running'` can't spuriously block and a paused agent (process already stopped) correctly doesn't. `GET /api/update/status` now reports `activeCosAgents`. Covered by `update.test.js` and `UpdateTab.test.jsx`.
+- **Updating/reconciling no longer severs a live CoS agent.** The update page's "Update Now", "Reconcile Now", and every fork *update* variant run `update.sh`, which pm2-restarts PortOS — killing any CoS agent mid-task (each agent's PTY/child process is a child of the server process). The Update tab now suppresses the "Install out of sync" reconcile prompt and the restart-triggering update buttons while agents are running, showing a "Update paused — CoS agents running" notice that clears automatically once the last agent finishes (the tab polls status every 4s while agents are live). Safe, non-restarting actions stay available — "Sync Fork Only" (just `gh repo sync`) and "Ignore v…" are not hidden. Defense-in-depth on the server: `POST /api/update/execute` hard-rejects with `409 AGENTS_ACTIVE` when agents exist, so a race, a stale client, or a direct API call can't restart out from under a running agent. The active-agent signal counts the in-memory live-process maps (direct + runner spawns) **plus in-flight spawns** (`spawningTasks`) — a just-launched agent whose child process exists but isn't yet registered in a process map would otherwise be invisible to a plain live-process check and still get severed. A stale persisted `status: 'running'` can't spuriously block, and a paused agent (process already stopped) correctly doesn't. `GET /api/update/status` now reports `activeCosAgents`. Covered by `update.test.js` and `UpdateTab.test.jsx`.
- **[issue-2681] POST daily status now uses your timezone, not the server's UTC day.** `completedToday`, `todayScore`, and the POST streaks in the MeatSpace POST service derived the day boundary from the server's UTC day (the process runs `TZ=UTC`), so for anyone outside UTC a POST completed the previous local evening could read as "done today," or a just-completed local-day POST could read as incomplete — and the Daily Post widget and the Daily Driver card (#2666), which both render `completedToday` from `getPostStats()`, inherited the drift. The day boundary now threads your configured timezone (`getUserTimezone`/`todayInTimezone`, via a shared `userLocalToday()` helper) through both sides: every writer that stamps a day (`submitPostSession`, `submitTrainingEntry`, memory-practice `submitPractice`, and Morse `appendMorseRound`) records a new record's `date` in your local day — derived from the same instant it stamps into `timestamp`/`startedAt` so a midnight boundary can't split the two — and every reader (`getPostStats`/`getPostProgress`/`getUnifiedActivityStreak`/`getTrainingStats`/`getMorseProgress`, plus the mastery-window cutoffs) derives "today" in your local day, mirroring the Daily Driver's tz-correct first-visit/handled markers so every surface agrees. All window cutoffs use DST-safe day math off the local today. The POST launcher's "completed today"/today's-minutes and the history range floor also derive their day key in your configured timezone (new `useUserTimezone` hook + `dayKeyInTimezone` util) so the client agrees with the server instead of computing "today" in UTC. A one-time migration (`192-post-dates-to-local-timezone`) re-derives existing session, training-log, and Morse-round day-strings from each record's stored UTC timestamp in your timezone (preferring the retry-stable `startedAt`, and preserving a legacy practice entry's only instant into `timestamp` before rewriting `date`), so historical streaks stay correct and don't collide with newly-written local-day records; it falls back to UTC (matching the server's `TZ=UTC` runtime), making it a no-op for UTC/unconfigured installs.
diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsx
index f8dc82fb85..2a11342346 100644
--- a/client/src/components/apps/tabs/UpdateTab.jsx
+++ b/client/src/components/apps/tabs/UpdateTab.jsx
@@ -551,20 +551,25 @@ export default function UpdateTab() {
</div>
)}
- {/* Update Actions — suppressed while CoS agents are live (see notice above) */}
- {hasUpdate && !agentsActive && (
+ {/* Update Actions. Only the restart-triggering buttons (Sync Fork & Update,
+ Update from Fork As-Is, Update Now — all call runUpdate → update.sh →
+ pm2 restart) are suppressed while CoS agents are live; the safe actions
+ (Sync Fork Only = gh repo sync only, Ignore = no restart) stay available. */}
+ {hasUpdate && (
<div className="flex flex-wrap gap-2">
{isFork ? (
<>
- <button
- onClick={handleSyncForkAndUpdate}
- disabled={updating || polling || syncingFork}
- className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm flex items-center gap-2 hover:bg-port-accent/80 disabled:opacity-50"
- title={`Fast-forwards ${remote?.fullName} main from ${upstreamName} via gh repo sync, then runs the local update. Refuses to overwrite divergent fork commits.`}
- >
- <GitFork size={14} className={syncingFork ? 'animate-pulse' : ''} />
- {syncingFork ? 'Syncing fork...' : updating ? 'Updating...' : polling ? 'Restarting...' : 'Sync Fork & Update'}
- </button>
+ {!agentsActive && (
+ <button
+ onClick={handleSyncForkAndUpdate}
+ disabled={updating || polling || syncingFork}
+ className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm flex items-center gap-2 hover:bg-port-accent/80 disabled:opacity-50"
+ title={`Fast-forwards ${remote?.fullName} main from ${upstreamName} via gh repo sync, then runs the local update. Refuses to overwrite divergent fork commits.`}
+ >
+ <GitFork size={14} className={syncingFork ? 'animate-pulse' : ''} />
+ {syncingFork ? 'Syncing fork...' : updating ? 'Updating...' : polling ? 'Restarting...' : 'Sync Fork & Update'}
+ </button>
+ )}
<button
onClick={handleSyncForkOnly}
disabled={updating || polling || syncingFork}
@@ -574,25 +579,29 @@ export default function UpdateTab() {
<GitFork size={14} />
Sync Fork Only
</button>
+ {!agentsActive && (
+ <button
+ onClick={handleUpdateFromForkAsIs}
+ disabled={updating || polling || syncingFork}
+ className="px-4 py-2 bg-port-border text-gray-400 rounded-lg text-sm flex items-center gap-2 hover:bg-port-border/80 hover:text-white disabled:opacity-50"
+ title="Skip the fork sync and pull from your fork's origin as-is. Use this if you already merged upstream into your fork via your own workflow."
+ >
+ <Download size={14} className={updating ? 'animate-bounce' : ''} />
+ Update from Fork As-Is
+ </button>
+ )}
+ </>
+ ) : (
+ !agentsActive && (
<button
- onClick={handleUpdateFromForkAsIs}
- disabled={updating || polling || syncingFork}
- className="px-4 py-2 bg-port-border text-gray-400 rounded-lg text-sm flex items-center gap-2 hover:bg-port-border/80 hover:text-white disabled:opacity-50"
- title="Skip the fork sync and pull from your fork's origin as-is. Use this if you already merged upstream into your fork via your own workflow."
+ onClick={handleUpdate}
+ disabled={updating || polling}
+ className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm flex items-center gap-2 hover:bg-port-accent/80 disabled:opacity-50"
>
<Download size={14} className={updating ? 'animate-bounce' : ''} />
- Update from Fork As-Is
+ {updating ? 'Updating...' : polling ? 'Restarting...' : 'Update Now'}
</button>
- </>
- ) : (
- <button
- onClick={handleUpdate}
- disabled={updating || polling}
- className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm flex items-center gap-2 hover:bg-port-accent/80 disabled:opacity-50"
- >
- <Download size={14} className={updating ? 'animate-bounce' : ''} />
- {updating ? 'Updating...' : polling ? 'Restarting...' : 'Update Now'}
- </button>
+ )
)}
{release && (
<button
diff --git a/client/src/components/apps/tabs/UpdateTab.test.jsx b/client/src/components/apps/tabs/UpdateTab.test.jsx
index d508d58579..46903fb3de 100644
--- a/client/src/components/apps/tabs/UpdateTab.test.jsx
+++ b/client/src/components/apps/tabs/UpdateTab.test.jsx
@@ -214,6 +214,44 @@ describe('UpdateTab — active CoS agent suppression', () => {
expect(screen.queryByText(/Update paused/i)).toBeNull();
});
+ it('keeps safe non-restart actions (Ignore) available while agents run, hides Update Now', async () => {
+ // P2: only restart-triggering buttons are suppressed. A non-fork install with
+ // an available update and a live agent should hide "Update Now" (restarts)
+ // but still offer "Ignore" (no restart).
+ mockGetUpdateStatus.mockReset().mockResolvedValue({
+ currentVersion: '2.24.0',
+ updateAvailable: true,
+ latestRelease: { version: '2.25.0' },
+ remoteInfo: { isFork: false, hasOrigin: true, fullName: 'atomantic/PortOS' },
+ activeCosAgents: 1,
+ });
+ render(<UpdateTab />);
+
+ await screen.findByText(/Update paused — CoS agents running/i);
+ expect(screen.queryByRole('button', { name: 'Update Now' })).toBeNull();
+ // Ignore is safe (no restart) and must remain available.
+ expect(screen.getByRole('button', { name: /Ignore v2\.25\.0/i })).toBeTruthy();
+ });
+
+ it('keeps Sync Fork Only available while agents run (it does not restart), hides fork update buttons', async () => {
+ mockGetUpdateStatus.mockReset().mockResolvedValue({
+ currentVersion: '2.24.0',
+ updateAvailable: true,
+ latestRelease: { version: '2.25.0' },
+ remoteInfo: { isFork: true, hasOrigin: true, fullName: 'alice/PortOS' },
+ upstream: { fullName: 'atomantic/PortOS' },
+ activeCosAgents: 1,
+ });
+ render(<UpdateTab />);
+
+ await screen.findByText(/Update paused — CoS agents running/i);
+ // Restart-triggering fork actions hidden.
+ expect(screen.queryByRole('button', { name: 'Sync Fork & Update' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Update from Fork As-Is' })).toBeNull();
+ // Sync Fork Only only runs `gh repo sync` — no restart — so it stays.
+ expect(screen.getByRole('button', { name: 'Sync Fork Only' })).toBeTruthy();
+ });
+
it('auto-clears the paused notice when the last agent finishes (4s status poll)', async () => {
// Pins the notice's "this notice clears automatically" claim: while agents
// are live the tab polls status every 4s (useAutoRefetch), so when the last
diff --git a/server/routes/update.js b/server/routes/update.js
index ce8a3d95d1..2f3d89468b 100644
--- a/server/routes/update.js
+++ b/server/routes/update.js
@@ -5,10 +5,28 @@ import { validateRequest } from '../lib/validation.js';
import { UPSTREAM_FULL_NAME } from '../lib/gitRemote.js';
import * as updateChecker from '../services/updateChecker.js';
import { executeUpdate } from '../services/updateExecutor.js';
-import { getActiveAgentIds } from '../services/agentState.js';
+import { getActiveAgentIds, spawningTasks } from '../services/agentState.js';
const router = Router();
+// Count CoS agents a PortOS restart (update.sh → pm2 restart) would disrupt:
+// live processes (direct + runner spawns) PLUS any task mid-spawn. During a
+// spawn the task sits in `spawningTasks` while its child process is created and
+// only THEN registered in the process maps (`withSpawnDedupGuard` holds the set
+// across the whole launch) — so an agent that has already spawned a process but
+// not yet registered it is invisible to getActiveAgentIds() alone. Counting
+// spawningTasks closes that launch window. Use `live || spawning` (not a sum):
+// during the brief overlap where a launching agent is in BOTH a process map and
+// spawningTasks, a sum would double-count it. This still can't close the
+// sub-millisecond window where a NEW spawn begins after this read but before
+// update.sh execs — full spawn/update mutual-exclusion is disproportionate for a
+// single-user install where updating is a deliberate, rare action, and the
+// orphan reaper handles any agent the restart does catch.
+function countActiveCosAgents() {
+ const live = getActiveAgentIds().length;
+ return live || spawningTasks.size;
+}
+
const ignoreSchema = z.object({
version: z.string().min(1, 'version is required')
});
@@ -33,7 +51,7 @@ const executeSchema = z.object({
router.get('/status', asyncHandler(async (req, res) => {
await updateChecker.clearStaleUpdateInProgress();
const status = await updateChecker.getUpdateStatus();
- res.json({ ...status, activeCosAgents: getActiveAgentIds().length });
+ res.json({ ...status, activeCosAgents: countActiveCosAgents() });
}));
// POST /api/update/check — triggers manual check
@@ -118,14 +136,13 @@ router.post('/execute', asyncHandler(async (req, res) => {
// Never restart PortOS out from under a live CoS agent. Both a normal update
// and a reconcile run update.sh, which pm2-restarts THIS server process and
// severs any in-flight agent (each agent's PTY/child process is a child of it).
- // getActiveAgentIds() reads the in-memory live-process maps (direct + runner
- // spawns), so it reflects exactly what a restart would kill — a stale persisted
- // `status: 'running'` on disk can't spuriously block, and a paused agent (its
- // process already stopped) correctly doesn't. Gate here so it covers reconcile,
- // normal update, and both fork variants, which all funnel through /execute.
- const liveAgents = getActiveAgentIds();
- if (liveAgents.length > 0) {
- const n = liveAgents.length;
+ // countActiveCosAgents() reflects exactly what a restart would kill — live
+ // processes plus in-flight spawns — so a stale persisted `status: 'running'`
+ // on disk can't spuriously block, and a paused agent (its process already
+ // stopped) correctly doesn't. Gate here so it covers reconcile, normal update,
+ // and both fork variants, which all funnel through /execute.
+ const n = countActiveCosAgents();
+ if (n > 0) {
throw new ServerError(
`${n} CoS agent${n === 1 ? ' is' : 's are'} running — updating would restart PortOS and ` +
`sever ${n === 1 ? 'it' : 'them'}. Pause or wait for the agent${n === 1 ? '' : 's'} to finish, then update.`,
diff --git a/server/routes/update.test.js b/server/routes/update.test.js
index e21ac74bef..5c27c33f36 100644
--- a/server/routes/update.test.js
+++ b/server/routes/update.test.js
@@ -18,10 +18,14 @@ vi.mock('../services/updateChecker.js', () => ({
vi.mock('../services/updateExecutor.js', () => ({
executeUpdate: vi.fn().mockResolvedValue({ success: true, version: '1.26.0' })
}));
-// getActiveAgentIds reads live-process maps; mock it so tests control the
-// "are CoS agents running?" signal without spawning real processes.
+// getActiveAgentIds reads live-process maps and spawningTasks holds in-flight
+// spawns; mock both so tests control the "are CoS agents running?" signal
+// without spawning real processes. spawningTasks is a real Set the tests mutate
+// (hoisted so the mock factory, which is hoisted above imports, can reference it).
+const { mockSpawningTasks } = vi.hoisted(() => ({ mockSpawningTasks: new Set() }));
vi.mock('../services/agentState.js', () => ({
- getActiveAgentIds: vi.fn().mockReturnValue([])
+ getActiveAgentIds: vi.fn().mockReturnValue([]),
+ spawningTasks: mockSpawningTasks
}));
import * as updateChecker from '../services/updateChecker.js';
@@ -139,6 +143,7 @@ describe('POST /api/update/execute — reconcile gating (issue #1779)', () => {
describe('POST /api/update/execute — active CoS agent gating', () => {
beforeEach(() => {
vi.clearAllMocks();
+ mockSpawningTasks.clear();
updateChecker.setUpdateInProgress.mockResolvedValue(true);
updateChecker.getUpdateStatus.mockResolvedValue(baseStatus());
executeUpdate.mockResolvedValue({ success: true, version: '1.26.0' });
@@ -155,6 +160,17 @@ describe('POST /api/update/execute — active CoS agent gating', () => {
expect(updateChecker.setUpdateInProgress).not.toHaveBeenCalled();
});
+ it('rejects when a task is mid-spawn (in spawningTasks) even before it registers a process', async () => {
+ // No live process yet — the agent has launched but not yet populated the
+ // process maps; a restart would still sever it. spawningTasks closes that gap.
+ getActiveAgentIds.mockReturnValue([]);
+ mockSpawningTasks.add('task-42');
+ const res = await request(makeApp()).post('/api/update/execute').send({});
+ expect(res.status).toBe(409);
+ expect(res.body.code).toBe('AGENTS_ACTIVE');
+ expect(executeUpdate).not.toHaveBeenCalled();
+ });
+
it('rejects a reconcile with 409 AGENTS_ACTIVE while agents are live', async () => {
updateChecker.getUpdateStatus.mockResolvedValue(baseStatus({ installState: { outOfSync: true } }));
getActiveAgentIds.mockReturnValue(['agent-1', 'agent-2']);
@@ -177,6 +193,7 @@ describe('POST /api/update/execute — active CoS agent gating', () => {
describe('GET /api/update/status — activeCosAgents', () => {
beforeEach(() => {
vi.clearAllMocks();
+ mockSpawningTasks.clear();
updateChecker.clearStaleUpdateInProgress.mockResolvedValue(false);
updateChecker.getUpdateStatus.mockResolvedValue(baseStatus());
getActiveAgentIds.mockReturnValue([]);
@@ -189,6 +206,14 @@ describe('GET /api/update/status — activeCosAgents', () => {
expect(res.body.activeCosAgents).toBe(3);
});
+ it('counts an in-flight spawn when no process is registered yet', async () => {
+ getActiveAgentIds.mockReturnValue([]);
+ mockSpawningTasks.add('task-1');
+ const res = await request(makeApp()).get('/api/update/status');
+ expect(res.status).toBe(200);
+ expect(res.body.activeCosAgents).toBe(1);
+ });
+
it('reports 0 when no agents are running', async () => {
const res = await request(makeApp()).get('/api/update/status');
expect(res.status).toBe(200);