Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-ui): complete publish scope contract
Josuéb627a99783b8
diff --git a/control-ui/components/PublishToRegistryForm.tsx b/control-ui/components/PublishToRegistryForm.tsxindex c76c93a5c..0650e581e 100644--- a/control-ui/components/PublishToRegistryForm.tsx+++ b/control-ui/components/PublishToRegistryForm.tsx@@ -1,13 +1,13 @@'use client'-import React, { useCallback, useEffect, useState } from 'react'+import React, { useCallback, useState } from 'react'import type { ReactNode } from 'react'import Link from 'next/link'import { CONTROL_ROUTES } from '@constants/routes'-import { getPublishScope, publishToRegistry } from '../lib/api'-import type { PublishScope } from '../lib/api'+import { publishToRegistry } from '../lib/api'import { egressStatusToRegistrySummary } from '../lib/egressModel'import type { EgressEditorStatus, EgressSummary } from '../lib/egressModel'+import { usePublishScope } from '../lib/hooks/usePublishScope'import { isValidK8sName } from '../lib/k8sValidation'import { CreateFlowPanel } from './CreateFlowPanel'import { CreateStepFlow } from './CreateStepFlow'@@ -124,22 +124,7 @@ export function PublishToRegistryForm({// Resolved publish target (org scope vs curated catalog). Informational only:// control-api applies the scope to the name server-side, so we don't touch the// bare `name` input or the payload — we only surface where the entry will land.- const [publishScope, setPublishScope] = useState<PublishScope | null>(null)-- useEffect(() => {- let cancelled = false- getPublishScope()- .then(scope => {- if (!cancelled) setPublishScope(scope)- })- .catch(() => {- // Soft-fail: if the target can't be resolved we just omit the indicator- // rather than blocking the publish flow.- })- return () => {- cancelled = true- }- }, [])+ const { scope: publishScope } = usePublishScope()const nameValid = isValidK8sName(name)const metadataValid =diff --git a/control-ui/components/RegistryConnectPanel.tsx b/control-ui/components/RegistryConnectPanel.tsxindex 0d0cce977..f259a8dd7 100644--- a/control-ui/components/RegistryConnectPanel.tsx+++ b/control-ui/components/RegistryConnectPanel.tsx@@ -9,6 +9,7 @@ import {requestRegistryConnection,submitRegistryClaim,} from '../lib/api'+import { usePublishScope } from '../lib/hooks/usePublishScope'import { useConfirmDialog } from './ConfirmDialog'import { TablePanelHeader } from './TablePanelHeader'import { useToast } from './Toast'@@ -34,6 +35,7 @@ type View =export default function RegistryConnectPanel() {const { showToast } = useToast()const { confirm, confirmDialog } = useConfirmDialog()+ const { refresh: refreshPublishScope } = usePublishScope()const [view, setView] = useState<View>({ kind: 'loading' })// request-form fieldsconst [orgName, setOrgName] = useState('')@@ -125,6 +127,7 @@ export default function RegistryConnectPanel() {// approve it by hand (pending, the original claim-token flow).if (s.state === 'connected') {setView({ kind: 'connected', org: s.org, authEnabled: s.authEnabled })+ void refreshPublishScope({ force: true })showToast(`Connected to @${s.org}.`, { tone: 'success' })} else if (s.state === 'connecting') {setView({@@ -182,6 +185,7 @@ export default function RegistryConnectPanel() {const { org } = await submitRegistryClaim({ claimToken: claimToken.trim() })setClaimToken('')setView({ kind: 'connected', org })+ void refreshPublishScope({ force: true })showToast(`Connected to @${org}.`, { tone: 'success' })} catch (e) {const code = (e as { code?: string }).code@@ -213,6 +217,7 @@ export default function RegistryConnectPanel() {const s = await recoverRegistryConnection()if (s.state === 'connected') {setView({ kind: 'connected', org: s.org, authEnabled: s.authEnabled })+ void refreshPublishScope({ force: true })showToast(`Connected to @${s.org}.`, { tone: 'success' })} else {await load()@@ -241,6 +246,7 @@ export default function RegistryConnectPanel() {setBusy(true)try {await disconnectRegistryConnection()+ void refreshPublishScope({ force: true })} catch {/* best-effort — the next GET reports disconnected once the row is gone */} finally {@@ -268,6 +274,7 @@ export default function RegistryConnectPanel() {setBusy(true)try {await disconnectRegistryConnection()+ void refreshPublishScope({ force: true })} catch {/* best-effort — the next GET reports disconnected once the row is gone */} finally {@@ -289,6 +296,7 @@ export default function RegistryConnectPanel() {if (!ok) returntry {await disconnectRegistryConnection()+ void refreshPublishScope({ force: true })showToast('Disconnected from the Evenfire Registry.', { tone: 'success' })} catch {showToast('Could not disconnect.', { tone: 'error' })diff --git a/control-ui/components/__tests__/PublishToRegistryForm.test.tsx b/control-ui/components/__tests__/PublishToRegistryForm.test.tsxindex 0a83cf4f1..3c9b0f7d2 100644--- a/control-ui/components/__tests__/PublishToRegistryForm.test.tsx+++ b/control-ui/components/__tests__/PublishToRegistryForm.test.tsx@@ -2,6 +2,7 @@ import type { ReactNode } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'import { getPublishScope } from '../../lib/api'+import { PublishScopeProvider, resetPublishScopeCache } from '../../lib/hooks/usePublishScope'import { PublishToRegistryForm } from '../PublishToRegistryForm'import { ToastProvider } from '../Toast'@@ -21,7 +22,11 @@ vi.mock('../EgressEditor', () => ({}))function render(children: ReactNode) {- return rtlRender(<ToastProvider>{children}</ToastProvider>)+ return rtlRender(+ <ToastProvider>+ <PublishScopeProvider cacheKey="admin-1">{children}</PublishScopeProvider>+ </ToastProvider>+ )}async function advanceToReviewStep() {@@ -54,11 +59,13 @@ async function advanceToReviewStep() {describe('PublishToRegistryForm publish target', () => {beforeEach(() => {vi.mocked(getPublishScope).mockReset()+ resetPublishScopeCache()})afterEach(() => {cleanup()vi.clearAllMocks()+ resetPublishScopeCache()})it('shows the org publish target when the caller is bound to an org', async () => {@@ -78,6 +85,7 @@ describe('PublishToRegistryForm publish target', () => {// Exactly one @ — guards against the double-@ regression.expect(screen.getByText('@newtenantwf')).toBeInTheDocument()expect(screen.getByText(/@newtenantwf\/my-connector/)).toBeInTheDocument()+ expect(getPublishScope).toHaveBeenCalledTimes(1)})it('shows the public catalog target when the caller is the curator', async () => {@@ -94,5 +102,6 @@ describe('PublishToRegistryForm publish target', () => {await waitFor(() =>expect(screen.getByText(/Publishing to the public catalog \(@clerum\)/)).toBeInTheDocument())+ expect(getPublishScope).toHaveBeenCalledTimes(1)})})diff --git a/control-ui/components/__tests__/PublisherView.test.tsx b/control-ui/components/__tests__/PublisherView.test.tsxindex f5f8b114d..276b73c9b 100644--- a/control-ui/components/__tests__/PublisherView.test.tsx+++ b/control-ui/components/__tests__/PublisherView.test.tsx@@ -4,6 +4,12 @@ import * as inboundHook from '../../lib/hooks/useInboundGrants'import * as hook from '../../lib/hooks/usePublishScope'import { PublisherView } from '../PublisherView'+const refreshPublishScope = vi.fn()++function publishScopeState(state: Omit<hook.PublishScopeState, 'refresh'>): hook.PublishScopeState {+ return { ...state, refresh: refreshPublishScope }+}+// Stub the three panels so this test targets only the shell + gate.vi.mock('../PublisherView/OwnedEntries', () => ({OwnedEntries: () => <div>owned-entries-panel</div>,@@ -34,37 +40,45 @@ beforeEach(() => {describe('PublisherView', () => {it('renders a loading state while publish-scope resolves', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({ scope: null, loading: true, error: false })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({ scope: null, loading: true, error: false })+ )render(<PublisherView activeTab="entries" />)expect(screen.getByText(/loading/i)).toBeInTheDocument()})it('renders unavailable on a curator deploy (fails closed)', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({- scope: { scope: null, curator: true, orgName: null },- loading: false,- error: false,- })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({+ scope: { scope: null, curator: true, orgName: null },+ loading: false,+ error: false,+ })+ )render(<PublisherView activeTab="entries" />)expect(screen.getByText(/not available on this deployment/i)).toBeInTheDocument()})it('renders unavailable when publisherUiEnabled is false (self-hosted default), even for an org-bound non-curator deploy (fails closed)', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({- scope: { scope: 'acme', curator: false, orgName: 'Acme', publisherUiEnabled: false },- loading: false,- error: false,- })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({+ scope: { scope: 'acme', curator: false, orgName: 'Acme', publisherUiEnabled: false },+ loading: false,+ error: false,+ })+ )render(<PublisherView activeTab="entries" />)expect(screen.getByText(/not available on this deployment/i)).toBeInTheDocument()})it('renders the owned-entries panel for an org-bound deploy on the entries tab', async () => {- vi.mocked(hook.usePublishScope).mockReturnValue({- scope: { scope: 'acme', curator: false, orgName: 'Acme' },- loading: false,- error: false,- })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({+ scope: { scope: 'acme', curator: false, orgName: 'Acme' },+ loading: false,+ error: false,+ })+ )render(<PublisherView activeTab="entries" />)expect(await screen.findByText('owned-entries-panel')).toBeInTheDocument()})@@ -73,42 +87,50 @@ describe('PublisherView', () => {// resolvePublishScope() in control-api returns `scope` already prefixed as// `@<org>` (registryClient.ts). The header must render it verbatim and must// NOT prepend a second '@', otherwise it reads "Publisher — @@acme".- vi.mocked(hook.usePublishScope).mockReturnValue({- scope: { scope: '@acme', curator: false, orgName: 'Acme' },- loading: false,- error: false,- })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({+ scope: { scope: '@acme', curator: false, orgName: 'Acme' },+ loading: false,+ error: false,+ })+ )render(<PublisherView activeTab="entries" />)expect(screen.getByText('Publisher — @acme')).toBeInTheDocument()expect(screen.queryByText(/@@/)).not.toBeInTheDocument()})it('renders the docker-credentials panel on the credentials tab', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({- scope: { scope: 'acme', curator: false, orgName: 'Acme' },- loading: false,- error: false,- })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({+ scope: { scope: 'acme', curator: false, orgName: 'Acme' },+ loading: false,+ error: false,+ })+ )render(<PublisherView activeTab="credentials" />)expect(screen.getByText('docker-credentials-panel')).toBeInTheDocument()})it('renders the granted-to-me panel on the shared tab', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({- scope: { scope: 'acme', curator: false, orgName: 'Acme' },- loading: false,- error: false,- })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({+ scope: { scope: 'acme', curator: false, orgName: 'Acme' },+ loading: false,+ error: false,+ })+ )render(<PublisherView activeTab="shared" />)expect(screen.getByText('granted-to-me-panel')).toBeInTheDocument()})it('tab nav uses Link hrefs to the route segments (not query params)', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({- scope: { scope: 'acme', curator: false, orgName: 'Acme' },- loading: false,- error: false,- })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({+ scope: { scope: 'acme', curator: false, orgName: 'Acme' },+ loading: false,+ error: false,+ })+ )render(<PublisherView activeTab="entries" />)const shared = screen.getByRole('tab', { name: /shared with me/i })expect(shared).toHaveAttribute('href', '/publisher/shared-with-me')@@ -120,11 +142,13 @@ describe('PublisherView', () => {grants: [],reload: vi.fn(),})- vi.mocked(hook.usePublishScope).mockReturnValue({- scope: { scope: '@acme', curator: false, orgName: 'Acme' },- loading: false,- error: false,- })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({+ scope: { scope: '@acme', curator: false, orgName: 'Acme' },+ loading: false,+ error: false,+ })+ )render(<PublisherView activeTab="entries" />)expect(screen.queryByRole('tab', { name: /shared with me/i })).toBeNull()expect(screen.getByRole('tab', { name: /published entries/i })).toBeInTheDocument()@@ -137,11 +161,13 @@ describe('PublisherView', () => {grants: [],reload: vi.fn(),})- vi.mocked(hook.usePublishScope).mockReturnValue({- scope: { scope: '@acme', curator: false, orgName: 'Acme' },- loading: false,- error: false,- })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({+ scope: { scope: '@acme', curator: false, orgName: 'Acme' },+ loading: false,+ error: false,+ })+ )render(<PublisherView activeTab="entries" />)expect(screen.getByRole('tab', { name: /shared with me/i })).toBeInTheDocument()})diff --git a/control-ui/components/__tests__/RegistryConnectPanel.test.tsx b/control-ui/components/__tests__/RegistryConnectPanel.test.tsxindex 33d54e993..0193edf25 100644--- a/control-ui/components/__tests__/RegistryConnectPanel.test.tsx+++ b/control-ui/components/__tests__/RegistryConnectPanel.test.tsx@@ -7,6 +7,10 @@ import * as ConfirmDialogModule from '../ConfirmDialog'import RegistryConnectPanel from '../RegistryConnectPanel'import { ToastProvider } from '../Toast'+const publishScopeMocks = vi.hoisted(() => ({+ refresh: vi.fn(),+}))+vi.mock('../../lib/api', () => ({getRegistryConnection: vi.fn(),requestRegistryConnection: vi.fn(),@@ -14,6 +18,18 @@ vi.mock('../../lib/api', () => ({disconnectRegistryConnection: vi.fn(),recoverRegistryConnection: vi.fn(),}))+vi.mock('../../lib/hooks/usePublishScope', async orig => {+ const actual = await orig<typeof import('../../lib/hooks/usePublishScope')>()+ return {+ ...actual,+ usePublishScope: () => ({+ scope: null,+ loading: false,+ error: false,+ refresh: publishScopeMocks.refresh,+ }),+ }+})vi.mock('../ConfirmDialog', () => ({ useConfirmDialog: vi.fn() }))function render(ui: React.ReactNode) {@@ -22,6 +38,7 @@ function render(ui: React.ReactNode) {afterEach(cleanup)beforeEach(() => {vi.clearAllMocks()+ publishScopeMocks.refresh.mockResolvedValue(null)vi.mocked(ConfirmDialogModule.useConfirmDialog).mockReturnValue({confirm: vi.fn().mockResolvedValue(true),confirmDialog: null,@@ -119,6 +136,7 @@ describe('RegistryConnectPanel', () => {await waitFor(() =>expect(screen.getByText(/Connected to the Evenfire Registry/)).toBeInTheDocument())+ expect(publishScopeMocks.refresh).toHaveBeenCalledTimes(1)})it('shows the expired-token message on a claim_expired code', async () => {@@ -217,6 +235,7 @@ describe('RegistryConnectPanel', () => {// Scoped to the banner text (not just "@acme") because the success toast also// renders "Connected to @acme." — a bare /@acme/ match would be ambiguous.expect(await screen.findByText(/Connected to the Evenfire Registry.*@acme/)).toBeInTheDocument()+ expect(publishScopeMocks.refresh).toHaveBeenCalledTimes(1)// The toast is a SEPARATE mutation from the view: branching the view but// leaving the toast unconditional tells a connected user to wait for an// operator who does not exist.@@ -340,6 +359,7 @@ describe('RegistryConnectPanel', () => {render(<RegistryConnectPanel />)await userEvent.click(await screen.findByRole('button', { name: /finish connecting/i }))expect(await screen.findByText(/Connected to the Evenfire Registry.*@acme/)).toBeInTheDocument()+ expect(publishScopeMocks.refresh).toHaveBeenCalledTimes(1)})// Renamed from the original "shows a retry message when recovery is not yet@@ -505,6 +525,7 @@ describe('RegistryConnectPanel', () => {expect(message).toMatch(/lost permanently/i)expect(message).toMatch(/cannot be recovered/i)await waitFor(() => expect(api.disconnectRegistryConnection).toHaveBeenCalledTimes(1))+ expect(publishScopeMocks.refresh).toHaveBeenCalledTimes(1)})it('does not disconnect the connecting view when Start over is cancelled', async () => {@@ -520,6 +541,7 @@ describe('RegistryConnectPanel', () => {render(<RegistryConnectPanel />)await userEvent.click(await screen.findByRole('button', { name: /start over/i }))expect(api.disconnectRegistryConnection).not.toHaveBeenCalled()+ expect(publishScopeMocks.refresh).not.toHaveBeenCalled()expect(screen.getByRole('button', { name: /finish connecting/i })).toBeInTheDocument()})@@ -533,4 +555,17 @@ describe('RegistryConnectPanel', () => {await screen.findByRole('button', { name: /finish connecting/i })expect(screen.queryByRole('button', { name: /^disconnect$/i })).toBeNull()})++ it('refreshes publish scope after disconnecting an active connection', async () => {+ vi.mocked(api.getRegistryConnection).mockResolvedValue({+ state: 'connected',+ deploymentId: 'd',+ org: 'acme',+ })+ render(<RegistryConnectPanel />)+ await userEvent.click(await screen.findByRole('button', { name: /^disconnect$/i }))+ await waitFor(() => expect(api.disconnectRegistryConnection).toHaveBeenCalledTimes(1))+ expect(publishScopeMocks.refresh).toHaveBeenCalledTimes(1)+ expect(screen.getByText('Request registration')).toBeInTheDocument()+ })})diff --git a/control-ui/components/__tests__/Sidebar.test.tsx b/control-ui/components/__tests__/Sidebar.test.tsxindex de46ee3dc..c3e7a63f2 100644--- a/control-ui/components/__tests__/Sidebar.test.tsx+++ b/control-ui/components/__tests__/Sidebar.test.tsx@@ -6,6 +6,11 @@ import { activeSidebarChildHref } from '../Sidebar/activeChild'import { SIDEBAR_TABS } from '../Sidebar/constants'const navigationState = vi.hoisted(() => ({ pathname: '/agents' }))+const refreshPublishScope = vi.fn()++function publishScopeState(state: Omit<hook.PublishScopeState, 'refresh'>): hook.PublishScopeState {+ return { ...state, refresh: refreshPublishScope }+}vi.mock('next/navigation', () => ({usePathname: () => navigationState.pathname,@@ -24,50 +29,62 @@ beforeEach(() => vi.clearAllMocks())describe('Sidebar publisher gating', () => {it('shows the Publisher entry for an org-bound non-curator deploy', async () => {- vi.mocked(hook.usePublishScope).mockReturnValue({- scope: { scope: 'acme', curator: false, orgName: 'Acme' },- loading: false,- error: false,- })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({+ scope: { scope: 'acme', curator: false, orgName: 'Acme' },+ loading: false,+ error: false,+ })+ )render(<Sidebar currentTab="hosts" />)const link = await screen.findByRole('link', { name: /publisher/i })expect(link).toHaveAttribute('href', '/publisher')})it('hides the Publisher entry when publisherUiEnabled is false (self-hosted default), even for an org-bound non-curator deploy', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({- scope: { scope: 'acme', curator: false, orgName: 'Acme', publisherUiEnabled: false },- loading: false,- error: false,- })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({+ scope: { scope: 'acme', curator: false, orgName: 'Acme', publisherUiEnabled: false },+ loading: false,+ error: false,+ })+ )render(<Sidebar currentTab="hosts" />)expect(screen.queryByRole('link', { name: /publisher/i })).toBeNull()})it('hides the Publisher entry on a curator deploy', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({- scope: { scope: null, curator: true, orgName: null },- loading: false,- error: false,- })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({+ scope: { scope: null, curator: true, orgName: null },+ loading: false,+ error: false,+ })+ )render(<Sidebar currentTab="hosts" />)expect(screen.queryByRole('link', { name: /publisher/i })).toBeNull()})it('hides the Publisher entry while publish-scope is loading', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({ scope: null, loading: true, error: false })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({ scope: null, loading: true, error: false })+ )render(<Sidebar currentTab="hosts" />)expect(screen.queryByRole('link', { name: /publisher/i })).toBeNull()})it('still renders the other navigation entries', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({ scope: null, loading: false, error: true })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({ scope: null, loading: false, error: true })+ )render(<Sidebar currentTab="hosts" />)expect(screen.getByRole('link', { name: /agents/i })).toBeInTheDocument()})it('keeps Traces hidden and sorts visible navigation labels alphabetically', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({ scope: null, loading: false, error: false })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({ scope: null, loading: false, error: false })+ )render(<Sidebar currentTab="traces" />)expect(screen.queryByText('Traces')).not.toBeInTheDocument()@@ -81,7 +98,9 @@ describe('Sidebar publisher gating', () => {})it('keeps Settings in the footer on its canonical route', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({ scope: null, loading: false, error: false })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({ scope: null, loading: false, error: false })+ )render(<Sidebar currentTab="settings" />)expect(screen.getByRole('link', { name: 'Settings' })).toHaveAttribute('href', '/settings/ui')@@ -90,7 +109,9 @@ describe('Sidebar publisher gating', () => {it.each(['/llm-models', '/llm-models/model-id/edit', '/llm-models/discovery'])('keeps the merged LLM Models entry selected for %s',pathname => {- vi.mocked(hook.usePublishScope).mockReturnValue({ scope: null, loading: false, error: false })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({ scope: null, loading: false, error: false })+ )navigationState.pathname = pathnamerender(<Sidebar currentTab="llm-models" />)@@ -106,7 +127,9 @@ describe('Sidebar publisher gating', () => {['/agent-outputs/desktop-app-artifacts', 'Agent Outputs', '/agent-outputs/recipe-artifacts'],['/global-file-system', 'Global File System', '/global-file-system'],])('selects the matching Directories child for %s', (pathname, label, href) => {- vi.mocked(hook.usePublishScope).mockReturnValue({ scope: null, loading: false, error: false })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({ scope: null, loading: false, error: false })+ )navigationState.pathname = pathnamerender(<Sidebar currentTab="directories" />)@@ -119,7 +142,9 @@ describe('Sidebar publisher gating', () => {})it('renders a thin icon for every visible child route', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({ scope: null, loading: false, error: false })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({ scope: null, loading: false, error: false })+ )render(<Sidebar currentTab="directories" />)for (const label of ['Agent Outputs', 'Global File System']) {@@ -129,7 +154,9 @@ describe('Sidebar publisher gating', () => {})it('renders an icon for the Directories group', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({ scope: null, loading: false, error: false })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({ scope: null, loading: false, error: false })+ )render(<Sidebar currentTab="directories" />)const directories = screen.getByRole('button', { name: 'Directories' })@@ -137,7 +164,9 @@ describe('Sidebar publisher gating', () => {})it('hides Agent Files from the sidebar without changing its route', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({ scope: null, loading: false, error: false })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({ scope: null, loading: false, error: false })+ )navigationState.pathname = '/agent-files/example'render(<Sidebar currentTab="directories" />)@@ -146,7 +175,9 @@ describe('Sidebar publisher gating', () => {})it('uses the shared Desktop paperclip glyph for Global File System', () => {- vi.mocked(hook.usePublishScope).mockReturnValue({ scope: null, loading: false, error: false })+ vi.mocked(hook.usePublishScope).mockReturnValue(+ publishScopeState({ scope: null, loading: false, error: false })+ )navigationState.pathname = '/global-file-system'render(<Sidebar currentTab="directories" />)diff --git a/control-ui/lib/hooks/__tests__/usePublishScope.test.tsx b/control-ui/lib/hooks/__tests__/usePublishScope.test.tsxindex 18454ea45..08e7816d1 100644--- a/control-ui/lib/hooks/__tests__/usePublishScope.test.tsx+++ b/control-ui/lib/hooks/__tests__/usePublishScope.test.tsx@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { cleanup, render, screen, waitFor } from '@testing-library/react'+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import * as api from '../../api'import {PublishScopeProvider,@@ -22,10 +22,40 @@ function Probe() {)}+function RefreshProbe() {+ const { scope, loading, refresh } = usePublishScope()+ return (+ <div>+ <div data-testid="scope">{loading ? 'loading' : (scope?.scope ?? 'none')}</div>+ <button type="button" onClick={() => void refresh({ force: true })}>+ Refresh+ </button>+ </div>+ )+}+function renderWithProvider(children: React.ReactNode = <Probe />) {return render(<PublishScopeProvider cacheKey="admin-1">{children}</PublishScopeProvider>)}+function deferred<T>() {+ let resolve!: (value: T) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise+ reject = rejectPromise+ })+ return { promise, reject, resolve }+}++function scope(value: string | null) {+ return {+ scope: value,+ curator: value === null,+ orgName: value,+ }+}+afterEach(cleanup)beforeEach(() => {vi.clearAllMocks()@@ -116,4 +146,97 @@ describe('usePublishScope / isPublisherEnabled', () => {expect(await screen.findByTestId('next-route')).toBeInTheDocument()expect(api.getPublishScope).toHaveBeenCalledTimes(1)})++ it('does not expose a stale keyed request that resolves after reset', async () => {+ const stale = deferred<api.PublishScope>()+ const fresh = deferred<api.PublishScope>()+ vi.mocked(api.getPublishScope)+ .mockReturnValueOnce(stale.promise)+ .mockReturnValueOnce(fresh.promise)++ const view = renderWithProvider(<RefreshProbe />)+ expect(await screen.findByText('loading')).toBeInTheDocument()+ expect(api.getPublishScope).toHaveBeenCalledTimes(1)++ resetPublishScopeCache('admin-1')+ await act(async () => {+ stale.resolve(scope('@stale'))+ await stale.promise+ })+ expect(screen.queryByText('@stale')).toBeNull()+ expect(screen.getByText('none')).toBeInTheDocument()+ view.unmount()++ renderWithProvider(<RefreshProbe />)+ expect(api.getPublishScope).toHaveBeenCalledTimes(2)++ await act(async () => {+ fresh.resolve(scope('@fresh'))+ await fresh.promise+ })+ expect(await screen.findByText('@fresh')).toBeInTheDocument()+ })++ it('does not expose a stale request that resolves after a full reset', async () => {+ const stale = deferred<api.PublishScope>()+ const fresh = deferred<api.PublishScope>()+ vi.mocked(api.getPublishScope)+ .mockReturnValueOnce(stale.promise)+ .mockReturnValueOnce(fresh.promise)++ const view = renderWithProvider(<RefreshProbe />)+ expect(await screen.findByText('loading')).toBeInTheDocument()+ expect(api.getPublishScope).toHaveBeenCalledTimes(1)++ resetPublishScopeCache()+ await act(async () => {+ stale.resolve(scope('@stale'))+ await stale.promise+ })+ expect(screen.queryByText('@stale')).toBeNull()+ expect(screen.getByText('none')).toBeInTheDocument()+ view.unmount()++ renderWithProvider(<RefreshProbe />)+ expect(api.getPublishScope).toHaveBeenCalledTimes(2)++ await act(async () => {+ fresh.resolve(scope('@fresh'))+ await fresh.promise+ })+ expect(await screen.findByText('@fresh')).toBeInTheDocument()+ })++ it('keeps an older request from overwriting a newer provider refresh', async () => {+ const stale = deferred<api.PublishScope>()+ const fresh = deferred<api.PublishScope>()+ vi.mocked(api.getPublishScope)+ .mockReturnValueOnce(stale.promise)+ .mockReturnValueOnce(fresh.promise)++ const view = renderWithProvider(<RefreshProbe />)+ expect(await screen.findByText('loading')).toBeInTheDocument()+ expect(api.getPublishScope).toHaveBeenCalledTimes(1)++ fireEvent.click(screen.getByRole('button', { name: 'Refresh' }))+ expect(api.getPublishScope).toHaveBeenCalledTimes(2)++ await act(async () => {+ fresh.resolve(scope('@fresh'))+ await fresh.promise+ })+ expect(await screen.findByText('@fresh')).toBeInTheDocument()++ await act(async () => {+ stale.resolve(scope('@stale'))+ await stale.promise+ })+ expect(screen.getByText('@fresh')).toBeInTheDocument()+ expect(screen.queryByText('@stale')).toBeNull()++ view.unmount()+ renderWithProvider(<RefreshProbe />)+ expect(api.getPublishScope).toHaveBeenCalledTimes(2)+ expect(await screen.findByText('@fresh')).toBeInTheDocument()+ })})diff --git a/control-ui/lib/hooks/usePublishScope.ts b/control-ui/lib/hooks/usePublishScope.tsindex 119905dcc..c145eb8d6 100644--- a/control-ui/lib/hooks/usePublishScope.ts+++ b/control-ui/lib/hooks/usePublishScope.ts@@ -1,52 +1,93 @@'use client'import type { ReactNode } from 'react'-import { createContext, createElement, useContext, useEffect, useMemo, useState } from 'react'+import {+ createContext,+ createElement,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react'import { type PublishScope, getPublishScope, isSilentApiError } from '../api'-export type PublishScopeState = {+type RefreshOptions = { force?: boolean }++type PublishScopeSnapshot = {scope: PublishScope | nullloading: booleanerror: boolean}-const EMPTY_STATE: PublishScopeState = {+export type PublishScopeState = PublishScopeSnapshot & {+ refresh: (options?: RefreshOptions) => Promise<PublishScope | null>+}++const EMPTY_SNAPSHOT: PublishScopeSnapshot = {scope: null,loading: true,error: false,}+const EMPTY_STATE: PublishScopeState = {+ ...EMPTY_SNAPSHOT,+ refresh: async () => null,+}+const PublishScopeContext = createContext<PublishScopeState | null>(null)-const resolvedScopes = new Map<string, PublishScope>()-const pendingScopes = new Map<string, Promise<PublishScope>>()+type PublishScopeCacheEntry = {+ request?: Promise<PublishScope | null>+ scope?: PublishScope+}-function requestPublishScope(cacheKey: string): Promise<PublishScope> {- const resolved = resolvedScopes.get(cacheKey)- if (resolved) return Promise.resolve(resolved)+const scopeCache = new Map<string, PublishScopeCacheEntry>()- const pending = pendingScopes.get(cacheKey)- if (pending) return pending+function entryFor(cacheKey: string): PublishScopeCacheEntry {+ const cached = scopeCache.get(cacheKey)+ if (cached) return cached+ const next: PublishScopeCacheEntry = {}+ scopeCache.set(cacheKey, next)+ return next+}++function requestPublishScope(+ cacheKey: string,+ options: RefreshOptions = {}+): Promise<PublishScope | null> {+ let entry = entryFor(cacheKey)+ if (options.force) {+ entry = {}+ scopeCache.set(cacheKey, entry)+ }++ if (!options.force && entry.scope) return Promise.resolve(entry.scope)+ if (entry.request) return entry.requestconst request = getPublishScope().then(scope => {- resolvedScopes.set(cacheKey, scope)- return scope+ const liveEntry = scopeCache.get(cacheKey) === entry+ if (liveEntry) {+ entry.scope = scope+ }+ return liveEntry ? scope : null}).finally(() => {- pendingScopes.delete(cacheKey)+ if (scopeCache.get(cacheKey) === entry && entry.request === request) {+ delete entry.request+ }})- pendingScopes.set(cacheKey, request)+ entry.request = requestreturn request}export function resetPublishScopeCache(cacheKey?: string): void {if (cacheKey) {- resolvedScopes.delete(cacheKey)- pendingScopes.delete(cacheKey)+ scopeCache.delete(cacheKey)return}- resolvedScopes.clear()- pendingScopes.clear()+ scopeCache.clear()}export function PublishScopeProvider({@@ -56,40 +97,52 @@ export function PublishScopeProvider({cacheKey: stringchildren: ReactNode}) {- const cachedScope = cacheKey ? resolvedScopes.get(cacheKey) : undefined- const [state, setState] = useState<PublishScopeState>(() =>- cachedScope ? { scope: cachedScope, loading: false, error: false } : EMPTY_STATE+ const cachedScope = cacheKey ? scopeCache.get(cacheKey)?.scope : undefined+ const [state, setState] = useState<PublishScopeSnapshot>(() =>+ cachedScope ? { scope: cachedScope, loading: false, error: false } : EMPTY_SNAPSHOT+ )+ const requestSequenceRef = useRef(0)++ const refresh = useCallback(+ async (options: RefreshOptions = {}) => {+ const requestSequence = ++requestSequenceRef.current+ if (!cacheKey) {+ setState(EMPTY_SNAPSHOT)+ return null+ }++ const nextCachedScope = options.force ? undefined : scopeCache.get(cacheKey)?.scope+ if (nextCachedScope) {+ setState({ scope: nextCachedScope, loading: false, error: false })+ return nextCachedScope+ }++ setState(EMPTY_SNAPSHOT)+ try {+ const scope = await requestPublishScope(cacheKey, options)+ if (requestSequenceRef.current === requestSequence) {+ setState({ scope, loading: false, error: false })+ }+ return scope+ } catch (error) {+ if (requestSequenceRef.current === requestSequence) {+ setState({ scope: null, loading: false, error: !isSilentApiError(error) })+ }+ return null+ }+ },+ [cacheKey])useEffect(() => {- let cancelled = false- if (!cacheKey) {- setState(EMPTY_STATE)- return- }-- const nextCachedScope = resolvedScopes.get(cacheKey)- if (nextCachedScope) {- setState({ scope: nextCachedScope, loading: false, error: false })- return- }-- setState(EMPTY_STATE)- void requestPublishScope(cacheKey)- .then(scope => {- if (!cancelled) setState({ scope, loading: false, error: false })- })- .catch(error => {- if (cancelled || isSilentApiError(error)) return- setState({ scope: null, loading: false, error: true })- })+ void refresh()return () => {- cancelled = true+ requestSequenceRef.current += 1}- }, [cacheKey])+ }, [refresh])- const value = useMemo(() => state, [state])+ const value = useMemo(() => ({ ...state, refresh }), [refresh, state])return createElement(PublishScopeContext.Provider, { value }, children)}