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
fix: keep feature navigation consistent across mounted views (#6662)
[._.]/ Adam Eivy795464136a7c
diff --git a/client/src/hooks/useInstanceFeatures.js b/client/src/hooks/useInstanceFeatures.jsindex 655e36ccbd..7e70116506 100644--- a/client/src/hooks/useInstanceFeatures.js+++ b/client/src/hooks/useInstanceFeatures.js@@ -1,58 +1,78 @@-import { useCallback, useEffect, useState } from 'react';+import { useCallback, useSyncExternalStore } from 'react';import { INSTANCE_FEATURES_CHANGED } from '../constants/events.js';import * as api from '../services/api';-// Shared read of Settings > Features (`GET /api/settings/features`), with one-// module-level cache so the sidebar, the ⌘K palette, and the Features tab-// collapse to a single fetch per page load.-//-// Change notification rides the EXISTING `INSTANCE_FEATURES_CHANGED` window-// event rather than a second broadcast channel — the engagement-reminder toast-// already publishes on it and three dashboard widgets already listen, so a-// private subscriber list here would have left those halves able to drift.-// A publisher that already holds the server's fresh list passes it as-// `detail.features` to skip the refetch; the `{ featureId, enabled }` shape the-// existing publisher sends still works and simply triggers one.-//-// `null` features means NOT LOADED — deliberately distinct from `[]`, which-// means loaded and this version registers no optional features.-let cached = null;+// One snapshot and event bridge for every mounted consumer. `null` means not+// loaded (or failed), while [] is a successfully loaded empty feature list.+const INITIAL_STATE = { features: null, error: null };+let snapshot = INITIAL_STATE;let inFlight = null;-let inFlightGeneration = null;-// Bumped whenever something newer than an outstanding request lands (a toggle-// publishing the server's fresh list, or an invalidation). A response that read-// the OLD state must not overwrite it just because it resolved later — without-// this, saving a JIRA instance while the initial fetch is still in flight leaves-// the sidebar and ⌘K showing the pre-save answer until a reload.let generation = 0;+const subscribers = new Set();++const getSnapshot = () => snapshot;+const commitSnapshot = (result) => {+ snapshot = result;+ subscribers.forEach((notify) => notify());+};const loadInstanceFeatures = () => {- if (!inFlight || inFlightGeneration !== generation) {+ if (!inFlight) {const requested = generation;const request = api.getInstanceFeatures({ silent: true }).then((data) => ({ features: Array.isArray(data?.features) ? data.features : [], error: null })).catch((error) => {- // Fail OPEN: an unreadable feature list must not blank out navigation.console.warn(`⚠️ instance features fetch failed: ${error?.message || error}`);return { features: null, error };}).then((result) => {- if (inFlight === request) {- inFlight = null;- inFlightGeneration = null;- }- // Superseded while in flight — hand the caller what IS current instead- // of the answer it asked for, so no consumer renders the stale one.- if (requested !== generation) return cached || result;- cached = result;- return result;+ if (inFlight === request) inFlight = null;+ // A superseded request never publishes, even while its replacement is+ // pending. Subscribers receive only the current generation's result.+ if (requested === generation) commitSnapshot(result);});inFlight = request;- inFlightGeneration = requested;}return inFlight;};+const onFeaturesChanged = (event) => {+ generation += 1;+ inFlight = null;+ const features = event?.detail?.features;+ if (Array.isArray(features)) {+ commitSnapshot({ features, error: null });+ } else {+ commitSnapshot(INITIAL_STATE);+ loadInstanceFeatures();+ }+};++const subscribe = (notify) => {+ if (subscribers.size === 0) {+ window.addEventListener(INSTANCE_FEATURES_CHANGED, onFeaturesChanged);+ }+ subscribers.add(notify);+ if (snapshot === INITIAL_STATE) loadInstanceFeatures();+ return () => {+ subscribers.delete(notify);+ if (subscribers.size === 0) {+ window.removeEventListener(INSTANCE_FEATURES_CHANGED, onFeaturesChanged);+ }+ };+};++const reload = () => {+ generation += 1;+ const requested = generation;+ inFlight = null;+ commitSnapshot(INITIAL_STATE);+ return loadInstanceFeatures().then(() => {+ // Preserve the public success announcement for non-hook event listeners.+ if (requested === generation && snapshot.features) publishInstanceFeatures(snapshot.features);+ });+};+/*** @returns {{* features: Array|null, // null while loading or after a failed fetch@@ -68,34 +88,7 @@ const loadInstanceFeatures = () => {* - errored → true, so a server hiccup shows everything instead of hiding it*/export function useInstanceFeatures() {- const [state, setState] = useState(() => cached || { features: null, error: null });-- useEffect(() => {- let active = true;- const sync = (result) => { if (active) setState(result); };-- if (cached) sync(cached); else loadInstanceFeatures().then(sync);-- const onFeaturesChanged = (event) => {- const features = event?.detail?.features;- generation += 1;- if (Array.isArray(features)) {- cached = { features, error: null };- sync(cached);- return;- }- cached = null;- loadInstanceFeatures().then(sync);- };-- window.addEventListener(INSTANCE_FEATURES_CHANGED, onFeaturesChanged);- return () => {- active = false;- window.removeEventListener(INSTANCE_FEATURES_CHANGED, onFeaturesChanged);- };- }, []);-- const { features, error } = state;+ const { features, error } = useSyncExternalStore(subscribe, getSnapshot);const isFeatureEnabled = useCallback((featureId) => {if (!featureId) return true;@@ -105,18 +98,6 @@ export function useInstanceFeatures() {return feature ? feature.enabled !== false : true;}, [features, error]);- // Announced rather than applied locally: after a failed first fetch every- // consumer is sitting in the fail-open error state, and a retry that updated- // only the Settings tab would leave the sidebar and ⌘K stale until a reload.- const reload = useCallback(() => {- generation += 1;- cached = null;- return loadInstanceFeatures().then((result) => {- if (result.features) publishInstanceFeatures(result.features);- else setState(result);- });- }, []);-return { features, error, isFeatureEnabled, reload };}@@ -134,7 +115,7 @@ export const publishInstanceFeatures = (features, { featureId, enabled } = {}) =* Announce that the state a feature's AUTO-detection reads has changed — the* integration pages call this after adding or removing an instance, because the* DataDog/JIRA gates are derived from whether one is configured. Carries no- * feature list, so every listener re-fetches the freshly-resolved answer.+ * feature list, so the store re-fetches the freshly-resolved answer once.*/export const invalidateInstanceFeatures = (featureId) => {publishInstanceFeatures(null, { featureId });@@ -142,8 +123,7 @@ export const invalidateInstanceFeatures = (featureId) => {// Test-only: drop the module cache so suites don't leak state between tests.export const __resetInstanceFeatureCache = () => {- cached = null;+ snapshot = INITIAL_STATE;inFlight = null;- inFlightGeneration = null;generation += 1;};diff --git a/client/src/hooks/useInstanceFeatures.test.jsx b/client/src/hooks/useInstanceFeatures.test.jsxindex 0ab32e3911..ec457657d5 100644--- a/client/src/hooks/useInstanceFeatures.test.jsx+++ b/client/src/hooks/useInstanceFeatures.test.jsx@@ -1,5 +1,6 @@import { describe, expect, it, beforeEach, vi } from 'vitest';-import { act, render, screen } from '@testing-library/react';+import { StrictMode } from 'react';+import { act, fireEvent, render, screen } from '@testing-library/react';const mock = vi.hoisted(() => ({ getInstanceFeatures: vi.fn() }));vi.mock('../services/api', () => mock);@@ -8,6 +9,7 @@ import { INSTANCE_FEATURES_CHANGED } from '../constants/events.js';import {useInstanceFeatures,publishInstanceFeatures,+ invalidateInstanceFeatures,__resetInstanceFeatureCache,} from './useInstanceFeatures.js';@@ -15,14 +17,20 @@ const JIRA_ON = [{ id: 'jira', label: 'JIRA', enabled: true }];const JIRA_OFF = [{ id: 'jira', label: 'JIRA', enabled: false }];function Probe({ label = 'a' }) {- const { isFeatureEnabled } = useInstanceFeatures();- return <output data-testid={label}>{isFeatureEnabled('jira') ? 'on' : 'off'}</output>;+ const { features, error, isFeatureEnabled, reload } = useInstanceFeatures();+ return <>+ <output data-testid={label} data-features={JSON.stringify(features)} data-error={Boolean(error)}>+ {isFeatureEnabled('jira') ? 'on' : 'off'}+ </output>+ <button onClick={reload}>Reload {label}</button>+ </>;}const deferred = () => {let resolve;- const promise = new Promise((r) => { resolve = r; });- return { promise, resolve };+ let reject;+ const promise = new Promise((r, j) => { resolve = r; reject = j; });+ return { promise, resolve, reject };};describe('useInstanceFeatures', () => {@@ -53,12 +61,12 @@ describe('useInstanceFeatures', () => {});it('refetches when told the underlying state changed but not what it is', async () => {- render(<Probe />);+ render(<><Probe label="a" /><Probe label="b" /></>);await act(async () => {});mock.getInstanceFeatures.mockResolvedValue({ features: JIRA_ON });await act(async () => {- window.dispatchEvent(new CustomEvent(INSTANCE_FEATURES_CHANGED, { detail: { featureId: 'jira' } }));+ window.dispatchEvent(new CustomEvent(INSTANCE_FEATURES_CHANGED, { detail: { featureId: 'jira', enabled: true } }));});expect(screen.getByTestId('a')).toHaveTextContent('on');@@ -70,7 +78,7 @@ describe('useInstanceFeatures', () => {it('does not let a stale in-flight response overwrite a newer answer', async () => {const slow = deferred();mock.getInstanceFeatures.mockReturnValueOnce(slow.promise);- render(<Probe />);+ render(<><Probe label="a" /><Probe label="b" /></>);// The save publishes the fresh list while the first fetch is still open.act(() => publishInstanceFeatures(JIRA_ON, { featureId: 'jira', enabled: true }));@@ -85,35 +93,70 @@ describe('useInstanceFeatures', () => {expect(screen.getByTestId('a')).toHaveTextContent('on');});- it('starts a fresh shared read after a legacy invalidation during an in-flight read', async () => {+ it.each(['before', 'after'])('ignores a superseded read settling %s its replacement', async (order) => {const stale = deferred();const fresh = deferred();- mock.getInstanceFeatures- .mockReturnValueOnce(stale.promise)- .mockReturnValueOnce(fresh.promise);- render(<Probe />);-- act(() => {- window.dispatchEvent(new CustomEvent(INSTANCE_FEATURES_CHANGED, { detail: { featureId: 'jira' } }));- });+ mock.getInstanceFeatures.mockReturnValueOnce(stale.promise).mockReturnValueOnce(fresh.promise);+ render(<><Probe label="a" /><Probe label="b" /></>);+ act(() => invalidateInstanceFeatures('jira'));expect(mock.getInstanceFeatures).toHaveBeenCalledTimes(2);- await act(async () => {- fresh.resolve({ features: JIRA_ON });- await fresh.promise;- });- expect(screen.getByTestId('a')).toHaveTextContent('on');+ const settleStale = () => act(async () => { stale.resolve({ features: JIRA_ON }); });+ if (order === 'before') {+ await settleStale();+ for (const label of ['a', 'b']) {+ expect(screen.getByTestId(label)).toHaveAttribute('data-features', 'null');+ expect(screen.getByTestId(label)).toHaveTextContent('off');+ }+ }+ await act(async () => { fresh.resolve({ features: JIRA_OFF }); });+ if (order === 'after') await settleStale();+ for (const label of ['a', 'b']) {+ expect(screen.getByTestId(label)).toHaveAttribute('data-features', JSON.stringify(JIRA_OFF));+ expect(screen.getByTestId(label)).toHaveTextContent('off');+ }+ });- await act(async () => {- stale.resolve({ features: JIRA_OFF });- await stale.promise;- });- expect(screen.getByTestId('a')).toHaveTextContent('on');+ it('shares refresh failures and recovers every consumer when one retries', async () => {+ render(<><Probe label="a" /><Probe label="b" /></>);+ await act(async () => {});+ const failed = deferred();+ mock.getInstanceFeatures.mockReturnValueOnce(failed.promise);+ act(() => invalidateInstanceFeatures('jira'));+ expect(mock.getInstanceFeatures).toHaveBeenCalledTimes(2);+ await act(async () => { failed.reject(new Error('synthetic offline')); });+ for (const label of ['a', 'b']) {+ expect(screen.getByTestId(label)).toHaveTextContent('on');+ expect(screen.getByTestId(label)).toHaveAttribute('data-features', 'null');+ expect(screen.getByTestId(label)).toHaveAttribute('data-error', 'true');+ }+ await act(async () => { fireEvent.click(screen.getByText('Reload a')); });+ expect(mock.getInstanceFeatures).toHaveBeenCalledTimes(3);+ for (const label of ['a', 'b']) {+ expect(screen.getByTestId(label)).toHaveTextContent('off');+ expect(screen.getByTestId(label)).toHaveAttribute('data-error', 'false');+ }+ });++ it('keeps one bridge through StrictMode, late subscriptions and remounts', async () => {+ const view = render(<StrictMode><Probe /></StrictMode>);+ await act(async () => {});+ act(() => publishInstanceFeatures([]));+ view.rerender(<StrictMode><Probe /><Probe label="b" /></StrictMode>);+ expect(screen.getByTestId('b')).toHaveAttribute('data-features', '[]');+ expect(screen.getByTestId('b')).toHaveTextContent('on');+ expect(mock.getInstanceFeatures).toHaveBeenCalledTimes(1);+ view.unmount();+ render(<StrictMode><Probe /><Probe label="b" /></StrictMode>);+ await act(async () => { invalidateInstanceFeatures('jira'); });+ expect(mock.getInstanceFeatures).toHaveBeenCalledTimes(2);+ expect(screen.getByTestId('a')).toHaveTextContent('off');+ expect(screen.getByTestId('b')).toHaveTextContent('off');});it('fails open so a failed fetch never blanks navigation', async () => {mock.getInstanceFeatures.mockRejectedValue(new Error('offline'));- render(<Probe />);+ render(<><Probe label="a" /><Probe label="b" /></>);await act(async () => {});expect(screen.getByTestId('a')).toHaveTextContent('on');