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.

feat(model-hub): wire the annotated tail onto the shipped contracts (L5) (#1115)

Call White1d75cd034575
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsx
index 3fc6b602c..832ec6952 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx
@@ -17,12 +17,17 @@ import {
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Select } from '@/components/ui/select';
-import { modelsApi } from './modelsApi';
+import { modelsApi, type Adoption } from './modelsApi';
import { AdoptionNote } from './AdoptionNote';
import { Field } from './dialogFields';
import { adoptionVerdict } from './sufficiency';
import { DEFAULT_VENDOR, VENDOR_OPTIONS } from './vendorMeta';
-import type { AdoptedBy, Source } from './types';
+import type { Source } from './types';
+
+/** Nothing created yet. `skipped_by: null` rather than `[]` for the reason the
+ * reader defaults it that way: 「nobody was left out」 is a claim, and no
+ * creation has made it. */
+const NO_ADOPTION: Adoption = { adopted_by: [], skipped_by: null };
type Phase = 'edit' | 'submitting' | 'done' | 'error';
@@ -37,7 +42,9 @@ export const AddApiKeyDialog: React.FC<{
const [baseUrl, setBaseUrl] = React.useState('');
const [phase, setPhase] = React.useState<Phase>('edit');
const [discovered, setDiscovered] = React.useState(0);
- const [adoptedBy, setAdoptedBy] = React.useState<AdoptedBy[]>([]);
+ // One state for both halves of the tail: the note and the auto-close timer each
+ // read both, and two states could hold one half of an older response.
+ const [adoption, setAdoption] = React.useState<Adoption>(NO_ADOPTION);
const [error, setError] = React.useState<string | null>(null);
const closeTimer = React.useRef<number | null>(null);
// Bumped on every open/close so a test-and-add resolving after the dialog was
@@ -53,7 +60,7 @@ export const AddApiKeyDialog: React.FC<{
setBaseUrl(DEFAULT_VENDOR.base_url ?? '');
setPhase('edit');
setDiscovered(0);
- setAdoptedBy([]);
+ setAdoption(NO_ADOPTION);
setError(null);
}
return () => {
@@ -74,7 +81,7 @@ export const AddApiKeyDialog: React.FC<{
setPhase('submitting');
setError(null);
try {
- const { source, adopted_by } = await modelsApi.createApiKeySource({
+ const { source, adopted_by, skipped_by } = await modelsApi.createApiKeySource({
kind: 'api_key',
vendor,
base_url: baseUrl.trim() || null,
@@ -82,7 +89,7 @@ export const AddApiKeyDialog: React.FC<{
});
if (submitSeq.current !== seq) return; // dialog closed/reopened mid-request
setDiscovered(source.models.length);
- setAdoptedBy(adopted_by);
+ setAdoption({ adopted_by, skipped_by });
setPhase('done');
onAdded(source);
// Auto-dismiss only when the note is pure confirmation. 「还没有 Agent
@@ -92,10 +99,11 @@ export const AddApiKeyDialog: React.FC<{
//
// `covered` and nothing weaker: a non-empty adopter list does not rule out a
// `custom` backend that skipped the key, and that sentence is an instruction
- // too. Today's payload cannot prove `covered`, so this nicety is dormant until
- // the server sends `skipped_by` — a confirmation that can lie under a mixed
- // outcome is worth less than the second the user spends closing the dialog.
- if (adoptionVerdict(adopted_by).kind === 'covered') closeTimer.current = window.setTimeout(onClose, 1500);
+ // too. `skipped_by` is what makes `covered` reachable at all — a server that
+ // omits it leaves the verdict `indeterminate`, and the dialog waits, which is
+ // the same answer this site gave before the field existed.
+ if (adoptionVerdict(adopted_by, skipped_by).kind === 'covered')
+ closeTimer.current = window.setTimeout(onClose, 1500);
} catch (e: any) {
if (submitSeq.current !== seq) return;
const code = e?.code || e?.message || 'discovery_failed';
@@ -175,7 +183,7 @@ export const AddApiKeyDialog: React.FC<{
<CheckCircle2 className="size-4 shrink-0" />
<span>{t('settings.models.addKey.discovered', { count: discovered })}</span>
</div>
- <AdoptionNote adoptedBy={adoptedBy} />
+ <AdoptionNote adoptedBy={adoption.adopted_by} skippedBy={adoption.skipped_by} />
</div>
)}
{phase === 'error' && (
diff --git a/ui/src/components/settings/models/AdoptionNote.test.tsx b/ui/src/components/settings/models/AdoptionNote.test.tsx
index 4c51d6c67..04b2b1336 100644
--- a/ui/src/components/settings/models/AdoptionNote.test.tsx
+++ b/ui/src/components/settings/models/AdoptionNote.test.tsx
@@ -10,8 +10,7 @@ import { describe, expect, it } from 'vitest';
import en from '../../../i18n/en.json';
import zh from '../../../i18n/zh.json';
import { AdoptionNote } from './AdoptionNote';
-import type { SkippedBy } from './sufficiency';
-import type { AdoptedBy } from './types';
+import type { AdoptedBy, SkippedBy } from './types';
const instance = (lng: 'en' | 'zh') => {
const i18n = createInstance();
@@ -64,11 +63,11 @@ describe('AdoptionNote', () => {
expect(render([entry('futurecli', 2)])).toContain('futurecli');
});
- // 「谁没有」 is the answer this note exists for, and it is the one today's payload
- // cannot give: `_adopted_by` filters `policy == "follow"`, so a `custom` backend
- // that skipped the source is absent for the same reason an ineligible one is. The
- // note therefore says only what it can prove — and names the omission the moment
- // the server sends it.
+ // 「谁没有」 is the answer this note exists for, and `adopted_by` alone cannot give
+ // it: `_adopted_by` filters `policy == "follow"`, so a `custom` backend that
+ // skipped the source is absent for the same reason an ineligible one is. That is
+ // what `skipped_by` is for — and a response that omits it is still a response that
+ // did not answer, so the note keeps saying only what it can prove.
it('claims nothing about who skipped it while the server does not say', () => {
const html = render([entry('claude', 1)]);
expect(text(html)).toContain('Claude Code');
@@ -77,13 +76,24 @@ describe('AdoptionNote', () => {
});
it('names the skipped backends once the server sends them', () => {
- const html = render([entry('claude', 1)], [{ backend: 'codex', reason: 'custom-order-omission' }]);
+ const html = render([entry('claude', 1)], [{ backend: 'codex', reason: 'custom_order' }]);
const body = text(html);
expect(body).toContain('Claude Code');
expect(body).toContain('Codex');
expect(body).toContain('自定义顺序');
});
+ it('names them even when nobody adopted it at all', () => {
+ // `adopted_by: []` with a non-empty complement — every eligible backend keeps a
+ // hand-picked order. The generic 「还没有 Agent 启用它」 is true here but throws
+ // away the one thing the payload knows: which orders to go edit. And the adopted
+ // half must NOT appear: there is no list to name.
+ const body = text(render([], [{ backend: 'codex', reason: 'custom_order' }]));
+ expect(body).toContain('Codex');
+ expect(body).toContain('自定义顺序');
+ expect(body).not.toContain('已自动加入');
+ });
+
it('says nothing at all when the creation reported no adoption result', () => {
// OAuthConnectDialog's unreported-creation path. An absent result is not an empty
// one: 「没有 Agent 启用它」 would be a claim, and this is ignorance. The component
diff --git a/ui/src/components/settings/models/AdoptionNote.tsx b/ui/src/components/settings/models/AdoptionNote.tsx
index e454cf2e2..db105058c 100644
--- a/ui/src/components/settings/models/AdoptionNote.tsx
+++ b/ui/src/components/settings/models/AdoptionNote.tsx
@@ -12,13 +12,14 @@
// copy is exactly where the two drifted into saying different things.
//
// Which of those two answers can be given is `adoptionVerdict`'s call, not this
-// component's: 「who did not」 is only answerable once the server sends the
-// eligible-but-skipped complement, and until then the note says what it can prove.
+// component's: 「who did not」 is only answerable from the server's own
+// eligible-but-skipped complement, and a response that omits it still gets the
+// sentence the note can prove rather than a guess at the missing half.
import * as React from 'react';
import { useTranslation } from 'react-i18next';
-import { adoptionVerdict, type SkippedBy } from './sufficiency';
-import type { AdoptedBy } from './types';
+import { adoptionVerdict } from './sufficiency';
+import type { AdoptedBy, SkippedBy } from './types';
export const AdoptionNote: React.FC<{ adoptedBy: AdoptedBy[] | null; skippedBy?: SkippedBy[] | null }> = ({
adoptedBy,
@@ -32,10 +33,21 @@ export const AdoptionNote: React.FC<{ adoptedBy: AdoptedBy[] | null; skippedBy?:
const backendName = (backend: string) =>
t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string;
- if (verdict.kind === 'adopted_none') {
+ if (verdict.kind === 'adopted_none' || verdict.kind === 'skipped_all') {
// Not an error — the source exists and is healthy. It is a pointer to the one
- // action that makes it serve traffic, on the page the user is already on.
- return <p className="text-[12px] leading-relaxed text-muted">{t('settings.models.adoption.none')}</p>;
+ // action that makes it serve traffic, on the page the user is already on. And
+ // it points AT the orders whenever the server named them: 「nobody took it」 and
+ // 「these hand-picked orders left it out」 want the same edit in two very
+ // different amounts of hunting.
+ return (
+ <p className="text-[12px] leading-relaxed text-muted">
+ {verdict.kind === 'skipped_all'
+ ? t('settings.models.adoption.noneSkipped', {
+ skipped: verdict.backends.map(backendName).join(' · '),
+ })
+ : t('settings.models.adoption.none')}
+ </p>
+ );
}
// Position order, not response order: 「第 1 位」 before 「第 3 位」 reads as a
diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsx
index f36744c22..5ecf014ea 100644
--- a/ui/src/components/settings/models/AgentCard.tsx
+++ b/ui/src/components/settings/models/AgentCard.tsx
@@ -97,8 +97,22 @@ const Chip: React.FC<{ chip: ChainChip }> = ({ chip }) => (
</span>
{/* Gold dot = this source cannot serve right now. It rides the chip even when
the resolver has not reached it yet, which is the row's early warning: the
- next failover will skip this position too. */}
- {chip.unhealthy && <span className="size-1 shrink-0 rounded-full bg-gold sm:size-[5px]" aria-hidden />}
+ next failover will skip this position too.
+
+ Muted dot = the same skip for a reason nobody can act on from this page: the
+ source is healthy and on the route, this process just cannot sign the
+ backend's CLI in with it. A second HUE on the one dot, not a second dot — a
+ position is stepped over for one reason at a time, and 10px of chip has no
+ room to argue. Which is also why neither dot carries its own label: the gold
+ one is named by the source row's state chip and the muted one by
+ `order.nativeUnavailable` in the order drawer, the two places the user goes
+ to do something about it. */}
+ {(chip.unhealthy || chip.unavailable) && (
+ <span
+ className={cn('size-1 shrink-0 rounded-full sm:size-[5px]', chip.unhealthy ? 'bg-gold' : 'bg-muted')}
+ aria-hidden
+ />
+ )}
</span>
);
diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsx
index 5aa1c095d..c0b9a3ce9 100644
--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx
+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx
@@ -37,13 +37,13 @@ import {
} from './asyncLifetime';
import { ExperimentalConsentDialog } from './ExperimentalConsentDialog';
import { SUBSCRIPTION_HUB_EXPERIMENTAL } from './featureFlags';
-import { apiFailure, modelsApi, type OAuthResult } from './modelsApi';
+import { apiFailure, modelsApi, type Adoption, type OAuthResult } from './modelsApi';
import { REPAIR_LINE_KEY, REPAIR_TOAST, repairOutcome, repairSettles, type RepairOutcome } from './repair';
import { oauthFailureKey, serverText, type OAuthJourney } from './serverCopy';
import { adoptionVerdict } from './sufficiency';
import { SupplyGapNote } from './SupplyGapNote';
import { ACCENT_ICON, ACCENT_TILE } from './vendorMeta';
-import type { AdoptedBy, Source, SupplyChannel, SupplyGap } from './types';
+import type { Source, SupplyChannel, SupplyGap } from './types';
const POLL_MS = 2000;
const DEADLINE_MS = 16 * 60 * 1000;
@@ -86,8 +86,11 @@ export const OAuthConnectDialog: React.FC<{
//
// `null` means the terminal response did not report a creation — which is not
// 「没有 Agent 采用」 and must not be rendered as it.
- const [adoptedBy, setAdoptedBy] = React.useState<AdoptedBy[] | null>(null);
- // The reauth counterpart of `adoptedBy`, read through the same owner the key
+ //
+ // The whole tail rather than the adopter list alone, held as one value: the note
+ // reads both halves, and two states can hold one half of an older arrival.
+ const [adoption, setAdoption] = React.useState<Adoption | null>(null);
+ // The reauth counterpart of `adoption`, read through the same owner the key
// replacement uses so 「did that fix it?」 has one answer on the page.
const [repair, setRepair] = React.useState<RepairOutcome | null>(null);
// What a FAILED reauth stranded on its way down. Not the same thing as
@@ -264,10 +267,11 @@ export const OAuthConnectDialog: React.FC<{
t(toast?.key ?? 'settings.models.oauth.status.success') as string,
toast?.tone ?? 'success',
);
- // Unlike the adoption auto-close below this one is PROVABLE: 「nothing was
- // stranded」 is a field the server sends, so a clean repair may dismiss
- // itself while a gap report stays on screen to be read. An absent tail
- // says nothing to read either, so it closes too.
+ // Same shape as the adoption auto-close below, on the same footing now that
+ // both halves are server facts: 「nothing was stranded」 is a field the
+ // server sends, so a clean repair may dismiss itself while a gap report
+ // stays on screen to be read. An absent tail says nothing to read either,
+ // so it closes too.
if (!verdict || repairSettles(verdict))
successTimer.current = window.setTimeout(() => onCloseRef.current(), 1400);
} else if (step.action === 'succeed') {
@@ -275,14 +279,20 @@ export const OAuthConnectDialog: React.FC<{
// success materializes it server-side and consumes the flow binding doing
// it — there is nothing left to finalize, and a POST /sources afterwards
// is refused as `flow_not_found` on a connect that in fact succeeded.
- setAdoptedBy(created ? created.adopted_by : null);
+ setAdoption(created ? { adopted_by: created.adopted_by, skipped_by: created.skipped_by } : null);
showToast(t('settings.models.oauth.status.success') as string, 'success');
// Same rule as the API-key dialog, through the same owner: 1.4s auto-dismiss
// is for a pure 「连接成功」, and every other verdict leaves an instruction on
// screen that 1.4s is not long enough to read. The old `!== 0` also read an
// ABSENT creation as adopted, which auto-dismissed the one case that knows
// least — `adoptionVerdict(null)` is indeterminate, so it now waits.
- if (adoptionVerdict(created?.adopted_by ?? null).kind === 'covered')
+ //
+ // `covered` and nothing weaker, and `skipped_by` is what makes it reachable
+ // at all: a non-empty adopter list never ruled out a `custom` backend that
+ // was left out, and that sentence is an instruction too. A response that
+ // omits the field leaves the verdict `indeterminate` and the dialog open —
+ // the same answer this site gave before the field existed.
+ if (adoptionVerdict(created?.adopted_by ?? null, created?.skipped_by).kind === 'covered')
successTimer.current = window.setTimeout(() => onCloseRef.current(), 1400);
}
// Both branches above end with the same fact about the page behind them, and
@@ -359,7 +369,7 @@ export const OAuthConnectDialog: React.FC<{
transition({ kind: 'reset' });
setCode('');
setSubmitting(false);
- setAdoptedBy(null);
+ setAdoption(null);
setRepair(null);
setStranded([]);
void (async () => {
@@ -656,8 +666,10 @@ export const OAuthConnectDialog: React.FC<{
</div>
{/* Only when the response actually reported the creation: an absent
`adopted_by` is not an empty one, and 「没有 Agent 采用」 would be
- a claim this response never made. */}
- <AdoptionNote adoptedBy={adoptedBy} />
+ a claim this response never made. The two halves come off ONE
+ value, so the note can never read a skip list from one arrival
+ against an adopter list from another. */}
+ <AdoptionNote adoptedBy={adoption?.adopted_by ?? null} skippedBy={adoption?.skipped_by} />
</div>
) : (
active && (
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index 0ff43f85a..4ac4e8bf9 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -20,7 +20,7 @@ import { AdvancedRow } from './AdvancedRow';
import { AddApiKeyDialog } from './AddApiKeyDialog';
import { OAuthConnectDialog } from './OAuthConnectDialog';
import { RepairJourney, type RepairTarget } from './RepairJourney';
-import { createLatestAsyncAuthority } from './asyncLifetime';
+import { agentsWithEcho, createLatestAsyncAuthority, createPendingWrites } from './asyncLifetime';
import {
emptyFeed,
feedAfterHeadRead,
@@ -113,6 +113,15 @@ export const SettingsModelsPage: React.FC = () => {
const [menuBackend, setMenuBackend] = React.useState<AgentBackend | null>(null);
const [orderBackend, setOrderBackend] = React.useState<AgentBackend | null>(null);
+ // Which backends have a 来源顺序 write outstanding. Held HERE and not in the
+ // drawer that issues it, because the drawer does not outlive its own write:
+ // 完成, the close X, Escape and the overlay all stay live while the PUT and its
+ // read-back are in flight, and closing unmounts the drawer, so a flag inside it
+ // is re-created reading 「idle」 by the reopen — which is exactly when the
+ // hand-off below must still be shut. See `createPendingWrites`.
+ const [orderWrites, setOrderWrites] = React.useState<ReadonlySet<string>>(() => new Set());
+ const [orderWriteRegistry] = React.useState(() => createPendingWrites(setOrderWrites));
+
// Guards event-handler async writes (refresh / connect) from landing after
// the page unmounts — the whole class of stale-async writes the review flagged.
//
@@ -202,6 +211,26 @@ export const SettingsModelsPage: React.FC = () => {
}
}, [refreshAuthority, showToast, t]);
+ /**
+ * The one way an Agent write reports itself: hand back the row the server
+ * echoed, then re-read everything else the write moved.
+ *
+ * Taking the echo is not an optimization of the re-read, it is the part that
+ * cannot fail. `refreshSourcesAgents` swallows a failed read into a toast and
+ * `refreshAuthority` drops a superseded one, so `await`ing it proves an attempt
+ * finished and never that the page caught up — and the drawers seed, diff and
+ * gate off these rows. `agentsWithEcho` explains why the echo is allowed to
+ * speak for one; the re-read still runs because the echo is one Agent and the
+ * write moved source rows, the other Agents and the feed too.
+ */
+ const agentSaved = React.useCallback(
+ (echoed: AgentSupply) => {
+ setAgents((prev) => agentsWithEcho(prev, echoed));
+ return refreshSourcesAgents();
+ },
+ [refreshSourcesAgents],
+ );
+
const loadOlderEvents = React.useCallback(async () => {
const oldest = feedTailCursor(feed);
if (!oldest) return;
@@ -232,8 +261,9 @@ export const SettingsModelsPage: React.FC = () => {
// see connectOutcome, which exists because `current: null` conflates four
// unrelated states and the copy behind it promised a Direct fallback the
// resolver does not perform.
- const outcome = connectOutcome(await modelsApi.setAgentMode(agent.backend, 'hub'), sources);
- await refreshSourcesAgents();
+ const echoed = await modelsApi.setAgentMode(agent.backend, 'hub');
+ const outcome = connectOutcome(echoed, sources);
+ await agentSaved(echoed);
if (!aliveRef.current) return;
if (outcome === 'failed') {
showToast(t('settings.models.toast.connectFailed') as string, 'error');
@@ -321,7 +351,18 @@ export const SettingsModelsPage: React.FC = () => {
agents={agents}
sources={sources}
onClose={() => setOrderBackend(null)}
- onSaved={() => void refreshSourcesAgents()}
+ // Returned, not discarded: the write stays marked pending for the whole
+ // of this, so the hand-off to the menu drawer cannot open mid-write. What
+ // makes the baseline it hands over CORRECT is the echo `agentSaved` takes
+ // — the re-read is allowed to fail here without leaving one behind.
+ onSaved={agentSaved}
+ // 试跑's own re-read. It is not this drawer's write, so there is no echo
+ // to take — the probe moves source state and answers with a probe result.
+ onReread={() => void refreshSourcesAgents()}
+ orderWrite={{
+ pending: orderWrites.has(orderAgent.backend),
+ track: (work) => orderWriteRegistry.track(orderAgent.backend, work),
+ }}
// 模型菜单与映射 hands off to the menu drawer: the two answer adjacent
// questions (which sources, which models), and V6 02's footer is the only
// way into the menu now that the row's action is 来源顺序. Withheld while
@@ -343,7 +384,8 @@ export const SettingsModelsPage: React.FC = () => {
agent={menuAgent}
sources={sources}
onClose={() => setMenuBackend(null)}
- onSaved={() => void refreshSourcesAgents()}
+ onSaved={(echoed) => void agentSaved(echoed)}
+ // A custom model is a SOURCE write: it echoes the source, not the Agent.
onRefresh={() => void refreshSourcesAgents()}
/>
) : menuAgent && (menuAgent.backend === 'claude' || menuAgent.backend === 'codex') ? (
@@ -353,7 +395,7 @@ export const SettingsModelsPage: React.FC = () => {
agent={menuAgent}
sources={sources}
onClose={() => setMenuBackend(null)}
- onSaved={() => void refreshSourcesAgents()}
+ onSaved={(echoed) => void agentSaved(echoed)}
/>
) : null}
</SettingsPageShell>
diff --git a/ui/src/components/settings/models/SourceOrderDrawer.tsx b/ui/src/components/settings/models/SourceOrderDrawer.tsx
index 6a7669224..d7aef6a28 100644
--- a/ui/src/components/settings/models/SourceOrderDrawer.tsx
+++ b/ui/src/components/settings/models/SourceOrderDrawer.tsx
@@ -41,7 +41,7 @@ import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { useIsMobile } from '@/lib/useIsMobile';
import { useToast } from '@/context/ToastContext';
-import { initialSeedState, savedSourcesKey, seedStep } from './asyncLifetime';
+import { initialSeedState, savedSourcesKey, seedStep, type PendingWrite } from './asyncLifetime';
import { CurrentChip, StateChip } from './chips';
import { eligibilityOf } from './eligibility';
import { DRY_RUN_ENABLED } from './featureFlags';
@@ -59,7 +59,7 @@ import {
import { movedOrder, sameIds } from './reorder';
import { serverText } from './serverCopy';
import { orderSufficiency } from './sufficiency';
-import { isUnhealthy, needsAttention } from './supply';
+import { healthyButUnrunnable, isUnhealthy, needsAttention } from './supply';
import { ACCENT_ICON, ACCENT_TILE, backendVisual, sourceVisual } from './vendorMeta';
import type { AgentBackend, AgentSourcesPut, AgentSupply, Source, SourcePolicy } from './types';
@@ -123,12 +123,23 @@ export const SourceOrderDrawer: React.FC<{
agents: AgentSupply[];
sources: Source[];
onClose: () => void;
- /** Re-read sources + agents: an order change moves ● 当前 on the page too. */
- onSaved: () => void;
+ /** Hands the page the Agent row this write echoed, and re-reads what else the
+ * order moved (● 当前 elsewhere, the source rows, the feed). Returning that
+ * read's promise lets the pending mark span it — see `persist`. */
+ onSaved: (echoed: AgentSupply) => void | Promise<void>;
+ /** Re-reads the rows behind the drawer, claiming nothing about them. Separate
+ * from `onSaved` because only a write can hand over an echo: 试跑 is a probe
+ * that moves source state (a cooldown, a 需处理) and echoes no Agent, so a read
+ * is genuinely all there is to do about it. */
+ onReread: () => void;
+ /** This backend's slot in the page's pending-write registry. Held by the page
+ * because every close path stays live during a write and closing unmounts this
+ * drawer — see `createPendingWrites` in asyncLifetime.ts. */
+ orderWrite: PendingWrite;
/** Desktop footer 模型菜单与映射 — hand off to this backend's menu drawer.
* Omitted while the menus are flagged off. */
onOpenMenu?: () => void;
-}> = ({ open, agent, agents, sources, onClose, onSaved, onOpenMenu }) => {
+}> = ({ open, agent, agents, sources, onClose, onSaved, onReread, orderWrite, onOpenMenu }) => {
const { t } = useTranslation();
const { showToast } = useToast();
const { Icon, accent } = backendVisual(agent.backend);
@@ -144,7 +155,9 @@ export const SourceOrderDrawer: React.FC<{
const [policy, setPolicy] = React.useState<SourcePolicy>(agent.sources?.policy ?? 'follow');
const [order, setOrder] = React.useState<string[]>(agent.sources?.order ?? []);
- const [saving, setSaving] = React.useState(false);
+ // Deliberately not this component's state: the user can close this drawer —
+ // which unmounts it — and reopen it while the write is still outstanding.
+ const saving = orderWrite.pending;
/** Last state the server confirmed — the revert target and the no-op test.
* `order` alone can serve neither: a drag has already moved it by the time
* the commit fires. */
@@ -181,7 +194,7 @@ export const SourceOrderDrawer: React.FC<{
const enabledIds = enabledSources.map((s) => s.id);
// Asked about the order the user is CURRENTLY editing, not about the saved one —
// the warning is about what pressing 保存 would leave this backend with.
- const orderVerdict = orderSufficiency(order, sources);
+ const orderVerdict = orderSufficiency(order, sources, agent);
const rest = sources.filter((s) => !order.includes(s.id));
const disabledSources = rest.filter((s) => eligibilityOf(agent, s.id).eligible);
const ineligible = rest
@@ -195,6 +208,10 @@ export const SourceOrderDrawer: React.FC<{
* 未启用 `供 GLM 全系 · 经模型菜单改写后可供 Claude 使用`
* 不适用 the server's eligibility reason, alone
*
+ * 启用 and 未启用 share one retraction: a healthy source this machine cannot
+ * launch the Agent's process against says so instead of naming what it supplies
+ * — see `healthyButUnrunnable`.
+ *
* The 供 segment names a model FAMILY, which is a vendor label, so a source with
* no family (a relay / custom endpoint) omits it rather than inventing one. The
* mapping note is read off the payload — none of this backend's own built-in ids
@@ -211,6 +228,22 @@ export const SourceOrderDrawer: React.FC<{
const identity = (source: Source) => source.account_label ?? source.masked_credential ?? '';
const join = (parts: (string | false)[]) => parts.filter(Boolean).join(' · ');
+ /**
+ * The second segment answers 「why is this row not the one serving」, and there
+ * are two independent answers competing for it. Health first — a cooling or
+ * broken source is the one the user can act on, and its state chip has already
+ * raised the question this segment answers. A HEALTHY source that this machine
+ * cannot launch gets the segment instead, and it must not be spent on 供 … 全系
+ * there: a model count is a promise, and this is the row that cannot keep it.
+ *
+ * Only a per-Agent surface may say it at all (it is per (source, backend)), and
+ * only in muted grey: `needsAttention` is false for a healthy source, so the
+ * line stays the same colour as the chain strip's dim dot rather than borrowing
+ * the gold that means 「and it needs you」.
+ */
+ const nativeUnavailable = () =>
+ t('settings.models.order.nativeUnavailable', { backend: backendName }) as string;
+
const enabledSubline = (source: Source): string =>
join([
identity(source),
@@ -220,10 +253,26 @@ export const SourceOrderDrawer: React.FC<{
? (t('settings.models.source.retryIn', { minutes: cooldownEtaMinutes(source.state.retry_at) }) as string)
: isUnhealthy(source.state)
? ''
- : supplies(source),
+ : healthyButUnrunnable(agent, source)
+ ? nativeUnavailable()
+ : supplies(source),
]);
+ /**
+ * The 未启用 row says what turning this source on would get — so it owes the
+ * same retraction the 启用 row owes, and owes it EARLIER. Availability is per
+ * (source, backend) and has nothing to do with where the source sits in the
+ * order, so a row that only admits it once enabled has told the user one step
+ * after the step it was about; `chainChips` already promises that 「the
+ * all-sources drawer keeps the ungated fact」, and this is half of that drawer.
+ *
+ * It replaces the whole line rather than joining it, in both branches: 供 … 全系
+ * is the promise being retracted, and 经模型菜单改写后可供 X 使用 is the same
+ * promise routed through a rewrite — neither survives a process that cannot be
+ * launched, and the sub-line is two segments wide.
+ */
const disabledSubline = (source: Source): string => {
+ if (healthyButUnrunnable(agent, source)) return join([identity(source), nativeUnavailable()]);
// Only a fixed-menu backend rewrites ids through mappings; the open-menu
// backend picks a supplied id directly, so the note would be false there.
const viaMapping =
@@ -272,42 +321,59 @@ export const SourceOrderDrawer: React.FC<{
* `follow` the server owns the order outright, so 恢复推荐顺序 learns the
* recommended order from the response and nowhere else.
*
- * Two edits in flight resolve last-write-wins, which is correct here because
- * every PUT carries the whole list rather than a delta.
+ * Two edits made in quick succession resolve later-edit-wins, which every PUT
+ * carrying the whole list rather than a delta makes possible and `orderWrite`'s
+ * per-backend queue makes true: sent together they would settle in whichever
+ * order they reached the server's lock, and the discarded one is a whole list.
*
* Runs to completion even if the drawer closes mid-flight, and deliberately so.
- * Both of the things this does on the way out belong to components that stay
- * mounted — `onSaved()` re-reads the page whose ● 当前 the write just moved, and
- * the failure toast lives at the app root — so a mounted-ref guard here would
- * not be protecting anything, it would be dropping the only report that a
- * rejected reorder ever gets. (The setState calls need no guard either: since
- * React 18 they are a no-op on an unmounted component, not a warning.)
+ * Everything this does on the way out belongs to something that outlives the
+ * drawer — the pending mark to the page, `onSaved()` to the page whose ● 当前 the
+ * write just moved, the failure toast to the app root — so a mounted-ref guard
+ * here would not be protecting anything, it would be dropping the only report
+ * that a rejected reorder ever gets. (The setState calls need no guard either:
+ * since React 18 they are a no-op on an unmounted component, not a warning.)
+ *
+ * Which is also why `orderWrite.track` and not a local flag. The drawer is not
+ * alive for the whole of its own write: 完成, the X, Escape and the overlay all
+ * stay live while this runs, and closing UNMOUNTS this component. A flag in here
+ * would then be re-created reading 「idle」 by the reopen, over a write still
+ * outstanding, and the gate below would be off for exactly the user who closed
+ * and reopened. The page holds it instead — see `createPendingWrites`.
*/
- const persist = async (body: AgentSourcesPut, next: { policy: SourcePolicy; order: string[] }) => {
- const previous = saved.current;
- setPolicy(next.policy);
- setOrder(next.order);
- setSaving(true);
- try {
- // No `contract_version` in the body — the route rejects unknown keys.
- const echoed = await modelsApi.putAgentSources(agent.backend, body);
- const adopted = {
- policy: echoed.sources?.policy ?? next.policy,
- order: echoed.sources?.order ?? next.order,
- };
- saved.current = adopted;
- setPolicy(adopted.policy);
- setOrder(adopted.order);
- onSaved();
- } catch {
- saved.current = previous;
- setPolicy(previous.policy);
- setOrder([...previous.order]);
- showToast(t('settings.models.toast.reorderFailed') as string, 'error');
- } finally {
- setSaving(false);
- }
- };
+ const persist = (body: AgentSourcesPut, next: { policy: SourcePolicy; order: string[] }) =>
+ // Marked pending for the whole hand-back and not merely until the PUT returns,
+ // because the mark is what keeps 模型菜单与映射 shut while this runs, and the
+ // drawer it hands off to reads its enrollment baseline out of the page's Agent
+ // list. What the mark cannot do is make that baseline right: `onSaved` finishes
+ // whether the page's re-read landed, failed or was superseded. So the baseline
+ // travels with the hand-back — the echo below IS the server's post-write row —
+ // and the mark only has to cover the window in which the write is in flight.
+ orderWrite.track(async () => {
+ const previous = saved.current;
+ setPolicy(next.policy);
+ setOrder(next.order);
+ try {
+ // No `contract_version` in the body — the route rejects unknown keys.
+ const echoed = await modelsApi.putAgentSources(agent.backend, body);
+ const adopted = {
+ policy: echoed.sources?.policy ?? next.policy,
+ order: echoed.sources?.order ?? next.order,
+ };
+ saved.current = adopted;
+ setPolicy(adopted.policy);
+ setOrder(adopted.order);
+ // A failed re-read belongs to the page that made it and is not this write's
+ // to roll back: the server accepted the order either way. Which is why the
+ // echo goes over with it rather than being left for that read to rediscover.
+ await Promise.resolve(onSaved(echoed)).catch(() => {});
+ } catch {
+ saved.current = previous;
+ setPolicy(previous.policy);
+ setOrder([...previous.order]);
+ showToast(t('settings.models.toast.reorderFailed') as string, 'error');
+ }
+ });
// Any manual edit is a fork to `custom`: the user just said which sources, in
// which order — that is the definition of a user-owned subset.
@@ -359,9 +425,21 @@ export const SourceOrderDrawer: React.FC<{
)}
{/* Desktop home for 模型菜单与映射 (V6 02's footer). The phone's home is
the row at the end of the list — M02 gives this footer to 恢复推荐
- 顺序 + 完成, and there is no width where the flow may be missing. */}
+ 顺序 + 完成, and there is no width where the flow may be missing.
+
+ Disabled while an order write is unsettled, for the same reason as
+ the two 恢复推荐顺序 buttons and one more: the hand-off closes this
+ drawer and opens one whose enrollment notice is a diff against the
+ page's copy of this order. Leaving on the way out of an edit the page
+ has not read back is how that diff acquires someone else's append. */}
{onOpenMenu && (
- <Button variant="outline" size="sm" className="hidden sm:inline-flex" onClick={onOpenMenu}>
+ <Button
+ variant="outline"
+ size="sm"
+ className="hidden sm:inline-flex"
+ onClick={onOpenMenu}
+ disabled={saving}
+ >
<List className="size-3.5" />
{t('settings.models.order.openMenu')}
</Button>
@@ -476,7 +554,7 @@ export const SourceOrderDrawer: React.FC<{
sources={sources}
chainKey={dryRunChainKey(agent, policy, order, sources)}
saving={saving}
- reread={onSaved}
+ reread={onReread}
/>
)}
@@ -490,6 +568,7 @@ export const SourceOrderDrawer: React.FC<{
variant="outline"
className="mt-1 h-[46px] w-full justify-between rounded-xl px-4 text-[13px] font-semibold sm:hidden"
onClick={onOpenMenu}
+ disabled={saving}
>
<span className="flex items-center gap-2">
<List className="size-4" />
@@ -535,10 +614,11 @@ const DryRunRow: React.FC<{
* chain the server still holds, filed under the one the user already sees —
* `dryRunRowView` owns that rule. */
saving: boolean;
- /** Re-read sources + agents, the drawer's own `onSaved`: a failing 试跑 is a
+ /** Re-read sources + agents, the drawer's own `onReread`: a failing 试跑 is a
* write, so the page it sits on is stale until this runs — and `probeArrival`
* owns the part that is easy to get wrong, that this is owed even for an answer
- * the row will not draw. */
+ * the row will not draw. A read and not an echo: the probe writes SOURCE state
+ * and hands back no Agent row to take. */
reread: () => void;
}> = ({ agent, sources, chainKey, saving, reread }) => {
const { t } = useTranslation();
diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.ts
index d8b0615c5..436ecd3ee 100644
--- a/ui/src/components/settings/models/asyncLifetime.test.ts
+++ b/ui/src/components/settings/models/asyncLifetime.test.ts
@@ -41,14 +41,31 @@
// the rows, but it did so while that request was still in flight, so it can
// have read them before the write — and the rejection path returned without a
// second read, leaving healthy rows on a page whose source is 需处理.
+//
+// 7. reopen-clears-the-guard. Interleaving 1's other half. The order drawer marks
+// itself busy for the span of its write, which shuts the hand-off to 模型菜单与
+// 映射 — whose enrollment notice diffs against the page's copy of that order. But
+// every way out of the drawer stays live while the write runs, and closing
+// unmounts it, so the reopen re-creates the mark reading 「idle」 over a write
+// still outstanding. The user then walks into the menu on a stale baseline and
+// the menu's own save reports the ORDER write's append as its own.
+//
+// 8. write-lands-read-does-not. Interleaving 7 once more, and the last place it
+// can hide: the mark now spans the re-read, but a re-read is not an outcome.
+// `refreshSourcesAgents` swallows a failure into a toast and the authority
+// drops a superseded run, so the await finishes either way and clears the mark
+// over rows that never moved — the same stale baseline, reached by waiting for
+// exactly the right thing and being told nothing about how it went.
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import {
+ agentsWithEcho,
createFlowAuthority,
createLatestAsyncAuthority,
+ createPendingWrites,
failureLanded,
flowLetGo,
flowStateTerminal,
@@ -108,6 +125,266 @@ describe('latest async authority', () => {
expect(landed).toEqual(['server order: b,a']);
});
+
+ // Interleaving 8, at its source. These are the two ways a re-read finishes with
+ // the rows exactly where they were, and the mutation awaiting it cannot tell
+ // either one from success — which is what makes 「the re-read finished」 a
+ // different fact from 「the row is current」.
+ it('reports a superseded run rather than landing it, and hands a failed one back', async () => {
+ const landed: string[] = [];
+ const authority = createLatestAsyncAuthority<string>((value) => landed.push(value));
+ const older = deferred<string>();
+
+ const olderRun = authority.run(() => older.promise);
+ await authority.run(() => Promise.resolve('newest'));
+ older.resolve('older');
+
+ expect(await olderRun).toBe('stale');
+ await expect(authority.run(() => Promise.reject(new Error('read failed')))).rejects.toThrow('read failed');
+ expect(landed).toEqual(['newest']);
+ });
+});
+
+describe('agentsWithEcho — what speaks for a row when no read does', () => {
+ const claude = agent({ backend: 'claude', sources: { policy: 'custom', order: ['src_a'] } });
+ const codex = agent({ backend: 'codex', sources: { policy: 'follow', order: ['src_b'] } });
+
+ it('takes the write’s echo into the row it is about', () => {
+ const echoed = agent({ backend: 'claude', sources: { policy: 'custom', order: ['src_a', 'src_c'] } });
+
+ expect(agentsWithEcho([claude, codex], echoed)).toEqual([echoed, codex]);
+ });
+
+ it('leaves every other Agent to the read that owns it', () => {
+ // An order write is per backend; it says nothing about the others, so it may
+ // not answer for them either.
+ const echoed = agent({ backend: 'codex', sources: { policy: 'custom', order: ['src_b', 'src_c'] } });
+
+ expect(agentsWithEcho([claude, codex], echoed)[0]).toBe(claude);
+ });
+
+ it('does not invent a row the page has not read', () => {
+ // Which Agents exist is the list read's to say. A write echo is an update.
+ const echoed = agent({ backend: 'opencode' });
+
+ expect(agentsWithEcho([claude], echoed)).toEqual([claude]);
+ });
+
+ it('does not mutate the list it was handed', () => {
+ const before = [claude, codex];
+ agentsWithEcho(before, agent({ backend: 'claude', sources: { policy: 'follow', order: [] } }));
+
+ expect(before).toEqual([claude, codex]);
+ });
+
+ // Interleaving 8. TypeScript already forces every drawer to hand its echo over —
+ // `onSaved` takes one — so what is left to guard is the page: that it TAKES the
+ // echo rather than dropping it beside a re-read, and that no Agent write reports
+ // itself any other way.
+ it('is how every Agent write on the page reports itself', () => {
+ const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');
+
+ expect(page).toMatch(/setAgents\(\(prev\) => agentsWithEcho\(prev, echoed\)\)/);
+ // The mode PATCH echoes the same row the drawers' writes do.
+ expect(page).toMatch(/await agentSaved\(echoed\)/);
+
+ const handlers = [...page.matchAll(/onSaved=\{([^}]*)\}/g)].map((m) => m[1]);
+ expect(handlers.length).toBeGreaterThanOrEqual(3);
+ expect(handlers.filter((h) => !h.includes('agentSaved'))).toEqual([]);
+ });
+});
+
+describe('createPendingWrites — a write that outlives the drawer that issued it', () => {
+ /** The published set, as the page would hold it in state. */
+ const registry = () => {
+ let keys: ReadonlySet<string> = new Set();
+ const writes = createPendingWrites((next) => {
+ keys = next;
+ });
+ return { writes, pending: (key: string) => keys.has(key) };
+ };
+
+ /** Lets the queue's own chaining run, without settling any of the work. */
+ const flush = async () => {
+ for (let i = 0; i < 4; i += 1) await Promise.resolve();
+ };
+
+ it('holds the mark for the whole of the work, not just its request', async () => {
+ const put = deferred<void>();
+ const reread = deferred<void>();
+ const { writes, pending } = registry();
+
+ const run = writes.track('claude', async () => {
+ await put.promise;
+ await reread.promise;
+ });
+
+ expect(pending('claude')).toBe(true);
+ put.resolve();
+ await Promise.resolve();
+ // The PUT has returned and the page has NOT read it back yet — the gap the
+ // hand-off may not leave through.
+ expect(pending('claude')).toBe(true);
+ reread.resolve();
+ await run;
+ expect(pending('claude')).toBe(false);
+ });
+
+ it('survives the drawer that issued the write', async () => {
+ // Interleaving 7. Nothing here is the drawer: the write is issued, the drawer
+ // that issued it is gone (closed → unmounted), a fresh one opens and asks
+ // whether a write is outstanding. It gets the truth, because the fact was
+ // never the drawer's to hold.
+ const put = deferred<void>();
+ const { writes, pending } = registry();
+
+ const run = writes.track('claude', () => put.promise);
+ const reopened = pending('claude');
+
+ put.resolve();
+ await run;
+
+ expect(reopened).toBe(true);
+ expect(pending('claude')).toBe(false);
+ });
+
+ it('stays pending until the LAST of two overlapping writes finishes', async () => {
+ // Two drags in quick succession. 「Pending」 is a property of the SET of writes on
+ // the key, so the first to return must not report the second one finished.
+ const first = deferred<void>();
+ const second = deferred<void>();
+ const { writes, pending } = registry();
+
+ const runFirst = writes.track('claude', () => first.promise);
+ const runSecond = writes.track('claude', () => second.promise);
+
+ first.resolve();
+ await runFirst;
+ expect(pending('claude')).toBe(true);
+
+ second.resolve();
+ await runSecond;
+ expect(pending('claude')).toBe(false);
+ });
+
+ it('runs two edits on one key in the order the user made them', async () => {
+ // 「The later edit wins」 is a claim about COMMIT order. Sent together, two PUTs
+ // settle in whichever order they reach the server's mutation lock — and each
+ // carries the WHOLE list, so the loser is discarded rather than merged into the
+ // winner. The order left on disk could be the user's second-to-last edit while
+ // the drawer shows their last.
+ const first = deferred<void>();
+ const second = deferred<void>();
+ const started: string[] = [];
+ const { writes } = registry();
+
+ const runFirst = writes.track('claude', () => {
+ started.push('first');
+ return first.promise;
+ });
+ const runSecond = writes.track('claude', () => {
+ started.push('second');
+ return second.promise;
+ });
+
+ await flush();
+ expect(started).toEqual(['first']);
+
+ first.resolve();
+ await runFirst;
+ expect(started).toEqual(['first', 'second']);
+
+ second.resolve();
+ await runSecond;
+ });
+
+ it('does not strand the edit waiting behind a rejected write', async () => {
+ // The edit behind it is the user's newer intent and still has to reach the
+ // server — and the write that failed rolled its own optimistic display back, so
+ // there is nothing for its successor to inherit.
+ const second = deferred<void>();
+ let ran = false;
+ const { writes, pending } = registry();
+
+ const runFirst = writes.track('claude', () => Promise.reject(new Error('put rejected')));
+ const runSecond = writes.track('claude', () => {
+ ran = true;
+ return second.promise;
+ });
+
+ await expect(runFirst).rejects.toThrow('put rejected');
+ await flush();
+ expect(ran).toBe(true);
+ expect(pending('claude')).toBe(true);
+
+ second.resolve();
+ await runSecond;
+ expect(pending('claude')).toBe(false);
+ });
+
+ it('does not let one backend’s write gate another', async () => {
+ // `PUT /agents/<backend>/sources` moves one backend's order, so this is the
+ // write's own grain: a claude order edit says nothing about codex's menu — and
+ // so has no business making codex's own edit wait for it either.
+ const claude = deferred<void>();
+ const codex = deferred<void>();
+ const started: string[] = [];
+ const { writes, pending } = registry();
+
+ const runClaude = writes.track('claude', () => {
+ started.push('claude');
+ return claude.promise;
+ });
+ const runCodex = writes.track('codex', () => {
+ started.push('codex');
+ return codex.promise;
+ });
+
+ expect(pending('claude')).toBe(true);
+ expect(pending('opencode')).toBe(false);
+ await flush();
+ expect(started).toEqual(['claude', 'codex']);
+
+ claude.resolve();
+ codex.resolve();
+ await Promise.all([runClaude, runCodex]);
+ expect(pending('claude')).toBe(false);
+ expect(pending('codex')).toBe(false);
+ });
+
+ it('clears the mark when the work throws', async () => {
+ const { writes, pending } = registry();
+
+ await expect(
+ writes.track('claude', async () => {
+ throw new Error('put rejected');
+ }),
+ ).rejects.toThrow('put rejected');
+
+ // A rejected write is a finished one. Leaving it marked would disable the
+ // drawer's controls for the rest of the session.
+ expect(pending('claude')).toBe(false);
+ });
+
+ it('is where the order drawer’s busy flag actually lives', () => {
+ // The guard the round-1 fix put in the drawer was real and still incomplete:
+ // it was component state, and 完成 / the X / Escape / the overlay all stay live
+ // while the write runs. So the assertion is not 「the drawer disables things」
+ // but 「the drawer does not OWN the fact it disables them on」.
+ const drawer = readFileSync(join(__dirname, 'SourceOrderDrawer.tsx'), 'utf8');
+ const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');
+
+ expect(drawer).toMatch(/const saving = orderWrite\.pending;/);
+ expect(drawer).not.toMatch(/setSaving/);
+ // And the mark spans the whole of `persist`, read-back included, because
+ // `track` is what opens and closes it.
+ expect(drawer).toMatch(/orderWrite\.track\(async \(\) => \{/);
+ expect(drawer).toMatch(/await Promise\.resolve\(onSaved\(echoed\)\)\.catch\(\(\) => \{\}\);/);
+
+ expect(page).toMatch(/createPendingWrites\(setOrderWrites\)/);
+ expect(page).toMatch(/pending: orderWrites\.has\(orderAgent\.backend\)/);
+ expect(page).toMatch(/track: \(work\) => orderWriteRegistry\.track\(orderAgent\.backend, work\)/);
+ });
});
describe('savedSourcesKey / savedMappingsKey / savedMenuKey', () => {
diff --git a/ui/src/components/settings/models/asyncLifetime.ts b/ui/src/components/settings/models/asyncLifetime.ts
index 6000b413d..ca611ceef 100644
--- a/ui/src/components/settings/models/asyncLifetime.ts
+++ b/ui/src/components/settings/models/asyncLifetime.ts
@@ -1,5 +1,6 @@
// Async ownership rules extracted from the Models components so interleavings can
-// be exercised directly: which request may land, when a drawer re-seeds, and
+// be exercised directly: which request may land, what speaks for a row when no
+// read does, how long a write counts as outstanding, when a drawer re-seeds, and
// whether a connect-flow transition may change an already terminal view.
import type { AgentMenu, AgentSupply, OAuthFlow, OAuthFlowState } from './types';
@@ -27,6 +28,138 @@ export const createLatestAsyncAuthority = <T>(land: (value: T) => void) => {
};
};
+// ── What speaks for a row when no read does ────────────────────────────────
+/**
+ * Takes a write's echoed Agent row into the page's list.
+ *
+ * A mutation here is followed by a re-read, and for a while the re-read was the
+ * only thing that updated the row it moved. That is a read landing in the middle
+ * of the two things it must not be confused with: it can FAIL (the page toasts
+ * 「视图可能不是最新的」 and carries on), and it can be superseded — the authority
+ * above lands only the latest request and reports the rest `stale`. Either way the
+ * mutation returns normally over a row that still shows the pre-write state, which
+ * for 来源顺序 means the enrollment baseline 模型菜单与映射 diffs against is one
+ * write behind, and the menu's own save reports an append the ORDER write made.
+ *
+ * So the write's own answer is taken directly. Every one of these routes replies
+ * with the same `_agent_payload` projection the list read returns
+ * (`service.py:1972` returns it straight out of `set_agent_sources`), computed
+ * under the mutation lock after the commit — it is not a client-side prediction of
+ * what the write did, it is the server's own statement of what the row now is, and
+ * it cannot fail separately from the write that produced it.
+ *
+ * It does not make the re-read redundant: the echo is one Agent, and an order
+ * change also moves the source rows, the other Agents' ● 当前 and the event feed.
+ * It makes the re-read's LANDING stop being the only way the row can catch up.
+ *
+ * What it is not is a way to order two writes. An echo is the server's word about
+ * the row as of ONE commit, so it may speak for the row only while it is the
+ * newest word there is — and that is a fact about the writes, not something this
+ * function can check: two responses do not say which of them committed second.
+ * `createPendingWrites` below is where it is made true, by running the writes on
+ * a backend one at a time.
+ *
+ * A backend the page has no row for is left alone rather than appended. A write
+ * echo is an update to a row; which rows exist is the list read's to say.
+ */
+export const agentsWithEcho = (
+ agents: readonly AgentSupply[],
+ echoed: AgentSupply,
+): AgentSupply[] => agents.map((agent) => (agent.backend === echoed.backend ? echoed : agent));
+
+// ── A write that outlives the drawer that issued it ────────────────────────
+/**
+ * Which keys have a write outstanding, where 「outstanding」 spans the read-back
+ * and not merely the request.
+ *
+ * It lives above the drawers rather than inside one because a drawer is not
+ * alive for the whole of its own write. 完成, the close X, Escape and the overlay
+ * all stay live while a PUT is in flight, the page unmounts the drawer when it
+ * closes, and reopening mints a fresh component whose local flag reads 「idle」
+ * over a write that is still outstanding. A flag with that lifetime is not a
+ * guard — it can be false while the fact is true — so everything it gates is
+ * ungated for exactly the user who closed and reopened, which for the order
+ * drawer means a hand-off to 模型菜单与映射 leaving on a baseline the page has not
+ * read back. `seedStep` below is the same lifetime fact met from the other side:
+ * the drawer's seed has to survive that reopen too, and does it by re-deriving
+ * from props instead of by remembering.
+ *
+ * Writes on one key run ONE AT A TIME, in the order the user made them, and the
+ * key stays pending from the moment an edit joins the queue until the last one
+ * has read back.
+ *
+ * Queued rather than concurrent, because 「the later edit wins」 is a claim about
+ * COMMIT order, and two PUTs in flight together settle in whatever order they
+ * reach the server's mutation lock. Each carries the whole list, so the loser is
+ * not merged into the winner, it is discarded — and the order left on disk can
+ * be the user's second-to-last edit while the drawer shows their last. The same
+ * ambiguity decides which of the two echoed rows is the newest word about the
+ * Agent, and nothing in the two responses says which commit came first. A queue
+ * makes issue order and commit order the same order, which is what the drawer's
+ * optimistic list and `agentsWithEcho` above were both already assuming.
+ *
+ * Counted rather than a flag per key, because 「pending」 is a property of the SET
+ * of writes on the key — the one running plus any waiting behind it — and the
+ * first to finish must not clear the key while the next is still to go.
+ *
+ * Keyed by backend because that is the write's own grain: `PUT
+ * /agents/<backend>/sources` moves one backend's order, so a claude write says
+ * nothing about codex and has no business gating or delaying it.
+ */
+export const createPendingWrites = (land: (keys: ReadonlySet<string>) => void) => {
+ const outstanding = new Map<string, number>();
+ const tail = new Map<string, Promise<void>>();
+ const publish = () => land(new Set(outstanding.keys()));
+
+ return {
+ /**
+ * Runs `work` after every write already queued on `key`, and marks the key
+ * pending for the whole of it — including whatever `work` awaits after its
+ * own request returns. Pairing is not the caller's to get right: there is no
+ * way to begin one without ending it.
+ */
+ track: async (key: string, work: () => Promise<void>): Promise<void> => {
+ outstanding.set(key, (outstanding.get(key) ?? 0) + 1);
+ publish();
+ const mine = (tail.get(key) ?? Promise.resolve()).then(work);
+ // A rejected write must not break the queue behind it. The edit waiting is
+ // the user's newer intent and still has to reach the server — and the one
+ // that failed rolled its own optimistic display back, so there is nothing
+ // for its successor to inherit.
+ tail.set(
+ key,
+ mine.then(
+ () => {},
+ () => {},
+ ),
+ );
+ try {
+ await mine;
+ } finally {
+ const left = (outstanding.get(key) ?? 1) - 1;
+ if (left > 0) outstanding.set(key, left);
+ else {
+ outstanding.delete(key);
+ // Nothing is queued, so the next write starts a fresh chain rather than
+ // hanging off a promise whose only remaining job is to be already done.
+ tail.delete(key);
+ }
+ publish();
+ }
+ },
+ };
+};
+
+/** One key's slot in the registry above, as the component issuing writes sees it. */
+export type PendingWrite = {
+ /** Whether a write on this key is outstanding — possibly one this component
+ * never issued, because the component that did may already be gone. */
+ pending: boolean;
+ /** Queues `work` behind any write already outstanding on this key, and marks
+ * the key pending until it has read back. */
+ track: (work: () => Promise<void>) => Promise<void>;
+};
+
// ── The drawers' seed ──────────────────────────────────────────────────────
// A drawer seeds its editable state from the server's saved state, and needs to
// know when that saved state MOVED. Comparing the props object is useless (every
diff --git a/ui/src/components/settings/models/eligibility.test.ts b/ui/src/components/settings/models/eligibility.test.ts
index ba0f3c702..bfd5eb822 100644
--- a/ui/src/components/settings/models/eligibility.test.ts
+++ b/ui/src/components/settings/models/eligibility.test.ts
@@ -3,7 +3,7 @@
// `isSourceEligible` mirror rather than moving it.
import { describe, expect, it } from 'vitest';
-import { eligibilityOf, eligibleSources } from './eligibility';
+import { eligibilityOf, eligibleSources, offCurrentModelChain } from './eligibility';
import type { AgentSupply, Source } from './types';
const source = (id: string): Source => ({
@@ -60,6 +60,33 @@ describe('eligibilityOf', () => {
});
});
+describe('offCurrentModelChain', () => {
+ // A claim about the ROUTE, not about the source: the server builds it from the
+ // eligible sources carrying the selected model, before health or runnability
+ // narrows them. Only an explicit `false` is a claim; `null` (nothing selected) and
+ // an absent field are silence, and reading silence as exclusion would retract
+ // markers the chain strip has always been right to draw.
+ it('speaks only when the server says false', () => {
+ const a = agent({
+ policy: 'follow',
+ order: ['src_on', 'src_off', 'src_unknown'],
+ eligibility: [
+ { source_id: 'src_on', eligible: true, in_current_model_chain: true },
+ { source_id: 'src_off', eligible: true, in_current_model_chain: false },
+ { source_id: 'src_unknown', eligible: true, in_current_model_chain: null },
+ ],
+ });
+ expect(offCurrentModelChain(a, 'src_off')).toBe(true);
+ expect(offCurrentModelChain(a, 'src_on')).toBe(false);
+ expect(offCurrentModelChain(a, 'src_unknown')).toBe(false);
+ });
+
+ it('is silent for a row the payload never mentions, and in Direct mode', () => {
+ expect(offCurrentModelChain(agent({ policy: 'follow', order: ['src_a'] }), 'src_a')).toBe(false);
+ expect(offCurrentModelChain(agent(null), 'src_a')).toBe(false);
+ });
+});
+
describe('eligibleSources', () => {
it('keeps inventory order and drops what the server refused', () => {
const sources = [source('src_a'), source('src_b'), source('src_c')];
diff --git a/ui/src/components/settings/models/eligibility.ts b/ui/src/components/settings/models/eligibility.ts
index 75e239b2f..cac6909e1 100644
--- a/ui/src/components/settings/models/eligibility.ts
+++ b/ui/src/components/settings/models/eligibility.ts
@@ -8,7 +8,7 @@
// the UI can see, so it was guaranteed to drift and to offer rows the live API
// rejects. Contract v3 publishes `sources.eligibility` on
// `GET /api/models/agents`, and this file is the only place the UI reads it.
-import type { AgentSupply, EligibilityReasonKey, Source } from './types';
+import type { AgentSupply, EligibilityReasonKey, ProcessAvailabilityReason, Source } from './types';
export type Eligibility = { eligible: boolean; reasonKey: EligibilityReasonKey | null };
@@ -38,6 +38,61 @@ export function eligibilityOf(agent: Pick<AgentSupply, 'sources'>, sourceId: str
return sources.order.includes(sourceId) ? ELIGIBLE : INELIGIBLE;
}
+/** Whether this source can be LAUNCHED for this Agent right now, and why not. */
+export type ProcessAvailability = { runnable: boolean; reasonKey: ProcessAvailabilityReason | null };
+
+const RUNNABLE: ProcessAvailability = { runnable: true, reasonKey: null };
+
+/**
+ * The second half of 「can this source take the next turn」, and the half the source
+ * itself cannot answer: `native_cli` sources are launched by rewriting the CLI's own
+ * config, so one this process cannot sign that CLI in with is unrunnable while its
+ * credential, its models and its `state` all read perfectly healthy.
+ *
+ * 「Unrunnable」 is NOT 「the executable is missing」, and nothing here may say it is:
+ * `_default_native_cli_ready` also refuses when an `ANTHROPIC_*` / `OPENAI_*`
+ * override, a stored API key, a custom base URL or a foreign `model_provider` has
+ * claimed the CLI's sign-in — configurations where the CLI is installed and works
+ * fine. So this reader carries the server's reason key and no diagnosis of its own,
+ * and the copy it feeds names the sign-in rather than the binary.
+ *
+ * Per (source, BACKEND), like eligibility beside it — the server computes it from
+ * `_unavailable_native_sources(config, backend)`, so the same source is runnable for
+ * one Agent and not for another. That is why it is read here off the Agent's own
+ * inventory and can never live on the backend-agnostic source row.
+ *
+ * Total over every id, and the default is RUNNABLE rather than blocked: an absent
+ * row, a server that omits the optional field, and Direct mode all mean 「nothing is
+ * claimed」, and the surfaces this feeds (the chain's dim chip, the drawer's
+ * 「nothing runnable」 warning) would otherwise invent an outage out of silence.
+ */
+export function processAvailabilityOf(
+ agent: Pick<AgentSupply, 'sources'>,
+ sourceId: string,
+): ProcessAvailability {
+ const reasonKey = agent.sources?.eligibility?.find((e) => e.source_id === sourceId)?.process_availability_reason;
+ return reasonKey ? { runnable: false, reasonKey } : RUNNABLE;
+}
+
+/**
+ * Does the server positively say this source does NOT carry the selected model?
+ *
+ * `in_current_model_chain` is a claim about the ROUTE, not about the source: the
+ * server builds it from `resolution.matching_sources`, the eligible sources whose
+ * inventory carries the selected model, BEFORE health or runnability narrows them
+ * down. So a `false` means the resolver was never going to stop at this position,
+ * whatever else is true of it or of this machine.
+ *
+ * Only an explicit `false` counts. The field is `null` when nothing is selected —
+ * there is no route to be off — and absent from a server that predates it, and in
+ * both of those the order itself is the route the resolver walks. Reading silence
+ * as exclusion would retract a claim the strip has always been right to make.
+ */
+export function offCurrentModelChain(agent: Pick<AgentSupply, 'sources'>, sourceId: string): boolean {
+ const entry = agent.sources?.eligibility?.find((e) => e.source_id === sourceId);
+ return entry?.in_current_model_chain === false;
+}
+
/** The subset of `sources` this Agent may use — the menu/mapping surfaces' input. */
export function eligibleSources(sources: Source[], agent: Pick<AgentSupply, 'sources'>): Source[] {
return sources.filter((s) => eligibilityOf(agent, s.id).eligible);
diff --git a/ui/src/components/settings/models/menus/MappingDrawer.tsx b/ui/src/components/settings/models/menus/MappingDrawer.tsx
index 8f8c4c99d..38251632f 100644
--- a/ui/src/components/settings/models/menus/MappingDrawer.tsx
+++ b/ui/src/components/settings/models/menus/MappingDrawer.tsx
@@ -19,6 +19,7 @@ import { MenuDrawer } from './MenuDrawer';
import { eligibleSources } from '../eligibility';
import { buildTargetModels, type TargetModel } from './identifiers';
import { SupplyDots } from './supplyBits';
+import { useAnnounceEnrollment } from './enrollment';
import { useCompactSourceLabel } from './sourceLabel';
// Fixed-menu backends expose their built-in model catalog via agent.builtin_models
@@ -143,7 +144,8 @@ export const MappingDrawer: React.FC<{
agent: AgentSupply;
sources: Source[];
onClose: () => void;
- onSaved: () => void;
+ /** Hands the page the Agent row this write echoed — see `agentsWithEcho`. */
+ onSaved: (echoed: AgentSupply) => void;
}> = ({ open, backend, agent, sources, onClose, onSaved }) => {
const { t } = useTranslation();
const { showToast } = useToast();
@@ -152,6 +154,9 @@ export const MappingDrawer: React.FC<{
// (`agent.sources.eligibility`) — anything else is rejected by the live API
// with `mapping_target_unavailable`.
const targets = React.useMemo(() => buildTargetModels(eligibleSources(sources, agent)), [sources, agent]);
+ // Accepting an override may also enroll its supplier into this backend's source
+ // order (api.md → "Mapping and menu enrollment"). Read off the echo at commit.
+ const announceEnrollment = useAnnounceEnrollment(backend, sources);
const [draft, setDraft] = React.useState<AgentMapping[]>(() => seedDraft(agent));
const initialRef = React.useRef<AgentMapping[]>(draft);
@@ -203,8 +208,12 @@ export const MappingDrawer: React.FC<{
// supplier source was deleted); it reverts to 跟随原生 instead of being
// resubmitted and rejected as mapping_target_unavailable.
const targetIds = new Set(targets.map((tg) => tg.id));
- await modelsApi.putMappings(backend, draft.filter((m) => m.enabled && targetIds.has(m.target_model_id)));
- onSaved();
+ const echoed = await modelsApi.putMappings(
+ backend,
+ draft.filter((m) => m.enabled && targetIds.has(m.target_model_id)),
+ );
+ announceEnrollment(agent, echoed);
+ onSaved(echoed);
onClose();
} catch {
showToast(t('settings.models.menus.saveFailed') as string, 'error');
diff --git a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx
index 485a6b344..39f77aeef 100644
--- a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx
+++ b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx
@@ -21,6 +21,7 @@ import { AddCustomModelDialog } from './AddCustomModelDialog';
import { eligibleSources as filterEligible } from '../eligibility';
import { buildMenuGroups, type MenuModelRow } from './identifiers';
import { SupplyDots } from './supplyBits';
+import { useAnnounceEnrollment } from './enrollment';
type EditTarget = { sourceId: string; modelId: string; displayName: string | null } | null;
@@ -73,7 +74,8 @@ export const OpenCodeMenuDrawer: React.FC<{
agent: AgentSupply;
sources: Source[];
onClose: () => void;
- onSaved: () => void;
+ /** Hands the page the Agent row this write echoed — see `agentsWithEcho`. */
+ onSaved: (echoed: AgentSupply) => void;
/** Re-fetch sources after a custom model is added/edited. */
onRefresh: () => void;
}> = ({ open, agent, sources, onClose, onSaved, onRefresh }) => {
@@ -96,6 +98,9 @@ export const OpenCodeMenuDrawer: React.FC<{
// force-deleted source) is dropped rather than shown as an invisible checked
// row or sent to putMenu (which the server rejects as mapping_target_unavailable).
const availableIds = React.useMemo(() => new Set(allRows.map((r) => r.identifier)), [allRows]);
+ // Ticking a model may also enroll its supplier into OpenCode's source order
+ // (api.md → "Mapping and menu enrollment"). Read off the echo at commit.
+ const announceEnrollment = useAnnounceEnrollment('opencode', sources);
const [view, setView] = React.useState<'featured' | 'full'>(agent.menu?.view ?? 'featured');
const [checked, setChecked] = React.useState<Set<string>>(() => new Set(agent.menu?.checked ?? []));
@@ -152,8 +157,9 @@ export const OpenCodeMenuDrawer: React.FC<{
// `checked` is already self-healed at open and only grows via toggles/adds
// of available (or just-added) identifiers, so send it as-is — filtering
// here would strip a just-added custom model before onRefresh lands.
- await modelsApi.putMenu({ view, checked: [...checked] });
- onSaved();
+ const echoed = await modelsApi.putMenu({ view, checked: [...checked] });
+ announceEnrollment(agent, echoed);
+ onSaved(echoed);
onClose();
} catch {
showToast(t('settings.models.menus.saveFailed') as string, 'error');
diff --git a/ui/src/components/settings/models/menus/enrollment.test.ts b/ui/src/components/settings/models/menus/enrollment.test.ts
new file mode 100644
index 000000000..9b5a612cf
--- /dev/null
+++ b/ui/src/components/settings/models/menus/enrollment.test.ts
@@ -0,0 +1,55 @@
+// api.md → "Mapping and menu enrollment": accepting a target auto-appends its
+// supplier to the backend's order, and 「the confirm step must surface the
+// append」. These pin the one rule that makes the notice safe to show — the
+// append is READ, never predicted — and the two silences that must not become a
+// sentence.
+import { describe, expect, it } from 'vitest';
+
+import { enrolledByCommit } from './enrollment';
+import type { AgentSupply } from '../types';
+
+const withOrder = (order: string[] | null): Pick<AgentSupply, 'sources'> => ({
+ sources: order === null ? null : { policy: 'custom', order, eligibility: null },
+});
+
+describe('enrolledByCommit', () => {
+ it('names what the commit added, and nothing that was already there', () => {
+ expect(enrolledByCommit(withOrder(['src_a']), withOrder(['src_a', 'src_b']))).toEqual(['src_b']);
+ });
+
+ it('says nothing when the order came back unchanged', () => {
+ // The ordinary case: the ticked model's supplier was already enrolled, so the
+ // save changed the menu and nothing else. A notice here would fire on every
+ // 完成 and teach the user to dismiss the one that matters.
+ expect(enrolledByCommit(withOrder(['src_a', 'src_b']), withOrder(['src_a', 'src_b']))).toEqual([]);
+ });
+
+ it('reports several appends in the order the server put them', () => {
+ // One per target group, and the contract caps each group at one — but a
+ // multi-target commit can still enroll more than one supplier.
+ expect(enrolledByCommit(withOrder([]), withOrder(['src_b', 'src_c']))).toEqual(['src_b', 'src_c']);
+ });
+
+ it('reads a missing baseline as nothing to report, never as everything new', () => {
+ // `sources` is null in direct mode, and a drawer that opened against one
+ // would otherwise announce the entire order as freshly enrolled — the one
+ // sentence this must never produce.
+ expect(enrolledByCommit(withOrder(null), withOrder(['src_a', 'src_b']))).toEqual([]);
+ });
+
+ it('claims nothing when the echo itself carries no order', () => {
+ expect(enrolledByCommit(withOrder(['src_a']), withOrder(null))).toEqual([]);
+ });
+
+ it('ignores a reordering that enrolled nobody', () => {
+ // The diff is membership, not position: the drawer does not edit the order,
+ // so a server that re-sorted it has still enrolled nothing.
+ expect(enrolledByCommit(withOrder(['src_a', 'src_b']), withOrder(['src_b', 'src_a']))).toEqual([]);
+ });
+
+ it('does not report a source the commit REMOVED as if it were added', () => {
+ // A dropped id (deleted, or newly ineligible) is a shrinking order. The
+ // notice is about what came in; a subtraction has no sentence here.
+ expect(enrolledByCommit(withOrder(['src_a', 'src_b']), withOrder(['src_a']))).toEqual([]);
+ });
+});
diff --git a/ui/src/components/settings/models/menus/enrollment.ts b/ui/src/components/settings/models/menus/enrollment.ts
new file mode 100644
index 000000000..bae67196f
--- /dev/null
+++ b/ui/src/components/settings/models/menus/enrollment.ts
@@ -0,0 +1,101 @@
+// What accepting a menu edit ALSO did to the backend's source order.
+//
+// api.md → "Mapping and menu enrollment": a mapping or open-menu target is
+// accepted only when its selected source is enrolled in the post-mutation
+// effective order, and acceptance auto-appends that source — 「the confirm step
+// must surface the append」. The user ticked a model; the server also changed
+// which accounts that backend will spend, and nothing on screen said so.
+//
+// Read from the echo, never predicted. The server picks the first supplier in ITS
+// recommended order (`_enroll_target_sources`), so a client that computed the
+// append before committing would be re-deriving a server rule from a snapshot
+// that may already be stale — and would name the wrong source the first time the
+// two disagree. Both orders below are `effective_source_order` as the payload
+// reports it, for either policy, so the diff is one subtraction and no rule.
+import * as React from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useToast } from '@/context/ToastContext';
+import type { AgentBackend, AgentSupply, Source } from '../types';
+import { useCompactSourceLabel } from './sourceLabel';
+
+/**
+ * The ids the commit added to the order, in the order the server put them.
+ *
+ * `[]` when nothing was appended AND when either side is missing, because the two
+ * are the same statement here: with no baseline every id looks new, and 「保存后
+ * 自动加入了全部来源」 is the one sentence this must never produce. Both callers
+ * only speak when the list is non-empty, so silence needs no second member.
+ *
+ * WHAT `before` HAS TO BE: the order the server held when this write began. It is
+ * the page's own Agent list, so a `sources.order` PUT that lands in the window
+ * between the page reading it and this write returning would show up in the diff
+ * and be reported as this write's doing. The one path that could reach that window
+ * is closed where it opens rather than compensated for here, in two parts that meet:
+ * 来源顺序's hand-off to these drawers is shut while its write is in flight — the
+ * outstanding-write fact held by the PAGE, not by the drawer issuing it, since the
+ * user can close that drawer, which unmounts it, and reopen it mid-write
+ * (`createPendingWrites`) — and the order it wrote reaches this list as the WRITE'S
+ * OWN ECHO (`agentsWithEcho`), so the baseline is caught up even when the re-read
+ * that would otherwise have carried it fails or is superseded.
+ * The general case — any order write from outside this page's read cycle — is not
+ * client-answerable, and its fix is the mutation response naming its own appends
+ * (`enrolled_source_ids`), server-side and escalated rather than approximated here.
+ */
+export function enrolledByCommit(
+ before: Pick<AgentSupply, 'sources'>,
+ after: Pick<AgentSupply, 'sources'>,
+): string[] {
+ const was = before.sources?.order;
+ const now = after.sources?.order;
+ if (!was || !now) return [];
+ const enrolled = new Set(was);
+ return now.filter((id) => !enrolled.has(id));
+}
+
+/**
+ * Both drawers' 完成, in one place: diff the echo against what was on screen and
+ * say what the save also enrolled.
+ *
+ * Shared rather than written twice for the reason `AdoptionNote` was: two dialogs
+ * reporting one server behaviour in their own words is how they end up saying
+ * different things about the same event. The append is per-commit and identical
+ * for a fixed menu and an open one — only the backend's name differs.
+ *
+ * Silent when nothing was appended, which is the ordinary case: a ticked model
+ * whose supplier is already in the order changes only the menu, and a toast that
+ * fires every time teaches the user to dismiss the one that matters. It says
+ * nothing about the policy either — under `follow` the effective order is
+ * exhaustive over eligible sources, so an append means the order was already
+ * `custom` and no recommendation was lost.
+ */
+export function useAnnounceEnrollment(
+ backend: AgentBackend,
+ sources: readonly Source[],
+): (before: Pick<AgentSupply, 'sources'>, after: Pick<AgentSupply, 'sources'>) => void {
+ const { t } = useTranslation();
+ const { showToast } = useToast();
+ const compactLabel = useCompactSourceLabel();
+ return React.useCallback(
+ (before, after) => {
+ const enrolled = enrolledByCommit(before, after);
+ if (enrolled.length === 0) return;
+ const byId = new Map(sources.map((s) => [s.id, s]));
+ const names = enrolled.map((id) => {
+ const source = byId.get(id);
+ // An id the inventory on screen does not carry is still an enrollment
+ // that happened. Naming it by id is worse copy and a true sentence;
+ // dropping it would silently under-report what the save did.
+ return source ? compactLabel(source) : id;
+ });
+ showToast(
+ t('settings.models.menus.enrolled', {
+ sources: names.join(' · '),
+ backend: t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string,
+ }) as string,
+ 'success',
+ );
+ },
+ [backend, compactLabel, showToast, sources, t],
+ );
+}
diff --git a/ui/src/components/settings/models/mockData.ts b/ui/src/components/settings/models/mockData.ts
index c87e2ed95..b9332a946 100644
--- a/ui/src/components/settings/models/mockData.ts
+++ b/ui/src/components/settings/models/mockData.ts
@@ -148,6 +148,9 @@ export function buildMockAgents(sources: Source[] = buildMockSources()): AgentSu
menu_kind: 'fixed',
selected_by_agent: null,
selected_model_id: 'claude-opus-4-6',
+ // A stored request stands behind the id, which is what the server reports
+ // as explicit — the resolver-picked case only exists on the open menu.
+ selected_model_explicit: true,
current: { model_id: 'claude-opus-4-6', source_id: 'src_claudepro1', channel: 'native_cli' },
sources: {
policy: 'custom',
@@ -189,6 +192,7 @@ export function buildMockAgents(sources: Source[] = buildMockSources()): AgentSu
menu_kind: 'fixed',
selected_by_agent: 'codex',
selected_model_id: 'gpt-5.6',
+ selected_model_explicit: true,
current: { model_id: 'gpt-5.6', source_id: 'src_chatgptplus', channel: 'native_cli' },
sources: {
policy: 'follow',
@@ -218,6 +222,7 @@ export function buildMockAgents(sources: Source[] = buildMockSources()): AgentSu
menu_kind: 'open',
selected_by_agent: null,
selected_model_id: null,
+ selected_model_explicit: false,
current: null,
sources: null,
supply_status: null,
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
index 039b1a20b..d0a37f45e 100644
--- a/ui/src/components/settings/models/modelsApi.ts
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -18,6 +18,7 @@ import {
mockEligibility,
mockRecommendedOrder,
} from './mockData';
+import { buildIdentifier } from './menus/identifiers';
import { canReauth, canReplaceKey, wasBlocked } from './repair';
import { isUnhealthy } from './supply';
import type {
@@ -39,6 +40,7 @@ import type {
ProbeResult,
ResolutionEvent,
RuntimeDependency,
+ SkippedBy,
Source,
SourcePatch,
SourceRepaired,
@@ -57,8 +59,16 @@ import { AGENT_CHAIN_CONTRACT_VERSION, PROBE_RESULT_CONTRACT_VERSION } from './t
* in and at which one-based position. A `custom` backend is absent — not because
* nothing happened to it, but because nothing did, which is exactly the case the
* user has to be told about while the dialog is still open.
+ *
+ * `skipped_by` is the server naming that case: the backends that COULD have used
+ * this source and were left out because they keep a `custom` order. It is carried
+ * beside `adopted_by` rather than derived from it, because 「absent」 covers both
+ * that and 「never eligible」, and only the server can tell the two apart. Kept
+ * nullable through this reader: an absent array is a server that did not answer
+ * the question, which is not the same as one answering 「nobody」.
*/
-export type SourceCreated = { source: Source; adopted_by: AdoptedBy[] };
+export type Adoption = { adopted_by: AdoptedBy[]; skipped_by: SkippedBy[] | null };
+export type SourceCreated = { source: Source } & Adoption;
/**
* The response of BOTH oauth status and submit (api.md → OAuth completion): the
@@ -269,14 +279,33 @@ const jsonInit = (method: string, body?: unknown): RequestInit => ({
body: body === undefined ? undefined : JSON.stringify(body),
});
-/** api.md pins the shape to `{source, adopted_by}` with no extra nesting; the
- * bare-`Source` arm is the same tolerance every other write here keeps. */
-type SourceCreatedResponse = { source?: Source; adopted_by?: AdoptedBy[] } & Source;
+/**
+ * The adoption tail, defaulted. Both creation routes answer with it — the plain
+ * one and the oauth envelope — and the two defaults below are DIFFERENT rules, so
+ * they get one reader rather than two copies that would eventually agree.
+ *
+ * `adopted_by` is a list of things that happened: absent can only mean none did.
+ * (Absent-is-not-empty holds in the contract for reauth, which never reaches here.)
+ *
+ * `skipped_by` is the answer to 「who was left out」, and `[]` there is a positive
+ * claim that nobody was. A server that never sent the field has not made that
+ * claim, so silence stays null — defaulting it to `[]` would upgrade 「did not
+ * say」 into 「fully covered」, which is the one thing the adoption note exists to
+ * avoid.
+ */
+type AdoptionTail = { adopted_by?: AdoptedBy[]; skipped_by?: SkippedBy[] };
+const adoption = (r: AdoptionTail): Adoption => ({
+ adopted_by: r.adopted_by ?? [],
+ skipped_by: r.skipped_by ?? null,
+});
+
+/** api.md pins the shape to `{source, adopted_by, skipped_by}` with no extra
+ * nesting; the bare-`Source` arm is the same tolerance every other write here
+ * keeps. */
+type SourceCreatedResponse = { source?: Source } & AdoptionTail & Source;
const created = (r: SourceCreatedResponse): SourceCreated => ({
source: (r.source ?? r) as Source,
- // Absent is not the same as empty in the contract only for reauth, which never
- // reaches here; for creation an absent array means nothing adopted it.
- adopted_by: r.adopted_by ?? [],
+ ...adoption(r),
});
/** api.md "recovery symmetry": both repair routes answer with this same tail,
@@ -289,9 +318,9 @@ const repaired = (r: SourceRepairedResponse): SourceRepaired => ({
});
/** The oauth terminal envelope, unwrapped without discarding either tail. */
-export type OAuthResultResponse = { flow?: OAuthFlow } & OAuthFlow & {
+export type OAuthResultResponse = { flow?: OAuthFlow } & OAuthFlow &
+ AdoptionTail & {
source?: Source;
- adopted_by?: AdoptedBy[];
recovered?: boolean;
interrupted_pairs?: SupplyGap[];
};
@@ -308,9 +337,10 @@ export const oauthResult = (r: OAuthResultResponse): OAuthResult => {
return {
flow,
// No bare-`Source` tolerance here, unlike `created()`: this envelope always
- // nests the source under `source`, beside the flow it accompanies. An absent
- // `adopted_by` beside a present `source` still means nothing adopted it.
- created: isCreate && r.source ? { source: r.source, adopted_by: r.adopted_by ?? [] } : null,
+ // nests the source under `source`, beside the flow it accompanies. The tail
+ // itself goes through the same `adoption` reader, so the two routes cannot
+ // default one of these arrays differently from the other.
+ created: isCreate && r.source ? { source: r.source, ...adoption(r) } : null,
// The repair tail. `recovered` is defaulted false rather than optional: it is
// the server's own 「this source had been blocked」 judgement, and absent must
// read as 「did not say so」 — never as a client guess that it was.
@@ -421,6 +451,7 @@ class MockStore {
if (a.mode === 'direct') {
a.current = null;
a.selected_model_id = null;
+ a.selected_model_explicit = false;
a.selected_by_agent = null;
a.supply_status = null;
a.model_supply = null;
@@ -487,6 +518,30 @@ class MockStore {
}));
}
+ /**
+ * The complement, derived the way `_skipped_by` derives it: ELIGIBLE for this
+ * backend, on a `custom` order, and not in it. The eligibility filter is what
+ * makes the two lists different from `MODEL_HUB_BACKENDS` minus `adopted_by` —
+ * a backend that could never use the credential belongs to neither.
+ */
+ private skippedOf(sourceId: string): SkippedBy[] {
+ this.syncAgents();
+ return this.agents
+ .filter(
+ (a) =>
+ a.mode === 'hub' &&
+ a.sources?.policy === 'custom' &&
+ !a.sources.order.includes(sourceId) &&
+ (a.sources.eligibility ?? []).some((e) => e.source_id === sourceId && e.eligible),
+ )
+ .map((a) => ({ backend: a.backend, reason: 'custom_order' as const }));
+ }
+
+ /** Both creation routes answer with the same pair. */
+ private adoptionTail(sourceId: string) {
+ return { adopted_by: this.adoptionOf(sourceId), skipped_by: this.skippedOf(sourceId) };
+ }
+
createApiKeySource(draft: ApiKeySourceCreate) {
const count = mockDiscoveredCount(draft.vendor);
const source: Source = {
@@ -514,7 +569,7 @@ class MockStore {
};
this.sources.push(source);
// simulate probe latency
- return delay({ source: structuredClone(source), adopted_by: this.adoptionOf(source.id) }, 900);
+ return delay({ source: structuredClone(source), ...this.adoptionTail(source.id) }, 900);
}
/**
@@ -775,6 +830,9 @@ class MockStore {
// model the backend defaults to (first built-in / first supplied id).
agent.sources = { policy: 'follow', order: [], eligibility: null };
agent.selected_model_id = agent.builtin_models?.[0] ?? this.sources[0]?.models[0]?.id ?? null;
+ // The server's default comes from the STORED per-backend request, so a
+ // non-null id here is explicit; nothing selected is the false case.
+ agent.selected_model_explicit = agent.selected_model_id !== null;
agent.named_agents = (agent.named_agents ?? []).map((n) => ({
...n,
effective_model_id: agent.selected_model_id ?? null,
@@ -784,17 +842,68 @@ class MockStore {
return delay(structuredClone(agent));
}
+ /**
+ * `_enroll_target_sources` in miniature (api.md → "Mapping and menu
+ * enrollment"): a target whose suppliers are all outside the order pulls in
+ * EXACTLY ONE — the first in the recommendation — and the order forks to
+ * `custom` only when something was actually appended.
+ *
+ * Modelled here rather than left as a no-op for the reason `oauthResult`
+ * documents: a mock that treats a mutation and its side effect as separate is
+ * a mock that cannot fail the way the product does, and the drawers' 完成
+ * notice exists only because of this side effect.
+ */
+ private enrollTargets(agent: AgentSupply, targetGroups: string[][]) {
+ const order = agent.sources?.order ?? [];
+ const enrolled = new Set(order);
+ const appended: string[] = [];
+ for (const group of targetGroups) {
+ if (group.length === 0 || group.some((id) => enrolled.has(id))) continue;
+ enrolled.add(group[0]);
+ appended.push(group[0]);
+ }
+ if (appended.length === 0) return;
+ agent.sources = { policy: 'custom', order: [...order, ...appended], eligibility: null };
+ }
+
+ /** The suppliers of one target, in the recommendation's order — the list the
+ * server picks its single enrollee from. */
+ private suppliersOf(backend: AgentBackend, carries: (source: Source) => boolean): string[] {
+ const byId = new Map(this.sources.map((s) => [s.id, s]));
+ return mockRecommendedOrder(this.sources, backend).filter((id) => {
+ const source = byId.get(id);
+ return source ? carries(source) : false;
+ });
+ }
+
putMappings(backend: AgentBackend, mappings: AgentMapping[]) {
const agent = this.agents.find((a) => a.backend === backend);
if (!agent) throw new ApiCallError('source_not_found');
+ this.enrollTargets(
+ agent,
+ mappings
+ .filter((m) => m.enabled)
+ .map((m) => this.suppliersOf(backend, (s) => s.models.some((mm) => mm.id === m.target_model_id))),
+ );
agent.mappings = mappings;
+ this.syncAgents();
return delay(structuredClone(agent));
}
putMenu(menu: AgentMenu) {
const agent = this.agents.find((a) => a.backend === 'opencode');
if (!agent) throw new ApiCallError('source_not_found');
+ const standardVendors = new Set(agent.standard_vendors ?? []);
+ this.enrollTargets(
+ agent,
+ menu.checked.map((identifier) =>
+ this.suppliersOf('opencode', (s) =>
+ s.models.some((mm) => buildIdentifier(s.vendor, mm.id, standardVendors) === identifier),
+ ),
+ ),
+ );
agent.menu = menu;
+ this.syncAgents();
return delay(structuredClone(agent));
}
@@ -1027,7 +1136,7 @@ class MockStore {
}
return {
flow,
- created: { source: structuredClone(source), adopted_by: this.adoptionOf(source.id) },
+ created: { source: structuredClone(source), ...this.adoptionTail(source.id) },
repaired: null,
};
}
diff --git a/ui/src/components/settings/models/oauthResult.test.ts b/ui/src/components/settings/models/oauthResult.test.ts
index 8a868ade7..8493eef93 100644
--- a/ui/src/components/settings/models/oauthResult.test.ts
+++ b/ui/src/components/settings/models/oauthResult.test.ts
@@ -10,7 +10,7 @@
import { describe, expect, it } from 'vitest';
import { oauthResult, type OAuthResultResponse } from './modelsApi';
-import type { AdoptedBy, OAuthFlow, Source } from './types';
+import type { AdoptedBy, OAuthFlow, SkippedBy, Source } from './types';
const flow = (over: Partial<OAuthFlow> = {}): OAuthFlow => ({
flow_id: 'oaf_1',
@@ -26,18 +26,41 @@ const flow = (over: Partial<OAuthFlow> = {}): OAuthFlow => ({
const source = { id: 'src_1', vendor: 'anthropic', kind: 'subscription' } as unknown as Source;
const adopted: AdoptedBy[] = [{ backend: 'claude', policy: 'follow', position: 1 }];
+const skipped: SkippedBy[] = [{ backend: 'codex', reason: 'custom_order' }];
describe('oauthResult', () => {
it('keeps the creation the terminal response reports', () => {
- const r = { flow: flow(), source, adopted_by: adopted } as OAuthResultResponse;
- expect(oauthResult(r)).toEqual({ flow: r.flow, created: { source, adopted_by: adopted }, repaired: null });
+ const r = { flow: flow(), source, adopted_by: adopted, skipped_by: skipped } as OAuthResultResponse;
+ expect(oauthResult(r)).toEqual({
+ flow: r.flow,
+ created: { source, adopted_by: adopted, skipped_by: skipped },
+ repaired: null,
+ });
});
it('reads an absent adopted_by beside a source as nothing adopted it', () => {
// Distinct from a response that reports no creation at all: here the source
// exists, so 「没有 Agent 采用」 is a true statement and must be rendered.
const { created } = oauthResult({ flow: flow(), source } as OAuthResultResponse);
- expect(created).toEqual({ source, adopted_by: [] });
+ expect(created?.adopted_by).toEqual([]);
+ });
+
+ it('reads an absent skipped_by the OTHER way, as a question left unanswered', () => {
+ // The two halves of the tail default in opposite directions, and this is the
+ // one the dialog's auto-close hangs on. `adopted_by` lists things that
+ // happened, so absent can only mean none did. `skipped_by` answers 「who was
+ // left out」, where `[]` is a positive claim of full coverage — a server that
+ // never sent the field has not made it, so silence stays null and `covered`
+ // stays out of reach.
+ const { created } = oauthResult({ flow: flow(), source, adopted_by: adopted } as OAuthResultResponse);
+ expect(created?.skipped_by).toBeNull();
+ });
+
+ it('keeps an empty skipped_by as the claim it is', () => {
+ // The counterpart: `[]` here IS the server saying 「nobody was left out」, and
+ // collapsing it back to null would strand the one arrival that can settle.
+ const r = { flow: flow(), source, adopted_by: adopted, skipped_by: [] } as OAuthResultResponse;
+ expect(oauthResult(r).created?.skipped_by).toEqual([]);
});
it('reports no creation while the flow is still running', () => {
diff --git a/ui/src/components/settings/models/repair.test.ts b/ui/src/components/settings/models/repair.test.ts
index e47927254..73b79ee4b 100644
--- a/ui/src/components/settings/models/repair.test.ts
+++ b/ui/src/components/settings/models/repair.test.ts
@@ -372,6 +372,9 @@ describe('dryRunPlan — whether 试跑 has anything to run (SourceOrderDrawer)'
describe('dryRunChainKey — which edits make a 试跑 report stop being about anything', () => {
const base = agent({
selected_model_id: 'claude-opus-4-6',
+ // What the server sends beside a non-null id on a fixed-menu backend: the hub
+ // path echoes the stored request, so an id there always had a request behind it.
+ selected_model_explicit: true,
mappings: [{ builtin_id: 'claude-opus-4-6', target_model_id: 'glm-5.2', enabled: true }],
menu: { view: 'featured', checked: ['zhipuai/glm-5.2'] },
});
@@ -399,6 +402,34 @@ describe('dryRunChainKey — which edits make a 试跑 report stop being about a
expect(key({ menu: { view: 'featured', checked: [] } })).not.toBe(same);
});
+ it('keys on the selected model only while the user is the one who asked for it', () => {
+ // Round 15 escalated this gap and #1110 closed it. `selected_model_id` is the
+ // resolver's ECHO: on opencode with no explicit request the resolver walks
+ // `checked` and returns the first identifier whose source is runnable, so
+ // keying on it would let a failing probe cool the head, move the pick, and
+ // erase the very report the click produced. `selected_model_explicit` is the
+ // config fact behind that echo, so the member is present for an explicit pick
+ // on ANY backend and absent for a resolved one — no backend special case left.
+ const opencode = {
+ backend: 'opencode',
+ menu_kind: 'open',
+ menu: { view: 'featured', checked: ['zhipuai/glm-5.2', 'anthropic/claude-opus-4-6'] },
+ } as const;
+ const resolved = key({ ...opencode, selected_model_id: 'zhipuai/glm-5.2', selected_model_explicit: false });
+ // A pick the resolver made is not a surface the user selected with: which of
+ // the two runnable identifiers came back cannot move this key.
+ expect(
+ key({ ...opencode, selected_model_id: 'anthropic/claude-opus-4-6', selected_model_explicit: false }),
+ ).toBe(resolved);
+ // The same identifier, this time because the user asked for it — a different
+ // configuration, and now a different key.
+ const asked = key({ ...opencode, selected_model_id: 'zhipuai/glm-5.2', selected_model_explicit: true });
+ expect(asked).not.toBe(resolved);
+ // And an explicit opencode selection moves the key when it changes, which is
+ // exactly what the old backend exclusion dropped.
+ expect(key({ ...opencode, selected_model_id: 'zhipuai/glm-5.3', selected_model_explicit: true })).not.toBe(asked);
+ });
+
it('holds still for everything the server derives from those', () => {
// The trap this key exists inside: a failing 试跑 cools its own head down and
// the re-read it owes then moves `agent.current`, the rollup, and the source
@@ -483,15 +514,12 @@ describe('dryRunChainKey — which edits make a 试跑 report stop being about a
);
});
- it('reads opencode by its own selection surface, not by the pick', () => {
- // `selected_model_id` is config for a fixed menu, but for opencode with an
- // empty request `resolve_model_hub_turn` walks `menu.checked` and returns the
- // first identifier whose source is runnable — so a cooldown MOVES it. Keying
- // on it there would smuggle head health back in through the model field and
- // re-create the self-erasing report above.
- const oc = { backend: 'opencode' as const, menu_kind: 'open' as const };
- expect(key({ ...oc, selected_model_id: 'zhipuai/glm-5.2' })).toBe(key({ ...oc, selected_model_id: 'openai/gpt-6' }));
- // What the user actually selects with there still counts.
+ it('falls back to the opencode selection surface when the resolver made the pick', () => {
+ // The other half of the rule above: with the model member gone, what the user
+ // selects with on an open menu is the checked list itself, and that still moves
+ // the key. Otherwise excluding a resolved pick would leave opencode with no
+ // selection member at all.
+ const oc = { backend: 'opencode' as const, menu_kind: 'open' as const, selected_model_explicit: false };
expect(key({ ...oc, menu: { view: 'full', checked: ['openai/gpt-6'] } })).not.toBe(key(oc));
});
diff --git a/ui/src/components/settings/models/repair.ts b/ui/src/components/settings/models/repair.ts
index 2ec63fce7..e0e2066de 100644
--- a/ui/src/components/settings/models/repair.ts
+++ b/ui/src/components/settings/models/repair.ts
@@ -219,10 +219,11 @@ export const repairOutcome = (tail: SourceRepaired): RepairOutcome =>
/**
* Whether the journey may close itself.
*
- * Provable from the tail alone, unlike the adoption auto-close next door: that
- * one stays dormant because `covered` needs a `skipped_by` the contract does not
- * carry yet, whereas 「nothing was stranded, and the source came back working」 is
- * two fields the server sends.
+ * Provable from the tail alone: 「nothing was stranded, and the source came back
+ * working」 is two fields the server sends. The adoption auto-close next door now
+ * stands on the same footing — `covered` needs `skipped_by`, and that field has
+ * since landed — so the two differ in which fields they read, not in whether they
+ * can reach a verdict at all.
*
* An allowlist rather than `!== 'gaps'`: L4's rule is that the 1.4s dismissal is
* for a plain success and 「every other verdict leaves an instruction on screen
@@ -343,26 +344,31 @@ export function dryRunPlan(agent: AgentSupply): DryRunPlan {
* by an edit that did not matter, which the user answers by re-running 一次试跑
* — the same asymmetry the inventory paragraph below settles the same way.
* `savedMenuKey` already reads this list in order for the drawer's own baseline.
- * - `selected_model_id` for every backend EXCEPT opencode. On the fixed-menu
- * backends the hub path echoes `requested_model` back verbatim in every return
- * (only `target_model` takes the mapping), so it is the configured request. On
- * opencode with no explicit request the resolver loops `menu.checked` and returns
- * the first identifier whose source is runnable — `unavailable_source_ids` and
- * cooldown gating decide which one wins, so there it is a health-derived pick and
- * `checked` is the honest stand-in for what the user chose.
- *
- * That last exclusion is coarser than the truth, and knowingly so: an OpenCode
- * request that IS explicit comes back normalized but otherwise untouched, so it is
- * a selection this key drops. The payload has no way to tell the two apart — the
- * agent config carries no model at all, and every projected model on it is the same
- * resolver output — and both client-side approximations are worse than the gap.
- * Keying on the value erases a failure report on any single-source setup, because
- * the probe that failed cools the only source the head model had and the pick moves.
- * Gating the member on `supply_status` (sound: the loop only ever returns a
- * candidate WITH a source, so `waiting`/`interrupted` proves the request was
- * explicit) does the same thing through the guard instead of the value. The fix is
- * a server-side discriminator — explicitness beside `selected_model_id` — and this
- * stays as it is until there is one.
+ * - `selected_model_id`, but only while `selected_model_explicit` says the user is
+ * the one who asked for it. One rule for every backend, because the flag states
+ * the rule the backends were a proxy for: it is a CONFIG fact, derived from the
+ * stored request before anything resolves (`service.py:2109` —
+ * `mode == "hub" and bool(requested_model)`), while `selected_model_id` is the
+ * resolver's echo of that same request. On the fixed-menu backends the two agree
+ * and the guard changes nothing: the hub path echoes `requested_model` back
+ * verbatim in every return (only `target_model` takes the mapping), so a
+ * non-null id there always had a request behind it, and an unset request stays
+ * empty through to a null id. On opencode it separates the two cases that used to
+ * be one — an explicit request comes back merely normalized and IS now keyed on,
+ * while an empty one sends the resolver walking `checked` for the first
+ * identifier whose source is runnable (`resolver.py:171-182`), a pick that
+ * `unavailable_source_ids` and cooldown gating decide and that `checked` above
+ * stands in for.
+ *
+ * Reading the flag is what makes the member health-free, and it is why this
+ * waited for the server instead of approximating. Both client-side stand-ins
+ * keyed on something the failing probe itself moves: on the VALUE, a
+ * single-source setup erases its own report, because the probe cools the only
+ * source the head model had and the pick moves; on `supply_status` (sound —
+ * the loop only ever returns a candidate WITH a source, so
+ * `waiting`/`interrupted` proves the request was explicit) the same erasure,
+ * through the guard rather than the value. `selected_model_explicit` moves only
+ * when the user edits the request, so the report survives its own failure.
*
* - the sources' model INVENTORIES, and this one is not the user's edit at all.
* Everything above is a surface the user changes from this page, and the
@@ -403,7 +409,7 @@ export const dryRunChainKey = (
[
policy,
order.join('>'),
- agent.backend === 'opencode' ? '' : (agent.selected_model_id ?? ''),
+ agent.selected_model_explicit ? (agent.selected_model_id ?? '') : '',
(agent.mappings ?? [])
.map((m) => `${m.builtin_id}>${m.target_model_id}:${m.enabled ? 'on' : 'off'}`)
.sort()
diff --git a/ui/src/components/settings/models/sufficiency.test.ts b/ui/src/components/settings/models/sufficiency.test.ts
index f37b3da9d..3f9157282 100644
--- a/ui/src/components/settings/models/sufficiency.test.ts
+++ b/ui/src/components/settings/models/sufficiency.test.ts
@@ -17,7 +17,7 @@ import {
isSupplyWarning,
orderSufficiency,
} from './sufficiency';
-import type { AdoptedBy, AgentSupply, Source, SourceState, SourceStatus } from './types';
+import type { AdoptedBy, AgentSupply, Source, SourceEligibility, SourceState, SourceStatus } from './types';
const source = (id: string, status: SourceStatus): Source => ({
id,
@@ -31,11 +31,30 @@ const source = (id: string, status: SourceStatus): Source => ({
models: [],
});
-const hub = (order: string[], supply_status: AgentSupply['supply_status'] = null): AgentSupply => ({
+/** Sources the server says this Agent's machine cannot launch — healthy, eligible,
+ * and still unable to take the turn. The rows carry `eligible: true` on purpose:
+ * the two questions are independent, and this one has to bite on its own. */
+const unlaunchable = (ids: readonly string[]): SourceEligibility[] =>
+ ids.map((id) => ({ source_id: id, eligible: true, process_availability_reason: 'native_cli_unavailable' }));
+
+/** The Agent-grain facts `orderSufficiency` hangs off. Its `order` is deliberately
+ * the WRONG list — the ids under test come in as the first argument. */
+const facts = (...cannotLaunch: string[]): Pick<AgentSupply, 'sources'> => ({
+ sources: { policy: 'follow', order: ['not-the-list-under-test'], eligibility: unlaunchable(cannotLaunch) },
+});
+
+/** Direct mode, and every payload that omits the optional field: nothing claimed. */
+const NO_FACTS: Pick<AgentSupply, 'sources'> = { sources: null };
+
+const hub = (
+ order: string[],
+ supply_status: AgentSupply['supply_status'] = null,
+ cannotLaunch: string[] = [],
+): AgentSupply => ({
backend: 'claude',
mode: 'hub',
menu_kind: 'fixed',
- sources: { policy: 'follow', order },
+ sources: { policy: 'follow', order, eligibility: unlaunchable(cannotLaunch) },
supply_status,
});
@@ -73,28 +92,38 @@ describe('adoptionVerdict — the creation dialogs (AdoptionNote, AddApiKeyDialo
it('names the skipped backends when the server states them', () => {
const verdict = adoptionVerdict(
[adopted('claude', 1)],
- [{ backend: 'codex', reason: 'custom-order-omission' }],
+ [{ backend: 'codex', reason: 'custom_order' }],
);
expect(verdict).toEqual({ kind: 'partly_skipped', backends: ['codex'] });
});
- it('still reports adopted_none when everyone skipped', () => {
- // Nobody adopted it: the remedy is the same 「go add it somewhere」 line, and
- // splitting that into a second sentence would say less, not more.
- expect(adoptionVerdict([], [{ backend: 'codex', reason: 'custom-order-omission' }])).toEqual({
- kind: 'adopted_none',
+ it('names the orders when nobody adopted it and the server said who left it out', () => {
+ // Not a corner case: this is the normal shape of an install where every eligible
+ // backend keeps a hand-picked order, and it is the case `skipped_by` was added
+ // for. The remedy matches `adopted_none`, and the difference is the whole value —
+ // 「go add it somewhere」 vs. 「go add it in these two」.
+ expect(adoptionVerdict([], [{ backend: 'codex', reason: 'custom_order' }])).toEqual({
+ kind: 'skipped_all',
+ backends: ['codex'],
});
});
+
+ it('stays at adopted_none when an empty adopter list is all the server sent', () => {
+ // Nothing to name, from either direction: no complement at all, and a complement
+ // that is itself empty (nothing eligible was left out either).
+ expect(adoptionVerdict([], null)).toEqual({ kind: 'adopted_none' });
+ expect(adoptionVerdict([], [])).toEqual({ kind: 'adopted_none' });
+ });
});
describe('orderSufficiency — the drawer (SourceOrderDrawer) and the connect toasts', () => {
it('separates 「nothing enabled」 from 「nothing works」, because the remedies differ', () => {
- expect(orderSufficiency([], [source('a', 'active')])).toEqual({ kind: 'adopted_none' });
- expect(orderSufficiency(['a'], [source('a', 'needs_action')])).toEqual({ kind: 'nothing_runnable' });
+ expect(orderSufficiency([], [source('a', 'active')], NO_FACTS)).toEqual({ kind: 'adopted_none' });
+ expect(orderSufficiency(['a'], [source('a', 'needs_action')], NO_FACTS)).toEqual({ kind: 'nothing_runnable' });
});
it('is covered when any enabled source can serve, not when the list is non-empty', () => {
- expect(orderSufficiency(['a', 'b'], [source('a', 'error'), source('b', 'standby')])).toEqual({
+ expect(orderSufficiency(['a', 'b'], [source('a', 'error'), source('b', 'standby')], NO_FACTS)).toEqual({
kind: 'covered',
});
});
@@ -102,17 +131,154 @@ describe('orderSufficiency — the drawer (SourceOrderDrawer) and the connect to
it('counts a cooling source as unable to serve right now', () => {
// `cooldown` heals itself, but the turn taken during it still fails, and this
// verdict answers 「the NEXT turn」.
- expect(orderSufficiency(['a'], [source('a', 'cooldown')])).toEqual({ kind: 'nothing_runnable' });
+ expect(orderSufficiency(['a'], [source('a', 'cooldown')], NO_FACTS)).toEqual({ kind: 'nothing_runnable' });
});
it('will not claim nothing runs when an enabled id is missing from the inventory', () => {
// The two reads can disagree; an id we cannot resolve is unknown, not broken.
- expect(orderSufficiency(['a', 'ghost'], [source('a', 'error')])).toEqual({ kind: 'indeterminate' });
+ expect(orderSufficiency(['a', 'ghost'], [source('a', 'error')], NO_FACTS)).toEqual({ kind: 'indeterminate' });
});
it('is indeterminate where the source inventory is not loaded', () => {
- expect(orderSufficiency(['a'], null)).toEqual({ kind: 'indeterminate' });
- expect(orderSufficiency(null, [source('a', 'active')])).toEqual({ kind: 'indeterminate' });
+ expect(orderSufficiency(['a'], null, NO_FACTS)).toEqual({ kind: 'indeterminate' });
+ expect(orderSufficiency(null, [source('a', 'active')], NO_FACTS)).toEqual({ kind: 'indeterminate' });
+ });
+
+ // The v4 caveat this closes: a `native_cli` source whose CLI is not usable on this
+ // machine reports itself perfectly healthy, because the credential IS fine.
+ it('counts a healthy source this machine cannot launch as unable to serve', () => {
+ expect(orderSufficiency(['a'], [source('a', 'active')], facts('a'))).toEqual({ kind: 'nothing_runnable' });
+ });
+
+ it('needs BOTH halves before it says covered', () => {
+ // One reachable-and-launchable source is enough; neither half alone is.
+ expect(orderSufficiency(['a', 'b'], [source('a', 'active'), source('b', 'active')], facts('a'))).toEqual({
+ kind: 'covered',
+ });
+ expect(orderSufficiency(['a', 'b'], [source('a', 'active'), source('b', 'cooldown')], facts('a'))).toEqual({
+ kind: 'nothing_runnable',
+ });
+ });
+
+ it('reads silence as runnable rather than inventing an outage', () => {
+ // Direct mode, a server that omits the optional field, and a source with no row
+ // all mean 「nothing claimed」 — the weaker claim, never the false alarm.
+ expect(orderSufficiency(['a'], [source('a', 'active')], NO_FACTS)).toEqual({ kind: 'covered' });
+ expect(orderSufficiency(['a'], [source('a', 'active')], facts())).toEqual({ kind: 'covered' });
+ expect(orderSufficiency(['a'], [source('a', 'active')], facts('b'))).toEqual({ kind: 'covered' });
+ });
+
+ it('grades the ids it was handed, never the order saved on the Agent', () => {
+ // The drawer asks about the list the user is CURRENTLY editing. `facts()` carries
+ // a decoy order for exactly this: the Agent comes along for the server facts that
+ // hang off it, and for nothing else.
+ expect(orderSufficiency(['a'], [source('a', 'active')], facts())).toEqual({ kind: 'covered' });
+ });
+});
+
+/** The same Agent-grain facts with the route gate's two inputs made explicit: the
+ * order the server's answer was ABOUT, and per-source membership in the selected
+ * model's chain. An id left out of `membership` has no eligibility row at all —
+ * the payload that never mentions it. */
+const routed = (
+ savedOrder: readonly string[],
+ membership: Record<string, boolean | null>,
+ cannotLaunch: readonly string[] = [],
+): Pick<AgentSupply, 'sources'> => ({
+ sources: {
+ policy: 'custom',
+ order: [...savedOrder],
+ eligibility: Object.entries(membership).map(([id, inChain]) => ({
+ source_id: id,
+ eligible: true,
+ in_current_model_chain: inChain,
+ process_availability_reason: cannotLaunch.includes(id) ? 'native_cli_unavailable' : null,
+ })),
+ },
+});
+
+describe('orderSufficiency — of the sources the selected model can actually reach', () => {
+ it('stops a source that cannot serve THIS turn from answering for it', () => {
+ // The finding. Enabled: a healthy metered key that does not stock the selected
+ // model, and the one source that does — a native CLI this machine cannot launch.
+ // A rollup over 「can any of these serve something」 says 「fine」 about a turn that
+ // has already been decided to fail.
+ expect(
+ orderSufficiency(
+ ['a', 'b'],
+ [source('a', 'active'), source('b', 'active')],
+ routed(['a', 'b'], { a: false, b: true }, ['b']),
+ ),
+ ).toEqual({ kind: 'nothing_runnable' });
+ });
+
+ it('still lets an on-route source answer for it', () => {
+ // The other side of the same gate: dropping the off-route ones may not turn a
+ // working order into a warning.
+ expect(
+ orderSufficiency(
+ ['a', 'b'],
+ [source('a', 'active'), source('b', 'active')],
+ routed(['a', 'b'], { a: false, b: true }),
+ ),
+ ).toEqual({ kind: 'covered' });
+ });
+
+ it('warns when the route is empty because nothing enabled stocks the model', () => {
+ // Not 「everything is down」 — everything here is healthy and launchable, and the
+ // next turn still has no supplier. One verdict, because the warning offers both
+ // remedies and the user has to do one of them either way.
+ expect(
+ orderSufficiency(
+ ['a', 'b'],
+ [source('a', 'active'), source('b', 'active')],
+ routed(['a', 'b'], { a: false, b: false }),
+ ),
+ ).toEqual({ kind: 'nothing_runnable' });
+ });
+
+ it('does not apply the answer to an id the answer was not about', () => {
+ // The false alarm this gate has to not become. `in_current_model_chain` is
+ // computed by walking `config.effective_source_order(backend)` — the very list
+ // the payload reports as `sources.order` — so a source the user has just enabled
+ // in the drawer and not yet saved reads `false` because it was outside that walk,
+ // for a reason about the ORDER and not about the model. Gated on that, the drawer
+ // would say 「下一个回合会失败,再启用一个」 at the exact moment the user enabled
+ // the one that fixes it.
+ expect(
+ orderSufficiency(
+ ['a', 'b'],
+ [source('a', 'active'), source('b', 'active')],
+ routed(['b'], { a: false, b: true }, ['b']),
+ ),
+ ).toEqual({ kind: 'covered' });
+ });
+
+ it('reads a null or absent membership as the silence it is', () => {
+ // `null` is what every row carries while no model is selected: there is no route,
+ // so there is nothing to be off. An absent row is a payload that never spoke.
+ expect(
+ orderSufficiency(
+ ['a', 'b'],
+ [source('a', 'active'), source('b', 'active')],
+ routed(['a', 'b'], { a: null, b: true }, ['b']),
+ ),
+ ).toEqual({ kind: 'covered' });
+ expect(
+ orderSufficiency(
+ ['a', 'b'],
+ [source('a', 'active'), source('b', 'active')],
+ routed(['a', 'b'], { b: true }, ['b']),
+ ),
+ ).toEqual({ kind: 'covered' });
+ });
+
+ it('keeps 「unknown id」 ahead of the route gate', () => {
+ // An id the inventory cannot resolve is still unknown, not broken — even when
+ // everything the gate DID resolve is off the route.
+ expect(
+ orderSufficiency(['a', 'ghost'], [source('a', 'active')], routed(['a', 'ghost'], { a: false })),
+ ).toEqual({ kind: 'indeterminate' });
});
});
@@ -140,6 +306,30 @@ describe('connectOutcome — the two mode-switch toasts', () => {
expect(connectOutcome(hub(['a']), [source('a', 'active')])).toBe('connected');
});
+ it('warns about an order it cannot launch, even though every source reads healthy', () => {
+ // The switch just took, the server has no model to resolve yet, and the only
+ // enabled source is a native CLI this machine cannot run. Health alone would
+ // call this connected.
+ expect(connectOutcome(hub(['a'], null, ['a']), [source('a', 'active')])).toBe('nothingRunnable');
+ });
+
+ it('still defers to the grade the server did give', () => {
+ // `supply_status` is the server's own answer about the resolved model, computed
+ // where this fact came from. Our inventory read does not get to overrule it.
+ expect(connectOutcome(hub(['a'], 'ok', ['a']), [source('a', 'active')])).toBe('connected');
+ });
+
+ it('is never reached by the route gate, because the two states cannot coexist', () => {
+ // The verdict's route gate only bites where a model is selected, and this caller
+ // only consults the verdict where `supply_status` is null — which is the server
+ // saying it had no model to resolve, the same condition that makes
+ // `in_current_model_chain` null for every row. So the narrowing has nothing to
+ // say here, and a payload that somehow carried both would still be answered by
+ // the membership rather than by the grade's absence.
+ const noSelection = { ...hub(['a', 'b']), sources: routed(['a', 'b'], { a: null, b: null }).sources };
+ expect(connectOutcome(noSelection, [source('a', 'active'), source('b', 'active')])).toBe('connected');
+ });
+
it('says 「I did not check」 rather than 「fine」 where the inventory is absent', () => {
// BackendSupplyModeCard holds no source list. Its toast states the mode change,
// which is a fact it owns; it must not upgrade that into a supply claim.
diff --git a/ui/src/components/settings/models/sufficiency.ts b/ui/src/components/settings/models/sufficiency.ts
index 47e212e4f..78541292a 100644
--- a/ui/src/components/settings/models/sufficiency.ts
+++ b/ui/src/components/settings/models/sufficiency.ts
@@ -8,18 +8,24 @@
// review had named two of them. So the remedy is not five guards: it is one function
// that returns a CLOSED verdict, and no caller left holding a length.
//
-// The honesty rule that shapes the union: what today's payload cannot prove is
-// `indeterminate`, never optimistic. Two fields would make more of it provable —
-// `skipped_by` beside `adopted_by` (the eligible-but-skipped complement, which
-// `_adopted_by` filters out server-side) and process availability at backend grain
-// (contracts v4 carries it only on `agent-chain`). Both are server-side and out of
-// this lane. Until they land, the verdicts that depend on them stay indeterminate and
-// the surfaces keyed on them stay quiet — which is the correct behaviour for a
-// confirmation that would otherwise be able to lie. Their arrival is pure wiring:
-// `adoptionVerdict` already takes the complement, and `orderSufficiency` already asks
-// one predicate about each source.
+// The honesty rule that shapes the union: what the payload cannot prove is
+// `indeterminate`, never optimistic. Two server facts were missing when this module
+// was written, and both have since landed — `skipped_by` beside `adopted_by` (the
+// eligible-but-skipped complement, which `_adopted_by` filters out server-side) and
+// `process_availability_reason` on `sources.eligibility` (whether the local machine
+// can launch a source at all, at per-(source, backend) grain). Each is now read by
+// the function that was already shaped to take it: `adoptionVerdict` takes the
+// complement, `orderSufficiency` asks its predicates per source — of the sources
+// the selected model's route can actually reach, which `in_current_model_chain`,
+// arriving alongside, is what let it narrow to.
+//
+// The rule outlives them, because the arrival is what proves it was right: neither
+// function grew a branch to accommodate the field, and a payload that still omits
+// one keeps returning the same weaker verdict it always did. Silence stays
+// `indeterminate` or the weaker claim, never a false alarm and never a guess.
+import { offCurrentModelChain, processAvailabilityOf } from './eligibility';
import { isUnhealthy } from './supply';
-import type { AdoptedBy, AgentBackend, AgentSupply, Source } from './types';
+import type { AdoptedBy, AgentBackend, AgentSupply, SkippedBy, Source } from './types';
/**
* The closed verdict. Not every grain can produce every member — each function
@@ -28,64 +34,89 @@ import type { AdoptedBy, AgentBackend, AgentSupply, Source } from './types';
* `adopted_none` is the empty-membership case at either grain: no backend adopted the
* source, or no source is enabled for the backend. It is deliberately distinct from
* `nothing_runnable`, because the remedy is 「add one」 rather than 「fix one」.
+ *
+ * `skipped_all` is that same 「add one」 remedy with the orders NAMED. It is a separate
+ * member rather than a field on `adopted_none` because only one grain can ever reach
+ * it: `orderSufficiency` has no complement to read.
*/
export type Sufficiency =
| { kind: 'covered' }
| { kind: 'partly_skipped'; backends: AgentBackend[] }
+ | { kind: 'skipped_all'; backends: AgentBackend[] }
| { kind: 'nothing_runnable' }
| { kind: 'adopted_none' }
| { kind: 'indeterminate' };
-/**
- * The eligible-but-skipped complement of `adopted_by`.
- *
- * Typed locally on purpose: `types.ts` mirrors the FROZEN contracts and never runs
- * ahead of them. When the field ships, this type moves there and the parameter below
- * starts being fed — no logic changes, and the tests that already cover the branch
- * stop being the only thing exercising it.
- */
-export type SkippedBy = {
- backend: AgentBackend;
- /** v2's only cause: the backend keeps a `custom` order, which the server never
- * extends. An INELIGIBLE backend is not 「skipped」 — it was never a candidate. */
- reason: 'custom-order-omission';
-};
-
/**
* Did the new source actually reach everyone it should have?
*
- * Returns `adopted_none` | `partly_skipped` | `covered` | `indeterminate`.
+ * Returns `adopted_none` | `skipped_all` | `partly_skipped` | `covered` |
+ * `indeterminate`.
+ *
+ * `adopted_by.length` decides how much of the answer is good news, and NOTHING else:
+ * that array never says who was left out, at any length. So the complement is read on
+ * both sides of the branch. Zero adopters with a non-empty complement is not a corner
+ * case but the normal shape of an install where every eligible backend keeps a
+ * hand-picked order — the exact case the field was added for, and the one where
+ * naming the orders saves the most work. Deciding it from `adopted_by` alone would be
+ * this module's own header defect, an emptiness test standing in for an adequacy one.
*/
export function adoptionVerdict(
adoptedBy: readonly AdoptedBy[] | null | undefined,
skippedBy?: readonly SkippedBy[] | null,
): Sufficiency {
if (!adoptedBy) return { kind: 'indeterminate' };
- // Empty is a closed fact — the server sent the list and nobody is on it.
- if (adoptedBy.length === 0) return { kind: 'adopted_none' };
+ const skipped = skippedBy?.map((s) => s.backend) ?? [];
+ // Empty is a closed fact — the server sent the list and nobody is on it. What it
+ // is NOT is a reason to stop reading: 「nobody took it」 and 「these three orders
+ // left it out」 share one remedy and differ entirely in where to go do it.
+ if (adoptedBy.length === 0) {
+ return skipped.length > 0 ? { kind: 'skipped_all', backends: skipped } : { kind: 'adopted_none' };
+ }
// Non-empty proves someone took it and nothing about who did not.
if (!skippedBy) return { kind: 'indeterminate' };
- if (skippedBy.length === 0) return { kind: 'covered' };
- return { kind: 'partly_skipped', backends: skippedBy.map((s) => s.backend) };
+ return skipped.length === 0 ? { kind: 'covered' } : { kind: 'partly_skipped', backends: skipped };
}
/**
* Can this backend's enabled order serve the next turn?
*
* Returns `adopted_none` | `nothing_runnable` | `covered` | `indeterminate`. Takes the
- * ids rather than the agent so the drawer can ask about the order the user is CURRENTLY
- * editing, which is the order the warning is about.
+ * ids rather than the agent's own order so the drawer can ask about the order the user
+ * is CURRENTLY editing, which is the order the warning is about; the agent comes along
+ * for the server facts that hang off it, never for its saved order.
+ *
+ * Two independent ways to be unable to serve, and the verdict needs BOTH: the
+ * source's own health (`isUnhealthy`) and whether it can be launched here at all
+ * (`processAvailabilityOf`). The second was the documented v4 caveat — a healthy
+ * `native_cli` source this process cannot sign the CLI in with reports itself
+ * perfectly able to serve — and it closed when `process_availability_reason` arrived
+ * on `sources.eligibility` at exactly this grain, per (source, backend). `covered`
+ * now means 「a source can be reached AND launched」; an agent whose payload omits
+ * the field falls back to the old, weaker claim rather than to a false alarm.
+ *
+ * But being able to serve SOMETHING is not being able to serve the next turn, and
+ * a rollup over every enabled source quietly asked the first question. A healthy
+ * key that does not stock the selected model answered 「fine」 for a turn it was
+ * never going to be asked — so with the model's only supplier a native CLI this
+ * process cannot launch, the drawer stayed silent about a turn that fails. Sources
+ * the server puts outside the current model's route are therefore dropped from the
+ * rollup: they cannot serve THIS turn, whatever else is true of them.
*
- * Known v4 caveat: `isUnhealthy` reads the source's own state, and a healthy
- * `native_cli` source can still be unrunnable at chain grain (the CLI process is not
- * installed on this machine). v4 publishes that fact only on `agent-chain`, whose grain
- * is (agent, model). So `covered` here means 「a source reports itself able to serve」,
- * which is the strongest claim this payload supports; the verdict tightens on its own
- * the day availability arrives at backend grain.
+ * `in_current_model_chain` is only ever consulted about ids the server's answer was
+ * ABOUT. The route is built by walking `config.effective_source_order(backend)`
+ * (`resolver.py:252`), the very list the payload reports as `sources.order`, so a
+ * source the user has just enabled in the drawer and not yet saved is outside that
+ * walk and reads `false` for a reason that is about the ORDER and not about the
+ * model. Applied to it, the gate would announce 「下一个回合会失败」 at the exact
+ * moment the user enabled the source that fixes it — telling them to do the thing
+ * they just did. So an id not in the answered-about order keeps its old, ungated
+ * treatment, which is also what a `null` or absent membership gets.
*/
export function orderSufficiency(
orderIds: readonly string[] | null | undefined,
sources: readonly Source[] | null | undefined,
+ agent: Pick<AgentSupply, 'sources'>,
): Sufficiency {
if (!orderIds) return { kind: 'indeterminate' };
if (orderIds.length === 0) return { kind: 'adopted_none' };
@@ -93,9 +124,16 @@ export function orderSufficiency(
const byId = new Map(sources.map((s) => [s.id, s]));
const resolved = orderIds.map((id) => byId.get(id)).filter((s): s is Source => s !== undefined);
- if (resolved.some((s) => !isUnhealthy(s.state))) return { kind: 'covered' };
- // Every id we could resolve is down. If some could not be resolved, the two reads
- // disagree and an unknown source is not a broken one.
+ const answeredAbout = new Set(agent.sources?.order ?? []);
+ const onRoute = resolved.filter((s) => !(answeredAbout.has(s.id) && offCurrentModelChain(agent, s.id)));
+ const servable = (s: Source) => !isUnhealthy(s.state) && processAvailabilityOf(agent, s.id).runnable;
+ if (onRoute.some(servable)) return { kind: 'covered' };
+ // Nothing on the route can serve — either everything left is down, or the route
+ // is empty because nothing enabled stocks the model. Both fail the next turn, and
+ // the warning offers both remedies (「修好下面的某一个,或者再启用一个」).
+ //
+ // If some id could not be resolved, the two reads disagree and an unknown source
+ // is not a broken one.
return resolved.length === orderIds.length ? { kind: 'nothing_runnable' } : { kind: 'indeterminate' };
}
@@ -118,7 +156,7 @@ export function connectOutcome(agent: AgentSupply, sources: readonly Source[] |
// The PATCH echoed something other than hub: the switch did not take.
if (agent.mode !== 'hub') return 'failed';
- const verdict = orderSufficiency(agent.sources?.order, sources);
+ const verdict = orderSufficiency(agent.sources?.order, sources, agent);
// Its own remedy, and it outranks any grade — an empty order has nothing to grade.
if (verdict.kind === 'adopted_none') return 'noSources';
@@ -137,6 +175,10 @@ export function connectOutcome(agent: AgentSupply, sources: readonly Source[] |
// `supply_status: null` means the server had no model to resolve, not that the order
// is fine. It is silence, so the order's own runnability is the only fact left.
+ //
+ // Which is also the one state where the verdict's route gate has nothing to say:
+ // no model selected means no route, and the server sends `in_current_model_chain:
+ // null` for every source. The narrowing above cannot reach this caller.
if (verdict.kind === 'nothing_runnable') return 'nothingRunnable';
return verdict.kind === 'covered' ? 'connected' : 'indeterminate';
}
diff --git a/ui/src/components/settings/models/supply.test.ts b/ui/src/components/settings/models/supply.test.ts
index e54724986..91b678284 100644
--- a/ui/src/components/settings/models/supply.test.ts
+++ b/ui/src/components/settings/models/supply.test.ts
@@ -4,11 +4,15 @@
// otherwise "simplify" back into a boolean.
import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+
import {
attribution,
chainChips,
chainRoles,
hasAttribution,
+ healthyButUnrunnable,
isUnhealthy,
needsAttention,
pageStatus,
@@ -77,6 +81,18 @@ const directAgent = (): AgentSupply =>
model_supply: null,
});
+/** The server's per-(source, backend) verdict that this machine cannot launch the
+ * source. `eligible: true` on purpose — the source MAY serve this backend, which
+ * is what makes the second question a separate one. */
+const cannotLaunch = (...ids: string[]) =>
+ ids.map((id) => ({ source_id: id, eligible: true, process_availability_reason: 'native_cli_unavailable' as const }));
+
+/** The same verdict on a source the selected model does not come from at all.
+ * `in_current_model_chain` is a claim about the ROUTE, built from the eligible
+ * sources carrying the model BEFORE health or runnability narrows them. */
+const cannotLaunchOffRoute = (...ids: string[]) =>
+ cannotLaunch(...ids).map((e) => ({ ...e, in_current_model_chain: false }));
+
const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({
manifest: { name: 'cliproxyapi', version: '1.0.0', source_sha: 'sha', assets: [] },
status: { installed_version: '1.0.0', verified: true, listening: null, health, last_check: null },
@@ -150,6 +166,142 @@ describe('chainChips', () => {
it('draws nothing in Direct mode (AC-7)', () => {
expect(chainChips(directAgent(), sources)).toEqual([]);
});
+
+ // The second reason a position gets stepped over, and the one the source itself
+ // cannot report: its credential, its models and its state all read perfectly
+ // healthy, and the CLI that would serve it is not usable on this machine.
+ it('marks a healthy source this machine cannot launch, without calling it unhealthy', () => {
+ const agent = hubAgent({
+ sources: { policy: 'follow', order: ['src_a', 'src_b'], eligibility: cannotLaunch('src_b') },
+ });
+ const chips = chainChips(agent, [source('src_a', ACTIVE), nativeSource('src_b', ACTIVE)]);
+ expect(chips[1]).toMatchObject({ unhealthy: false, unavailable: true });
+ });
+
+ it('dims it once the resolver has walked past it, exactly like a broken one', () => {
+ const agent = hubAgent({
+ current: { model_id: 'claude-opus-4-6', source_id: 'src_b', channel: 'hub' },
+ sources: { policy: 'follow', order: ['src_a', 'src_b'], eligibility: cannotLaunch('src_a') },
+ });
+ const chips = chainChips(agent, [nativeSource('src_a', ACTIVE), source('src_b', ACTIVE)]);
+ expect(chips.map((c) => c.tone)).toEqual(['skipped', 'current']);
+ });
+
+ // One row, ONE reason. The two are not mutually exclusive server-side, and the
+ // row renders a single dot, so health takes the tie: it is the actionable one,
+ // and its gold dot is named by the source row's own state chip.
+ it('states one reason per row, and health wins the tie', () => {
+ const agent = hubAgent({
+ sources: { policy: 'follow', order: ['src_a', 'src_b'], eligibility: cannotLaunch('src_b') },
+ });
+ const chips = chainChips(agent, [source('src_a', ACTIVE), nativeSource('src_b', DEAD)]);
+ expect(chips[1]).toMatchObject({ unhealthy: true, unavailable: false });
+ });
+
+ it('reads a payload that says nothing as launchable', () => {
+ // An older server omits the optional field entirely. Silence must not draw a
+ // dim chain — every position would look stepped over.
+ const agent = hubAgent({ sources: { policy: 'follow', order: ['src_a', 'src_b'] } });
+ const chips = chainChips(agent, [source('src_a', ACTIVE), nativeSource('src_b', ACTIVE)]);
+ expect(chips.map((c) => c.unavailable)).toEqual([false, false]);
+ });
+
+ // The marker names a CAUSE for the failover, so it may only be spent on a
+ // position the failover was ever going to consider. This one does not carry the
+ // selected model: the resolver walks past it with the CLI signed in and the state
+ // green, and pointing at a remedy that changes nothing about the route is worse
+ // than pointing at nothing.
+ it('does not blame availability for a position the model never came from', () => {
+ const agent = hubAgent({
+ current: { model_id: 'claude-opus-4-6', source_id: 'src_b', channel: 'hub' },
+ sources: { policy: 'follow', order: ['src_a', 'src_b'], eligibility: cannotLaunchOffRoute('src_a') },
+ });
+ const chips = chainChips(agent, [nativeSource('src_a', ACTIVE), source('src_b', ACTIVE)]);
+ expect(chips[0]).toMatchObject({ unavailable: false, unhealthy: false, tone: 'neutral' });
+ });
+
+ it('keeps the marker when the server claims nothing about the route', () => {
+ // `in_current_model_chain` is null with nothing selected and absent from a server
+ // that predates the field. Silence is not exclusion: with no selected model the
+ // order IS the route, so this position really was stepped over for this reason.
+ const agent = hubAgent({
+ selected_model_id: null,
+ sources: {
+ policy: 'follow',
+ order: ['src_a', 'src_b'],
+ eligibility: cannotLaunch('src_b').map((e) => ({ ...e, in_current_model_chain: null })),
+ },
+ });
+ const chips = chainChips(agent, [source('src_a', ACTIVE), nativeSource('src_b', ACTIVE)]);
+ expect(chips[1]).toMatchObject({ unavailable: true });
+ });
+
+ it('still dims an off-route source that is genuinely broken', () => {
+ // The gate is on the availability disjunct only. 「Cannot serve right now」 is
+ // true of the source wherever it sits, and its gold dot is an early warning
+ // about the next failover rather than a reading of this one's route.
+ const agent = hubAgent({
+ current: { model_id: 'claude-opus-4-6', source_id: 'src_b', channel: 'hub' },
+ sources: { policy: 'follow', order: ['src_a', 'src_b'], eligibility: cannotLaunchOffRoute('src_a') },
+ });
+ const chips = chainChips(agent, [nativeSource('src_a', DEAD), source('src_b', ACTIVE)]);
+ expect(chips[0]).toMatchObject({ unhealthy: true, unavailable: false, tone: 'skipped' });
+ });
+});
+
+describe('healthyButUnrunnable', () => {
+ const agentWith = (eligibility: NonNullable<AgentSupply['sources']>['eligibility']) =>
+ hubAgent({ sources: { policy: 'follow', order: ['src_a', 'src_b'], eligibility } });
+
+ it('retracts a healthy row’s promise this machine cannot keep', () => {
+ // 供 … 全系 is a promise, and the source looks fine — nothing else on the row
+ // would tell the user that turning it on gets them nothing here.
+ expect(healthyButUnrunnable(agentWith(cannotLaunch('src_b')), nativeSource('src_b', ACTIVE))).toBe(true);
+ });
+
+ it('leaves the segment to health when the source is not serving', () => {
+ // Two answers compete for one segment of copy. A cooling or broken source is
+ // the one the user can act on, and its state chip has already raised it.
+ const agent = agentWith(cannotLaunch('src_b'));
+ expect(healthyButUnrunnable(agent, nativeSource('src_b', COOLING))).toBe(false);
+ expect(healthyButUnrunnable(agent, nativeSource('src_b', DEAD))).toBe(false);
+ expect(healthyButUnrunnable(agent, nativeSource('src_b', EXHAUSTED))).toBe(false);
+ });
+
+ it('says nothing about a source this machine can launch', () => {
+ // Silence is runnable — the server names only what it has ruled out.
+ expect(healthyButUnrunnable(agentWith([]), nativeSource('src_b', ACTIVE))).toBe(false);
+ expect(healthyButUnrunnable(agentWith(cannotLaunch('src_a')), nativeSource('src_b', ACTIVE))).toBe(false);
+ expect(healthyButUnrunnable(hubAgent({ sources: null }), nativeSource('src_b', ACTIVE))).toBe(false);
+ });
+
+ it('does not read the route’s answer as the model’s', () => {
+ // Deliberately ungated, unlike `unavailable` in `chainChips`: that marker blames
+ // a FAILOVER on a cause. A source row answers 「what would I get by turning this
+ // on」, and `in_current_model_chain` is only an answer about `sources.order` — so
+ // every 未启用 row reads `false` there, and a gate would silence exactly the rows
+ // that need it earliest.
+ expect(healthyButUnrunnable(agentWith(cannotLaunchOffRoute('src_c')), nativeSource('src_c', ACTIVE))).toBe(true);
+ // The server builds `eligibility` over every configured source, not just the
+ // ordered ones, so a row outside the order still carries its own verdict.
+ const offOrder = hubAgent({ sources: { policy: 'follow', order: ['src_a'], eligibility: cannotLaunch('src_c') } });
+ expect(healthyButUnrunnable(offOrder, nativeSource('src_c', ACTIVE))).toBe(true);
+ });
+
+ it('is what BOTH of the order drawer’s source lines ask', () => {
+ // Round 4. The retraction was in the 启用 line only, so a row admitted it one
+ // step after the step it was about: availability is per (source, backend) and
+ // has nothing to do with where the source sits in the order.
+ const drawer = readFileSync(join(__dirname, 'SourceOrderDrawer.tsx'), 'utf8');
+
+ expect([...drawer.matchAll(/healthyButUnrunnable\(agent, source\)/g)].length).toBe(2);
+ // The 未启用 branch REPLACES the line rather than joining it: both 供 … 全系 and
+ // its rewritten form are the promise being retracted, and the line is two
+ // segments wide.
+ expect(drawer).toMatch(/if \(healthyButUnrunnable\(agent, source\)\) return join\(\[identity\(source\), nativeUnavailable\(\)\]\);/);
+ // And nothing reaches around the shared predicate to the raw reader.
+ expect(drawer).not.toMatch(/processAvailabilityOf/);
+ });
});
describe('chainRoles', () => {
@@ -171,6 +323,20 @@ describe('chainRoles', () => {
const { enrolled } = chainRoles([directAgent()], sources);
expect(enrolled.size).toBe(0);
});
+
+ // `skipped` now has a second cause, and this set is shared with the page pill —
+ // so the widening has to be shown to stay inside the surface that asked for it.
+ it('displaces a source the machine cannot launch, and the pill still says nothing', () => {
+ const agent = hubAgent({
+ current: { model_id: 'm', source_id: 'src_b', channel: 'hub' },
+ sources: { policy: 'follow', order: ['src_a', 'src_b'], eligibility: cannotLaunch('src_a') },
+ });
+ const inventory = [nativeSource('src_a', ACTIVE), nativeSource('src_b', ACTIVE)];
+ expect([...chainRoles([agent], inventory).displaced]).toEqual(['src_a']);
+ // `pageStatus` reads `displaced` only through `state.status === 'cooldown'`, and
+ // an unlaunchable source is healthy by construction — the two cannot overlap.
+ expect(pageStatus(inventory, [agent], runtime('ok'))).toEqual({ tone: 'ok', kind: 'ok', hubCount: 1 });
+ });
});
describe('attribution (AC-9)', () => {
diff --git a/ui/src/components/settings/models/supply.ts b/ui/src/components/settings/models/supply.ts
index ab72b28b3..ac78fe07f 100644
--- a/ui/src/components/settings/models/supply.ts
+++ b/ui/src/components/settings/models/supply.ts
@@ -4,6 +4,7 @@
// supply failure is actually about (AC-9), and what the header pill is allowed to
// claim. Rules deserve unit tests, and this repo's vitest setup has no DOM, so
// they are plain functions over the contract types and nothing else.
+import { offCurrentModelChain, processAvailabilityOf } from './eligibility';
import type {
AgentSupply,
ModelSupply,
@@ -61,6 +62,10 @@ export type ChainChip = {
tone: ChainTone;
/** Draws the gold dot: this source cannot serve right now. */
unhealthy: boolean;
+ /** Draws the muted dot: healthy, on the route, and still not launchable here —
+ * this process cannot sign the backend's CLI in with it. Never true at the same
+ * time as `unhealthy`: the row states ONE reason, the one in the way. */
+ unavailable: boolean;
};
/**
@@ -73,6 +78,26 @@ export type ChainChip = {
* is a warning about the next failover, not a record of one, and greying it out
* would claim something that has not happened.
*
+ * A position can be stepped over for a second reason, and the strip has to draw it
+ * or the frame contradicts itself: a `native_cli` source this process cannot sign
+ * the CLI in with is skipped by the resolver while its own state reads `active`, so
+ * without this the chain would show a healthy position 1 and 当前 sitting at 2 with
+ * nothing between them to explain the move. It is ONE more disjunct in the same
+ * 「walked past」 rule, and one more hue on the same dot — never a second dot and
+ * never a second rule, because the question 「why did the resolver move on」 has one
+ * answer per position. Health wins the tie: it is the one the user can act on, and
+ * the source row next door already names it.
+ *
+ * That second disjunct is gated on route membership, and the gate is about what the
+ * marker CLAIMS. 「Not launchable here」 names a CAUSE for the failover, and a
+ * position the server reports as `in_current_model_chain: false` was going to be
+ * walked past with the CLI signed in and the state green — it does not carry the
+ * selected model at all. Marking it would blame the move on a remedy that changes
+ * nothing. Health needs no such gate: 「cannot serve right now」 is true of the
+ * source wherever it sits in whosever order. And the gate is on the Agent row only —
+ * the all-sources drawer keeps the ungated fact, which is the surface the user goes
+ * to in order to act on it.
+ *
* Returns [] in Direct mode: there is no Hub order to draw (AC-7).
*/
export function chainChips(agent: AgentSupply, sources: Source[]): ChainChip[] {
@@ -82,16 +107,41 @@ export function chainChips(agent: AgentSupply, sources: Source[]): ChainChip[] {
return order.map((sourceId, i) => {
const source = sources.find((s) => s.id === sourceId);
const unhealthy = source ? isUnhealthy(source.state) : false;
+ const unavailable =
+ !unhealthy && !offCurrentModelChain(agent, sourceId) && !processAvailabilityOf(agent, sourceId).runnable;
const tone: ChainTone =
sourceId === currentId
? 'current'
- : unhealthy && currentIndex >= 0 && i < currentIndex
+ : (unhealthy || unavailable) && currentIndex >= 0 && i < currentIndex
? 'skipped'
: 'neutral';
- return { sourceId, label: source?.display_name ?? sourceId, position: i + 1, tone, unhealthy };
+ return { sourceId, label: source?.display_name ?? sourceId, position: i + 1, tone, unhealthy, unavailable };
});
}
+/**
+ * Is this row's 供 … 全系 a promise this machine cannot keep — healthy, and still
+ * not something the Agent's process can be launched against?
+ *
+ * A model count is a promise, and the two answers that can retract it compete for
+ * one segment of copy. Health wins, exactly as it does in the strip above: a
+ * cooling or broken source is the one the user can act on, and its state chip has
+ * already raised the question. So this is only about the row that looks fine.
+ *
+ * Ungated by route membership, and deliberately so — unlike `unavailable` in
+ * `chainChips`, where the gate exists because that marker blames a FAILOVER on a
+ * cause and must not name one for a position the resolver was walking past
+ * anyway. A row in a source list is not explaining a move; it is answering 「what
+ * would I get by turning this on」. And a 未启用 source sits outside
+ * `agent.sources.order`, which is the only list `in_current_model_chain` is an
+ * answer about, so a gate there would read an ORDER fact as a MODEL one.
+ *
+ * Per (source, backend), like `processAvailabilityOf` it reads — never a property
+ * of the source row on its own.
+ */
+export const healthyButUnrunnable = (agent: Pick<AgentSupply, 'sources'>, source: Source): boolean =>
+ !isUnhealthy(source.state) && !processAvailabilityOf(agent, source.id).runnable;
+
// ── AC-9: who a supply problem is about ─────────────────────────────────
export type SupplyAttribution = {
/** Named Agents whose effective model cannot be served at all. */
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index 2dbf8fbf3..ba6f01020 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -152,6 +152,12 @@ export type EligibilityReasonKey =
| 'models.eligibility.opencode_api_key_only'
| 'models.eligibility.consent_required';
+/** Why a source that MAY serve this backend still cannot be launched on this
+ * machine. Independent of eligibility and of the source's own health: the
+ * credential is fine, the CLI process is not there. A `hub` source is always
+ * null — nothing local to run. */
+export type ProcessAvailabilityReason = 'native_cli_unavailable';
+
/** Server-computed per (source, backend). The UI renders this and never
* re-derives eligibility from source kind/vendor. */
export type SourceEligibility = {
@@ -159,6 +165,12 @@ export type SourceEligibility = {
eligible: boolean;
/** Required (and non-null) when `eligible` is false; null when it is true. */
reason_key?: EligibilityReasonKey | null;
+ /** Whether this source can serve the CURRENT selection — true/false while
+ * `selected_model_id` is non-null, null when no selection exists. Membership
+ * in the model chain, which is a narrower question than being in `order`. */
+ in_current_model_chain?: boolean | null;
+ /** Non-null when the source is enabled and healthy and still cannot run here. */
+ process_availability_reason?: ProcessAvailabilityReason | null;
};
export type AgentSources = {
@@ -205,6 +217,11 @@ export type AgentSupply = {
/** The model the next turn would ask for. null in direct mode and when no
* selection resolves — an honest null, never a guessed default. */
selected_model_id?: string | null;
+ /** TRUE iff `selected_model_id` originates from the user's explicit
+ * configuration request; FALSE also covers a resolver-picked value. The
+ * server derives it from the stored request BEFORE resolving, which is what
+ * makes it the one health-free way to read the id — see `dryRunChainKey`. */
+ selected_model_explicit?: boolean;
/** What the next turn would actually use (composite pill). null in exactly
* three cases: mode=direct, supply_status=waiting, supply_status=interrupted. */
current?: AgentCurrent | null;
@@ -391,6 +408,24 @@ export type AdoptedBy = {
position: number;
};
+/**
+ * api.md — the eligible-but-skipped complement of `adopted_by`, returned beside it
+ * by both creation routes.
+ *
+ * It exists because absence in `adopted_by` says two different things: a backend
+ * that could never use this source, and one that could and was left out. Only the
+ * second is worth telling the user about, and only the server can tell them apart —
+ * `_skipped_by` filters on `_eligible_for_agent` before reporting a `custom` order
+ * that omits the id.
+ */
+export type SkippedBy = {
+ backend: AgentBackend;
+ /** v2's only cause: the backend keeps a `custom` order, which the server never
+ * extends on its own. An INELIGIBLE backend is not 「skipped」 — it was never a
+ * candidate, and it appears in neither list. */
+ reason: 'custom_order';
+};
+
// ── oauth-flow.schema.json ──────────────────────────────────────────────
export type OAuthFlowState =
| 'starting'
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 6fd962471..d11453cd6 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -667,7 +667,8 @@
"kimi": "Kimi",
"xai": "Grok"
},
- "enabledNoneRunnable": "None of {{backend}}’s enabled sources can serve right now, so the next turn fails with no supply. Fix one below, or enable another."
+ "enabledNoneRunnable": "None of {{backend}}’s enabled sources can serve right now, so the next turn fails with no supply. Fix one below, or enable another.",
+ "nativeUnavailable": "{{backend}} CLI sign-in unavailable here"
},
"billing": {
"monthly": "Monthly",
@@ -852,12 +853,14 @@
"enabled": "Added to the source order of {{list}}",
"entry": "{{name}} (#{{position}})",
"none": "No agent has enabled it yet · add it to an agent's source order for it to be used",
+ "noneSkipped": "No agent has enabled it yet · skipped for {{skipped}} (hand-picked order) — add it there to use it",
"partlySkipped": "Added to the source order of {{list}} · skipped for {{skipped}} (hand-picked order) — add it there to use it"
},
"menus": {
"done": "Done",
"resetAll": "Reset all to default",
"saveFailed": "Couldn't save your changes, please retry",
+ "enrolled": "Added {{sources}} to {{backend}}’s source order so your selection has a supplier",
"mapping": {
"title": "{{backend}} · Model menu",
"subtitle": "Fixed menu: {{backend}} only recognizes these built-in model IDs. Each ID can be redirected to another model — this affects {{backend}} only.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index ac8abd7ea..278de1d4c 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -667,7 +667,8 @@
"kimi": "Kimi",
"xai": "Grok"
},
- "enabledNoneRunnable": "{{backend}} 已启用的来源当前都无法供给,下一个回合会因为没有供给而失败。修好下面的某一个,或者再启用一个。"
+ "enabledNoneRunnable": "{{backend}} 已启用的来源当前都无法供给,下一个回合会因为没有供给而失败。修好下面的某一个,或者再启用一个。",
+ "nativeUnavailable": "本机无法使用 {{backend}} CLI 登录"
},
"billing": {
"monthly": "包月",
@@ -852,12 +853,14 @@
"enabled": "已自动加入 {{list}} 的来源顺序",
"entry": "{{name}}(第 {{position}} 位)",
"none": "还没有 Agent 启用它 · 到各 Agent 的「来源顺序」里加进来才会被使用",
+ "noneSkipped": "还没有 Agent 启用它 · {{skipped}} 使用自定义顺序,未加入——到那里手动加进来才会被使用",
"partlySkipped": "已自动加入 {{list}} 的来源顺序 · {{skipped}} 使用自定义顺序,未加入——到那里手动加进来才会被使用"
},
"menus": {
"done": "完成",
"resetAll": "恢复全部默认",
"saveFailed": "保存失败,请重试",
+ "enrolled": "已自动把「{{sources}}」加入 {{backend}} 的来源顺序,你选的模型才有来源可用",
"mapping": {
"title": "{{backend}} · 模型菜单",
"subtitle": "菜单固定:{{backend}} 只认这些内置 model ID;每个 ID 可改写为其他模型供给,只影响 {{backend}}。",