Keep workload metadata within its mounted reader (#3704)

**Keep workload metadata within its mounted reader**

Stop reusing org-only browser metadata across credentials. Retain the
existing authenticated read and confirmed edits in each mounted
Workloads owner, reject late results after disposal, and remove legacy
scoped copies only after acknowledged local sign-out. Server metadata,
preferences and independent authority are unchanged.

**Format the workload metadata lifetime repair**

Apply the prepared offline toolchain's formatting to the
mounted-metadata repair and its registered tests. No runtime tokens or
behaviour change.

Contract-Neutral: Prettier formatting only; the preceding commit records
the mounted-metadata and sign-out cleanup contracts.

**Type the legacy metadata namespace collection explicitly**

The acknowledged-sign-out cleanup gathers arbitrary organisation keys
rather than only the literal base key. Keep that set typed as strings.

Contract-Neutral: TypeScript collection annotation only; no runtime,
API, grant or persistence contract change.

**Keep the cleanup-failure fetch fixture asynchronous**

The runtime mock has a Promise<Response> contract. Preserve it in the
new legacy metadata failure scenarios so the full frontend type check
can execute the regression proof.

**Record Workloads metadata lifetime browser verification**

Bind the final mounted-reader repair to its own parent and actual
production Workloads desktop/narrow consumers. Retain the earlier test
timeout and isolated setup timeout alongside the passing build, full
runtime-file and 67 browser controls; no overall all-suite pass or
original administrator recovery is claimed.

---
Fleet candidate `20261101T150033Z-web-product` from the `web-product`
lane. Reviewed tip `e3b8fa8c626d1f8c7fc7859aa3171c6052d7443e` on `main`.

[How Pulse handles
triage](https://github.com/rcourtman/Pulse/blob/main/docs/AI_TRANSPARENCY.md)
This commit is contained in:
pulse-triage[bot]
2026-11-01 16:15:58 +00:00
committed by GitHub
10 changed files with 391 additions and 297 deletions

View File

@@ -3966,8 +3966,19 @@ consumer with synthetic independent sessions and inspected pixels; it is not
live IdP or original administrator recovery. The proxy guide and shipped mirror
must describe the same sequence without claiming upstream revocation.
The current Workloads metadata owner also has organisation-scoped persistent
and module caches plus deferred persistence. This bounded redirect repair does
not establish their erasure or original administrator recovery. Session-binding
that existing owner is the next retained Web step; help must not describe
credential cleanup as erasing every copy of already-held monitoring data.
Workloads metadata now lives only in its mounted authenticated owner. Each
mount keeps the existing server read; no org-only disk or module cache is read,
written or scheduled for idle persistence. Disposal (including the app shell's
confirmed-sign-out gate) clears that owner's signal and excludes late reads and
edits. Organisation switches clear outgoing metadata before refreshing, and a
revision excludes old responses even after switching back to the same org.
Confirmed sign-out also removes the legacy flat key and every dot-prefixed org
metadata key, snapshotting names before removal and attempting each separately.
Enumeration/removal failures retain the existing explicit cleanup warning and
do not prevent shell teardown. Unrelated local preferences, server metadata,
API-token authority and independent sessions are unchanged. A pending or denied
fresh metadata read cannot reuse another credential's browser copy; this can
withhold saved links until the read succeeds. It is not erasure of every copy
already held elsewhere, live IdP or original administrator recovery. Registered
metadata-lifetime, Workloads consumer and runtime tests cover the boundaries;
desktop/narrow browser proof must exercise the actual platform consumer.

View File

@@ -1596,7 +1596,7 @@ change may globally weaken the Task 03 lifecycle-state idempotency invariant.
instead of recomputing a percent from a zero used value, and per-machine
max-disk derivations must skip sentinel rows rather than surface them as
0% or negative percents.
13. Extend workload guest metadata cache persistence, metadata refresh, org-scope switching, and optimistic custom-URL updates through `frontend-modern/src/components/Workloads/useWorkloadGuestMetadataState.ts` rather than rebuilding workload-local storage caches, event listeners, or guest metadata API wiring inside `frontend-modern/src/components/Workloads/useWorkloadsState.ts`
13. Extend mounted workload guest metadata lifetime, metadata refresh, org-scope switching, and optimistic custom-URL updates through `frontend-modern/src/components/Workloads/useWorkloadGuestMetadataState.ts` rather than rebuilding workload-local storage caches, event listeners, or guest metadata API wiring inside `frontend-modern/src/components/Workloads/useWorkloadsState.ts`
A changed set of native metadata keys refreshes that cache after accepted
inventory publication. Metric-only updates do not refetch it. Superseded
responses cannot overwrite a newer refresh, confirmed edit or tenant scope.
@@ -3071,7 +3071,7 @@ and grouped/windowed table math, while
owns grouped workload viewport synchronization and the scroll/resize listener
lifecycle, while
`frontend-modern/src/components/Workloads/useWorkloadGuestMetadataState.ts`
owns guest metadata cache persistence, optimistic custom-URL updates,
owns mounted guest metadata, optimistic custom-URL updates,
org-scope switching, and metadata refresh, and
`frontend-modern/src/components/Workloads/useWorkloadRouteState.ts`
owns workload-route synchronization, deep-link normalization, and route-scoped
@@ -4685,8 +4685,19 @@ consumer with synthetic independent sessions and inspected pixels; it is not
live IdP or original administrator recovery. The proxy guide and shipped mirror
must describe the same sequence without claiming upstream revocation.
The current Workloads metadata owner also has organisation-scoped persistent
and module caches plus deferred persistence. This bounded redirect repair does
not establish their erasure or original administrator recovery. Session-binding
that existing owner is the next retained Web step; help must not describe
credential cleanup as erasing every copy of already-held monitoring data.
Workloads metadata now lives only in its mounted authenticated owner. Each
mount keeps the existing server read; no org-only disk or module cache is read,
written or scheduled for idle persistence. Disposal (including the app shell's
confirmed-sign-out gate) clears that owner's signal and excludes late reads and
edits. Organisation switches clear outgoing metadata before refreshing, and a
revision excludes old responses even after switching back to the same org.
Confirmed sign-out also removes the legacy flat key and every dot-prefixed org
metadata key, snapshotting names before removal and attempting each separately.
Enumeration/removal failures retain the existing explicit cleanup warning and
do not prevent shell teardown. Unrelated local preferences, server metadata,
API-token authority and independent sessions are unchanged. A pending or denied
fresh metadata read cannot reuse another credential's browser copy; this can
withhold saved links until the read succeeds. It is not erasure of every copy
already held elsewhere, live IdP or original administrator recovery. Registered
metadata-lifetime, Workloads consumer and runtime tests cover the boundaries;
desktop/narrow browser proof must exercise the actual platform consumer.

View File

@@ -0,0 +1,55 @@
{
"version": 1,
"base_sha": "03aac234347a5cd26bb88b7063bc22e8f712730a",
"verified_at": "2026-11-01T15:42:41.500078Z",
"result": "passed",
"changed_paths": [
"frontend-modern/src/components/Workloads/useWorkloadGuestMetadataState.ts",
"frontend-modern/src/useAppRuntimeState.ts"
],
"content_sha256": {
"frontend-modern/src/components/Workloads/useWorkloadGuestMetadataState.ts": "d788491136efa758ff1b196d911788a29657fe3473be07b241f1e3b0078ca41c",
"frontend-modern/src/useAppRuntimeState.ts": "4c18ee30d8a726bd443136f6ac0ae1361419db8c91db371a30ecb9a0462fb93b"
},
"routes": [
"/proxmox/overview",
"/proxmox/overview#metadata-withdrawn"
],
"viewports": [
{
"width": 1280,
"height": 900
},
{
"width": 390,
"height": 844
}
],
"states": [
"Actual production App, Proxmox Workloads owner, saved-link editor and Login, using their real API client and CSS with synthetic loopback GET/PUT/logout/session fixtures. No live IdP, installed administrator/workload recovery or all-copy-erasure claim.",
"Six browser contexts: desktop/light Chromium 141.0.7390.37 and dark touch 390px WebKit 26.0, each covering acknowledged cleanup, blocked scoped-key cleanup and denied fresh metadata. Playwright 1.56.1 matches the integration lock. All 67 semantic controls pass; all ten captures were opened with native view_image at original detail.",
"Prepared offline source o57bwazg on this parent passes full types, changed-file format/eslint and 242/243 tests; the unchanged retained-state bootstrap test times out at its 5s test deadline. No full-suite pass is claimed. Source 9y23sp8b passes production/embed build, unchanged bundle/preload/integrity controls and the complete runtime file (65/65), but its isolated cold beforeEach times out at 10s; overall exit remains 1. Exact raw outputs, failures and stopped guests remain retained.",
"All 2559 build inputs match this committed source. Browser client exits 0 with no page errors; four console 403 messages are the explicit denied-read controls, not hidden or claimed absent."
],
"interactions": [
"Pending and forbidden authenticated metadata reads cannot render an old flat/org-keyed disk URL. The actual editor receives the completed permitted value; one real metadata PUT per success case updates the fixture, and reopening the editor shows the confirmed saved value with no unsaved changes.",
"Acknowledged sign-out disposes the Workloads consumer even when the document stays at its same-path fragment or a scoped cache deletion throws. Releasing obsolete metadata reads and draining held idle callbacks cannot recreate cleared storage; no new metadata disk writes occur.",
"Legacy flat and all dot-prefixed org keys are removed on success, only the synthetically blocked key remains on partial cleanup, unrelated preferences survive, and server metadata is retained. The partial cleanup warning remains legible at both widths. Late owner/ABA-org/independent-owner cases also have registered component tests; they are not a claim of original cross-user exposure."
],
"evidence": {
"browser_checks": 67,
"native_pixel_inspections": 10,
"source_proofs": [
"source-o57bwazg",
"source-9y23sp8b",
"source-uive2lqt"
],
"lane_records": [
"RECEIPTS.md",
"SOURCE.tar.xz",
"BROWSER.tar.xz",
"PIXELS.json",
"BUILD-COMPOSITION.json"
]
}
}

View File

@@ -665,6 +665,17 @@ describe('App architecture', () => {
expect(preparation).toContain('process.env.PULSE_E2E_OFFLINE_ACTIVATION_KEY');
});
it('owns mounted platform pages inside the confirmed-sign-out authentication gate', () => {
// This gate disposes Workloads metadata without relying on provider
// navigation. Runtime tests exercise successful and partial cleanup;
// the metadata lifetime tests exercise late results after disposal.
expect(appSource).toContain('when={!runtime.needsAuth()}');
expect(appRuntimeStateSource).toContain('setNeedsAuth(true)');
for (const source of platformSurfaceSources) {
expect(source).not.toContain('pulseGuestMetadata');
}
});
it('keeps authenticated chrome in AppLayout and hosted bootstrap in useAppRuntimeState', () => {
expect(appLayoutSource).toContain('export function AppLayout(props: AppLayoutProps)');
expect(appLayoutSource).toContain(

View File

@@ -780,6 +780,10 @@ describe('useAppRuntimeState', () => {
for (const key of ['auth', 'guest_metadata', 'docker_metadata', 'docker_metadata_hosts']) {
localStorage.setItem(key, 'synthetic-cache');
}
const scopedMetadataKeys = ['guest_metadata.default', 'guest_metadata.ops%2Feu'];
for (const key of scopedMetadataKeys) localStorage.setItem(key, 'synthetic-scoped-cache');
localStorage.setItem('guest_metadataTheme', 'keep-near-prefix');
localStorage.setItem('workloadsHiddenColumns', '["tags"]');
sessionStorage.setItem('auth', 'synthetic-browser-token');
sessionStorage.setItem('pulse_auth_user', 'synthetic-user');
let finish!: (value: Response) => void;
@@ -797,6 +801,8 @@ describe('useAppRuntimeState', () => {
expect(clearAuthMock).not.toHaveBeenCalled();
expect(shutdownGlobalWebSocketStoreMock).not.toHaveBeenCalled();
expect(localStorage.getItem('auth')).toBe('synthetic-cache');
for (const key of scopedMetadataKeys)
expect(localStorage.getItem(key)).toBe('synthetic-scoped-cache');
expect(window.location.hash).toBe('');
await hookState.handleLogout();
expect(apiFetchMock.mock.calls.filter(([url]) => url === '/api/logout')).toHaveLength(1);
@@ -817,6 +823,9 @@ describe('useAppRuntimeState', () => {
for (const key of ['auth', 'guest_metadata', 'docker_metadata', 'docker_metadata_hosts']) {
expect(localStorage.getItem(key)).toBeNull();
}
for (const key of scopedMetadataKeys) expect(localStorage.getItem(key)).toBeNull();
expect(localStorage.getItem('guest_metadataTheme')).toBe('keep-near-prefix');
expect(localStorage.getItem('workloadsHiddenColumns')).toBe('["tags"]');
expect(sessionStorage.getItem('auth')).toBeNull();
expect(sessionStorage.getItem('pulse_auth_user')).toBeNull();
expect(sessionStorage.getItem('pulse_demo_auto_login')).toBe('suppressed');
@@ -949,6 +958,47 @@ describe('useAppRuntimeState', () => {
);
});
it.each(['scoped-key', 'enumeration'])(
'logout reports legacy metadata %s cleanup failure but still tears down the authenticated shell',
async (failure) => {
const { hookState } = await mountLogout();
localStorage.setItem('guest_metadata.default', 'synthetic-cache');
localStorage.setItem('guest_metadata.other', 'synthetic-cache');
const remove = Storage.prototype.removeItem;
const spy =
failure === 'scoped-key'
? vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(function (
this: Storage,
key: string,
) {
if (key === 'guest_metadata.default') throw new Error('Synthetic blocked cache');
remove.call(this, key);
})
: vi.spyOn(Storage.prototype, 'key').mockImplementation(() => {
throw new Error('Synthetic blocked enumeration');
});
const fallback = apiFetchMock.getMockImplementation()!;
apiFetchMock.mockImplementation(async (url: string) =>
url === '/api/logout' ? new Response('{"success":true}') : fallback(url),
);
await hookState.handleLogout();
spy.mockRestore();
if (failure === 'scoped-key') {
expect(localStorage.getItem('guest_metadata.default')).toBe('synthetic-cache');
expect(localStorage.getItem('guest_metadata.other')).toBeNull();
}
expect(shutdownGlobalWebSocketStoreMock).toHaveBeenCalledOnce();
expect(hookState.enhancedStore()).toBeNull();
expect(hookState.needsAuth()).toBe(true);
expect(window.location.hash).toBe('');
expect(showToastMock).toHaveBeenCalledWith(
'error',
'Browser cleanup incomplete',
expect.stringContaining('could not finish browser cleanup'),
);
},
);
it.each(['auth', 'socket'])('logout keeps %s cleanup failure explicit', async (failure) => {
const { hookState } = await mountLogout();
sessionStorage.setItem('auth', 'synthetic-browser-credential');

View File

@@ -1,8 +1,10 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
import { fireEvent, render, renderHook, screen, waitFor } from '@solidjs/testing-library';
import { createSignal, onCleanup, onMount } from 'solid-js';
import { Route, Router } from '@solidjs/router';
import type { Resource } from '@/types/resource';
import { GuestMetadataAPI } from '@/api/guestMetadata';
import type { GuestMetadata } from '@/api/guestMetadata';
import { syncSessionSettingsCapabilities } from '@/stores/sessionSettingsCapabilities';
import { WorkloadsSurface, type WorkloadsSurfaceProps } from '../WorkloadsSurface';
import { useWorkloadsState, type WorkloadsStateOptions } from '../useWorkloadsState';
@@ -498,6 +500,26 @@ describe('Workloads performance contract', () => {
wsReconnecting = false;
});
it('cannot carry a disposed platform metadata read into its replacement workload state', async () => {
const read = vi.mocked(GuestMetadataAPI.getAllMetadata);
let finish!: (metadata: Record<string, GuestMetadata>) => void;
read.mockReturnValueOnce(
new Promise((resolve) => {
finish = resolve;
}),
);
const first = renderHook(() => useWorkloadsState({}));
first.result.handleCustomUrlUpdate('guest', 'https://confirmed.example');
first.cleanup();
read.mockReturnValueOnce(new Promise(() => {}));
const replacement = renderHook(() => useWorkloadsState({}));
finish({ guest: { id: 'guest', customUrl: 'https://obsolete.example' } });
await flushEffects();
expect(first.result.guestMetadata()).toEqual({});
expect(replacement.result.guestMetadata()).toEqual({});
replacement.cleanup();
});
describe('Fixture profile validation', () => {
for (const [profile, count] of Object.entries(PROFILES)) {
it(`builds profile ${profile} with stable size and type distribution`, () => {

View File

@@ -13,9 +13,8 @@ import { useWorkloadGuestMetadataState } from '../useWorkloadGuestMetadataState'
// metadata-changed event subscription (no/nil metadataId, missing kind or
// customUrl, docker kind), refresh (rejection + null payload), the org_switched
// subscription body, onMount teardown, the handleCustomUrlUpdate clearing/trim
// arms, and the localStorage persist queue. Each test is isolated by giving the
// hook a unique org scope (unique storage key) so the module-level metadata
// cache never leaks state across tests.
// arms. Saved metadata now comes only from each owner's authenticated read;
// the separate lifetime suite covers disposal and legacy-cache non-reuse.
type OrgSwitchedHandler = (orgID?: string) => void;
@@ -104,30 +103,26 @@ describe('useWorkloadGuestMetadataState (branch coverage 0722am)', () => {
});
});
it('keeps a non-stable entry (dropping only customUrl) when it carries additional metadata', () => {
it('keeps a non-stable entry (dropping only customUrl) when it carries additional metadata', async () => {
mocks.orgID = 'keep-extra';
window.localStorage.setItem(
keyFor('keep-extra'),
JSON.stringify({
'guest:keep': {
id: 'guest:keep',
customUrl: 'https://k.example',
description: 'desc',
tags: ['t'],
},
}),
);
createRoot((dispose) => {
const state = useWorkloadGuestMetadataState();
state.handleCustomUrlUpdate('guest:keep', '');
expect(state.guestMetadata()['guest:keep']).toEqual({
mocks.getAllMetadata.mockResolvedValue({
'guest:keep': {
id: 'guest:keep',
customUrl: 'https://k.example',
description: 'desc',
tags: ['t'],
});
expect(state.guestMetadata()['guest:keep']?.customUrl).toBeUndefined();
dispose();
},
});
const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());
await flush();
result.handleCustomUrlUpdate('guest:keep', '');
expect(result.guestMetadata()['guest:keep']).toEqual({
id: 'guest:keep',
description: 'desc',
tags: ['t'],
});
expect(result.guestMetadata()['guest:keep']?.customUrl).toBeUndefined();
cleanup();
});
it('no-ops when clearing a non-stable id that has no entry at all', () => {
@@ -260,7 +255,7 @@ describe('useWorkloadGuestMetadataState (branch coverage 0722am)', () => {
);
mocks.getAllMetadata.mockResolvedValue(null);
const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());
expect(result.guestMetadata()['guest:seed']?.customUrl).toBe('https://s.example');
expect(result.guestMetadata()).toEqual({});
await flush();
expect(result.guestMetadata()['guest:seed']).toBeUndefined();
expect(result.guestMetadata()).toEqual({});
@@ -281,7 +276,7 @@ describe('useWorkloadGuestMetadataState (branch coverage 0722am)', () => {
cleanup();
});
it('re-reads the cache under the new org scope on org_switched', async () => {
it('reads metadata with the new org scope without reusing legacy disk data', async () => {
mocks.orgID = 'scope-default';
mocks.getAllMetadata.mockRejectedValue(new Error('no api'));
window.localStorage.setItem(
@@ -293,9 +288,15 @@ describe('useWorkloadGuestMetadataState (branch coverage 0722am)', () => {
const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());
await flush();
expect(result.guestMetadata()['guest:target']).toBeUndefined();
mocks.getAllMetadata.mockResolvedValue({
'guest:target': { id: 'guest:target', customUrl: 'https://authorised.example' },
});
mocks.orgSwitchedHandler.current?.('org-target');
expect(result.guestMetadata()).toEqual({});
await vi.waitFor(() => {
expect(result.guestMetadata()['guest:target']?.customUrl).toBe('https://t.example');
expect(result.guestMetadata()['guest:target']?.customUrl).toBe(
'https://authorised.example',
);
});
cleanup();
});
@@ -322,40 +323,4 @@ describe('useWorkloadGuestMetadataState (branch coverage 0722am)', () => {
expect(mocks.unsubscribeOrgSwitched).toHaveBeenCalledTimes(1);
});
});
describe('localStorage persist queue (no requestIdleCallback -> setTimeout fallback)', () => {
it('persists queued metadata to localStorage via the setTimeout fallback', () => {
vi.stubGlobal('requestIdleCallback', undefined);
vi.stubGlobal('cancelIdleCallback', undefined);
vi.useFakeTimers();
mocks.orgID = 'persist-ok';
mocks.getAllMetadata.mockReturnValue(new Promise(() => {}));
const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());
result.handleCustomUrlUpdate('guest:persist', 'https://p.example');
vi.advanceTimersByTime(1);
const raw = window.localStorage.getItem(keyFor('persist-ok'));
expect(raw).not.toBeNull();
expect(raw).toContain('guest:persist');
expect(raw).toContain('https://p.example');
cleanup();
});
it('swallows a localStorage.setItem failure during persist without throwing', () => {
vi.stubGlobal('requestIdleCallback', undefined);
vi.stubGlobal('cancelIdleCallback', undefined);
vi.useFakeTimers();
mocks.orgID = 'persist-err';
mocks.getAllMetadata.mockReturnValue(new Promise(() => {}));
const setItemSpy = vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {
throw new Error('quota exceeded');
});
const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());
expect(() => {
result.handleCustomUrlUpdate('guest:persist-err', 'https://pe.example');
vi.advanceTimersByTime(1);
}).not.toThrow();
setItemSpy.mockRestore();
cleanup();
});
});
});

View File

@@ -0,0 +1,156 @@
import { createSignal } from 'solid-js';
import { renderHook } from '@solidjs/testing-library';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { GuestMetadata } from '@/api/guestMetadata';
import { eventBus } from '@/stores/events';
import { RESOURCE_METADATA_CHANGED_EVENT } from '@/utils/resourceMetadataEvents';
import { useWorkloadGuestMetadataState } from '../useWorkloadGuestMetadataState';
const mocks = vi.hoisted(() => ({ org: 'default', read: vi.fn() }));
vi.mock('@/api/guestMetadata', () => ({
GuestMetadataAPI: { getAllMetadata: () => mocks.read() },
}));
vi.mock('@/utils/apiClient', () => ({ getOrgID: () => mocks.org }));
type Metadata = Record<string, GuestMetadata>;
const record = (url: string): Metadata => ({ guest: { id: 'guest', customUrl: url } });
const deferred = () => {
let resolve!: (value: Metadata) => void;
const promise = new Promise<Metadata>((finish) => {
resolve = finish;
});
return { promise, resolve };
};
describe('Workloads metadata owner lifetime', () => {
beforeEach(() => {
localStorage.clear();
mocks.org = 'default';
mocks.read.mockReset().mockResolvedValue({});
});
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
vi.useRealTimers();
});
it.each(['resolve', 'deny'])(
"does not expose a previous credential's disk data while the new read will %s",
async (result) => {
localStorage.setItem('pulseGuestMetadata', JSON.stringify(record('https://legacy.example')));
localStorage.setItem(
'pulseGuestMetadata.default',
JSON.stringify(record('https://private.example')),
);
const pending = deferred();
mocks.read.mockImplementation(() =>
result === 'deny' ? Promise.reject(new Error('Forbidden')) : pending.promise,
);
const { result: state, cleanup } = renderHook(() => useWorkloadGuestMetadataState());
expect(state.guestMetadata()).toEqual({});
await Promise.resolve();
expect(state.guestMetadata()).toEqual({});
if (result === 'resolve') {
pending.resolve(record('https://permitted.example'));
await Promise.resolve();
expect(state.guestMetadata()).toEqual(record('https://permitted.example'));
}
cleanup();
},
);
it.each(['idle', 'timeout'])(
'never queues a %s write that can restore removed metadata',
async (scheduler) => {
vi.useFakeTimers();
const idle = vi.fn();
vi.stubGlobal('requestIdleCallback', scheduler === 'idle' ? idle : undefined);
const writes = vi.spyOn(Storage.prototype, 'setItem');
const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());
await Promise.resolve();
result.handleCustomUrlUpdate('guest', 'https://confirmed.example');
expect(result.guestMetadata()).toEqual(record('https://confirmed.example'));
cleanup();
vi.runAllTimers();
expect(idle).not.toHaveBeenCalled();
expect(writes).not.toHaveBeenCalled();
expect(localStorage.length).toBe(0);
},
);
it('rejects a disposed read and callback without seeding the next owner in the same org', async () => {
const old = deferred();
const current = deferred();
mocks.read.mockReturnValueOnce(old.promise).mockReturnValueOnce(current.promise);
const first = renderHook(() => useWorkloadGuestMetadataState());
first.result.handleCustomUrlUpdate('guest', 'https://confirmed.example');
first.cleanup();
const second = renderHook(() => useWorkloadGuestMetadataState());
expect(second.result.guestMetadata()).toEqual({});
old.resolve(record('https://obsolete.example'));
first.result.handleCustomUrlUpdate('guest', 'https://late-edit.example');
await Promise.resolve();
expect(first.result.guestMetadata()).toEqual({});
expect(second.result.guestMetadata()).toEqual({});
current.resolve(record('https://current.example'));
await Promise.resolve();
expect(second.result.guestMetadata()).toEqual(record('https://current.example'));
second.cleanup();
});
it('does not reuse even a completed read in a new owner, or disturb an independent owner', async () => {
mocks.read
.mockResolvedValueOnce(record('https://first.example'))
.mockResolvedValueOnce(record('https://independent.example'))
.mockReturnValueOnce(new Promise(() => {}));
const first = renderHook(() => useWorkloadGuestMetadataState());
const independent = renderHook(() => useWorkloadGuestMetadataState());
await Promise.resolve();
first.cleanup();
const replacement = renderHook(() => useWorkloadGuestMetadataState());
expect(replacement.result.guestMetadata()).toEqual({});
expect(independent.result.guestMetadata()).toEqual(record('https://independent.example'));
independent.cleanup();
replacement.cleanup();
});
it('clears outgoing metadata and rejects an old A read after an A → B → A switch', async () => {
const oldA = deferred();
const b = deferred();
const newA = deferred();
mocks.read
.mockReturnValueOnce(oldA.promise)
.mockReturnValueOnce(b.promise)
.mockReturnValueOnce(newA.promise);
const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());
result.handleCustomUrlUpdate('guest', 'https://confirmed.example');
eventBus.emit('org_switched', 'b');
expect(result.guestMetadata()).toEqual({});
eventBus.emit('org_switched', 'default');
oldA.resolve(record('https://old-a.example'));
b.resolve(record('https://b.example'));
await Promise.resolve();
expect(result.guestMetadata()).toEqual({});
newA.resolve(record('https://new-a.example'));
await Promise.resolve();
expect(result.guestMetadata()).toEqual(record('https://new-a.example'));
cleanup();
});
it('cannot refresh or accept metadata events after disposal', async () => {
const [ids, setIds] = createSignal<ReadonlySet<string>>(new Set(['guest']));
const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState(ids));
await Promise.resolve();
cleanup();
mocks.read.mockClear();
setIds(new Set(['moved-guest']));
eventBus.emit('org_switched', 'another');
window.dispatchEvent(
new CustomEvent(RESOURCE_METADATA_CHANGED_EVENT, {
detail: { metadataId: 'guest', customUrl: 'https://late.example' },
}),
);
expect(mocks.read).not.toHaveBeenCalled();
expect(result.guestMetadata()).toEqual({});
});
});

View File

@@ -1,17 +1,8 @@
import {
createEffect,
createMemo,
createSignal,
on,
onCleanup,
onMount,
type Accessor,
} from 'solid-js';
import { createEffect, createSignal, on, onCleanup, onMount, type Accessor } from 'solid-js';
import { GuestMetadataAPI } from '@/api/guestMetadata';
import type { GuestMetadata } from '@/api/guestMetadata';
import { getOrgID } from '@/utils/apiClient';
import { logger } from '@/utils/logger';
import { STORAGE_KEYS } from '@/utils/localStorage';
import { normalizeOrgScope } from '@/utils/orgScope';
import {
RESOURCE_METADATA_CHANGED_EVENT,
@@ -20,225 +11,39 @@ import {
import { eventBus } from '@/stores/events';
type GuestMetadataRecord = Record<string, GuestMetadata>;
type IdleCallbackHandle = number;
type IdleCallback = (deadline?: { didTimeout: boolean; timeRemaining: () => number }) => void;
type IdleCapableWindow = Window & {
requestIdleCallback?: (
callback: IdleCallback,
options?: { timeout: number },
) => IdleCallbackHandle;
cancelIdleCallback?: (handle: IdleCallbackHandle) => void;
};
let cachedGuestMetadata: GuestMetadataRecord | null = null;
let cachedGuestMetadataStorageKey: string | null = null;
let lastPersistedGuestMetadataJSON: string | null = null;
let lastPersistedGuestMetadataStorageKey: string | null = null;
let pendingPersistMetadata: GuestMetadataRecord | null = null;
let pendingPersistStorageKey: string | null = null;
let persistHandle: number | null = null;
let persistHandleType: 'idle' | 'timeout' | null = null;
const instrumentationEnabled = import.meta.env.DEV && typeof performance !== 'undefined';
const guestMetadataStorageKeyForOrg = (orgScope: string): string =>
`${STORAGE_KEYS.GUEST_METADATA}.${encodeURIComponent(orgScope)}`;
// Saved metadata belongs to the server. Keep only this mounted owner's copy:
// an org-only disk/module cache can outlive the credential that read it, and
// delayed persistence can recreate it after sign-out removed it.
const isStableAppContainerMetadataId = (guestId: string): boolean =>
guestId.trim().startsWith('app-container:') && guestId.includes(':name:');
const readGuestMetadataCache = (storageKey: string): GuestMetadataRecord => {
if (cachedGuestMetadata && cachedGuestMetadataStorageKey === storageKey) {
return cachedGuestMetadata;
}
if (typeof window === 'undefined') {
cachedGuestMetadata = {};
cachedGuestMetadataStorageKey = storageKey;
return cachedGuestMetadata;
}
try {
const raw = window.localStorage.getItem(storageKey);
if (!raw) {
cachedGuestMetadata = {};
cachedGuestMetadataStorageKey = storageKey;
lastPersistedGuestMetadataJSON = null;
lastPersistedGuestMetadataStorageKey = storageKey;
return cachedGuestMetadata;
}
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === 'object') {
cachedGuestMetadata = parsed as GuestMetadataRecord;
cachedGuestMetadataStorageKey = storageKey;
lastPersistedGuestMetadataJSON = raw;
lastPersistedGuestMetadataStorageKey = storageKey;
return cachedGuestMetadata;
}
} catch (error) {
logger.warn('Failed to parse cached guest metadata', error);
}
cachedGuestMetadata = {};
cachedGuestMetadataStorageKey = storageKey;
lastPersistedGuestMetadataJSON = null;
lastPersistedGuestMetadataStorageKey = storageKey;
return cachedGuestMetadata;
};
const clearPendingPersistHandle = (idleWindow: IdleCapableWindow) => {
if (persistHandle === null || persistHandleType === null) {
return;
}
if (persistHandleType === 'idle' && idleWindow.cancelIdleCallback) {
idleWindow.cancelIdleCallback(persistHandle);
} else if (persistHandleType === 'timeout') {
window.clearTimeout(persistHandle);
}
persistHandle = null;
persistHandleType = null;
};
const runGuestMetadataPersist = () => {
if (typeof window === 'undefined' || !pendingPersistMetadata || !pendingPersistStorageKey) {
pendingPersistMetadata = null;
pendingPersistStorageKey = null;
return;
}
const metadata = pendingPersistMetadata;
const storageKey = pendingPersistStorageKey;
pendingPersistMetadata = null;
pendingPersistStorageKey = null;
const markBase = instrumentationEnabled ? `guest-metadata:persist:${Date.now()}` : null;
if (markBase) {
performance.mark(`${markBase}:start`);
}
let serialized: string;
try {
serialized = JSON.stringify(metadata);
} catch (error) {
if (markBase) {
performance.mark(`${markBase}:end`);
performance.measure(markBase, `${markBase}:start`, `${markBase}:end`);
performance.clearMarks(`${markBase}:start`);
performance.clearMarks(`${markBase}:end`);
performance.clearMeasures(markBase);
}
logger.warn('Failed to serialize guest metadata cache', error);
return;
}
if (
serialized === lastPersistedGuestMetadataJSON &&
storageKey === lastPersistedGuestMetadataStorageKey
) {
if (markBase) {
performance.mark(`${markBase}:end`);
performance.measure(markBase, `${markBase}:start`, `${markBase}:end`);
const entries = performance.getEntriesByName(markBase);
const entry = entries[entries.length - 1];
if (entry) {
logger.debug('[guestMetadataCache] skipped persist (unchanged)', {
durationMs: entry.duration,
});
}
performance.clearMarks(`${markBase}:start`);
performance.clearMarks(`${markBase}:end`);
performance.clearMeasures(markBase);
}
return;
}
try {
window.localStorage.setItem(storageKey, serialized);
lastPersistedGuestMetadataJSON = serialized;
lastPersistedGuestMetadataStorageKey = storageKey;
if (markBase) {
performance.mark(`${markBase}:end`);
performance.measure(markBase, `${markBase}:start`, `${markBase}:end`);
const entries = performance.getEntriesByName(markBase);
const entry = entries[entries.length - 1];
if (entry) {
logger.debug('[guestMetadataCache] persisted entries', {
count: Object.keys(metadata).length,
durationMs: entry.duration,
});
}
performance.clearMarks(`${markBase}:start`);
performance.clearMarks(`${markBase}:end`);
performance.clearMeasures(markBase);
}
} catch (error) {
if (markBase) {
performance.mark(`${markBase}:end`);
performance.measure(markBase, `${markBase}:start`, `${markBase}:end`);
performance.clearMarks(`${markBase}:start`);
performance.clearMarks(`${markBase}:end`);
performance.clearMeasures(markBase);
}
logger.warn('Failed to persist guest metadata cache', error);
}
};
const queueGuestMetadataPersist = (storageKey: string, metadata: GuestMetadataRecord) => {
cachedGuestMetadata = metadata;
cachedGuestMetadataStorageKey = storageKey;
if (typeof window === 'undefined') {
return;
}
pendingPersistMetadata = metadata;
pendingPersistStorageKey = storageKey;
const idleWindow = window as IdleCapableWindow;
clearPendingPersistHandle(idleWindow);
const schedule: IdleCallback = () => {
persistHandle = null;
persistHandleType = null;
runGuestMetadataPersist();
};
if (idleWindow.requestIdleCallback) {
persistHandleType = 'idle';
persistHandle = idleWindow.requestIdleCallback(schedule, { timeout: 750 });
} else {
persistHandleType = 'timeout';
persistHandle = window.setTimeout(schedule, 0);
}
};
export function useWorkloadGuestMetadataState(metadataIds?: Accessor<ReadonlySet<string>>) {
let refreshRevision = 0;
let disposed = false;
const [orgScope, setOrgScope] = createSignal(normalizeOrgScope(getOrgID()));
const guestMetadataStorageKey = createMemo(() => guestMetadataStorageKeyForOrg(orgScope()));
const [guestMetadata, setGuestMetadata] = createSignal<GuestMetadataRecord>(
readGuestMetadataCache(guestMetadataStorageKey()),
);
const [guestMetadata, setGuestMetadata] = createSignal<GuestMetadataRecord>({});
const updateGuestMetadataState = (updater: (prev: GuestMetadataRecord) => GuestMetadataRecord) =>
setGuestMetadata((prev) => {
const next = updater(prev);
if (next === prev) {
return prev;
}
queueGuestMetadataPersist(guestMetadataStorageKey(), next);
return next;
});
// The authenticated app shell disposes this owner on confirmed sign-out,
// even when provider navigation or browser cleanup cannot complete.
onCleanup(() => {
disposed = true;
refreshRevision += 1;
setGuestMetadata({});
});
const updateGuestMetadataState = (
updater: (prev: GuestMetadataRecord) => GuestMetadataRecord,
) => {
if (!disposed) setGuestMetadata(updater);
};
const refreshGuestMetadata = async () => {
if (disposed) return;
const revision = ++refreshRevision;
const storageKey = guestMetadataStorageKey();
const requestOrg = orgScope();
try {
const metadata = await GuestMetadataAPI.getAllMetadata();
if (revision !== refreshRevision || storageKey !== guestMetadataStorageKey()) return;
if (disposed || revision !== refreshRevision || requestOrg !== orgScope()) return;
updateGuestMetadataState(() => metadata || {});
logger.debug('Guest metadata refreshed');
} catch (error) {
@@ -247,6 +52,7 @@ export function useWorkloadGuestMetadataState(metadataIds?: Accessor<ReadonlySet
};
const handleCustomUrlUpdate = (guestId: string, url: string) => {
if (disposed) return;
const trimmedUrl = url.trim();
const nextUrl = trimmedUrl === '' ? undefined : trimmedUrl;
const currentUrl = guestMetadata()[guestId]?.customUrl;
@@ -336,6 +142,8 @@ export function useWorkloadGuestMetadataState(metadataIds?: Accessor<ReadonlySet
window.addEventListener(RESOURCE_METADATA_CHANGED_EVENT, handleMetadataChanged);
const unsubscribeOrgSwitched = eventBus.on('org_switched', (nextOrgID) => {
refreshRevision += 1;
setGuestMetadata({});
setOrgScope(normalizeOrgScope(nextOrgID));
void refreshGuestMetadata();
});
@@ -346,11 +154,6 @@ export function useWorkloadGuestMetadataState(metadataIds?: Accessor<ReadonlySet
});
});
createEffect(() => {
const storageKey = guestMetadataStorageKey();
setGuestMetadata(readGuestMetadataCache(storageKey));
});
return {
guestMetadata,
handleCustomUrlUpdate,

View File

@@ -867,9 +867,19 @@ export const useAppRuntimeState = () => {
}
};
clean(clearAuth);
// Older Workloads versions persisted an org-only copy of server
// metadata. New owners never read/write it; remove every legacy scope
// only after withdrawal is acknowledged. Snapshot keys before removal.
const guestMetadataKeys = new Set<string>([STORAGE_KEYS.GUEST_METADATA]);
clean(() => {
for (let index = 0; index < localStorage.length; index += 1) {
const key = localStorage.key(index);
if (key?.startsWith(`${STORAGE_KEYS.GUEST_METADATA}.`)) guestMetadataKeys.add(key);
}
});
for (const key of [
STORAGE_KEYS.AUTH,
STORAGE_KEYS.GUEST_METADATA,
...guestMetadataKeys,
STORAGE_KEYS.DOCKER_METADATA,
STORAGE_KEYS.DOCKER_METADATA + '_hosts',
]) {