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
address review (codex): fail open when feature detection cannot answer
[._.]/ Adam Eivyb77113a91ff9
diff --git a/client/src/hooks/useInstanceFeatures.js b/client/src/hooks/useInstanceFeatures.jsindex 7eec29ab09..31e34eaa35 100644--- a/client/src/hooks/useInstanceFeatures.js+++ b/client/src/hooks/useInstanceFeatures.js@@ -18,9 +18,16 @@ import * as api from '../services/api';// means loaded and this version registers no optional features.let cached = null;let inFlight = 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 loadInstanceFeatures = () => {if (!inFlight) {+ const requested = generation;inFlight = api.getInstanceFeatures({ silent: true }).then((data) => ({ features: Array.isArray(data?.features) ? data.features : [], error: null })).catch((error) => {@@ -29,8 +36,11 @@ const loadInstanceFeatures = () => {return { features: null, error };}).then((result) => {- cached = result;inFlight = 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;});}@@ -62,6 +72,7 @@ export function useInstanceFeatures() {const onFeaturesChanged = (event) => {const features = event?.detail?.features;+ generation += 1;if (Array.isArray(features)) {cached = { features, error: null };sync(cached);@@ -92,6 +103,7 @@ export function useInstanceFeatures() {// 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);@@ -126,4 +138,5 @@ export const invalidateInstanceFeatures = (featureId) => {export const __resetInstanceFeatureCache = () => {cached = null;inFlight = null;+ generation += 1;};diff --git a/client/src/hooks/useInstanceFeatures.test.jsx b/client/src/hooks/useInstanceFeatures.test.jsxnew file mode 100644index 0000000000..f2225dd269--- /dev/null+++ b/client/src/hooks/useInstanceFeatures.test.jsx@@ -0,0 +1,95 @@+import { describe, expect, it, beforeEach, vi } from 'vitest';+import { act, render, screen } from '@testing-library/react';++const mock = vi.hoisted(() => ({ getInstanceFeatures: vi.fn() }));+vi.mock('../services/api', () => mock);++import { INSTANCE_FEATURES_CHANGED } from '../constants/events.js';+import {+ useInstanceFeatures,+ publishInstanceFeatures,+ __resetInstanceFeatureCache,+} from './useInstanceFeatures.js';++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 deferred = () => {+ let resolve;+ const promise = new Promise((r) => { resolve = r; });+ return { promise, resolve };+};++describe('useInstanceFeatures', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ __resetInstanceFeatureCache();+ mock.getInstanceFeatures.mockResolvedValue({ features: JIRA_OFF });+ });++ it('shares one fetch across every consumer', async () => {+ render(<><Probe label="a" /><Probe label="b" /></>);+ await act(async () => {});++ expect(mock.getInstanceFeatures).toHaveBeenCalledTimes(1);+ expect(screen.getByTestId('a')).toHaveTextContent('off');+ expect(screen.getByTestId('b')).toHaveTextContent('off');+ });++ it('applies a published list to every consumer without refetching', async () => {+ render(<><Probe label="a" /><Probe label="b" /></>);+ await act(async () => {});++ act(() => publishInstanceFeatures(JIRA_ON, { featureId: 'jira', enabled: true }));++ expect(screen.getByTestId('a')).toHaveTextContent('on');+ expect(screen.getByTestId('b')).toHaveTextContent('on');+ expect(mock.getInstanceFeatures).toHaveBeenCalledTimes(1);+ });++ it('refetches when told the underlying state changed but not what it is', async () => {+ render(<Probe />);+ await act(async () => {});+ mock.getInstanceFeatures.mockResolvedValue({ features: JIRA_ON });++ await act(async () => {+ window.dispatchEvent(new CustomEvent(INSTANCE_FEATURES_CHANGED, { detail: { featureId: 'jira' } }));+ });++ expect(screen.getByTestId('a')).toHaveTextContent('on');+ expect(mock.getInstanceFeatures).toHaveBeenCalledTimes(2);+ });++ // The race the generation counter exists for: a save lands while the initial+ // fetch is still open, and that fetch read the PRE-save state.+ it('does not let a stale in-flight response overwrite a newer answer', async () => {+ const slow = deferred();+ mock.getInstanceFeatures.mockReturnValueOnce(slow.promise);+ render(<Probe />);++ // The save publishes the fresh list while the first fetch is still open.+ act(() => publishInstanceFeatures(JIRA_ON, { featureId: 'jira', enabled: true }));+ expect(screen.getByTestId('a')).toHaveTextContent('on');++ // The stale response now arrives carrying the pre-save answer.+ await act(async () => {+ slow.resolve({ features: JIRA_OFF });+ await slow.promise;+ });++ expect(screen.getByTestId('a')).toHaveTextContent('on');+ });++ it('fails open so a failed fetch never blanks navigation', async () => {+ mock.getInstanceFeatures.mockRejectedValue(new Error('offline'));+ render(<Probe />);+ await act(async () => {});++ expect(screen.getByTestId('a')).toHaveTextContent('on');+ });+});diff --git a/server/lib/instanceFeatureRegistry.js b/server/lib/instanceFeatureRegistry.jsindex ae604598d2..7ac15bd967 100644--- a/server/lib/instanceFeatureRegistry.js+++ b/server/lib/instanceFeatureRegistry.js@@ -37,3 +37,26 @@ export const INSTANCE_FEATURES = Object.freeze([]);export const INSTANCE_FEATURE_IDS = Object.freeze(INSTANCE_FEATURES.map((feature) => feature.id));++/**+ * How many instances an integration's config file declares — the signal every+ * `detect` hook is built on.+ *+ * THROWS on a malformed shape rather than counting it, because every wrong+ * answer here is silently wrong: `{"instances": "bad"}` would count its three+ * CHARACTER keys as three configured instances, and `{"instances": []}` (or+ * `null`) would report a confident zero. Both are "the file is not what we+ * think", which the caller must treat as detection failure — not as a+ * trustworthy count. An absent file never reaches here; it resolves to the+ * empty default upstream, which is a trustworthy zero.+ */+export const countConfiguredInstances = (config, label = 'instance config') => {+ const instances = config?.instances;+ const isPlainObject = instances !== null+ && typeof instances === 'object'+ && !Array.isArray(instances);+ if (!isPlainObject) {+ throw new Error(`Malformed ${label}: "instances" must be an object`);+ }+ return Object.keys(instances).length;+};diff --git a/server/lib/instanceFeatureRegistry.test.js b/server/lib/instanceFeatureRegistry.test.jsnew file mode 100644index 0000000000..8d95b9eff7--- /dev/null+++ b/server/lib/instanceFeatureRegistry.test.js@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest';+import { INSTANCE_FEATURES, INSTANCE_FEATURE_IDS, countConfiguredInstances } from './instanceFeatureRegistry.js';++describe('instance feature registry', () => {+ it('declares an id, label, description and default for every feature', () => {+ for (const feature of INSTANCE_FEATURES) {+ expect(feature.id).toBeTruthy();+ expect(feature.label).toBeTruthy();+ expect(feature.description).toBeTruthy();+ expect(typeof feature.defaultEnabled).toBe('boolean');+ }+ expect(INSTANCE_FEATURE_IDS).toEqual(INSTANCE_FEATURES.map((f) => f.id));+ expect(new Set(INSTANCE_FEATURE_IDS).size).toBe(INSTANCE_FEATURE_IDS.length);+ });+});++describe('countConfiguredInstances', () => {+ it('counts the declared instances', () => {+ expect(countConfiguredInstances({ instances: {} })).toBe(0);+ expect(countConfiguredInstances({ instances: { a: {}, b: {} } })).toBe(2);+ });++ // Every one of these would otherwise produce a CONFIDENT wrong answer that+ // silently shows or hides navigation, so each must read as detection failure.+ it('throws on a shape it cannot trust rather than guessing a count', () => {+ // The dangerous one: Object.keys('bad') is ['0','1','2'] — three "instances".+ expect(() => countConfiguredInstances({ instances: 'bad' })).toThrow(/Malformed/);+ // These would each report a confident zero.+ expect(() => countConfiguredInstances({ instances: [] })).toThrow(/Malformed/);+ expect(() => countConfiguredInstances({ instances: null })).toThrow(/Malformed/);+ expect(() => countConfiguredInstances({})).toThrow(/Malformed/);+ expect(() => countConfiguredInstances(null)).toThrow(/Malformed/);+ });++ it('names the file in the error so a corrupt config is findable', () => {+ expect(() => countConfiguredInstances({ instances: [] }, 'jira.json')).toThrow(/jira\.json/);+ });+});diff --git a/server/services/datadog.js b/server/services/datadog.jsindex a073392b5d..55f7fd3707 100644--- a/server/services/datadog.js+++ b/server/services/datadog.js@@ -5,6 +5,7 @@import fs from 'fs/promises';import { createHttpClient } from '../lib/httpClient.js';+import { countConfiguredInstances } from '../lib/instanceFeatureRegistry.js';import path from 'path';import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';@@ -40,7 +41,7 @@ export async function getInstances() {// absent file still returns the empty default — absent is a trustworthy empty.export async function hasConfiguredInstances() {const config = await readJSONFile(DATADOG_CONFIG_FILE, { instances: {} }, { logError: false, strict: true });- return Object.keys(config?.instances || {}).length > 0;+ return countConfiguredInstances(config, 'datadog.json') > 0;}/**diff --git a/server/services/instanceFeatures.js b/server/services/instanceFeatures.jsindex c291a7e8d6..1ef37d68cb 100644--- a/server/services/instanceFeatures.js+++ b/server/services/instanceFeatures.js@@ -57,6 +57,17 @@ const resolveOne = (feature, settings, detected) => {const configured = detected?.[feature.id];if (typeof configured === 'boolean') return { enabled: configured, source: 'auto' };++ // Detection was supposed to answer and couldn't (unreadable or malformed+ // config). FAIL OPEN — show the feature — rather than falling through to+ // `defaultEnabled`, which is `false` for both integrations and would hide the+ // page on exactly the install that needs it: the config file EXISTS, so the+ // integration is probably set up, and /devtools/jira is itself where the user+ // goes to fix it. Hiding it there strands them. Mirrors the client hook, which+ // also fails open when it cannot read the feature list.+ if (typeof DETECTORS[feature.id] === 'function') {+ return { enabled: true, source: 'detect-failed' };+ }return { enabled: feature.defaultEnabled, source: 'default' };};diff --git a/server/services/instanceFeatures.test.js b/server/services/instanceFeatures.test.jsindex a4ef5ba7b9..3f4812513f 100644--- a/server/services/instanceFeatures.test.js+++ b/server/services/instanceFeatures.test.js@@ -129,31 +129,40 @@ describe('instance features', () => {expect(await isInstanceFeatureEnabled('datadog')).toBe(true);});- it('falls back to the default (not "unconfigured") when detection itself fails', async () => {+ // A PRESENT-but-corrupt config file is the case that fails silently. The+ // detector throws, and the gate must then fail OPEN: the file exists, so the+ // integration is probably configured, and /devtools/jira is itself where the+ // user goes to fix it — hiding it there strands them.+ it('fails OPEN when detection cannot answer, rather than hiding the page', async () => {mock.datadogThrows = true;+ mock.settings = {};- expect(await detectFeatureConfiguration()).toMatchObject({ datadog: null });- const { features } = await getInstanceFeatures();- // defaultEnabled is false for DataDog, but the reason must be `default`,- // not a probe result that never came back.- expect(byId(features, 'datadog')).toMatchObject({ enabled: false, source: 'default' });- expect(await isInstanceFeatureEnabled('datadog')).toBe(false);+ expect((await detectFeatureConfiguration()).datadog).toBeNull();+ expect(byId((await getInstanceFeatures()).features, 'datadog')).toMatchObject({+ enabled: true,+ source: 'detect-failed',+ });+ expect(await isInstanceFeatureEnabled('datadog')).toBe(true);});- // A PRESENT-but-corrupt config file is the case that fails silently: the- // detector must throw so this resolves to the shipped default, NOT report a- // confident "no instances" that would hide the navigation.- it('treats a corrupt integration config as detection failure, not "unconfigured"', async () => {+ it('still lets an explicit disable win over a failed probe', async () => {mock.datadogThrows = true;- mock.settings = {};+ mock.settings = { instanceFeatures: { datadog: { enabled: false } } };- expect((await detectFeatureConfiguration()).datadog).toBeNull();- expect(byId((await getInstanceFeatures()).features, 'datadog')).toMatchObject({ source: 'default' });+ expect(byId((await getInstanceFeatures()).features, 'datadog')).toMatchObject({+ enabled: false,+ source: 'explicit',+ });});+ // A feature with NO detector reads null for a different reason — nothing was+ // ever probed — so it must keep taking its shipped default, not fail open.it('reports no detection for a feature with no detector', async () => {expect(await detectFeatureConfiguration()).toMatchObject({ post: null });- expect(byId((await getInstanceFeatures()).features, 'post')).toMatchObject({ source: 'default' });+ expect(byId((await getInstanceFeatures()).features, 'post')).toMatchObject({+ enabled: true,+ source: 'default',+ });});});diff --git a/server/services/jira.js b/server/services/jira.jsindex e3eda4557c..dc6cfc910d 100644--- a/server/services/jira.js+++ b/server/services/jira.js@@ -8,6 +8,7 @@ import { createHttpClient } from '../lib/httpClient.js';import path from 'path';import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';import { hostFromOriginUrl } from '../lib/workTracker.js';+import { countConfiguredInstances } from '../lib/instanceFeatureRegistry.js';const JIRA_CONFIG_FILE = path.join(PATHS.data, 'jira.json');@@ -23,7 +24,7 @@ const JIRA_CONFIG_FILE = path.join(PATHS.data, 'jira.json');// absent file still returns the empty default — absent is a trustworthy empty.export async function hasConfiguredInstances() {const config = await readJSONFile(JIRA_CONFIG_FILE, { instances: {} }, { logError: false, strict: true });- return Object.keys(config?.instances || {}).length > 0;+ return countConfiguredInstances(config, 'jira.json') > 0;}export const escapeJql = (s) => String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"');