Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Fix RC metrics, agent state, and bundle regressions

rcourtman1b0b54534bd1
diff --git a/.gitleaksignore b/.gitleaksignore
index 748197b601..c156fa3ab4 100644
--- a/.gitleaksignore
+++ b/.gitleaksignore
@@ -1,4 +1,5 @@
-# browser-verification.json stores a SHA-256 digest beside the APITokenManager
-# source path. That path context makes the generic API-key rule classify the
-# required content digest as a credential; suppress only that exact fingerprint.
-frontend-modern/browser-verification.json:generic-api-key:10
+# browser-verification.json stores SHA-256 digests beside the API token manager
+# source paths. That path context makes the generic API-key rule classify the
+# required content digests as credentials; suppress only those exact fingerprints.
+frontend-modern/browser-verification.json:generic-api-key:11
+frontend-modern/browser-verification.json:generic-api-key:12
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 00b22696df..c50be016da 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -5587,9 +5587,13 @@ Report ingestion holds a shared lifecycle lock for the full state transition;
deletion, manual allowance, and tombstone expiry hold the exclusive side.
Reports that began before deletion complete first, then deletion removes their
result. Reports arriving after deletion see the tombstone. A completed delete
-therefore cannot be undone by an in-flight report, while unrelated and
-duplicate-machine agents remain concurrent and independently bound by token
-plus hostname.
+therefore cannot be undone by an in-flight report. Before that delete returns,
+the same transition must republish the canonical unified-resource generation
+so an immediate `/api/state` read cannot retain the removed host behind the
+read-path freshness window. Unrelated and duplicate-machine agents remain
+concurrent and independently bound by token plus hostname. The focused
+read-after-delete proof lives in
+`internal/monitoring/monitor_host_agent_removal_lifecycle_test.go`.
The server transition does not introduce a second installer lifecycle.
Generated host install commands still mint the canonical scoped token, and the
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index a868db5cef..7ccb31c9e3 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -93,6 +93,7 @@ an enabled external-probe assignment.
15. `frontend-modern/src/api/responseUtils.ts`
16. `frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx`
17. `frontend-modern/src/components/Settings/APITokenManager.tsx`
+17. `frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx`
18. `frontend-modern/src/components/Settings/apiTokenManagerModel.ts`
19. `frontend-modern/src/constants/apiScopes.ts`
20. `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`
@@ -1190,6 +1191,11 @@ payload shape change when the portal presents compact client rows.
pressed/unpressed selector pill shell routes through frontend-primitives
`SelectablePillButton` instead of API-token-local rounded-full selector
classes.
+16. `frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx` shared with `security-privacy`: the deferred API token edit and revoke dialogs preserve the shared security/privacy and API contract boundary.
+ Edit and revoke dialogs are deferred behind the explicit row action so the
+ API Access entry chunk does not ship mutation-only controls before they are
+ requested. Deferral must not weaken the existing confirmation, scope
+ validation, failure-open, or read-after-write behavior.
17. `frontend-modern/src/components/Settings/apiTokenManagerModel.ts` shared with `security-privacy`: the pure API token settings model is both a security/privacy control surface and a canonical API payload contract boundary.
18. `frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/NodeCredentialSlot.tsx` shared with `agent-lifecycle`: the inline node credential slot is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.
19. `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx` shared with `agent-lifecycle`: the pure infrastructure operations inventory/install model is both an agent fleet lifecycle control surface and an API token, lookup, assignment, and reporting/install contract boundary.
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 76e1ba1eda..9b09e8d981 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -2596,6 +2596,10 @@ snapshot and cache.
`ApplyHostReport` and removal are ordered by the dedicated host lifecycle
read/write lock. Concurrent reports may proceed together, but deletion waits
for earlier reports and prevents later reports from resurrecting the host.
+Accepted reports and completed removals both republish the canonical unified
+resource store before returning. An immediate state read therefore observes
+the removal even when the prior registry generation remains inside the
+read-path freshness window.
Only a post-removal token and matching retained machine identity may transition
the tombstone back to active continuity. The canonical host ID survives report
ID or persisted-agent-ID alias changes across Linux/systemd, Docker unified
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 59efa8ff1f..d072dfac4d 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -1281,7 +1281,13 @@ bounded live-ingestion queue. SQLite remains the serialization boundary for
their transactions, but maintenance CPU or read work must not stop buffered
writes or `Flush` barriers from progressing; shutdown must join both workers
before closing their shared database. `pkg/metrics/store_additional_test.go`
-must prove ingestion remains live while startup maintenance is blocked. Rollup
+must prove ingestion remains live while startup maintenance is blocked.
+Synchronous platform-poller batches must also enter SQLite through that single
+ingestion worker rather than opening one write transaction per caller. A busy
+WAL writer may delay the worker, but it must not let concurrent pollers consume
+the shared reader pool, starve `/api/state` history reads, or multiply slow
+`BEGIN` waits; the concurrent-poller regression proof must keep database use
+bounded to the existing writer plus one ingestion-worker connection. Rollup
transactions must also keep a bounded
time-window working set and resume from checkpoints across invocations instead
of aggregating every pending series and bucket in one global SQLite GROUP BY
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 4e10be0961..1b5a00795f 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -242,6 +242,14 @@
"security-privacy"
]
},
+ {
+ "path": "frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx",
+ "rationale": "the deferred API token edit and revoke dialogs preserve the shared security/privacy and API contract boundary",
+ "subsystems": [
+ "api-contracts",
+ "security-privacy"
+ ]
+ },
{
"path": "frontend-modern/src/components/Settings/apiTokenManagerModel.ts",
"rationale": "the pure API token settings model is both a security/privacy control surface and a canonical API payload contract boundary",
@@ -2469,6 +2477,7 @@
"docs/release-control/v6/internal/mobile_compatibility_manifest.schema.json",
"frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx",
"frontend-modern/src/components/Settings/APITokenManager.tsx",
+ "frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx",
"frontend-modern/src/components/Settings/apiTokenManagerModel.ts",
"frontend-modern/src/components/Settings/availabilitySettingsModel.ts",
"frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/AvailabilityTargetSlot.tsx",
@@ -2908,6 +2917,7 @@
"match_prefixes": [],
"match_files": [
"frontend-modern/src/components/Settings/APITokenManager.tsx",
+ "frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx",
"frontend-modern/src/components/Settings/apiTokenManagerModel.ts",
"frontend-modern/src/components/Settings/useAPITokenManagerState.ts",
"frontend-modern/src/constants/apiScopes.ts"
@@ -5250,6 +5260,7 @@
"test_prefixes": [],
"exact_files": [
"internal/monitoring/kubernetes_agents_test.go",
+ "internal/monitoring/monitor_host_agent_removal_lifecycle_test.go",
"internal/monitoring/monitor_host_agents_test.go",
"internal/monitoring/monitor_pbs_coverage_test.go",
"internal/monitoring/monitor_pmg_test.go",
@@ -6561,6 +6572,7 @@
"frontend-modern/src/api/security.ts",
"frontend-modern/src/components/Settings/APIAccessPanel.tsx",
"frontend-modern/src/components/Settings/APITokenManager.tsx",
+ "frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx",
"frontend-modern/src/components/Settings/apiTokenManagerModel.ts",
"frontend-modern/src/components/Settings/DataHandlingPanel.tsx",
"frontend-modern/src/components/Settings/dataHandlingPanelModel.ts",
@@ -6656,6 +6668,7 @@
"match_files": [
"frontend-modern/src/components/Settings/APIAccessPanel.tsx",
"frontend-modern/src/components/Settings/APITokenManager.tsx",
+ "frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx",
"frontend-modern/src/components/Settings/apiTokenManagerModel.ts",
"frontend-modern/src/components/Settings/DataHandlingPanel.tsx",
"frontend-modern/src/components/Settings/dataHandlingPanelModel.ts",
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 3c8c38802e..546c315d7c 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -47,6 +47,7 @@ into availability-probe entitlement.
5. `frontend-modern/src/api/security.ts`
6. `frontend-modern/src/components/Settings/APIAccessPanel.tsx`
7. `frontend-modern/src/components/Settings/APITokenManager.tsx`
+7. `frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx`
8. `frontend-modern/src/components/Settings/apiTokenManagerModel.ts`
9. `frontend-modern/src/components/Settings/GeneralSettingsPanel.tsx`
10. `frontend-modern/src/components/Settings/SecurityAuthPanel.tsx`
@@ -127,6 +128,11 @@ with missing, unknown, or unrelated scopes fail closed.
Stable in-page anchors for sibling API Access onboarding panels are allowed
only as navigation into the token creation section; those sibling panels do
not own token scope derivation or preset contents.
+3. `frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx` shared with `api-contracts`: the deferred API token edit and revoke dialogs preserve the shared security/privacy and API contract boundary.
+ The dialogs may load on demand after the operator selects their row action.
+ This bundle boundary changes neither authorization nor mutation semantics
+ and must preserve the explicit revoke confirmation, scope validation, and
+ failed-edit state.
4. `frontend-modern/src/components/Settings/apiTokenManagerModel.ts` shared with `api-contracts`: the pure API token settings model is both a security/privacy control surface and a canonical API payload contract boundary.
5. `frontend-modern/src/components/Settings/DataHandlingPanel.tsx` shared with `frontend-primitives`: the data-handling settings surface is both a security/privacy trust surface and a canonical settings-shell presentation boundary.
6. `frontend-modern/src/components/Settings/dataHandlingPanelModel.ts` shared with `frontend-primitives`: the data-handling settings model is both a security/privacy posture projection and a canonical settings-shell presentation boundary.
diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.json
index d0c2c5d4d0..104295a595 100644
--- a/frontend-modern/browser-verification.json
+++ b/frontend-modern/browser-verification.json
@@ -1,37 +1,33 @@
{
"version": 1,
- "base_sha": "1e4791df4bc38be488f597b9e1f67922c850207b",
- "verified_at": "2026-08-04T19:19:20Z",
+ "base_sha": "8e25badea1d13b32ca659aaa9f9727ecf1c32c17",
+ "verified_at": "2026-08-04T23:21:18Z",
"result": "passed",
"changed_paths": [
- "frontend-modern/src/features/alerts/AlertHistoryTableAlertRow.tsx",
- "frontend-modern/src/features/alerts/AlertHistoryTableSection.tsx",
- "frontend-modern/src/index.css"
+ "frontend-modern/src/components/Settings/APITokenManager.tsx",
+ "frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx"
],
"content_sha256": {
- "frontend-modern/src/features/alerts/AlertHistoryTableAlertRow.tsx": "478c6e7cb0dbcd3df3cbdfa109a8c9bdaac6a74d79dd10f164effeb04b8c8d59",
- "frontend-modern/src/features/alerts/AlertHistoryTableSection.tsx": "4ee36f4c32c7a91a18c3e1b6dcbc58772a80d32dcd77e947f99b9ea195e0d9d9",
- "frontend-modern/src/index.css": "dee4c03b06fcb24cd5642516f11e6dc7c4777a3989a1a2ef30a50354e1625091"
+ "frontend-modern/src/components/Settings/APITokenManager.tsx": "46bd97089aab5be47b7595fc8abcbf15a908444d0922906433389222bc348777",
+ "frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx": "7355009b809c47eae65c8704efc6c74ca673567dc7abdd24f8ef4ba247b5c1ca"
},
- "routes": ["/alerts/history"],
+ "routes": ["/settings/security/api"],
"viewports": [
- { "width": 375, "height": 812 },
- { "width": 768, "height": 900 },
- { "width": 1024, "height": 900 },
- { "width": 1280, "height": 900 },
- { "width": 1600, "height": 900 }
+ { "width": 1440, "height": 1000 },
+ { "width": 390, "height": 844 }
],
"states": [
- "Rendered grouped mobile alert cards at 375px with the desktop table fully inactive and no document overflow",
- "Rendered the six core columns Timestamp, Resource, Severity, Message, Status, and Actions at 768px and 1024px",
- "Rendered Duration as the seventh context column once the table shell reached 800px at the 1280px viewport",
- "Rendered the complete nine-column inventory, including Type and Node, once the table shell reached 1024px at the 1600px viewport",
- "Measured equal table-shell client and scroll widths at every desktop and tablet breakpoint"
+ "Rendered the API Access token inventory with five scoped credentials and no wildcard warning",
+ "Opened the deferred scope editor with the live settings:write selection and unchanged Save scopes action disabled",
+ "Opened the deferred revoke confirmation with the selected token name and irreversible-impact warning",
+ "Rendered the scope editor at 390px with a 358px dialog, bounded internal scrolling, and both footer actions visible",
+ "Confirmed both dialogs close cleanly and leave no dialog mounted",
+ "Observed no browser console errors across the desktop and narrow interaction matrix"
],
"interactions": [
- "Opened the Timeline action for the 10:24 PM pve3 row at 1024px and verified the expanded incident row remained within the table shell",
- "Closed the expanded timeline using its Hide action without changing the responsive column allocation",
- "Inspected the accessibility snapshot at compact width and confirmed collapsed Type, Duration, and Node columns are omitted rather than announced with hidden content",
- "Compared the live column widths at 768px, 1024px, 1280px, and 1600px and confirmed every visible track redistributes across the full card"
+ "Opened Edit scopes from a specific token card at 1440px, inspected the complete checkbox inventory, and cancelled without mutation",
+ "Opened Revoke from the same token card, verified the explicit confirmation boundary, and cancelled without revoking the token",
+ "Repeated the deferred Edit scopes load at 390px and verified Cancel and disabled Save scopes remained visible and usable",
+ "Closed the narrow scope editor and verified the dialog was removed without changing token state"
]
}
diff --git a/frontend-modern/src/components/Settings/APITokenManager.tsx b/frontend-modern/src/components/Settings/APITokenManager.tsx
index 24df9b23ca..bfafe6ed71 100644
--- a/frontend-modern/src/components/Settings/APITokenManager.tsx
+++ b/frontend-modern/src/components/Settings/APITokenManager.tsx
@@ -1,6 +1,5 @@
-import { Component, For, Show, createSignal } from 'solid-js';
+import { Component, For, Show, createSignal, lazy } from 'solid-js';
import { Card } from '@/components/shared/Card';
-import { Dialog } from '@/components/shared/Dialog';
import { ExternalTextLink } from '@/components/shared/ExternalTextLink';
import { SectionHeader } from '@/components/shared/SectionHeader';
import { LoadingSpinner } from '@/components/shared/LoadingSpinner';
@@ -24,6 +23,12 @@ interface APITokenManagerProps {
canManage?: boolean;
}
+const APITokenManagerDialogs = lazy(() =>
+ import('./APITokenManagerDialogs').then((module) => ({
+ default: module.APITokenManagerDialogs,
+ })),
+);
+
export const APITokenManager: Component<APITokenManagerProps> = (props) => {
const [tokenToRevoke, setTokenToRevoke] = createSignal<APITokenRecord | null>(null);
const [tokenToEdit, setTokenToEdit] = createSignal<APITokenRecord | null>(null);
@@ -117,6 +122,11 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
}
};
+ const revokeToken = (token: APITokenRecord) => {
+ setTokenToRevoke(null);
+ void handleDelete(token);
+ };
+
const renderTokenScopes = (token: APITokenRecord) => {
const rawScopes = effectiveScopes(token);
const scopeBadges = rawScopes.includes('*')
@@ -689,148 +699,20 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
</ExternalTextLink>
</Card>
- <Show when={tokenToEdit()}>
- <Dialog
- isOpen={true}
- onClose={closeScopeEditor}
- panelClass="max-w-2xl"
- ariaLabel="Edit API token scopes"
- >
- <div class="w-full space-y-5 p-6">
- <div>
- <h3 class="text-lg font-semibold text-base-content">Edit token scopes</h3>
- <p class="mt-1 text-sm text-muted">
- Changes to{' '}
- <span class="font-medium text-base-content">
- {tokenToEdit()!.name || tokenToEdit()!.id}
- </span>{' '}
- take effect on its next request. The token value and expiry do not change.
- </p>
- </div>
-
- <label class="flex cursor-pointer items-start gap-3 rounded-md border border-amber-300 bg-amber-50 p-3 text-sm dark:border-amber-700 dark:bg-amber-900">
- <input
- type="checkbox"
- checked={editScopes().includes('*')}
- onChange={() => toggleEditScope('*')}
- disabled={updatingTokenId() !== null}
- class="mt-0.5 h-4 w-4 rounded border-border text-amber-600 focus:ring-amber-500"
- />
- <span>
- <span class="block font-semibold text-amber-900 dark:text-amber-100">
- Full access
- </span>
- <span class="text-amber-800 dark:text-amber-200">
- Legacy wildcard access to every API capability.
- </span>
- </span>
- </label>
-
- <div class="max-h-[50vh] space-y-4 overflow-y-auto pr-1">
- <For each={scopeGroups()}>
- {([group, options]) => (
- <fieldset class="space-y-2">
- <legend class="text-[0.7rem] font-semibold uppercase tracking-wide text-muted">
- {group}
- </legend>
- <div class="grid gap-2 sm:grid-cols-2">
- <For each={options}>
- {(option) => (
- <label class="flex cursor-pointer items-start gap-3 rounded-md border border-border p-3 text-sm transition hover:bg-surface-hover">
- <input
- type="checkbox"
- checked={editScopes().includes(option.value)}
- onChange={() => toggleEditScope(option.value)}
- disabled={updatingTokenId() !== null}
- class="mt-0.5 h-4 w-4 rounded border-border text-blue-600 focus:ring-blue-500"
- />
- <span>
- <span class="block font-medium text-base-content">
- {option.label}
- </span>
- <span class="text-xs text-muted">{option.description}</span>
- </span>
- </label>
- )}
- </For>
- </div>
- </fieldset>
- )}
- </For>
- </div>
-
- <Show when={editScopes().length === 0}>
- <p class="text-sm text-red-600 dark:text-red-300">
- Select at least one scope before saving.
- </p>
- </Show>
-
- <div class="flex justify-end gap-3 border-t border-border pt-4">
- <button
- type="button"
- onClick={closeScopeEditor}
- disabled={updatingTokenId() !== null}
- class="rounded-md border border-border px-4 py-2 text-sm font-medium text-base-content hover:bg-surface-hover disabled:cursor-not-allowed disabled:opacity-60"
- >
- Cancel
- </button>
- <button
- type="button"
- onClick={() => void saveEditedScopes()}
- disabled={
- editScopes().length === 0 || !editScopesChanged() || updatingTokenId() !== null
- }
- class="rounded-md bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-60"
- >
- {updatingTokenId() !== null ? 'Saving…' : 'Save scopes'}
- </button>
- </div>
- </div>
- </Dialog>
- </Show>
-
- {/* Revoke confirmation modal — token deletion is irreversible
- and breaks any agents/integrations relying on the token,
- so guard the action behind an explicit confirm. */}
- <Show when={tokenToRevoke()}>
- <Dialog
- isOpen={true}
- onClose={() => setTokenToRevoke(null)}
- panelClass="max-w-md"
- ariaLabel="Revoke API token"
- >
- <div class="w-full p-6">
- <h3 class="text-lg font-semibold text-base-content mb-2">Revoke API token?</h3>
- <p class="text-sm text-muted mb-4">
- This permanently revokes{' '}
- <span class="font-medium text-base-content">
- {tokenToRevoke()!.name || tokenToRevoke()!.id}
- </span>
- . Any agents, scripts, or integrations using it will stop authenticating until you
- issue and configure a replacement token.
- </p>
- <div class="flex justify-end gap-3">
- <button
- type="button"
- onClick={() => setTokenToRevoke(null)}
- class="px-4 py-2 text-sm font-medium text-base-content border border-border rounded-md hover:bg-surface-hover"
- >
- Cancel
- </button>
- <button
- type="button"
- onClick={() => {
- const token = tokenToRevoke();
- setTokenToRevoke(null);
- if (token) void handleDelete(token);
- }}
- class="px-4 py-2 text-sm font-medium bg-red-600 text-white rounded-md hover:bg-red-700"
- >
- Revoke token
- </button>
- </div>
- </div>
- </Dialog>
+ <Show when={tokenToEdit() || tokenToRevoke()}>
+ <APITokenManagerDialogs
+ tokenToEdit={tokenToEdit}
+ tokenToRevoke={tokenToRevoke}
+ editScopes={editScopes}
+ scopeGroups={scopeGroups}
+ updatingTokenId={updatingTokenId}
+ editScopesChanged={editScopesChanged}
+ onToggleEditScope={toggleEditScope}
+ onCloseScopeEditor={closeScopeEditor}
+ onSaveEditedScopes={() => void saveEditedScopes()}
+ onCancelRevoke={() => setTokenToRevoke(null)}
+ onRevoke={revokeToken}
+ />
</Show>
</div>
);
diff --git a/frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx b/frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx
new file mode 100644
index 0000000000..5df14a23b2
--- /dev/null
+++ b/frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx
@@ -0,0 +1,162 @@
+import { Component, For, Show, type Accessor } from 'solid-js';
+import { Dialog } from '@/components/shared/Dialog';
+import type { APIScopeOption } from '@/constants/apiScopes';
+import type { APITokenRecord } from '@/types/api';
+
+interface APITokenManagerDialogsProps {
+ tokenToEdit: Accessor<APITokenRecord | null>;
+ tokenToRevoke: Accessor<APITokenRecord | null>;
+ editScopes: Accessor<string[]>;
+ scopeGroups: Accessor<[APIScopeOption['group'], APIScopeOption[]][]>;
+ updatingTokenId: Accessor<string | null>;
+ editScopesChanged: () => boolean;
+ onToggleEditScope: (scope: string) => void;
+ onCloseScopeEditor: () => void;
+ onSaveEditedScopes: () => void;
+ onCancelRevoke: () => void;
+ onRevoke: (token: APITokenRecord) => void;
+}
+
+export const APITokenManagerDialogs: Component<APITokenManagerDialogsProps> = (props) => (
+ <>
+ <Show when={props.tokenToEdit()}>
+ <Dialog
+ isOpen={true}
+ onClose={props.onCloseScopeEditor}
+ panelClass="max-w-2xl"
+ ariaLabel="Edit API token scopes"
+ >
+ <div class="w-full space-y-5 p-6">
+ <div>
+ <h3 class="text-lg font-semibold text-base-content">Edit token scopes</h3>
+ <p class="mt-1 text-sm text-muted">
+ Changes to{' '}
+ <span class="font-medium text-base-content">
+ {props.tokenToEdit()!.name || props.tokenToEdit()!.id}
+ </span>{' '}
+ take effect on its next request. The token value and expiry do not change.
+ </p>
+ </div>
+
+ <label class="flex cursor-pointer items-start gap-3 rounded-md border border-amber-300 bg-amber-50 p-3 text-sm dark:border-amber-700 dark:bg-amber-900">
+ <input
+ type="checkbox"
+ checked={props.editScopes().includes('*')}
+ onChange={() => props.onToggleEditScope('*')}
+ disabled={props.updatingTokenId() !== null}
+ class="mt-0.5 h-4 w-4 rounded border-border text-amber-600 focus:ring-amber-500"
+ />
+ <span>
+ <span class="block font-semibold text-amber-900 dark:text-amber-100">
+ Full access
+ </span>
+ <span class="text-amber-800 dark:text-amber-200">
+ Legacy wildcard access to every API capability.
+ </span>
+ </span>
+ </label>
+
+ <div class="max-h-[50vh] space-y-4 overflow-y-auto pr-1">
+ <For each={props.scopeGroups()}>
+ {([group, options]) => (
+ <fieldset class="space-y-2">
+ <legend class="text-[0.7rem] font-semibold uppercase tracking-wide text-muted">
+ {group}
+ </legend>
+ <div class="grid gap-2 sm:grid-cols-2">
+ <For each={options}>
+ {(option) => (
+ <label class="flex cursor-pointer items-start gap-3 rounded-md border border-border p-3 text-sm transition hover:bg-surface-hover">
+ <input
+ type="checkbox"
+ checked={props.editScopes().includes(option.value)}
+ onChange={() => props.onToggleEditScope(option.value)}
+ disabled={props.updatingTokenId() !== null}
+ class="mt-0.5 h-4 w-4 rounded border-border text-blue-600 focus:ring-blue-500"
+ />
+ <span>
+ <span class="block font-medium text-base-content">{option.label}</span>
+ <span class="text-xs text-muted">{option.description}</span>
+ </span>
+ </label>
+ )}
+ </For>
+ </div>
+ </fieldset>
+ )}
+ </For>
+ </div>
+
+ <Show when={props.editScopes().length === 0}>
+ <p class="text-sm text-red-600 dark:text-red-300">
+ Select at least one scope before saving.
+ </p>
+ </Show>
+
+ <div class="flex justify-end gap-3 border-t border-border pt-4">
+ <button
+ type="button"
+ onClick={props.onCloseScopeEditor}
+ disabled={props.updatingTokenId() !== null}
+ class="rounded-md border border-border px-4 py-2 text-sm font-medium text-base-content hover:bg-surface-hover disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ onClick={props.onSaveEditedScopes}
+ disabled={
+ props.editScopes().length === 0 ||
+ !props.editScopesChanged() ||
+ props.updatingTokenId() !== null
+ }
+ class="rounded-md bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {props.updatingTokenId() !== null ? 'Saving…' : 'Save scopes'}
+ </button>
+ </div>
+ </div>
+ </Dialog>
+ </Show>
+
+ <Show when={props.tokenToRevoke()}>
+ <Dialog
+ isOpen={true}
+ onClose={props.onCancelRevoke}
+ panelClass="max-w-md"
+ ariaLabel="Revoke API token"
+ >
+ <div class="w-full p-6">
+ <h3 class="text-lg font-semibold text-base-content mb-2">Revoke API token?</h3>
+ <p class="text-sm text-muted mb-4">
+ This permanently revokes{' '}
+ <span class="font-medium text-base-content">
+ {props.tokenToRevoke()!.name || props.tokenToRevoke()!.id}
+ </span>
+ . Any agents, scripts, or integrations using it will stop authenticating until you issue
+ and configure a replacement token.
+ </p>
+ <div class="flex justify-end gap-3">
+ <button
+ type="button"
+ onClick={props.onCancelRevoke}
+ class="px-4 py-2 text-sm font-medium text-base-content border border-border rounded-md hover:bg-surface-hover"
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ const token = props.tokenToRevoke();
+ if (token) props.onRevoke(token);
+ }}
+ class="px-4 py-2 text-sm font-medium bg-red-600 text-white rounded-md hover:bg-red-700"
+ >
+ Revoke token
+ </button>
+ </div>
+ </div>
+ </Dialog>
+ </Show>
+ </>
+);
diff --git a/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx b/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
index 6905a182ea..10afb0f24d 100644
--- a/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
@@ -18,6 +18,7 @@ import {
import { API_TOKEN_CREATE_ANCHOR, PULSE_MCP_TOKEN_SETUP_PATH } from '@/routing/resourceLinks';
import apiAccessPanelSource from '../APIAccessPanel.tsx?raw';
import apiTokenManagerSource from '../APITokenManager.tsx?raw';
+import apiTokenManagerDialogsSource from '../APITokenManagerDialogs.tsx?raw';
import { APIAccessPanel } from '../APIAccessPanel';
import { APITokenManager } from '../APITokenManager';
@@ -159,6 +160,10 @@ describe('APITokenManager security surface', () => {
expect(apiAccessPanelSource).not.toContain('AgentIntegrationsPanel');
expect(apiAccessPanelSource).not.toContain('isExternalAgentSetupHash');
expect(apiAccessPanelSource).not.toContain('api-access-external-agent-section');
+ expect(apiTokenManagerSource).toContain("import('./APITokenManagerDialogs')");
+ expect(apiTokenManagerSource).not.toContain('<Dialog');
+ expect(apiTokenManagerDialogsSource).toContain('ariaLabel="Edit API token scopes"');
+ expect(apiTokenManagerDialogsSource).toContain('ariaLabel="Revoke API token"');
});
});
diff --git a/internal/monitoring/kubernetes_agents.go b/internal/monitoring/kubernetes_agents.go
index 0155c72000..827750f562 100644
--- a/internal/monitoring/kubernetes_agents.go
+++ b/internal/monitoring/kubernetes_agents.go
@@ -332,7 +332,7 @@ func (m *Monitor) ApplyKubernetesReport(report agentsk8s.Report, tokenRecord *co
m.state.UpsertKubernetesCluster(cluster)
m.state.SetConnectionHealth(kubernetesConnectionPrefix+identifier, true)
m.recordKubernetesPodMetrics(cluster, receivedAt)
- m.refreshUnifiedResourceStoreAfterAgentReport()
+ m.refreshUnifiedResourceStoreAfterAgentStateChange()
return cluster, nil
}
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 84877b8653..9ad3b26ae0 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -4835,11 +4835,12 @@ func (m *Monitor) updateResourceStore(state models.StateSnapshot) {
m.syncUnifiedResourceAlertsToState(store.GetAll())
}
-// refreshUnifiedResourceStoreAfterAgentReport makes accepted agent ingest
-// immediately visible to canonical ReadState consumers. WebSocket broadcasts
-// may also rebuild the store for their own hydrate path, but client presence
-// must never be the trigger that publishes agent-backed runtime truth.
-func (m *Monitor) refreshUnifiedResourceStoreAfterAgentReport() {
+// refreshUnifiedResourceStoreAfterAgentStateChange makes accepted agent
+// ingest and removal immediately visible to canonical ReadState consumers.
+// WebSocket broadcasts may also rebuild the store for their own hydrate path,
+// but client presence must never be the trigger that publishes agent-backed
+// runtime truth or retires removed inventory.
+func (m *Monitor) refreshUnifiedResourceStoreAfterAgentStateChange() {
if m == nil || m.state == nil {
return
}
diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.go
index 732eb1ada3..178dc67fe4 100644
--- a/internal/monitoring/monitor_agents.go
+++ b/internal/monitoring/monitor_agents.go
@@ -491,6 +491,7 @@ func (m *Monitor) RemoveHostAgent(hostID string) (models.Host, error) {
m.hostReportOrderMu.Lock()
delete(m.hostReportOrders, hostID)
m.hostReportOrderMu.Unlock()
+ m.refreshUnifiedResourceStoreAfterAgentStateChange()
return host, nil
}
@@ -1382,7 +1383,7 @@ func (m *Monitor) applyRejectedHostReportLiveness(
// clear an offline alert, or renew the accepted telemetry lease.
m.state.SetConnectionHealth(hostConnectionPrefix+host.ID, true)
m.persistHostContinuity(host, report, order)
- m.refreshUnifiedResourceStoreAfterAgentReport()
+ m.refreshUnifiedResourceStoreAfterAgentStateChange()
log.Debug().
Str("hostID", host.ID).
@@ -2183,7 +2184,7 @@ func (m *Monitor) ApplyDockerReport(report agentsdocker.Report, tokenRecord *con
Int("containers", len(containers)).
Msg("Docker host report processed")
- m.refreshUnifiedResourceStoreAfterAgentReport()
+ m.refreshUnifiedResourceStoreAfterAgentStateChange()
return host, nil
}
@@ -3123,7 +3124,7 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
// committed, because ownership is checked against that host ID.
m.ApplyProbeAvailabilityResults(host.ID, probeAvailabilityResultsFromReport(report.AvailabilityResults))
m.persistHostContinuity(host, report, reportOrder)
- m.refreshUnifiedResourceStoreAfterAgentReport()
+ m.refreshUnifiedResourceStoreAfterAgentStateChange()
return host, nil
}
@@ -4329,7 +4330,7 @@ func (m *Monitor) evaluateHostAgents(now time.Time) {
}
if resourceRefreshNeeded {
- m.refreshUnifiedResourceStoreAfterAgentReport()
+ m.refreshUnifiedResourceStoreAfterAgentStateChange()
}
}
diff --git a/internal/monitoring/monitor_host_agent_removal_lifecycle_test.go b/internal/monitoring/monitor_host_agent_removal_lifecycle_test.go
index 53e10a8605..9c26f0a125 100644
--- a/internal/monitoring/monitor_host_agent_removal_lifecycle_test.go
+++ b/internal/monitoring/monitor_host_agent_removal_lifecycle_test.go
@@ -10,6 +10,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
)
@@ -187,6 +188,39 @@ func TestHostAgentRemovalLifecycleRevokesDedicatedCredentialAndRetainsDenial(t *
}
}
+func TestHostAgentRemovalLifecycleRepublishesUnifiedReadState(t *testing.T) {
+ monitor := newHostRemovalLifecycleMonitor(t, t.TempDir())
+ adapter := unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(nil))
+ monitor.SetResourceStore(adapter)
+
+ now := time.Now().UTC()
+ report := hostRemovalLifecycleReport(
+ "state-convergence-machine",
+ "state-convergence-machine",
+ "state-convergence-agent",
+ "state-convergence.local",
+ "linux",
+ now,
+ )
+ host, err := monitor.ApplyHostReport(report, &config.APITokenRecord{
+ ID: "state-convergence-token",
+ CreatedAt: now.Add(-time.Hour),
+ })
+ if err != nil {
+ t.Fatalf("ApplyHostReport: %v", err)
+ }
+ if hosts := adapter.Hosts(); len(hosts) != 1 {
+ t.Fatalf("unified read state before removal = %+v, want one host", hosts)
+ }
+
+ if _, err := monitor.RemoveHostAgent(host.ID); err != nil {
+ t.Fatalf("RemoveHostAgent: %v", err)
+ }
+ if hosts := adapter.Hosts(); len(hosts) != 0 {
+ t.Fatalf("unified read state retained removed host: %+v", hosts)
+ }
+}
+
func TestHostAgentRemovalLifecycleSurvivesMonitorReconstruction(t *testing.T) {
dataPath := t.TempDir()
now := time.Now().UTC()
diff --git a/pkg/metrics/store.go b/pkg/metrics/store.go
index 6e31afc14f..7e544e5493 100644
--- a/pkg/metrics/store.go
+++ b/pkg/metrics/store.go
@@ -752,7 +752,10 @@ func (s *Store) WriteWithTier(resourceType, resourceID, metricType string, value
s.enqueueWrite(writeRequest{metrics: toWrite})
}
-// WriteBatchSync writes metrics directly to the database without buffering.
+// WriteBatchSync bypasses the in-memory sample buffer but still serializes the
+// batch through the ingestion worker. Platform pollers call this concurrently;
+// letting every caller open its own SQLite transaction exhausts the shared
+// reader pool while those transactions wait on the single WAL writer lock.
func (s *Store) WriteBatchSync(metrics []WriteMetric) {
if len(metrics) == 0 {
return
@@ -796,7 +799,7 @@ func (s *Store) WriteBatchSync(metrics []WriteMetric) {
return
}
- s.writeBatch(batch)
+ s.enqueueAndWait(writeRequest{metrics: batch})
}
func (s *Store) enqueueMaintenance(run func()) {
diff --git a/pkg/metrics/store_additional_test.go b/pkg/metrics/store_additional_test.go
index dc63c9a8bd..4c5c8f8709 100644
--- a/pkg/metrics/store_additional_test.go
+++ b/pkg/metrics/store_additional_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"os"
"path/filepath"
+ "strconv"
"strings"
"sync"
"syscall"
@@ -137,6 +138,90 @@ func TestStoreWriteBatchSync(t *testing.T) {
}
}
+func TestStoreWriteBatchSyncSerializesConcurrentPollers(t *testing.T) {
+ store, err := NewStore(DefaultConfig(t.TempDir()))
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ defer store.Close()
+ if err := store.WaitForMaintenance(10 * time.Second); err != nil {
+ t.Fatalf("WaitForMaintenance: %v", err)
+ }
+
+ // Hold SQLite's WAL writer lock while several platform pollers submit
+ // synchronous batches. Only the store's single ingestion worker should
+ // wait on a database connection; callers must queue before the pool instead
+ // of consuming every reader connection with competing write transactions.
+ blockingTx, err := store.db.Begin()
+ if err != nil {
+ t.Fatalf("begin blocking transaction: %v", err)
+ }
+ if _, err := blockingTx.Exec(`
+ INSERT INTO metrics (resource_type, resource_id, metric_type, value, timestamp, tier)
+ VALUES ('node', 'blocker', 'cpu', 1, ?, 'raw')
+ `, time.Now().UTC().Unix()); err != nil {
+ _ = blockingTx.Rollback()
+ t.Fatalf("lock WAL writer: %v", err)
+ }
+
+ const pollers = 8
+ start := make(chan struct{})
+ done := make(chan struct{}, pollers)
+ base := time.Now().UTC().Truncate(time.Second)
+ for i := 0; i < pollers; i++ {
+ i := i
+ go func() {
+ <-start
+ store.WriteBatchSync([]WriteMetric{{
+ ResourceType: "node",
+ ResourceID: "poller-" + strconv.Itoa(i),
+ MetricType: "cpu",
+ Value: float64(i),
+ Timestamp: base,
+ Tier: TierRaw,
+ }})
+ done <- struct{}{}
+ }()
+ }
+ close(start)
+
+ maxInUse := 0
+ observationDeadline := time.Now().Add(750 * time.Millisecond)
+ for time.Now().Before(observationDeadline) {
+ if inUse := store.db.DB.Stats().InUse; inUse > maxInUse {
+ maxInUse = inUse
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+
+ if err := blockingTx.Rollback(); err != nil {
+ t.Fatalf("release WAL writer: %v", err)
+ }
+ for i := 0; i < pollers; i++ {
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ t.Fatal("concurrent synchronous metrics writes did not drain")
+ }
+ }
+
+ if maxInUse > 2 {
+ t.Fatalf("concurrent writers consumed %d database connections, want at most blocker plus one ingestion worker", maxInUse)
+ }
+
+ var persisted int
+ if err := store.db.QueryRow(`
+ SELECT COUNT(*)
+ FROM metrics
+ WHERE resource_type = 'node' AND resource_id LIKE 'poller-%'
+ `).Scan(&persisted); err != nil {
+ t.Fatalf("count persisted poller metrics: %v", err)
+ }
+ if persisted != pollers {
+ t.Fatalf("persisted poller metrics = %d, want %d", persisted, pollers)
+ }
+}
+
func TestStoreWriteBatchUpsertsDuplicateRawMetric(t *testing.T) {
dir := t.TempDir()
cfg := DefaultConfig(dir)
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index 2a9215b80e..c6e3102053 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -4112,6 +4112,7 @@ class SubsystemLookupTest(unittest.TestCase):
match["verification_requirement"]["exact_files"],
[
"internal/monitoring/kubernetes_agents_test.go",
+ "internal/monitoring/monitor_host_agent_removal_lifecycle_test.go",
"internal/monitoring/monitor_host_agents_test.go",
"internal/monitoring/monitor_pbs_coverage_test.go",
"internal/monitoring/monitor_pmg_test.go",