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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
block PortOS update/reconcile while CoS agents are running
[._.]/ Adam Eivy6e6e8ae219e5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 7a41fcb018..f209a33eee 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -61,6 +61,8 @@## 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`.+- **[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.- **[issue-2567] Stop double error toasts across the Settings tabs and the JIRA integration page.** Several Settings surfaces routed a request through the auto-toasting `request()` helper AND showed their own `toast.error` in a custom catch, so a failure stacked two toasts. Every such call now passes `{ silent: true }` so the caller's catch is the single error layer — covering VoiceTab (config load/save, Piper voice download), ImageGenTab (settings/tools load, save, tool register/update, test render), TelegramTab (settings load, method/config/test/disconnect, forward-types), BackupTab (settings load + save), DatabaseTab (status load), EmbeddingsTab (save), MortalLoomTab and CaptionModelPicker (save), and the JIRA instances page (load/save/delete/test — mirroring the DataDog fix from #2520). Loaders and callers without a custom toast are unchanged (single default-helper layer preserved). The `getVoiceConfig`/`updateVoiceConfig`/`fetchPiperVoice`, telegram, `registerTool`/`updateTool`/`getToolsList`, and `getDatabaseStatus` wrappers gained a backward-compatible trailing `options` param so callers can opt into silent. Follow-up sweep of the remaining pipeline/writers-room/universe/media/etc. areas is tracked in #2669.diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsxindex 5c3c406fb5..f8dc82fb85 100644--- a/client/src/components/apps/tabs/UpdateTab.jsx+++ b/client/src/components/apps/tabs/UpdateTab.jsx@@ -234,6 +234,15 @@ export default function UpdateTab() {useAutoRefetch(pollHealth, 2000, { enabled: polling, pollOnly: true });+ // While CoS agents are live, updates/reconcile are blocked server-side (a+ // restart would sever them). Poll the status so the block clears promptly once+ // the last agent finishes, without the user manually re-checking. No-op when+ // no agents are running or an update is already underway.+ useAutoRefetch(fetchStatus, 4000, {+ enabled: (status?.activeCosAgents || 0) > 0 && !updating && !polling,+ pollOnly: true+ });+const handleCheck = async () => {setChecking(true);const result = await api.checkForUpdate().catch(() => null);@@ -359,6 +368,13 @@ export default function UpdateTab() {// `git pull`, no ./update.sh). Distinct from "a new release is available".const installState = status?.installState;const outOfSync = !!installState?.outOfSync;++ // Live CoS agents make a restart destructive — updating/reconciling pm2-restarts+ // PortOS and severs any in-flight agent. When agents are running we suppress the+ // reconcile prompt and the update actions (the server also hard-rejects with 409+ // AGENTS_ACTIVE) and show a notice instead.+ const activeCosAgents = status?.activeCosAgents || 0;+ const agentsActive = activeCosAgents > 0;const installIssues = [];if (installState?.runningStaleCode) {installIssues.push('Running code is older than what’s checked out — a restart/update is required.');@@ -430,8 +446,19 @@ export default function UpdateTab() {</div>)}+ {/* CoS agents live — updating/reconciling would restart PortOS and sever+ them, so the reconcile prompt and update actions below are suppressed. */}+ {agentsActive && (outOfSync || hasUpdate) && (+ <Banner tone="warning" icon={AlertTriangle} size="md" title="Update paused — CoS agents running">+ {activeCosAgents} CoS agent{activeCosAgents === 1 ? ' is' : 's are'} currently running.+ Updating or reconciling restarts PortOS, which would sever {activeCosAgents === 1 ? 'it' : 'them'} mid-task.+ Pause or wait for the agent{activeCosAgents === 1 ? '' : 's'} to finish — this notice clears automatically,+ then you can update.+ </Banner>+ )}+{/* Install out of sync (issue #1779) — distinct from "new release available" */}- {outOfSync && (+ {outOfSync && !agentsActive && (<div className="p-4 rounded-lg border border-port-warning/50 bg-port-warning/5"><div className="flex items-start gap-2"><AlertTriangle size={18} className="text-port-warning shrink-0 mt-0.5" />@@ -524,8 +551,8 @@ export default function UpdateTab() {</div>)}- {/* Update Actions */}- {hasUpdate && (+ {/* Update Actions — suppressed while CoS agents are live (see notice above) */}+ {hasUpdate && !agentsActive && (<div className="flex flex-wrap gap-2">{isFork ? (<>diff --git a/client/src/components/apps/tabs/UpdateTab.test.jsx b/client/src/components/apps/tabs/UpdateTab.test.jsxindex 545a75ecb7..f18b3d248b 100644--- a/client/src/components/apps/tabs/UpdateTab.test.jsx+++ b/client/src/components/apps/tabs/UpdateTab.test.jsx@@ -176,3 +176,41 @@ describe('UpdateTab reconcile flow', () => {expect(mockToast.loading).not.toHaveBeenCalled();});});++describe('UpdateTab — active CoS agent suppression', () => {+ beforeEach(() => {+ handlers.clear();+ mockCheckHealth.mockReset().mockResolvedValue({ version: '2.24.0', uptime: 120 });+ mockExecutePortosUpdate.mockReset();+ mockToast.mockClear();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('suppresses the reconcile prompt and shows a paused notice while agents are live', async () => {+ mockGetUpdateStatus.mockReset().mockResolvedValue({+ ...OUT_OF_SYNC_STATUS,+ activeCosAgents: 2,+ });+ render(<UpdateTab />);++ // The paused notice appears in place of the reconcile action.+ await screen.findByText(/Update paused — CoS agents running/i);+ expect(screen.getByText(/2 CoS agents are currently running/i)).toBeTruthy();+ // The reconcile button must be gone — a restart would sever the agents.+ expect(screen.queryByRole('button', { name: 'Reconcile Now' })).toBeNull();+ });++ it('shows the reconcile button again once no agents are running', async () => {+ mockGetUpdateStatus.mockReset().mockResolvedValue({+ ...OUT_OF_SYNC_STATUS,+ activeCosAgents: 0,+ });+ render(<UpdateTab />);++ await screen.findByRole('button', { name: 'Reconcile Now' });+ expect(screen.queryByText(/Update paused/i)).toBeNull();+ });+});diff --git a/server/routes/update.js b/server/routes/update.jsindex b96bbd37c2..ce8a3d95d1 100644--- a/server/routes/update.js+++ b/server/routes/update.js@@ -5,6 +5,7 @@ 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';const router = Router();@@ -24,11 +25,15 @@ const executeSchema = z.object({reconcile: z.boolean().optional()});-// GET /api/update/status — returns update state (also clears stale locks)+// GET /api/update/status — returns update state (also clears stale locks).+// `activeCosAgents` counts live CoS agent processes (direct + runner spawns) so+// the UI can suppress the reconcile/update actions while an agent is in flight —+// updating restarts PortOS and would sever those live processes (issue: don't+// restart out from under a running agent).router.get('/status', asyncHandler(async (req, res) => {await updateChecker.clearStaleUpdateInProgress();const status = await updateChecker.getUpdateStatus();- res.json(status);+ res.json({ ...status, activeCosAgents: getActiveAgentIds().length });}));// POST /api/update/check — triggers manual check@@ -109,6 +114,25 @@ router.post('/sync-fork', asyncHandler(async (req, res) => {// POST /api/update/execute — kicks off updaterouter.post('/execute', asyncHandler(async (req, res) => {const { acknowledgeFork, reconcile } = validateRequest(executeSchema, req.body || {});++ // 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;+ 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.`,+ { status: 409, code: 'AGENTS_ACTIVE' }+ );+ }+const status = await updateChecker.getUpdateStatus();// Two distinct entry points:diff --git a/server/routes/update.test.js b/server/routes/update.test.jsindex 4d20fe615b..e21ac74bef 100644--- a/server/routes/update.test.js+++ b/server/routes/update.test.js@@ -18,9 +18,15 @@ 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.+vi.mock('../services/agentState.js', () => ({+ getActiveAgentIds: vi.fn().mockReturnValue([])+}));import * as updateChecker from '../services/updateChecker.js';import { executeUpdate } from '../services/updateExecutor.js';+import { getActiveAgentIds } from '../services/agentState.js';import updateRoutes from './update.js';const makeApp = () => {@@ -47,6 +53,7 @@ describe('POST /api/update/execute — reconcile gating (issue #1779)', () => {vi.clearAllMocks();updateChecker.setUpdateInProgress.mockResolvedValue(true);executeUpdate.mockResolvedValue({ success: true, version: '1.26.0' });+ getActiveAgentIds.mockReturnValue([]);});it('rejects reconcile when the install is already in sync (even with a cached release)', async () => {@@ -128,3 +135,63 @@ describe('POST /api/update/execute — reconcile gating (issue #1779)', () => {expect(executeUpdate).toHaveBeenCalledWith('v1.27.0', expect.any(Function), { forceCleanWorkspaces: undefined });});});++describe('POST /api/update/execute — active CoS agent gating', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ updateChecker.setUpdateInProgress.mockResolvedValue(true);+ updateChecker.getUpdateStatus.mockResolvedValue(baseStatus());+ executeUpdate.mockResolvedValue({ success: true, version: '1.26.0' });+ getActiveAgentIds.mockReturnValue([]);+ });++ it('rejects a normal update with 409 AGENTS_ACTIVE while an agent is live (no restart)', async () => {+ getActiveAgentIds.mockReturnValue(['agent-1']);+ 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();+ // Guard runs before the in-progress lock is acquired.+ expect(updateChecker.setUpdateInProgress).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']);+ const res = await request(makeApp()).post('/api/update/execute').send({ reconcile: true });+ expect(res.status).toBe(409);+ expect(res.body.code).toBe('AGENTS_ACTIVE');+ // Pluralized message names both agents.+ expect(res.body.error).toMatch(/2 CoS agents are running/);+ expect(executeUpdate).not.toHaveBeenCalled();+ });++ it('proceeds normally when no agents are running', async () => {+ getActiveAgentIds.mockReturnValue([]);+ const res = await request(makeApp()).post('/api/update/execute').send({});+ expect(res.status).toBe(200);+ expect(executeUpdate).toHaveBeenCalled();+ });+});++describe('GET /api/update/status — activeCosAgents', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ updateChecker.clearStaleUpdateInProgress.mockResolvedValue(false);+ updateChecker.getUpdateStatus.mockResolvedValue(baseStatus());+ getActiveAgentIds.mockReturnValue([]);+ });++ it('reports the live agent count so the UI can suppress update actions', async () => {+ getActiveAgentIds.mockReturnValue(['agent-1', 'agent-2', 'agent-3']);+ const res = await request(makeApp()).get('/api/update/status');+ expect(res.status).toBe(200);+ expect(res.body.activeCosAgents).toBe(3);+ });++ it('reports 0 when no agents are running', async () => {+ const res = await request(makeApp()).get('/api/update/status');+ expect(res.status).toBe(200);+ expect(res.body.activeCosAgents).toBe(0);+ });+});