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
feat: share system activity over coalesced socket invalidation (#7967)
[._.]/ Adam Eivy5645cc86e394
diff --git a/client/src/components/UpdateBanners.jsx b/client/src/components/UpdateBanners.jsxindex 6446c4e8a5..dd7e750ad8 100644--- a/client/src/components/UpdateBanners.jsx+++ b/client/src/components/UpdateBanners.jsx@@ -1,7 +1,7 @@import { AlertTriangle, RefreshCw } from 'lucide-react';import { useNavigate } from 'react-router';import Banner from './ui/Banner';-import { useAutoRefetch } from '../hooks/useAutoRefetch';+import { useSystemActivity } from '../hooks/useSystemActivity';import { useUpdateChecker } from '../hooks/useUpdateChecker';import * as api from '../services/api';@@ -15,15 +15,13 @@ export default function UpdateBanners() {} = useUpdateChecker();const hasAdvisory = Boolean(update || outOfSync);- const { data: jobsActive } = useAutoRefetch(async () => {- const processing = await api.getActiveProcessing({ silent: true });- return processing.agents?.active > 0- || processing.jobs?.length > 0- || processing.extras?.imageTo3d?.length > 0;- }, 15000, { enabled: hasAdvisory });- // Keep advisories pending until activity is known and jobs have drained.- // Hiding must not dismiss them: they become actionable again when idle.- if (!hasAdvisory || jobsActive !== false) return null;+ // The server's idle verdict, not a client recount. `status !== 'ready'`+ // (still loading, or the last read failed) stays busy so a restart prompt+ // cannot appear over work we failed to see. Hiding must not dismiss the+ // advisory: it becomes actionable again when the verdict is idle.+ const { snapshot, status } = useSystemActivity();+ const idle = status === 'ready' && snapshot?.activity?.idle === true;+ if (!hasAdvisory || !idle) return null;const goToUpdate = () => navigate(`/apps/${api.PORTOS_APP_ID}/update`);diff --git a/client/src/components/UpdateBanners.test.jsx b/client/src/components/UpdateBanners.test.jsxindex e36d63ad04..b8f01a0752 100644--- a/client/src/components/UpdateBanners.test.jsx+++ b/client/src/components/UpdateBanners.test.jsx@@ -15,10 +15,10 @@ vi.mock('../services/socket', () => ({}));const getUpdateStatus = vi.fn();-const getActiveProcessing = vi.fn();+const getSystemActivity = vi.fn();const ignoreUpdateVersion = vi.fn(() => Promise.resolve({}));vi.mock('../services/api', () => ({- getActiveProcessing: (...a) => getActiveProcessing(...a),+ getSystemActivity: (...a) => getSystemActivity(...a),PORTOS_APP_ID: 'portos-default',getUpdateStatus: (...a) => getUpdateStatus(...a),ignoreUpdateVersion: (...a) => ignoreUpdateVersion(...a),@@ -36,6 +36,13 @@ vi.mock('./ui/Toast', () => ({ default: Object.assign((...a) => toastFn(...a), {import UpdateBanners from './UpdateBanners';import { __internal } from '../hooks/useUpdateChecker';+import { __resetSystemActivityForTests, SYSTEM_ACTIVITY_COALESCE_MS } from '../hooks/useSystemActivity';++const idleActivity = { activity: { idle: true, activeCount: 0, queuedCount: 0, blockers: [] } };+const busyActivity = (extra = {}) => ({+ ...extra,+ activity: { idle: false, activeCount: 1, queuedCount: extra.jobs?.some((job) => job.status === 'queued') ? 1 : 0, blockers: [] },+});const renderBanners = () => render(<MemoryRouter><UpdateBanners /></MemoryRouter>);@@ -46,14 +53,18 @@ beforeEach(() => {navigate.mockClear();toastFn.mockClear();ignoreUpdateVersion.mockClear();- getActiveProcessing.mockReset();- getActiveProcessing.mockResolvedValue({ agents: { active: 0 }, jobs: [], extras: { imageTo3d: [] } });+ getSystemActivity.mockReset();+ getSystemActivity.mockResolvedValue(idleActivity);getUpdateStatus.mockReset();getUpdateStatus.mockResolvedValue({});localStorage.clear();});-afterEach(() => { cleanup(); vi.useRealTimers(); });+afterEach(() => {+ cleanup();+ __resetSystemActivityForTests();+ vi.useRealTimers();+});describe('UpdateBanners', () => {it('renders nothing when the install is current', async () => {@@ -64,28 +75,36 @@ describe('UpdateBanners', () => {});it.each([- ['agents', { agents: { active: 1 } }],- ['media renders', { jobs: [{ id: 'render', status: 'running' }] }],- ['queued media', { jobs: [{ id: 'render', status: 'queued' }] }],- ['3D renders', { extras: { imageTo3d: [{ id: 'model' }] } }],- ])('hides both advisories during %s and restores them when work drains', async (_label, busy) => {+ ['agents', busyActivity({ agents: { active: 1 } })],+ ['media renders', busyActivity({ jobs: [{ id: 'render', status: 'running' }] })],+ ['queued media', busyActivity({ jobs: [{ id: 'render', status: 'queued' }] })],+ ['3D renders', busyActivity({ extras: { imageTo3d: [{ id: 'model' }] } })],+ ['an LLM run', busyActivity({ llm: { trusted: true, active: 1 } })],+ ['a backup', busyActivity({ backup: { inProgress: true } })],+ ])('hides both advisories during %s and restores them when the verdict drains', async (_label, busy) => {vi.useFakeTimers();getUpdateStatus.mockResolvedValue({installState: { outOfSync: true, currentCommit: 'abc123' },updateAvailable: true, currentVersion: '1.0.0', latestRelease: { version: '1.1.0' },});- getActiveProcessing.mockResolvedValue(busy);+ getSystemActivity.mockResolvedValue(busy);renderBanners();await flush();expect(screen.queryByRole('status')).toBeNull();- getActiveProcessing.mockResolvedValue({ agents: { active: 0 }, jobs: [] });- await act(async () => { await vi.advanceTimersByTimeAsync(15000); });+ getSystemActivity.mockResolvedValue(idleActivity);+ await act(async () => {+ handlers.get('system:activity')();+ await vi.advanceTimersByTimeAsync(SYSTEM_ACTIVITY_COALESCE_MS);+ });expect(screen.getByRole('button', { name: 'Reconcile' })).toBeTruthy();expect(screen.getByRole('button', { name: 'Update' })).toBeTruthy();- getActiveProcessing.mockResolvedValue(busy);- await act(async () => { await vi.advanceTimersByTimeAsync(15000); });+ getSystemActivity.mockResolvedValue(busy);+ await act(async () => {+ handlers.get('system:activity')();+ await vi.advanceTimersByTimeAsync(SYSTEM_ACTIVITY_COALESCE_MS);+ });expect(screen.queryByRole('status')).toBeNull();expect(localStorage.getItem(__internal.OUT_OF_SYNC_DISMISS_KEY)).toBeNull();expect(ignoreUpdateVersion).not.toHaveBeenCalled();@@ -94,12 +113,39 @@ describe('UpdateBanners', () => {it('waits for the first activity snapshot before showing an advisory', async () => {getUpdateStatus.mockResolvedValue({ installState: { outOfSync: true, currentCommit: 'abc123' } });let resolveActivity;- getActiveProcessing.mockReturnValue(new Promise(resolve => { resolveActivity = resolve; }));+ getSystemActivity.mockReturnValue(new Promise(resolve => { resolveActivity = resolve; }));renderBanners();await flush();expect(screen.queryByRole('status')).toBeNull();- await act(async () => { resolveActivity({ agents: { active: 0 }, jobs: [] }); });+ await act(async () => { resolveActivity(idleActivity); });+ expect(screen.getByRole('button', { name: 'Reconcile' })).toBeTruthy();+ });++ it('hides an advisory again when a later activity read fails', async () => {+ vi.useFakeTimers();+ getUpdateStatus.mockResolvedValue({ installState: { outOfSync: true, currentCommit: 'abc123' } });+ renderBanners();+ await flush();expect(screen.getByRole('button', { name: 'Reconcile' })).toBeTruthy();++ getSystemActivity.mockRejectedValue(new Error('activity unavailable'));+ await act(async () => {+ handlers.get('system:activity')();+ await vi.advanceTimersByTimeAsync(SYSTEM_ACTIVITY_COALESCE_MS);+ });+ expect(screen.queryByRole('status')).toBeNull();+ expect(localStorage.getItem(__internal.OUT_OF_SYNC_DISMISS_KEY)).toBeNull();+ });++ it('does not poll processing while an advisory sits idle', async () => {+ vi.useFakeTimers();+ getUpdateStatus.mockResolvedValue({ installState: { outOfSync: true, currentCommit: 'abc123' } });+ renderBanners();+ await flush();+ const reads = getSystemActivity.mock.calls.length;+ expect(reads).toBeGreaterThan(0);+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });+ expect(getSystemActivity).toHaveBeenCalledTimes(reads);});it('renders the out-of-sync advisory inline (no toast)', async () => {diff --git a/client/src/components/dashboard/ActiveProcessingWidget.jsx b/client/src/components/dashboard/ActiveProcessingWidget.jsxindex eccccb49c4..ce7015ee66 100644--- a/client/src/components/dashboard/ActiveProcessingWidget.jsx+++ b/client/src/components/dashboard/ActiveProcessingWidget.jsx@@ -1,8 +1,39 @@-import { memo } from 'react';+import { memo, useEffect, useRef, useState } from 'react';import { Link } from 'react-router';import { AudioLines, Bot, Brain, Cpu, ExternalLink, Film, Image as ImageIcon, Layers3, Package, X } from 'lucide-react';import * as api from '../../services/api';import { useAutoRefetch } from '../../hooks/useAutoRefetch';+import { sameProcessingSnapshot, useSystemActivity } from '../../hooks/useSystemActivity';++export { sameProcessingSnapshot };++// nvidia-smi has no lifecycle event, so utilization cannot ride the activity+// invalidation. Poll it only while this inspector intersects the viewport;+// useAutoRefetch also pauses while the tab is hidden. The activity snapshot+// itself is not polled.+const GPU_SAMPLE_MS = 3000;+const sameGpuSample = (a, b) => a?.gpu?.status === b?.gpu?.status+ && a?.gpu?.laneBusy === b?.gpu?.laneBusy+ && a?.gpu?.gpus?.[0]?.utilizationPercent === b?.gpu?.gpus?.[0]?.utilizationPercent;++function useElementVisible() {+ const ref = useRef(null);+ const [visible, setVisible] = useState(false);+ useEffect(() => {+ const node = ref.current;+ if (!node) return undefined;+ if (typeof IntersectionObserver !== 'function') {+ setVisible(true);+ return undefined;+ }+ const observer = new IntersectionObserver(([entry]) => {+ setVisible(Boolean(entry?.isIntersecting));+ });+ observer.observe(node);+ return () => observer.disconnect();+ }, []);+ return [ref, visible];+}const elapsed = (startedAt, now = Date.now()) => {if (!startedAt) return 'queued';@@ -12,27 +43,6 @@ const elapsed = (startedAt, now = Date.now()) => {return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;};const eta = (etaMs) => (Number.isFinite(etaMs) && etaMs >= 0 ? `~${Math.ceil(etaMs / 60000)}m` : null);-export const sameProcessingSnapshot = (a, b) => {- if (!a || !b) return a === b;- return a.agents?.active === b.agents?.active- && a.agents?.queued === b.agents?.queued- && a.gpu?.status === b.gpu?.status- && a.gpu?.laneBusy === b.gpu?.laneBusy- && a.gpu?.gpus?.[0]?.utilizationPercent === b.gpu?.gpus?.[0]?.utilizationPercent- && a.mind?.thinking === b.mind?.thinking- && a.mind?.queued === b.mind?.queued- && a.mind?.status === b.mind?.status- && (a.appOperations || []).length === (b.appOperations || []).length- && a.jobs?.length === b.jobs?.length- && (a.extras?.imageTo3d || []).length === (b.extras?.imageTo3d || []).length- && (a.jobs || []).every((job, index) => job?.id === b.jobs[index]?.id- && job?.status === b.jobs[index]?.status- && job?.progress === b.jobs[index]?.progress- && job?.position === b.jobs[index]?.position- && job?.statusMsg === b.jobs[index]?.statusMsg)- && (a.extras?.imageTo3d || []).every((item, index) => item?.id === b.extras?.imageTo3d?.[index]?.id- && item?.name === b.extras?.imageTo3d?.[index]?.name);-};function JobRow({ job, onCancel }) {const tag = job.params?.musicStudio;@@ -74,12 +84,19 @@ function LaneRow({ to, icon: Icon, label, detail }) {}function ActiveProcessingWidget() {- const { data } = useAutoRefetch(() => api.getActiveProcessing({ silent: true }), 3000, {- compare: sameProcessingSnapshot,- });+ const [rootRef, visible] = useElementVisible();+ const { snapshot, status } = useSystemActivity();+ // Samples only. `enabled: visible` is the "inspector on screen" gate; the+ // hook's own visibility pause covers a hidden tab. No activity fields here.+ const { data: telemetry } = useAutoRefetch(+ () => api.getGpuTelemetry({ silent: true }),+ GPU_SAMPLE_MS,+ { enabled: visible, compare: sameGpuSample },+ );+ const data = snapshot;const cancel = (id) => api.cancelMediaJob(id, { silent: true }).catch(() => undefined);const jobs = data?.jobs || [];- const gpu = data?.gpu;+ const gpu = telemetry?.gpu;const imageTo3d = data?.extras?.imageTo3d || [];const mind = data?.mind;const appOperations = data?.appOperations || [];@@ -88,18 +105,21 @@ function ActiveProcessingWidget() {// unattended auto-updater refuses to restart the install on this same verdict,// so a second definition here is exactly what that module exists to prevent.const activity = data?.activity ?? null;- const idle = !activity || activity.idle;+ // Unknown and failed reads are not idle. The last good rows can stay on+ // screen, but the idle headline is only the server's confirmed verdict.+ const confirmed = status === 'ready';+ const idle = confirmed && activity?.idle === true;const runningJobs = jobs.filter((job) => job.status !== 'queued').length;return (// @container on the widget's OWN root: a dashboard cell is ~250px wide on a// 2560px screen, so a viewport breakpoint here would pin the four-up metric// row into the narrowest column. See the dashboard AGENTS.md.- <div className="@container h-full rounded-xl border border-port-border bg-port-card p-4">+ <div ref={rootRef} className="@container h-full rounded-xl border border-port-border bg-port-card p-4"><div className="mb-3 flex items-start justify-between gap-3"><div><h3 className="flex items-center gap-2 text-sm font-semibold text-white"><span className={`relative flex h-6 w-6 items-center justify-center rounded-lg ${idle ? 'bg-port-border/60 text-gray-400' : 'bg-port-accent/15 text-port-accent'}`}><Cpu size={15} />{!idle ? <span className="absolute -right-0.5 -top-0.5 h-2 w-2 animate-ping rounded-full bg-port-accent" /> : null}</span> Live activity</h3><p className="mt-1 text-[11px] text-gray-500">What PortOS is working on right now</p></div>- <span className={`rounded-full px-2 py-1 text-[10px] font-medium uppercase tracking-wider ${idle ? 'bg-port-border/60 text-gray-500' : 'bg-port-accent/15 text-port-accent'}`}>{idle ? 'idle' : `${activity.activeCount} active${activity.queuedCount ? ` · ${activity.queuedCount} queued` : ''}`}</span>+ <span className={`rounded-full px-2 py-1 text-[10px] font-medium uppercase tracking-wider ${idle ? 'bg-port-border/60 text-gray-500' : 'bg-port-accent/15 text-port-accent'}`}>{!confirmed ? 'unknown' : idle ? 'idle' : `${activity.activeCount} active${activity.queuedCount ? ` · ${activity.queuedCount} queued` : ''}`}</span></div>- {!data ? <p className="text-xs text-gray-500">Checking render lanes…</p> : <>+ {!confirmed && !data ? <p className="text-xs text-gray-500">Checking render lanes…</p> : !data ? <p className="text-xs text-gray-500">Activity unknown</p> : <>{!idle ? <div className="mb-3 grid grid-cols-2 gap-1.5 text-center @xs:grid-cols-4"><Metric icon={Bot} value={activeAgents} label="agents" /><Metric icon={Layers3} value={runningJobs} label="rendering" /><Metric icon={Brain} value={mind?.thinking ? 'yes' : 'no'} label="thinking" /><Metric icon={Cpu} value={gpu?.laneBusy ? 'busy' : 'ready'} label="GPU" /></div> : null}{idle ? <Link to="/system-resources/overview" className="flex items-center justify-between rounded-lg border border-port-border bg-port-bg px-3 py-3 text-xs text-gray-400 transition-colors hover:border-port-accent/50 hover:text-gray-200"><span>Nothing is running</span><span>GPU {gpu?.status === 'available' ? 'ready' : gpu?.status || 'unknown'} →</span></Link> : null}<div className="space-y-1.5">{jobs.map((job) => <JobRow key={job.id} job={job} onCancel={cancel} />)}</div>diff --git a/client/src/components/dashboard/ActiveProcessingWidget.test.jsx b/client/src/components/dashboard/ActiveProcessingWidget.test.jsxindex abc5c986be..752a1fdace 100644--- a/client/src/components/dashboard/ActiveProcessingWidget.test.jsx+++ b/client/src/components/dashboard/ActiveProcessingWidget.test.jsx@@ -1,42 +1,66 @@-import { render, screen } from '@testing-library/react';+import { render, screen, cleanup, act } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter } from 'react-router';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import ActiveProcessingWidget, { sameProcessingSnapshot } from './ActiveProcessingWidget';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import ActiveProcessingWidget from './ActiveProcessingWidget';+import { sameProcessingSnapshot, __resetSystemActivityForTests } from '../../hooks/useSystemActivity';-const { mockGetActiveProcessing, mockCancelMediaJob } = vi.hoisted(() => ({- mockGetActiveProcessing: vi.fn(),+const handlers = new Map();+vi.mock('../../services/socket', () => ({+ default: {+ on: (event, fn) => { handlers.set(event, fn); },+ off: (event, fn) => { if (handlers.get(event) === fn) handlers.delete(event); },+ },+}));++const { mockGetSystemActivity, mockGetGpuTelemetry, mockCancelMediaJob } = vi.hoisted(() => ({+ mockGetSystemActivity: vi.fn(),+ mockGetGpuTelemetry: vi.fn(),mockCancelMediaJob: vi.fn().mockResolvedValue({}),}));vi.mock('../../services/api', () => ({- getActiveProcessing: mockGetActiveProcessing,- cancelMediaJob: mockCancelMediaJob,+ getSystemActivity: (...args) => mockGetSystemActivity(...args),+ getGpuTelemetry: (...args) => mockGetGpuTelemetry(...args),+ cancelMediaJob: (...args) => mockCancelMediaJob(...args),}));-vi.mock('../../hooks/useAutoRefetch', () => ({- useAutoRefetch: (fetchFn) => {- fetchFn();- return { data: mockGetActiveProcessing.mock.results.at(-1)?.value, loading: false };- },-}));+let intersecting = true;+class FakeObserver {+ constructor(callback) { this.callback = callback; }+ observe() { this.callback([{ isIntersecting: intersecting }]); }+ disconnect() {}+}const renderWidget = () => render(<MemoryRouter><ActiveProcessingWidget /></MemoryRouter>);+const idle = { activity: { idle: true, activeCount: 0, queuedCount: 0, blockers: [] }, jobs: [], extras: {}, agents: {} };-beforeEach(() => vi.clearAllMocks());+beforeEach(() => {+ handlers.clear();+ intersecting = true;+ globalThis.IntersectionObserver = FakeObserver;+ mockGetSystemActivity.mockReset();+ mockGetGpuTelemetry.mockReset();+ mockCancelMediaJob.mockClear();+ mockGetSystemActivity.mockResolvedValue(idle);+ mockGetGpuTelemetry.mockResolvedValue({ gpu: { status: 'available', gpus: [] } });+});++afterEach(() => {+ cleanup();+ __resetSystemActivityForTests();+});describe('ActiveProcessingWidget', () => {- it('shows an idle GPU link when nothing is active', () => {- mockGetActiveProcessing.mockReturnValue({ gpu: { status: 'available' }, jobs: [], extras: {}, agents: {} });+ it('shows an idle GPU link when nothing is active', async () => {renderWidget();- expect(screen.getByText('Live activity')).toBeInTheDocument();+ expect(await screen.findByText('Live activity')).toBeInTheDocument();expect(screen.getByText('Nothing is running')).toBeInTheDocument();expect(screen.getByRole('link', { name: /GPU ready/ })).toHaveAttribute('href', '/system-resources/overview');});- it('summarizes active work and links each lane to its destination', () => {- mockGetActiveProcessing.mockReturnValue({- gpu: { status: 'available', laneBusy: true, gpus: [{ utilizationPercent: 42 }] },+ it('summarizes active work and links each lane to its destination', async () => {+ mockGetSystemActivity.mockResolvedValue({jobs: [{ id: 'image-1', kind: 'image', status: 'running', progress: 0.5, startedAt: new Date().toISOString(), params: { prompt: 'Example image' } },{ id: 'audio-1', kind: 'audio', status: 'queued', position: 2, params: { musicStudio: { title: 'Example track' } } },@@ -44,14 +68,11 @@ describe('ActiveProcessingWidget', () => {extras: { imageTo3d: [{ id: 'model-1', name: 'Example mesh' }] },agents: { active: 2, queued: 1 },mind: { trusted: true, thinking: false, queued: 0 },- // Sent by the server (lib/systemIdle.js) and rendered as-is — the widget- // deliberately has no second definition of "idle" to fall back on.activity: { idle: false, activeCount: 4, queuedCount: 2, blockers: [] },});+ mockGetGpuTelemetry.mockResolvedValue({ gpu: { status: 'available', laneBusy: true, gpus: [{ utilizationPercent: 42 }] } });renderWidget();- // Running and queued are counted separately: a queued render is real work- // waiting on the user, not part of the "active" tally.- expect(screen.getByText('4 active · 2 queued')).toBeInTheDocument();+ expect(await screen.findByText('4 active · 2 queued')).toBeInTheDocument();expect(screen.getByText('Example image')).toBeInTheDocument();expect(screen.getByText('Example track')).toBeInTheDocument();expect(screen.getByRole('link', { name: 'Open image activity' })).toHaveAttribute('href', '/media/image');@@ -60,11 +81,8 @@ describe('ActiveProcessingWidget', () => {expect(screen.getByText('50%')).toBeInTheDocument();});- // Counts and lifecycle only — the widget must never render what the mind is- // thinking about, and the snapshot never carries it.- it('surfaces a thinking Persistent Mind as its own lane', () => {- mockGetActiveProcessing.mockReturnValue({- gpu: { status: 'available' },+ it('surfaces a thinking Persistent Mind as its own lane', async () => {+ mockGetSystemActivity.mockResolvedValue({jobs: [],extras: {},agents: {},@@ -72,36 +90,44 @@ describe('ActiveProcessingWidget', () => {activity: { idle: false, activeCount: 1, queuedCount: 2, blockers: [{ kind: 'mind-thinking', label: 'Persistent Mind is thinking', count: 1 }] },});renderWidget();- expect(screen.getByRole('link', { name: /Persistent Mind is thinking/ })).toHaveAttribute('href', '/cos/mind');+ expect(await screen.findByRole('link', { name: /Persistent Mind is thinking/ })).toHaveAttribute('href', '/cos/mind');expect(screen.getByText('1 active · 2 queued')).toBeInTheDocument();});- it('shows a running app operation as activity', () => {- mockGetActiveProcessing.mockReturnValue({- gpu: { status: 'available' },+ it('shows a running app operation as activity', async () => {+ mockGetSystemActivity.mockResolvedValue({jobs: [],extras: {},agents: {},appOperations: [{ appId: 'example', appName: 'Example App', type: 'update' }],- activity: { idle: false, activeCount: 1, queuedCount: 0, blockers: [{ kind: 'app-operations', label: '1 app operation running', count: 1 }] },+ activity: { idle: false, activeCount: 1, queuedCount: 0, blockers: [] },});renderWidget();- expect(screen.getByRole('link', { name: /Example App · update/ })).toHaveAttribute('href', '/apps');+ expect(await screen.findByRole('link', { name: /Example App · update/ })).toHaveAttribute('href', '/apps');});it('cancels a live job from its row', async () => {- mockGetActiveProcessing.mockReturnValue({- gpu: { status: 'available' },+ mockGetSystemActivity.mockResolvedValue({jobs: [{ id: 'image-1', kind: 'image', status: 'running', progress: 0.5, startedAt: new Date().toISOString(), params: { prompt: 'Example image' } }],extras: {},agents: {},+ activity: { idle: false, activeCount: 1, queuedCount: 0, blockers: [] },});const user = userEvent.setup();renderWidget();- await user.click(screen.getByRole('button', { name: 'Cancel Example image' }));+ await user.click(await screen.findByRole('button', { name: 'Cancel Example image' }));expect(mockCancelMediaJob).toHaveBeenCalledWith('image-1', { silent: true });});+ it('does not sample the GPU while the inspector is off screen', async () => {+ intersecting = false;+ renderWidget();+ await screen.findByText('Live activity');+ await act(async () => { await Promise.resolve(); });+ expect(mockGetGpuTelemetry).not.toHaveBeenCalled();+ expect(mockGetSystemActivity).toHaveBeenCalled();+ });+it('recognizes queue movement while ignoring server timestamps', () => {const base = { updatedAt: '2026-01-01T00:00:00Z', jobs: [{ id: 'job-1', status: 'queued', position: 2 }], agents: {}, gpu: {}, extras: {} };expect(sameProcessingSnapshot(base, { ...base, updatedAt: '2026-01-01T00:00:03Z' })).toBe(true);diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 4b05c81f35..2701204cc4 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -104,6 +104,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useAnchorReveal` | `useAnchorReveal(getTarget, key, { reveal? })` — scroll a freshly-opened element into view + flash a tint over it; re-fires when `key` changes; no-op when `key` is falsy or `getTarget()` is null. | Reveal an editorial finding's anchored manuscript text on open / prev-next step (#1601). || `useArmedAction` | Two-click-arm `[armed, fire]` confirmation. | Destructive button needing a confirm tap. (Project memory: user finds this less discoverable — prefer inline confirm rows for new UI.) || `useAutoRefetch` | Poll-based refetch on an interval. `{ pollOnly: true }` skips internal data/loading state for side-effect-only callers (returns `{ refetch }` only). | Data needs periodic refresh (no socket / SSE available). |+| `useSystemActivity` | One shared bounded system-activity snapshot. Socket invalidation coalesces to a single read; reconnect and reshow reconcile missed frames. A failed read stays unknown, never idle. | Update banner and the live-activity widget. GPU samples stay on a visible-only poll — they have no event. || `useAutoSizeTextarea` | `[ref, resize]` — grows a `<textarea>` to fit its content (no scroll / hand-resize); recomputes before paint on value change. | A textarea that should auto-fit content. Prefer the `AutoSizeTextarea` UI component, which wraps this. || `useChartColors` | Resolves the `--port-*` theme tokens (accent/success/warning/error, `chart-1..4`, grid, axis, tooltip surfaces) to concrete `rgb()` strings via `getComputedStyle`, re-resolving on theme switch. | A recharts card needs theme-following colors — SVG `fill`/`stroke` props can't read CSS vars, so pass these resolved strings instead of hardcoded hex. || `useClickOutside` | Fire `onOutside` on mousedown outside a ref — or outside *every* ref in an array. | Popovers, menus, drawers. Pass `[triggerRef, panelRef]` for a portaled panel, which is outside the trigger's subtree. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 1471df6e2d..3868c3e93a 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -173,6 +173,7 @@ export * from './useVisibilityEvent.js';// === UI / interaction ===export * from './useArmedAction.js';export * from './useAutoRefetch.js';+export * from './useSystemActivity.js';export * from './useCmdKSearch.js';export * from './useCooldownTick.js';export { default as useDrawerTab } from './useDrawerTab.js';diff --git a/client/src/hooks/useSystemActivity.js b/client/src/hooks/useSystemActivity.jsnew file mode 100644index 0000000000..631e09ab32--- /dev/null+++ b/client/src/hooks/useSystemActivity.js@@ -0,0 +1,187 @@+import { useCallback, useSyncExternalStore } from 'react';+import * as api from '../services/api';+import socket from '../services/socket';+import { subscribeVisibility } from './useVisibilityEvent.js';++/**+ * One shared system-activity snapshot for the update banner and the live+ * activity widget.+ *+ * The server emits `system:activity` when an activity source changes. Bursts+ * collapse into one read of `GET /api/system/activity` (no GPU shell-out).+ * Subscribe and socket reconnect each read immediately, which is how a missed+ * frame is recovered. A failed or shape-invalid read keeps the previous+ * snapshot and reports `status: 'error'` — it never publishes an idle snapshot+ * the banner could treat as "safe to restart."+ *+ * There is no interval. An idle page produces no recurring processing requests.+ * GPU samples are a separate visible-only poll; they have no lifecycle event.+ */++export const SYSTEM_ACTIVITY_COALESCE_MS = 50;++export const sameProcessingSnapshot = (a, b) => {+ if (!a || !b) return a === b;+ return a.agents?.active === b.agents?.active+ && a.agents?.queued === b.agents?.queued+ && a.agents?.trusted === b.agents?.trusted+ && a.gpu?.status === b.gpu?.status+ && a.gpu?.laneBusy === b.gpu?.laneBusy+ && a.gpu?.gpus?.[0]?.utilizationPercent === b.gpu?.gpus?.[0]?.utilizationPercent+ && a.mind?.thinking === b.mind?.thinking+ && a.mind?.queued === b.mind?.queued+ && a.mind?.status === b.mind?.status+ && a.mind?.trusted === b.mind?.trusted+ && a.llm?.active === b.llm?.active+ && a.llm?.trusted === b.llm?.trusted+ && a.backup?.inProgress === b.backup?.inProgress+ && a.update?.inProgress === b.update?.inProgress+ && a.activity?.idle === b.activity?.idle+ && a.activity?.activeCount === b.activity?.activeCount+ && a.activity?.queuedCount === b.activity?.queuedCount+ && (a.appOperations || []).length === (b.appOperations || []).length+ && a.jobs?.length === b.jobs?.length+ && (a.extras?.imageTo3d || []).length === (b.extras?.imageTo3d || []).length+ && (a.jobs || []).every((job, index) => job?.id === b.jobs[index]?.id+ && job?.status === b.jobs[index]?.status+ && job?.progress === b.jobs[index]?.progress+ && job?.position === b.jobs[index]?.position+ && job?.statusMsg === b.jobs[index]?.statusMsg)+ && (a.extras?.imageTo3d || []).every((item, index) => item?.id === b.extras?.imageTo3d?.[index]?.id+ && item?.name === b.extras?.imageTo3d?.[index]?.name);+};++const EMPTY = { snapshot: null, status: 'unknown', error: null };++let state = EMPTY;+let generation = 0;+let inFlight = null;+let followUp = false;+let timer = null;+let hiddenDeferred = false;+let unsubscribeVisibility = null;+const listeners = new Set();++const publish = (next) => {+ state = next;+ for (const notify of listeners) notify();+};++const visible = () => typeof document === 'undefined' || document.visibilityState !== 'hidden';++function read() {+ if (inFlight) {+ followUp = true;+ return inFlight;+ }+ const started = generation;+ inFlight = api.getSystemActivity({ silent: true }).then((snapshot) => {+ if (started !== generation) return;+ if (!snapshot || typeof snapshot !== 'object' || !snapshot.activity || typeof snapshot.activity.idle !== 'boolean') {+ publish({ snapshot: state.snapshot, status: 'error', error: new Error('Invalid system activity') });+ return;+ }+ const nextSnapshot = state.snapshot && sameProcessingSnapshot(state.snapshot, snapshot) ? state.snapshot : snapshot;+ publish({ snapshot: nextSnapshot, status: 'ready', error: null });+ }).catch((error) => {+ if (started !== generation) return;+ const err = error instanceof Error ? error : new Error(String(error ?? 'System activity read failed'));+ publish({ snapshot: state.snapshot, status: 'error', error: err });+ }).finally(() => {+ inFlight = null;+ if (followUp && listeners.size) {+ followUp = false;+ schedule();+ }+ });+ return inFlight;+}++function schedule() {+ if (!visible()) {+ hiddenDeferred = true;+ return;+ }+ if (timer) return;+ timer = setTimeout(() => {+ timer = null;+ if (listeners.size) read();+ }, SYSTEM_ACTIVITY_COALESCE_MS);+}++function reconcile() {+ if (!visible()) {+ hiddenDeferred = true;+ return;+ }+ hiddenDeferred = false;+ if (timer) {+ clearTimeout(timer);+ timer = null;+ }+ read();+}++function onActivity() {+ schedule();+}++function onConnect() {+ reconcile();+}++function onVisibility(next) {+ if (next === 'visible' && hiddenDeferred && listeners.size) reconcile();+}++function subscribe(notify) {+ listeners.add(notify);+ if (listeners.size === 1) {+ socket.on('system:activity', onActivity);+ socket.on('connect', onConnect);+ unsubscribeVisibility = subscribeVisibility(onVisibility);+ reconcile();+ }+ return () => {+ listeners.delete(notify);+ if (listeners.size) return;+ generation += 1;+ followUp = false;+ hiddenDeferred = false;+ if (timer) {+ clearTimeout(timer);+ timer = null;+ }+ socket.off('system:activity', onActivity);+ socket.off('connect', onConnect);+ unsubscribeVisibility?.();+ unsubscribeVisibility = null;+ };+}++export function useSystemActivity() {+ const snapshot = useSyncExternalStore(subscribe, () => state, () => state);+ const refetch = useCallback(() => {+ generation += 1;+ return reconcile();+ }, []);+ return { ...snapshot, refetch };+}++/** Test seam. Call only after every consumer has unmounted. */+export function __resetSystemActivityForTests() {+ generation += 1;+ followUp = false;+ hiddenDeferred = false;+ if (timer) {+ clearTimeout(timer);+ timer = null;+ }+ inFlight = null;+ listeners.clear();+ state = EMPTY;+ socket.off('system:activity', onActivity);+ socket.off('connect', onConnect);+ unsubscribeVisibility?.();+ unsubscribeVisibility = null;+}diff --git a/client/src/hooks/useSystemActivity.test.jsx b/client/src/hooks/useSystemActivity.test.jsxnew file mode 100644index 0000000000..81a051339e--- /dev/null+++ b/client/src/hooks/useSystemActivity.test.jsx@@ -0,0 +1,135 @@+import { act, cleanup, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ SYSTEM_ACTIVITY_COALESCE_MS,+ __resetSystemActivityForTests,+ useSystemActivity,+} from './useSystemActivity';++const handlers = new Map();+vi.mock('../services/socket', () => ({+ default: {+ on: (event, fn) => {+ const list = handlers.get(event) || [];+ list.push(fn);+ handlers.set(event, list);+ },+ off: (event, fn) => {+ handlers.set(event, (handlers.get(event) || []).filter((item) => item !== fn));+ },+ },+}));++const getSystemActivity = vi.fn();+vi.mock('../services/api', () => ({+ getSystemActivity: (...args) => getSystemActivity(...args),+}));++const idle = { activity: { idle: true, activeCount: 0, queuedCount: 0, blockers: [] }, jobs: [] };+const busy = { activity: { idle: false, activeCount: 1, queuedCount: 0, blockers: [] }, jobs: [{ id: 'job-1', status: 'running' }] };++const fire = (event) => {+ for (const handler of handlers.get(event) || []) handler();+};++beforeEach(() => {+ handlers.clear();+ getSystemActivity.mockReset();+ getSystemActivity.mockResolvedValue(idle);+});++afterEach(() => {+ cleanup();+ __resetSystemActivityForTests();+ vi.useRealTimers();+});++describe('useSystemActivity', () => {+ it('coalesces an event burst into one bounded read', async () => {+ vi.useFakeTimers();+ const { result } = renderHook(() => useSystemActivity());+ await act(async () => { await Promise.resolve(); });+ expect(getSystemActivity).toHaveBeenCalledTimes(1);+ expect(result.current.status).toBe('ready');++ getSystemActivity.mockResolvedValue(busy);+ await act(async () => {+ fire('system:activity');+ fire('system:activity');+ fire('system:activity');+ await vi.advanceTimersByTimeAsync(SYSTEM_ACTIVITY_COALESCE_MS);+ });+ expect(getSystemActivity).toHaveBeenCalledTimes(2);+ expect(result.current.snapshot.activity.idle).toBe(false);+ });++ it('reconciles a missed frame when the socket reconnects', async () => {+ const { result } = renderHook(() => useSystemActivity());+ await act(async () => { await Promise.resolve(); });+ getSystemActivity.mockResolvedValue(busy);+ await act(async () => { fire('connect'); });+ expect(getSystemActivity).toHaveBeenCalledTimes(2);+ expect(result.current.snapshot.jobs).toHaveLength(1);+ });++ it('keeps the previous snapshot and refuses idle when a read fails', async () => {+ vi.useFakeTimers();+ const { result } = renderHook(() => useSystemActivity());+ await act(async () => { await Promise.resolve(); });+ expect(result.current.status).toBe('ready');++ getSystemActivity.mockRejectedValue(new Error('offline'));+ await act(async () => {+ fire('system:activity');+ await vi.advanceTimersByTimeAsync(SYSTEM_ACTIVITY_COALESCE_MS);+ });+ expect(result.current.status).toBe('error');+ expect(result.current.snapshot).toEqual(idle);+ expect(result.current.status === 'ready' && result.current.snapshot.activity.idle).toBe(false);+ });++ it('does not publish an idle snapshot for a malformed payload', async () => {+ getSystemActivity.mockResolvedValue({ jobs: [] });+ const { result } = renderHook(() => useSystemActivity());+ await act(async () => { await Promise.resolve(); });+ expect(result.current.status).toBe('error');+ expect(result.current.snapshot).toBeNull();+ });++ it('defers an invalidation that arrives while the tab is hidden', async () => {+ vi.useFakeTimers();+ let visibility = 'visible';+ const original = Object.getOwnPropertyDescriptor(document, 'visibilityState');+ Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility });+ try {+ renderHook(() => useSystemActivity());+ await act(async () => { await Promise.resolve(); });+ const reads = getSystemActivity.mock.calls.length;+ visibility = 'hidden';+ await act(async () => {+ fire('system:activity');+ await vi.advanceTimersByTimeAsync(SYSTEM_ACTIVITY_COALESCE_MS);+ });+ expect(getSystemActivity).toHaveBeenCalledTimes(reads);++ visibility = 'visible';+ getSystemActivity.mockResolvedValue(busy);+ await act(async () => {+ document.dispatchEvent(new Event('visibilitychange'));+ await Promise.resolve();+ });+ expect(getSystemActivity).toHaveBeenCalledTimes(reads + 1);+ } finally {+ if (original) Object.defineProperty(document, 'visibilityState', original);+ }+ });++ it('does not read on a timer while idle', async () => {+ vi.useFakeTimers();+ renderHook(() => useSystemActivity());+ await act(async () => { await Promise.resolve(); });+ const reads = getSystemActivity.mock.calls.length;+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });+ expect(getSystemActivity).toHaveBeenCalledTimes(reads);+ });+});diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 092fe3646e..4c9f092cfe 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -65,7 +65,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiSchedules.js` | Automation schedules. || `apiQuotaBurn.js` | Quota Burn plan + live status, the job-type catalog its config form renders, and manual runs (`getQuotaBurn`/`getQuotaBurnCatalog`/`saveQuotaBurn`/`runQuotaBurn`), plus `rearmQuotaBurn` to put spent `run once` steps back into the rotation. || `apiRapidReader.js` | Rapid Reader's optional author-hosted Accelerando loader and machine-local shelf API. |-| `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getHourlyUsage` for dashboard hourly counters, `getUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison, `getSubscriptions` / `updateSubscriptions` / `setSubscriptionEnabled` for the Subscriptions page's plan rows (PortOS-side enablement and plan-tier tracking only, never vendor billing), `updateUsageFleetBilling` to exclude an API-billed federated instance from Across Instances totals). Also `saveCredential` (write-only integration key save/clear) and `getCredentialInventory` (`GET /settings/credentials`) — presence and source of each PortOS credential, never a value. Also the Eidoverse world controls and its foundation ledger (`listEidoverseFoundations`, `recordEidoverseFoundation`, `packageEidoverseFoundationCandidate`, `promoteEidoverseFoundation`, `getEidoverseContributions`) — the last three answer 200 with a refusal verdict when a promote gate says no, so callers read `outcome` rather than catching. |+| `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing (`getSystemActivity` for the bounded snapshot, `getGpuTelemetry` for visible-only GPU samples) and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getHourlyUsage` for dashboard hourly counters, `getUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison, `getSubscriptions` / `updateSubscriptions` / `setSubscriptionEnabled` for the Subscriptions page's plan rows (PortOS-side enablement and plan-tier tracking only, never vendor billing), `updateUsageFleetBilling` to exclude an API-billed federated instance from Across Instances totals). Also `saveCredential` (write-only integration key save/clear) and `getCredentialInventory` (`GET /settings/credentials`) — presence and source of each PortOS credential, never a value. Also the Eidoverse world controls and its foundation ledger (`listEidoverseFoundations`, `recordEidoverseFoundation`, `packageEidoverseFoundationCandidate`, `promoteEidoverseFoundation`, `getEidoverseContributions`) — the last three answer 200 with a refusal verdict when a promote gate says no, so callers read `outcome` rather than catching. || `apiAuth.js` | Optional login password — status, login, set/clear password, list/revoke sessions, and read-only password-risk status. || `apiLoops.js` | Scheduled loops. |diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 5965b55867..5f02704380 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -25,6 +25,11 @@ export const triageSystemResources = (payload, options = {}) => request('/system...options,});export const getActiveProcessing = (options) => request('/system/processing', options);+// Bounded activity snapshot (no GPU shell-out). Shared by the update banner+// and the live-activity widget; refreshed from `system:activity`, not a poll.+export const getSystemActivity = (options) => request('/system/activity', options);+// nvidia-smi samples. Polled only while the live-activity inspector is visible.+export const getGpuTelemetry = (options) => request('/system/gpu-telemetry', options);export const getNetworkExposure = (options) => request('/network-exposure/status', options);export const getCapabilities = (options) => request('/capabilities', options);// Machine-local hardware facts used for UI fit and recommendation surfaces.diff --git a/server/index.js b/server/index.jsindex 69119a3009..e5a795edeb 100644--- a/server/index.js+++ b/server/index.js@@ -15,6 +15,7 @@ import alertsRoutes from './routes/alerts.js';import appleHealthRoutes from './routes/appleHealth.js';import avatarRoutes from './routes/avatar.js';import systemHealthRoutes from './routes/systemHealth.js';+import systemActivityRoutes from './routes/systemActivity.js';import systemCapabilitiesRoutes from './routes/systemCapabilities.js';import systemResourcesRoutes from './routes/systemResources.js';import capabilitiesRoutes from './routes/capabilities.js';@@ -276,6 +277,7 @@ app.use('/remote-desktop', remoteDesktopViewerRoutes);app.use('/api/auth', authRoutes);app.use('/api/alerts', alertsRoutes);app.use('/api/avatar', avatarRoutes);+app.use('/api/system', systemActivityRoutes);app.use('/api/system', systemHealthRoutes);app.use('/api/system/capabilities', systemCapabilitiesRoutes);app.use('/api/system-resources', systemResourcesRoutes);diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.mdindex 0494ff679a..ba5d53de07 100644--- a/server/lib/aiToolkit/AGENTS.md+++ b/server/lib/aiToolkit/AGENTS.md@@ -26,7 +26,7 @@ Inheritance mirrors `withGatewayApiKey`: a gateway-backed wrapper with no policy**Runner extension points.** The runner exposes a small declared override surface (in `runner.js`) so the host (PortOS) supplies its own runners without reaching into private internals:- `setCliRunner(fn)` / `setTuiRunner(fn)` — register host CLI/TUI runners (pass `null` to revert). PortOS calls both in `server/index.js`: its CLI variant is stdin-based and knows the per-CLI argv conventions (Codex `exec -`, Antigravity `agy --print`, Claude Code `-p -`); the TUI runner has no toolkit built-in, and `setTuiRunner` attaches/detaches `executeTuiRun` so the runs router's `typeof runnerService.executeTuiRun === 'function'` gate stays honest.-- `registerExternalRun(runId, killable)` / `unregisterExternalRun(runId)` / `hasExternalRun(runId)` — track host-spawned child processes / ptys. The toolkit's own `stopRun`, `isRunActive`, and `deleteRun` consult this registry *first*, so **a host runner that spawns its own process MUST register it here** (PortOS does this in `services/runner.js`) — otherwise the runs router reports live runs as inactive and refuses to stop them, and deleting a live run leaks a zombie process. `stopRun` also stamps a one-shot marker consumed through `consumeExternalRunStop(runId)` before unregistering, which lets the host classify the resulting signal as cancellation instead of a provider failure. That classification rides out to callers as `canceled: true` on the run metadata and `code: 'RUN_CANCELED'` on the rejection the prompt runner raises — **anything that turns an LLM failure into a verdict (a pause kind, a filed gap/investigation task, a provider bench, an `error` status) must call `isRunCanceledError` from `errorDetection.js` first**, or it files bug reports about a human pressing Stop. **`executeApiRun` keeps its own equivalent marker internally**, because its killable is an `AbortController` whose reason-less `abort()` reaches the finalizer as Node's bare `AbortError: This operation was aborted` — a message no pattern matches, so every Stop of an API run finalized as an UNKNOWN provider failure, fired `onRunFailed`, and was escalated to a tier-4 investigation task. It now writes the same `canceled` / `completionReason` terminal shape the CLI path does and fires no failure hook; a timeout still outranks it, since the timer's own abort is what ended that run. The cancel finalizer performs the same reasoning salvage the success/timeout/mid-stream-throw paths do — stopping a reasoning model mid-hidden-channel otherwise persisted `outputSize: 0` and discarded every token it had produced, which reads downstream as a provider that answered nothing. No sibling-method monkey-patching is needed: adding a new lifecycle method (e.g. `pauseRun`) just means having it consult `externalRuns` too.+- `registerExternalRun(runId, killable)` / `unregisterExternalRun(runId)` / `hasExternalRun(runId)` — track host-spawned child processes / ptys. The toolkit's own `stopRun`, `isRunActive`, and `deleteRun` consult this registry *first*, so **a host runner that spawns its own process MUST register it here** (PortOS does this in `services/runner.js`) — otherwise the runs router reports live runs as inactive and refuses to stop them, and deleting a live run leaks a zombie process. `stopRun` also stamps a one-shot marker consumed through `consumeExternalRunStop(runId)` before unregistering, which lets the host classify the resulting signal as cancellation instead of a provider failure. That classification rides out to callers as `canceled: true` on the run metadata and `code: 'RUN_CANCELED'` on the rejection the prompt runner raises — **anything that turns an LLM failure into a verdict (a pause kind, a filed gap/investigation task, a provider bench, an `error` status) must call `isRunCanceledError` from `errorDetection.js` first**, or it files bug reports about a human pressing Stop. **`executeApiRun` keeps its own equivalent marker internally**, because its killable is an `AbortController` whose reason-less `abort()` reaches the finalizer as Node's bare `AbortError: This operation was aborted` — a message no pattern matches, so every Stop of an API run finalized as an UNKNOWN provider failure, fired `onRunFailed`, and was escalated to a tier-4 investigation task. It now writes the same `canceled` / `completionReason` terminal shape the CLI path does and fires no failure hook; it fires `hooks.onRunCanceled?.({ runId })` instead, so a host can drop the run from its activity snapshot without benching the provider. A timeout still outranks it, since the timer's own abort is what ended that run. The cancel finalizer performs the same reasoning salvage the success/timeout/mid-stream-throw paths do — stopping a reasoning model mid-hidden-channel otherwise persisted `outputSize: 0` and discarded every token it had produced, which reads downstream as a provider that answered nothing. No sibling-method monkey-patching is needed: adding a new lifecycle method (e.g. `pauseRun`) just means having it consult `externalRuns` too.- `createProviderStatusService({ prerequisitesMet })` — host gate for "can this provider run AT ALL?" (its CLI binary present). `getFallbackProvider` consults it on every candidate: task-level, configured, and system-priority alike. Injected rather than computed here because the answer needs host I/O (a PATH probe) and this directory stays self-contained; PortOS supplies `prerequisitesMetForRouting` from `services/providerPrerequisites.js` in `bootstrap.js`. It MUST be synchronous, and a missing / throwing / non-boolean answer deliberately reads as "yes" — an unknown answer has to route exactly as it did before, because emptying the fallback chain is a far worse failure than the late ENOENT the gate exists to prevent.- Time-based state transitions need read-side mirrors. `providerStatus.init()` clears expired `estimatedRecovery` entries; every reader (`getStatus`, `getAllStatuses`, `isAvailable`) must re-apply the same recovery check on read — otherwise providers stay "unavailable" past their recovery deadline until the next process restart.diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex 615bd0f74a..802a3dee3e 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -728,6 +728,9 @@ export function createRunnerService(config = {}) {await atomicWrite(metadataPath, metadata).catch((err) => {console.error(`❌ API run ${runId} cancel finalize error: ${err.message}`);});+ // Not `onRunFailed`: a Stop must not bench the provider. The host uses+ // this hook to drop the run from the shared activity snapshot.+ safeSettle(() => hooks.onRunCanceled?.({ runId }), `Run ${runId} onRunCanceled hook`);safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);};// `bound` is 'stall' or 'absolute'. The two mean different things — onediff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex 943013b9bc..f61a7888d9 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -750,9 +750,10 @@ describe('AI Toolkit runner service', () => {vi.stubGlobal('fetch', fetch);const onRunFailed = vi.fn();+ const onRunCanceled = vi.fn();const runner = createRunnerService({dataDir,- hooks: { ensureProviderReady: async () => ({ success: true }), onRunFailed }+ hooks: { ensureProviderReady: async () => ({ success: true }), onRunFailed, onRunCanceled }});let done;@@ -782,6 +783,7 @@ describe('AI Toolkit runner service', () => {// A cancellation is evidence about the operator, not the provider: no// failure hook, so nothing benches the provider or escalates a task.expect(onRunFailed).not.toHaveBeenCalled();+ expect(onRunCanceled).toHaveBeenCalledWith({ runId: 'run-stopped' });expect(await runner.isRunActive('run-stopped')).toBe(false);// Persisted too — /runs replays the record, not the in-memory result.const persisted = JSON.parse(await readFile(join(dataDir, 'runs', 'run-stopped', 'metadata.json'), 'utf-8'));diff --git a/server/routes/systemActivity.js b/server/routes/systemActivity.jsnew file mode 100644index 0000000000..3646ff7b06--- /dev/null+++ b/server/routes/systemActivity.js@@ -0,0 +1,20 @@+import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { getGpuTelemetry, getSystemActivity } from '../services/activeProcessing.js';++const router = Router();++// Bounded activity snapshot: agents, media, 3D, LLM runs, mind, app operations,+// backup, and update state. No GPU shell-out. Clients read it once on subscribe+// and again when `system:activity` invalidates, including after a reconnect.+router.get('/activity', asyncHandler(async (_req, res) => {+ res.json(await getSystemActivity());+}));++// nvidia-smi samples. No event source — the live-activity inspector polls this+// only while it is visible. Do not call it from the global shell.+router.get('/gpu-telemetry', asyncHandler(async (_req, res) => {+ res.json(await getGpuTelemetry());+}));++export default router;diff --git a/server/routes/systemActivity.test.js b/server/routes/systemActivity.test.jsnew file mode 100644index 0000000000..9341ac3e4c--- /dev/null+++ b/server/routes/systemActivity.test.js@@ -0,0 +1,34 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++const activity = vi.hoisted(() => ({+ getSystemActivity: vi.fn(),+ getGpuTelemetry: vi.fn(),+}));+vi.mock('../services/activeProcessing.js', () => activity);++const { default: routes } = await import('./systemActivity.js');++const app = express();+app.use('/api/system', routes);++describe('system activity routes', () => {+ beforeEach(() => vi.clearAllMocks());++ it('serves the bounded activity snapshot without GPU telemetry', async () => {+ activity.getSystemActivity.mockResolvedValue({ activity: { idle: true } });+ const response = await request(app).get('/api/system/activity');+ expect(response.status).toBe(200);+ expect(response.body.activity.idle).toBe(true);+ expect(activity.getGpuTelemetry).not.toHaveBeenCalled();+ });++ it('serves GPU samples from their own route', async () => {+ activity.getGpuTelemetry.mockResolvedValue({ gpu: { status: 'available', laneBusy: false, gpus: [] } });+ const response = await request(app).get('/api/system/gpu-telemetry');+ expect(response.status).toBe(200);+ expect(response.body.gpu.status).toBe('available');+ expect(activity.getSystemActivity).not.toHaveBeenCalled();+ });+});diff --git a/server/services/activeProcessing.js b/server/services/activeProcessing.jsindex 700548d510..a45845fc56 100644--- a/server/services/activeProcessing.js+++ b/server/services/activeProcessing.js@@ -152,21 +152,21 @@ export async function getSystemActivity() {return { ...slices, activity: summarizeSystemActivity(slices) };}-export async function getActiveProcessing() {- const [capability, activity, loadedModels] = await Promise.all([- getCudaCapability(),- getSystemActivity(),- getLoadedModels().catch(() => []),- ]);+/**+ * GPU samples have no lifecycle event — nvidia-smi is a poll. Kept off+ * `getSystemActivity()` so the shared activity read stays bounded, and so the+ * dashboard inspector can poll this alone while it is on screen.+ */+export async function getGpuTelemetry() {+ const capability = await getCudaCapability();const utilization = capability.status === 'available' ? await getCudaUtilization() : { status: capability.status, gpus: [] };- const gpuBusy = Boolean(getRunningJob());+ const running = getRunningJob();return {- ...activity,updatedAt: new Date().toISOString(),gpu: {status: capability.status,- laneBusy: gpuBusy,- laneKind: getRunningJob()?.kind || null,+ laneBusy: Boolean(running),+ laneKind: running?.kind || null,gpus: (utilization.gpus.length ? utilization.gpus : capability.gpus).map((gpu) => ({name: gpu.name,utilizationPercent: gpu.utilizationPercent ?? null,@@ -174,6 +174,19 @@ export async function getActiveProcessing() {memoryTotalMib: gpu.memoryTotalMib ?? gpu.vramMib ?? null,})),},+ };+}++export async function getActiveProcessing() {+ const [telemetry, activity, loadedModels] = await Promise.all([+ getGpuTelemetry(),+ getSystemActivity(),+ getLoadedModels().catch(() => []),+ ]);+ return {+ ...activity,+ updatedAt: telemetry.updatedAt,+ gpu: telemetry.gpu,extras: { ...activity.extras, ollama: loadedModels },};}diff --git a/server/services/appOperations.js b/server/services/appOperations.jsindex 6e66ca553d..ad07443cdd 100644--- a/server/services/appOperations.js+++ b/server/services/appOperations.js@@ -11,8 +11,12 @@* restart PortOS while App Management is mid-deploy of something else).*/+import { noteSystemActivity } from './systemActivityNotify.js';+const activeAppOperations = new Map();+const END_PHASES = new Set(['completion', 'failure', 'cancellation']);+/*** The live operations as rows — id, name, type, age. One operation occupies* several keys, so they collapse back to one row; repoPath stays server-side,@@ -53,6 +57,7 @@ export const claimAppOperation = (io, app, type) => {const operation = { appId: app.id, appName: app.name, type, steps: [], startedAt: Date.now(), repoPath: app.repoPath };for (const key of operationKeys(app)) setOperationKey(key, operation);io.emit('app:operations:active', activeOperationsPayload());+ noteSystemActivity('appOperations', 'start');return { ok: true, operation };};@@ -63,13 +68,18 @@ export const __resetAppOperations = () => activeAppOperations.clear();// Clear every key this operation holds, and only the keys pointing at THIS// operation — a run that already finished must not evict a live sibling.-export const endAppOperation = (io, appId) => {+export const endAppOperation = (io, appId, phase = 'completion') => {const operation = activeAppOperations.get(appId);if (!operation) return;for (const [key, op] of activeAppOperations) {if (op === operation) activeAppOperations.delete(key);}io.emit('app:operations:active', activeOperationsPayload());+ const activityPhase = END_PHASES.has(phase) ? phase : 'completion';+ noteSystemActivity('appOperations', activityPhase);+ // Ending the last operation is the queue drain. A second note in the same+ // turn coalesces with the first; the following read sees an empty registry.+ if (listActiveAppOperations().length === 0) noteSystemActivity('appOperations', 'drained');};// Record a step into the operation's buffer using the same last-write-winsdiff --git a/server/services/appUpdateRunner.js b/server/services/appUpdateRunner.jsindex e77bc7cbb9..d2e1d6ffa6 100644--- a/server/services/appUpdateRunner.js+++ b/server/services/appUpdateRunner.js@@ -77,7 +77,7 @@ export async function runAppUpdate({acknowledgePersistentMindImageBackup,}).then(() => null, (err) => err);if (refusal) {- endAppOperation(io, app.id);+ endAppOperation(io, app.id, 'cancellation');operatingAppId = null;return { ok: false, reason: 'refused', appId: app.id, code: refusal.code || null, message: refusal.message };}@@ -139,6 +139,8 @@ export async function runAppUpdate({}return { ok: true };} finally {- if (operatingAppId && !result?.selfUpdateStarted) endAppOperation(io, operatingAppId);+ if (operatingAppId && !result?.selfUpdateStarted) {+ endAppOperation(io, operatingAppId, result?.success === true ? 'completion' : 'failure');+ }}}diff --git a/server/services/backup.js b/server/services/backup.jsindex 5b2d5a9fec..e503b0d052 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -23,10 +23,20 @@ import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';import { isSafeSnapshotSource, isSafeSubdirFilter, anchorUserExcludes } from '../lib/sharedSchemas.js';import { reloadSettings } from './settings.js';import { invalidateAllCaches as invalidateBrainCaches } from './brainStorage.js';+import { noteSystemActivity } from './systemActivityNotify.js';// Module-level statelet isRunning = false;+// The in-process lock is the activity signal the updater reads. Note the edge+// in the same assignment so a client cannot keep a stale "backup running"+// verdict after the lock drops, or miss one that just started. There is no+// cancel path: a failed run releases the lock as `failure`.+function setBackupRunning(running, phase) {+ isRunning = running;+ noteSystemActivity('backup', phase);+}+// Backups and restores can legitimately run for hours on large or remote// volumes, so a short elapsed-time cap would turn healthy work into failure.// Treat ten minutes with no observable progress as a stall, while retaining a@@ -494,7 +504,7 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disablthrow new Error('Backup destination not configured');}- isRunning = true;+ setBackupRunning(true, 'start');let snapshotId = null;let snapshotDir;let parentMarker;@@ -517,7 +527,7 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disablif (snapshotDir) await unlink(failedMarkerPath(snapshotDir)).catch(() => {});await clearInProgressMarkers();releaseActiveSnapshot();- isRunning = false;+ setBackupRunning(false, 'completion');return result;};@@ -530,7 +540,7 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl: false;if (failureRecorded) await clearInProgressMarkers();releaseActiveSnapshot();- isRunning = false;+ setBackupRunning(false, 'failure');await saveState({ lastRun: new Date().toISOString(), status: 'error', error: err.message, pgBackup: null }).catch(() => {});if (io) io.emit('backup:failed', { snapshotId, error: err.message });throw err;diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex c7efc43641..283748ba3c 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -2614,6 +2614,8 @@ describe('runBackup lifecycle', () => {proc.emit('close', 0);await pending;expect(isBackupInProgress()).toBe(false);+ const { drainActivityNotesForTests } = await import('./systemActivityNotify.js');+ expect(drainActivityNotesForTests().map((note) => note.phase)).toEqual(['start', 'completion']);});// A snapshot mid-assembly would tar/rsync as a truncated tree that looks like@@ -2758,6 +2760,8 @@ describe('runBackup lifecycle', () => {expect(state.status).toBe('error');expect(state.error).toMatch(/rsync exited with code 23/);expect(state.pgBackup).toBeNull();+ const { drainActivityNotesForTests } = await import('./systemActivityNotify.js');+ expect(drainActivityNotesForTests().map((note) => note.phase)).toEqual(['start', 'failure']);// No manifest is written for a failed run.const fsp = await actualFs();await expect(fsp.stat(joinPath(await findSnapshotDir(), 'manifest.json'))).rejects.toThrow();diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 5f719e2f1d..701c1c1a69 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -32,6 +32,7 @@ import { getBuildIdentity, getCachedBuildIdentity, formatBuildIdentity } from '.import { setupProcessErrorHandlers, asyncHandler, ServerError, errorEvents } from '../lib/errorHandler.js';import { ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';import { createAIToolkit } from '../lib/aiToolkit/index.js';+import { attachLlmActivityHooks } from './systemActivityNotify.js';import { verifyCollectionVersions } from '../lib/collectionStore.js';import { startIdleReaper, stopIdleReaper } from '../lib/managedDaemon.js';import { adoptNpmGlobalBinDir } from '../lib/npmGlobalBin.js';@@ -180,7 +181,7 @@ import { logFailureWithStack as logBootstrapFailure } from '../lib/failureLoggin*/export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverDir }) => {// Lifecycle hooks shared between AI Toolkit and PortOS runner shim- const aiToolkitHooks = {+ const aiToolkitHooks = attachLlmActivityHooks({ensureProviderReady: (provider) => ensureProviderReadyForExecution(provider),onRunCreated: (metadata) => {recordSession(metadata.providerId, metadata.providerName, metadata.model).catch(err => {@@ -226,7 +227,7 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD}});}- };+ });// The ORDER these run in is `runPreRouteSequence`'s contract (see// bootstrapSequence.js); this object is only the "what".diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.jsindex d105e67ac3..16c41dc3b1 100644--- a/server/services/imageTo3d/models.js+++ b/server/services/imageTo3d/models.js@@ -21,6 +21,14 @@ import { access } from 'node:fs/promises';import { ServerError } from '../../lib/errorHandler.js';import { PATHS, resolveGalleryImage, ensureDir, rmGuarded, writeFileGuarded } from '../../lib/fileUtils.js';import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';+import { noteSystemActivity } from '../systemActivityNotify.js';++// One heavy render occupies the generating set. Leaving it (ready, failed, or+// canceled) drains that set; the client re-reads rather than trusting the phase.+function noteImageTo3d(phase) {+ noteSystemActivity('imageTo3d', phase);+ if (phase !== 'start') noteSystemActivity('imageTo3d', 'drained');+}import { prepareLocalMemory, gpuBlockersMessage } from '../localMemory.js';import { slugifyForFilename } from '../../lib/civitai.js';import {@@ -155,7 +163,7 @@ async function failGeneration(id, operationId, error) {// includeDeleted so a record the user deleted mid-render resolves (rather than// throwing NOT_FOUND → a spurious "failure could not be persisted" log); the// `deleted` guard then no-ops the write — the delete already recorded the intent.- await store.mutateModel(id, (current) => {+ const updated = await store.mutateModel(id, (current) => {if (current.deleted || current.generationOperationId !== operationId) return null;return {...current,@@ -170,7 +178,12 @@ async function failGeneration(id, operationId, error) {};}, { includeDeleted: true }).catch((persistError) => {console.error(`❌ Image-to-3D model ${id} failure could not be persisted: ${persistError.message}`);+ return null;});+ // A deleted record no-ops the write (delete already noted cancellation).+ // A failed persist stays unnoted: the reconnect read must not be told the+ // build ended when the row may still say generating.+ if (updated && !updated.deleted && updated.status === 'failed') noteImageTo3d('failure');}async function executeRender({ id, operationId, adapter, sourcePath, caps, options }) {@@ -266,7 +279,7 @@ async function executeRender({ id, operationId, adapter, sourcePath, caps, optio// includeDeleted + `deleted` guard: if the user deleted the record while the// render ran, complete quietly as a no-op (the GLB on disk is orphaned — full// kill-on-delete is tracked as a follow-up) instead of throwing NOT_FOUND.- await store.mutateModel(id, (current) => {+ const finished = await store.mutateModel(id, (current) => {if (current.deleted || current.generationOperationId !== operationId) return null;return {...current,@@ -286,6 +299,7 @@ async function executeRender({ id, operationId, adapter, sourcePath, caps, optio}),};}, { includeDeleted: true });+ if (finished?.status === 'ready' && !finished.deleted) noteImageTo3d('completion');await rmGuarded(usdzDiskPath(id), { force: true }).catch((err) => console.error(`❌ Image-to-3D stale USDZ cleanup failed for ${id}: ${err.message}`));console.log(`🧊 Image-to-3D mesh ready: ${id}`);@@ -321,6 +335,7 @@ export const getModel = store.getModel;export async function deleteModel(id) {const current = await store.getModel(id, { includeDeleted: true });const result = await store.deleteModel(id);+ if (current?.status === 'generating') noteImageTo3d('cancellation');if (current?.status === 'generating' && current.generationOperationId) {const kill = activeRenders.get(current.generationOperationId);if (kill) {@@ -430,6 +445,7 @@ async function beginRender(record, adapter, sourcePath, caps, requestOptions) {};});+ if (next?.status === 'generating') noteImageTo3d('start');activeOperations.add(operationId);setImmediate(() => {void executeRender({ id, operationId, adapter, sourcePath, caps, options });diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.jsindex 46db2ae5e1..71774cff85 100644--- a/server/services/imageTo3d/models.test.js+++ b/server/services/imageTo3d/models.test.js@@ -74,6 +74,7 @@ import { isTrellis2Installed, runTrellis2Generate } from './trellis2.js';import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';import { prepareSourceImage } from './sourceKeying.js';import * as store from './db.js';+import { drainActivityNotesForTests } from '../systemActivityNotify.js';import {createModel, startGeneration, getModelAsset, getModelFullMesh, getModelUsdz, saveModelUsdz,USDZ_MAX_BYTES, recoverInterruptedModels, deleteModel,@@ -92,6 +93,7 @@ const draftRecord = () => ({describe('image-to-3D model orchestration', () => {beforeEach(() => {+ drainActivityNotesForTests();vi.clearAllMocks();claimHeavyLocalJob.mockResolvedValue({ ok: true, holder: {}, release: claimRelease });isTrellis2Installed.mockReturnValue(true);@@ -166,6 +168,7 @@ describe('image-to-3D model orchestration', () => {expect(posixPath(current.assetPath)).toBe('/data/image-to-3d/image3d-example/model.glb');expect(current.generationOperationId).toBeNull();expect(current.runs.at(-1)).toMatchObject({ status: 'completed', percent: 100 });+ expect(drainActivityNotesForTests().map((note) => note.phase)).toEqual(['start', 'completion', 'drained']);});// A new mesh makes the AR export a lie — it describes the geometry the render@@ -210,6 +213,7 @@ describe('image-to-3D model orchestration', () => {await vi.waitFor(() => expect(current.status).toBe('failed'));expect(current.error).toMatch(/exited 1/);expect(current.runs.at(-1)).toMatchObject({ status: 'failed' });+ expect(drainActivityNotesForTests().map((note) => note.phase)).toEqual(['start', 'failure', 'drained']);});it('recoverInterruptedModels never launches a render (no cold-bootstrap)', async () => {@@ -252,6 +256,7 @@ describe('image-to-3D model orchestration', () => {expect(current.status).toBe('generating');await deleteModel('image3d-example');+ expect(drainActivityNotesForTests().map((note) => note.phase)).toEqual(['start', 'cancellation', 'drained']);// The in-flight subprocess is SIGTERM'd promptly.expect(killSpy).toHaveBeenCalled();expect(current.deleted).toBe(true);diff --git a/server/services/runner.js b/server/services/runner.jsindex 36a690264c..ea7c68e10b 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -182,7 +182,11 @@ export async function finalizeRunRecord({ runId, output, exitCode, success, erro// already persisted by this point, so a failing hook must not un-finalize it.if (success) {safeSettle(() => runnerConfig.hooks?.onRunCompleted?.(metadata, output), 'onRunCompleted');- } else if (!canceled && reportFailure) {+ } else if (canceled) {+ // A Stop is not a provider failure. The hook still has to fire so the+ // shared activity snapshot drops the run; `onRunFailed` stays silent.+ safeSettle(() => runnerConfig.hooks?.onRunCanceled?.({ runId: metadata.id }), 'onRunCanceled');+ } else if (reportFailure) {safeSettle(() => runnerConfig.hooks?.onRunFailed?.(metadata, metadata.error, output), 'onRunFailed');}@@ -603,7 +607,9 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, sc// the terminal result or prevents the caller from settling.if (metadata.success) {safeSettle(() => runnerConfig.hooks?.onRunCompleted?.(metadata, output), `Run ${runId} onRunCompleted hook`);- } else if (!canceled) {+ } else if (canceled) {+ safeSettle(() => runnerConfig.hooks?.onRunCanceled?.({ runId }), `Run ${runId} onRunCanceled hook`);+ } else {safeSettle(() => runnerConfig.hooks?.onRunFailed?.(metadata, metadata.error, output), `Run ${runId} onRunFailed hook`);}safeSettle(() => onComplete?.(stdoutIsResponse && metadata.success ? { ...metadata, text: assistantOutput } : metadata), `Run ${runId} onComplete`);@@ -622,7 +628,9 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, scoutputSize: Buffer.byteLength(output),...(canceled ? { canceled: true, completionReason: hostInterrupted ? 'host-shutdown' : 'canceled' } : {}),};- if (!canceled) {+ if (canceled) {+ safeSettle(() => runnerConfig.hooks?.onRunCanceled?.({ runId }), `Run ${runId} onRunCanceled hook`);+ } else {safeSettle(() => runnerConfig.hooks?.onRunFailed?.(failMetadata, failMetadata.error, output), `Run ${runId} onRunFailed hook`);}safeSettle(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);diff --git a/server/services/runner.test.js b/server/services/runner.test.jsindex 8b1be99e7b..f7704ece9a 100644--- a/server/services/runner.test.js+++ b/server/services/runner.test.js@@ -203,9 +203,10 @@ describe('finalizeRunRecord — authoritative timeout classification', () => {it('records cancellation without scanning output or firing the provider-failure hook', async () => {const errorDetection = { analyzeError: vi.fn() };const onRunFailed = vi.fn();+ const onRunCanceled = vi.fn();setAIToolkit(fakeToolkit(errorDetection), {dataDir: '/tmp/test-runner',- hooks: { onRunFailed },+ hooks: { onRunFailed, onRunCanceled },});const metadata = await finalizeRunRecord({@@ -225,6 +226,7 @@ describe('finalizeRunRecord — authoritative timeout classification', () => {});expect(errorDetection.analyzeError).not.toHaveBeenCalled();expect(onRunFailed).not.toHaveBeenCalled();+ expect(onRunCanceled).toHaveBeenCalledWith({ runId: 'run-canceled-story' });});// A caller that synthesizes its own run id instead of going through toolkit@@ -475,10 +477,11 @@ describe('executeCliRun — intentional cancellation', () => {spawn.mockReturnValue(child);const errorDetection = { analyzeError: vi.fn() };const onRunFailed = vi.fn();+ const onRunCanceled = vi.fn();const toolkit = fakeToolkit(errorDetection);setAIToolkit(toolkit, {dataDir: '/tmp/test-runner',- hooks: { onRunFailed },+ hooks: { onRunFailed, onRunCanceled },});const onComplete = vi.fn();const provider = {@@ -509,6 +512,7 @@ describe('executeCliRun — intentional cancellation', () => {}));expect(errorDetection.analyzeError).not.toHaveBeenCalled();expect(onRunFailed).not.toHaveBeenCalled();+ expect(onRunCanceled).toHaveBeenCalledWith({ runId: 'run-cli-canceled' });});});diff --git a/server/services/socket.js b/server/services/socket.jsindex 33fbf20309..25c22c3487 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -41,6 +41,7 @@ import { detachShellSocket, registerShellHandlers } from '../sockets/shell.js';import { getBuildId } from '../lib/buildId.js';import { authEvents, extractToken, isAuthEnabled, verifySession } from './auth.js';import { runEventLogEvents } from './agentRunEventLog.js';+import { armSystemActivityWatchers, bindSystemActivityIo } from './systemActivityNotify.js';// Store CoS subscribersconst cosSubscribers = new Set();@@ -255,6 +256,12 @@ export function initSocket(io) {ioInstance = io;setupEventForwarding();+ // Invalidation only. Clients coalesce the frame into one bounded activity+ // read; a missed frame is repaired by the reconnect read, not by polling.+ bindSystemActivityIo(io);+ armSystemActivityWatchers().catch((err) => {+ console.error(`❌ system activity watchers failed: ${err.message}`);+ });}// Bridge importer analyze-phase stage progress onto Socket.IO so the Importerdiff --git a/server/services/systemActivityNotify.js b/server/services/systemActivityNotify.jsnew file mode 100644index 0000000000..9895aa3627--- /dev/null+++ b/server/services/systemActivityNotify.js@@ -0,0 +1,194 @@+/**+ * Coalesced invalidation for the shared system-activity snapshot.+ *+ * Lifecycle transitions call `noteSystemActivity(source, phase)`. Bursts inside+ * one short window collapse to a single `system:activity` frame. The frame is+ * an invalidation — sequence, source, phase — never the snapshot and never+ * record content. Clients perform one bounded read of `getSystemActivity()`,+ * and a failed read stays unknown rather than idle.+ *+ * GPU/CPU samples have no lifecycle event. They stay on a separate telemetry+ * read that the live-activity inspector polls only while it is visible.+ */++const ACTIVITY_SOURCES = new Set([+ 'agents', 'media', 'imageTo3d', 'llm', 'mind', 'appOperations', 'backup', 'update',+]);++export const SYSTEM_ACTIVITY_COALESCE_MS = 50;++let io = null;+let seq = 0;+let timer = null;+let pending = null;+const notes = [];+let armed = false;+let previousMind = null;+const unsubs = [];++export function bindSystemActivityIo(next) {+ io = next || null;+}++export function noteSystemActivity(source, phase) {+ if (!ACTIVITY_SOURCES.has(source) || typeof phase !== 'string' || !phase) return;+ notes.push({ source, phase });+ pending = { source, phase };+ if (timer) return;+ timer = setTimeout(flushSystemActivity, SYSTEM_ACTIVITY_COALESCE_MS);+ timer.unref?.();+}++export function flushSystemActivity() {+ if (timer) {+ clearTimeout(timer);+ timer = null;+ }+ const note = pending;+ pending = null;+ if (!note || !io || typeof io.emit !== 'function') return;+ seq += 1;+ try {+ io.emit('system:activity', { seq, source: note.source, phase: note.phase });+ } catch (err) {+ console.error(`❌ system activity notify failed: ${err.message}`);+ }+}++/** Every note since the last drain, including ones still waiting to coalesce. */+export function drainActivityNotesForTests() {+ return notes.splice(0);+}++export function resetSystemActivityNotifyForTests() {+ if (timer) clearTimeout(timer);+ timer = null;+ pending = null;+ notes.length = 0;+ seq = 0;+ io = null;+ previousMind = null;+ for (const off of unsubs.splice(0)) off();+ armed = false;+}++function listen(emitter, event, handler) {+ emitter.on(event, handler);+ unsubs.push(() => emitter.off(event, handler));+}++export function mindActivityPhases(previous, next) {+ if (!next || typeof next !== 'object') return [];+ const thinking = Boolean(next.activeTurnId);+ const wasThinking = Boolean(previous?.activeTurnId);+ const queued = Number(next.queuedMessageCount) || 0;+ const wasQueued = Number(previous?.queuedMessageCount) || 0;+ const failed = (Number(next.failureCount) || 0) > (Number(previous?.failureCount) || 0);+ const phases = [];+ if (!wasThinking && thinking) phases.push('start');+ else if (wasThinking && !thinking) {+ if (next.status === 'paused') phases.push('cancellation');+ else if (failed || next.status === 'degraded' || next.status === 'interrupted') phases.push('failure');+ else phases.push('completion');+ }+ if (queued > wasQueued) phases.push('queued');+ else if (wasQueued > 0 && queued < wasQueued) phases.push('drained');+ return phases;+}++export function agentCompletionPhase(agent) {+ if (agent?.result?.success === true) return 'completion';+ const error = typeof agent?.result?.error === 'string' ? agent.result.error : '';+ if (/terminat|kill|cancel/i.test(error)) return 'cancellation';+ return 'failure';+}++export function taskQueuePhase(change) {+ const action = change?.action;+ if (action === 'added' || action === 'unblocked' || action === 'requeued' || action === 'approved') return 'queued';+ if (action === 'deleted') return 'drained';+ if (change?.previousStatus === 'pending' && change?.task?.status && change.task.status !== 'pending') return 'drained';+ return null;+}++const MEDIA_PHASE = {+ enqueued: 'queued',+ started: 'start',+ completed: 'completion',+ failed: 'failure',+ canceled: 'cancellation',+};++const MEDIA_TERMINAL = new Set(['completion', 'failure', 'cancellation']);+const LIVE_MEDIA = new Set(['queued', 'running']);++/**+ * Wrap the host's runner hooks so every LLM lifecycle edge invalidates the+ * snapshot. Notes first: a throwing usage/error hook must not swallow the+ * invalidation. Cancellation is its own hook because a Stop does not fire+ * `onRunFailed`.+ */+export function attachLlmActivityHooks(hooks = {}) {+ return {+ ...hooks,+ onRunStarted: (metadata) => {+ noteSystemActivity('llm', 'start');+ return hooks.onRunStarted?.(metadata);+ },+ onRunCompleted: (metadata, output) => {+ noteSystemActivity('llm', 'completion');+ return hooks.onRunCompleted?.(metadata, output);+ },+ onRunFailed: (metadata, error) => {+ noteSystemActivity('llm', 'failure');+ return hooks.onRunFailed?.(metadata, error);+ },+ onRunCanceled: (metadata) => {+ noteSystemActivity('llm', 'cancellation');+ return hooks.onRunCanceled?.(metadata);+ },+ };+}++export async function armSystemActivityWatchers() {+ if (armed) return;+ armed = true;+ let mediaJobEvents;+ let listJobs;+ let cosEvents;+ try {+ ({ mediaJobEvents, listJobs } = await import('./mediaJobQueue/index.js'));+ ({ cosEvents } = await import('./cosEvents.js'));+ } catch (err) {+ armed = false;+ throw err;+ }++ for (const [event, phase] of Object.entries(MEDIA_PHASE)) {+ listen(mediaJobEvents, event, () => {+ noteSystemActivity('media', phase);+ if (!MEDIA_TERMINAL.has(phase)) return;+ let live = true;+ try {+ live = listJobs().some((job) => LIVE_MEDIA.has(job?.status));+ } catch (err) {+ console.error(`❌ media activity drain check failed: ${err.message}`);+ return;+ }+ if (!live) noteSystemActivity('media', 'drained');+ });+ }++ listen(cosEvents, 'agent:spawned', () => noteSystemActivity('agents', 'start'));+ listen(cosEvents, 'agent:terminate', () => noteSystemActivity('agents', 'cancellation'));+ listen(cosEvents, 'agent:completed', (agent) => noteSystemActivity('agents', agentCompletionPhase(agent)));+ listen(cosEvents, 'tasks:changed', (change) => {+ const phase = taskQueuePhase(change);+ if (phase) noteSystemActivity('agents', phase);+ });+ listen(cosEvents, 'persistent-mind:status', (status) => {+ const phases = mindActivityPhases(previousMind, status);+ previousMind = status && typeof status === 'object' ? status : previousMind;+ for (const phase of phases) noteSystemActivity('mind', phase);+ });+}diff --git a/server/services/systemActivityNotify.test.js b/server/services/systemActivityNotify.test.jsnew file mode 100644index 0000000000..8a846b406d--- /dev/null+++ b/server/services/systemActivityNotify.test.js@@ -0,0 +1,121 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { claimAppOperation, endAppOperation, __resetAppOperations } from './appOperations.js';+import { cosEvents } from './cosEvents.js';+import { mediaJobEvents } from './mediaJobQueue/index.js';+import {+ SYSTEM_ACTIVITY_COALESCE_MS,+ agentCompletionPhase,+ armSystemActivityWatchers,+ attachLlmActivityHooks,+ bindSystemActivityIo,+ drainActivityNotesForTests,+ mindActivityPhases,+ noteSystemActivity,+ resetSystemActivityNotifyForTests,+ taskQueuePhase,+} from './systemActivityNotify.js';++afterEach(() => {+ resetSystemActivityNotifyForTests();+ __resetAppOperations();+ vi.useRealTimers();+});++describe('system activity invalidation', () => {+ it('coalesces a burst into one frame that carries no snapshot', () => {+ vi.useFakeTimers();+ const emit = vi.fn();+ bindSystemActivityIo({ emit });+ noteSystemActivity('media', 'start');+ noteSystemActivity('media', 'completion');+ noteSystemActivity('agents', 'queued');+ expect(emit).not.toHaveBeenCalled();+ vi.advanceTimersByTime(SYSTEM_ACTIVITY_COALESCE_MS);+ expect(emit).toHaveBeenCalledTimes(1);+ expect(emit).toHaveBeenCalledWith('system:activity', { seq: 1, source: 'agents', phase: 'queued' });+ expect(Object.keys(emit.mock.calls[0][1]).sort()).toEqual(['phase', 'seq', 'source']);+ });++ it('maps mind, agent, and task edges onto lifecycle phases', () => {+ expect(mindActivityPhases(null, { activeTurnId: 't', queuedMessageCount: 2, status: 'thinking', failureCount: 0 }))+ .toEqual(['start', 'queued']);+ expect(mindActivityPhases(+ { activeTurnId: 't', queuedMessageCount: 2, failureCount: 0 },+ { activeTurnId: null, queuedMessageCount: 0, status: 'idle', failureCount: 0 },+ )).toEqual(['completion', 'drained']);+ expect(mindActivityPhases(+ { activeTurnId: 't', queuedMessageCount: 0, failureCount: 0 },+ { activeTurnId: null, queuedMessageCount: 0, status: 'paused', failureCount: 0 },+ )).toEqual(['cancellation']);+ expect(mindActivityPhases(+ { activeTurnId: 't', queuedMessageCount: 0, failureCount: 0 },+ { activeTurnId: null, queuedMessageCount: 0, status: 'degraded', failureCount: 1 },+ )).toEqual(['failure']);++ expect(agentCompletionPhase({ result: { success: true } })).toBe('completion');+ expect(agentCompletionPhase({ result: { success: false, error: 'provider failed' } })).toBe('failure');+ expect(agentCompletionPhase({ result: { success: false, error: 'Agent terminated by user' } })).toBe('cancellation');+ expect(taskQueuePhase({ action: 'added' })).toBe('queued');+ expect(taskQueuePhase({ action: 'requeued' })).toBe('queued');+ expect(taskQueuePhase({ action: 'deleted' })).toBe('drained');+ expect(taskQueuePhase({ action: 'updated', previousStatus: 'pending', task: { status: 'in_progress' } })).toBe('drained');+ expect(taskQueuePhase({ action: 'updated', previousStatus: 'pending', task: { status: 'pending' } })).toBeNull();+ });++ it('notifies start, completion, failure, cancellation, and queue drain for every event-backed source', async () => {+ await armSystemActivityWatchers();+ drainActivityNotesForTests();++ mediaJobEvents.emit('enqueued', { id: 'job-1' });+ mediaJobEvents.emit('started', { id: 'job-1' });+ mediaJobEvents.emit('completed', { id: 'job-1', status: 'completed' });+ mediaJobEvents.emit('failed', { id: 'job-2', status: 'failed' });+ mediaJobEvents.emit('canceled', { id: 'job-3', status: 'canceled' });++ cosEvents.emit('agent:spawned', { id: 'agent-1' });+ cosEvents.emit('agent:completed', { id: 'agent-1', result: { success: true } });+ cosEvents.emit('agent:completed', { id: 'agent-2', result: { success: false, error: 'spawn failed' } });+ cosEvents.emit('agent:terminate', 'agent-3');+ cosEvents.emit('agent:completed', { id: 'agent-3', result: { success: false, error: 'Agent killed by user' } });+ cosEvents.emit('tasks:changed', { action: 'added', task: { status: 'pending' } });+ cosEvents.emit('tasks:changed', { action: 'updated', previousStatus: 'pending', task: { status: 'in_progress' } });++ cosEvents.emit('persistent-mind:status', { activeTurnId: 'turn-1', queuedMessageCount: 1, status: 'thinking', failureCount: 0 });+ cosEvents.emit('persistent-mind:status', { activeTurnId: null, queuedMessageCount: 0, status: 'idle', failureCount: 0 });+ cosEvents.emit('persistent-mind:status', { activeTurnId: 'turn-2', queuedMessageCount: 0, status: 'thinking', failureCount: 0 });+ cosEvents.emit('persistent-mind:status', { activeTurnId: null, queuedMessageCount: 0, status: 'paused', failureCount: 0 });+ cosEvents.emit('persistent-mind:status', { activeTurnId: 'turn-3', queuedMessageCount: 0, status: 'thinking', failureCount: 0 });+ cosEvents.emit('persistent-mind:status', { activeTurnId: null, queuedMessageCount: 0, status: 'interrupted', failureCount: 1 });++ const hooks = attachLlmActivityHooks({+ onRunCompleted: () => 'kept',+ });+ expect(hooks.onRunStarted({})).toBeUndefined();+ expect(hooks.onRunCompleted({}, '')).toBe('kept');+ hooks.onRunFailed({}, new Error('no'));+ hooks.onRunCanceled({ runId: 'run-1' });++ const io = { emit: vi.fn() };+ const app = { id: 'app-1', name: 'Example', repoPath: 'app-1' };+ expect(claimAppOperation(io, app, 'update').ok).toBe(true);+ endAppOperation(io, 'app-1', 'failure');+ expect(claimAppOperation(io, app, 'standardize').ok).toBe(true);+ endAppOperation(io, 'app-1', 'completion');+ expect(claimAppOperation(io, app, 'update').ok).toBe(true);+ endAppOperation(io, 'app-1', 'cancellation');++ const phases = drainActivityNotesForTests();+ const of = (source) => phases.filter((note) => note.source === source).map((note) => note.phase);+ expect(of('media')).toEqual([+ 'queued', 'start', 'completion', 'drained', 'failure', 'drained', 'cancellation', 'drained',+ ]);+ expect(of('agents')).toEqual([+ 'start', 'completion', 'failure', 'cancellation', 'cancellation', 'queued', 'drained',+ ]);+ expect(of('mind')).toEqual(['start', 'queued', 'completion', 'drained', 'start', 'cancellation', 'start', 'failure']);+ expect(of('llm')).toEqual(['start', 'completion', 'failure', 'cancellation']);+ expect(of('appOperations')).toEqual([+ 'start', 'failure', 'drained', 'start', 'completion', 'drained', 'start', 'cancellation', 'drained',+ ]);+ });+});diff --git a/server/services/updateChecker.js b/server/services/updateChecker.jsindex ad772857f1..b2cb42e87b 100644--- a/server/services/updateChecker.js+++ b/server/services/updateChecker.js@@ -1,6 +1,7 @@import { join } from 'path';import { readFile, unlink } from 'fs/promises';import { EventEmitter } from 'events';+import { noteSystemActivity } from './systemActivityNotify.js';import { readJSONFile, PATHS, ensureDir, atomicWrite } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';import { isPlainObject } from '../lib/objects.js';@@ -424,6 +425,10 @@ export async function setUpdateInProgress(inProgress) {// Mirror BEFORE returning so the caller's next synchronous statement — and// any spawn engine that runs before the next tick — already sees the gate.updateInProgressMirror = inProgress;+ // `false` here is an explicit lock release with no result record — the+ // caller aborted the attempt. A finished attempt notes completion or+ // failure from `recordUpdateResult` instead.+ noteSystemActivity('update', inProgress ? 'start' : 'cancellation');return true;});}@@ -439,6 +444,7 @@ export async function recordUpdateResult(result) {state.lastUpdateResult = result;await saveState(state);updateInProgressMirror = false;+ noteSystemActivity('update', result?.success === true ? 'completion' : 'failure');});}@@ -525,6 +531,7 @@ export async function clearStaleUpdateInProgress() {};await saveState(state);updateInProgressMirror = false;+ noteSystemActivity('update', 'failure');return true;}diff --git a/server/services/updateChecker.test.js b/server/services/updateChecker.test.jsindex 31bcfc6d6f..e9addc7439 100644--- a/server/services/updateChecker.test.js+++ b/server/services/updateChecker.test.js@@ -573,6 +573,31 @@ describe('isUpdateInProgress mirror', () => {expect(atomicWrite).not.toHaveBeenCalled();});+ it('notifies system activity when the update lock starts, is canceled, finishes, or fails', async () => {+ const { drainActivityNotesForTests } = await import('./systemActivityNotify.js');+ drainActivityNotesForTests();+ readJSONFile.mockResolvedValue(persisted());+ await setUpdateInProgress(true);+ readJSONFile.mockResolvedValue(persisted({ updateInProgress: true }));+ await setUpdateInProgress(false);+ readJSONFile.mockResolvedValue(persisted());+ await setUpdateInProgress(true);+ readJSONFile.mockResolvedValue(persisted({ updateInProgress: true }));+ await recordUpdateResult({ version: '1.2.3', success: true, completedAt: '2026-01-01T00:00:00.000Z', log: '' });+ readJSONFile.mockResolvedValue(persisted());+ await setUpdateInProgress(true);+ readJSONFile.mockResolvedValue(persisted({ updateInProgress: true }));+ await recordUpdateResult({ version: '1.2.3', success: false, completedAt: '2026-01-01T00:00:00.000Z', log: 'nope' });+ expect(drainActivityNotesForTests()).toEqual([+ { source: 'update', phase: 'start' },+ { source: 'update', phase: 'cancellation' },+ { source: 'update', phase: 'start' },+ { source: 'update', phase: 'completion' },+ { source: 'update', phase: 'start' },+ { source: 'update', phase: 'failure' },+ ]);+ });+it('is cleared by the boot-time stale sweep', async () => {readJSONFile.mockResolvedValue(persisted());await setUpdateInProgress(true);diff --git a/server/sockets/apps.js b/server/sockets/apps.jsindex 2aff91fb3f..37ea75d8d5 100644--- a/server/sockets/apps.js+++ b/server/sockets/apps.js@@ -104,6 +104,7 @@ export const registerAppHandlers = (socket, io) => {socket.on('app:standardize', async (rawData) => {let operatingAppId = null;+ let outcome = 'failure';try {const data = validateSocketData(appStandardizeSchema, rawData, socket, 'app:standardize');if (!data) return;@@ -187,13 +188,14 @@ export const registerAppHandlers = (socket, io) => {processes: analysis.proposedChanges.processes}});+ outcome = 'completion';console.log(`✅ Socket standardize complete for ${app.name}`);} catch (err) {const message = err?.message ?? String(err);console.error(`❌ Socket handler error [app:standardize]: ${message}`);io.emit('app:standardize:error', { appId: operatingAppId, message });} finally {- if (operatingAppId) endAppOperation(io, operatingAppId);+ if (operatingAppId) endAppOperation(io, operatingAppId, outcome);}});