Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(models): preserve source mutation reports (#1467)

Call White499e94576381
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
index 4ac96e9c3..564f8cbb5 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
@@ -8,7 +8,12 @@ import i18n from '@/i18n';
import { AddApiKeyDialog } from './AddApiKeyDialog';
import { createSourceCollectionReadAuthority } from './collectionReadAuthority';
import { ApiCallError, modelsApi } from './modelsApi';
-import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';
+import type {
+ SourceMutationLanding,
+ SourceMutationLandingReads,
+ SourceMutationSettlement,
+ TrackSourceMutation,
+} from './mutationSettlement';
import {
CONTRACT_VERSION,
SOURCE_DISPLAY_NAME_MAX_LENGTH,
@@ -79,9 +84,21 @@ const renderDialog = (onClose = vi.fn(), onAdded = vi.fn()) => {
const replacementSettlement = (
overrides: Partial<SourceMutationSettlement> = {},
): SourceMutationSettlement => ({
- source: vi.fn().mockResolvedValue('landed'),
- gone: vi.fn().mockResolvedValue('landed'),
- unread: vi.fn().mockResolvedValue('landed'),
+ source: vi.fn().mockResolvedValue({
+ verdict: 'landed',
+ reads: {} as SourceMutationLandingReads,
+ affectedChains: [],
+ } satisfies SourceMutationLanding),
+ gone: vi.fn().mockResolvedValue({
+ verdict: 'landed',
+ reads: {} as SourceMutationLandingReads,
+ affectedChains: [],
+ } satisfies SourceMutationLanding),
+ unread: vi.fn().mockResolvedValue({
+ verdict: 'landed',
+ reads: {} as SourceMutationLandingReads,
+ affectedChains: [],
+ } satisfies SourceMutationLanding),
release: vi.fn(),
readInventory: vi.fn().mockResolvedValue({ snapshot: 1, sources: [blockedSource] }),
...overrides,
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 24230091d..09cca6e79 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -8,7 +8,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { ToastProvider } from '@/context/ToastProvider';
import i18n from '@/i18n';
+import { MANAGE_COMMIT_ACTIONS } from './manage';
import { modelsApi } from './modelsApi';
+import { SOURCE_MUTATION_REPORT_PROJECTIONS } from './mutationSettlement';
import { SettingsModelsPage } from './SettingsModelsPage';
import type { AgentBackend, AgentChain, AgentSupply, RuntimeDependency, Source } from './types';
@@ -565,6 +567,119 @@ describe('SettingsModelsPage surface branches', () => {
expect(screen.getAllByText('—').length).toBeGreaterThan(0);
});
+ it.each(MANAGE_COMMIT_ACTIONS)(
+ '[MH-SRC-DELETE-001] keeps the page-owned $action impact readable until every referenced projection lands',
+ async (action) => {
+ const modelId = 'claude-opus-4-6';
+ const updatedSource = { ...retainedSource, display_name: 'Updated source' };
+ const hubAgent: AgentSupply = {
+ ...takeoverAgent,
+ backend: 'claude',
+ selected_model_id: modelId,
+ sources: {
+ order: [retainedSource.id],
+ eligibility: [{ source_id: retainedSource.id, eligible: true }],
+ },
+ routes: { [modelId]: { hops: [{ source_id: retainedSource.id, model_id: modelId }] } },
+ model_supply: [{ model_id: modelId, chain_length: 1, has_runnable_hop: true }],
+ builtin_models: [modelId],
+ };
+ const affectedChain: AgentChain = {
+ contract_version: 5,
+ backend: 'claude',
+ model_id: modelId,
+ current: { source_id: retainedSource.id, model_id: modelId },
+ chain: [{
+ source_id: retainedSource.id,
+ model_id: modelId,
+ channel: 'hub',
+ health: 'healthy',
+ runnable: true,
+ reason: null,
+ retry_at: null,
+ }],
+ supply_state: 'ok',
+ };
+ const impact = {
+ removed_hops: [{
+ backend: 'claude' as const,
+ menu_model: modelId,
+ position: 1,
+ source_id: retainedSource.id,
+ model_id: modelId,
+ }],
+ interrupted: [{ backend: 'claude' as const, model_id: modelId, agents: ['Release bot'] }],
+ };
+ const sourceRead = vi.spyOn(modelsApi, 'listSources').mockResolvedValue([retainedSource]);
+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([hubAgent]);
+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);
+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
+ const chainRead = vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(affectedChain);
+ if (action === 'edit') {
+ vi.spyOn(modelsApi, 'patchSource').mockResolvedValueOnce({ source: updatedSource, ...impact });
+ } else {
+ vi.spyOn(modelsApi, 'deleteSource').mockResolvedValueOnce(impact);
+ }
+
+ render(
+ <ToastProvider>
+ <I18nextProvider i18n={i18n}>
+ <SettingsModelsPage />
+ </I18nextProvider>
+ </ToastProvider>,
+ );
+ await userEvent.click((await screen.findByText('Retained source')).closest('button') as HTMLButtonElement);
+ await waitFor(() => expect(chainRead).toHaveBeenCalled());
+
+ await userEvent.click(screen.getByRole('button', { name: /Manage Retained source|管理 Retained source/i }));
+ if (action === 'edit') {
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑来源$/i }));
+ const name = screen.getByLabelText(/^Display name$|^显示名称$/i);
+ await userEvent.clear(name);
+ await userEvent.type(name, updatedSource.display_name);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+ } else {
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove source$|^移除来源$/i }));
+ await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除来源$/i }));
+ }
+
+ const report = await screen.findByRole('dialog', {
+ name: action === 'edit' ? /source was updated|来源已更新/i : /source was removed|来源已移除/i,
+ });
+ expect(report.dataset.reportProjections?.split(' ')).toEqual(
+ Object.keys(SOURCE_MUTATION_REPORT_PROJECTIONS),
+ );
+ expect(report.textContent).toContain(modelId);
+ expect(report.textContent).toContain('Release bot');
+
+ const chainLanding = deferred<AgentChain>();
+ chainRead.mockImplementationOnce(() => chainLanding.promise);
+ sourceRead.mockResolvedValue(action === 'edit' ? [updatedSource] : []);
+ const done = within(report).getAllByRole('button', { name: /^Done$|^完成$/i })
+ .find((button) => button.classList.contains('model-hub-guard-action'));
+ await userEvent.click(done!);
+
+ if (action === 'edit') {
+ await waitFor(() => expect(document.querySelector('.model-hub-source-title')?.textContent)
+ .toBe(updatedSource.display_name));
+ } else {
+ await waitFor(() => expect(document.querySelector('.model-hub-source-title')).toBeNull());
+ }
+ expect(screen.getByRole('dialog', {
+ name: action === 'edit' ? /source was updated|来源已更新/i : /source was removed|来源已移除/i,
+ })).toBeTruthy();
+ expect(chainRead).toHaveBeenLastCalledWith('claude', modelId);
+
+ await act(async () => {
+ chainLanding.resolve(affectedChain);
+ await chainLanding.promise;
+ });
+ await waitFor(() => expect(screen.queryByRole('dialog', {
+ name: action === 'edit' ? /source was updated|来源已更新/i : /source was removed|来源已移除/i,
+ })).toBeNull());
+ },
+ );
+
it('cannot restore chains after the authoritative supply leaves hub mode', async () => {
const head = { ...retainedSource, id: 'src_head', display_name: 'Paused source', state: { status: 'cooldown' as const, retry_at: '2099-01-01T00:00:00Z', detail_key: null } };
const relay = { ...retainedSource, id: 'src_relay', display_name: 'Replacement source', state: { status: 'active' as const, retry_at: null, detail_key: null } };
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index d8fc5c931..ea5f58b1d 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -18,6 +18,7 @@ import { RecentSwitchesCard } from './RecentSwitchesCard';
import { RouteChainDialog, type RouteCollectionObservation, type RouteCommitReconciliation, type RouteReport } from './RouteChainDialog';
import { routeChainMatchesAttempt } from './routeChainDraft';
import { SourceDetailPanel } from './SourceDetailPanel';
+import { SourceMutationReport } from './SourceMutationReport';
import { SourceOrderDrawer } from './SourceOrderDrawer';
import { SourcesCard } from './SourcesCard';
import { modelsSurfaceKindFromReads } from './modelHubSurfaceState';
@@ -31,13 +32,19 @@ import {
import { SupplyGraph, SupplyLegend } from './SupplyGraph';
import './modelHubSurface.css';
import { agentsWithEcho, createLatestAsyncAuthority, createLatestAsyncAuthorityByKey, createLatestEntityAuthorityByKey, createPendingWrites, mapWithConcurrency } from './asyncLifetime';
-import { createAgentCollectionReadAuthority, createSourceCollectionReadAuthority, type CollectionReadAuthority } from './collectionReadAuthority';
+import { createAgentCollectionReadAuthority, createSourceCollectionReadAuthority } from './collectionReadAuthority';
import { emptyFeed, feedAfterHeadRead, feedAfterTailRead, feedTailCursor, type EventFeed } from './eventFeed';
-import { readFirstPaintRegions, type SurfaceLanding } from './firstPaintRegions';
import { modelsApi, type SourceCreated } from './modelsApi';
import { convergeMutation, createIntentAuthority } from './mutationConvergence';
-import type { SourceMutationLanding, SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';
-import { modelChainKey, modelChainRequests, type ModelChainIndex } from './modelRows';
+import {
+ readSurfaceLanding,
+ sourceMutationLanding,
+ type SourceMutationLanding,
+ type SourceMutationLandingReads,
+ type SourceMutationSettlement,
+ type TrackSourceMutation,
+} from './mutationSettlement';
+import { modelChainKey, modelChainRequests, type ModelChainIndex, type ModelChainRequest } from './modelRows';
import {
beginRegionRead,
failRegionRead,
@@ -45,13 +52,13 @@ import {
degradedRegion,
loadingRegion,
readyRegion,
- regionFailed,
settleRegionRead,
unreadRegion,
type RegionRead,
} from './regionRead';
import { freshRuntimeProjection, pollRuntimeStatus, runtimeHasInstallAsset, startRuntimeWithStatusRefresh } from './runtimeLifecycle';
import { createRouteProjectionReconciler, type RouteProjectionStatus } from './routeProjectionReconciliation';
+import { useSourceMutationReport } from './useSourceMutationReport';
import { backendVisual } from './vendorMeta';
import type { AgentBackend, AgentSupply, ResolutionEvent, RuntimeDependency, Source } from './types';
@@ -63,9 +70,9 @@ const SUBSCRIPTION_PICKER_OPTIONS = [
] as const;
type SubscriptionPickerVendor = (typeof SUBSCRIPTION_PICKER_OPTIONS)[number]['vendor'];
-const readAgentChains = async (agent: AgentSupply): Promise<ModelChainIndex> => Object.fromEntries(
+const readChainRequests = async (requests: readonly ModelChainRequest[]): Promise<ModelChainIndex> => Object.fromEntries(
await mapWithConcurrency(
- modelChainRequests([agent]),
+ requests,
CHAIN_READ_CONCURRENCY,
async ({ backend, modelId }) => {
const key = modelChainKey(backend, modelId);
@@ -78,6 +85,9 @@ const readAgentChains = async (agent: AgentSupply): Promise<ModelChainIndex> =>
),
);
+const readAgentChains = async (agent: AgentSupply): Promise<ModelChainIndex> =>
+ readChainRequests(modelChainRequests([agent]));
+
const readExactAgentChain = async (
agent: AgentSupply,
modelId: string,
@@ -124,23 +134,15 @@ const beginAgentChainIndex = (
return next;
};
+type ChainAuthorityLanding =
+ | { scope: 'backend'; agent: AgentSupply; chains: ModelChainIndex }
+ | { scope: 'models'; chains: ModelChainIndex };
+
type AuthorizedSurfaceLanding = {
- landing: SurfaceLanding;
+ landing: SourceMutationLandingReads;
sourceSnapshot: number;
};
-const readSurfaceLanding = (
- sourceReads: CollectionReadAuthority<Source[]>,
- agentReads: CollectionReadAuthority<AgentSupply[]>,
-): Promise<SurfaceLanding> => readFirstPaintRegions({
- sources: sourceReads.readValue,
- supply: agentReads.readValue,
- runtime: () => modelsApi.getRuntimeStatus(),
-});
-
-const surfaceLandingFailed = (landing: SurfaceLanding): boolean =>
- Object.values(landing).some(regionFailed);
-
export const RuntimePill: React.FC<{
read: RegionRead<RuntimeDependency>;
starting: boolean;
@@ -339,6 +341,7 @@ export const SettingsModelsPage: React.FC = () => {
const [sourceIntentAuthority] = React.useState(createIntentAuthority);
const [sourceCollectionReads] = React.useState(() => createSourceCollectionReadAuthority(modelsApi));
const [agentCollectionReads] = React.useState(() => createAgentCollectionReadAuthority(modelsApi));
+ const sourceMutationReport = useSourceMutationReport();
const overviewRef = React.useRef<HTMLDivElement>(null);
const pageRef = React.useRef<HTMLDivElement>(null);
const aliveRef = React.useRef(true);
@@ -403,7 +406,7 @@ export const SettingsModelsPage: React.FC = () => {
});
}, [runtimeHealth, runtimeRead.kind, runtimeRecoveryPending, startingRuntime]);
- const [chainReadAuthority] = React.useState(() => createLatestAsyncAuthorityByKey<AgentBackend, { agent: AgentSupply; chains: ModelChainIndex; scope: 'backend' | 'model' }>((_backend, incoming) => {
+ const [chainReadAuthority] = React.useState(() => createLatestAsyncAuthorityByKey<AgentBackend, ChainAuthorityLanding>((_backend, incoming) => {
if (!aliveRef.current) return;
setChainsRead((previous) => {
const current = foldRegionRead<ModelChainIndex, ModelChainIndex>(previous, {
@@ -432,6 +435,31 @@ export const SettingsModelsPage: React.FC = () => {
}));
}, [chainReadAuthority]);
+ const refreshAffectedChains = React.useCallback(async (
+ requests: readonly ModelChainRequest[],
+ ): Promise<ModelChainIndex> => {
+ const byBackend = new Map<AgentBackend, ModelChainRequest[]>();
+ for (const request of requests) {
+ const backendRequests = byBackend.get(request.backend) ?? [];
+ backendRequests.push(request);
+ byBackend.set(request.backend, backendRequests);
+ }
+ const landings = await Promise.all([...byBackend].map(async ([backend, backendRequests]) => {
+ let incoming: ModelChainIndex = {};
+ const result = await chainReadAuthority.run(backend, async () => {
+ incoming = await readChainRequests(backendRequests);
+ return { scope: 'models' as const, chains: incoming };
+ });
+ return result === 'landed'
+ ? incoming
+ : Object.fromEntries(backendRequests.map(({ backend: requestBackend, modelId }) => [
+ modelChainKey(requestBackend, modelId),
+ unreadRegion(),
+ ]));
+ }));
+ return Object.assign({}, ...landings);
+ }, [chainReadAuthority]);
+
const refreshAllAgentChains = React.useCallback((agentRows: AgentSupply[]) => {
const hubAgents = agentRows.filter((agent) => agent.mode === 'hub');
const suspendedBackends = new Set(suspendedRouteAttempts.keys());
@@ -519,25 +547,31 @@ export const SettingsModelsPage: React.FC = () => {
if (landing.supply.kind !== 'ready') setChainsRead(failRegionRead);
}));
- const refresh = React.useCallback(async (): Promise<SourceMutationLanding> => {
+ const refresh = React.useCallback(async (
+ affectedChains: ModelChainRequest[] = [],
+ ): Promise<SourceMutationLanding> => {
void refreshEventHead();
- const outcome: { landing: SurfaceLanding | null } = { landing: null };
+ const outcome: { landing: SourceMutationLandingReads | null } = { landing: null };
const result = await refreshAuthority.run(async () => {
const sourceSnapshot = sourceEntityAuthority.beginSnapshot();
- outcome.landing = await readSurfaceLanding(sourceCollectionReads, agentCollectionReads);
+ outcome.landing = await readSurfaceLanding({
+ sources: sourceCollectionReads.readValue,
+ supply: agentCollectionReads.readValue,
+ runtime: () => modelsApi.getRuntimeStatus(),
+ chains: refreshAffectedChains,
+ }, affectedChains);
return { landing: outcome.landing, sourceSnapshot };
});
- const failed = Boolean(aliveRef.current
- && result === 'landed'
- && outcome.landing
- && surfaceLandingFailed(outcome.landing));
- if (failed) {
+ const landing = sourceMutationLanding(
+ outcome.landing,
+ affectedChains,
+ aliveRef.current && result === 'landed',
+ );
+ if (aliveRef.current && result === 'landed' && landing.verdict === 'degraded') {
showToast(t('settings.models.toast.refreshFailed') as string, 'error');
}
- return aliveRef.current && result === 'landed' && outcome.landing && !failed
- ? 'landed'
- : 'degraded';
- }, [agentCollectionReads, refreshAuthority, refreshEventHead, showToast, sourceCollectionReads, sourceEntityAuthority, t]);
+ return landing;
+ }, [agentCollectionReads, refreshAffectedChains, refreshAuthority, refreshEventHead, showToast, sourceCollectionReads, sourceEntityAuthority, t]);
const trackSourceMutation = React.useCallback((sourceId: string): TrackSourceMutation => async <T,>(work: (source: Source, settlement: SourceMutationSettlement) => Promise<T>): Promise<T> => {
let result!: T;
@@ -546,16 +580,22 @@ export const SettingsModelsPage: React.FC = () => {
if (!current) throw new Error(`Source ${sourceId} is no longer available`);
const generation = sourceEntityAuthority.begin(sourceId);
let settled = false;
- const finish = async (apply: () => void, reconcile = true): Promise<SourceMutationLanding> => {
+ const finish = async (
+ apply: () => void,
+ affectedChains: ModelChainRequest[] = [],
+ ): Promise<SourceMutationLanding> => {
if (!settled) {
settled = true;
apply();
}
- return reconcile ? refresh() : 'landed';
+ return refresh(affectedChains);
};
const settlement: SourceMutationSettlement = {
- source: async (echoed) => finish(() => { sourceEntityAuthority.settle(generation, echoed); }),
- gone: async (goneId, inventory) => finish(() => {
+ source: async (echoed, scope) => finish(
+ () => { sourceEntityAuthority.settle(generation, echoed); },
+ scope?.affectedChains,
+ ),
+ gone: async (goneId, inventory, scope) => finish(() => {
if (inventory) {
sourceEntityAuthority.settleSnapshotEntries(
inventory.snapshot,
@@ -563,9 +603,16 @@ export const SettingsModelsPage: React.FC = () => {
);
}
if (goneId === sourceId) sourceEntityAuthority.settleRemoval(generation);
- }),
- unread: async () => finish(() => { sourceEntityAuthority.abandon(generation); }),
- release: () => { void finish(() => { sourceEntityAuthority.abandon(generation); }, false); },
+ }, scope?.affectedChains),
+ unread: async (scope) => finish(
+ () => { sourceEntityAuthority.abandon(generation); },
+ scope?.affectedChains,
+ ),
+ release: () => {
+ if (settled) return;
+ settled = true;
+ sourceEntityAuthority.abandon(generation);
+ },
readInventory: async () => {
const snapshot = sourceEntityAuthority.beginSnapshot();
return { snapshot, sources: await sourceCollectionReads.readValue() };
@@ -811,9 +858,8 @@ export const SettingsModelsPage: React.FC = () => {
void (async () => {
try {
await chainReadAuthority.run(held.backend, async () => ({
- agent: freshAgent,
chains: await readExactAgentChain(freshAgent, held.modelId),
- scope: 'model' as const,
+ scope: 'models' as const,
}));
if (suspendedHubFrontiersRef.current.get(held.backend) !== freshAgent) return;
} catch {
@@ -968,7 +1014,13 @@ export const SettingsModelsPage: React.FC = () => {
{landingLoading ? <div className="text-[13px] text-muted">{t('common.loading')}</div>
: selectedSourceId
? selectedSource
- ? <SourceDetailPanel source={selectedSource} headingRef={sourceDetailHeadingRef} trackMutation={trackSourceMutation(selectedSource.id)} onReauth={setReauthSource} />
+ ? <SourceDetailPanel
+ source={selectedSource}
+ headingRef={sourceDetailHeadingRef}
+ trackMutation={trackSourceMutation(selectedSource.id)}
+ onReauth={setReauthSource}
+ onMutationCommitted={sourceMutationReport.present}
+ />
: <section className="rounded-xl border border-border bg-surface px-5 py-12 text-center text-[12px] text-muted">{t('settings.models.sourceDetail.gone')}</section>
: directEmpty ? <DirectHome agents={installedAgents} onSwitch={setAdoptAgent} />
: <div className="space-y-[22px]">
@@ -1071,6 +1123,11 @@ export const SettingsModelsPage: React.FC = () => {
<AdvancedRow />
</div> : <section className="rounded-xl border border-border bg-surface px-5 py-8"><div className="flex items-start gap-3"><Info className="mt-0.5 size-4 text-muted" /><div><h2 className="text-[14px] font-semibold text-foreground">{t('settings.models.usageTab.title')}</h2><p className="mt-1 text-[12px] text-muted">{t('settings.models.usageTab.detail')}</p></div></div></section>}
</div>}
+ <SourceMutationReport
+ report={sourceMutationReport.report}
+ onComplete={() => { void sourceMutationReport.complete(); }}
+ onDismiss={sourceMutationReport.dismiss}
+ />
<AddApiKeyDialog open={apiKeyOpen} sourceReads={sourceCollectionReads} onClose={() => setApiKeyOpen(false)} onAdded={(created) => void sourceAdded(created)} />
{subscriptionVendor && (
<OAuthConnectDialog
diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
index 20a8c63c0..0ace43a35 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
@@ -12,10 +12,16 @@ import i18n from '@/i18n';
import { classifyModelHubFailure, createPendingWrites } from './asyncLifetime';
import { MANAGE_DESTINATION, type ManageKind } from './manage';
import { ApiCallError, modelsApi } from './modelsApi';
-import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';
+import type {
+ SourceMutationLanding,
+ SourceMutationLandingReads,
+ SourceMutationSettlement,
+ TrackSourceMutation,
+} from './mutationSettlement';
import { GuardGapList } from './GuardGapList';
import { REPAIR_DESTINATION, REPAIR_LABEL_KEY, repairAction, type RepairKind } from './repair';
import { SourceDetailPanel } from './SourceDetailPanel';
+import { SourceMutationReport } from './SourceMutationReport';
import {
COOLDOWN_DETAIL_KEYS,
ERROR_DETAIL_KEYS,
@@ -23,6 +29,7 @@ import {
SOURCE_STATUSES,
} from './types';
import type { Source, SourceDetailKey, SourceKind, SupplyChannel } from './types';
+import { useSourceMutationReport } from './useSourceMutationReport';
const source: Source = {
id: 'src_detail',
@@ -112,15 +119,34 @@ const deferred = <T,>() => {
let sourceSnapshot = 0;
const beginSourceSnapshot = () => ++sourceSnapshot;
+const mutationLanding = (
+ verdict: SourceMutationLanding['verdict'] = 'landed',
+): SourceMutationLanding => verdict === 'landed'
+ ? { verdict, reads: {} as SourceMutationLandingReads, affectedChains: [] }
+ : { verdict, reads: null, affectedChains: [] };
const settlement = (overrides: Partial<SourceMutationSettlement> = {}): SourceMutationSettlement => ({
- source: vi.fn().mockResolvedValue('landed'),
- gone: vi.fn().mockResolvedValue('landed'),
- unread: vi.fn().mockResolvedValue('landed'),
+ source: vi.fn().mockResolvedValue(mutationLanding()),
+ gone: vi.fn().mockResolvedValue(mutationLanding()),
+ unread: vi.fn().mockResolvedValue(mutationLanding()),
release: vi.fn(),
readInventory: async () => ({ snapshot: beginSourceSnapshot(), sources: await modelsApi.listSources() }),
...overrides,
});
const immediateTrack: TrackSourceMutation = async (work) => work(source, settlement());
+type ReportOwnedPanelProps = Omit<React.ComponentProps<typeof SourceDetailPanel>, 'onMutationCommitted'>;
+const ReportOwnedPanel: React.FC<ReportOwnedPanelProps> = (props) => {
+ const owner = useSourceMutationReport();
+ return (
+ <>
+ <SourceDetailPanel {...props} onMutationCommitted={owner.present} />
+ <SourceMutationReport
+ report={owner.report}
+ onComplete={() => { void owner.complete(); }}
+ onDismiss={owner.dismiss}
+ />
+ </>
+ );
+};
type MutationScheduler = <T>(work: () => Promise<T>) => Promise<T>;
const serializedTrack = (): MutationScheduler => {
const writes = createPendingWrites(() => {});
@@ -134,12 +160,16 @@ const serializedTrack = (): MutationScheduler => {
const renderPanel = (adoptedBy: Source['adopted_by'] = undefined) => render(
<ToastProvider>
<I18nextProvider i18n={i18n}>
- <SourceDetailPanel source={{ ...source, adopted_by: adoptedBy }} trackMutation={immediateTrack} onReauth={noReauth} />
+ <ReportOwnedPanel source={{ ...source, adopted_by: adoptedBy }} trackMutation={immediateTrack} onReauth={noReauth} />
</I18nextProvider>
</ToastProvider>,
);
-const EchoPanel: React.FC<{ reconcile?: () => Promise<void> | void; scheduler?: MutationScheduler }> = ({ reconcile = vi.fn(), scheduler = async (work) => work() }) => {
+const EchoPanel: React.FC<{
+ reconcile?: () => Promise<SourceMutationLanding['verdict'] | void> | SourceMutationLanding['verdict'] | void;
+ scheduler?: MutationScheduler;
+}> = ({ reconcile = vi.fn(), scheduler = async (work) => work() }) => {
+ const owner = useSourceMutationReport();
const [current, setCurrent] = React.useState<Source | null>(source);
const currentRef = React.useRef<Source | null>(current);
currentRef.current = current;
@@ -147,14 +177,23 @@ const EchoPanel: React.FC<{ reconcile?: () => Promise<void> | void; scheduler?:
const latest = currentRef.current;
if (!latest) throw new Error('Source is gone');
return work(latest, settlement({
- source: async (echoed) => { currentRef.current = echoed; setCurrent(echoed); await reconcile(); return 'landed'; },
- gone: async () => { currentRef.current = null; setCurrent(null); await reconcile(); return 'landed'; },
- unread: async () => { await reconcile(); return 'landed'; },
+ source: async (echoed) => { currentRef.current = echoed; setCurrent(echoed); return mutationLanding((await reconcile()) ?? 'landed'); },
+ gone: async () => { currentRef.current = null; setCurrent(null); return mutationLanding((await reconcile()) ?? 'landed'); },
+ unread: async () => mutationLanding((await reconcile()) ?? 'landed'),
}));
});
- return current
- ? <SourceDetailPanel source={current} trackMutation={trackMutation} onReauth={noReauth} />
- : <p data-testid="source-gone">Source gone</p>;
+ return (
+ <>
+ {current
+ ? <SourceDetailPanel source={current} trackMutation={trackMutation} onReauth={noReauth} onMutationCommitted={owner.present} />
+ : <p data-testid="source-gone">Source gone</p>}
+ <SourceMutationReport
+ report={owner.report}
+ onComplete={() => { void owner.complete(); }}
+ onDismiss={owner.dismiss}
+ />
+ </>
+ );
};
const renderEchoPanel = (reconcile = vi.fn(), scheduler?: MutationScheduler) => render(
@@ -177,7 +216,7 @@ describe('SourceDetailPanel', () => {
const headingRef = React.createRef<HTMLHeadingElement>();
render(
<I18nextProvider i18n={i18n}>
- <SourceDetailPanel source={source} headingRef={headingRef} trackMutation={immediateTrack} onReauth={noReauth} />
+ <ReportOwnedPanel source={source} headingRef={headingRef} trackMutation={immediateTrack} onReauth={noReauth} />
</I18nextProvider>,
);
@@ -276,7 +315,7 @@ describe('SourceDetailPanel', () => {
it('renders the proved protocol through its product-facing locale key', async () => {
render(
<I18nextProvider i18n={i18n}>
- <SourceDetailPanel
+ <ReportOwnedPanel
source={{ ...source, vendor: 'custom', protocol: 'openai_chat' }}
trackMutation={immediateTrack}
onReauth={noReauth}
@@ -635,13 +674,13 @@ describe('SourceDetailPanel', () => {
});
}
const trackMutation: TrackSourceMutation = (work) => work(source, settlement({
- source: reconcile,
- gone: reconcile,
+ source: async () => mutationLanding(await reconcile()),
+ gone: async () => mutationLanding(await reconcile()),
}));
render(
<ToastProvider>
<I18nextProvider i18n={i18n}>
- <SourceDetailPanel source={source} trackMutation={trackMutation} onReauth={noReauth} />
+ <ReportOwnedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} />
</I18nextProvider>
</ToastProvider>,
);
@@ -684,7 +723,9 @@ describe('SourceDetailPanel', () => {
let tracked: Promise<unknown> | undefined;
let trackedSettled = false;
const trackMutation: TrackSourceMutation = (work) => {
- const operation = work(source, settlement({ source: reconcile }));
+ const operation = work(source, settlement({
+ source: async () => mutationLanding(await reconcile()),
+ }));
tracked = operation;
void operation.then(
() => { trackedSettled = true; },
@@ -695,7 +736,7 @@ describe('SourceDetailPanel', () => {
render(
<ToastProvider>
<I18nextProvider i18n={i18n}>
- <SourceDetailPanel source={source} trackMutation={trackMutation} onReauth={noReauth} />
+ <ReportOwnedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} />
</I18nextProvider>
</ToastProvider>,
);
@@ -723,49 +764,28 @@ describe('SourceDetailPanel', () => {
expect(trackedSettled).toBe(true);
});
- it('releases tracked work when delete settlement unmounts the impact holder', async () => {
+ it('keeps a deletion report readable after settlement unmounts its Source panel', async () => {
vi.spyOn(modelsApi, 'deleteSource').mockResolvedValueOnce({
removed_hops: heldHops,
interrupted: heldGaps,
});
- let tracked: Promise<unknown> | undefined;
- let trackedSettled = false;
- let view: ReturnType<typeof render> | null = null;
- const gone = vi.fn(async () => {
- view?.unmount();
- return 'degraded' as const;
- });
- const trackMutation: TrackSourceMutation = (work) => {
- const operation = work(source, settlement({ gone }));
- tracked = operation;
- void operation.then(
- () => { trackedSettled = true; },
- () => { trackedSettled = true; },
- );
- return operation;
- };
- view = render(
- <ToastProvider>
- <I18nextProvider i18n={i18n}>
- <SourceDetailPanel source={source} trackMutation={trackMutation} onReauth={noReauth} />
- </I18nextProvider>
- </ToastProvider>,
- );
+ const landing = deferred<SourceMutationLanding['verdict']>();
+ renderEchoPanel(() => landing.promise);
await submitManagementWrite('delete', false);
const impact = await screen.findByRole('dialog', { name: /source was removed|来源已移除/i });
const done = within(impact).getAllByRole('button', { name: /^Done$|^完成$/i })
.find((button) => button.classList.contains('model-hub-guard-action'));
expect(done).toBeTruthy();
- expect(trackedSettled).toBe(false);
await userEvent.click(done!);
- await waitFor(() => expect(gone).toHaveBeenCalledOnce());
- expect(tracked).toBeDefined();
- // Completeness comes from the total stage predicate, not from remembering
- // each UI event that can stop holding the committed-impact stage.
- await tracked;
- expect(trackedSettled).toBe(true);
+ expect(await screen.findByTestId('source-gone')).toBeTruthy();
+ expect(screen.getByRole('dialog', { name: /source was removed|来源已移除/i })).toBeTruthy();
+ expect(impact.textContent).toContain(heldHops[0].menu_model);
+ expect(impact.textContent).toContain(heldGaps[0].agents[0]);
+
+ landing.resolve('landed');
+ await waitFor(() => expect(screen.queryByRole('dialog', { name: /source was removed|来源已移除/i })).toBeNull());
});
it.each((['edit', 'delete'] as const).flatMap((action) => [
@@ -796,7 +816,7 @@ describe('SourceDetailPanel', () => {
);
it('omits native refetch because that channel has no stored discovery credential', () => {
- render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={{ ...source, kind: 'subscription', supply_channel: 'native_cli' }} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={{ ...source, kind: 'subscription', supply_channel: 'native_cli' }} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);
expect(screen.queryByRole('button', { name: /^Refetch$|^重新拉取$/i })).toBeNull();
});
@@ -832,7 +852,7 @@ describe('SourceDetailPanel', () => {
vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([reconciled]);
const applySource = vi.fn().mockResolvedValue(undefined);
const trackMutation: TrackSourceMutation = (work) => work(source, settlement({ source: applySource }));
- render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);
await userEvent.click(screen.getByRole('button', { name: /^Refetch$|^重新拉取$/i }));
@@ -915,7 +935,6 @@ describe('SourceDetailPanel', () => {
expect(jsx).toMatch(/editManageDraft/);
expect(jsx).toMatch(/cancelManage/);
expect(jsx).toMatch(/dismissUnresolvedManage/);
- expect(jsx).toMatch(/completeManageImpact/);
});
it('keeps Source entities behind one generation authority without an adoption side cache', () => {
@@ -1057,12 +1076,12 @@ describe('SourceDetailPanel', () => {
const list = vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([{ ...source, models: [] }]);
const onMutation = vi.fn().mockResolvedValue(undefined);
const trackMutation: TrackSourceMutation = (work) => work(source, settlement({ source: onMutation }));
- render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);
await userEvent.click(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i }));
await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));
- await waitFor(() => expect(onMutation).toHaveBeenCalledWith(expect.objectContaining({ models: [] })));
+ await waitFor(() => expect(onMutation).toHaveBeenCalledWith(expect.objectContaining({ models: [] }), undefined));
expect(list).toHaveBeenCalledOnce();
expect(remove).toHaveBeenCalledOnce();
expect(screen.queryByRole('button', { name: /^Try again$|^重试$/i })).toBeNull();
@@ -1103,12 +1122,16 @@ describe('SourceDetailPanel', () => {
vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([]);
const onGone = vi.fn().mockResolvedValue(undefined);
const trackMutation: TrackSourceMutation = (work) => work(source, settlement({ gone: onGone }));
- render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);
await userEvent.click(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i }));
await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));
- await waitFor(() => expect(onGone).toHaveBeenCalledWith(source.id, { kind: 'gone', sources: [], snapshot: 1 }));
+ await waitFor(() => expect(onGone).toHaveBeenCalledWith(
+ source.id,
+ { kind: 'gone', sources: [], snapshot: 1 },
+ undefined,
+ ));
expect(remove).toHaveBeenCalledOnce();
expect(screen.queryByRole('button', { name: /^Try again$|^重试$/i })).toBeNull();
});
@@ -1139,7 +1162,7 @@ describe('SourceDetailPanel', () => {
for (const shape of shapes) {
const view = render(
<I18nextProvider i18n={i18n}>
- <SourceDetailPanel source={shape} trackMutation={immediateTrack} onReauth={vi.fn()} />
+ <ReportOwnedPanel source={shape} trackMutation={immediateTrack} onReauth={vi.fn()} />
</I18nextProvider>,
);
const action = repairAction(shape);
@@ -1160,7 +1183,7 @@ describe('SourceDetailPanel', () => {
it('opens key replacement from the revoked hub credential repair tap', async () => {
render(
<I18nextProvider i18n={i18n}>
- <SourceDetailPanel
+ <ReportOwnedPanel
source={{
...source,
state: {
@@ -1184,7 +1207,7 @@ describe('SourceDetailPanel', () => {
it('confirms a native re-login with the cost it pays at start before handing the source up', async () => {
const native = blockedSubscription('native_cli');
const onReauth = vi.fn();
- render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={native} trackMutation={immediateTrack} onReauth={onReauth} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={native} trackMutation={immediateTrack} onReauth={onReauth} /></I18nextProvider>);
await userEvent.click(screen.getByRole('button', { name: /^Sign in$|^重新登录$/i }));
@@ -1199,7 +1222,7 @@ describe('SourceDetailPanel', () => {
});
it('warns a hub re-login about the cost it can pay, not the one it cannot', async () => {
- render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={blockedSubscription('hub')} trackMutation={immediateTrack} onReauth={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={blockedSubscription('hub')} trackMutation={immediateTrack} onReauth={vi.fn()} /></I18nextProvider>);
await userEvent.click(screen.getByRole('button', { name: /^Sign in$|^重新登录$/i }));
diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsx
index 904d6fc27..48df14d46 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx
@@ -17,7 +17,6 @@ import { GuardImpact } from './GuardImpact';
import {
assessSourceEdit,
canEditSourceEndpoint,
- holdsCommittedImpact,
manageActions,
MANAGE_DESTINATION,
MANAGE_LABEL_KEY,
@@ -26,12 +25,20 @@ import {
} from './manage';
import type {
ManageGuardPlan,
+ ManageCommitAction,
ManageKind,
ManageStage,
SourceEditDraft,
} from './manage';
import { apiFailure, modelsApi, type GuardConfirmation } from './modelsApi';
-import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';
+import {
+ sourceMutationReadScope,
+ type PresentSourceMutationCommit,
+ type SourceMutationLanding,
+ type SourceMutationReadScope,
+ type SourceMutationSettlement,
+ type TrackSourceMutation,
+} from './mutationSettlement';
import { handOffProviderTab } from './providerTab';
import { reconcileUnknownWrite } from './reconcileUnknownWrite';
import { REPAIR_DESTINATION, REPAIR_LABEL_KEY, reauthBodyKey, reauthCost, repairAction } from './repair';
@@ -285,9 +292,11 @@ export const SourceDetailPanel: React.FC<{
* invalidates is wider than the one row this panel owns.
*/
onReauth: (source: Source) => void;
+ /** Owns every post-commit report and read verdict outside this entity panel. */
+ onMutationCommitted: PresentSourceMutationCommit;
/** Stable focus target for callers that navigate into this detail surface. */
headingRef?: React.Ref<HTMLHeadingElement>;
-}> = ({ source, trackMutation, onReauth, headingRef }) => {
+}> = ({ source, trackMutation, onReauth, onMutationCommitted, headingRef }) => {
const { t, i18n } = useTranslation();
const now = useDeadlineClock(source.state.status === 'cooldown' ? source.state.retry_at : null);
const { Icon, accent } = sourceVisual(source);
@@ -295,7 +304,6 @@ export const SourceDetailPanel: React.FC<{
const [confirmingReauth, setConfirmingReauth] = React.useState(false);
const [replacingKey, setReplacingKey] = React.useState(false);
const [manageStage, dispatchManageStage] = React.useReducer(transitionManageStage, { kind: 'idle' });
- const committedImpactReleaseRef = React.useRef<(() => void) | null>(null);
const [manualDraft, setManualDraft] = React.useState<{ modelId: string; tiers: string[]; failed: boolean; retryRead: boolean } | null>(null);
const [guard, setGuard] = React.useState<GuardedAction | null>(null);
const [result, setResult] = React.useState<{ added: string[]; removed: string[] } | null>(null);
@@ -306,16 +314,6 @@ export const SourceDetailPanel: React.FC<{
const editAssessment = editDraft
? assessSourceEdit(source, editDraft)
: { valid: false as const, patch: null, reason: null };
- const releaseCommittedImpact = React.useCallback(() => {
- const release = committedImpactReleaseRef.current;
- committedImpactReleaseRef.current = null;
- release?.();
- }, []);
-
- React.useEffect(() => {
- if (!holdsCommittedImpact(manageStage)) releaseCommittedImpact();
- }, [manageStage, releaseCommittedImpact]);
- React.useEffect(() => () => releaseCommittedImpact(), [releaseCommittedImpact]);
const beginEdit = () => {
dispatchManageStage({
@@ -379,9 +377,14 @@ export const SourceDetailPanel: React.FC<{
: undefined;
},
);
- const applyReconciliation = async (sourceId: string, value: SourceReconciliation, settlement: SourceMutationSettlement) => {
- if (value.kind === 'gone') await settlement.gone(sourceId, value);
- else await settlement.source(value.source);
+ const applyReconciliation = async (
+ sourceId: string,
+ value: SourceReconciliation,
+ settlement: SourceMutationSettlement,
+ scope?: SourceMutationReadScope,
+ ) => {
+ if (value.kind === 'gone') return settlement.gone(sourceId, value, scope);
+ return settlement.source(value.source, scope);
};
const addManualModel = () => {
if (!manualDraft || busy) return;
@@ -489,15 +492,16 @@ export const SourceDetailPanel: React.FC<{
}
}).finally(() => setBusy(false));
};
- const holdCommittedImpact = (
- kind: 'edit' | 'delete',
- plan: ManageGuardPlan,
- settle: Extract<ManageStage, { kind: 'committed_edit_impact' }>['complete'],
- ) => new Promise<void>((resolve) => {
- setBusy(false);
- committedImpactReleaseRef.current = resolve;
- dispatchManageStage({ type: 'commit_impact', action: kind, plan, complete: settle });
- });
+ const commitManagementMutation = async (
+ action: ManageCommitAction,
+ impact: ManageGuardPlan | null,
+ settle: (scope: SourceMutationReadScope) => Promise<SourceMutationLanding>,
+ ) => {
+ dispatchManageStage({ type: 'commit', action });
+ const scope = sourceMutationReadScope(impact);
+ await onMutationCommitted({ action, impact, settle: () => settle(scope) });
+ dispatchManageStage({ type: 'settled' });
+ };
const reconcileEditWrite = async (
before: Source,
draft: SourceEditDraft,
@@ -523,16 +527,11 @@ export const SourceDetailPanel: React.FC<{
const current = reconciliation.value.kind === 'source'
? reconciliation.value.source
: null;
- if (current && plan) {
- await holdCommittedImpact(
- 'edit',
- plan,
- () => settlement.source(current),
- );
- } else {
- dispatchManageStage({ type: 'settled' });
- await applyReconciliation(before.id, reconciliation.value, settlement);
- }
+ await commitManagementMutation(
+ 'edit',
+ current ? plan : null,
+ (scope) => applyReconciliation(before.id, reconciliation.value, settlement, scope),
+ );
return;
}
settlement.release();
@@ -558,16 +557,11 @@ export const SourceDetailPanel: React.FC<{
: { sources, snapshot },
);
if (reconciliation.kind === 'committed') {
- if (plan) {
- await holdCommittedImpact(
- 'delete',
- plan,
- () => settlement.gone(before.id, reconciliation.value),
- );
- } else {
- dispatchManageStage({ type: 'settled' });
- await settlement.gone(before.id, reconciliation.value);
- }
+ await commitManagementMutation(
+ 'delete',
+ plan,
+ (scope) => settlement.gone(before.id, reconciliation.value, scope),
+ );
return;
}
settlement.release();
@@ -597,16 +591,19 @@ export const SourceDetailPanel: React.FC<{
plan ? { ...patch, ...confirmGuardPlan(plan) } : patch,
);
const impact = committedPlan(answer.removed_hops, answer.interrupted);
- if (impact) await holdCommittedImpact('edit', impact, () => settlement.source(answer.source));
- else {
- dispatchManageStage({ type: 'settled' });
- await settlement.source(answer.source);
- }
+ await commitManagementMutation(
+ 'edit',
+ impact,
+ (scope) => settlement.source(answer.source, scope),
+ );
} catch (error) {
const failure = apiFailure(error);
if (failure?.code === 'source_not_found') {
- dispatchManageStage({ type: 'settled' });
- await settlement.gone(latest.id);
+ await commitManagementMutation(
+ 'edit',
+ null,
+ (scope) => settlement.gone(latest.id, undefined, scope),
+ );
} else if (classifyModelHubFailure(failure) === 'inconclusive') {
await reconcileEditWrite(latest, draft, patch, plan, settlement);
} else {
@@ -642,16 +639,19 @@ export const SourceDetailPanel: React.FC<{
plan ? confirmGuardPlan(plan) : undefined,
);
const impact = committedPlan(answer.removed_hops, answer.interrupted);
- if (impact) await holdCommittedImpact('delete', impact, () => settlement.gone(latest.id));
- else {
- dispatchManageStage({ type: 'settled' });
- await settlement.gone(latest.id);
- }
+ await commitManagementMutation(
+ 'delete',
+ impact,
+ (scope) => settlement.gone(latest.id, undefined, scope),
+ );
} catch (error) {
const failure = apiFailure(error);
if (failure?.code === 'source_not_found') {
- dispatchManageStage({ type: 'settled' });
- await settlement.gone(latest.id);
+ await commitManagementMutation(
+ 'delete',
+ null,
+ (scope) => settlement.gone(latest.id, undefined, scope),
+ );
} else if (classifyModelHubFailure(failure) === 'inconclusive') {
await reconcileDeleteWrite(latest, plan, settlement);
} else {
@@ -716,18 +716,6 @@ export const SourceDetailPanel: React.FC<{
if (busy) return;
dispatchManageStage({ type: 'dismiss_unresolved' });
};
- const completeManageImpact = () => {
- if (busy || (
- manageStage.kind !== 'committed_edit_impact'
- && manageStage.kind !== 'committed_delete_impact'
- )) return;
- const complete = manageStage.complete;
- setBusy(true);
- void complete()
- .then((verdict) => dispatchManageStage({ type: 'land', verdict }))
- .catch(() => dispatchManageStage({ type: 'land', verdict: 'degraded' }))
- .finally(() => setBusy(false));
- };
const editManageDraft = (draft: SourceEditDraft) => {
dispatchManageStage({ type: 'edit_draft', draft });
};
@@ -760,13 +748,7 @@ export const SourceDetailPanel: React.FC<{
const manageGuardOpen = manageStage.kind === 'confirming_edit'
|| manageStage.kind === 'confirming_delete'
|| manageStage.kind === 'submitting_delete'
- || (manageStage.kind === 'submitting_edit' && manageStage.surface === 'guard')
- || manageStage.kind === 'committed_edit_impact'
- || manageStage.kind === 'committed_delete_impact';
- const manageImpact = manageStage.kind === 'committed_edit_impact'
- || manageStage.kind === 'committed_delete_impact'
- ? manageStage
- : null;
+ || (manageStage.kind === 'submitting_edit' && manageStage.surface === 'guard');
const manageUnresolved = (manageStage.kind === 'edit_failed' || manageStage.kind === 'delete_failed')
&& manageStage.retryRead;
const managePlan = 'plan' in manageStage ? manageStage.plan : null;
@@ -933,27 +915,20 @@ export const SourceDetailPanel: React.FC<{
>
<header className="model-hub-guard-head">
<div className="flex items-center justify-between gap-3">
- <DialogPrimitive.Title className="model-hub-guard-title text-foreground">{manageImpact
- ? t(`settings.models.sourceDetail.${manageImpact.kind === 'committed_edit_impact' ? 'edit' : 'remove'}.impact.title`)
- : manageGuardOpen
+ <DialogPrimitive.Title className="model-hub-guard-title text-foreground">{manageGuardOpen
? t(`settings.models.guard.title.${manageCopyKind}`, { source: source.display_name })
: t(`settings.models.guard.title.${guard ? GUARD_COPY_KIND[guard.kind] : 'refetch'}`, { model: guard?.kind === 'removeModel' ? guard.model.id : undefined, source: source.display_name })}</DialogPrimitive.Title>
- <DialogPrimitive.Close asChild><Button type="button" variant="ghost" size="icon" className="model-hub-guard-close" disabled={busy || (manageImpact !== null && !manageImpact.landingFailed)} onClick={manageImpact?.landingFailed ? dismissUnresolvedManage : undefined} aria-label={t(manageImpact?.landingFailed ? 'settings.models.sourceDetail.dismissUnverified' : manageImpact ? `settings.models.sourceDetail.${manageImpact.kind === 'committed_edit_impact' ? 'edit' : 'remove'}.impact.done` : 'settings.models.guard.cancel')} title={t(manageImpact?.landingFailed ? 'settings.models.sourceDetail.dismissUnverified' : manageImpact ? `settings.models.sourceDetail.${manageImpact.kind === 'committed_edit_impact' ? 'edit' : 'remove'}.impact.done` : 'settings.models.guard.cancel')}><X aria-hidden /></Button></DialogPrimitive.Close>
+ <DialogPrimitive.Close asChild><Button type="button" variant="ghost" size="icon" className="model-hub-guard-close" disabled={busy} aria-label={t('settings.models.guard.cancel')} title={t('settings.models.guard.cancel')}><X aria-hidden /></Button></DialogPrimitive.Close>
</div>
- <DialogPrimitive.Description className="model-hub-guard-subtitle">{manageImpact
- ? t(`settings.models.sourceDetail.${manageImpact.kind === 'committed_edit_impact' ? 'edit' : 'remove'}.impact.detail`)
- : manageGuardOpen
+ <DialogPrimitive.Description className="model-hub-guard-subtitle">{manageGuardOpen
? t(`settings.models.guard.subtitle.${manageCopyKind}`)
: t(`settings.models.guard.subtitle.${guard ? GUARD_COPY_KIND[guard.kind] : 'refetch'}`)}</DialogPrimitive.Description>
</header>
- {manageImpact && <div className="model-hub-guard-body"><GuardImpact hops={manageImpact.plan.hops} gaps={manageImpact.plan.gaps} committed />{manageImpact.landingFailed && <p data-manage-impact-failure className="text-[11.5px] text-destructive-ink">{t('settings.models.sourceDetail.impact.refreshFail')}</p>}</div>}
- {!manageImpact && manageGuardOpen && managePlan && <div className="model-hub-guard-body"><GuardImpact hops={managePlan.hops} gaps={managePlan.gaps} /></div>}
+ {manageGuardOpen && managePlan && <div className="model-hub-guard-body"><GuardImpact hops={managePlan.hops} gaps={managePlan.gaps} /></div>}
{!manageGuardOpen && guard?.plan && <div className="model-hub-guard-body"><GuardImpact hops={guard.plan.hops} gaps={guard.plan.gaps} /></div>}
- {manageImpact
- ? <footer className="model-hub-guard-foot">{manageImpact.landingFailed && <Button type="button" variant="outline" className="model-hub-guard-action" onClick={dismissUnresolvedManage} disabled={busy}>{t('settings.models.sourceDetail.dismissUnverified')}</Button>}<Button className="model-hub-guard-action" onClick={completeManageImpact} disabled={busy}>{busy && <Loader2 className="animate-spin" />}{t(manageImpact.landingFailed ? 'settings.models.sourceDetail.retry' : `settings.models.sourceDetail.${manageImpact.kind === 'committed_edit_impact' ? 'edit' : 'remove'}.impact.done`)}</Button></footer>
- : manageGuardOpen
- ? <footer className="model-hub-guard-foot"><Button variant="outline" className="model-hub-guard-action" onClick={cancelManage} disabled={busy}>{t('settings.models.guard.cancel')}</Button><Button variant="destructive" className="model-hub-guard-action" onClick={confirmManage} disabled={busy}>{busy && <Loader2 className="animate-spin" />}{t(`settings.models.guard.confirm.${manageCopyKind}`)}</Button></footer>
- : <footer className="model-hub-guard-foot"><Button variant="outline" className="model-hub-guard-action" onClick={() => setGuard(null)} disabled={busy}>{t('settings.models.guard.cancel')}</Button><Button variant="destructive" className="model-hub-guard-action" onClick={confirmGuard} disabled={busy}>{busy && <Loader2 className="animate-spin" />}{t(`settings.models.guard.confirm.${guard ? GUARD_COPY_KIND[guard.kind] : 'refetch'}`)}</Button></footer>}
+ {manageGuardOpen
+ ? <footer className="model-hub-guard-foot"><Button variant="outline" className="model-hub-guard-action" onClick={cancelManage} disabled={busy}>{t('settings.models.guard.cancel')}</Button><Button variant="destructive" className="model-hub-guard-action" onClick={confirmManage} disabled={busy}>{busy && <Loader2 className="animate-spin" />}{t(`settings.models.guard.confirm.${manageCopyKind}`)}</Button></footer>
+ : <footer className="model-hub-guard-foot"><Button variant="outline" className="model-hub-guard-action" onClick={() => setGuard(null)} disabled={busy}>{t('settings.models.guard.cancel')}</Button><Button variant="destructive" className="model-hub-guard-action" onClick={confirmGuard} disabled={busy}>{busy && <Loader2 className="animate-spin" />}{t(`settings.models.guard.confirm.${guard ? GUARD_COPY_KIND[guard.kind] : 'refetch'}`)}</Button></footer>}
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
</DialogPrimitive.Root>
diff --git a/ui/src/components/settings/models/SourceMutationReport.tsx b/ui/src/components/settings/models/SourceMutationReport.tsx
new file mode 100644
index 000000000..7fc250e17
--- /dev/null
+++ b/ui/src/components/settings/models/SourceMutationReport.tsx
@@ -0,0 +1,103 @@
+import * as React from 'react';
+import * as DialogPrimitive from '@radix-ui/react-dialog';
+import { Loader2, X } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@/components/ui/button';
+import { GuardImpact } from './GuardImpact';
+import { SOURCE_MUTATION_REPORT_PROJECTIONS } from './mutationSettlement';
+import type { SourceMutationReportState } from './useSourceMutationReport';
+
+export const SourceMutationReport: React.FC<{
+ report: SourceMutationReportState | null;
+ onComplete: () => void;
+ onDismiss: () => void;
+}> = ({ report, onComplete, onDismiss }) => {
+ const { t } = useTranslation();
+ const impact = report?.commit.impact ?? null;
+ const action = report?.commit.action ?? 'edit';
+ const copyKind = action === 'edit' ? 'edit' : 'remove';
+ const titleKey = impact
+ ? `settings.models.sourceDetail.${copyKind}.impact.title`
+ : `settings.models.sourceDetail.${copyKind}.settlement.title`;
+ const detailKey = impact
+ ? `settings.models.sourceDetail.${copyKind}.impact.detail`
+ : 'settings.models.sourceDetail.impact.refreshFail';
+ const actionKey = report?.landingFailed
+ ? 'settings.models.sourceDetail.retry'
+ : `settings.models.sourceDetail.${copyKind}.impact.done`;
+
+ return (
+ <DialogPrimitive.Root
+ open={report !== null}
+ onOpenChange={(open) => { if (!open && report?.landingFailed && !report.busy) onDismiss(); }}
+ >
+ <DialogPrimitive.Portal>
+ <DialogPrimitive.Overlay className="model-hub-guard-overlay fixed inset-0 z-50" />
+ <DialogPrimitive.Content
+ data-source-mutation-report={action}
+ data-report-projections={Object.keys(SOURCE_MUTATION_REPORT_PROJECTIONS).join(' ')}
+ className="model-hub-guard-dialog fixed left-1/2 top-1/2 z-50 flex max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col overflow-y-auto border border-border-strong bg-surface outline-none"
+ onEscapeKeyDown={(event) => { if (!report?.landingFailed || report.busy) event.preventDefault(); }}
+ onPointerDownOutside={(event) => event.preventDefault()}
+ >
+ <header className="model-hub-guard-head">
+ <div className="flex items-center justify-between gap-3">
+ <DialogPrimitive.Title className="model-hub-guard-title text-foreground">
+ {t(titleKey)}
+ </DialogPrimitive.Title>
+ <DialogPrimitive.Close asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="model-hub-guard-close"
+ disabled={!report?.landingFailed || report.busy}
+ aria-label={t(report?.landingFailed ? 'settings.models.sourceDetail.dismissUnverified' : actionKey)}
+ title={t(report?.landingFailed ? 'settings.models.sourceDetail.dismissUnverified' : actionKey)}
+ >
+ <X aria-hidden />
+ </Button>
+ </DialogPrimitive.Close>
+ </div>
+ <DialogPrimitive.Description className="model-hub-guard-subtitle">
+ {t(detailKey)}
+ </DialogPrimitive.Description>
+ </header>
+ {impact && (
+ <div className="model-hub-guard-body">
+ <GuardImpact hops={impact.hops} gaps={impact.gaps} committed />
+ {report?.landingFailed && (
+ <p data-manage-impact-failure className="text-[11.5px] text-destructive-ink">
+ {t('settings.models.sourceDetail.impact.refreshFail')}
+ </p>
+ )}
+ </div>
+ )}
+ <footer className="model-hub-guard-foot">
+ {report?.landingFailed && (
+ <Button
+ type="button"
+ variant="outline"
+ className="model-hub-guard-action"
+ onClick={onDismiss}
+ disabled={report.busy}
+ >
+ {t('settings.models.sourceDetail.dismissUnverified')}
+ </Button>
+ )}
+ <Button
+ type="button"
+ className="model-hub-guard-action"
+ onClick={onComplete}
+ disabled={!report || report.busy}
+ >
+ {report?.busy && <Loader2 className="animate-spin" />}
+ {t(actionKey)}
+ </Button>
+ </footer>
+ </DialogPrimitive.Content>
+ </DialogPrimitive.Portal>
+ </DialogPrimitive.Root>
+ );
+};
diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.ts
index 241a948e2..1136fd62c 100644
--- a/ui/src/components/settings/models/asyncLifetime.test.ts
+++ b/ui/src/components/settings/models/asyncLifetime.test.ts
@@ -330,8 +330,8 @@ describe('Source entity landing through the shared authority', () => {
expect(detail).toMatch(/trackMutation\(async \(latest, settlement\)[\s\S]*?modelsApi\.refreshSource\(latest\.id, confirmation\)/);
expect(detail).toMatch(/await settlement\.source\(answer\.source\)/);
expect(page).toMatch(/sourceWriteRegistry\.track\(sourceId[\s\S]*?sourceEntityAuthority\.current\(sourceId\)[\s\S]*?sourceEntityAuthority\.begin\(sourceId\)[\s\S]*?const settlement: SourceMutationSettlement/);
- expect(page).toMatch(/source: async \(echoed\)[\s\S]*?sourceEntityAuthority\.settle\(generation/);
- expect(page).not.toMatch(/const sourceMutation|activeSourceGenerations/);
+ expect(page).toMatch(/source: async \(echoed, scope\)[\s\S]*?sourceEntityAuthority\.settle\(generation/);
+ expect(page).not.toMatch(/const sourceMutation\s*=|activeSourceGenerations/);
expect(page).toMatch(/await refreshAuthority\.run/);
expect(sourceRetry).toMatch(/await refresh\(\)/);
expect(supplyRetry).toMatch(/await refresh\(\)/);
diff --git a/ui/src/components/settings/models/eventFeed.test.ts b/ui/src/components/settings/models/eventFeed.test.ts
index fb36c2c96..59563aa8e 100644
--- a/ui/src/components/settings/models/eventFeed.test.ts
+++ b/ui/src/components/settings/models/eventFeed.test.ts
@@ -201,6 +201,7 @@ describe('feedAfterTailRead — 加载更早, and the first page at mount', () =
describe('the page reads the feed through this owner', () => {
const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');
const firstPaint = readFileSync(join(__dirname, 'firstPaintRegions.ts'), 'utf8');
+ const mutationSettlement = readFileSync(join(__dirname, 'mutationSettlement.ts'), 'utf8');
it('re-reads events in the shared post-write refresh', () => {
// The whole point: the refresh every mutation site already calls is what has
@@ -213,7 +214,10 @@ describe('the page reads the feed through this owner', () => {
it('lets the ancillary feed read fail without losing the rows', () => {
// A slow or broken /events must not enter the operational first-paint barrier.
- const landing = page.slice(page.indexOf('const readSurfaceLanding'), page.indexOf('\n\nconst surfaceLandingFailed'));
+ const landing = mutationSettlement.slice(
+ mutationSettlement.indexOf('export const readSurfaceLanding'),
+ mutationSettlement.indexOf('\n\nexport type SourceMutationLanding ='),
+ );
expect(landing).not.toMatch(/listEvents|events/);
expect(page).toMatch(/createLatestAsyncAuthority<RegionRead<ResolutionEvent\[\]>>/);
expect(page).toMatch(/createLatestAsyncAuthority<AuthorizedSurfaceLanding>/);
diff --git a/ui/src/components/settings/models/manage.test.ts b/ui/src/components/settings/models/manage.test.ts
index bbd07ac1e..bf380cc8c 100644
--- a/ui/src/components/settings/models/manage.test.ts
+++ b/ui/src/components/settings/models/manage.test.ts
@@ -7,8 +7,8 @@ import zh from '../../../i18n/zh.json';
import {
assessSourceEdit,
canEditSourceEndpoint,
- holdsCommittedImpact,
manageActions,
+ MANAGE_COMMIT_ACTIONS,
MANAGE_DESTINATION,
MANAGE_LABEL_KEY,
MANAGE_STAGE_CANCEL,
@@ -16,8 +16,8 @@ import {
MANAGE_STAGE_EDIT_DRAFT,
MANAGE_STAGE_FAILURE_SURFACE,
MANAGE_STAGE_KINDS,
- MANAGE_STAGE_LANDING,
MANAGE_STAGE_RETRY,
+ MANAGE_STAGE_SETTLED,
SOURCE_EDIT_REASON_KEY,
transitionManageStage,
} from './manage';
@@ -89,7 +89,7 @@ describe('source management capabilities', () => {
MANAGE_STAGE_RETRY,
MANAGE_STAGE_EDIT_DRAFT,
MANAGE_STAGE_DISMISS_UNRESOLVED,
- MANAGE_STAGE_LANDING,
+ MANAGE_STAGE_SETTLED,
]) {
expect(new Set(Object.keys(record))).toEqual(new Set(MANAGE_STAGE_KINDS));
for (const kind of MANAGE_STAGE_KINDS) expect(record[kind]).toEqual(expect.any(Function));
@@ -134,24 +134,25 @@ describe('source management capabilities', () => {
}
});
- it('earns exit from every committed impact stage from landing evidence', () => {
- const plan = { hops: [], gaps: [] };
- const complete = async () => 'landed' as const;
- const committed = {
- committed_edit_impact: { kind: 'committed_edit_impact', plan, complete, landingFailed: false },
- committed_delete_impact: { kind: 'committed_delete_impact', plan, complete, landingFailed: false },
- } satisfies {
- [Kind in Extract<ManageStage, { landingFailed: boolean }>['kind']]: Extract<ManageStage, { kind: Kind }>
- };
+ it('announces settlement only after every committed mutation action', () => {
+ const submitting = {
+ edit: {
+ kind: 'submitting_edit',
+ draft: { displayName: source().display_name, baseUrl: source().base_url ?? '' },
+ patch: { display_name: 'Updated' },
+ plan: null,
+ forced: false,
+ surface: 'edit',
+ },
+ delete: { kind: 'submitting_delete', plan: null, forced: false },
+ } satisfies Record<(typeof MANAGE_COMMIT_ACTIONS)[number], ManageStage>;
- for (const stage of Object.values(committed)) {
- const degraded = transitionManageStage(stage, { type: 'land', verdict: 'degraded' });
- expect(degraded.kind).toBe(stage.kind);
- expect('plan' in degraded && degraded.plan).toBe(plan);
- expect('landingFailed' in degraded && degraded.landingFailed).toBe(true);
- expect(transitionManageStage(stage, { type: 'dismiss_unresolved' })).toBe(stage);
- expect(transitionManageStage(degraded, { type: 'dismiss_unresolved' })).toEqual({ kind: 'idle' });
- expect(transitionManageStage(degraded, { type: 'land', verdict: 'landed' })).toEqual({ kind: 'idle' });
+ expect(new Set(Object.keys(submitting))).toEqual(new Set(MANAGE_COMMIT_ACTIONS));
+ for (const action of MANAGE_COMMIT_ACTIONS) {
+ expect(transitionManageStage(submitting[action], { type: 'settled' })).toBe(submitting[action]);
+ const committed = transitionManageStage(submitting[action], { type: 'commit', action });
+ expect(committed.kind).toBe(`committed_${action}`);
+ expect(transitionManageStage(committed, { type: 'settled' })).toEqual({ kind: 'idle' });
}
});
@@ -160,7 +161,6 @@ describe('source management capabilities', () => {
const draft = { displayName: before.display_name, baseUrl: before.base_url ?? '' };
const patch = { display_name: before.display_name };
const plan = { hops: [], gaps: [] };
- const complete = async () => 'landed' as const;
const stages = {
idle: { kind: 'idle' },
editing: { kind: 'editing', draft },
@@ -170,19 +170,19 @@ describe('source management capabilities', () => {
confirming_delete: { kind: 'confirming_delete', plan },
submitting_delete: { kind: 'submitting_delete', plan, forced: true },
delete_failed: { kind: 'delete_failed', plan, forced: true, retryRead: true, before },
- committed_edit_impact: { kind: 'committed_edit_impact', plan, complete, landingFailed: true },
- committed_delete_impact: { kind: 'committed_delete_impact', plan, complete, landingFailed: true },
+ committed_edit: { kind: 'committed_edit' },
+ committed_delete: { kind: 'committed_delete' },
} satisfies { [Kind in ManageStage['kind']]: Extract<ManageStage, { kind: Kind }> };
const exitEvents = [
{ type: 'cancel' },
{ type: 'dismiss_unresolved' },
{ type: 'settled' },
- { type: 'land', verdict: 'landed' },
+ { type: 'commit', action: 'edit' },
+ { type: 'commit', action: 'delete' },
] as const;
expect(new Set(Object.keys(stages))).toEqual(new Set(MANAGE_STAGE_KINDS));
for (const stage of Object.values(stages)) {
- expect(holdsCommittedImpact(stage), `${stage.kind}:holds committed impact`).toBe('complete' in stage);
if (stage.kind === 'idle') continue;
expect(
exitEvents.some((event) => transitionManageStage(stage, event).kind !== stage.kind),
diff --git a/ui/src/components/settings/models/manage.ts b/ui/src/components/settings/models/manage.ts
index 9ee16cf68..4a7852869 100644
--- a/ui/src/components/settings/models/manage.ts
+++ b/ui/src/components/settings/models/manage.ts
@@ -1,6 +1,10 @@
-import type { RouteHopRef, Source, SourcePatch, SupplyGap } from './types';
+import type { Source, SourcePatch } from './types';
import { SOURCE_DISPLAY_NAME_MAX_LENGTH } from './types';
-import type { SourceMutationLanding } from './mutationSettlement';
+import {
+ SOURCE_MUTATION_ACTIONS,
+ type SourceMutationAction,
+ type SourceMutationImpact,
+} from './mutationSettlement';
import { optionalTrimmedTextWithin } from './validation';
/** Management changes a valid Source; repair restores a blocked one. */
@@ -30,7 +34,10 @@ export type SourceEditDraft = {
baseUrl: string;
};
-export type ManageGuardPlan = { hops: RouteHopRef[]; gaps: SupplyGap[] };
+export type ManageGuardPlan = SourceMutationImpact;
+
+export const MANAGE_COMMIT_ACTIONS = SOURCE_MUTATION_ACTIONS;
+export type ManageCommitAction = SourceMutationAction;
export const MANAGE_STAGE_KINDS = [
'idle',
@@ -41,8 +48,8 @@ export const MANAGE_STAGE_KINDS = [
'confirming_delete',
'submitting_delete',
'delete_failed',
- 'committed_edit_impact',
- 'committed_delete_impact',
+ 'committed_edit',
+ 'committed_delete',
] as const;
export type ManageStageKind = (typeof MANAGE_STAGE_KINDS)[number];
@@ -55,15 +62,10 @@ export type ManageStage =
| { kind: 'confirming_delete'; plan: ManageGuardPlan | null }
| { kind: 'submitting_delete'; plan: ManageGuardPlan | null; forced: boolean }
| { kind: 'delete_failed'; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }
- | { kind: 'committed_edit_impact'; plan: ManageGuardPlan; complete: () => Promise<SourceMutationLanding>; landingFailed: boolean }
- | { kind: 'committed_delete_impact'; plan: ManageGuardPlan; complete: () => Promise<SourceMutationLanding>; landingFailed: boolean };
-
-export const holdsCommittedImpact = (
- stage: ManageStage,
-): stage is Extract<ManageStage, { landingFailed: boolean }> =>
- stage.kind === 'committed_edit_impact' || stage.kind === 'committed_delete_impact';
+ | { kind: 'committed_edit' }
+ | { kind: 'committed_delete' };
-export type ManageFailureSurface = 'none' | 'edit_dialog' | 'guard_dialog' | 'delete_inline' | 'committed_dialog';
+export type ManageFailureSurface = 'none' | 'edit_dialog' | 'guard_dialog' | 'delete_inline';
type ManageStageTransition<Event> = {
[Kind in ManageStageKind]: (
@@ -76,7 +78,7 @@ type CancelManageStage = { type: 'cancel' };
type RetryManageStage = { type: 'retry' };
type EditManageDraft = { type: 'edit_draft'; draft: SourceEditDraft };
type DismissUnresolvedManageStage = { type: 'dismiss_unresolved' };
-type LandManageStage = { type: 'land'; verdict: SourceMutationLanding };
+type SettleManageStage = { type: 'settled' };
const keepManageStage = <Stage extends ManageStage>(stage: Stage): Stage => stage;
const idleManageStage = (): ManageStage => ({ kind: 'idle' });
@@ -91,8 +93,8 @@ export const MANAGE_STAGE_CANCEL = {
confirming_delete: idleManageStage,
submitting_delete: keepManageStage,
delete_failed: (stage) => stage.retryRead ? stage : idleManageStage(),
- committed_edit_impact: keepManageStage,
- committed_delete_impact: keepManageStage,
+ committed_edit: keepManageStage,
+ committed_delete: keepManageStage,
} satisfies ManageStageTransition<CancelManageStage>;
export const MANAGE_STAGE_RETRY = {
@@ -126,8 +128,8 @@ export const MANAGE_STAGE_RETRY = {
plan: stage.plan,
forced: stage.forced,
}),
- committed_edit_impact: keepManageStage,
- committed_delete_impact: keepManageStage,
+ committed_edit: keepManageStage,
+ committed_delete: keepManageStage,
} satisfies ManageStageTransition<RetryManageStage>;
export const MANAGE_STAGE_EDIT_DRAFT = {
@@ -139,8 +141,8 @@ export const MANAGE_STAGE_EDIT_DRAFT = {
confirming_delete: keepManageStage,
submitting_delete: keepManageStage,
delete_failed: keepManageStage,
- committed_edit_impact: keepManageStage,
- committed_delete_impact: keepManageStage,
+ committed_edit: keepManageStage,
+ committed_delete: keepManageStage,
} satisfies ManageStageTransition<EditManageDraft>;
export const MANAGE_STAGE_DISMISS_UNRESOLVED = {
@@ -152,11 +154,12 @@ export const MANAGE_STAGE_DISMISS_UNRESOLVED = {
confirming_delete: keepManageStage,
submitting_delete: keepManageStage,
delete_failed: (stage) => stage.retryRead ? idleManageStage() : stage,
- committed_edit_impact: (stage) => stage.landingFailed ? idleManageStage() : stage,
- committed_delete_impact: (stage) => stage.landingFailed ? idleManageStage() : stage,
+ committed_edit: keepManageStage,
+ committed_delete: keepManageStage,
} satisfies ManageStageTransition<DismissUnresolvedManageStage>;
-export const MANAGE_STAGE_LANDING = {
+/** Settlement may close only a post-commit stage; every earlier announcement is ignored. */
+export const MANAGE_STAGE_SETTLED = {
idle: keepManageStage,
editing: keepManageStage,
submitting_edit: keepManageStage,
@@ -165,13 +168,9 @@ export const MANAGE_STAGE_LANDING = {
confirming_delete: keepManageStage,
submitting_delete: keepManageStage,
delete_failed: keepManageStage,
- committed_edit_impact: (stage, event) => event.verdict === 'landed'
- ? idleManageStage()
- : { ...stage, landingFailed: true },
- committed_delete_impact: (stage, event) => event.verdict === 'landed'
- ? idleManageStage()
- : { ...stage, landingFailed: true },
-} satisfies ManageStageTransition<LandManageStage>;
+ committed_edit: idleManageStage,
+ committed_delete: idleManageStage,
+} satisfies ManageStageTransition<SettleManageStage>;
export type ManageStageEvent =
| { type: 'begin_edit'; draft: SourceEditDraft }
@@ -182,13 +181,12 @@ export type ManageStageEvent =
| { type: 'guard_delete'; plan: ManageGuardPlan }
| { type: 'fail_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }
| { type: 'fail_delete'; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }
- | { type: 'commit_impact'; action: 'edit' | 'delete'; plan: ManageGuardPlan; complete: () => Promise<SourceMutationLanding> }
+ | { type: 'commit'; action: ManageCommitAction }
| { type: 'settled' }
| CancelManageStage
| RetryManageStage
| EditManageDraft
- | DismissUnresolvedManageStage
- | LandManageStage;
+ | DismissUnresolvedManageStage;
const applyManageStageTransition = <Event,>(
transitions: ManageStageTransition<Event>,
@@ -239,15 +237,14 @@ export const transitionManageStage = (stage: ManageStage, event: ManageStageEven
retryRead: event.retryRead,
before: event.before,
};
- case 'commit_impact': return event.action === 'edit'
- ? { kind: 'committed_edit_impact', plan: event.plan, complete: event.complete, landingFailed: false }
- : { kind: 'committed_delete_impact', plan: event.plan, complete: event.complete, landingFailed: false };
- case 'settled': return idleManageStage();
+ case 'commit': return event.action === 'edit'
+ ? { kind: 'committed_edit' }
+ : { kind: 'committed_delete' };
+ case 'settled': return applyManageStageTransition(MANAGE_STAGE_SETTLED, stage, event);
case 'cancel': return applyManageStageTransition(MANAGE_STAGE_CANCEL, stage, event);
case 'retry': return applyManageStageTransition(MANAGE_STAGE_RETRY, stage, event);
case 'edit_draft': return applyManageStageTransition(MANAGE_STAGE_EDIT_DRAFT, stage, event);
case 'dismiss_unresolved': return applyManageStageTransition(MANAGE_STAGE_DISMISS_UNRESOLVED, stage, event);
- case 'land': return applyManageStageTransition(MANAGE_STAGE_LANDING, stage, event);
}
};
@@ -260,8 +257,8 @@ export const MANAGE_STAGE_FAILURE_SURFACE: Record<ManageStageKind, ManageFailure
confirming_delete: 'guard_dialog',
submitting_delete: 'delete_inline',
delete_failed: 'delete_inline',
- committed_edit_impact: 'committed_dialog',
- committed_delete_impact: 'committed_dialog',
+ committed_edit: 'none',
+ committed_delete: 'none',
};
export type SourceEditInvalidReason =
diff --git a/ui/src/components/settings/models/mutationConvergence.test.ts b/ui/src/components/settings/models/mutationConvergence.test.ts
index e46ac9a49..38347d694 100644
--- a/ui/src/components/settings/models/mutationConvergence.test.ts
+++ b/ui/src/components/settings/models/mutationConvergence.test.ts
@@ -48,7 +48,7 @@ describe('convergeMutation', () => {
expect(page).toMatch(/const sourceAdded = async[\s\S]*?await convergeMutation\(\{[\s\S]*?intent:\s*\{[\s\S]*?reconcile: refresh/);
expect(page).toMatch(/const trackSourceMutation[\s\S]*?sourceEntityAuthority\.current\(sourceId\)[\s\S]*?const settlement: SourceMutationSettlement/);
expect(detail).toMatch(/reconcileRemoval[\s\S]*?await applyReconciliation\(sourceId, reconciliation\.value, settlement\)/);
- expect(detail).toMatch(/kind: 'gone'[\s\S]*?await settlement\.gone\(sourceId, value\)/);
- expect(detail).not.toMatch(/onSourceEcho|onChanged|onMutation|onGone/);
+ expect(detail).toMatch(/if \(value\.kind === 'gone'\) return settlement\.gone\(sourceId, value, scope\)/);
+ expect(detail).not.toMatch(/onSourceEcho|onChanged|onGone|\bonMutation(?:=|:)/);
});
});
diff --git a/ui/src/components/settings/models/mutationSettlement.test.ts b/ui/src/components/settings/models/mutationSettlement.test.ts
index 17be7f125..831cd6025 100644
--- a/ui/src/components/settings/models/mutationSettlement.test.ts
+++ b/ui/src/components/settings/models/mutationSettlement.test.ts
@@ -4,8 +4,18 @@ import { fileURLToPath } from 'node:url';
import { describe, expect, it, vi } from 'vitest';
-import { createContinuationSettlement, createSourceCreatedDelivery } from './mutationSettlement';
+import { modelChainKey } from './modelRows';
import type { SourceCreated } from './modelsApi';
+import {
+ createContinuationSettlement,
+ createSourceCreatedDelivery,
+ readSurfaceLanding,
+ SOURCE_MUTATION_REPORT_PROJECTIONS,
+ sourceMutationLanding,
+ sourceMutationReadScope,
+} from './mutationSettlement';
+import { failRegionRead, readyRegion, unreadRegion } from './regionRead';
+import type { AgentChain, AgentSupply, RuntimeDependency, Source } from './types';
describe('mutation settlement fences', () => {
it('atomically rejects every effect belonging to an invalidated attempt', () => {
@@ -44,15 +54,72 @@ describe('mutation settlement fences', () => {
expect(detail).toContain('settlement.gone');
});
- it('carries the surface landing verdict through every Source settlement', () => {
+ it('lands only after every projection referenced by the report was read', async () => {
+ const impact = {
+ hops: [{ backend: 'claude' as const, menu_model: 'claude-opus-4-6', position: 1, source_id: 'src', model_id: 'model-a' }],
+ gaps: [{ backend: 'codex' as const, model_id: 'gpt-5.6-sol', agents: ['release'] }],
+ };
+ const affectedChains = sourceMutationReadScope(impact).affectedChains;
+ const calls: string[] = [];
+ const reads = await readSurfaceLanding({
+ sources: async () => { calls.push('sources'); return [] as Source[]; },
+ supply: async () => { calls.push('supply'); return [] as AgentSupply[]; },
+ runtime: async () => { calls.push('runtime'); return {} as RuntimeDependency; },
+ chains: async (requests) => {
+ calls.push('chains');
+ return Object.fromEntries(requests.map(({ backend, modelId }) => [
+ modelChainKey(backend, modelId),
+ readyRegion({} as AgentChain),
+ ]));
+ },
+ }, affectedChains);
+
+ expect(new Set(calls)).toEqual(new Set(Object.keys(SOURCE_MUTATION_REPORT_PROJECTIONS)));
+ expect(new Set(Object.keys(reads))).toEqual(new Set(Object.keys(SOURCE_MUTATION_REPORT_PROJECTIONS)));
+ expect(sourceMutationLanding(reads, affectedChains, true).verdict).toBe('landed');
+
+ for (const projection of Object.keys(
+ SOURCE_MUTATION_REPORT_PROJECTIONS,
+ ) as (keyof typeof SOURCE_MUTATION_REPORT_PROJECTIONS)[]) {
+ expect(
+ sourceMutationLanding({
+ ...reads,
+ [projection]: failRegionRead(reads[projection]),
+ }, affectedChains, true).verdict,
+ projection,
+ ).toBe('degraded');
+ }
+
+ for (const request of affectedChains) {
+ const key = modelChainKey(request.backend, request.modelId);
+ const missing = readyRegion({
+ ...Object.fromEntries(affectedChains.map(({ backend, modelId }) => [
+ modelChainKey(backend, modelId),
+ readyRegion({} as AgentChain),
+ ])),
+ [key]: unreadRegion(),
+ });
+ expect(sourceMutationLanding({ ...reads, chains: missing }, affectedChains, true).verdict, key)
+ .toBe('degraded');
+ }
+ });
+
+ it('routes every management settlement through one post-await announcement', () => {
const here = dirname(fileURLToPath(import.meta.url));
const page = readFileSync(resolve(here, 'SettingsModelsPage.tsx'), 'utf8');
+ const detail = readFileSync(resolve(here, 'SourceDetailPanel.tsx'), 'utf8');
const refresh = page.slice(page.indexOf('const refresh = React.useCallback'), page.indexOf('\n\n const trackSourceMutation'));
const settlement = page.slice(page.indexOf('const trackSourceMutation'), page.indexOf('\n\n React.useEffect', page.indexOf('const trackSourceMutation')));
+ const committed = detail.slice(
+ detail.indexOf('const commitManagementMutation'),
+ detail.indexOf('\n const reconcileEditWrite'),
+ );
expect(refresh).toMatch(/Promise<SourceMutationLanding>/);
- expect(refresh).toMatch(/\? 'landed'\s*:\s*'degraded'/);
+ expect(refresh).toContain('sourceMutationLanding(');
expect(settlement).toMatch(/Promise<SourceMutationLanding>/);
- expect(settlement).toMatch(/return reconcile \? refresh\(\) : 'landed'/);
+ expect(settlement).toContain('return refresh(affectedChains)');
+ expect((detail.match(/dispatchManageStage\(\{ type: 'settled' \}\)/g) ?? []).length).toBe(1);
+ expect(committed).toMatch(/await onMutationCommitted[\s\S]*dispatchManageStage\(\{ type: 'settled' \}\)/);
});
});
diff --git a/ui/src/components/settings/models/mutationSettlement.ts b/ui/src/components/settings/models/mutationSettlement.ts
index 8e270d1cf..9a5312976 100644
--- a/ui/src/components/settings/models/mutationSettlement.ts
+++ b/ui/src/components/settings/models/mutationSettlement.ts
@@ -1,5 +1,14 @@
import type { SourceCreated } from './modelsApi';
-import type { Source } from './types';
+import { readFirstPaintRegions } from './firstPaintRegions';
+import { modelChainKey, type ModelChainIndex, type ModelChainRequest } from './modelRows';
+import { foldRegionRead, readRegion, regionFailed, type RegionRead } from './regionRead';
+import type {
+ AgentSupply,
+ RouteHopRef,
+ RuntimeDependency,
+ Source,
+ SupplyGap,
+} from './types';
export type ContinuationTicket = number & { readonly __continuationTicket: unique symbol };
@@ -42,12 +51,130 @@ export const createSourceCreatedDelivery = () => {
export type SourceInventorySnapshot = { snapshot: number; sources: Source[] };
-export type SourceMutationLanding = 'landed' | 'degraded';
+type SourceMutationProjectionValues = {
+ sources: Source[];
+ supply: AgentSupply[];
+ runtime: RuntimeDependency;
+ chains: ModelChainIndex;
+};
+
+/** Every projection named by the committed Source report must be read before it lands. */
+export const SOURCE_MUTATION_REPORT_PROJECTIONS = {
+ sources: 'the Source inventory after the mutation',
+ supply: 'the backend supply projection after the mutation',
+ runtime: 'the runtime projection that qualifies live chain claims',
+ chains: 'every route chain named by the impact evidence',
+} as const satisfies Record<keyof SourceMutationProjectionValues, string>;
+
+export type SourceMutationLandingReads = {
+ [K in keyof SourceMutationProjectionValues]: RegionRead<SourceMutationProjectionValues[K]>;
+};
+
+export type SourceMutationProjectionReaders = {
+ sources: () => Promise<Source[]>;
+ supply: () => Promise<AgentSupply[]>;
+ runtime: () => Promise<RuntimeDependency>;
+ chains: (requests: readonly ModelChainRequest[]) => Promise<ModelChainIndex>;
+};
+
+export const readSurfaceLanding = async (
+ readers: SourceMutationProjectionReaders,
+ affectedChains: readonly ModelChainRequest[],
+): Promise<SourceMutationLandingReads> => {
+ const [surface, chains] = await Promise.all([
+ readFirstPaintRegions({
+ sources: readers.sources,
+ supply: readers.supply,
+ runtime: readers.runtime,
+ }),
+ readRegion(() => readers.chains(affectedChains)),
+ ]);
+ return { ...surface, chains };
+};
+
+export type SourceMutationLanding =
+ | {
+ verdict: 'landed';
+ reads: SourceMutationLandingReads;
+ affectedChains: ModelChainRequest[];
+ }
+ | {
+ verdict: 'degraded';
+ reads: SourceMutationLandingReads | null;
+ affectedChains: ModelChainRequest[];
+ };
+
+export type SourceMutationImpact = { hops: RouteHopRef[]; gaps: SupplyGap[] };
+
+export type SourceMutationReadScope = { affectedChains: ModelChainRequest[] };
+
+export const SOURCE_MUTATION_ACTIONS = ['edit', 'delete'] as const;
+export type SourceMutationAction = (typeof SOURCE_MUTATION_ACTIONS)[number];
+
+export type SourceMutationCommit = {
+ action: SourceMutationAction;
+ impact: SourceMutationImpact | null;
+ settle: () => Promise<SourceMutationLanding>;
+};
+
+export type PresentSourceMutationCommit = (commit: SourceMutationCommit) => Promise<void>;
+
+/** A landed verdict is proof that every report projection was current and readable. */
+export const sourceMutationLanding = (
+ reads: SourceMutationLandingReads | null,
+ affectedChains: ModelChainRequest[],
+ applied: boolean,
+): SourceMutationLanding => {
+ const reportProjectionFailed = reads
+ ? (
+ Object.keys(
+ SOURCE_MUTATION_REPORT_PROJECTIONS,
+ ) as (keyof SourceMutationLandingReads)[]
+ ).some((projection) => regionFailed(reads[projection]))
+ : true;
+
+ if (!reads || !applied || reportProjectionFailed) {
+ return { verdict: 'degraded', reads, affectedChains };
+ }
+ const chains = foldRegionRead<ModelChainIndex, ModelChainIndex | null>(reads.chains, {
+ loading: () => null,
+ ready: (data) => data,
+ unread: () => null,
+ degraded: () => null,
+ });
+ const chainReadsLanded = chains !== null && affectedChains.every(({ backend, modelId }) => {
+ const read = chains[modelChainKey(backend, modelId)];
+ return Boolean(read && !regionFailed(read));
+ });
+ return chainReadsLanded
+ ? { verdict: 'landed', reads, affectedChains }
+ : { verdict: 'degraded', reads, affectedChains };
+};
+
+/** The report evidence is the authority for which exact route projections must land. */
+export const sourceMutationReadScope = (
+ impact: SourceMutationImpact | null,
+): SourceMutationReadScope => {
+ const requests = new Map<string, ModelChainRequest>();
+ for (const hop of impact?.hops ?? []) {
+ const request = { backend: hop.backend, modelId: hop.menu_model };
+ requests.set(modelChainKey(request.backend, request.modelId), request);
+ }
+ for (const gap of impact?.gaps ?? []) {
+ const request = { backend: gap.backend, modelId: gap.model_id };
+ requests.set(modelChainKey(request.backend, request.modelId), request);
+ }
+ return { affectedChains: [...requests.values()] };
+};
export type SourceMutationSettlement = {
- source: (source: Source) => Promise<SourceMutationLanding>;
- gone: (sourceId: string, inventory?: SourceInventorySnapshot) => Promise<SourceMutationLanding>;
- unread: () => Promise<SourceMutationLanding>;
+ source: (source: Source, scope?: SourceMutationReadScope) => Promise<SourceMutationLanding>;
+ gone: (
+ sourceId: string,
+ inventory?: SourceInventorySnapshot,
+ scope?: SourceMutationReadScope,
+ ) => Promise<SourceMutationLanding>;
+ unread: (scope?: SourceMutationReadScope) => Promise<SourceMutationLanding>;
release: () => void;
readInventory: () => Promise<SourceInventorySnapshot>;
};
diff --git a/ui/src/components/settings/models/regionRead.test.ts b/ui/src/components/settings/models/regionRead.test.ts
index 8782b784c..46d20bafe 100644
--- a/ui/src/components/settings/models/regionRead.test.ts
+++ b/ui/src/components/settings/models/regionRead.test.ts
@@ -77,8 +77,11 @@ describe('RegionRead', () => {
expect(called).toEqual(keys);
expect(Object.keys(landing)).toEqual(keys);
- const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');
- const barrier = page.slice(page.indexOf('const readSurfaceLanding'), page.indexOf('\n\nconst surfaceLandingFailed'));
+ const settlement = readFileSync(join(__dirname, 'mutationSettlement.ts'), 'utf8');
+ const barrier = settlement.slice(
+ settlement.indexOf('export const readSurfaceLanding'),
+ settlement.indexOf('\n\nexport type SourceMutationLanding ='),
+ );
expect(barrier).not.toMatch(/listEvents|events/);
});
@@ -104,20 +107,25 @@ describe('RegionRead', () => {
it('routes every per-model chain read through the per-backend latest authority', () => {
const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');
- const definitionStart = page.indexOf('const readAgentChains');
+ const definitionStart = page.indexOf('const readChainRequests');
const definitionEnd = page.indexOf('\n\nconst settleAgentChainIndex');
const withoutDefinition = `${page.slice(0, definitionStart)}${page.slice(definitionEnd)}`;
- const unownedCalls = [...withoutDefinition.matchAll(/\breadAgentChains\(/g)].flatMap((match) => {
- const before = withoutDefinition.slice(Math.max(0, (match.index ?? 0) - 240), match.index);
- return before.includes('chainReadAuthority.run') ? [] : [match.index];
- });
- const landing = page.slice(page.indexOf('const readSurfaceLanding'), page.indexOf('\n\nconst surfaceLandingFailed'));
+ const affectedRefresh = page.slice(
+ page.indexOf('const refreshAffectedChains'),
+ page.indexOf('\n\n const refreshAllAgentChains'),
+ );
+ const settlement = readFileSync(join(__dirname, 'mutationSettlement.ts'), 'utf8');
+ const landing = settlement.slice(
+ settlement.indexOf('export const readSurfaceLanding'),
+ settlement.indexOf('\n\nexport type SourceMutationLanding ='),
+ );
expect(definitionStart).toBeGreaterThanOrEqual(0);
expect(definitionEnd).toBeGreaterThan(definitionStart);
expect(withoutDefinition).not.toMatch(/modelsApi\.getAgentChain/);
- expect(unownedCalls).toEqual([]);
- expect(landing).not.toMatch(/readAgentChains|getAgentChain/);
+ expect(affectedRefresh).toMatch(/chainReadAuthority\.run[\s\S]*readChainRequests/);
+ expect(landing).toMatch(/readers\.chains\(affectedChains\)/);
+ expect(landing).not.toMatch(/getAgentChain/);
expect(page).not.toMatch(/\breadChains\b/);
expect(page).toMatch(/chainReadAuthority\.invalidateExcept\(activeBackends\)/);
});
diff --git a/ui/src/components/settings/models/useSourceMutationReport.test.tsx b/ui/src/components/settings/models/useSourceMutationReport.test.tsx
new file mode 100644
index 000000000..242015fcb
--- /dev/null
+++ b/ui/src/components/settings/models/useSourceMutationReport.test.tsx
@@ -0,0 +1,88 @@
+// @vitest-environment jsdom
+import * as React from 'react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { I18nextProvider } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import i18n from '@/i18n';
+import { SourceMutationReport } from './SourceMutationReport';
+import type { SourceMutationCommit, SourceMutationLanding } from './mutationSettlement';
+import { useSourceMutationReport } from './useSourceMutationReport';
+
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => { resolve = done; });
+ return { promise, resolve };
+};
+
+const degradedLanding = (): SourceMutationLanding => ({
+ verdict: 'degraded',
+ reads: null,
+ affectedChains: [],
+});
+
+afterEach(cleanup);
+
+describe('page-owned Source mutation reports', () => {
+ it('queues overlapping reports without destroying either mutation holder', async () => {
+ const editLanding = deferred<SourceMutationLanding>();
+ const deleteLanding = deferred<SourceMutationLanding>();
+ const commits: SourceMutationCommit[] = [
+ { action: 'edit', impact: null, settle: () => editLanding.promise },
+ { action: 'delete', impact: null, settle: () => deleteLanding.promise },
+ ];
+ const editReleased = vi.fn();
+ const deleteReleased = vi.fn();
+ const Owner = () => {
+ const owner = useSourceMutationReport();
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => { void owner.present(commits[0]).then(editReleased); }}
+ >
+ Present edit report
+ </button>
+ <button
+ type="button"
+ onClick={() => { void owner.present(commits[1]).then(deleteReleased); }}
+ >
+ Present delete report
+ </button>
+ <SourceMutationReport
+ report={owner.report}
+ onComplete={() => { void owner.complete(); }}
+ onDismiss={owner.dismiss}
+ />
+ </>
+ );
+ };
+ render(<I18nextProvider i18n={i18n}><Owner /></I18nextProvider>);
+ fireEvent.click(screen.getByRole('button', { name: 'Present edit report' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Present delete report' }));
+
+ await act(async () => {
+ editLanding.resolve(degradedLanding());
+ await editLanding.promise;
+ });
+ expect(screen.getByRole('dialog', { name: /^The source was updated$/i })).toBeTruthy();
+
+ await act(async () => {
+ deleteLanding.resolve(degradedLanding());
+ await deleteLanding.promise;
+ });
+ expect(screen.getByRole('dialog', { name: /^The source was updated$/i })).toBeTruthy();
+ expect(screen.queryByRole('dialog', { name: /^The source was removed$/i })).toBeNull();
+ expect(editReleased).not.toHaveBeenCalled();
+ expect(deleteReleased).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getAllByRole('button', { name: 'Dismiss unverified result' })[0]);
+ await waitFor(() => expect(editReleased).toHaveBeenCalledOnce());
+ expect(deleteReleased).not.toHaveBeenCalled();
+ expect(screen.getByRole('dialog', { name: /^The source was removed$/i })).toBeTruthy();
+
+ fireEvent.click(screen.getAllByRole('button', { name: 'Dismiss unverified result' })[0]);
+ await waitFor(() => expect(deleteReleased).toHaveBeenCalledOnce());
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+});
diff --git a/ui/src/components/settings/models/useSourceMutationReport.ts b/ui/src/components/settings/models/useSourceMutationReport.ts
new file mode 100644
index 000000000..cde4277fc
--- /dev/null
+++ b/ui/src/components/settings/models/useSourceMutationReport.ts
@@ -0,0 +1,96 @@
+import * as React from 'react';
+
+import type {
+ PresentSourceMutationCommit,
+ SourceMutationCommit,
+ SourceMutationLanding,
+} from './mutationSettlement';
+
+export type SourceMutationReportState = {
+ commit: SourceMutationCommit;
+ landingFailed: boolean;
+ busy: boolean;
+};
+
+type HeldSourceMutationReport = {
+ state: SourceMutationReportState;
+ resolve: () => void;
+};
+
+const settleCommit = async (
+ commit: SourceMutationCommit,
+): Promise<SourceMutationLanding | null> => {
+ try {
+ return await commit.settle();
+ } catch {
+ return null;
+ }
+};
+
+/** Page-owned post-commit evidence; a Source panel may disappear without releasing it. */
+export const useSourceMutationReport = () => {
+ const [report, setReport] = React.useState<SourceMutationReportState | null>(null);
+ const queueRef = React.useRef<HeldSourceMutationReport[]>([]);
+ const mountedRef = React.useRef(true);
+
+ const resolveHeldReports = React.useCallback(() => {
+ const held = queueRef.current;
+ queueRef.current = [];
+ for (const entry of held) entry.resolve();
+ }, []);
+
+ const releaseCurrent = React.useCallback(() => {
+ const [current, ...remaining] = queueRef.current;
+ if (!current) return;
+ queueRef.current = remaining;
+ current.resolve();
+ setReport(remaining[0]?.state ?? null);
+ }, []);
+
+ const hold = React.useCallback((
+ commit: SourceMutationCommit,
+ landingFailed: boolean,
+ ): Promise<void> => {
+ if (!mountedRef.current) return Promise.resolve();
+ return new Promise((resolve) => {
+ const held = { state: { commit, landingFailed, busy: false }, resolve };
+ queueRef.current.push(held);
+ if (queueRef.current.length === 1) setReport(held.state);
+ });
+ }, []);
+
+ const present = React.useCallback<PresentSourceMutationCommit>(async (commit) => {
+ if (commit.impact) {
+ await hold(commit, false);
+ return;
+ }
+ const landing = await settleCommit(commit);
+ if (landing?.verdict === 'landed') return;
+ await hold(commit, true);
+ }, [hold]);
+
+ const complete = React.useCallback(async () => {
+ const current = queueRef.current[0];
+ if (!current || current.state.busy) return;
+ current.state = { ...current.state, busy: true };
+ setReport(current.state);
+ const landing = await settleCommit(current.state.commit);
+ if (!mountedRef.current || queueRef.current[0] !== current) return;
+ if (landing?.verdict === 'landed') {
+ releaseCurrent();
+ return;
+ }
+ current.state = { ...current.state, landingFailed: true, busy: false };
+ setReport(current.state);
+ }, [releaseCurrent]);
+
+ React.useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ resolveHeldReports();
+ };
+ }, [resolveHeldReports]);
+
+ return { report, present, complete, dismiss: releaseCurrent };
+};
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 6cff12b0f..eef658b5c 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1308,6 +1308,9 @@
"title": "The source was updated, and some supply was affected",
"detail": "These routes or models were removed or interrupted.",
"done": "Done"
+ },
+ "settlement": {
+ "title": "The source was updated"
}
},
"remove": {
@@ -1315,6 +1318,9 @@
"title": "The source was removed, and some supply was affected",
"detail": "These are the routes and models actually affected by this removal.",
"done": "Done"
+ },
+ "settlement": {
+ "title": "The source was removed"
}
},
"impact": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index dc3a75eeb..2755ce53e 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1308,6 +1308,9 @@
"title": "来源已更新,部分供给受到影响",
"detail": "以下路由或型号已被移除或中断。",
"done": "完成"
+ },
+ "settlement": {
+ "title": "来源已更新"
}
},
"remove": {
@@ -1315,6 +1318,9 @@
"title": "来源已移除,部分供给受到影响",
"detail": "以下是这次移除实际影响的路由和型号。",
"done": "完成"
+ },
+ "settlement": {
+ "title": "来源已移除"
}
},
"impact": {