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
hide DataDog, JIRA and POST navigation when the instance feature is off
[._.]/ Adam Eivyb792f0c4fe4d
diff --git a/.claude/skills/portos-add-page/SKILL.md b/.claude/skills/portos-add-page/SKILL.mdindex 5d34bdb238..a8736ad303 100644--- a/.claude/skills/portos-add-page/SKILL.md+++ b/.claude/skills/portos-add-page/SKILL.md@@ -22,6 +22,7 @@ PortOS has a single source of truth for navigation: `server/lib/navManifest.js`- `section` — matches the sidebar group label so the palette and sidebar stay visually aligned.- `aliases` — short spoken/typed tokens the user is likely to say. The voice agent's fuzzy resolver tries each alias with tiered matching; more aliases = more forgiving voice navigation.- `keywords` — extra terms used only by the palette's in-UI scorer (synonyms, feature names).+- `feature` (optional) — gates the page on an optional instance feature (`post`, `datadog`, `jira`; see `server/lib/instanceFeatureRegistry.js`). When the feature is off in **Settings > Features**, the entry disappears from `⌘K` and its sidebar row disappears too — the route itself keeps working, so a bookmark, a direct link, or voice `ui_navigate` still resolves. The manifest ships the tag and the CLIENT applies the gate (`useInstanceFeatures` + `client/src/lib/navFeatures.js`), which is what makes a toggle take effect without a reload. Whole sidebar sections gate through navManifest's `SECTION_FEATURE` map instead, so a new page in one of those sections inherits the gate with no tag. **Tag the matching `Layout.jsx` row with the same `feature`** — the sidebar is a separate list, and `navManifest.test.js` fails when the two halves drift.Fail-fast guards at module load catch missing fields, non-slash paths, and duplicate ids — so a bad entry blocks server boot instead of silently breaking palette/voice.diff --git a/AGENTS.md b/AGENTS.mdindex 42a77052fb..23518496c3 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -88,6 +88,8 @@ Client- and server-specific conventions live in nested memory files that load wh`server/lib/navManifest.js` is the single source of truth for navigation: `NAV_COMMANDS` + `resolveNavCommand()`, consumed by both the `⌘K` palette and the voice agent's `ui_navigate` tool. **Adding a `<Route>` without a `NAV_COMMANDS` entry leaves the page unreachable from `⌘K` and un-navigable by voice.** Invoke the `portos-add-page` skill for the entry shape, palette-action wiring, and the fail-fast guards.+**Optional features gate navigation, not routes.** `server/lib/instanceFeatureRegistry.js` declares the optional per-install features (`post`, `datadog`, `jira`) the user toggles in **Settings > Features**; `server/services/instanceFeatures.js` resolves each one as stored override → auto-detection of the integration it fronts → `defaultEnabled`. A nav entry tagged `feature: '<id>'` (or living in a section listed in navManifest's `SECTION_FEATURE` map) drops out of `⌘K` and the sidebar while that feature is off — **the `<Route>` keeps working, so bookmarks, direct links, and voice `ui_navigate` still resolve**. The gate is applied CLIENT-side (`useInstanceFeatures` + `client/src/lib/navFeatures.js`), not by filtering the manifest response: `⌘K` and the voice widget each fetch `/api/palette/manifest` once per session and it is HTTP-cached, so a server-side filter would both defeat that cache and still show hidden pages until a reload. Tag the sidebar row in `client/src/components/Layout.jsx` with the same id; `navManifest.test.js` scrapes both lists and fails when they drift, when a tag names an unregistered feature, or when a `SECTION_FEATURE` key stops matching a live section.+### Slashdo Commands (`lib/slashdo`)PortOS bundles [slashdo](https://github.com/atomantic/slashdo) as a git submodule at `lib/slashdo`, providing slash commands (`/do:next`, `/do:review`, `/do:pr`, `/do:push`, `/do:release`, …) without a separate global install. The `.claude/commands/do/` symlinks expose them as project-level slash commands. `/do:next` claims the next PLAN.md item (or GitHub issue with `--issues`) in an isolated worktree and ships a PR. CoS agents can inline a command's content into a prompt via `loadSlashdoCommand(name)` from `server/services/subAgentSpawner.js` (it resolves `!cat` lib includes automatically).diff --git a/client/src/components/CmdKSearch.jsx b/client/src/components/CmdKSearch.jsxindex 2effb856de..e899ce9a14 100644--- a/client/src/components/CmdKSearch.jsx+++ b/client/src/components/CmdKSearch.jsx@@ -3,6 +3,7 @@ import { createPortal } from 'react-dom';import { useLocation, useNavigate } from 'react-router';import { Brain, Cpu, Package, History, HeartPulse, Search, Loader2, Navigation, Play, LayoutGrid, BookMarked } from 'lucide-react';import { useCmdKSearch } from '../hooks/useCmdKSearch';+import { useInstanceFeatures } from '../hooks/useInstanceFeatures.js';import { useScrollLock } from '../hooks/useScrollLock';import { search, getPaletteManifest, runPaletteAction, getDashboardLayouts, setActiveDashboardLayout, listCatalogIngredients } from '../services/api';import toast from './ui/Toast';@@ -10,6 +11,7 @@ import { modKey } from '../utils/platform';import { DASHBOARD_LAYOUT_CHANGED } from '../constants/events.js';import { recordManualLayoutPick } from '../utils/timeWindow.js';import { RECENT_KEY, RECENT_CAP, resolveRecentNavEntries } from '../utils/navWorkingSet.js';+import { filterNavByFeatures } from '../lib/navFeatures.js';import { safeReadJsonStorage } from '../lib/safeStorage.js';const ICON_MAP = { Brain, Cpu, Package, History, HeartPulse };@@ -69,6 +71,7 @@ export default function CmdKSearch() {const [query, setQuery] = useState('');const [manifest, setManifest] = useState(null);+ const { isFeatureEnabled } = useInstanceFeatures();const [searchResults, setSearchResults] = useState([]);const [catalogResults, setCatalogResults] = useState([]);const [loading, setLoading] = useState(false);@@ -200,17 +203,26 @@ export default function CmdKSearch() {setFocusedIndex(0);}, [searchResults, catalogResults, query]);+ // Pages belonging to a feature this install turned off are dropped here rather+ // than server-side: the manifest is fetched once per session (and HTTP-cached),+ // so filtering it on the server would leave ⌘K offering hidden pages until a+ // reload. Applying the gate at render keeps it live with the Features toggle.+ const gatedNav = useMemo(+ () => (manifest ? filterNavByFeatures(manifest.nav, isFeatureEnabled) : []),+ [manifest, isFeatureEnabled],+ );+const combined = useMemo(() => {if (!manifest) return { recentNav: [], nav: [], actions: [], layouts: [], commandCount: 0 };const q = query.trim().toLowerCase();if (!q) {- const recentNav = resolveRecentNavEntries(recentPaths, manifest.nav, {+ const recentNav = resolveRecentNavEntries(recentPaths, gatedNav, {currentPath: location.pathname,limit: RECENT_CAP,}).map((c) => ({ ...c, kind: 'nav' }));const recentIds = new Set(recentNav.map((c) => c.id));const fallbackLimit = Math.max(0, RECENT_CAP - recentNav.length);- const nav = manifest.nav+ const nav = gatedNav.filter((c) => DEFAULT_NAV_IDS.has(c.id) && !recentIds.has(c.id) && c.path !== location.pathname).slice(0, fallbackLimit).map((c) => ({ ...c, kind: 'nav' }));@@ -223,11 +235,11 @@ export default function CmdKSearch() {.sort((a, b) => b.score - a.score).slice(0, max).map((x) => x.cmd);- const nav = rank(manifest.nav, 8).map((c) => ({ ...c, kind: 'nav' }));+ const nav = rank(gatedNav, 8).map((c) => ({ ...c, kind: 'nav' }));const actions = rank(manifest.actions, 5).map((a) => ({ ...a, kind: 'action' }));const layouts = rank(manifest.layouts || [], 5).map((l) => ({ ...l, kind: 'layout' }));return { recentNav: [], nav, actions, layouts, commandCount: nav.length + actions.length + layouts.length };- }, [manifest, query, recentPaths, location.pathname]);+ }, [manifest, gatedNav, query, recentPaths, location.pathname]);const flatSearchResults = useMemo(() => searchResults.flatMap((source) => {diff --git a/client/src/components/CmdKSearch.test.jsx b/client/src/components/CmdKSearch.test.jsxindex f5a2f2e465..acdb4d7670 100644--- a/client/src/components/CmdKSearch.test.jsx+++ b/client/src/components/CmdKSearch.test.jsx@@ -4,18 +4,21 @@ import { MemoryRouter, useLocation } from 'react-router';import { RECENT_KEY } from '../utils/navWorkingSet.js';const getPaletteManifest = vi.fn();+const getInstanceFeatures = vi.fn();const getDashboardLayouts = vi.fn();const search = vi.fn(() => Promise.resolve({ sources: [] }));vi.mock('../services/api', () => ({search: (...args) => search(...args),getPaletteManifest: (...args) => getPaletteManifest(...args),+ getInstanceFeatures: (...args) => getInstanceFeatures(...args),runPaletteAction: vi.fn(() => Promise.resolve({ ok: true })),getDashboardLayouts: (...args) => getDashboardLayouts(...args),setActiveDashboardLayout: vi.fn(() => Promise.resolve()),listCatalogIngredients: vi.fn(() => Promise.resolve({ items: [] })),}));+import { __resetInstanceFeatureCache } from '../hooks/useInstanceFeatures.js';import CmdKSearch from './CmdKSearch.jsx';const NAV = [@@ -24,14 +27,23 @@ const NAV = [{ id: 'nav.brain.inbox', path: '/brain/inbox', label: 'Brain Inbox', section: 'Brain', aliases: [], keywords: [] },{ id: 'nav.goals', path: '/goals', label: 'Goals', section: 'Life', aliases: [], keywords: [] },{ id: 'nav.current', path: '/current', label: 'Current Page', section: 'Test', aliases: [], keywords: [] },+ // Gated on an optional instance feature — present in the manifest, hidden by+ // the palette whenever that feature is off.+ { id: 'nav.devtools.jira', path: '/devtools/jira', label: 'JIRA', section: 'Dev Tools', feature: 'jira', aliases: ['jira'], keywords: [] },];+const FEATURES_ON = [{ id: 'jira', label: 'JIRA', enabled: true }];+const FEATURES_OFF = [{ id: 'jira', label: 'JIRA', enabled: false }];+function LocationProbe() {const location = useLocation();return <output data-testid="location">{location.pathname}</output>;}beforeEach(() => {+ // The feature list is cached at module scope and shared with the sidebar.+ __resetInstanceFeatureCache();+ getInstanceFeatures.mockResolvedValue({ features: FEATURES_ON });getPaletteManifest.mockResolvedValue({ nav: NAV, actions: [] });getDashboardLayouts.mockResolvedValue({ layouts: [] });search.mockReset();@@ -72,6 +84,43 @@ describe('CmdKSearch recent destinations', () => {});});+// The manifest ships gated entries tagged rather than filtered, so the palette+// has to apply the gate itself — filtering server-side would leave ⌘K offering+// hidden pages until a reload, because it fetches the manifest once per session.+describe('CmdKSearch instance feature gating', () => {+ const openAndSearch = async (query) => {+ render(+ <MemoryRouter initialEntries={['/current']}>+ <CmdKSearch />+ <LocationProbe />+ </MemoryRouter>,+ );+ fireEvent.keyDown(document, { key: 'k', metaKey: true });+ const input = await screen.findByLabelText('Command palette');+ fireEvent.change(input, { target: { value: query } });+ await act(async () => {});+ };++ it('offers a gated page while its feature is on', async () => {+ await openAndSearch('jira');+ expect(screen.getByText('JIRA')).toBeInTheDocument();+ });++ it('hides a gated page when its feature is off', async () => {+ getInstanceFeatures.mockResolvedValue({ features: FEATURES_OFF });++ await openAndSearch('jira');+ expect(screen.queryByText('JIRA')).not.toBeInTheDocument();+ });++ it('shows gated pages when the feature list cannot be read', async () => {+ getInstanceFeatures.mockRejectedValue(new Error('offline'));++ await openAndSearch('jira');+ expect(screen.getByText('JIRA')).toBeInTheDocument();+ });+});+describe('CmdKSearch global search staleness', () => {it('does not let a slow older-query response overwrite the newer query results', async () => {vi.useFakeTimers();diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 10700d69a9..b53a32fb82 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -122,6 +122,8 @@ import UpdateBanners from './UpdateBanners';import { useAIStatusNotifications } from '../hooks/useAIStatusNotifications';import { useNavWorkingSet } from '../hooks/useNavWorkingSet.js';import { migrateLegacyNavPath } from '../utils/navWorkingSet.js';+import { useInstanceFeatures } from '../hooks/useInstanceFeatures.js';+import { filterNavByFeatures } from '../lib/navFeatures.js';import { useSidebarApps } from '../hooks/useSidebarApps.js';import { useSidebarSeries } from '../hooks/useSidebarSeries.js';import { useSidebarUniverses } from '../hooks/useSidebarUniverses.js';@@ -273,14 +275,14 @@ const navItems = [{ to: '/capabilities', label: 'Capabilities', icon: Compass },{ to: '/devtools/runner', label: 'Code', icon: Code2 },{ to: '/data', label: 'Data', icon: HardDrive },- { to: '/devtools/datadog', label: 'DataDog', icon: Dog },+ { to: '/devtools/datadog', label: 'DataDog', icon: Dog, feature: 'datadog' },{ to: '/devtools/flows', label: 'Flows', icon: WorkflowIcon },{ to: '/devtools/github', label: 'GitHub', icon: GitBranch },{ to: '/devtools/history', label: 'History', icon: History },{ to: '/devtools/image-clean', label: 'Image Cleaner', icon: Eraser },{ to: '/instances', label: 'Instances', icon: Network },- { to: '/devtools/jira', label: 'JIRA', icon: Ticket },- { to: '/devtools/jira/reports', label: 'JIRA Reports', icon: FileText },+ { to: '/devtools/jira', label: 'JIRA', icon: Ticket, feature: 'jira' },+ { to: '/devtools/jira/reports', label: 'JIRA Reports', icon: FileText, feature: 'jira' },{ to: '/loops', label: 'Loops', icon: RefreshCw },{ to: '/devtools/processes', label: 'Processes', icon: Activity },{ to: '/devtools/quota-burn', label: 'Quota Burn', icon: Flame },@@ -376,6 +378,7 @@ const navItems = [{label: 'POST',icon: Zap,+ feature: 'post',defaultTo: '/post/launcher',children: [{ to: '/post/config', label: 'Config', icon: Settings },@@ -709,6 +712,9 @@ export default function Layout() {// Sidebar data-fetch loops (apps / pipeline series / universes) live in// dedicated hooks so the shared focus-debounce + signature-guard pattern is// testable in isolation. See client/src/hooks/useSidebar*.js.+ // Optional features the user turned off in Settings > Features drop out of the+ // sidebar entirely (their routes keep working for a direct link/bookmark).+ const { isFeatureEnabled } = useInstanceFeatures();const sidebarApps = useSidebarApps();const pipelineSeries = useSidebarSeries();const universes = useSidebarUniverses();@@ -723,13 +729,15 @@ export default function Layout() {.catch((err) => console.warn(`⚠️ Layout: palette manifest fetch failed: ${err?.message || err}`));}, []);+ // Manifest-only paths still honour the feature gate, so a row pinned before the+ // user disabled its feature stops resolving into Pinned/Recent too.const manifestEntryByPath = useMemo(() => {const map = new Map();- manifestNav.forEach((c) => {+ filterNavByFeatures(manifestNav, isFeatureEnabled).forEach((c) => {if (c?.path && !map.has(c.path)) map.set(c.path, { path: c.path, label: c.label, icon: Navigation });});return map;- }, [manifestNav]);+ }, [manifestNav, isFeatureEnabled]);useEffect(() => {safeWriteStorage(SIDEBAR_KEY, String(collapsed));@@ -768,7 +776,20 @@ export default function Layout() {})),};};- return navItems.map((item) => {+ // Feature gate, applied before any decoration: a disabled feature drops its+ // whole section (POST) or just its tagged rows (DataDog, JIRA), and a+ // section left with no navigable child disappears with them. Sections that+ // lose nothing keep their identity so the memo below doesn't reallocate.+ const gatedItems = navItems.flatMap((item) => {+ if (!isFeatureEnabled(item.feature)) return [];+ if (!Array.isArray(item.children)) return [item];+ const children = item.children.filter((child) => isFeatureEnabled(child.feature));+ if (children.length === item.children.length) return [item];+ const navigable = item.dynamic || children.some((child) => child.to || child.href);+ return navigable ? [{ ...item, children }] : [];+ });++ return gatedItems.map((item) => {if (item.dynamic === 'apps') {return {...item,@@ -788,7 +809,7 @@ export default function Layout() {}return item;});- }, [sidebarApps, pipelineSeries, universes]);+ }, [sidebarApps, pipelineSeries, universes, isFeatureEnabled]);// Flat path -> { path, label, icon } lookup over every leaf nav row, so the// Pinned/Recent sections render a stored path with its real label + icon.diff --git a/client/src/components/Layout.test.jsx b/client/src/components/Layout.test.jsxindex f58422fffb..c0501398c9 100644--- a/client/src/components/Layout.test.jsx+++ b/client/src/components/Layout.test.jsx@@ -52,13 +52,26 @@ vi.mock('../services/socket', () => ({// --- API: every sidebar fetch resolves empty so the dynamic sections stay bare// and the single rows are the only top-level leaves under test. ---+// Instance features gate sidebar rows (POST / DataDog / JIRA). Default every+// feature ON so these tests see the full sidebar; the gating itself is covered+// by 'Layout — instance feature gating' below.+const allFeaturesOn = () => [+ { id: 'post', label: 'POST', enabled: true },+ { id: 'datadog', label: 'DataDog', enabled: true },+ { id: 'jira', label: 'JIRA', enabled: true },+];+const featureMock = vi.hoisted(() => ({ features: null }));+vi.mock('../services/api', () => ({getApps: vi.fn(() => Promise.resolve([])),listPipelineSeries: vi.fn(() => Promise.resolve([])),listUniverses: vi.fn(() => Promise.resolve([])),getPaletteManifest: vi.fn(() => Promise.resolve({ nav: [] })),+ getInstanceFeatures: vi.fn(() => Promise.resolve({ features: featureMock.features })),}));+import { __resetInstanceFeatureCache } from '../hooks/useInstanceFeatures.js';+import Layout, { isFullWidthRoute } from './Layout';const renderLayout = async (initialPath = '/brain/inbox') => {@@ -82,6 +95,10 @@ const pinnedSection = () => screen.queryByTestId('pinned-section');beforeEach(() => {localStorage.clear();+ // The feature list is cached at module scope so every consumer shares one+ // fetch — drop it between tests so a case that flips a flag cannot leak.+ __resetInstanceFeatureCache();+ featureMock.features = allFeaturesOn();// __APP_VERSION__ is a Vite build-time define; undefined under vitest.vi.stubGlobal('__APP_VERSION__', 'test');});@@ -138,6 +155,53 @@ describe('Layout — pinned single nav rows', () => {});});+describe('Layout — instance feature gating', () => {+ // Rendering an UNGATED /devtools/* route auto-expands the Dev Tools section,+ // so its children are queryable without driving the disclosure — and the+ // expansion does not itself depend on a gated row surviving the filter.+ it('shows the DataDog and JIRA rows while those features are on', async () => {+ await renderLayout('/devtools/flows');++ expect(screen.getByRole('link', { name: 'DataDog' })).toHaveAttribute('href', '/devtools/datadog');+ expect(screen.getByRole('link', { name: 'JIRA' })).toBeTruthy();+ expect(screen.getByRole('link', { name: 'JIRA Reports' })).toBeTruthy();+ expect(screen.getByRole('button', { name: 'POST' })).toBeTruthy();+ });++ it('drops only the rows of the features this install turned off', async () => {+ featureMock.features = allFeaturesOn()+ .map((f) => (f.id === 'post' ? f : { ...f, enabled: false }));++ await renderLayout('/devtools/flows');++ expect(screen.queryByRole('link', { name: 'DataDog' })).toBeNull();+ expect(screen.queryByRole('link', { name: 'JIRA' })).toBeNull();+ expect(screen.queryByRole('link', { name: 'JIRA Reports' })).toBeNull();+ // Ungated Dev Tools rows and the POST section stay put.+ expect(screen.getByRole('link', { name: 'Flows' })).toBeTruthy();+ expect(screen.getByRole('button', { name: 'POST' })).toBeTruthy();+ });++ it('drops the whole POST section when POST is off', async () => {+ featureMock.features = allFeaturesOn()+ .map((f) => (f.id === 'post' ? { ...f, enabled: false } : f));++ await renderLayout('/devtools/flows');++ expect(screen.queryByRole('button', { name: 'POST' })).toBeNull();+ expect(screen.getByRole('link', { name: 'DataDog' })).toBeTruthy();+ });++ it('shows everything when the feature list cannot be read', async () => {+ api.getInstanceFeatures.mockRejectedValueOnce(new Error('offline'));++ await renderLayout('/devtools/flows');++ expect(screen.getByRole('link', { name: 'DataDog' })).toBeTruthy();+ expect(screen.getByRole('button', { name: 'POST' })).toBeTruthy();+ });+});+describe('Layout — System Resources location state', () => {it('keeps Dev Tools expanded and System Resources active on every subtab', async () => {await renderLayout('/system-resources/storage');diff --git a/client/src/components/settings/InstanceFeaturesTab.jsx b/client/src/components/settings/InstanceFeaturesTab.jsxindex 91fb4c5521..85e1a71aec 100644--- a/client/src/components/settings/InstanceFeaturesTab.jsx+++ b/client/src/components/settings/InstanceFeaturesTab.jsx@@ -1,57 +1,48 @@-import { useCallback, useEffect, useState } from 'react';+import { useState } from 'react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import ToggleSwitch from '../ToggleSwitch';-import { getInstanceFeatures, updateInstanceFeature } from '../../services/api';+import { useInstanceFeatures, publishInstanceFeatures } from '../../hooks/useInstanceFeatures.js';+import { updateInstanceFeature } from '../../services/api';++// How the current value was decided, so a user who never touched the toggle can+// see that the install picked it up from a configured integration rather than+// guessing why a section is missing from the sidebar.+const sourceHint = (feature) => {+ if (feature.source !== 'auto') return null;+ return feature.enabled+ ? `Detected automatically — this install has ${feature.label} configured.`+ : `Detected automatically — no ${feature.label} instance is configured yet.`;+};export function InstanceFeaturesTab() {- const [features, setFeatures] = useState(null);- const [loadError, setLoadError] = useState(null);+ const { features, error, reload } = useInstanceFeatures();const [savingId, setSavingId] = useState(null);- const loadFeatures = useCallback(() => {- setLoadError(null);- getInstanceFeatures({ silent: true })- .then((data) => setFeatures(Array.isArray(data?.features) ? data.features : []))- .catch((error) => {- setFeatures(null);- setLoadError(error.message || 'Failed to load instance features');- });- }, []);-- useEffect(() => {- loadFeatures();- }, [loadFeatures]);-+ // The toggle is announced on the shared INSTANCE_FEATURES_CHANGED channel, so+ // the sidebar, the ⌘K palette, and the dashboard widgets that already listen+ // all follow it — no reload, and no second broadcast path to keep in step.const handleToggle = async (feature) => {if (!feature?.id || savingId) return;const enabled = !feature.enabled;- const previous = features;setSavingId(feature.id);- setFeatures((current) => current?.map((item) => (- item.id === feature.id ? { ...item, enabled } : item- )) || current);- const result = await updateInstanceFeature(feature.id, enabled, { silent: true }).catch((error) => {- toast.error(error.message || `Could not update ${feature.label}`);+ const result = await updateInstanceFeature(feature.id, enabled, { silent: true }).catch((err) => {+ toast.error(err.message || `Could not update ${feature.label}`);return null;});- if (!result) {- setFeatures(previous);- } else if (Array.isArray(result.features)) {- setFeatures(result.features);- }+ if (result) publishInstanceFeatures(result.features, { featureId: feature.id, enabled });setSavingId(null);};- if (loadError) {+ if (error) {return (<div className="space-y-3 max-w-3xl">- <p className="text-sm text-port-error">{loadError}</p>+ <p className="text-sm text-port-error">{error.message || 'Failed to load instance features'}</p><buttontype="button"- onClick={loadFeatures}+ onClick={reload}className="inline-flex items-center justify-center min-h-[44px] px-3 text-sm bg-port-border hover:bg-port-border/70 text-white rounded transition-colors">Retry@@ -67,32 +58,36 @@ export function InstanceFeaturesTab() {<div><h2 className="text-lg font-semibold text-white">Instance features</h2><p className="text-sm text-gray-400 mt-1">- Choose which optional PortOS features this install actively uses. Disabled features remain available when opened directly, but do not contribute passive metrics, reminders, or proactive prompts.+ Choose which optional PortOS features this install actively uses. A disabled feature drops out of the sidebar and the ⌘K palette, and stops contributing passive metrics, reminders, and proactive prompts — its pages stay reachable by direct link.</p></div><div className="space-y-3">- {features.map((feature) => (- <div- key={feature.id}- className="flex items-start justify-between gap-4 bg-port-card border border-port-border rounded-lg p-4"- >- <div className="min-w-0">- <h3 className="text-sm font-semibold text-white">{feature.label}</h3>- <p className="text-sm text-gray-400 mt-1">{feature.description}</p>- <p className={`text-xs mt-2 ${feature.enabled ? 'text-port-success' : 'text-gray-500'}`}>- {feature.enabled ? 'Active on this instance' : 'Not used on this instance'}- </p>+ {features.map((feature) => {+ const hint = sourceHint(feature);+ return (+ <div+ key={feature.id}+ className="flex items-start justify-between gap-4 bg-port-card border border-port-border rounded-lg p-4"+ >+ <div className="min-w-0">+ <h3 className="text-sm font-semibold text-white">{feature.label}</h3>+ <p className="text-sm text-gray-400 mt-1">{feature.description}</p>+ <p className={`text-xs mt-2 ${feature.enabled ? 'text-port-success' : 'text-gray-500'}`}>+ {feature.enabled ? 'Active on this instance' : 'Not used on this instance'}+ </p>+ {hint && <p className="text-xs text-gray-500 mt-1">{hint}</p>}+ </div>+ <ToggleSwitch+ enabled={feature.enabled}+ onChange={() => handleToggle(feature)}+ disabled={savingId !== null}+ ariaLabel={`${feature.enabled ? 'Disable' : 'Enable'} ${feature.label} on this instance`}+ className="mt-1"+ /></div>- <ToggleSwitch- enabled={feature.enabled}- onChange={() => handleToggle(feature)}- disabled={savingId !== null}- ariaLabel={`${feature.enabled ? 'Disable' : 'Enable'} ${feature.label} on this instance`}- className="mt-1"- />- </div>- ))}+ );+ })}{features.length === 0 && (<div className="bg-port-card border border-port-border rounded-lg p-4 text-sm text-gray-400">No optional features are registered for this version of PortOS.diff --git a/client/src/components/settings/InstanceFeaturesTab.test.jsx b/client/src/components/settings/InstanceFeaturesTab.test.jsxindex a146d2cc10..6a695366cc 100644--- a/client/src/components/settings/InstanceFeaturesTab.test.jsx+++ b/client/src/components/settings/InstanceFeaturesTab.test.jsx@@ -8,6 +8,7 @@ const mock = vi.hoisted(() => ({vi.mock('../../services/api', () => mock);+import { __resetInstanceFeatureCache } from '../../hooks/useInstanceFeatures.js';import InstanceFeaturesTab from './InstanceFeaturesTab';const POST_FEATURE = {@@ -15,13 +16,26 @@ const POST_FEATURE = {label: 'POST',description: 'Daily cognitive practice, progress metrics, and reminder prompts.',enabled: true,+ source: 'default',+};++const JIRA_FEATURE = {+ id: 'jira',+ label: 'JIRA',+ description: 'Sprint boards, ticket triage, and JIRA reports.',+ enabled: true,+ source: 'auto',+ configured: true,};describe('InstanceFeaturesTab', () => {beforeEach(() => {vi.clearAllMocks();+ // The feature list is cached at module scope and shared with the sidebar,+ // so it has to be dropped between tests.+ __resetInstanceFeatureCache();mock.getInstanceFeatures.mockResolvedValue({ features: [POST_FEATURE] });- mock.updateInstanceFeature.mockResolvedValue({ features: [{ ...POST_FEATURE, enabled: false }] });+ mock.updateInstanceFeature.mockResolvedValue({ features: [{ ...POST_FEATURE, enabled: false, source: 'explicit' }] });});it('shows the instance-local feature switch', async () => {@@ -42,4 +56,31 @@ describe('InstanceFeaturesTab', () => {expect(toggle).toHaveAttribute('aria-checked', 'false');expect(screen.getByText('Not used on this instance')).toBeInTheDocument();});++ it('explains an auto-detected value so a missing nav section is not a mystery', async () => {+ mock.getInstanceFeatures.mockResolvedValue({ features: [JIRA_FEATURE] });+ render(<InstanceFeaturesTab />);++ expect(await screen.findByText(/this install has JIRA configured/i)).toBeInTheDocument();+ });++ it('says an unconfigured integration is why the feature is off', async () => {+ mock.getInstanceFeatures.mockResolvedValue({+ features: [{ ...JIRA_FEATURE, enabled: false, configured: false }],+ });+ render(<InstanceFeaturesTab />);++ expect(await screen.findByText(/no JIRA instance is configured yet/i)).toBeInTheDocument();+ });++ it('offers a retry when the feature list cannot be read', async () => {+ mock.getInstanceFeatures.mockRejectedValueOnce(new Error('offline'));+ render(<InstanceFeaturesTab />);++ const retry = await screen.findByRole('button', { name: 'Retry' });+ mock.getInstanceFeatures.mockResolvedValue({ features: [POST_FEATURE] });+ fireEvent.click(retry);++ expect(await screen.findByRole('switch', { name: 'Disable POST on this instance' })).toBeInTheDocument();+ });});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 1070282550..38bc251c3f 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -144,6 +144,7 @@ grep -i "what you want to do" client/src/hooks/README.md| Hook | Purpose | Use when ||---|---|---|| `useFocusRefreshedList` | Load-once-then-refresh-on-focus list fetcher: debounces focus refreshes to 30s, sorts by name, and skips re-render when an `id\|name` signature is unchanged. Owns its own warn-on-error. | Any sidebar/nav list that should refresh when the user returns to the tab without hammering the API. Pass a stable `api.*` fetch fn. |+| `useInstanceFeatures` | Shared read of Settings > Features with a module-level cache, so the sidebar, ⌘K, and the Features tab collapse to one fetch. Returns `isFeatureEnabled(id)`; `publishInstanceFeatures` announces a toggle on the existing `INSTANCE_FEATURES_CHANGED` window event (the channel the reminder toast and the dashboard widgets already use). Fails open on a fetch error so navigation is never blanked. | Gating a sidebar row, page, palette entry, or widget on an optional instance feature (`post`, `datadog`, `jira`). Pair with `lib/navFeatures.js` for manifest entries. || `useSidebarApps` | Apps list for sidebar nav: socket-driven (`apps:changed`), archived filtered out, name-sorted. | The sidebar apps section. || `useSidebarSeries` | Pipeline series for the Create > Pipeline grandchildren (built on `useFocusRefreshedList`). | The sidebar pipeline-series section. || `useSidebarUniverses` | Universes for the Create > Universes grandchildren (built on `useFocusRefreshedList`). | The sidebar universes section. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex bf204e88ed..cb2d453a62 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -178,6 +178,7 @@ export * from './useNavWorkingSet.js';// === Sidebar navigation data ===export * from './useFocusRefreshedList.js';+export * from './useInstanceFeatures.js';export * from './useSidebarApps.js';export * from './useSidebarSeries.js';export * from './useSidebarUniverses.js';diff --git a/client/src/hooks/useInstanceFeatures.js b/client/src/hooks/useInstanceFeatures.jsnew file mode 100644index 0000000000..9a10aaa685--- /dev/null+++ b/client/src/hooks/useInstanceFeatures.js@@ -0,0 +1,113 @@+import { useCallback, useEffect, useState } 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;+let inFlight = null;++const loadInstanceFeatures = () => {+ if (!inFlight) {+ inFlight = 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) => {+ cached = result;+ inFlight = null;+ return result;+ });+ }+ return inFlight;+};++/**+ * @returns {{+ * features: Array|null, // null while loading or after a failed fetch+ * error: Error|null,+ * isFeatureEnabled: (featureId: string) => boolean,+ * reload: () => Promise<void>,+ * }}+ *+ * `isFeatureEnabled` answers for navigation gating:+ * - loaded → the stored/auto-resolved value; an unregistered id is enabled+ * (an unknown gate must never erase a page)+ * - loading → false, so a gated row appears once rather than flashing away+ * - 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;+ 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 isFeatureEnabled = useCallback((featureId) => {+ if (!featureId) return true;+ if (error) return true;+ if (features === null) return false;+ const feature = features.find((item) => item?.id === featureId);+ return feature ? feature.enabled !== false : true;+ }, [features, error]);++ const reload = useCallback(() => {+ cached = null;+ return loadInstanceFeatures().then((result) => setState(result));+ }, []);++ return { features, error, isFeatureEnabled, reload };+}++/**+ * Announce a feature change on the shared channel. Pass the server's fresh+ * `features` list so every listener applies it without a second round-trip.+ */+export const publishInstanceFeatures = (features, { featureId, enabled } = {}) => {+ window.dispatchEvent(new CustomEvent(INSTANCE_FEATURES_CHANGED, {+ detail: { featureId, enabled, features: Array.isArray(features) ? features : undefined },+ }));+};++// Test-only: drop the module cache so suites don't leak state between tests.+export const __resetInstanceFeatureCache = () => {+ cached = null;+ inFlight = null;+};diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 27248516ac..4917409b91 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -17,6 +17,7 @@ is the contract.grep -i "what you want to do" client/src/lib/README.md```+| `navFeatures.js` | `filterNavByFeatures(navEntries, isFeatureEnabled)` — drops nav-manifest entries whose optional instance feature (`post`, `datadog`, `jira`) is off. The single gate for BROWSE surfaces (sidebar, ⌘K); routes stay reachable by URL, bookmark, and voice. Pair with `useInstanceFeatures`. || `postQuickSession.js` | Pure Quick POST duration presets, local-observation estimator, deterministic budget composer, and preview metadata. |---diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 1f39af6eac..1944a79f94 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -130,6 +130,7 @@ export * from './editorialHealth.js';export * from './lookaheadTransport.js';export * from './lossSparkline.js';export * from './metronome.js';+export * from './navFeatures.js';export * from './midiChords.js';export * from './midiNotes.js';export * from './midiPlayback.js';diff --git a/client/src/lib/navFeatures.js b/client/src/lib/navFeatures.jsnew file mode 100644index 0000000000..3132f2b5e9--- /dev/null+++ b/client/src/lib/navFeatures.js@@ -0,0 +1,22 @@+// The one gate every BROWSE surface applies to the nav manifest.+//+// `GET /api/palette/manifest` ships each entry's optional `feature` tag rather+// than pre-filtering, so the response stays HTTP-cacheable and shared across the+// three consumers that fetch it. The gate is applied here instead, on the client+// that holds the user's live feature state — which is also what makes a toggle+// in Settings > Features take effect without a reload (⌘K and the voice widget+// both cache the manifest for the session).+//+// Gating covers browse surfaces only: the sidebar and ⌘K. A route stays live and+// navigable by URL, bookmark, or voice `ui_navigate`, exactly as a disabled+// feature's page stays reachable when opened directly.++/**+ * @param {Array<{feature?: string}>} navEntries manifest entries+ * @param {(featureId?: string) => boolean} isFeatureEnabled from `useInstanceFeatures`+ */+export const filterNavByFeatures = (navEntries, isFeatureEnabled) => (+ (navEntries || []).filter((entry) => isFeatureEnabled(entry?.feature))+);++export default filterNavByFeatures;diff --git a/server/lib/README.md b/server/lib/README.mdindex 6e0e6fb587..4eaa38411a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -145,6 +145,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. || `usageRange.js` | `resolveUsageRange({ period, from, to })` — pure period→inclusive-YYYY-MM-DD range resolution for the usage cost report (explicit dates win; `all` unbounded; default 7d). || `subscriptionSavings.js` | Subscription-vs-API savings math for the usage page — `resolveSavingsWindow` (clamps an open-ended report range to today / first activity day), `prorateMonthlyCost` (monthly plan price → this window's share, `DAYS_PER_MONTH`, capped by `MAX_MONTHLY_COST`), `savingsPercent` / `costMultiplier` (null, never 0, when the comparison is undefined), `attributeReportCostToFamilies` (groups report rows by their stamped `family`), `roundCents` (the one money rounder), and `buildSubscriptionSavings({ entries, range, unmatchedApiCost })` → per-family rows + totals. Pure. |+| `instanceFeatureRegistry.js` | The registry of optional per-install features (`INSTANCE_FEATURES`, `INSTANCE_FEATURE_IDS`, `isInstanceFeatureId`) — pure data, so `validation.js` derives its feature schemas from it and `navManifest.js` can be checked against it without a service→lib inversion. Runtime resolution (stored override → auto-detection → `defaultEnabled`) lives in `services/instanceFeatures.js`. A feature id tagged on a nav entry hides that page from ⌘K and the sidebar when the feature is off. || `providerFamilies.js` | Subscription-quota FAMILY identity — `PROVIDER_FAMILIES` (`{ id, label, matches }` for claude/codex/agy/grok), `PROVIDER_FAMILY_IDS`, `familyLabel`, `familyForProvider(config)` → family id or null (local-runtime wrappers and API-only providers belong to none). The pure half of the registry `services/providerUsage.js` attaches quota `fetch`ers to, so cost attribution and route validation can ask "which plan is this provider on?" without importing the PTY-scrape graph. Distinct from `providerVendors.js`, which is argv-shaped and includes vendors with no subscription quota. || `providerGateways.js` | `PROVIDER_GATEWAYS` — one row per hosted OpenAI-compatible gateway an OpenCode CLI/TUI wrapper can front-end (`orcarouter`, `openrouter`), plus `PROVIDER_GATEWAY_IDS`, `gatewayById`, `isGatewayNamespace(ns)` and `gatewayForProvider(config)` → row or null. Each row's `id` is simultaneously the OpenCode provider namespace, the `gatewayBacked` marker value, and the id of the sibling `api` record that owns the key — so the sibling lookup is `providers[gateway.id]` and an OrcaRouter key can never satisfy an OpenRouter wrapper. Replaces the `orcarouterBacked` boolean + literal `'orcarouter'` that had been hand-copied across ~15 server and client files (namespace resolution, the OpenCode config builder, both zod schemas, the model-fetcher table, the sibling-key attach, the prerequisite check, and the two "not a local runtime" carve-outs in `cliChildEnv.js`/`localProviderRuntime.js`). Reads the legacy per-gateway boolean FOREVER, so stored records are never rewritten. Distinct from a local runtime (`ollamaBacked`, `vllmBacked`, …): remote, always authenticating, and no thinking toggle. Deliberately mirrored in `aiToolkit/internal/gateways.js` (the vendored toolkit may not import out) and `client/src/utils/providers.js` (the browser cannot import server code) — `providerGateways.parity.test.js` fails when the first two drift. Dependency-light: imports nothing. || `providerTranscriptUsage.js` | Parsers for the real per-message token counts the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Both de-duplicate a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, and Codex's `total_token_usage` is cumulative and repeated. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. |diff --git a/server/lib/index.js b/server/lib/index.jsindex d33c95b0a4..2f66732622 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -321,6 +321,7 @@ export * from './mediaItemKey.js';export * from './migrationMarker.js';export * from './modelPricing.js';export * from './navManifest.js';+export * from './instanceFeatureRegistry.js';export * from './usageRange.js';export * from './subscriptionSavings.js';export * from './providerFamilies.js';diff --git a/server/lib/instanceFeatureRegistry.js b/server/lib/instanceFeatureRegistry.jsnew file mode 100644index 0000000000..ae604598d2--- /dev/null+++ b/server/lib/instanceFeatureRegistry.js@@ -0,0 +1,39 @@+// The registry of optional per-install features — the single list that Settings+// > Features renders, `server/lib/validation.js` validates against, and+// `server/lib/navManifest.js` gates navigation on.+//+// It lives in lib/ (pure data, no I/O) so both a lib and a service can read it+// without a service→lib inversion. Runtime resolution — stored overrides,+// auto-detection, the enabled/disabled answer — is+// `server/services/instanceFeatures.js`.+//+// Adding a feature:+// 1. add a descriptor here;+// 2. tag its pages in navManifest.js (`feature: '<id>'`, or a SECTION_FEATURE+// entry when a whole sidebar section belongs to it) and the matching rows+// in client/src/components/Layout.jsx;+// 3. add a `detect` hook in services/instanceFeatures.js when a fresh install+// should infer the default from whether the integration is configured.+// The validation schemas and the Features tab pick it up with no further edit.+export const INSTANCE_FEATURES = Object.freeze([+ Object.freeze({+ id: 'post',+ label: 'POST',+ description: 'Daily cognitive practice, progress metrics, and reminder prompts.',+ defaultEnabled: true,+ }),+ Object.freeze({+ id: 'datadog',+ label: 'DataDog',+ description: 'Error monitoring dashboards for apps wired to a DataDog instance.',+ defaultEnabled: false,+ }),+ Object.freeze({+ id: 'jira',+ label: 'JIRA',+ description: 'Sprint boards, ticket triage, and JIRA reports for apps wired to a JIRA instance.',+ defaultEnabled: false,+ }),+]);++export const INSTANCE_FEATURE_IDS = Object.freeze(INSTANCE_FEATURES.map((feature) => feature.id));diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex b440da7f5f..a1f1d5f542 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -52,7 +52,16 @@ const OPEN_WORLD_REGION_COMMANDS = [keywords: ['openworld', 'fast travel', 'warp', 'region', 'teleport'],}));-export const NAV_COMMANDS = [+// Sections whose every page belongs to one optional instance feature, so a page+// added there inherits the gate with no edit. A single page inside an otherwise+// ungated section (DataDog, JIRA) carries `feature` on its own entry instead.+// Keys must be real section labels and values must be ids declared in+// server/lib/instanceFeatureRegistry.js — navManifest.test.js fails on both+// kinds of drift, because a stale key here would silently un-gate a section+// with every other assertion still green.+export const SECTION_FEATURE = new Map([['POST', 'post']]);++const RAW_NAV_COMMANDS = [{ id: 'nav.dashboard', path: '/', label: 'Dashboard', section: 'Main', aliases: ['dashboard', 'home'], keywords: ['overview', 'start'] },{ id: 'nav.review-hub', path: '/review', label: 'Review Hub', section: 'Main', aliases: ['review', 'review-hub'] },{ id: 'nav.cybercity', path: '/openworld', label: 'OpenWorld', section: 'Main', previousPaths: ['/city'], aliases: ['openworld', 'open world', 'open-world', 'city'], keywords: ['3d', 'visualization', 'game', 'map', 'explore'] },@@ -173,13 +182,13 @@ export const NAV_COMMANDS = [{ id: 'nav.devtools.agents', path: '/devtools/agents', label: 'AI Agents', section: 'Dev Tools', aliases: ['ai-agents', 'devtools'] },{ id: 'nav.browser', path: '/browser', label: 'Browser', section: 'Dev Tools', aliases: ['browser'] },{ id: 'nav.devtools.runner', path: '/devtools/runner', label: 'Code', section: 'Dev Tools', aliases: ['devtools-runner'] },- { id: 'nav.devtools.datadog', path: '/devtools/datadog', label: 'DataDog', section: 'Dev Tools', previousPaths: ['/datadog'], aliases: ['datadog', 'devtools-datadog'] },+ { id: 'nav.devtools.datadog', path: '/devtools/datadog', label: 'DataDog', section: 'Dev Tools', feature: 'datadog', previousPaths: ['/datadog'], aliases: ['datadog', 'devtools-datadog'] },{ id: 'nav.devtools.flows', path: '/devtools/flows', label: 'Flows', section: 'Dev Tools', aliases: ['flows', 'integration-flows', 'workflows'], keywords: ['architecture', 'diagram', 'data flow', 'integrations', 'how it works'] },{ id: 'nav.devtools.github', path: '/devtools/github', label: 'GitHub', section: 'Dev Tools', aliases: ['github', 'devtools-github'] },{ id: 'nav.devtools.history', path: '/devtools/history', label: 'History', section: 'Dev Tools', aliases: ['devtools-history'] },{ id: 'nav.devtools.image-clean', path: '/devtools/image-clean', label: 'Image Cleaner', section: 'Dev Tools', aliases: ['image-clean', 'image-cleaner'], keywords: ['metadata', 'c2pa', 'content-credentials', 'sharp', 'denoise'] },- { id: 'nav.devtools.jira', path: '/devtools/jira', label: 'JIRA', section: 'Dev Tools', previousPaths: ['/jira'], aliases: ['jira', 'devtools-jira'] },- { id: 'nav.devtools.jira-reports', path: '/devtools/jira/reports', label: 'JIRA Reports', section: 'Dev Tools', aliases: ['jira-reports'] },+ { id: 'nav.devtools.jira', path: '/devtools/jira', label: 'JIRA', section: 'Dev Tools', feature: 'jira', previousPaths: ['/jira'], aliases: ['jira', 'devtools-jira'] },+ { id: 'nav.devtools.jira-reports', path: '/devtools/jira/reports', label: 'JIRA Reports', section: 'Dev Tools', feature: 'jira', aliases: ['jira-reports'] },{ id: 'nav.devtools.quota-burn', path: '/devtools/quota-burn', label: 'Quota Burn', section: 'Dev Tools', aliases: ['quota-burn', 'burn-quota', 'quota'], keywords: ['subscription', 'usage', 'reset window', 'spend quota', 'claude', 'codex', 'grok', 'agy', 'burn'] },{ id: 'nav.shell', path: '/shell', label: 'Shell', section: 'Dev Tools', aliases: ['shell', 'terminal'] },{ id: 'nav.devtools.usage', path: '/devtools/usage', label: 'Usage', section: 'Dev Tools', aliases: ['devtools-usage'] },@@ -332,6 +341,26 @@ export const NAV_COMMANDS = [{ id: 'nav.wiki.search', path: '/wiki/search', label: 'Search', section: 'Brain', aliases: ['wiki-search'] },];+// A gated entry carries `feature`: the id of the optional instance feature it+// belongs to (server/lib/instanceFeatureRegistry.js). The manifest ships the tag+// rather than dropping the entry, and the GATE IS APPLIED CLIENT-SIDE — by the+// sidebar and the ⌘K palette, which both hold the user's live feature state and+// so react to a toggle without a reload. Filtering here instead would defeat the+// manifest's HTTP caching and still leave ⌘K stale, because it caches the+// manifest for the session.+//+// Gating hides a page from those two BROWSE surfaces only. The route keeps+// working, and so does navigating to it by name — a bookmark, a direct URL, or+// voice `ui_navigate` all still resolve, the same way a disabled feature's page+// stays reachable when opened directly.+export const NAV_COMMANDS = RAW_NAV_COMMANDS.map((cmd) => {+ const feature = cmd.feature || SECTION_FEATURE.get(cmd.section);+ return feature ? { ...cmd, feature } : cmd;+});++// Every feature id this manifest gates on, for the registry-drift guard.+export const NAV_FEATURE_IDS = [...new Set(NAV_COMMANDS.map((c) => c.feature).filter(Boolean))].sort();+const seenIds = new Set();for (const cmd of NAV_COMMANDS) {if (!cmd.id || !cmd.path || !cmd.label || !cmd.section) {diff --git a/server/lib/navManifest.test.js b/server/lib/navManifest.test.jsindex 3b8f1faff0..e0c2be022b 100644--- a/server/lib/navManifest.test.js+++ b/server/lib/navManifest.test.js@@ -2,7 +2,8 @@ import { describe, it, expect } from 'vitest';import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';-import { NAV_COMMANDS, getNavAliasMap, resolveNavCommand } from './navManifest.js';+import { NAV_COMMANDS, NAV_FEATURE_IDS, SECTION_FEATURE, getNavAliasMap, resolveNavCommand } from './navManifest.js';+import { INSTANCE_FEATURE_IDS } from './instanceFeatureRegistry.js';import { PORTOS_APP_ID } from './appIdentity.js';const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -143,6 +144,74 @@ describe('navManifest — shape invariants', () => {});});+// Feature gating hides a page from the ⌘K palette and the sidebar. A typo in a+// `feature` tag would silently gate on a flag nothing can ever turn on, hiding+// the page on every install with no other symptom.+describe('nav contract — instance-feature gating', () => {+ it('every gated entry names a registered instance feature', () => {+ const unknown = NAV_FEATURE_IDS.filter((id) => !INSTANCE_FEATURE_IDS.includes(id));+ expect(unknown).toEqual([]);+ });++ // SECTION_FEATURE keys on the DISPLAY label, so renaming a section would+ // un-gate it silently — and every other assertion here would still pass,+ // because they filter on that same label and would simply match nothing.+ it('every SECTION_FEATURE key is a live section carrying that gate', () => {+ for (const [section, featureId] of SECTION_FEATURE) {+ const inSection = NAV_COMMANDS.filter((c) => c.section === section);+ expect(inSection.length, `no commands in section "${section}"`).toBeGreaterThan(0);+ expect(INSTANCE_FEATURE_IDS, `unregistered feature "${featureId}"`).toContain(featureId);+ expect(inSection.every((c) => c.feature === featureId)).toBe(true);+ }+ });++ it('gates the DataDog and JIRA Dev Tools pages', () => {+ const byId = Object.fromEntries(NAV_COMMANDS.map((c) => [c.id, c.feature]));+ expect(byId['nav.devtools.datadog']).toBe('datadog');+ expect(byId['nav.devtools.jira']).toBe('jira');+ expect(byId['nav.devtools.jira-reports']).toBe('jira');+ });++ it('leaves ungated pages untagged', () => {+ const gated = NAV_COMMANDS.filter((c) => c.feature).map((c) => c.id);+ expect(gated).toContain('nav.devtools.jira');+ expect(gated).not.toContain('nav.dashboard');+ expect(gated).not.toContain('nav.devtools.flows');+ });++ // The sidebar is a SEPARATE list from this manifest, so the two can drift: a+ // page gated here but untagged there stays visible in the sidebar while ⌘K+ // hides it, and vice versa. Scrape Layout's own path→feature pairs and require+ // them to agree with the manifest in BOTH directions.+ it('the sidebar tags exactly the paths this manifest gates', () => {+ const layout = fs.readFileSync(path.join(REPO_ROOT, 'client/src/components/Layout.jsx'), 'utf8');+ // Rows are one-liners: { to: '/devtools/jira', label: …, feature: 'jira' }.+ const layoutRows = [...layout.matchAll(/\{[^{}\n]*\bto:\s*'([^']+)'[^{}\n]*\}/g)]+ .map((m) => ({ path: m[1], feature: /\bfeature:\s*'([^']+)'/.exec(m[0])?.[1] || null }));+ expect(layoutRows.length).toBeGreaterThan(50);++ // A SECTION-level gate is carried by the sidebar's parent row, not repeated+ // on each child, so those paths are expected to be untagged here — the+ // section-level check below covers them.+ const sectionGated = new Set(SECTION_FEATURE.values());+ const expectedFeature = (cmd) => (cmd.feature && !sectionGated.has(cmd.feature) ? cmd.feature : null);+ const manifestFeatureByPath = new Map(NAV_COMMANDS.map((c) => [c.path, expectedFeature(c)]));+ const drift = layoutRows+ .filter((row) => manifestFeatureByPath.has(row.path))+ .filter((row) => manifestFeatureByPath.get(row.path) !== row.feature)+ .map((row) => `${row.path}: sidebar=${row.feature} manifest=${manifestFeatureByPath.get(row.path)}`);+ expect(drift).toEqual([]);+ });++ // A whole gated SECTION carries the tag on its parent row instead of on each+ // child, so the per-path check above can't see it.+ it('the sidebar gates each section-level feature on its parent row', () => {+ const layout = fs.readFileSync(path.join(REPO_ROOT, 'client/src/components/Layout.jsx'), 'utf8');+ const missing = [...SECTION_FEATURE.values()].filter((id) => !layout.includes(`feature: '${id}'`));+ expect(missing).toEqual([]);+ });+});+describe('resolveNavCommand — fuzzy matching', () => {it('resolves exact alias', () => {expect(resolveNavCommand('dashboard')?.path).toBe('/');diff --git a/server/lib/validation.js b/server/lib/validation.jsindex ccd151c2e7..6b39d12071 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -3,6 +3,7 @@ import { ServerError } from './errorHandler.js';import { partialWithoutDefaults, emptyToUndefined, emptyToNull, optionalBooleanMap } from './zodCompat.js';import { WORK_TRACKERS } from './workTracker.js';import { PROVIDER_FAMILY_IDS } from './providerFamilies.js';+import { INSTANCE_FEATURE_IDS } from './instanceFeatureRegistry.js';import { MAX_MONTHLY_COST } from './subscriptionSavings.js';import { QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODES } from './generationModes.js';import { RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';@@ -767,16 +768,18 @@ export const apiAccessSettingsSchema = z.object({sdapi: apiAccessEntrySchema.optional(),}).strict();-// Install-local feature participation flags. The registry owns the available-// feature ids; this schema keeps generic settings saves from persisting an-// unknown or malformed feature state.-export const instanceFeatureSettingsSchema = z.object({- post: z.object({- enabled: z.boolean().optional(),- }).strict().optional(),-}).strict();--export const instanceFeatureIdSchema = z.enum(['post']);+// Install-local feature participation flags. `instanceFeatureRegistry.js` owns+// the available feature ids and both schemas derive from it, so registering a+// feature there needs no edit here; the schemas keep generic settings saves from+// persisting an unknown or malformed feature state.+export const instanceFeatureSettingsSchema = z.object(+ Object.fromEntries(INSTANCE_FEATURE_IDS.map((id) => [+ id,+ z.object({ enabled: z.boolean().optional() }).strict().optional(),+ ]))+).strict();++export const instanceFeatureIdSchema = z.enum([...INSTANCE_FEATURE_IDS]);export const instanceFeatureUpdateSchema = z.object({enabled: z.boolean(),diff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsindex 8d25808e4d..01122dba45 100644--- a/server/routes/settings.test.js+++ b/server/routes/settings.test.js@@ -102,7 +102,11 @@ describe('Settings routes — instance feature participation', () => {const res = await request(buildApp()).get('/api/settings/features');expect(res.status).toBe(200);- expect(res.body.features).toEqual([expect.objectContaining({ id: 'post', label: 'POST', enabled: true })]);+ expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'post', label: 'POST', enabled: true }));+ // Integration-backed features ride the same list; with nothing configured+ // they resolve off, which is what hides their nav entries.+ expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'datadog', enabled: false }));+ expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'jira', enabled: false }));});it('updates one feature without replacing unrelated settings', async () => {@@ -113,7 +117,7 @@ describe('Settings routes — instance feature participation', () => {.send({ enabled: false });expect(res.status).toBe(200);- expect(res.body.features).toEqual([expect.objectContaining({ id: 'post', enabled: false })]);+ expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'post', enabled: false }));expect(store).toEqual({ theme: 'dark', instanceFeatures: { post: { enabled: false } } });});diff --git a/server/services/datadog.js b/server/services/datadog.jsindex 4ac0fe5b4e..c73e6df2a3 100644--- a/server/services/datadog.js+++ b/server/services/datadog.js@@ -29,6 +29,14 @@ export async function getInstances() {return await readJSONFile(DATADOG_CONFIG_FILE, { instances: {} });}+// Whether this install has any DataDog instance configured — the signal the+// instance-feature registry uses to decide whether the DataDog nav entries+// should appear before the user has toggled the feature explicitly.+export async function hasConfiguredInstances() {+ const config = await getInstances();+ return Object.keys(config?.instances || {}).length > 0;+}+/*** Save DataDog instances configuration*/diff --git a/server/services/instanceFeatures.js b/server/services/instanceFeatures.jsindex a1d09e6a01..c291a7e8d6 100644--- a/server/services/instanceFeatures.js+++ b/server/services/instanceFeatures.js@@ -1,50 +1,118 @@import { ServerError } from '../lib/errorHandler.js';+import { INSTANCE_FEATURES, INSTANCE_FEATURE_IDS } from '../lib/instanceFeatureRegistry.js';import { isPlainObject } from '../lib/objects.js';import { getSettingsWithStatus, updateSettingsWith } from './settings.js';-// Instance features are local to one PortOS install. They are deliberately-// separate from per-feature configuration so a feature can remain available-// when opened directly while its passive metrics, reminders, and proactive-// prompts stay quiet on installs that do not use it.-export const INSTANCE_FEATURES = Object.freeze([- Object.freeze({- id: 'post',- label: 'POST',- description: 'Daily cognitive practice, progress metrics, and reminder prompts.',- defaultEnabled: true,- }),-]);+// Runtime resolution for the feature registry in+// server/lib/instanceFeatureRegistry.js. Instance features are local to one+// PortOS install. They are deliberately separate from per-feature configuration+// so a feature can remain available when opened directly while its passive+// metrics, reminders, proactive prompts, and NAVIGATION ENTRIES stay quiet on+// installs that do not use it.+//+// A feature gates navigation by tagging nav-manifest entries with its id+// (`feature: 'jira'` in server/lib/navManifest.js) and the matching sidebar rows+// in client/src/components/Layout.jsx. Adding a page to a gated section — or to+// a section listed in navManifest's SECTION_FEATURE map — inherits the gate with+// no edit here. navManifest.test.js fails when a nav entry names a feature id+// the registry does not declare.+//+// A DETECTOR is the fresh-install default: a feature the user has never toggled+// shows up only when the integration it fronts is actually configured. It+// returns `null` when detection itself fails, which falls back to+// `defaultEnabled` rather than silently hiding a working integration.+const DETECTORS = {+ datadog: async () => {+ const { hasConfiguredInstances } = await import('./datadog.js');+ return hasConfiguredInstances();+ },+ jira: async () => {+ const { hasConfiguredInstances } = await import('./jira.js');+ return hasConfiguredInstances();+ },+};const FEATURE_BY_ID = new Map(INSTANCE_FEATURES.map((feature) => [feature.id, feature]));-const featureEnabled = (feature, settings) => {+// The stored override for one feature: `true`/`false` when the user has toggled+// it, `null` when they never have. `null` is the signal that detection (and then+// `defaultEnabled`) decides — distinct from a stored `false`, which must keep+// the feature off even once the integration is configured.+const storedOverride = (feature, settings) => {const instanceFeatures = settings?.instanceFeatures;- if (instanceFeatures === undefined) return feature.defaultEnabled;+ if (instanceFeatures === undefined) return null;if (!isPlainObject(instanceFeatures)) return false;- if (!Object.prototype.hasOwnProperty.call(instanceFeatures, feature.id)) return feature.defaultEnabled;+ if (!Object.prototype.hasOwnProperty.call(instanceFeatures, feature.id)) return null;const featureSettings = instanceFeatures[feature.id];if (!isPlainObject(featureSettings)) return false;const stored = featureSettings.enabled;- if (stored === undefined) return feature.defaultEnabled;+ if (stored === undefined) return null;return typeof stored === 'boolean' ? stored : false;};-export const resolveInstanceFeatures = (settings = {}, { corrupt = false } = {}) => INSTANCE_FEATURES.map((feature) => ({- ...feature,- enabled: !corrupt && featureEnabled(feature, settings),-}));+const resolveOne = (feature, settings, detected) => {+ const override = storedOverride(feature, settings);+ if (override !== null) return { enabled: override, source: 'explicit' };++ const configured = detected?.[feature.id];+ if (typeof configured === 'boolean') return { enabled: configured, source: 'auto' };+ return { enabled: feature.defaultEnabled, source: 'default' };+};++// One feature's detector: `true`/`false` when it answered, `null` when the+// feature has no detector or the probe threw — so the caller falls back to+// `defaultEnabled` rather than reading a failed probe as "not configured".+const runDetector = async (featureId) => {+ if (typeof DETECTORS[featureId] !== 'function') return null;+ const configured = await DETECTORS[featureId]().catch((error) => {+ console.error(`❌ Instance feature "${featureId}" detection failed: ${error.message}`);+ return null;+ });+ return typeof configured === 'boolean' ? configured : null;+};++export async function detectFeatureConfiguration() {+ return Object.fromEntries(await Promise.all(+ INSTANCE_FEATURE_IDS.map(async (id) => [id, await runDetector(id)]),+ ));+}++export const resolveInstanceFeatures = (settings = {}, { corrupt = false, detected = {} } = {}) => (+ INSTANCE_FEATURES.map((feature) => {+ const { enabled, source } = corrupt+ ? { enabled: false, source: 'default' }+ : resolveOne(feature, settings, detected);+ return {+ ...feature,+ enabled,+ // How `enabled` was decided, so the Features tab can say whether the user+ // set it or the install auto-detected the integration.+ source,+ };+ })+);export async function getInstanceFeatures() {- const { corrupt, settings } = await getSettingsWithStatus();- return { features: resolveInstanceFeatures(settings, { corrupt }) };+ const [{ corrupt, settings }, detected] = await Promise.all([+ getSettingsWithStatus(),+ detectFeatureConfiguration(),+ ]);+ return { features: resolveInstanceFeatures(settings, { corrupt, detected }) };}+// The same precedence ladder as `resolveInstanceFeatures`, but probing only this+// feature's detector — the single-feature callers (reminders, metrics, signal+// readers) must not pay for the others' disk reads.export async function isInstanceFeatureEnabled(featureId) {const feature = FEATURE_BY_ID.get(featureId);if (!feature) return false;const { corrupt, settings } = await getSettingsWithStatus();- return !corrupt && featureEnabled(feature, settings);+ if (corrupt) return false;++ const override = storedOverride(feature, settings);+ if (override !== null) return override;+ return resolveOne(feature, settings, { [featureId]: await runDetector(featureId) }).enabled;}export async function updateInstanceFeature(featureId, enabled) {@@ -64,5 +132,6 @@ export async function updateInstanceFeature(featureId, enabled) {};});- return { features: resolveInstanceFeatures(settings) };+ const detected = await detectFeatureConfiguration();+ return { features: resolveInstanceFeatures(settings, { detected }) };}diff --git a/server/services/instanceFeatures.test.js b/server/services/instanceFeatures.test.jsindex 6d5f88898c..0fd7d11721 100644--- a/server/services/instanceFeatures.test.js+++ b/server/services/instanceFeatures.test.js@@ -1,23 +1,47 @@import { describe, expect, it, vi, beforeEach } from 'vitest';-const mock = vi.hoisted(() => ({ settings: {}, corrupt: false, updateSettingsWith: vi.fn() }));+const mock = vi.hoisted(() => ({+ settings: {},+ corrupt: false,+ updateSettingsWith: vi.fn(),+ datadogConfigured: false,+ jiraConfigured: false,+ datadogThrows: false,+}));vi.mock('./settings.js', () => ({getSettingsWithStatus: vi.fn(async () => ({ corrupt: mock.corrupt, settings: structuredClone(mock.settings) })),updateSettingsWith: mock.updateSettingsWith,}));+vi.mock('./datadog.js', () => ({+ hasConfiguredInstances: vi.fn(async () => {+ if (mock.datadogThrows) throw new Error('datadog.json unreadable');+ return mock.datadogConfigured;+ }),+}));++vi.mock('./jira.js', () => ({+ hasConfiguredInstances: vi.fn(async () => mock.jiraConfigured),+}));+import {+ detectFeatureConfiguration,getInstanceFeatures,isInstanceFeatureEnabled,resolveInstanceFeatures,updateInstanceFeature,} from './instanceFeatures.js';+const byId = (features, id) => features.find((feature) => feature.id === id);+describe('instance features', () => {beforeEach(() => {mock.settings = {};mock.corrupt = false;+ mock.datadogConfigured = false;+ mock.jiraConfigured = false;+ mock.datadogThrows = false;mock.updateSettingsWith.mockReset();mock.updateSettingsWith.mockImplementation(async (mutate) => {mock.settings = await mutate(structuredClone(mock.settings));@@ -27,20 +51,21 @@ describe('instance features', () => {it('keeps POST enabled by default for existing installs', async () => {expect(await isInstanceFeatureEnabled('post')).toBe(true);- expect((await getInstanceFeatures()).features[0]).toMatchObject({ id: 'post', enabled: true });+ expect(byId((await getInstanceFeatures()).features, 'post')).toMatchObject({ id: 'post', enabled: true });});it('resolves an explicit disable without changing POST configuration', () => {- expect(resolveInstanceFeatures({ instanceFeatures: { post: { enabled: false } } })[0]).toMatchObject({+ expect(byId(resolveInstanceFeatures({ instanceFeatures: { post: { enabled: false } } }), 'post')).toMatchObject({id: 'post',enabled: false,+ source: 'explicit',});});it('fails closed for malformed persisted feature flags', async () => {const settings = { instanceFeatures: { post: { enabled: 'false' } } };- expect(resolveInstanceFeatures(settings)[0]).toMatchObject({ id: 'post', enabled: false });+ expect(byId(resolveInstanceFeatures(settings), 'post')).toMatchObject({ id: 'post', enabled: false });mock.settings = settings;expect(await isInstanceFeatureEnabled('post')).toBe(false);});@@ -48,9 +73,9 @@ describe('instance features', () => {it('fails closed when settings cannot be read or parsed', async () => {mock.corrupt = true;- expect(resolveInstanceFeatures({}, { corrupt: true })[0]).toMatchObject({ id: 'post', enabled: false });+ expect(byId(resolveInstanceFeatures({}, { corrupt: true }), 'post')).toMatchObject({ id: 'post', enabled: false });expect(await isInstanceFeatureEnabled('post')).toBe(false);- expect((await getInstanceFeatures()).features[0]).toMatchObject({ id: 'post', enabled: false });+ expect(byId((await getInstanceFeatures()).features, 'post')).toMatchObject({ id: 'post', enabled: false });});it('updates one feature inside the instance-local settings slice', async () => {@@ -62,7 +87,75 @@ describe('instance features', () => {theme: 'dark',instanceFeatures: { post: { enabled: false, future: 'keep' } },});- expect(result.features[0]).toMatchObject({ id: 'post', enabled: false });+ expect(byId(result.features, 'post')).toMatchObject({ id: 'post', enabled: false });expect(await isInstanceFeatureEnabled('post')).toBe(false);});++ describe('auto-detection for integration-backed features', () => {+ it('keeps DataDog and JIRA off on an install with no instances configured', async () => {+ const { features } = await getInstanceFeatures();+ expect(byId(features, 'datadog')).toMatchObject({ enabled: false, source: 'auto' });+ expect(byId(features, 'jira')).toMatchObject({ enabled: false, source: 'auto' });+ expect(await isInstanceFeatureEnabled('jira')).toBe(false);+ });++ it('turns a feature on once its integration is configured', async () => {+ mock.jiraConfigured = true;++ const { features } = await getInstanceFeatures();+ expect(byId(features, 'jira')).toMatchObject({ enabled: true, source: 'auto' });+ expect(byId(features, 'datadog')).toMatchObject({ enabled: false });+ expect(await isInstanceFeatureEnabled('jira')).toBe(true);+ });++ it('lets an explicit disable outrank a configured integration', async () => {+ mock.jiraConfigured = true;+ mock.settings = { instanceFeatures: { jira: { enabled: false } } };++ expect(byId((await getInstanceFeatures()).features, 'jira')).toMatchObject({+ enabled: false,+ source: 'explicit',+ });+ expect(await isInstanceFeatureEnabled('jira')).toBe(false);+ });++ it('lets an explicit enable outrank an unconfigured integration', async () => {+ mock.settings = { instanceFeatures: { datadog: { enabled: true } } };++ expect(byId((await getInstanceFeatures()).features, 'datadog')).toMatchObject({+ enabled: true,+ source: 'explicit',+ });+ expect(await isInstanceFeatureEnabled('datadog')).toBe(true);+ });++ it('falls back to the default (not "unconfigured") when detection itself fails', async () => {+ mock.datadogThrows = true;++ 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);+ });++ 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' });+ });+ });++ it('answers for every registered feature, so nothing is silently ungated', async () => {+ mock.datadogConfigured = true;++ const { features } = await getInstanceFeatures();+ expect(Object.fromEntries(features.map((f) => [f.id, f.enabled])))+ .toEqual({ post: true, datadog: true, jira: false });+ });++ it('rejects an unknown feature id', async () => {+ await expect(updateInstanceFeature('nope', true)).rejects.toMatchObject({ status: 404 });+ expect(await isInstanceFeatureEnabled('nope')).toBe(false);+ });});diff --git a/server/services/jira.js b/server/services/jira.jsindex bfcf668846..076caddbff 100644--- a/server/services/jira.js+++ b/server/services/jira.js@@ -6,11 +6,20 @@import fs from 'fs/promises';import { createHttpClient } from '../lib/httpClient.js';import path from 'path';-import { ensureDir, PATHS } from '../lib/fileUtils.js';+import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';import { hostFromOriginUrl } from '../lib/workTracker.js';const JIRA_CONFIG_FILE = path.join(PATHS.data, 'jira.json');+// Whether this install has any JIRA instance configured. Read-only on purpose:+// unlike getInstances() it never seeds an empty config file, because the+// instance-feature registry calls it just to decide whether the JIRA nav+// entries should appear on a fresh install.+export async function hasConfiguredInstances() {+ const config = await readJSONFile(JIRA_CONFIG_FILE, { instances: {} }, { logError: false });+ return Object.keys(config?.instances || {}).length > 0;+}+export const escapeJql = (s) => String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"');/**