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 supply repair journeys, dry run and remedy copy (L5) (#1101)

Call Whited833c7414fdb
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index 9d3687208..10ec6fd1d 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -78,6 +78,13 @@ scenarios:
layer: scenario
backend: claude
test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_native_model_hub_reauth_confirms_before_honest_failure
+ - id: AUTH-SETUP-107
+ name: Abandoned native re-auth reuses its pending flow, and cancelling a finished one commits it
+ status: covered
+ kind: negative_path
+ layer: scenario
+ backend: claude
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_native_reauth_reuses_a_pending_flow_and_cancel_commits_a_finished_one
- id: AUTH-SETUP-201
name: Re-entering setup replaces the active flow
status: covered
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index b1b36921d..3f833fac4 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -117,6 +117,87 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
"interrupted",
)
+ async def test_native_reauth_reuses_a_pending_flow_and_cancel_commits_a_finished_one(self):
+ """Scenario: AUTH-SETUP-107
+
+ Pins the three server-side rules the 模型 page's re-auth dialog is built
+ on, in the order a single abandoned journey meets them: a start REUSES a
+ live pending flow, cancelling a pending flow destroys the very flow a
+ successor would have reused, and the same cancel against a FINISHED flow
+ materializes the re-auth instead of cancelling it.
+
+ This is also the closed-loop evidence for the client-side ownership rules
+ in `ui/src/components/settings/models/asyncLifetime.ts` (`releaseFlow`):
+ the dialog only skips a teardown cancel when it no longer owns the source's
+ flow, and never skips the refetch, and both of those are conclusions about
+ the sequence asserted here. The dialog itself cannot be driven from this
+ harness — it is React, and this is an asyncio TestCase with no DOM — so the
+ UI-side interleavings are exercised in `asyncLifetime.test.ts` against the
+ same rules.
+ """
+ state_dir = tempfile.TemporaryDirectory()
+ self.addCleanup(state_dir.cleanup)
+ harness = NativeOAuthScenarioHarness(Path(state_dir.name))
+ source = ModelHubSourceConfig(
+ id="src_native0001",
+ kind="subscription",
+ vendor="anthropic",
+ display_name="Claude subscription",
+ protocol="anthropic",
+ supply_channel="native_cli",
+ billing="monthly",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[ModelHubModelConfig(id="claude-opus-4-6", provenance="discovered")],
+ )
+ harness.store.config.sources.append(source)
+ harness.store.config.refresh_follow_orders()
+ ack = {"acknowledge_irreversible": True}
+
+ # 1. A second start for the same source is handed the SAME flow, and the
+ # irreversible half is not paid twice: one spawn, one marking.
+ first = await harness.service.reauth_source(source.id, ack)
+ flow_id = first["flow"]["flow_id"]
+ self.assertEqual(harness.agent_auth.start_calls, [("claude", True)])
+ self.assertEqual(harness.store.config.sources[0].state.status, "needs_action")
+ self.assertEqual(harness.store.config.sources[0].models, [])
+
+ reused = await harness.service.reauth_source(source.id, ack)
+ self.assertEqual(reused["flow"]["flow_id"], flow_id)
+ self.assertEqual(harness.agent_auth.start_calls, [("claude", True)])
+ # A start answers with the flow ALONE — no repair tail — which is why the
+ # page has to re-read a start that comes back already finished.
+ self.assertEqual(set(reused), {"flow"})
+
+ # 2. Cancelling a still-pending flow destroys it, so the next start has to
+ # open a new one — and pay the irreversible half again.
+ await harness.service.oauth_cancel(flow_id)
+ self.assertEqual(harness.agent_auth.cancelled, [flow_id])
+
+ restarted = await harness.service.reauth_source(source.id, ack)
+ successor_flow_id = restarted["flow"]["flow_id"]
+ self.assertNotEqual(successor_flow_id, flow_id)
+ self.assertEqual(
+ harness.agent_auth.start_calls,
+ [("claude", True), ("claude", True)],
+ )
+ self.assertEqual(harness.store.config.sources[0].state.status, "needs_action")
+ self.assertEqual(harness.store.config.sources[0].models, [])
+
+ # 3. The same call against a FINISHED flow is not a cancel at all: it
+ # materializes the re-auth. Nothing polls the status first, so this call
+ # is the only thing that could have written the row.
+ harness.agent_auth.complete(successor_flow_id)
+ await harness.service.oauth_cancel(successor_flow_id)
+
+ self.assertEqual(harness.agent_auth.cancelled, [flow_id])
+ repaired = harness.store.config.sources[0]
+ self.assertEqual(repaired.state.status, "standby")
+ self.assertIn("claude-opus-4-6", [model.id for model in repaired.models])
+ self.assertEqual(
+ harness.service.get_agent_sources("claude")["supply_status"],
+ "ok",
+ )
+
async def test_codex_failure_scenario_emits_reset_path(self):
"""Scenario: AUTH-SETUP-202"""
harness = AuthSetupScenarioHarness()
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsx
index 23926dcec..3fc6b602c 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx
@@ -17,38 +17,15 @@ import {
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Select } from '@/components/ui/select';
-import { cn } from '@/lib/utils';
import { modelsApi } 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';
type Phase = 'edit' | 'submitting' | 'done' | 'error';
-const FieldLabel: React.FC<{ mono?: boolean; children: React.ReactNode }> = ({ mono, children }) => (
- <label
- className={cn(
- 'text-muted',
- mono
- ? 'font-mono text-[11px] font-medium uppercase tracking-wide'
- : 'text-[12px] font-semibold text-foreground',
- )}
- >
- {children}
- </label>
-);
-
-const IconField: React.FC<{
- icon: React.ComponentType<{ className?: string }>;
- children: React.ReactNode;
-}> = ({ icon: Icon, children }) => (
- <div className="relative">
- <Icon className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted" />
- {children}
- </div>
-);
-
export const AddApiKeyDialog: React.FC<{
open: boolean;
onClose: () => void;
@@ -138,50 +115,59 @@ export const AddApiKeyDialog: React.FC<{
<DialogDescription>{t('settings.models.addKey.subtitle')}</DialogDescription>
</DialogHeader>
- <div className="flex flex-col gap-2">
- <FieldLabel>{t('settings.models.addKey.vendorLabel')}</FieldLabel>
- <Select value={vendor} onChange={(e) => onVendorChange(e.target.value)} className="h-11 text-[14px]">
- {VENDOR_OPTIONS.map((v) => (
- <option key={v.value} value={v.value}>
- {t(v.labelKey)}
- </option>
- ))}
- </Select>
- <p className="text-[12px] leading-relaxed text-muted">{t('settings.models.addKey.vendorHint')}</p>
- </div>
+ <Field label={t('settings.models.addKey.vendorLabel')} hint={t('settings.models.addKey.vendorHint')}>
+ {(id) => (
+ <Select
+ id={id}
+ value={vendor}
+ onChange={(e) => onVendorChange(e.target.value)}
+ className="h-11 text-[14px]"
+ >
+ {VENDOR_OPTIONS.map((v) => (
+ <option key={v.value} value={v.value}>
+ {t(v.labelKey)}
+ </option>
+ ))}
+ </Select>
+ )}
+ </Field>
- <div className="flex flex-col gap-2">
- <FieldLabel mono>{t('settings.models.addKey.keyLabel')}</FieldLabel>
- <IconField icon={KeyRound}>
+ <Field label={t('settings.models.addKey.keyLabel')} mono icon={KeyRound}>
+ {(id) => (
<Input
+ id={id}
type="password"
autoComplete="off"
spellCheck={false}
- placeholder="sk-…"
+ placeholder={t('settings.models.field.apiKeyPlaceholder')}
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
className="h-11 pl-9 font-mono text-[14px]"
disabled={phase === 'submitting' || phase === 'done'}
/>
- </IconField>
- </div>
+ )}
+ </Field>
- <div className="flex flex-col gap-2">
- <FieldLabel mono>{t('settings.models.addKey.baseUrlLabel')}</FieldLabel>
- <IconField icon={Globe}>
+ <Field
+ label={t('settings.models.addKey.baseUrlLabel')}
+ mono
+ icon={Globe}
+ hint={t('settings.models.addKey.baseUrlHint')}
+ >
+ {(id) => (
<Input
+ id={id}
type="text"
autoComplete="off"
spellCheck={false}
- placeholder="https://api.example.com/v1"
+ placeholder={t('settings.models.field.baseUrlPlaceholder')}
value={baseUrl}
onChange={(e) => setBaseUrl(e.target.value)}
className="h-11 pl-9 font-mono text-[14px]"
disabled={phase === 'submitting' || phase === 'done'}
/>
- </IconField>
- <p className="text-[12px] leading-relaxed text-muted">{t('settings.models.addKey.baseUrlHint')}</p>
- </div>
+ )}
+ </Field>
{phase === 'done' && (
<div className="flex flex-col gap-2">
diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsx
index 0f875cfda..5aa1c095d 100644
--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx
+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx
@@ -5,6 +5,14 @@
// / OAuthSubmitRow) so it matches the Backends OAuth panel. State machine
// mirrors BackendOAuthPanel: start → 2s poll → verifying → success, 15-min
// timeout, cancel.
+//
+// It runs the RE-AUTH journey too (`reauth` prop, AC-2/AC-13). api.md gives both
+// intents one flow and one terminal envelope — only the tail beside it differs
+// (`adopted_by` for a create, `recovered`/`interrupted_pairs` for a repair) — so
+// they share this machine rather than getting a second copy of the poll, the
+// deadline, the paste submit and the cancel-on-unmount. A duplicate is precisely
+// how one of the two ends up reading a different half of the envelope, which is
+// the bug `settle` below was written to fix.
import * as React from 'react';
import { CheckCircle2, Sparkles, TriangleAlert } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -17,35 +25,28 @@ import { OAuthDeviceCodeRow, OAuthLinkRow, OAuthSubmitRow } from '../oauth/OAuth
import { AdoptionNote } from './AdoptionNote';
import {
createFlowAuthority,
+ failureLanded,
initialFlowView,
isDone,
+ pollFailureSettles,
+ releaseFlow,
+ startNeedsStatusRead,
+ terminalArrivalMovedRows,
type FlowAuthority,
type FlowView,
} from './asyncLifetime';
import { ExperimentalConsentDialog } from './ExperimentalConsentDialog';
import { SUBSCRIPTION_HUB_EXPERIMENTAL } from './featureFlags';
-import { modelsApi, type OAuthResult } from './modelsApi';
-import { serverText } from './serverCopy';
+import { apiFailure, modelsApi, 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, SupplyChannel } from './types';
+import type { AdoptedBy, Source, SupplyChannel, SupplyGap } from './types';
const POLL_MS = 2000;
const DEADLINE_MS = 16 * 60 * 1000;
-const TERMINAL = ['success', 'failed', 'cancelled'];
-
-// The creation half of a terminal status/submit response fails with its own
-// codes (api.md → POST /sources errors, raised while materializing the Source).
-const CREATION_CODES = ['discovery_failed', 'engine_down', 'migration_item_conflict'];
-
-/** Terminal-response failure code → copy, keeping 「授权没成」 distinct from
- * 「授权成了但来源没建起来」 instead of collapsing both into 连接失败. */
-const errorKeyFor = (code?: string): string =>
- code === 'consent_required'
- ? 'settings.models.oauth.error.consent'
- : code && CREATION_CODES.includes(code)
- ? 'settings.models.oauth.error.finalize'
- : 'settings.models.oauth.error.generic';
const Step: React.FC<{ n: number; label: string; children: React.ReactNode }> = ({ n, label, children }) => (
<div className="flex flex-col gap-2.5 rounded-lg border border-border bg-surface-2/40 px-4 py-3">
@@ -61,9 +62,16 @@ export const OAuthConnectDialog: React.FC<{
open: boolean;
/** 'anthropic' (Claude) | 'openai' (ChatGPT) | any future subscription vendor. */
vendor: string;
+ /**
+ * Present ⇒ this is a RE-AUTH of that existing source, not a new connect. A
+ * SNAPSHOT on purpose: a native re-auth writes 需处理 on the row before the login
+ * even starts, so re-reading the live row would rewrite this dialog's own
+ * subject mid-flow.
+ */
+ reauth?: Source | null;
onClose: () => void;
onConnected: () => void;
-}> = ({ open, vendor, onClose, onConnected }) => {
+}> = ({ open, vendor, reauth = null, onClose, onConnected }) => {
const { t } = useTranslation();
const { showToast } = useToast();
@@ -79,6 +87,14 @@ 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
+ // 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
+ // `repair`'s gap report: that one describes a write that landed, this one
+ // describes the irreversible half of a journey that then broke, and it exists
+ // only on the error the server threw.
+ const [stranded, setStranded] = React.useState<SupplyGap[]>([]);
const [, tick] = React.useReducer((x) => x + 1, 0);
// Set by the flow effect so `submit` lands through the very same owners as a
@@ -87,12 +103,99 @@ export const OAuthConnectDialog: React.FC<{
const flowAuthorityRef = React.useRef<FlowAuthority | null>(null);
const settleRef = React.useRef<((result: OAuthResult) => void) | null>(null);
const successTimer = React.useRef<number | null>(null);
+ // Mirrored for the flow effect, which is built once per attempt and would
+ // otherwise read this from the render that built it — i.e. always `false`.
+ const submittingRef = React.useRef(false);
+ submittingRef.current = submitting;
const onConnectedRef = React.useRef(onConnected);
onConnectedRef.current = onConnected;
const onCloseRef = React.useRef(onClose);
onCloseRef.current = onClose;
const accent = vendor === 'openai' ? 'gold' : 'mint';
+ // One derivation for 「which journey is this」, read by the start call, the
+ // terminal handler and the title alike.
+ const reauthId = reauth?.id ?? null;
+ const isReauth = reauthId !== null;
+ // The same derivation as a value, because the failure copy needs it as one: a
+ // terminal code means 「couldn't create it」 on a connect and 「it's still broken」
+ // on a repair, and `oauthFailureKey` takes the journey rather than guessing.
+ const journey: OAuthJourney = isReauth ? 'reauth' : 'connect';
+
+ /**
+ * One owner for 「the server moved the rows the page behind this dialog draws」,
+ * reached from EVERY path where that can have happened.
+ *
+ * The question at each call site is deliberately that one — not 「did it fail?」,
+ * and not 「is this a reauth?」. A reauth makes the difference impossible to miss,
+ * because its row is rewritten as the flow starts: `mark_native_irreversible_start`
+ * writes 需要处理 across that vendor's native sources and rolls it back only when
+ * the login fails to SPAWN, and `_materialize_reauth` clears the source and marks
+ * it unavailable before answering `discovery_failed`. But a create writes too, at
+ * the other end — `_materialize_completed_oauth` persists the new source, and
+ * `oauth_cancel` routes a `success` flow into it, so the call that was meant to
+ * throw the journey away is the one that commits it. Scoping the refetch to the
+ * journey is what left that page showing no source over a credential the server
+ * had already taken.
+ *
+ * A refetch of rows that did not move is inert, which is what makes it the wrong
+ * thing to be clever about. The pairs are not: they travel on the error for the
+ * same reason `adopted_by` travels with a creation — no later read of `/agents`
+ * reproduces them — and they name who the REAUTH's irreversible half left
+ * without a source. That half is what a create does not have, so that is the one
+ * part still asking about the journey.
+ *
+ * Which is why `pairsSpeak` exists beside them rather than being read off the
+ * failure: passing no pairs still WRITES an empty list, so 「this arrival has
+ * none」 and 「this arrival may not answer that question」 need saying separately.
+ * It defaults to the SILENT answer, because the two answers are not equally
+ * wrong. This component outlives the attempt — both hosts leave it mounted and
+ * toggle `open` (`RepairJourney.tsx`, `SettingsModelsPage.tsx`), so `stranded`
+ * survives a close, and a request left in flight by attempt A can land after
+ * attempt B has already put ITS gap report on screen. A site that forgets to
+ * speak costs nothing: the refetch it came for still runs. A site that forgets
+ * to stay silent erases the one part of B's report no later read reproduces.
+ *
+ * So exactly one arrival opts IN — the terminal settle, which is the account of
+ * record for the view it just settled and has no pairs to show, because
+ * `interrupted_pairs` rides an error envelope and a terminal RESPONSE has none.
+ * The three `catch` sites hand over `failureLanded(step.action)`, since an
+ * arrival the authority ignored is not the failure whose sentence these pairs
+ * are rendered under. Everything reached after the attempt is over — the
+ * resolved-after-close path, the released flow's re-read — says nothing, and
+ * says it by default.
+ */
+ const rowsBehindAreStale = (failure?: ReturnType<typeof apiFailure>, pairsSpeak = false) => {
+ if (isReauth && pairsSpeak) setStranded(failure?.interrupted ?? []);
+ onConnectedRef.current();
+ };
+
+ /**
+ * A request of one attempt that resolved after that attempt stopped being the one
+ * on screen — because the dialog closed, or because a later attempt replaced it.
+ * Those are one fact here: whatever this arrival wrote, it wrote it to rows
+ * somebody else is now reading.
+ *
+ * The close path re-read too — but it did so while this request was still in
+ * flight, so that read can predate the request's own write, and every request
+ * here has one: a status poll MATERIALIZES a just-succeeded flow, a paste submit
+ * does the same and can write BEFORE it rejects (`_materialize_reauth` saves the
+ * source as 需处理 with its models stripped and only then raises
+ * `discovery_failed`), a start that rejects can have kept
+ * `mark_native_irreversible_start`'s marking, and `oauth_cancel` itself routes a
+ * terminal flow into materialization. This is the last thing that corrects the
+ * rows, which is why it lives out here where every one of those exits can reach
+ * it — a request that outlived its attempt is one rule, not one per call site.
+ *
+ * It says nothing about the pairs, and takes the default to say so. Not because
+ * it has none to hand over — it never does — but because the empty list is
+ * itself a claim, and this arrival has no standing to make it: the dialog that
+ * would have shown ITS pairs is gone, while the one on screen may already
+ * belong to a later attempt. Closing a re-login and starting another on a
+ * different source is one click away, and this request can land after that
+ * one has failed.
+ */
+ const resolvedAfterAttempt = () => rowsBehindAreStale();
const copy = (text: string | null | undefined) => (e: React.MouseEvent) => {
e.preventDefault();
@@ -117,12 +220,23 @@ export const OAuthConnectDialog: React.FC<{
let cancelled = false;
let pollTimer: number | null = null;
let deadline = Date.now() + DEADLINE_MS;
+ // The flow id this journey opened, kept beside the view instead of read back out
+ // of it. Cleanup needs an id to cancel with, and the VIEW is exactly what
+ // `startNeedsStatusRead` keeps a terminal start out of — on purpose. Taking the
+ // id from there let 「what may be SHOWN」 decide 「what may be CANCELLED」, and the
+ // one arrival whose cancel IS the materialization was the one it left with
+ // neither.
+ let openedFlowId: string | null = null;
const stop = () => {
if (pollTimer !== null) window.clearTimeout(pollTimer);
pollTimer = null;
};
- const authority = createFlowAuthority(setView);
+ // The subject travels with the authority because `flowLetGo` asks about the
+ // identity of whichever journey holds the ref, and the server's handover is
+ // keyed by source: a successor re-authing a DIFFERENT row cannot be handed
+ // this flow, so it may not stand in for one that could.
+ const authority = createFlowAuthority(setView, reauthId);
flowAuthorityRef.current = authority;
const transition = authority.transition;
@@ -136,14 +250,33 @@ export const OAuthConnectDialog: React.FC<{
const settle = (result: OAuthResult): boolean => {
const { created } = result;
const step = transition({ kind: 'response', flow: result.flow });
- if (step.action === 'succeed') {
+ if (step.action === 'succeed' && isReauth) {
+ // A reauth terminates on the SAME source it started from; what the server
+ // adds is whether that cleared the blocker and what is still stranded.
+ const verdict = result.repaired ? repairOutcome(result.repaired) : null;
+ setRepair(verdict);
+ // Line AND tone from the verdict's own owner (`REPAIR_TOAST`), because
+ // choosing them separately here is what put a green 「连接成功」 over a gap
+ // report. An absent tail is the only arrival with no verdict to speak for
+ // it, and 「连接成功」 is what it has always said.
+ const toast = verdict ? REPAIR_TOAST[verdict.kind] : null;
+ showToast(
+ 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.
+ if (!verdict || repairSettles(verdict))
+ successTimer.current = window.setTimeout(() => onCloseRef.current(), 1400);
+ } else if (step.action === 'succeed') {
// The Source already exists. The status/submit call that first reports
// 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);
showToast(t('settings.models.oauth.status.success') as string, 'success');
- onConnectedRef.current();
// 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
@@ -152,6 +285,18 @@ export const OAuthConnectDialog: React.FC<{
if (adoptionVerdict(created?.adopted_by ?? null).kind === 'covered')
successTimer.current = window.setTimeout(() => onCloseRef.current(), 1400);
}
+ // Both branches above end with the same fact about the page behind them, and
+ // so does the failure neither of them handles: `terminalArrivalMovedRows`
+ // says which arrivals moved the rows, in one place, for all of them. A
+ // `failed` hub reauth has already been persisted as 需处理 with its models
+ // stripped by the time this reads it — the two branches asked 「did it
+ // succeed?」, and that is the one terminal the answer left behind.
+ // The `true` is the one opt-in to speaking for the pairs, and it is this
+ // arrival's to make: it just settled the view they render under, and it has
+ // none — `interrupted_pairs` rides an error envelope, so a terminal RESPONSE
+ // that says `failed` carries no list. Clearing them here is how a stale
+ // report from an earlier arrival stops outliving the sentence it belonged to.
+ if (terminalArrivalMovedRows(step.action)) rowsBehindAreStale(undefined, true);
// A paste submit can terminate the flow while a poll timer is still armed;
// the guard above already makes that poll harmless, but there is no reason
// to let it fire.
@@ -161,22 +306,51 @@ export const OAuthConnectDialog: React.FC<{
settleRef.current = settle;
const poll = async (flowId: string) => {
+ // Nothing has been requested yet on this tick, so there is nothing that
+ // could have written — unlike the two exits below.
if (cancelled) return;
const overdue = transition({ kind: 'tick', overdue: Date.now() > deadline });
if (isDone(overdue.action)) return;
try {
const result = await modelsApi.getOAuthStatus(flowId);
- if (cancelled) return;
+ if (cancelled) {
+ resolvedAfterAttempt();
+ return;
+ }
if (settle(result)) return;
pollTimer = window.setTimeout(() => void poll(flowId), POLL_MS);
} catch (err) {
- if (cancelled) return;
+ if (cancelled) {
+ resolvedAfterAttempt();
+ return;
+ }
// A poll that lands on a just-succeeded flow is also the call that
- // materializes the Source, so it can fail for creation reasons
- // (consent_required / discovery_failed / engine_down): the vendor said
- // yes and the Source still doesn't exist. Naming that separately is the
- // difference between 「重试授权」 and 「授权成功但没能建立来源」.
- transition({ kind: 'error', errorKey: errorKeyFor((err as { code?: string } | null)?.code) });
+ // materializes the outcome, so it can fail for reasons that have nothing
+ // to do with the authorization (consent_required / discovery_failed):
+ // the vendor said yes and what came after it broke. Naming that
+ // separately is the difference between 「重试授权」 and 「授权成功,后面
+ // 没成」 — and WHICH object it broke is the journey's to say.
+ //
+ // Which phase a code belongs to is `oauthFailureKey`'s to decide, not
+ // this site's: the SAME poll can fail before authorization completes,
+ // and the codes that only exist after it are the only ones that may
+ // claim completion. `engine_down` is not one of them.
+ const failure = apiFailure(err);
+ // Two reasons a failed READ may not speak for the journey, and
+ // `pollFailureSettles` holds both: the user's own submit is the writer of
+ // record beside it, and a failure the ROUTE never named is not an answer
+ // about the flow at all — that same read is what materializes a
+ // just-succeeded one. Keep reading instead of stopping; the deadline check
+ // at the top of each poll bounds either.
+ if (!pollFailureSettles(submittingRef.current, failure?.serverNamed ?? false)) {
+ pollTimer = window.setTimeout(() => void poll(flowId), POLL_MS);
+ return;
+ }
+ // The authority goes first because its answer is what decides whether these
+ // pairs are the ones on screen — see `failureLanded`. The refetch below is
+ // owed whatever it answers.
+ const step = transition({ kind: 'error', errorKey: oauthFailureKey(failure?.code, journey) });
+ rowsBehindAreStale(failure, failureLanded(step.action));
}
};
@@ -186,26 +360,95 @@ export const OAuthConnectDialog: React.FC<{
setCode('');
setSubmitting(false);
setAdoptedBy(null);
+ setRepair(null);
+ setStranded([]);
void (async () => {
try {
- // A hub-held subscription connect (channel === 'hub' only when the user
- // has confirmed the experimental consent below) must carry consent, or
- // the server returns consent_required.
- const started = await modelsApi.startOAuth(vendor, channel, channel === 'hub');
- if (cancelled) return;
+ // Two ways in, one flow out. The reauth route opens the flow ON the
+ // existing source and acknowledges the irreversibility server-side (the
+ // page has already asked); a create opens a fresh one, and a hub-held
+ // connect (channel === 'hub' only after the experimental consent below)
+ // must carry consent or the server returns consent_required.
+ const started = reauthId
+ ? await modelsApi.reauthSource(reauthId)
+ : await modelsApi.startOAuth(vendor, channel, channel === 'hub');
+ if (cancelled) {
+ // The dialog closed while this request was in flight, so the cleanup
+ // below found no flow to cancel — the flow id exists nowhere but here.
+ // Dropping it would leave a live login running against a source whose
+ // old sign-in the server has ALREADY invalidated. Hand it back where it
+ // is known instead.
+ //
+ // Through `releaseFlow`, which decides whether this journey may still
+ // cancel: by the time we resume, our own cleanup has already released
+ // the ref, so a replacement dialog may own the source's flow — and on a
+ // reauth FOR THE SAME ROW it would own THIS one, since `POST …/reauth`
+ // hands such a successor the live pending flow. `oauth_start` never
+ // does: it mints a fresh pending source id per call, so a create's flow
+ // has no successor to protect and the released ref means nobody is
+ // coming for it. Which is the difference `reusable` carries, because
+ // ownership alone cannot: the two are indistinguishable at this line.
+ // Whether the successor is the right ROW is the authority's subject to
+ // say — see `flowLetGo`. The refetch happens either way, and only after
+ // the call settles.
+ await releaseFlow(authority, flowAuthorityRef.current, {
+ cancel: () => modelsApi.cancelOAuth(started.flow_id),
+ reusable: isReauth,
+ // The close path refetches too, but while this request is still in
+ // flight: that read can return the row as it was before
+ // `mark_native_irreversible_start` committed, and nothing afterwards
+ // would correct it. The abandoned journey is the one case where the
+ // user is no longer looking at a dialog that could tell them — the
+ // same reason, and the same owner, as every other exit of a request
+ // that outlived its dialog.
+ reread: resolvedAfterAttempt,
+ });
+ return;
+ }
+ // A reused pending flow can arrive already finished — in ANY terminal
+ // state. Read its status instead of latching it (`startNeedsStatusRead`),
+ // so the terminal lands through `settle`: `oauth_start` does not
+ // materialize, and the status route is where a success grows its repair
+ // tail and an unsuccessful hub reauth gets failed closed.
+ // Cleanup can only cancel a flow it can NAME, and from this line it can: a
+ // close landing during the status read below now finds an id where it used
+ // to find a null. Earlier than this the abandoned-start branch above is the
+ // owner, because cleanup has already run and already answered.
+ openedFlowId = started.flow_id;
+ if (startNeedsStatusRead(started)) {
+ await poll(started.flow_id);
+ return;
+ }
transition({ kind: 'response', flow: started });
if (started.expires_at) deadline = new Date(started.expires_at).getTime() + 60_000;
pollTimer = window.setTimeout(() => void poll(started.flow_id), POLL_MS);
} catch (err) {
- if (cancelled) return;
- const code = (err as { code?: string } | null)?.code;
- transition({
+ const failure = apiFailure(err);
+ // A reauth that fails to START can still have written the row: the
+ // irreversible marking is rolled back only for a login that fails to
+ // spawn, not for the flow-binding failures after it. Which is why this
+ // rejection re-reads on BOTH sides of the guard — the abandoned case
+ // through the one owner for it, since the close path's own read may have
+ // been issued before this write landed.
+ if (cancelled) {
+ resolvedAfterAttempt();
+ return;
+ }
+ const code = failure?.code;
+ // Nothing can have settled this view yet — the reset above is the last
+ // thing that touched it, and both other arrivals need the flow this call
+ // failed to produce. It asks anyway, because 「may these pairs speak?」 is
+ // one rule for every arrival that carries them, and a site that answers it
+ // by being sure of its position is a site that stops being right when the
+ // position moves.
+ const step = transition({
kind: 'error',
errorKey:
code === 'consent_required'
? 'settings.models.oauth.error.consent'
: 'settings.models.oauth.error.start',
});
+ rowsBehindAreStale(failure, failureLanded(step.action));
}
})();
@@ -214,12 +457,38 @@ export const OAuthConnectDialog: React.FC<{
stop();
settleRef.current = null;
if (successTimer.current !== null) window.clearTimeout(successTimer.current);
- const cur = authority.current().flow;
transition({ kind: 'reset' });
- if (flowAuthorityRef.current === authority) flowAuthorityRef.current = null;
- if (cur && !TERMINAL.includes(cur.state)) modelsApi.cancelOAuth(cur.flow_id).catch(() => {});
+ // Read ownership BEFORE releasing it. React runs this cleanup ahead of the
+ // next effect body, so at this instant the ref is still ours whenever it is
+ // this dialog re-running — which is why the same `releaseFlow` call answers
+ // differently here than on the abandoned-start path above: that one only
+ // gets to ask after this line has already run.
+ const owner = flowAuthorityRef.current;
+ if (owner === authority) flowAuthorityRef.current = null;
+ // A cleanup cannot await, but the refetch inside `releaseFlow` still has to
+ // wait for the cancel: this call can BE the write (`oauth_cancel` on a
+ // terminal flow materializes it). Which is also why the id comes from the
+ // REQUEST and not from the landed view. The view was the wrong place twice
+ // over: a poll in flight can terminalize it between the read and the cancel
+ // landing, so nothing may branch on it — and a start that came back already
+ // terminal is never landed there at all, by design, so for that one the view
+ // had no id to give. `cancel: null` then read as 「there is nothing to
+ // cancel」 when it meant 「the view was not told」, and the flow the user
+ // closed stayed un-materialized: still `not completed`, which is the only
+ // thing `pending_reauth` filters on, so the next reauth of that same source
+ // is handed the login the close was abandoning and commits it.
+ // The re-read speaks for the rows and not for the pairs, by the default: it
+ // is the latest-landing arrival in the file, because it awaits the cancel
+ // first, and by then the attempt it belongs to is not merely settled but
+ // GONE. Whatever gap report is on screen when it returns is somebody else's.
+ const opened = openedFlowId;
+ void releaseFlow(authority, owner, {
+ cancel: opened ? () => modelsApi.cancelOAuth(opened) : null,
+ reusable: isReauth,
+ reread: () => rowsBehindAreStale(),
+ });
};
- }, [open, vendor, channel, t, showToast]);
+ }, [open, vendor, channel, reauthId, t, showToast]);
// 1-second ticker so the paste-flow countdown updates.
React.useEffect(() => {
@@ -245,15 +514,44 @@ export const OAuthConnectDialog: React.FC<{
setSubmitting(true);
try {
const result = await modelsApi.submitOAuth(cur.flow_id, code.trim());
- // Drop the response if the dialog closed or a new flow started meanwhile.
- if (!isCurrent()) return;
+ // Drop the response if the dialog closed or a new flow started meanwhile —
+ // the response, not the re-read. This call is the write of record: it went
+ // through `_materialize_completed_oauth` before answering, so by the time
+ // there is no dialog left to update, the rows behind the one on screen have
+ // already moved. The close path re-read while this was still in flight.
+ if (!isCurrent()) {
+ resolvedAfterAttempt();
+ return;
+ }
// Submit can terminate the flow outright (the contract gives status and
// submit the same terminal shape), so it goes through the same handler
// rather than storing the flow and waiting for a poll to notice.
settleRef.current?.(result);
} catch (err) {
- if (!isCurrent()) return;
- authority.transition({ kind: 'error', errorKey: errorKeyFor((err as { code?: string } | null)?.code) });
+ // Same fact as the success above, through the same owner: a rejection is not
+ // evidence that nothing was written. `_materialize_reauth` saves the source as
+ // 需处理 with its models stripped and only THEN raises `discovery_failed`, so
+ // an arrival with no dialog left to update still has rows to correct — and it
+ // is the only thing that can, the close path having read while it was in
+ // flight. Silent about the pairs by the default, because the report on screen
+ // belongs to whichever attempt replaced this one.
+ if (!isCurrent()) {
+ resolvedAfterAttempt();
+ return;
+ }
+ // Submit reaches the same materialization as the poll, so it can fail the
+ // same way — including after the credential change has committed.
+ //
+ // `isCurrent()` is not enough on its own to make this arrival the failure of
+ // record: a terminal poll settles the VIEW without touching the authority or
+ // the flow id, so a submit rejecting afterwards is still current and still
+ // ignored. `failureLanded` is the part that knows.
+ const failure = apiFailure(err);
+ const step = authority.transition({
+ kind: 'error',
+ errorKey: oauthFailureKey(failure?.code, journey),
+ });
+ rowsBehindAreStale(failure, failureLanded(step.action));
} finally {
if (isCurrent()) setSubmitting(false);
}
@@ -296,22 +594,61 @@ export const OAuthConnectDialog: React.FC<{
<span className={cn('grid size-8 shrink-0 place-items-center rounded-lg', ACCENT_TILE[accent])}>
<Sparkles className={cn('size-4', ACCENT_ICON[accent])} />
</span>
- {t(`settings.models.oauth.title.${vendor}`, {
- defaultValue: t('settings.models.oauth.title.generic') as string,
- })}
+ {isReauth
+ ? t('settings.models.oauth.title.reauth', { name: reauth?.display_name ?? '' })
+ : t(`settings.models.oauth.title.${vendor}`, {
+ defaultValue: t('settings.models.oauth.title.generic') as string,
+ })}
</DialogTitle>
</DialogHeader>
{failed && (
- <div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/[0.08] px-4 py-3 text-[13px] text-destructive">
- <TriangleAlert className="mt-0.5 size-4 shrink-0" />
- {/* errorKey may be the flow's own runtime-declared `error_key`, so
- an unknown one degrades to 连接失败 rather than rendering itself. */}
- <span>{serverText(t, errorKey, 'settings.models.oauth.error.generic')}</span>
+ <div className="flex flex-col gap-2">
+ <div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/[0.08] px-4 py-3 text-[13px] text-destructive">
+ <TriangleAlert className="mt-0.5 size-4 shrink-0" />
+ {/* errorKey may be the flow's own runtime-declared `error_key`, so
+ an unknown one degrades to 连接失败 rather than rendering itself. */}
+ <span>{serverText(t, errorKey, 'settings.models.oauth.error.generic')}</span>
+ </div>
+ {/* Past tense (`gapsDone`), because this is not a confirm: the
+ credential change these pairs are the cost of has already
+ happened. Self-hides when the failure stranded nobody. */}
+ <SupplyGapNote gaps={stranded} title={t('settings.models.repair.gapsDone') as string} />
</div>
)}
- {success ? (
+ {success && isReauth ? (
+ // A repair reports on the source it repaired, not on a new connection:
+ // 「已恢复可用」 when the login cleared the blocker, 「已更新」 when there
+ // was nothing to clear, 「仍然不可用」 when the flow finished and the
+ // source came back stopped anyway, and the stranded pairs when
+ // something is still without a source. Only the last stays on screen.
+ repair?.kind === 'gaps' ? (
+ <div className="flex flex-col gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-3.5 py-3">
+ <span className="text-[12.5px] font-semibold leading-relaxed text-gold">
+ {t('settings.models.repair.gapsDone')}
+ </span>
+ <SupplyGapNote gaps={repair.gaps} />
+ </div>
+ ) : repair?.kind === 'unresolved' ? (
+ // Gold, not destructive, and not a green check: nothing failed —
+ // the login completed and the source is still stopped (a native CLI
+ // that reports itself signed out lands here). A 「已恢复可用」 over
+ // that is the dead end §4.5 forbids; the row keeps its remedy and
+ // this line is why it is still there.
+ <div className="flex items-center gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-4 py-3 text-[13px] font-medium text-gold">
+ <TriangleAlert className="size-4 shrink-0" />
+ {t('settings.models.repair.unresolved')}
+ </div>
+ ) : (
+ <div className="flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium text-mint">
+ <CheckCircle2 className="size-4 shrink-0" />
+ {repair
+ ? t(REPAIR_LINE_KEY[repair.kind])
+ : t('settings.models.oauth.connected')}
+ </div>
+ )
+ ) : success ? (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium text-mint">
<CheckCircle2 className="size-4 shrink-0" />
@@ -366,7 +703,11 @@ export const OAuthConnectDialog: React.FC<{
)}
</Step>
- {SUBSCRIPTION_HUB_EXPERIMENTAL && (
+ {/* Withheld on a re-auth: where a subscription is HELD is a
+ property of the existing source, and this flow is signing back
+ into it — offering to move it here would be a different
+ operation wearing this one's clothes. */}
+ {SUBSCRIPTION_HUB_EXPERIMENTAL && !isReauth && (
<button
type="button"
onClick={() => (channel === 'hub' ? setChannel('native_cli') : setConsentOpen(true))}
diff --git a/ui/src/components/settings/models/RepairJourney.tsx b/ui/src/components/settings/models/RepairJourney.tsx
new file mode 100644
index 000000000..3acb8fa13
--- /dev/null
+++ b/ui/src/components/settings/models/RepairJourney.tsx
@@ -0,0 +1,96 @@
+// The page-level host for the two repairs that need more than a menu click: a
+// native/hub subscription re-login and an API-key replacement.
+//
+// Why the page hosts them rather than the row: both open a MODAL over the whole
+// page, and a modal owned by a list item dies when the list re-renders under it —
+// which is exactly what happens here, because a repair's first act is to change
+// the row that started it (`mark_native_irreversible_start` writes 需处理 before
+// the login page even loads).
+//
+// That is also why `target.source` is a SNAPSHOT, never a live lookup: the dialog
+// must keep naming the source the user clicked, with the display name it had, for
+// the whole journey. The page holds the object it was handed; it does not re-find
+// it in the refreshed list.
+//
+// The re-auth confirm is UNCONDITIONAL (AC-13): asked before anything is sent,
+// every time, with no remember-my-choice and no skip for a source that is already
+// broken. Both channels can lose the source to this journey — a native login pays
+// at 「开始」 and a hub login pays if the sign-in fails — so both are asked.
+//
+// What they are NOT asked is the same sentence. `reauthCost` (repair.ts) owns that
+// split, because a warning that is false on the channel reading it teaches the
+// user to click past the one that is true.
+import * as React from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { ConfirmDialog } from '@/components/ui/confirm-dialog';
+import { OAuthConnectDialog } from './OAuthConnectDialog';
+import { reauthBodyKey } from './repair';
+import { ReplaceKeyDialog } from './ReplaceKeyDialog';
+import type { RaisedRepair } from './SourceRowMenu';
+import type { Source } from './types';
+
+export type RepairTarget = { source: Source; kind: RaisedRepair };
+
+export const RepairJourney: React.FC<{
+ /** The row + remedy the user picked. A snapshot — see the note above. Null closes everything. */
+ target: RepairTarget | null;
+ onClose: () => void;
+ /** Something committed server-side: re-fetch sources + agents. */
+ onChanged: () => void;
+}> = ({ target, onClose, onChanged }) => {
+ const { t } = useTranslation();
+ // The confirm and the flow are two dialogs over one target, so which of them is
+ // showing is this component's only state.
+ const [acknowledged, setAcknowledged] = React.useState(false);
+
+ const reauthTarget = target?.kind === 'reauth' ? target.source : null;
+ const replaceTarget = target?.kind === 'replace_key' ? target.source : null;
+
+ // A new target always starts at the question again.
+ React.useEffect(() => {
+ setAcknowledged(false);
+ }, [target?.source.id, target?.kind]);
+
+ const closeAll = () => {
+ setAcknowledged(false);
+ onClose();
+ };
+
+ return (
+ <>
+ <ConfirmDialog
+ open={reauthTarget !== null && !acknowledged}
+ onOpenChange={(v) => !v && closeAll()}
+ title={t('settings.models.repair.reauthTitle', { name: reauthTarget?.display_name ?? '' })}
+ // The question is unconditional; its BODY is not the same sentence on both
+ // channels, and `reauthCost` owns which one is true (a native login is
+ // irreversible at 「开始」, a hub login only costs the source if it fails).
+ description={reauthTarget ? t(reauthBodyKey(reauthTarget)) : ''}
+ confirmLabel={t('settings.models.repair.reauthConfirm') as string}
+ onConfirm={() => setAcknowledged(true)}
+ />
+
+ <OAuthConnectDialog
+ open={reauthTarget !== null && acknowledged}
+ // The source's own vendor: a re-login goes back to the account it has, and
+ // the flow's presentation comes from the runtime either way.
+ vendor={reauthTarget?.vendor ?? 'anthropic'}
+ reauth={reauthTarget}
+ // Refresh on the way out WHATEVER happened: the reauth route has already
+ // written 需处理 and cleared the discovered models by the time this dialog
+ // is on screen, so a cancelled or failed login leaves the page stale in a
+ // way the user needs to see.
+ onClose={() => {
+ onChanged();
+ closeAll();
+ }}
+ onConnected={onChanged}
+ />
+
+ <ReplaceKeyDialog source={replaceTarget} onClose={closeAll} onReplaced={onChanged} />
+ </>
+ );
+};
+
+export default RepairJourney;
diff --git a/ui/src/components/settings/models/ReplaceKeyDialog.tsx b/ui/src/components/settings/models/ReplaceKeyDialog.tsx
new file mode 100644
index 000000000..e8065f5d8
--- /dev/null
+++ b/ui/src/components/settings/models/ReplaceKeyDialog.tsx
@@ -0,0 +1,220 @@
+// 更换 API Key — the credential-replacement journey (api.md 「Credential
+// replacement and reauth」, AC-3).
+//
+// Three things make it more than a form:
+//
+// 1. The write is ATOMIC and re-discovers on commit, landing the source on
+// `standby` exactly like the recovery test does. So the dialog never claims
+// the source is 使用中 afterwards — it reports what the server reported.
+// 2. The supply guard can REFUSE it. An elective replacement is evaluated against
+// the discovered replacement set before the write, so 「the new key can't serve
+// what the old one did」 arrives as `source_last_supplier` with the stranded
+// pairs named. That escalates in place: same typed key, one more confirm, then
+// `force: true`. A dialog stacked on a dialog would ask the user to re-read
+// the same field.
+// 3. A SUCCESSFUL replacement can still strand something — the server refuses
+// only an elective write, so a recovering one commits and reports
+// `interrupted_pairs` anyway. That report holds the dialog open.
+import * as React from 'react';
+import { CheckCircle2, KeyRound, TriangleAlert } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+import { apiFailure, modelsApi } from './modelsApi';
+import { Field } from './dialogFields';
+import { mayHaveWritten, REPAIR_LINE_KEY, repairOutcome, repairSettles, type RepairOutcome } from './repair';
+import { SupplyGapNote } from './SupplyGapNote';
+import type { Source, SupplyGap } from './types';
+
+type Phase = 'edit' | 'confirm' | 'submitting' | 'done' | 'error';
+
+export const ReplaceKeyDialog: React.FC<{
+ /** The row that opened this. Null closes it. */
+ source: Source | null;
+ onClose: () => void;
+ /** A commit happened — re-fetch sources + agents. */
+ onReplaced: () => void;
+}> = ({ source, onClose, onReplaced }) => {
+ const { t } = useTranslation();
+ const open = source !== null;
+ const [key, setKey] = React.useState('');
+ const [phase, setPhase] = React.useState<Phase>('edit');
+ const [gaps, setGaps] = React.useState<SupplyGap[]>([]);
+ const [outcome, setOutcome] = React.useState<RepairOutcome | null>(null);
+ const closeTimer = React.useRef<number | null>(null);
+ // Same guard as AddApiKeyDialog's: a commit resolving after the dialog closed or
+ // reopened on another row must not write its result into the new state.
+ const submitSeq = React.useRef(0);
+
+ React.useEffect(() => {
+ submitSeq.current += 1;
+ if (open) {
+ setKey('');
+ setPhase('edit');
+ setGaps([]);
+ setOutcome(null);
+ }
+ return () => {
+ if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);
+ };
+ }, [open, source?.id]);
+
+ const submit = async (force: boolean) => {
+ if (!source) return;
+ const value = key.trim();
+ if (!value) return;
+ const seq = submitSeq.current;
+ setPhase('submitting');
+ try {
+ const tail = await modelsApi.replaceCredential(source.id, force ? { key: value, force: true } : { key: value });
+ if (submitSeq.current !== seq) return;
+ const verdict = repairOutcome(tail);
+ setOutcome(verdict);
+ setPhase('done');
+ // Before the auto-close decision, unconditionally: the credential is
+ // committed whatever the report says, so the list is stale from here on.
+ onReplaced();
+ if (repairSettles(verdict)) closeTimer.current = window.setTimeout(onClose, 1500);
+ } catch (e) {
+ if (submitSeq.current !== seq) return;
+ const failure = apiFailure(e);
+ // The guard, in place: keep the typed key, name what would be stranded, and
+ // let the same button commit with `force`.
+ if (failure?.code === 'source_last_supplier' && !force) {
+ setGaps(failure.wouldInterrupt);
+ setPhase('confirm');
+ return;
+ }
+ // A refusal the route NAMED wrote nothing — that is what the guard above is,
+ // and what makes it safe to leave the rows alone. A failure it did not name
+ // is the atomic write with its answer lost coming back: the credential may
+ // be replaced and re-discovered already, in which case the row behind this
+ // dialog still shows the old key's state and 更换 would provision a second
+ // replacement. So the error is reported AND the list re-read — the two are
+ // not alternatives, and only the report is about this dialog.
+ if (mayHaveWritten(failure)) onReplaced();
+ setPhase('error');
+ }
+ };
+
+ const busy = phase === 'submitting';
+ const forcing = phase === 'confirm';
+ const settled = phase === 'done';
+
+ return (
+ // Closing mid-commit would drop a credential the server has already written.
+ <Dialog open={open} onOpenChange={(v) => !v && !busy && onClose()}>
+ <DialogContent className="max-w-[520px] gap-5">
+ <DialogHeader>
+ <DialogTitle className="text-[18px] font-bold">
+ {forcing
+ ? t('settings.models.repair.forceTitle')
+ : t('settings.models.repair.replaceTitle', { name: source?.display_name ?? '' })}
+ </DialogTitle>
+ <DialogDescription>
+ {forcing
+ ? t('settings.models.repair.gapsTitle')
+ : t('settings.models.repair.replaceBody')}
+ </DialogDescription>
+ </DialogHeader>
+
+ {forcing ? (
+ <SupplyGapNote gaps={gaps} />
+ ) : (
+ <Field label={t('settings.models.repair.replaceLabel')} mono icon={KeyRound}>
+ {(id) => (
+ <Input
+ id={id}
+ type="password"
+ autoComplete="off"
+ spellCheck={false}
+ autoFocus
+ placeholder={t('settings.models.field.apiKeyPlaceholder')}
+ value={key}
+ onChange={(e) => setKey(e.target.value)}
+ disabled={busy || settled}
+ className="h-11 pl-9 font-mono text-[14px]"
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !busy && !settled) {
+ e.preventDefault();
+ void submit(false);
+ }
+ }}
+ />
+ )}
+ </Field>
+ )}
+
+ {settled && outcome ? (
+ outcome.kind === 'gaps' ? (
+ <div className="flex flex-col gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-3.5 py-3">
+ <span className="text-[12.5px] font-semibold leading-relaxed text-gold">
+ {t('settings.models.repair.gapsDone')}
+ </span>
+ <SupplyGapNote gaps={outcome.gaps} />
+ </div>
+ ) : outcome.kind === 'unresolved' ? (
+ // The key was accepted and the source came back stopped anyway. Same
+ // rule as the reauth dialog: no green check over a row that is still
+ // 需处理, and no auto-close over it either.
+ <div className="flex items-center gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-4 py-3 text-[13px] font-medium text-gold">
+ <TriangleAlert className="size-4 shrink-0" />
+ <span>{t('settings.models.repair.unresolved')}</span>
+ </div>
+ ) : (
+ <div className="flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium text-mint">
+ <CheckCircle2 className="size-4 shrink-0" />
+ <span>{t(REPAIR_LINE_KEY[outcome.kind])}</span>
+ </div>
+ )
+ ) : null}
+
+ {phase === 'error' && (
+ <div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/[0.08] px-4 py-3 text-[13px] text-destructive">
+ <TriangleAlert className="mt-0.5 size-4 shrink-0" />
+ {/* One sentence, no code: every failure this route can report other
+ than the guard above is 「that key didn't work」, and the machine
+ code is in the network log for whoever needs it. */}
+ <span>{t('settings.models.repair.replaceFailed')}</span>
+ </div>
+ )}
+
+ <DialogFooter>
+ <div className="flex items-center gap-2">
+ {/* 关闭 once the credential is committed: 「取消」 on a completed write
+ reads as an undo this route does not have. */}
+ <Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={onClose} disabled={busy}>
+ {t(settled ? 'common.close' : 'common.cancel')}
+ </Button>
+ {!settled && (
+ <Button
+ variant={forcing ? 'destructive' : 'brand'}
+ size="sm"
+ className="h-10 sm:h-9"
+ onClick={() => void submit(forcing)}
+ disabled={busy || !key.trim()}
+ >
+ {busy
+ ? t('settings.models.repair.replacing')
+ : forcing
+ ? t('settings.models.repair.forceConfirm')
+ : t('settings.models.repair.replaceSubmit')}
+ </Button>
+ )}
+ </div>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+export default ReplaceKeyDialog;
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index a727a96d8..0ff43f85a 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -19,7 +19,15 @@ import { SourceOrderDrawer } from './SourceOrderDrawer';
import { AdvancedRow } from './AdvancedRow';
import { AddApiKeyDialog } from './AddApiKeyDialog';
import { OAuthConnectDialog } from './OAuthConnectDialog';
+import { RepairJourney, type RepairTarget } from './RepairJourney';
import { createLatestAsyncAuthority } from './asyncLifetime';
+import {
+ emptyFeed,
+ feedAfterHeadRead,
+ feedAfterTailRead,
+ feedTailCursor,
+ type EventFeed,
+} from './eventFeed';
import { MappingDrawer } from './menus/MappingDrawer';
import { OpenCodeMenuDrawer } from './menus/OpenCodeMenuDrawer';
import { modelsApi } from './modelsApi';
@@ -84,10 +92,9 @@ export const SettingsModelsPage: React.FC = () => {
const [sources, setSources] = React.useState<Source[]>([]);
const [agents, setAgents] = React.useState<AgentSupply[]>([]);
- const [events, setEvents] = React.useState<ResolutionEvent[]>([]);
- // A short page is the end of the feed — the only end-of-list signal the
- // endpoint gives (there is no total).
- const [eventsExhausted, setEventsExhausted] = React.useState(true);
+ // Rows and end-of-feed as ONE value: every read moves both, and the transition
+ // that moved only the rows is what made 加载更早 lie. `EventFeed` owns the rules.
+ const [feed, setFeed] = React.useState<EventFeed>(emptyFeed);
const [loadingEvents, setLoadingEvents] = React.useState(false);
const [runtime, setRuntime] = React.useState<RuntimeDependency | null>(null);
const [loading, setLoading] = React.useState(true);
@@ -96,6 +103,10 @@ export const SettingsModelsPage: React.FC = () => {
const [apiKeyOpen, setApiKeyOpen] = React.useState(false);
const [oauthVendor, setOauthVendor] = React.useState<string | null>(null);
+ // The row + remedy a repair journey is running for. Holds the SOURCE OBJECT, not
+ // its id, on purpose: a re-auth's first act is to change that row, so a live
+ // lookup would rewrite the dialog's own subject mid-flow (RepairJourney.tsx).
+ const [repairTarget, setRepairTarget] = React.useState<RepairTarget | null>(null);
// Which backend's 模型菜单 / 来源顺序 drawer is open. Tracked by backend id (not
// the agent object) so a background refresh keeps feeding the drawer the
// freshest agent.
@@ -118,12 +129,30 @@ export const SettingsModelsPage: React.FC = () => {
};
}, []);
+ // 最近切换 is re-read here with the rows, because the writes this refresh exists
+ // for are the writes that FILE events: a failing 试跑 cools its head down through
+ // `_cooldown`, which records the `cooldown` row that explains the state change
+ // the user is about to see. Fetched only at mount, the row changed and the line
+ // explaining it appeared nowhere until the page was reloaded — the explanation
+ // arriving later than the thing it explains.
+ // It rides along as an ANCILLARY leg, though — `null` when that one read failed.
+ // The feed explains the rows; it is not the rows. Letting it reject the whole
+ // `Promise.all` would mean a slow or broken `/events` holds back the repaired
+ // source state and the ● 当前 the user just changed, which is the opposite of
+ // this refresh's job. A feed left one write behind is not wrong, only not newer,
+ // and the next mutation or reload catches it up.
const [refreshAuthority] = React.useState(() =>
- createLatestAsyncAuthority<[Source[], AgentSupply[]]>(([nextSources, nextAgents]) => {
- if (!aliveRef.current) return;
- setSources(nextSources);
- setAgents(nextAgents);
- }),
+ createLatestAsyncAuthority<[Source[], AgentSupply[], ResolutionEvent[] | null]>(
+ ([nextSources, nextAgents, headEvents]) => {
+ if (!aliveRef.current) return;
+ setSources(nextSources);
+ setAgents(nextAgents);
+ // Merged, not replaced: 加载更早 pages tail-ward, and a head re-read must
+ // not silently drop the rows it never asked for. See `feedAfterHeadRead`
+ // for the one case merging is wrong, and for what that costs 加载更早.
+ if (headEvents) setFeed((prev) => feedAfterHeadRead(prev, headEvents));
+ },
+ ),
);
React.useEffect(() => {
@@ -139,8 +168,11 @@ export const SettingsModelsPage: React.FC = () => {
if (cancelled) return;
setSources(s);
setAgents(a);
- setEvents(e);
- setEventsExhausted(e.length < EVENT_PAGE);
+ // The first page is a tail read as much as a head one: it reaches the end
+ // of the feed exactly when it comes back short, and its cursor is `null`
+ // because it asked for the top. Applied to `prev` rather than to
+ // `emptyFeed` so the same 「still the feed I asked about?」 rule covers it.
+ setFeed((prev) => feedAfterTailRead(prev, e, EVENT_PAGE, null));
setRuntime(r);
setLoading(false);
})
@@ -156,7 +188,13 @@ export const SettingsModelsPage: React.FC = () => {
const refreshSourcesAgents = React.useCallback(async () => {
try {
- await refreshAuthority.run(() => Promise.all([modelsApi.listSources(), modelsApi.listAgents()]));
+ await refreshAuthority.run(() =>
+ Promise.all([
+ modelsApi.listSources(),
+ modelsApi.listAgents(),
+ modelsApi.listEvents(EVENT_PAGE).catch(() => null),
+ ]),
+ );
} catch {
// A mutation may have succeeded server-side but the re-read failed — tell
// the user the view might be stale rather than silently swallowing it.
@@ -165,25 +203,27 @@ export const SettingsModelsPage: React.FC = () => {
}, [refreshAuthority, showToast, t]);
const loadOlderEvents = React.useCallback(async () => {
- const oldest = events[events.length - 1]?.id;
+ const oldest = feedTailCursor(feed);
if (!oldest) return;
setLoadingEvents(true);
try {
const page = await modelsApi.listEvents(EVENT_PAGE, oldest);
if (!aliveRef.current) return;
// Merged by id rather than concatenated: the feed grows at the head while
- // we page from the tail, so an overlapping row is normal, not a bug.
- setEvents((prev) => {
- const seen = new Set(prev.map((e) => e.id));
- return [...prev, ...page.filter((e) => !seen.has(e.id))];
- });
- setEventsExhausted(page.length < EVENT_PAGE);
+ // we page from the tail, so an overlapping row is normal, not a bug. Same
+ // owner as the mount read, because reaching the end is the same question
+ // there; the head re-read has its own because merging is not always right.
+ //
+ // The cursor goes back in with the page: this request is a question about
+ // the rows below `oldest`, and a head re-read that REPLACED the feed while
+ // it was in flight left it about a feed that is no longer on screen.
+ setFeed((prev) => feedAfterTailRead(prev, page, EVENT_PAGE, oldest));
} catch {
if (aliveRef.current) showToast(t('settings.models.toast.refreshFailed') as string, 'error');
} finally {
if (aliveRef.current) setLoadingEvents(false);
}
- }, [events, showToast, t]);
+ }, [feed, showToast, t]);
const connectHub = async (agent: AgentSupply) => {
setConnecting(agent.backend);
@@ -241,6 +281,7 @@ export const SettingsModelsPage: React.FC = () => {
onConnectChatGPT={() => setOauthVendor('openai')}
onAddApiKey={() => setApiKeyOpen(true)}
onSourceChanged={() => void refreshSourcesAgents()}
+ onRepair={(source, kind) => setRepairTarget({ source, kind })}
/>
<AgentCard
agents={agents}
@@ -250,9 +291,9 @@ export const SettingsModelsPage: React.FC = () => {
connectingBackend={connecting}
/>
<RecentSwitchesCard
- events={events}
+ events={feed.events}
sources={sources}
- hasMore={!eventsExhausted}
+ hasMore={!feed.exhausted}
loadingMore={loadingEvents}
onLoadMore={() => void loadOlderEvents()}
/>
@@ -267,6 +308,11 @@ export const SettingsModelsPage: React.FC = () => {
onClose={() => setOauthVendor(null)}
onConnected={() => void refreshSourcesAgents()}
/>
+ <RepairJourney
+ target={repairTarget}
+ onClose={() => setRepairTarget(null)}
+ onChanged={() => void refreshSourcesAgents()}
+ />
{orderAgent && (
<SourceOrderDrawer
diff --git a/ui/src/components/settings/models/SourceOrderDrawer.tsx b/ui/src/components/settings/models/SourceOrderDrawer.tsx
index 4309eb23a..6a7669224 100644
--- a/ui/src/components/settings/models/SourceOrderDrawer.tsx
+++ b/ui/src/components/settings/models/SourceOrderDrawer.tsx
@@ -20,8 +20,20 @@
// Reachable in Hub mode only (AC-7): a Direct backend has no Hub order, no chain
// and no probe, so the affordance is withdrawn rather than shown empty.
import * as React from 'react';
+import type { TFunction } from 'i18next';
import { Reorder, useDragControls } from 'framer-motion';
-import { ChevronRight, CirclePlus, GripVertical, List, WandSparkles, X } from 'lucide-react';
+import {
+ CheckCircle2,
+ ChevronRight,
+ CirclePlus,
+ GripVertical,
+ List,
+ Loader2,
+ TriangleAlert,
+ WandSparkles,
+ X,
+ Zap,
+} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Badge } from '@/components/ui/badge';
@@ -32,14 +44,24 @@ import { useToast } from '@/context/ToastContext';
import { initialSeedState, savedSourcesKey, seedStep } from './asyncLifetime';
import { CurrentChip, StateChip } from './chips';
import { eligibilityOf } from './eligibility';
+import { DRY_RUN_ENABLED } from './featureFlags';
import { cooldownEtaMinutes } from './format';
import { MenuDrawer } from './menus/MenuDrawer';
-import { modelsApi } from './modelsApi';
+import { apiFailure, modelsApi } from './modelsApi';
+import {
+ dryRunChainKey,
+ dryRunOutcome,
+ dryRunPlan,
+ dryRunRowView,
+ probeArrival,
+ type DryRunOutcome,
+} from './repair';
import { movedOrder, sameIds } from './reorder';
+import { serverText } from './serverCopy';
import { orderSufficiency } from './sufficiency';
import { isUnhealthy, needsAttention } from './supply';
import { ACCENT_ICON, ACCENT_TILE, backendVisual, sourceVisual } from './vendorMeta';
-import type { AgentSourcesPut, AgentSupply, Source, SourcePolicy } from './types';
+import type { AgentBackend, AgentSourcesPut, AgentSupply, Source, SourcePolicy } from './types';
// ── Row parts ───────────────────────────────────────────────────────────
//
@@ -448,6 +470,16 @@ export const SourceOrderDrawer: React.FC<{
</>
)}
+ {DRY_RUN_ENABLED && (
+ <DryRunRow
+ agent={agent}
+ sources={sources}
+ chainKey={dryRunChainKey(agent, policy, order, sources)}
+ saving={saving}
+ reread={onSaved}
+ />
+ )}
+
{/* The phone's home for 模型菜单与映射. A frame that doesn't draw a control
at 390px is saying where to move it, not that a phone user may not
have it — the two configuration surfaces answer adjacent questions
@@ -471,6 +503,174 @@ export const SourceOrderDrawer: React.FC<{
);
};
+/** 「<name> 没跑通」, with the server's reason when it gave one. */
+const failedLine = (t: TFunction, name: string, detail: string | null): string =>
+ detail
+ ? (t('settings.models.dryRun.failed', { name, detail }) as string)
+ : (t('settings.models.dryRun.failedUnknown', { name }) as string);
+
+/**
+ * 试跑 — one real turn through this Agent's chain, and its answer.
+ *
+ * Full-width at every breakpoint, at the end of the list. No V6 or M02 frame
+ * draws it, so it takes the geometry of the phone's 模型菜单与映射 row rather than
+ * inventing one, and it is a row instead of a third footer button because the
+ * answer belongs UNDER the question: 「这条链现在能不能跑通」 is about the list
+ * above it, and a footer control would report on it from the wrong end of the
+ * sheet, with nowhere to put the result line.
+ *
+ * It reports the head the SERVER picked, never one this drawer chose: the probe
+ * takes no model, the reply names the source it reached, and a null latency is a
+ * head the Hub does not carry the request for (a native CLI login) — which is
+ * `可用` without a number, not a zero.
+ */
+const DryRunRow: React.FC<{
+ agent: AgentSupply;
+ sources: Source[];
+ /** Everything the USER selects the probed turn with — order, policy, and the
+ * model surface, from `dryRunChainKey`. Deliberately not the head the server
+ * computes from it; see that owner and the reset effect below. */
+ chainKey: string;
+ /** The drawer's order PUT is in flight. A probe started now would answer for the
+ * 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
+ * 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. */
+ reread: () => void;
+}> = ({ agent, sources, chainKey, saving, reread }) => {
+ const { t } = useTranslation();
+ const plan = dryRunPlan(agent);
+ const [running, setRunning] = React.useState(false);
+ const [outcome, setOutcome] = React.useState<DryRunOutcome | null>(null);
+ // The REASON, not the sentence built from it: a stored sentence keeps the
+ // language it was built in, and a language switch re-renders this row without
+ // re-running the probe. Wrapped rather than a bare `string | null`, because a
+ // thrown failure may carry no key at all and `null` has to keep meaning 「nothing
+ // ran yet」 — `{ key: null }` is the third state, 「it failed and nobody named
+ // why」, whose sentence is the generic line below.
+ const [errorReason, setErrorReason] = React.useState<{ key: string | null } | null>(null);
+ const seq = React.useRef(0);
+
+ // A result describes ONE chain, and editing the chain stops it being about
+ // anything — so it goes, rather than sitting there under a list it no longer
+ // answers for.
+ //
+ // Keyed on the chain the USER edits, not on `agent.current`, because the head
+ // is where the two diverge: a failing 试跑 cools its own head down, so the
+ // re-read below moves `agent.current` almost every time the report is a
+ // failure. Keyed on the head, the refresh would erase the sentence the click
+ // produced — and the line names its source, so after a self-inflicted move it
+ // is the EXPLANATION for the new head rather than a claim about it.
+ React.useEffect(() => {
+ seq.current += 1;
+ setRunning(false);
+ setOutcome(null);
+ setErrorReason(null);
+ }, [chainKey]);
+
+ const run = async (backend: AgentBackend) => {
+ const mine = ++seq.current;
+ setRunning(true);
+ setOutcome(null);
+ setErrorReason(null);
+ try {
+ const probe = await modelsApi.probeAgent(backend);
+ // `seq` guards the REPORT, not the refetch. An edit to the chain while this
+ // was in flight makes the answer moot, but not the cooldown it wrote — and
+ // that edit's own refetch went out before this returned, so it cannot have
+ // seen it. `probeArrival` owns the split; the verdict is stored first, then
+ // the page behind this sheet is corrected.
+ const arrival = probeArrival({ kind: 'result', probe }, seq.current === mine);
+ if (arrival.report) setOutcome(dryRunOutcome(probe, sources));
+ if (arrival.reread) reread();
+ } catch (err) {
+ const failure = apiFailure(err);
+ // `serverNamed` is the error's to state, not this site's to infer from
+ // 「is it one of ours?」: a response that would not parse is one of ours and
+ // names nothing, and that is the case the reread below exists for. The code
+ // rides along for the opposite case — a refusal that named itself and, in
+ // naming itself, disproved the head this button was drawn from.
+ const arrival = probeArrival(
+ {
+ kind: 'thrown',
+ serverNamed: failure?.serverNamed ?? false,
+ code: failure?.code ?? null,
+ },
+ seq.current === mine,
+ );
+ // The server's own reason when it named one (`probe_no_candidate` carries a
+ // detail key), and the absence of one when it didn't. Which sentence either
+ // becomes is the render's call — the same degradation the rest of the page
+ // gives a server-chosen key, applied with the `t` that is current when it is
+ // READ rather than the one that happened to be in scope when it arrived.
+ if (arrival.report) setErrorReason({ key: failure?.detail ?? null });
+ // Either because the probe may have run and written with the answer lost on
+ // the way back, or because the refusal that came back contradicts the chain
+ // this row is drawn from — `probeArrival` keeps those two apart.
+ if (arrival.reread) reread();
+ } finally {
+ if (seq.current === mine) setRunning(false);
+ }
+ };
+
+ const ok = outcome?.kind === 'ok';
+ const line = !outcome
+ ? errorReason && serverText(t, errorReason.key, 'settings.models.dryRun.error')
+ : outcome.kind === 'ok'
+ ? outcome.latencyMs !== null
+ ? (t('settings.models.dryRun.ok', { name: outcome.sourceName, ms: outcome.latencyMs }) as string)
+ : (t('settings.models.dryRun.okNoLatency', { name: outcome.sourceName }) as string)
+ : // The detail is the server's key; with none, the name alone is the honest
+ // sentence rather than a machine code appended to it.
+ failedLine(t, outcome.sourceName, serverText(t, outcome.detailKey));
+
+ // What this row IS right now, which the plan alone cannot say: no head means no
+ // control (Direct mode, or waiting/interrupted — the page states that one level
+ // up with the remedy attached, so a disabled 试跑 would only repeat it), and yet
+ // this very row is how a chain LOSES its head, because a failing probe cools its
+ // own head down. The answer therefore outlives the chain it was about; only the
+ // control goes with it. `saving` is in there for the mirror-image reason — see
+ // `dryRunRowView`.
+ const { backend, enabled, report } = dryRunRowView(plan, { line, saving, running });
+ if (backend === null && !report) return null;
+
+ return (
+ <div className="mt-1 flex flex-col gap-2">
+ {backend !== null && (
+ <Button
+ variant="outline"
+ className="h-[46px] w-full justify-between rounded-xl px-4 text-[13px] font-semibold"
+ onClick={() => void run(backend)}
+ disabled={!enabled}
+ >
+ <span className="flex items-center gap-2">
+ {running ? <Loader2 className="size-4 animate-spin" /> : <Zap className="size-4" />}
+ {t(running ? 'settings.models.dryRun.running' : 'settings.models.dryRun.action')}
+ </span>
+ </Button>
+ )}
+ {report && (
+ <p
+ className={cn(
+ 'flex items-start gap-1.5 px-1 text-[12px] leading-relaxed',
+ ok ? 'text-mint' : 'text-gold',
+ )}
+ >
+ {ok ? (
+ <CheckCircle2 className="mt-[2px] size-3.5 shrink-0" />
+ ) : (
+ <TriangleAlert className="mt-[2px] size-3.5 shrink-0" />
+ )}
+ {line}
+ </p>
+ )}
+ </div>
+ );
+};
+
const EnabledRow: React.FC<{
source: Source;
index: number;
diff --git a/ui/src/components/settings/models/SourceRow.tsx b/ui/src/components/settings/models/SourceRow.tsx
index b0ace8066..da5480553 100644
--- a/ui/src/components/settings/models/SourceRow.tsx
+++ b/ui/src/components/settings/models/SourceRow.tsx
@@ -20,7 +20,7 @@ import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import { BillingChip, ExperimentalChip, StateChip } from './chips';
import { SupplyTooltip } from './SupplyTooltip';
-import { SourceRowMenu } from './SourceRowMenu';
+import { SourceRowMenu, type RaisedRepair } from './SourceRowMenu';
import { ACCENT_ICON, ACCENT_TILE, isCustomEndpoint, sourceVisual } from './vendorMeta';
import { cooldownEtaMinutes, formatSpend } from './format';
import { isUnhealthy, needsAttention } from './supply';
@@ -119,7 +119,9 @@ export const SourceRow: React.FC<{
source: Source;
/** Re-fetch after a row action (rename / re-discover / delete). */
onChanged: () => void;
-}> = ({ source, onChanged }) => {
+ /** Open a repair journey the page hosts — see SourceRowMenu's `onRepair`. */
+ onRepair?: (source: Source, kind: RaisedRepair) => void;
+}> = ({ source, onChanged, onRepair }) => {
const { Icon, accent } = sourceVisual(source);
const subline = useSubline(source);
const isExperimental = source.kind === 'subscription' && source.supply_channel === 'hub';
@@ -176,9 +178,11 @@ export const SourceRow: React.FC<{
</div>
{/* Thumb-reachable on the identity line on phones (design.pen M01 m01More,
- 36×36), trailing the desktop row on sm+. */}
- <div className="order-2 shrink-0 sm:order-3">
- <SourceRowMenu source={source} onChanged={onChanged} />
+ 36×36), trailing the desktop row on sm+. A flex line rather than a bare
+ slot because a stopped row puts its one-tap remedy beside the ⋯ — both
+ come from the menu component, which owns the actions. */}
+ <div className="order-2 flex shrink-0 items-center gap-1.5 sm:order-3">
+ <SourceRowMenu source={source} onChanged={onChanged} onRepair={onRepair} />
</div>
</div>
);
diff --git a/ui/src/components/settings/models/SourceRowMenu.tsx b/ui/src/components/settings/models/SourceRowMenu.tsx
index 9f0990a64..807d1057b 100644
--- a/ui/src/components/settings/models/SourceRowMenu.tsx
+++ b/ui/src/components/settings/models/SourceRowMenu.tsx
@@ -6,6 +6,11 @@
// delete). Presentation lives in SourceRow; this owns the actions + their
// dialogs so the row stays declarative.
//
+// It also owns the ENTRY to the repair journeys: an inline, always-visible button
+// on a stopped row (§4.5's 「one tap to fix it」) plus the elective credential
+// entries in the menu. The journeys themselves are raised to the page — see
+// RepairJourney — because completing one refetches the list this row lives in.
+//
// No reorder actions: in V6 an order belongs to an Agent, not to the source
// inventory, so 上移/下移 moved into the per-Agent 来源顺序 drawer (which keeps a
// keyboard/screen-reader path of its own alongside drag).
@@ -14,7 +19,7 @@
// the row's identity in the header and a one-line rationale under each action,
// because a thumb menu has no hover to explain itself.
import * as React from 'react';
-import { MoreHorizontal, Pencil, RefreshCw, Trash2 } from 'lucide-react';
+import { KeyRound, LogIn, MoreHorizontal, Pencil, RefreshCw, Trash2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
@@ -25,9 +30,20 @@ import { ResponsiveMenu } from '@/components/ui/responsive-menu';
import { cn } from '@/lib/utils';
import { useIsMobile } from '@/lib/useIsMobile';
import { useToast } from '@/context/ToastContext';
-import { modelsApi } from './modelsApi';
+import { apiFailure, modelsApi } from './modelsApi';
+import { canReauth, canReplaceKey, reauthCost, repairAction, REPAIR_LABEL_KEY, type RepairKind } from './repair';
+import { SupplyGapNote } from './SupplyGapNote';
import { ACCENT_ICON, ACCENT_TILE, sourceVisual } from './vendorMeta';
-import type { Source } from './types';
+import type { Source, SupplyGap } from './types';
+
+/** The two remedies that need a dialog of their own, so the page hosts them. */
+export type RaisedRepair = Exclude<RepairKind, 'retest'>;
+
+const REPAIR_ICON: Record<RepairKind, React.ComponentType<{ className?: string }>> = {
+ reauth: LogIn,
+ replace_key: KeyRound,
+ retest: RefreshCw,
+};
const MenuAction: React.FC<{
Icon: React.ComponentType<{ className?: string }>;
@@ -66,7 +82,15 @@ export const SourceRowMenu: React.FC<{
source: Source;
/** Re-fetch sources + agents after any successful mutation. */
onChanged: () => void;
-}> = ({ source, onChanged }) => {
+ /**
+ * Raise a remedy that needs a dialog + a server flow to the page, which
+ * outlives this row: a re-auth replaces the source's models and a key
+ * replacement re-discovers them, so both trigger the refetch that unmounts
+ * whatever hosted the dialog. `retest` is handled here because it needs no
+ * dialog at all.
+ */
+ onRepair?: (source: Source, kind: RaisedRepair) => void;
+}> = ({ source, onChanged, onRepair }) => {
const { t } = useTranslation();
const { showToast } = useToast();
const isMobile = useIsMobile();
@@ -80,6 +104,10 @@ export const SourceRowMenu: React.FC<{
// Set once the server refuses a plain delete (only-supplier guard); the
// confirm then escalates to a forced delete instead of silently failing.
const [forceMode, setForceMode] = React.useState(false);
+ // What that refusal said it would strand. Kept as the server sent it: the
+ // confirm has to name the Agents, and re-deriving them from the loaded list
+ // would answer a question the guard already answered.
+ const [gaps, setGaps] = React.useState<SupplyGap[]>([]);
const [testing, setTesting] = React.useState(false);
// Re-armed on mount, not only cleared on unmount: a cleanup-only guard is
@@ -133,7 +161,15 @@ export const SourceRowMenu: React.FC<{
onChanged();
showToast(t('settings.models.sourceActions.rediscovered', { count }) as string, 'success');
} catch {
- if (aliveRef.current) showToast(t('settings.models.sourceActions.rediscoverFailed') as string, 'error');
+ if (!aliveRef.current) return;
+ // A failed test is NOT read-only: `test_source` persists the source as
+ // error/unclassified and only then raises `discovery_failed`. Refreshing on
+ // success alone would leave the row showing the cause it had before the
+ // server replaced it — and for the inline repair, the remedy that cause
+ // implied. Re-read either way; the toast reports the attempt, the row
+ // reports the state.
+ onChanged();
+ showToast(t('settings.models.sourceActions.rediscoverFailed') as string, 'error');
} finally {
if (aliveRef.current) setTesting(false);
}
@@ -142,6 +178,7 @@ export const SourceRowMenu: React.FC<{
const openDelete = () => {
setMenuOpen(false);
setForceMode(false);
+ setGaps([]);
setDeleteOpen(true);
};
@@ -153,26 +190,89 @@ export const SourceRowMenu: React.FC<{
onChanged();
showToast(t('settings.models.sourceActions.deleted') as string, 'success');
} catch (err) {
- const code = (err as { code?: string } | null)?.code;
- // Only-supplier guard: escalate to a forced delete instead of failing.
- if (code === 'mode_switch_blocked' && !forceMode) {
- if (aliveRef.current) setForceMode(true);
+ const failure = apiFailure(err);
+ // The supply guard: `source_last_supplier` is the code DELETE actually
+ // sends (`mode_switch_blocked` belongs to the mode route, so the old test
+ // never matched and every guarded delete failed with a generic toast).
+ // Escalate to `?force=true` AND show what the server said it would strand —
+ // that list is the reason a second confirm exists.
+ if (failure?.code === 'source_last_supplier' && !forceMode) {
+ if (aliveRef.current) {
+ setGaps(failure.wouldInterrupt);
+ setForceMode(true);
+ }
return;
}
if (aliveRef.current) {
setDeleteOpen(false);
+ // Same rule as `rediscover` above, for the same reason: a failed DELETE is
+ // not read-only either. The supply guard is the one refusal that provably
+ // wrote nothing — `delete_source` raises it off a CLONED config, before
+ // `_commit_synced` — and it left through the branch above. Everything that
+ // reaches here got past that commit or died inside it: a response lost on
+ // the way back arrives as `bad_response`, invented by this client about a
+ // delete that may well have happened, and `source_not_found` means the row
+ // is already gone. Deliberately not gated on `serverNamed`: that says
+ // whether the ROUTE named the failure, never whether the server wrote —
+ // `oauth_cancel` is the standing proof those are different questions. The
+ // toast reports the attempt, the row reports the state.
+ onChanged();
showToast(t('settings.models.sourceActions.deleteFailed') as string, 'error');
}
}
};
+ // ── Repair ───────────────────────────────────────────────────────────────
+ // §4.5: a `needs_action` row 「carries a detail_key naming the cause, so the row
+ // can offer ONE TAP to fix it … instead of a dead-end error string」. `repair.ts`
+ // owns which tap that is; this only routes it.
+ const blockedRemedy = repairAction(source);
+ const runRepair = (kind: RepairKind) => {
+ setMenuOpen(false);
+ if (kind === 'retest') {
+ void rediscover();
+ return;
+ }
+ onRepair?.(source, kind);
+ };
+ // A raised remedy needs the page's host; without it the row would open nothing.
+ const offer = (kind: RepairKind | null): kind is RepairKind =>
+ kind !== null && (kind === 'retest' || Boolean(onRepair));
+ const inlineRemedy = offer(blockedRemedy) ? blockedRemedy : null;
+
// Descriptions only exist in the sheet; passing undefined on desktop is what
// keeps the popover a compact label list.
const hint = (key: string, opts?: Record<string, unknown>) =>
isMobile ? (t(`settings.models.sourceActions.${key}`, opts) as string) : undefined;
+ const RemedyIcon = inlineRemedy ? REPAIR_ICON[inlineRemedy] : null;
+
return (
<>
+ {inlineRemedy && RemedyIcon ? (
+ // Always visible, unlike the ⋯ trigger next to it: the whole failure of a
+ // status-only row is that the remedy hides behind a hover the blocked
+ // state gives no reason to try. Geometry from design.pen V6 03's row-level
+ // button (`d6Btn 启用`): outline, radius 8, 6/12 padding, 11.5/600.
+ <Button
+ variant="outline"
+ size="xs"
+ className="h-7 shrink-0 rounded-md px-3 text-[11.5px] font-semibold"
+ // Composed rather than a per-kind string: the label already says what
+ // happens, and every row on the page repeats it.
+ aria-label={`${t(REPAIR_LABEL_KEY[inlineRemedy])} · ${source.display_name}`}
+ disabled={testing}
+ onClick={() => runRepair(inlineRemedy)}
+ >
+ {testing && inlineRemedy === 'retest' ? (
+ <RefreshCw className="size-3 animate-spin" />
+ ) : (
+ <RemedyIcon className="size-3" />
+ )}
+ {t(REPAIR_LABEL_KEY[inlineRemedy])}
+ </Button>
+ ) : null}
+
<ResponsiveMenu
open={menuOpen}
onOpenChange={setMenuOpen}
@@ -232,6 +332,32 @@ export const SourceRowMenu: React.FC<{
onClick={() => void rediscover()}
/>
)}
+ {/* Elective credential maintenance — available on a HEALTHY source too
+ (api.md gives both routes an elective form, guard included), which is
+ why these read the per-route predicates rather than `repairAction`.
+ Suppressed for the remedy the inline button already offers, so a
+ blocked row doesn't show the same action twice. */}
+ {onRepair && canReauth(source) && inlineRemedy !== 'reauth' && (
+ <MenuAction
+ Icon={LogIn}
+ label={t('settings.models.sourceActions.reauth') as string}
+ // Only the native channel pays at 「开始」, so only it has something to
+ // warn about before the confirm does. On a hub source the same line
+ // would promise a loss that does not happen — and the confirm one tap
+ // later states that channel's real cost. Deleting the sentence beats
+ // qualifying it.
+ description={reauthCost(source) === 'immediate' ? hint('reauthHint') : undefined}
+ onClick={() => runRepair('reauth')}
+ />
+ )}
+ {onRepair && canReplaceKey(source) && inlineRemedy !== 'replace_key' && (
+ <MenuAction
+ Icon={KeyRound}
+ label={t('settings.models.sourceActions.replaceKey') as string}
+ description={hint('replaceKeyHint')}
+ onClick={() => runRepair('replace_key')}
+ />
+ )}
<MenuAction
Icon={Trash2}
label={t('settings.models.sourceActions.delete') as string}
@@ -284,7 +410,10 @@ export const SourceRowMenu: React.FC<{
open={deleteOpen}
onOpenChange={(v) => {
setDeleteOpen(v);
- if (!v) setForceMode(false);
+ if (!v) {
+ setForceMode(false);
+ setGaps([]);
+ }
}}
destructive
title={t(forceMode ? 'settings.models.sourceActions.deleteForceTitle' : 'settings.models.sourceActions.deleteTitle')}
@@ -293,7 +422,11 @@ export const SourceRowMenu: React.FC<{
})}
confirmLabel={t(forceMode ? 'settings.models.sourceActions.deleteForceConfirm' : 'settings.models.sourceActions.deleteConfirm') as string}
onConfirm={confirmDelete}
- />
+ >
+ {/* No title: `deleteForceBody` above already states the consequence, and a
+ second sentence saying it again is the line worth deleting. */}
+ {forceMode ? <SupplyGapNote gaps={gaps} /> : null}
+ </ConfirmDialog>
</>
);
};
diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsx
index f5a3cdb6d..b9c1eee0f 100644
--- a/ui/src/components/settings/models/SourcesCard.tsx
+++ b/ui/src/components/settings/models/SourcesCard.tsx
@@ -17,6 +17,7 @@ import { useTranslation } from 'react-i18next';
import { AddSourceMenu } from './AddSourceMenu';
import { SourceRow } from './SourceRow';
+import type { RaisedRepair } from './SourceRowMenu';
import type { Source } from './types';
export const SourcesCard: React.FC<{
@@ -26,7 +27,9 @@ export const SourcesCard: React.FC<{
onAddApiKey: () => void;
/** Re-fetch after a per-row action (rename / re-discover / delete). */
onSourceChanged: () => void;
-}> = ({ sources, onConnectClaude, onConnectChatGPT, onAddApiKey, onSourceChanged }) => {
+ /** Open a repair journey the page hosts — see SourceRowMenu's `onRepair`. */
+ onRepair?: (source: Source, kind: RaisedRepair) => void;
+}> = ({ sources, onConnectClaude, onConnectChatGPT, onAddApiKey, onSourceChanged, onRepair }) => {
const { t } = useTranslation();
return (
@@ -49,7 +52,7 @@ export const SourcesCard: React.FC<{
) : (
<div className="flex flex-col">
{sources.map((source) => (
- <SourceRow key={source.id} source={source} onChanged={onSourceChanged} />
+ <SourceRow key={source.id} source={source} onChanged={onSourceChanged} onRepair={onRepair} />
))}
</div>
)}
diff --git a/ui/src/components/settings/models/SupplyGapNote.tsx b/ui/src/components/settings/models/SupplyGapNote.tsx
new file mode 100644
index 000000000..534e9afd0
--- /dev/null
+++ b/ui/src/components/settings/models/SupplyGapNote.tsx
@@ -0,0 +1,49 @@
+// The 「谁会没有来源」 list (api.md → `would_interrupt` / `interrupted_pairs`).
+//
+// The supply guard refuses a write by NAMING what it would strand, and the spec
+// says why that naming matters: 「删除后 pm 将没有可用来源」 is actionable where a
+// bare (backend, model) pair is not. So this renders the Agents first and the
+// model second, and falls back to the backend only when no named Agent runs the
+// pair — which is a real case (the backend default supplies it) and not a reason
+// to drop the entry.
+//
+// One component for all three sites — the forced-delete confirm, the forced
+// key-replacement confirm, and the post-repair report — because the list is the
+// same list, and the previous per-site prose is exactly where two surfaces would
+// start describing the same refusal differently.
+import * as React from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { SupplyGap } from './types';
+
+export const SupplyGapNote: React.FC<{
+ gaps: SupplyGap[];
+ /** Rendered above the list. Omitted where the dialog's own description already
+ * states the consequence — a second sentence saying it again is the kind of
+ * line that is better deleted. */
+ title?: string;
+}> = ({ gaps, title }) => {
+ const { t } = useTranslation();
+ if (gaps.length === 0) return null;
+ const backendName = (backend: string) =>
+ t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string;
+
+ return (
+ <div className="flex flex-col gap-1.5 rounded-lg border border-border bg-surface-2/60 px-3 py-2.5">
+ {title ? <p className="text-[12px] font-semibold text-foreground">{title}</p> : null}
+ <ul className="flex flex-col gap-1">
+ {gaps.map((gap) => (
+ <li key={`${gap.backend}:${gap.model_id}`} className="text-[12px] leading-relaxed text-muted">
+ {/* ' · ' is this page's separator everywhere else (source sub-lines,
+ the adoption note, the agent card's amber line) — locale-neutral
+ on purpose. Agent names are user-chosen identifiers, so they join
+ with a plain comma in both locales rather than through copy. */}
+ {`${gap.agents.length > 0 ? gap.agents.join(', ') : backendName(gap.backend)} · ${gap.model_id}`}
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+};
+
+export default SupplyGapNote;
diff --git a/ui/src/components/settings/models/apiFailure.test.ts b/ui/src/components/settings/models/apiFailure.test.ts
new file mode 100644
index 000000000..67c44c862
--- /dev/null
+++ b/ui/src/components/settings/models/apiFailure.test.ts
@@ -0,0 +1,70 @@
+// Which failures the ROUTE named, as the transport itself reports it.
+//
+// The regression these pin: a caught error was treated as server-named whenever
+// it was one of ours (`apiFailure(err) !== null`), and two of ours are not. `call`
+// mints `bad_response` when the body will not parse and `http_<n>` when it parses
+// with no `error` in it — both of which mean the answer never arrived intact, and
+// are entirely consistent with the request having been carried out first. Callers
+// that skip a corrective re-read because 「the route said what happened」 then skip
+// it in exactly the case the re-read exists for: a probe that ran, wrote its
+// cooldown, and lost the reply on the way back.
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { apiFailure, modelsApi } from './modelsApi';
+
+/** The failure `listSources` comes back with for a given response. */
+const failureFor = async (respond: () => Response) => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => respond()),
+ );
+ try {
+ await modelsApi.listSources();
+ } catch (err) {
+ return apiFailure(err);
+ }
+ throw new Error('expected the call to reject');
+};
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('apiFailure — whether the route named the failure', () => {
+ it('reads a route-declared code as named', async () => {
+ const failure = await failureFor(() => Response.json({ error: 'discovery_failed' }, { status: 409 }));
+ expect(failure).toMatchObject({ code: 'discovery_failed', serverNamed: true });
+ });
+
+ it('reads a body that would not parse as UNNAMED', async () => {
+ // The server may well have written before this response was truncated.
+ const failure = await failureFor(() => new Response('<html>502</html>', { status: 502 }));
+ expect(failure).toMatchObject({ code: 'bad_response', serverNamed: false });
+ });
+
+ it('reads a status this client had to summarize itself as UNNAMED', async () => {
+ // Parsed, and said nothing about what happened. `http_502` is this client's
+ // sentence, not a route outcome, even though it arrives as the same error type.
+ const failure = await failureFor(() => Response.json({}, { status: 502 }));
+ expect(failure).toMatchObject({ code: 'http_502', serverNamed: false });
+ });
+
+ it('reads an ok:false envelope by the code it carries', async () => {
+ const failure = await failureFor(() => Response.json({ ok: false, error: 'engine_down' }));
+ expect(failure).toMatchObject({ code: 'engine_down', serverNamed: true });
+ });
+
+ it('is not one of ours at all when the failure came from our own code', async () => {
+ // Unchanged, and the reason `serverNamed` could not simply be dropped in
+ // favour of a null check: a TypeError from the render path is not a supply
+ // refusal, and callers still have to be able to tell.
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw new TypeError('Failed to fetch');
+ }),
+ );
+ await expect(modelsApi.listSources()).rejects.toThrow(TypeError);
+ expect(apiFailure(new TypeError('Failed to fetch'))).toBeNull();
+ });
+});
diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.ts
index 0405eec71..d8b0615c5 100644
--- a/ui/src/components/settings/models/asyncLifetime.test.ts
+++ b/ui/src/components/settings/models/asyncLifetime.test.ts
@@ -15,18 +15,54 @@
// is replaced by a non-terminal one, so a connect that succeeded renders as
// still running — and the same hole in the deadline branch stamps `failed`
// over a success once the timeout passes.
+//
+// 3. cancel-after-terminal. A teardown cancels the flow it opened, reading a
+// snapshot that says `awaiting_action` — while the poll in flight is about to
+// report success. `oauth_cancel` materializes a terminal flow instead of
+// cancelling it, so that call IS the write, and the rows the page keeps
+// showing were read before it happened.
+//
+// 4. cancel-after-handoff. The dialog closes while its start is still in flight
+// and a replacement opens; the server's pending-flow reuse hands the
+// replacement THAT SAME flow. The first journey's cleanup then cancels the
+// login the user is watching in the dialog that replaced it. Its mirror image
+// is the same close-then-reopen for a DIFFERENT row: the reuse is keyed by
+// source id while ownership of the dialog's ref is not, so withholding the
+// cancel there abandons an authorization no successor can ever adopt.
+//
+// 5. poll-error-during-submit. The 2s status read fails at the moment the paste
+// submit it raced commits. Latching the READER's error settles the view, so
+// the submit's success — the only arrival that carries the terminal tail — is
+// then correctly ignored, and the dialog reports 授权失败 over a credential the
+// server did replace.
+//
+// 6. start-rejected-after-close. A reauth's start rejects AFTER the dialog closed
+// and after `mark_native_irreversible_start` committed. The close path re-read
+// 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 需处理.
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+
import { describe, expect, it } from 'vitest';
import {
createFlowAuthority,
createLatestAsyncAuthority,
+ failureLanded,
+ flowLetGo,
+ flowStateTerminal,
flowStep,
initialSeedState,
isDone,
+ pollFailureSettles,
+ releaseFlow,
savedMappingsKey,
savedMenuKey,
savedSourcesKey,
seedStep,
+ startNeedsStatusRead,
+ terminalArrivalMovedRows,
type FlowView,
} from './asyncLifetime';
import type { AgentSupply, OAuthFlow } from './types';
@@ -218,7 +254,7 @@ describe('flowStep', () => {
describe('flow authority', () => {
it('ignores a poll flow_not_found that lands after success settled', () => {
- const authority = createFlowAuthority(() => {});
+ const authority = createFlowAuthority(() => {}, null);
authority.transition({ kind: 'response', flow: flow('verifying') });
authority.transition({ kind: 'response', flow: flow('success') });
@@ -236,7 +272,7 @@ describe('flow authority', () => {
});
it('ignores a paste rejection that lands after success settled', () => {
- const authority = createFlowAuthority(() => {});
+ const authority = createFlowAuthority(() => {}, null);
authority.transition({ kind: 'response', flow: flow('awaiting_action') });
authority.transition({ kind: 'response', flow: flow('success') });
@@ -255,7 +291,7 @@ describe('flow authority', () => {
it('keeps the deadline terminal when a paste success resolves afterward', () => {
const landed: FlowView[] = [];
- const authority = createFlowAuthority((view) => landed.push(view));
+ const authority = createFlowAuthority((view) => landed.push(view), null);
let connected = 0;
authority.transition({ kind: 'response', flow: flow('success') });
@@ -276,3 +312,497 @@ describe('flow authority', () => {
expect(landed.at(-1)).toEqual(authority.current());
});
});
+
+describe('pollFailureSettles — who speaks for a journey whose submit is outstanding', () => {
+ it('lets a failed poll settle the journey when it is the only authority', () => {
+ // A status read is also the call that materializes a just-succeeded flow, so on
+ // a device-code login its failure can be the one thing that knows the login
+ // produced nothing usable — when the route is what said so.
+ expect(pollFailureSettles(false, true)).toBe(true);
+ });
+
+ it('does not let it settle one while the user’s own submit is outstanding', () => {
+ // The submit is the writer of record; a read failing beside it says nothing
+ // about whether that write committed.
+ expect(pollFailureSettles(true, true)).toBe(false);
+ });
+
+ it('does not let a failure the route never named settle one either', () => {
+ // The other half of 「only authority」: being the only one who could speak is not
+ // the same as having spoken. The call that materializes a just-succeeded create
+ // is this very read, so a dropped connection or an unparseable body means the
+ // source may exist while the dialog declares a terminal nobody reported — and
+ // an ordinary connect retried from that sentence mints a second source. Same
+ // `serverNamed` bit `mayHaveWritten` reads for the refetch, asked about speech.
+ expect(pollFailureSettles(false, false)).toBe(false);
+ // …and the submit's precedence does not depend on it.
+ expect(pollFailureSettles(true, false)).toBe(false);
+ });
+
+ it('shows what latching one costs: the success right behind it is ignored', () => {
+ // Interleaving 5 as a sequence. `flowStep` is right to ignore the second
+ // arrival — the fix is upstream, at which arrival is allowed to be a verdict.
+ const authority = createFlowAuthority(() => {}, null);
+
+ authority.transition({ kind: 'response', flow: flow('awaiting_action') });
+ authority.transition({ kind: 'error', errorKey: 'settings.models.oauth.error.generic' });
+ const submitSucceeded = authority.transition({ kind: 'response', flow: flow('success') });
+
+ expect(submitSucceeded.action).toBe('ignore');
+ expect(authority.current().errorKey).toBe('settings.models.oauth.error.generic');
+ });
+
+ it('is what the dialog’s poll actually asks, about the submit’s own flag', () => {
+ // A predicate nothing consults is worth nothing, and the value it reads is the
+ // other half of the fix: the flow effect is built once per attempt, so it must
+ // read the submit's in-flight state through a ref or it reads `false` forever.
+ const dialog = readFileSync(join(__dirname, 'OAuthConnectDialog.tsx'), 'utf8');
+
+ expect(dialog).toMatch(
+ /pollFailureSettles\(submittingRef\.current, failure\?\.serverNamed \?\? false\)/,
+ );
+ expect(dialog).toMatch(/submittingRef\.current = submitting;/);
+ // The second argument only exists if the failure is read BEFORE the question is
+ // asked — reading it after the settle branch is how this reverts silently.
+ expect(dialog.indexOf('const failure = apiFailure(err);')).toBeLessThan(
+ dialog.indexOf('if (!pollFailureSettles('),
+ );
+ });
+});
+
+describe('startNeedsStatusRead — a start response that is already terminal', () => {
+ it('sends an already-successful start to the status route', () => {
+ // `POST …/reauth` reuses a live pending flow rather than opening a second one,
+ // so the start can answer `success` — carrying the flow ALONE. Latching it
+ // would settle the dialog on the one arrival that has no
+ // `recovered`/`interrupted_pairs` beside it, and `flowStep` would then be
+ // right to ignore the status read that does.
+ expect(startNeedsStatusRead(flow('success'))).toBe(true);
+ });
+
+ it('sends an already-FAILED start there too', () => {
+ // The finding: this used to latch, because a failure's `error_key` is the whole
+ // message — enough to DISPLAY, which is not enough to SETTLE. Settling stops
+ // the poll at its next tick, and `oauth_start` never materializes: it is
+ // `oauth_status` → `_materialize_completed_oauth` that runs
+ // `_fail_closed_hub_reauth`, strips the discovered models and saves the source
+ // as 需处理. Latched, the dialog explained a failure over a row still drawn
+ // healthy and a binding still pending, until the user's eventual close made
+ // `oauth_cancel` do the write as a side effect.
+ expect(startNeedsStatusRead(flow('failed'))).toBe(true);
+ expect(startNeedsStatusRead(flow('cancelled'))).toBe(true);
+ });
+
+ it('asks 「is it terminal」 and nothing about which terminal', () => {
+ // WHICH terminals owe server-side work is a fact about the server
+ // (`_is_hub_unsuccessful_terminal` is hub × {failed, cancelled}) and a guard
+ // over the envelope may not decide it. So this is exactly `flowStateTerminal`
+ // — one list, so the two cannot drift into disagreeing.
+ for (const state of ['success', 'failed', 'cancelled'] as const)
+ expect(startNeedsStatusRead(flow(state))).toBe(flowStateTerminal(state));
+ for (const state of ['starting', 'awaiting_action', 'verifying'] as const)
+ expect(startNeedsStatusRead(flow(state))).toBe(flowStateTerminal(state));
+ });
+
+ it('leaves a running start to the poll it already schedules', () => {
+ expect(startNeedsStatusRead(flow('awaiting_action'))).toBe(false);
+ expect(startNeedsStatusRead(flow('verifying'))).toBe(false);
+ });
+});
+
+describe('flowStateTerminal — one list of the states the server calls finished', () => {
+ it('counts every state a flow can be reported finished in', () => {
+ expect(flowStateTerminal('success')).toBe(true);
+ expect(flowStateTerminal('failed')).toBe(true);
+ expect(flowStateTerminal('cancelled')).toBe(true);
+ });
+
+ it('does not count a flow still running', () => {
+ expect(flowStateTerminal('starting')).toBe(false);
+ expect(flowStateTerminal('awaiting_action')).toBe(false);
+ expect(flowStateTerminal('verifying')).toBe(false);
+ });
+
+ it('is the list flowStep latches on, not a second copy of it', () => {
+ // Two enumerations of 「finished」 in one file is how they drift; the dialog's
+ // 「read this through status」 and the reducer's 「nothing may reopen this」 have
+ // to be the same set or one of them is wrong about a state the other handles.
+ const source = readFileSync(join(__dirname, 'asyncLifetime.ts'), 'utf8');
+ expect(source).toMatch(/if \(flowStateTerminal\(flow\.state\)\) \{/);
+ expect(source).toMatch(/startNeedsStatusRead = \(flow: OAuthFlow\): boolean =>\s*flowStateTerminal\(flow\.state\)/);
+ // `timeout` is the dialog's OWN verdict about a flow the server still holds
+ // live, which is why it arrives as a tick and is not in this list.
+ expect(flowStateTerminal('starting')).toBe(false);
+ });
+});
+
+describe('terminalArrivalMovedRows — which terminal is also a write', () => {
+ it('counts a success, which materializes what it reports', () => {
+ expect(terminalArrivalMovedRows('succeed')).toBe(true);
+ });
+
+ it('counts a FAILURE, which a hub reauth has already been persisted by', () => {
+ // The finding this pins: `_fail_closed_hub_reauth` runs inside the status read
+ // that answers `failed` — the discovered models are stripped and the source is
+ // saved as 需处理 before the response is written. A dialog that refreshes only
+ // on success explains the failure over a page still drawing that source as
+ // healthy, and still crediting it with the ● 当前 it can no longer supply.
+ expect(terminalArrivalMovedRows('fail')).toBe(true);
+ });
+
+ it('does not count the dialog’s own timeout, where nothing arrived', () => {
+ // The line between the two: `succeed` and `fail` are the server's verdicts,
+ // `timeout` is this dialog's. Nothing arrived that could have written, and the
+ // close path — whose cancel can BE the write — is what re-reads there.
+ expect(terminalArrivalMovedRows('timeout')).toBe(false);
+ });
+
+ it('does not count an arrival the latch already ignored, or a pending one', () => {
+ // `ignore` means the terminal it would report was already handled by whichever
+ // arrival got there first, and that one re-read.
+ expect(terminalArrivalMovedRows('ignore')).toBe(false);
+ expect(terminalArrivalMovedRows('continue')).toBe(false);
+ });
+
+ it('leaves the dialog one place that says the rows behind it moved', () => {
+ // Structural, and the point of the extraction: the two success branches used
+ // to refetch inline, which is why the failure between them refetched nowhere.
+ // One predicate decides for all three, and one owner carries it out — so the
+ // parent's callback is reached from exactly one line.
+ const dialog = readFileSync(join(__dirname, 'OAuthConnectDialog.tsx'), 'utf8');
+
+ // The second argument is round 16's: silence became the default, so the arrival
+ // that IS the account of record for the view it just settled says so out loud.
+ expect(dialog).toMatch(
+ /if \(terminalArrivalMovedRows\(step\.action\)\) rowsBehindAreStale\(undefined, true\);/,
+ );
+ expect((dialog.match(/onConnectedRef\.current\(\)/g) ?? []).length).toBe(1);
+ // And that owner no longer asks which journey it is before re-reading: a
+ // create's `oauth_cancel` commits the source it was told to throw away.
+ expect(dialog).not.toMatch(/if \(!isReauth\) return;/);
+ });
+});
+
+describe('failureLanded — whose account of the rows is the one on screen', () => {
+ it('accepts the failure the authority actually latched', () => {
+ expect(failureLanded('fail')).toBe(true);
+ });
+
+ it('refuses an arrival that reached an already-settled view', () => {
+ // The finding this pins. A poll can settle terminally with `discovery_failed`
+ // AND a non-empty `interrupted_pairs`; a paste submit rejecting afterwards is
+ // still `isCurrent()` — settling changes neither the authority nor the flow id —
+ // so it used to hand its own (empty) list to the owner and erase the gap report
+ // while `flowStep` correctly kept the poll's sentence above it.
+ expect(failureLanded('ignore')).toBe(false);
+ });
+
+ it('refuses the states no error arrival can produce', () => {
+ // `flowStep` answers an `error` event with `fail` or `ignore` and nothing else,
+ // so these are unreachable from the two call sites — pinned so a later branch
+ // that starts producing one of them has to come back to this rule.
+ expect(failureLanded('timeout')).toBe(false);
+ expect(failureLanded('succeed')).toBe(false);
+ expect(failureLanded('continue')).toBe(false);
+ });
+
+ it('gates the pairs at every catch that carries them, and nothing else', () => {
+ // Structural: the two `catch` sites are the only places a failure's pairs enter
+ // the owner, and each has to hand over the authority's own answer. The reorder
+ // is the substance of the fix — the transition has to have happened before the
+ // pairs are offered, or there is no answer to hand over.
+ const dialog = readFileSync(join(__dirname, 'OAuthConnectDialog.tsx'), 'utf8');
+ const carrying = [...dialog.matchAll(/rowsBehindAreStale\(failure[^)]*\)/g)].map((m) => m[0]);
+
+ // Three: the start rejection, the status poll's, and the paste submit's. The
+ // start one cannot reach a settled view today and asks regardless — a site that
+ // is right because of where it sits stops being right when it is moved.
+ expect(carrying.length).toBe(3);
+ for (const call of carrying) expect(call).toMatch(/failureLanded\(step\.action\)/);
+ // And the refetch is still owed on the ignored path: the gate is the second
+ // argument, never a reason to skip the call.
+ expect(dialog).not.toMatch(/if \(failureLanded\(/);
+ });
+
+ it('makes silence the default, and lets exactly one arrival opt out of it', () => {
+ // Round 16's finding, and why it is fixed at the DEFAULT rather than at the two
+ // call sites that had it wrong. This component outlives the attempt: both hosts
+ // leave it mounted and toggle `open`, so `stranded` survives a close, and a
+ // request abandoned by attempt A can land after attempt B has put its own gap
+ // report on screen — one click away, since closing a re-login and starting
+ // another on a different source does exactly that. The two answers are not
+ // equally wrong. Forgetting to speak costs nothing, because the refetch runs
+ // either way; forgetting to stay silent writes an empty list over the one part
+ // of B's report that no later read of `/agents` reproduces.
+ const dialog = readFileSync(join(__dirname, 'OAuthConnectDialog.tsx'), 'utf8');
+
+ expect(dialog).toMatch(/pairsSpeak = false/);
+
+ // One opt-in, and it belongs to the arrival that just settled the view these
+ // pairs render under. Any other site passing a bare `true` is this bug again.
+ const speaking = [...dialog.matchAll(/rowsBehindAreStale\([^)]*true[^)]*\)/g)].map((m) => m[0]);
+ expect(speaking).toEqual(['rowsBehindAreStale(undefined, true)']);
+ expect(dialog).toMatch(
+ /terminalArrivalMovedRows\(step\.action\)\) rowsBehindAreStale\(undefined, true\)/,
+ );
+
+ // The two paths reached after the attempt is over take the default rather than
+ // restating it — including the release re-read, which awaits the cancel first
+ // and is therefore the latest-landing arrival in the file.
+ expect(dialog).toMatch(/const resolvedAfterAttempt = \(\) => rowsBehindAreStale\(\);/);
+ expect(dialog).toMatch(/reread: \(\) => rowsBehindAreStale\(\),/);
+ });
+});
+
+describe('releaseFlow — what a teardown does with the flow it opened', () => {
+ /** A journey, plus a recorder for the two things a teardown can do. */
+ const teardown = () => {
+ const log: string[] = [];
+ return {
+ log,
+ // Re-authing source A: the journey whose flow a successor can be handed.
+ journey: createFlowAuthority(() => {}, 'src_a'),
+ // `reusable` defaults to the reauth journey, which is the one the ownership
+ // rule was written for; the create cases below say so explicitly.
+ ops: (cancel: (() => Promise<unknown>) | null, reusable = true) => ({
+ cancel: cancel && (() => (log.push('cancel'), cancel())),
+ reread: () => log.push('reread'),
+ reusable,
+ }),
+ };
+ };
+
+ it('rereads only after the cancel it made has settled', async () => {
+ // Interleaving 3. The snapshot this teardown could have read said
+ // `awaiting_action`, and the poll in flight is about to report success — so
+ // this cancel reaches `_materialize_completed_oauth` and IS the write. A
+ // reread beside it, rather than after it, reads the rows before it happened.
+ const { log, journey, ops } = teardown();
+ const settle = deferred<void>();
+
+ const released = releaseFlow(journey, journey, ops(() => settle.promise));
+
+ expect(log).toEqual(['cancel']);
+ settle.resolve();
+ await released;
+ expect(log).toEqual(['cancel', 'reread']);
+ });
+
+ it('rereads even when its own cancel failed', async () => {
+ // The writes this journey already made upstream do not depend on the cleanup
+ // succeeding, so a failed cancel is a reason to reread rather than not to.
+ const { log, journey, ops } = teardown();
+ await releaseFlow(journey, journey, ops(() => Promise.reject(new Error('engine_down'))));
+ expect(log).toEqual(['cancel', 'reread']);
+ });
+
+ it('lets go once a newer journey owns the source flow', async () => {
+ // Interleaving 4. `POST …/reauth` reuses a live pending flow, so the
+ // replacement dialog FOR THE SAME ROW is polling THIS flow id. Cancelling it
+ // here ends a login the user is watching — and the reread is still owed,
+ // because the start this journey made had already committed the irreversible
+ // half.
+ const { log, journey, ops } = teardown();
+ const successor = createFlowAuthority(() => {}, 'src_a');
+
+ await releaseFlow(journey, successor, ops(() => Promise.resolve()));
+
+ expect(log).toEqual(['reread']);
+ });
+
+ it('CANCELS when the successor is re-authing a different row', async () => {
+ // `pending_reauth(source_id)` filters on `binding.source_id`, so the handover
+ // is keyed by SOURCE while ownership of the dialog's ref is global. Close a
+ // pending re-auth for A, open one for B before A's start returns, and A finds
+ // a live owner that can never be handed its flow: letting go there leaves A's
+ // authorization running until it expires.
+ const { log, journey, ops } = teardown();
+ const otherRow = createFlowAuthority(() => {}, 'src_b');
+
+ await releaseFlow(journey, otherRow, ops(() => Promise.resolve()));
+
+ expect(log).toEqual(['cancel', 'reread']);
+ });
+
+ it('CANCELS when the successor is a create, which adopts nothing', async () => {
+ // The same rule with the successor on the other route: a create has no source
+ // yet, so it is not the journey `pending_reauth` would hand this flow to.
+ const { log, journey, ops } = teardown();
+ const create = createFlowAuthority(() => {}, null);
+
+ await releaseFlow(journey, create, ops(() => Promise.resolve()));
+
+ expect(log).toEqual(['cancel', 'reread']);
+ });
+
+ it('CANCELS when nobody owns the flow, because an existing successor would be there', async () => {
+ // The handoff one beat earlier — a replacement whose own start is still in
+ // flight. That beat is not observable from here, and does not need to be: a
+ // successor takes the ref SYNCHRONOUSLY as its effect body runs, before its
+ // start request is awaited, so any successor that EXISTS has already put
+ // itself there by the time this late response reads the ref. `null` is
+ // therefore the user closing the dialog and not reopening it, and letting go
+ // leaves the authorization they just cancelled live until the server expires
+ // it — where the next re-auth for the row is handed exactly that flow and can
+ // materialize a login they declined. Only a successor that exists may suppress
+ // the cancel.
+ const { log, journey, ops } = teardown();
+ await releaseFlow(journey, null, ops(() => Promise.resolve()));
+ expect(log).toEqual(['cancel', 'reread']);
+ });
+
+ it('cancels an abandoned CREATE flow for its own second reason', async () => {
+ // Same ownership, other route, and the answer may not depend on the one above:
+ // `oauth_start` mints a fresh pending source id every call and never adopts a
+ // pending flow, so no successor could be handed this one whatever the ref
+ // holds. Read the route wrong and the abandoned authorization plus its
+ // registry binding stay live until the server expires them.
+ const { log, journey, ops } = teardown();
+ await releaseFlow(journey, null, ops(() => Promise.resolve(), false));
+ expect(log).toEqual(['cancel', 'reread']);
+ });
+
+ it('still asks ownership first for a reusable flow', async () => {
+ // The pair of the above, stated so neither can be simplified into the other:
+ // ownership answers 「is it still mine to cancel?」 and `reusable` answers
+ // 「could it ever have become someone else's?」. Only a `false` second answer
+ // makes the first one moot.
+ const { log, journey, ops } = teardown();
+ const successor = createFlowAuthority(() => {}, 'src_a');
+ await releaseFlow(journey, successor, ops(() => Promise.resolve(), true));
+ expect(log).toEqual(['reread']);
+ });
+
+ it('keeps the three questions independent', async () => {
+ // Stated on `flowLetGo` directly so none of them can be folded into another:
+ // ownership (「still mine?」), the route (「could it EVER move?」) and the
+ // successor's subject (「could THIS one be handed it?」).
+ const mine = createFlowAuthority(() => {}, 'src_a');
+ const sameRow = createFlowAuthority(() => {}, 'src_a');
+ const otherRow = createFlowAuthority(() => {}, 'src_b');
+
+ expect(flowLetGo(mine, mine, true)).toBe(false); // still mine
+ expect(flowLetGo(mine, sameRow, false)).toBe(false); // route never hands it over
+ expect(flowLetGo(mine, otherRow, true)).toBe(false); // successor cannot adopt it
+ expect(flowLetGo(mine, sameRow, true)).toBe(true); // all three agree
+ // No owner: nothing to hand it to. A successor is in the ref before it awaits
+ // anything, so an absent one is absent rather than pending.
+ expect(flowLetGo(mine, null, true)).toBe(false);
+ expect(flowLetGo(mine, null, false)).toBe(false);
+ });
+
+ it('has the successor in the ref before it awaits anything', () => {
+ // Structural, because the rule above is a claim about the dialog rather than a
+ // preference: `flowLetGo` may read an absent owner as 「no successor exists」
+ // only while every successor publishes itself before its first suspension
+ // point. Move that write below the start request and a real successor becomes
+ // invisible for a round trip, which is the interleaving the cancel above would
+ // then break.
+ const dialog = readFileSync(join(__dirname, 'OAuthConnectDialog.tsx'), 'utf8');
+ const claims = dialog.indexOf('const authority = createFlowAuthority(');
+ const takes = dialog.indexOf('flowAuthorityRef.current = authority;', claims);
+
+ expect(claims).toBeGreaterThan(-1);
+ expect(takes).toBeGreaterThan(claims);
+ expect(dialog.slice(0, takes)).not.toMatch(/\bawait\b/);
+ });
+
+ it('takes the journey each teardown is releasing from the dialog', () => {
+ // Structural, because the rule above is only as good as its wiring: both
+ // release sites state which journey they are in rather than letting
+ // `releaseFlow` infer it from an ownership that cannot tell the two apart.
+ const dialog = readFileSync(join(__dirname, 'OAuthConnectDialog.tsx'), 'utf8');
+ const releases = dialog.match(/releaseFlow\(/g) ?? [];
+ const declared = dialog.match(/reusable: isReauth/g) ?? [];
+
+ expect(releases.length).toBe(2);
+ expect(declared.length).toBe(releases.length);
+ // And the authority carries the row it is for, which is what makes the
+ // successor's subject answerable at all.
+ expect(dialog).toMatch(/createFlowAuthority\(setView, reauthId\)/);
+ });
+
+ it('still rereads when there was no flow to release', async () => {
+ // No flow id means no call to make, which is not the same as deciding a
+ // reread is unnecessary. A redundant reread is inert; a missing one is the bug.
+ const { log, journey, ops } = teardown();
+ await releaseFlow(journey, journey, ops(null));
+ expect(log).toEqual(['reread']);
+ });
+
+ it('leaves the cleanup cancel to the one owner that also rereads', () => {
+ // Structural, because this class has now been filed four times: both teardown
+ // paths hand their cancel to `releaseFlow`, so neither can decide for itself
+ // whether to reread — and no snapshot-shaped list is left behind to decide
+ // from. A `TERMINAL` array is what the retracted argument was made of.
+ const dialog = readFileSync(join(__dirname, 'OAuthConnectDialog.tsx'), 'utf8');
+ const calls = dialog.match(/modelsApi\.cancelOAuth\(/g) ?? [];
+ const handedOver = dialog.match(/=> modelsApi\.cancelOAuth\(/g) ?? [];
+
+ expect(calls.length).toBeGreaterThan(0);
+ expect(handedOver.length).toBe(calls.length);
+ expect(dialog).not.toMatch(/TERMINAL/);
+ });
+
+ it('hands the rows back on every exit a closed journey can still take', () => {
+ // Interleaving 6, structurally, because the reachable proof needs a DOM this
+ // repo's vitest does not have. THREE requests of one reauth journey can resolve
+ // after the dialog is gone — a start that rejects, a status read that
+ // materialized a just-succeeded flow, a poll that failed — and the close path's
+ // own re-read was issued while all three were still in flight, so it can predate
+ // their write. Each therefore re-reads on its way out, through one named owner.
+ //
+ // Exactly one guard may still return bare: the one at the TOP of `poll`, where
+ // nothing has been requested yet on that tick and so nothing can have written.
+ const dialog = readFileSync(join(__dirname, 'OAuthConnectDialog.tsx'), 'utf8');
+ const bare = dialog.match(/if \(cancelled\) return;/g) ?? [];
+ const handedBack = dialog.match(/if \(cancelled\) \{\s*resolvedAfterAttempt\(\);\s*return;\s*\}/g) ?? [];
+
+ expect(bare.length).toBe(1);
+ expect(handedBack.length).toBe(3);
+ // And the fourth exit — a start that SUCCEEDED after the close — reaches the
+ // same owner through the release it also has to make.
+ expect(dialog).toMatch(/reread: resolvedAfterAttempt,/);
+ });
+
+ it('counts the paste submit among those exits, on both of its outcomes', () => {
+ // Round 17's, and the reason the owner is no longer scoped to the effect: the
+ // submit could not reach it. Its two exits ask a different question — `cancelled`
+ // is 「the effect tore down」, `isCurrent()` is 「this attempt is still the one on
+ // screen」, which a mid-open restart also answers no — but they are the same fact
+ // about the rows, and both of them write before they can be dropped. The success
+ // went through `_materialize_completed_oauth` to be a success at all; the
+ // rejection can be `discovery_failed` raised one line after
+ // `_materialize_reauth` saved the source as 需处理 with its models stripped.
+ // Returning bare there left the close path's re-read — issued while the submit
+ // was in flight — as the last word on rows the submit changed afterwards.
+ const dialog = readFileSync(join(__dirname, 'OAuthConnectDialog.tsx'), 'utf8');
+ const superseded =
+ dialog.match(/if \(!isCurrent\(\)\) \{\s*resolvedAfterAttempt\(\);\s*return;\s*\}/g) ?? [];
+
+ expect(superseded.length).toBe(2);
+ expect(dialog).not.toMatch(/if \(!isCurrent\(\)\) return;/);
+ // Component scope, not effect scope, or the two above cannot see it.
+ expect(dialog).toMatch(/^ {2}const resolvedAfterAttempt = /m);
+ });
+
+ it('cancels the flow the request opened, not the one the view landed', () => {
+ // Round 17's other one. A start can come back ALREADY terminal, and that flow is
+ // deliberately never landed in the view — `startNeedsStatusRead` routes it
+ // through `poll` so that `settle` is what terminalizes it. Cleanup took its
+ // cancel id out of the view, so for exactly that start it found nothing and
+ // passed `cancel: null` — which `releaseFlow` is entitled to read as 「this
+ // journey never got a flow id」 when what had happened is that nobody told the
+ // view. Close during the status read and the flow stayed un-materialized;
+ // un-materialized is `not completed`, the only thing `pending_reauth` filters
+ // on, so `POST …/reauth` hands the next attempt on that source the login the
+ // close was abandoning — and reading its status is what commits it.
+ const dialog = readFileSync(join(__dirname, 'OAuthConnectDialog.tsx'), 'utf8');
+
+ expect(dialog).toMatch(/let openedFlowId: string \| null = null;/);
+ expect(dialog).toMatch(/openedFlowId = started\.flow_id;/);
+ expect(dialog).toMatch(/cancel: opened \? \(\) => modelsApi\.cancelOAuth\(opened\) : null,/);
+ // The view is not asked, because it was never the thing that knew.
+ expect(dialog).not.toMatch(/authority\.current\(\)\.flow;/);
+ });
+});
diff --git a/ui/src/components/settings/models/asyncLifetime.ts b/ui/src/components/settings/models/asyncLifetime.ts
index aecff6503..6000b413d 100644
--- a/ui/src/components/settings/models/asyncLifetime.ts
+++ b/ui/src/components/settings/models/asyncLifetime.ts
@@ -1,7 +1,7 @@
// Async ownership rules extracted from the Models components so interleavings can
// be exercised directly: which request may land, when a drawer re-seeds, and
// whether a connect-flow transition may change an already terminal view.
-import type { AgentMenu, AgentSupply, OAuthFlow } from './types';
+import type { AgentMenu, AgentSupply, OAuthFlow, OAuthFlowState } from './types';
// ── Latest async result ────────────────────────────────────────────────────
/**
@@ -103,6 +103,17 @@ export type FlowView = { flow: OAuthFlow | null; errorKey: string | null; settle
export const initialFlowView: FlowView = { flow: null, errorKey: null, settled: false };
+/**
+ * The states in which the SERVER has reported a flow finished — one list, because
+ * two places asking 「is this over?」 with two enumerations is how they drift.
+ *
+ * `timeout` is deliberately absent: it is the dialog's own verdict about a flow
+ * the server still considers live, which is why it arrives as a `tick` and not as
+ * a state at all.
+ */
+export const flowStateTerminal = (state: OAuthFlowState): boolean =>
+ state === 'success' || state === 'failed' || state === 'cancelled';
+
export const flowStep = (view: FlowView, event: FlowEvent): { view: FlowView; action: FlowAction } => {
if (event.kind === 'reset') return { view: { ...initialFlowView }, action: 'continue' };
// Nothing gets to change a finished flow — checked before the event is read, so
@@ -128,8 +139,10 @@ export const flowStep = (view: FlowView, event: FlowEvent): { view: FlowView; ac
const flow = event.flow;
if (flow.state === 'success') return { view: { flow, errorKey: null, settled: true }, action: 'succeed' };
// `settled` means terminal, not successful: a failed flow is just as finished,
- // and a later arrival has just as little business reopening it.
- if (flow.state === 'failed' || flow.state === 'cancelled') {
+ // and a later arrival has just as little business reopening it. Which states
+ // those are is `flowStateTerminal`'s to say — success has already returned, so
+ // this is「terminal」and not a second, driftable list of the unsuccessful ones.
+ if (flowStateTerminal(flow.state)) {
return {
view: {
flow,
@@ -142,9 +155,50 @@ export const flowStep = (view: FlowView, event: FlowEvent): { view: FlowView; ac
return { view: { flow, errorKey: null, settled: false }, action: 'continue' };
};
+/**
+ * Whether a START response has to be re-read through the status route before it
+ * may settle the dialog — which EVERY terminal start does.
+ *
+ * `POST …/reauth` REUSES a live pending flow — it only opens a new one once the
+ * old one failed or was cancelled — so a start can come back already terminal,
+ * and the start envelope carries the flow alone.
+ *
+ * This used to ask whether that envelope was RICH ENOUGH: a success needs the
+ * `{source, recovered, interrupted_pairs}` tail only status carries, while a
+ * failure's `error_key` is the whole message, so a failure could latch. But
+ * 「enough to DISPLAY」 is not 「enough to SETTLE」. Settling stops the poll — the
+ * next tick exits on the terminal latch — and `oauth_start` hands back the
+ * adapter's flow without materializing it. The materialization lives one route
+ * over: `oauth_status` → `_materialize_completed_oauth`, which is what runs
+ * `_fail_closed_hub_reauth` on an unsuccessful hub terminal, strips the discovered
+ * models and persists the source as 需处理. Latch a failed start and none of it
+ * happens: the dialog explains a failure while the row behind it still draws
+ * healthy and still supplies the ● 当前 it no longer can, the binding stays
+ * pending, and the missing write only lands when the user eventually closes the
+ * dialog and `oauth_cancel` performs it as a side effect of cancelling.
+ *
+ * So this does not try to know WHICH terminals owe server-side work — that is a
+ * fact about the server (`_is_hub_unsuccessful_terminal` is `hub` ×
+ * `{failed, cancelled}`, and a create's orphan cleanup keys off the retained
+ * material) and a guard over the envelope may not decide it. Every terminal start
+ * is read through the one route entitled to report a terminal; the dialog shows
+ * whatever that answers, and `terminalArrivalMovedRows` then re-reads the rows.
+ * A non-terminal start needs nothing: it is polled, as it always was.
+ */
+export const startNeedsStatusRead = (flow: OAuthFlow): boolean => flowStateTerminal(flow.state);
+
export type FlowAuthority = {
current: () => FlowView;
transition: (event: FlowEvent) => ReturnType<typeof flowStep>;
+ /**
+ * WHAT this journey is for: the source id a re-auth is repairing, or `null` for
+ * a create, which has no source yet.
+ *
+ * Carried on the authority because the authority is the journey's identity, and
+ * `flowLetGo` has to ask about the identity of a journey that is not the one
+ * asking — see there for the only question it answers.
+ */
+ subject: string | null;
};
/**
@@ -152,7 +206,10 @@ export type FlowAuthority = {
* that may land a new one. Keeping only `flow` at the landing site would let a
* caller silently drop `settled` and reopen an already terminal flow.
*/
-export const createFlowAuthority = (land: (view: FlowView) => void): FlowAuthority => {
+export const createFlowAuthority = (
+ land: (view: FlowView) => void,
+ subject: string | null,
+): FlowAuthority => {
let current: FlowView = { ...initialFlowView };
return {
@@ -163,8 +220,173 @@ export const createFlowAuthority = (land: (view: FlowView) => void): FlowAuthori
land(current);
return step;
},
+ subject,
};
};
/** Whether an action ends the flow, so the caller stops polling. */
export const isDone = (action: FlowAction): boolean => action !== 'continue';
+
+/**
+ * Whether a terminal ARRIVAL moved the rows the page behind the dialog draws.
+ *
+ * Both terminals the server reported are writes, and asking 「did it succeed?」 is
+ * what left one of them re-reading nothing. A success materializes the source (or
+ * the repair) inside the very call that first reports it. A `failed` hub reauth
+ * has already run `_fail_closed_hub_reauth` on its way to answering — the
+ * discovered models are stripped and the source is persisted as 需处理 — so the
+ * dialog explains a failure while the page behind it still draws that source as
+ * healthy, still supplying the ● 当前 it no longer can.
+ *
+ * `timeout` is not one of them, and that is the line this draws: it is the
+ * dialog's OWN verdict, with nothing arrived that could have written. What
+ * corrects the rows there is the close path, whose cancel can BE the write
+ * (`releaseFlow` below) and which re-reads unconditionally for that reason.
+ */
+export const terminalArrivalMovedRows = (action: FlowAction): boolean =>
+ action === 'succeed' || action === 'fail';
+
+/**
+ * Whether a FAILED status poll may speak for the journey.
+ *
+ * A poll is a reader; the paste submit is the writer of record. `GET …/status`
+ * failing while a submit is outstanding says nothing about whether that submit
+ * committed — and the submit's own response is the only arrival that carries the
+ * terminal tail (`repaired` / `created`) at all. Latching the reader's error
+ * settles the view, `flowStep` above then correctly ignores the success that
+ * follows, and the dialog says 授权失败 over a credential the server did replace:
+ * no toast, no refetch, no repair verdict, on a journey that worked.
+ *
+ * Dropping it is safe precisely because the other authority is guaranteed to
+ * answer: the submit settles the view itself, with its success or through its own
+ * catch. So the flow is not left hanging on a poll — and the caller keeps reading
+ * meanwhile, which is what preserves the deadline for a submit that never returns.
+ *
+ * With no submit outstanding a poll IS the only authority — but only when the ROUTE
+ * answered. That same materializing call is the reason: a status read that commits
+ * the create or the repair and then loses its response (a dropped connection, a
+ * proxy's HTML 502, a body that will not parse) throws a failure `call()` minted,
+ * not one the server named. Settling on it declares a terminal nobody reported, over
+ * an operation that may have committed — the dialog says 授权失败 on a source the
+ * server did create, and an ordinary connect retried from there mints a second one.
+ * `serverNamed` is the same discriminator `mayHaveWritten` reads for the refetch,
+ * asked here about speech instead of writes: a refusal that named itself knows the
+ * login went nowhere; a transport failure knows nothing at all.
+ *
+ * Dropping it is bounded either way — the caller keeps polling, and the deadline at
+ * the top of each tick is the dialog's own verdict when nothing ever answers.
+ */
+export const pollFailureSettles = (submitOutstanding: boolean, serverNamed: boolean): boolean =>
+ !submitOutstanding && serverNamed;
+
+/**
+ * Whether the failure that just arrived is the one now ON SCREEN.
+ *
+ * `flowStep` answers `ignore` to everything that reaches a view already settled, so
+ * a paste submit rejecting after the poll latched `discovery_failed` leaves the
+ * sentence the user is reading belonging to the POLL. The stranded pairs render
+ * directly beneath that sentence, as the cost of the failure it names, so they may
+ * only come from the arrival that produced it: the late one's own list is empty —
+ * the write that stranded those rows happened on the other request — and would
+ * erase the gap report rather than restate it.
+ *
+ * Deliberately not `terminalArrivalMovedRows`, which reads the same `action` to
+ * answer a different question. Whether a request may have WRITTEN is independent of
+ * whether it may SPEAK, and the refetch beside these pairs is owed either way.
+ */
+export const failureLanded = (action: FlowAction): boolean => action === 'fail';
+
+/**
+ * Whether a journey may walk away from the flow it opened without cancelling it —
+ * i.e. whether SOMEONE ELSE can still be handed that exact flow.
+ *
+ * Three facts have to agree, and each answers a different question:
+ *
+ * 1. Ownership — 「is it still mine to cancel?」 `POST …/reauth` REUSES a live
+ * pending flow, so a teardown that cancels after ownership moved does not clean
+ * up after itself: it ends the login the user is watching in the dialog that
+ * replaced it. The answer therefore depends on WHEN a path asks. The effect's
+ * own cleanup asks at the instant ownership transfers and still holds it, while
+ * a start whose dialog closed mid-request asks after that same cleanup already
+ * released it. Identical call, right in one place and wrong in the other.
+ * 2. The route — 「could it EVER have become someone else's?」 `oauth_start` mints a
+ * fresh pending source id on every call and never looks for a pending flow, so
+ * a create's flow belongs to the one journey that opened it. Ownership alone
+ * cannot say this, which is why `routeReuses` is asked separately: on a create
+ * there is no successor coming for that flow at all, so it dies with the journey
+ * that opened it.
+ * 3. The successor's SUBJECT — 「could this particular one be handed my flow?」
+ * `pending_reauth(source_id)` filters on `binding.source_id`, so the handover is
+ * keyed by SOURCE while ownership of this ref is global to the dialog. Close a
+ * pending re-auth for source A, open one for source B before A's start returns,
+ * and A finds a live owner that can never adopt its flow: withholding the cancel
+ * there leaves A's authorization running until it expires. So the route being
+ * reusable is a claim about a class of successors, not about whoever happens to
+ * hold the ref.
+ *
+ * A `null` owner is NOT let go, and that is a fact about this dialog rather than a
+ * preference. Every successor takes authority SYNCHRONOUSLY in the effect body —
+ * `flowAuthorityRef.current = authority` in `OAuthConnectDialog.tsx`, before the
+ * start request is awaited — so a successor that exists has already put itself
+ * there by the time any late response reads the ref. `null` therefore cannot mean
+ * 「a successor is about to」; it means the user closed the dialog and did not
+ * reopen it.
+ *
+ * An earlier revision read it the other way and withheld the cancel to protect a
+ * flow some future start might adopt. What that actually left behind was a live
+ * authorization the user had just cancelled: the server holds it until it times
+ * out, and the next re-auth for that source is handed exactly that flow and can
+ * materialize it — a login the user declined, completing later. A start after the
+ * cancel just mints a fresh flow, so the real trade is one extra round trip
+ * against honouring 取消, and only a successor that EXISTS may suppress it.
+ */
+export const flowLetGo = (
+ journey: FlowAuthority,
+ owner: FlowAuthority | null,
+ routeReuses: boolean,
+): boolean =>
+ owner !== null &&
+ owner !== journey &&
+ routeReuses &&
+ owner.subject === journey.subject;
+
+/**
+ * Hands back the flow a journey opened, and is the ONLY authorization for a
+ * teardown cancel.
+ *
+ * Whether the cancel is authorized is `flowLetGo`'s call — see there for the three
+ * separate facts that have to agree before a journey may walk away from a flow.
+ *
+ * Rereading is unconditional, and this function is not given the flow so that no
+ * caller can argue otherwise from it. `POST /oauth/cancel` is not always a
+ * cancel — `oauth_cancel` routes a `success` flow, and a failed hub reauth, into
+ * `_materialize_completed_oauth` — so the call can BE the write. The only state a
+ * caller could branch on is the last POLLED snapshot, which an in-flight poll or
+ * a paste submit can terminalize between that read and the cancel landing. An
+ * earlier revision branched on exactly that, from a list named `TERMINAL`;
+ * naming a snapshot after a fact did not make it one.
+ *
+ * A `null` cancel means the journey never got a flow id — there is no call to
+ * make, which is not the same as deciding not to make one.
+ */
+export const releaseFlow = async (
+ journey: FlowAuthority,
+ owner: FlowAuthority | null,
+ ops: {
+ cancel: (() => Promise<unknown>) | null;
+ reread: () => void;
+ /** Whether the ROUTE can hand this same flow to a successor journey. */
+ reusable: boolean;
+ },
+): Promise<void> => {
+ if (ops.cancel && !flowLetGo(journey, owner, ops.reusable)) {
+ try {
+ await ops.cancel();
+ } catch {
+ // Nothing to show — the dialog this belonged to is already gone. The reread
+ // below still has to run: the writes upstream of this call do not depend on
+ // it succeeding.
+ }
+ }
+ ops.reread();
+};
diff --git a/ui/src/components/settings/models/dialogFields.test.tsx b/ui/src/components/settings/models/dialogFields.test.tsx
new file mode 100644
index 000000000..38ba4783f
--- /dev/null
+++ b/ui/src/components/settings/models/dialogFields.test.tsx
@@ -0,0 +1,114 @@
+// A label that does not name its control, asserted the only way that means
+// anything: from the rendered markup.
+//
+// The defect this file exists for was invisible in review — a visible 「New API
+// key」 label sat directly above the password input, and assistive tech still
+// reached an unnamed field, because nothing connected the two. `Field` now mints
+// the id, so the check is that the id actually ARRIVES: `Input`/`Select` both
+// spread onto their native element, and a primitive that stopped doing so would
+// take the association down with it while looking identical on screen.
+import { readFileSync, readdirSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { KeyRound } from 'lucide-react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { describe, expect, it } from 'vitest';
+
+import { Input } from '@/components/ui/input';
+import { Select } from '@/components/ui/select';
+import { Field } from './dialogFields';
+
+/** The label's target and the control's own id, as the browser would read them. */
+const pair = (markup: string) => ({
+ labelFor: /<label[^>]*\bfor="([^"]*)"/.exec(markup)?.[1],
+ controlId: /<(?:input|select)[^>]*\bid="([^"]*)"/.exec(markup)?.[1],
+});
+
+describe('Field', () => {
+ it('names an icon-inset input', () => {
+ const { labelFor, controlId } = pair(
+ renderToStaticMarkup(
+ <Field label="New API key" mono icon={KeyRound}>
+ {(id) => <Input id={id} type="password" />}
+ </Field>,
+ ),
+ );
+ expect(labelFor).toBeTruthy();
+ expect(controlId).toBe(labelFor);
+ });
+
+ it('names a control with no icon inset', () => {
+ // The vendor <select> takes the same path minus the wrapper — the branch that
+ // renders `children(id)` bare is the one that could drop the argument.
+ const { labelFor, controlId } = pair(
+ renderToStaticMarkup(
+ <Field label="Vendor">
+ {(id) => (
+ <Select id={id}>
+ <option value="anthropic">Anthropic</option>
+ </Select>
+ )}
+ </Field>,
+ ),
+ );
+ expect(labelFor).toBeTruthy();
+ expect(controlId).toBe(labelFor);
+ });
+
+ it('gives each field its own id', () => {
+ // Two fields in one dialog: a shared constant id would associate the second
+ // label with the first control, which reads as correct in the markup diff.
+ const markup = renderToStaticMarkup(
+ <>
+ <Field label="One">{(id) => <Input id={id} />}</Field>
+ <Field label="Two">{(id) => <Input id={id} />}</Field>
+ </>,
+ );
+ const ids = [...markup.matchAll(/<input[^>]*\bid="([^"]*)"/g)].map((m) => m[1]);
+ expect(ids).toHaveLength(2);
+ expect(new Set(ids).size).toBe(2);
+ });
+
+ it('renders a hint only when there is one', () => {
+ const withHint = renderToStaticMarkup(
+ <Field label="Base URL" hint="Leave empty for the default">
+ {(id) => <Input id={id} />}
+ </Field>,
+ );
+ expect(withHint).toContain('Leave empty for the default');
+ expect(renderToStaticMarkup(<Field label="Base URL">{(id) => <Input id={id} />}</Field>)).not.toContain('<p');
+ });
+});
+
+describe('the class: the models dialogs do not hand-roll a field', () => {
+ const here = dirname(fileURLToPath(import.meta.url));
+ const files = readdirSync(here, { recursive: true, encoding: 'utf8' }).filter(
+ (f) => /\.tsx$/.test(f) && !/\.test\.tsx$/.test(f),
+ );
+ const read = (f: string) => readFileSync(join(here, f), 'utf8');
+
+ it('sweeps a non-trivial file set', () => {
+ expect(files.length).toBeGreaterThan(10);
+ expect(files).toContain('ReplaceKeyDialog.tsx');
+ });
+
+ /**
+ * An upper bound, not an equality: a NEW file that writes its own `<label>` is
+ * the regression, while `menus/AddCustomModelDialog.tsx` is a pre-existing local
+ * copy from another lane (disclosed in the PR, not silently rewritten here) and
+ * this list must not start failing on the day someone deletes it.
+ */
+ const MAY_WRITE_A_LABEL = ['dialogFields.tsx', join('menus', 'AddCustomModelDialog.tsx')];
+
+ it('leaves <label> to the shared field', () => {
+ const handRolled = files.filter((f) => /<label\b/.test(read(f)));
+ expect(handRolled.filter((f) => !MAY_WRITE_A_LABEL.includes(f))).toEqual([]);
+ });
+
+ it('has no user-visible placeholder outside the locale bundles', () => {
+ // `placeholder="sk-…"` was display text a translator could never reach. The
+ // literal form is the tell; `placeholder={t(...)}` is the shape that stays.
+ expect(files.filter((f) => /placeholder="/.test(read(f)))).toEqual([]);
+ });
+});
diff --git a/ui/src/components/settings/models/dialogFields.tsx b/ui/src/components/settings/models/dialogFields.tsx
new file mode 100644
index 000000000..8c1b32b64
--- /dev/null
+++ b/ui/src/components/settings/models/dialogFields.tsx
@@ -0,0 +1,76 @@
+// The credential dialogs' one field primitive: a label, the control, an optional
+// icon inset, an optional hint — with the label always NAMING the control.
+//
+// Promoted here from AddApiKeyDialog when the key-replacement dialog needed the
+// same 「新的 API Key」 field: two dialogs asking for the same credential must look
+// like the same field, and the alternative — a second pair of local copies — is
+// how the two drift by a pixel and a font weight.
+//
+// It exports ONE concept now, and the id is the reason. As a label and a wrapper
+// exported separately, the association was every call site's job, and every call
+// site skipped it: a password input reached assistive tech unnamed while a visible
+// 「New API key」 label sat directly above it. `Field` mints the id and hands it to
+// the control, so the pairing is not something a caller can forget — there is no
+// arrangement of these parts that yields an unlabelled input.
+import * as React from 'react';
+
+import { cn } from '@/lib/utils';
+
+/** Never exported: a label that does not name a control is the defect above, so
+ * `htmlFor` is required and `Field` is the only thing that can supply it. */
+const FieldLabel: React.FC<{ htmlFor: string; mono?: boolean; children: React.ReactNode }> = ({
+ htmlFor,
+ mono,
+ children,
+}) => (
+ <label
+ htmlFor={htmlFor}
+ className={cn(
+ 'text-muted',
+ mono
+ ? 'font-mono text-[11px] font-medium uppercase tracking-wide'
+ : 'text-[12px] font-semibold text-foreground',
+ )}
+ >
+ {children}
+ </label>
+);
+
+/** The glyph inset. Local for the same reason: on its own it invites a bare
+ * `<Input>` child, which is exactly the child that arrives unnamed. */
+const IconField: React.FC<{
+ icon: React.ComponentType<{ className?: string }>;
+ children: React.ReactNode;
+}> = ({ icon: Icon, children }) => (
+ <div className="relative">
+ <Icon className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted" />
+ {children}
+ </div>
+);
+
+/**
+ * One labelled field. `children` is a function because the id has to reach the
+ * control: taking it as a prop would let a caller pass its own and drift, and
+ * cloning the child to inject it would do the same thing invisibly.
+ *
+ * `icon` is optional because a `<Select>` carries its own chevron; `hint` because
+ * only two of the four fields explain themselves.
+ */
+export const Field: React.FC<{
+ label: React.ReactNode;
+ children: (id: string) => React.ReactNode;
+ mono?: boolean;
+ icon?: React.ComponentType<{ className?: string }>;
+ hint?: React.ReactNode;
+}> = ({ label, children, mono, icon, hint }) => {
+ const id = React.useId();
+ return (
+ <div className="flex flex-col gap-2">
+ <FieldLabel htmlFor={id} mono={mono}>
+ {label}
+ </FieldLabel>
+ {icon ? <IconField icon={icon}>{children(id)}</IconField> : children(id)}
+ {hint ? <p className="text-[12px] leading-relaxed text-muted">{hint}</p> : null}
+ </div>
+ );
+};
diff --git a/ui/src/components/settings/models/eventFeed.test.ts b/ui/src/components/settings/models/eventFeed.test.ts
new file mode 100644
index 000000000..9ba5fbe90
--- /dev/null
+++ b/ui/src/components/settings/models/eventFeed.test.ts
@@ -0,0 +1,244 @@
+// The feed merge, in both directions.
+//
+// The regression these pin: 最近切换 was fetched once at mount, so a write that
+// filed an event (a failing 试跑 cooling its own head down) changed the source row
+// while the line explaining that change stayed invisible until a full reload. The
+// post-write refresh now re-reads the head — which is only safe if it cannot throw
+// away the rows 加载更早 已经 paged in, and cannot splice a hole into the sequence.
+//
+// And the follow-on: the rows and 「is there anything older」 are one fact. Moving
+// only the rows is how the replace branch left 加载更早 claiming an end it had just
+// discarded, over history that certainly still existed.
+//
+// And its own follow-on, one interleaving further out: that replacement can happen
+// while a tail read is in flight, and a tail page is only about the feed it was
+// asked of. Merged into the replacement it splices two ends together with the
+// middle missing — and unlike a replacement, unrecoverably, because paging goes on
+// from the old cursor.
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ emptyFeed,
+ feedAfterHeadRead,
+ feedAfterTailRead,
+ feedTailCursor,
+ headReadGapped,
+ mergeEventFeed,
+ type EventFeed,
+} from './eventFeed';
+import type { ResolutionEvent } from './types';
+
+/** A feed row: only `id` matters to the merge, and only identity to the rest. */
+const ev = (id: string): ResolutionEvent =>
+ ({ id, ts: '2026-07-30T10:00:00Z', agent: 'claude', kind: 'cooldown' }) as ResolutionEvent;
+
+const ids = (events: ResolutionEvent[]) => events.map((e) => e.id);
+
+/** On-screen feed with the tail already reached, unless said otherwise. */
+const onScreen = (rows: ResolutionEvent[], exhausted = true): EventFeed => ({
+ events: rows,
+ exhausted,
+});
+
+describe('mergeEventFeed — one list from two pages of the same feed', () => {
+ it('keeps the given order and drops the overlap', () => {
+ expect(ids(mergeEventFeed([ev('c'), ev('b')], [ev('b'), ev('a')]))).toEqual(['c', 'b', 'a']);
+ });
+
+ it('lets the FIRST argument win a duplicated row', () => {
+ // Which is what makes a head re-read the fresher copy of a row already held.
+ const fresh = { ...ev('b'), kind: 'recover' } as ResolutionEvent;
+ const merged = mergeEventFeed([fresh], [ev('b')]);
+ expect(merged).toHaveLength(1);
+ expect(merged[0].kind).toBe('recover');
+ });
+
+ it('is a no-op for an empty page in either position', () => {
+ expect(ids(mergeEventFeed([ev('a')], []))).toEqual(['a']);
+ expect(ids(mergeEventFeed([], [ev('a')]))).toEqual(['a']);
+ });
+
+ it('never sorts by id, because ids do not order', () => {
+ // `evt_<uuid4hex>`: sorting would scramble the feed into a plausible-looking
+ // random permutation. Given newest-first pages, output order is positional.
+ const merged = mergeEventFeed([ev('evt_ff'), ev('evt_00')], [ev('evt_aa')]);
+ expect(ids(merged)).toEqual(['evt_ff', 'evt_00', 'evt_aa']);
+ });
+});
+
+describe('headReadGapped — whether the two pages still touch', () => {
+ it('is false when the head page overlaps what is on screen', () => {
+ expect(headReadGapped([ev('d'), ev('c')], [ev('c'), ev('b'), ev('a')])).toBe(false);
+ });
+
+ it('is TRUE when more than a page landed in between', () => {
+ // Nothing shared: every row between the two is missing, and a merge would read
+ // as one continuous history.
+ expect(headReadGapped([ev('z'), ev('y')], [ev('c'), ev('b')])).toBe(true);
+ });
+
+ it('is not about page fullness', () => {
+ // A full head page is true of every feed with a page of history in it, new or
+ // not — the discriminator this deliberately is not.
+ const held = [ev('c'), ev('b'), ev('a')];
+ expect(headReadGapped([ev('d'), ev('c'), ev('b')], held)).toBe(false);
+ });
+
+ it('finds no hole against an empty screen or an empty page', () => {
+ expect(headReadGapped([ev('a')], [])).toBe(false);
+ expect(headReadGapped([], [ev('a')])).toBe(false);
+ });
+});
+
+describe('feedAfterHeadRead — what the post-write refresh leaves on screen', () => {
+ it('merges the new rows in front of the paged-in tail', () => {
+ const held = onScreen([ev('c'), ev('b'), ev('a')]);
+ expect(ids(feedAfterHeadRead(held, [ev('d'), ev('c')]).events)).toEqual(['d', 'c', 'b', 'a']);
+ });
+
+ it('replaces rather than splices when the pages no longer touch', () => {
+ // The paged rows are still reachable by paging; a spliced feed is reachable by
+ // nothing, because no row in it looks wrong.
+ const held = onScreen([ev('c'), ev('b')]);
+ expect(ids(feedAfterHeadRead(held, [ev('z'), ev('y')]).events)).toEqual(['z', 'y']);
+ });
+
+ it('holds the screen when the head read came back empty', () => {
+ expect(ids(feedAfterHeadRead(onScreen([ev('b'), ev('a')]), []).events)).toEqual(['b', 'a']);
+ });
+
+ it('keeps a merge from touching exhaustion, in either state', () => {
+ // A claim about the TAIL, and the tail is still on screen after a merge.
+ expect(feedAfterHeadRead(onScreen([ev('b'), ev('a')], true), [ev('c'), ev('b')]).exhausted).toBe(
+ true,
+ );
+ expect(
+ feedAfterHeadRead(onScreen([ev('b'), ev('a')], false), [ev('c'), ev('b')]).exhausted,
+ ).toBe(false);
+ });
+
+ it('CLEARS exhaustion when it replaces a gapped feed', () => {
+ // The regression: 加载更早 disappeared over rows that certainly still exist,
+ // because the flag outlived the list it was a claim about. Disjoint pages mean
+ // a page-plus landed in between, so the discarded rows are older than
+ // everything kept — 「nothing older」 is precisely what stopped being true.
+ expect(feedAfterHeadRead(onScreen([ev('c'), ev('b')], true), [ev('z')]).exhausted).toBe(false);
+ });
+});
+
+describe('feedTailCursor — the row a tail read continues from', () => {
+ it('is the last row on screen', () => {
+ expect(feedTailCursor(onScreen([ev('c'), ev('b'), ev('a')]))).toBe('a');
+ });
+
+ it('is null for a feed with no tail yet, which is what reading the top is', () => {
+ expect(feedTailCursor(emptyFeed)).toBeNull();
+ });
+});
+
+describe('feedAfterTailRead — 加载更早, and the first page at mount', () => {
+ it('appends the older page and reads the end off a short one', () => {
+ const held = onScreen([ev('c'), ev('b')], false);
+ const next = feedAfterTailRead(held, [ev('b'), ev('a')], 20, 'b');
+ expect(ids(next.events)).toEqual(['c', 'b', 'a']);
+ expect(next.exhausted).toBe(true);
+ });
+
+ it('keeps paging open on a full page', () => {
+ expect(feedAfterTailRead(onScreen([ev('b')], true), [ev('a')], 1, 'b').exhausted).toBe(false);
+ });
+
+ it('reads the mount page as the tail it also is', () => {
+ // Same owner as 加载更早 deliberately: reaching the end is the same question,
+ // and a hand-rolled second copy is how the two drifted apart. Its cursor is
+ // null because it asked for the top, which is what an empty feed's tail is.
+ const first = feedAfterTailRead(emptyFeed, [ev('b'), ev('a')], 20, null);
+ expect(ids(first.events)).toEqual(['b', 'a']);
+ expect(first.exhausted).toBe(true);
+ expect(feedAfterTailRead(emptyFeed, [ev('b'), ev('a')], 2, null).exhausted).toBe(false);
+ });
+
+ it('starts from a feed with nothing to page back to', () => {
+ expect(emptyFeed.events).toEqual([]);
+ expect(emptyFeed.exhausted).toBe(true);
+ });
+
+ it('DROPS a page whose cursor is no longer the feed it was asked of', () => {
+ // The interleaving: 加载更早 requested the rows below 'b', and while it was in
+ // flight a mutation refresh found the feed gapped and replaced it. Appending
+ // here would put ['b','a'] straight under ['z','y'] and lose the middle for
+ // good — the next 加载更早 carries on below 'a' and never comes back for it.
+ const replaced = onScreen([ev('z'), ev('y')], false);
+ expect(feedAfterTailRead(replaced, [ev('b'), ev('a')], 20, 'b')).toBe(replaced);
+ });
+
+ it('drops both halves, not just the rows', () => {
+ // A page that may not speak for the rows may not speak for 「nothing older」:
+ // a short stale page setting exhaustion would hide 加载更早 over the very rows
+ // the replacement still needs it to reach.
+ const replaced = onScreen([ev('z')], false);
+ expect(feedAfterTailRead(replaced, [], 20, 'b').exhausted).toBe(false);
+ });
+
+ it('drops a mount page that lands after rows are already on screen', () => {
+ // Same rule, the other cursor: `null` means 「from the top」, and a feed with a
+ // tail is not the feed that question was about.
+ const held = onScreen([ev('c'), ev('b')], false);
+ expect(feedAfterTailRead(held, [ev('q')], 20, null)).toBe(held);
+ });
+
+ it('accepts a page whose cursor still holds after the feed grew at the HEAD', () => {
+ // Growing at the head does not move the tail, so the page still attaches — the
+ // ordinary case, and the reason this checks the cursor rather than identity.
+ const grown = onScreen([ev('d'), ev('c'), ev('b')], false);
+ expect(ids(feedAfterTailRead(grown, [ev('a')], 20, 'b').events)).toEqual(['d', 'c', 'b', 'a']);
+ });
+});
+
+describe('the page reads the feed through this owner', () => {
+ const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');
+
+ it('re-reads events in the shared post-write refresh', () => {
+ // The whole point: the refresh every mutation site already calls is what has
+ // to move the feed, not a probe-only twin bolted onto one call site.
+ expect(page).toMatch(/refreshAuthority\.run\([\s\S]*?modelsApi\.listEvents\(EVENT_PAGE\)/);
+ expect(page).toMatch(/if \(headEvents\) setFeed\(\(prev\) => feedAfterHeadRead\(prev, headEvents\)\)/);
+ });
+
+ it('lets the ancillary feed read fail without losing the rows', () => {
+ // A slow or broken /events must not veto the supply refresh: joined bare into
+ // the same Promise.all, one failing leg left repaired sources and the ● 当前
+ // the user just moved on screen as they were before the mutation.
+ expect(page).toMatch(/modelsApi\.listEvents\(EVENT_PAGE\)\.catch\(\(\) => null\)/);
+ expect(page).toMatch(/createLatestAsyncAuthority<\[Source\[\], AgentSupply\[\], ResolutionEvent\[\] \| null\]>/);
+ // Sources and agents are NOT tolerated the same way — they are what this
+ // refresh is for, and the caller's toast is what reports them failing.
+ expect(page).not.toMatch(/modelsApi\.list(Sources|Agents)\(\)\.catch/);
+ });
+
+ it('moves rows and end-of-feed together, through the owners', () => {
+ // One state, so no transition can move the rows and leave the flag behind.
+ expect(page).toMatch(/const \[feed, setFeed\] = React\.useState<EventFeed>\(emptyFeed\)/);
+ expect(page).toMatch(/setFeed\(\(prev\) => feedAfterTailRead\(prev, e, EVENT_PAGE, null\)\)/);
+ expect(page).toMatch(/setFeed\(\(prev\) => feedAfterTailRead\(prev, page, EVENT_PAGE, oldest\)\)/);
+ // Nothing left that could set one half on its own.
+ expect(page).not.toMatch(/setEventsExhausted|setEvents\(/);
+ // And no hand-rolled dedupe or page-length test outside the owners.
+ expect(page).not.toMatch(/new Set\(prev\.map/);
+ expect(page).not.toMatch(/\.length < EVENT_PAGE/);
+ });
+
+ it('reads 加载更早 off the same feed it renders', () => {
+ expect(page).toMatch(/hasMore=\{!feed\.exhausted\}/);
+ expect(page).toMatch(/events=\{feed\.events\}/);
+ // Through the owner, and the SAME cursor is handed back to the merge — the
+ // request and the answer have to be about one row for the check to mean
+ // anything, which a second hand-rolled read of the tail would not guarantee.
+ expect(page).toMatch(/const oldest = feedTailCursor\(feed\)/);
+ expect(page).toMatch(/modelsApi\.listEvents\(EVENT_PAGE, oldest\)/);
+ expect(page).not.toMatch(/feed\.events\[feed\.events\.length - 1\]/);
+ });
+});
diff --git a/ui/src/components/settings/models/eventFeed.ts b/ui/src/components/settings/models/eventFeed.ts
new file mode 100644
index 000000000..3a8d50d17
--- /dev/null
+++ b/ui/src/components/settings/models/eventFeed.ts
@@ -0,0 +1,137 @@
+// 最近切换 as a feed rather than a snapshot: it grows at the HEAD while 加载更早
+// pages from the TAIL, so both directions are merges into one accumulated list
+// and neither may throw the other's rows away.
+import type { ResolutionEvent } from './types';
+
+/**
+ * 最近切换 as the page knows it: the rows, and whether its far end has been seen.
+ *
+ * One value rather than two pieces of state because every transition moves both,
+ * and the one that moved only the rows is the bug this type exists to make
+ * unwriteable: a head read that REPLACES a gapped feed throws away the tail the
+ * exhaustion flag was a claim about, and 加载更早 then offers no way back to rows
+ * that certainly still exist.
+ */
+export type EventFeed = {
+ events: ResolutionEvent[];
+ /** Whether the TAIL has been reached, i.e. 加载更早 has nothing left to fetch. */
+ exhausted: boolean;
+};
+
+/** Before anything has been read: no rows, and nothing to page back to yet. */
+export const emptyFeed: EventFeed = { events: [], exhausted: true };
+
+/**
+ * The row a tail read of this feed continues from — `/events?before=…` — or `null`
+ * for a feed with no tail yet, which is what reading from the top is.
+ *
+ * Exported because the CALLER has to pass back the cursor it requested with, and
+ * a cursor derived any other way is not the one the answer is about.
+ */
+export const feedTailCursor = (feed: EventFeed): string | null =>
+ feed.events[feed.events.length - 1]?.id ?? null;
+
+/**
+ * One list from two pages of the same feed, in the order given, without repeats.
+ *
+ * ORDER IS POSITIONAL and has to be: `id` is `evt_<uuid4hex>`, so sorting by it
+ * would scramble the feed into a random permutation that still looked plausible.
+ * The endpoint returns newest-first (`BoundedEventLog.list` reverses the append
+ * log), so the caller states the relationship by argument order — a head page
+ * goes first, a tail page goes second — and this only removes the overlap.
+ *
+ * The overlap is normal, not a bug: a head re-read after a write returns rows we
+ * already hold, and a tail page can be crossed by an event landing mid-request.
+ * The FIRST argument wins a duplicate, which is what makes the head page the
+ * fresher copy of a row it shares with what is on screen.
+ */
+export const mergeEventFeed = (
+ first: ResolutionEvent[],
+ second: ResolutionEvent[],
+): ResolutionEvent[] => {
+ const seen = new Set(first.map((event) => event.id));
+ return [...first, ...second.filter((event) => !seen.has(event.id))];
+};
+
+/**
+ * Whether a re-read head page has left a HOLE between itself and the rows already
+ * on screen — the one case where merging the two would be a lie.
+ *
+ * The test is disjointness, not page fullness. A full head page proves nothing:
+ * `listEvents(EVENT_PAGE)` returns the newest page whether or not anything is
+ * new, so 「full」 is true of every feed with at least a page of history in it.
+ * What actually distinguishes the bad case is that the newest page and the rows
+ * we hold no longer touch: more than a page of events landed between the two
+ * reads, so everything in between is missing, and splicing them together yields a
+ * list where every row is well-formed and the sequence is fiction.
+ *
+ * An empty screen cannot have a hole (there is nothing to be apart from), and
+ * neither can an empty head page — a feed that just answered with nothing has no
+ * newer rows to be separated by.
+ */
+export const headReadGapped = (
+ headPage: ResolutionEvent[],
+ onScreen: ResolutionEvent[],
+): boolean => {
+ if (headPage.length === 0 || onScreen.length === 0) return false;
+ const held = new Set(onScreen.map((event) => event.id));
+ return !headPage.some((event) => held.has(event.id));
+};
+
+/**
+ * The feed after a head re-read: merged onto what is on screen, or — when the two
+ * no longer touch — replaced by the contiguous newest page.
+ *
+ * Replacing costs the user their 加载更早 rows, which is the honest price: those
+ * rows are still reachable by paging, while a spliced feed is unreachable by any
+ * action because nothing about it looks wrong.
+ *
+ * Which is only true if paging can still reach them, and that is why `exhausted`
+ * is part of the answer. Merging leaves it alone — the tail is still on screen, so
+ * a claim about the tail still holds, and this read was of the head. Replacing
+ * clears it: the rows it discarded are older than everything it kept and they
+ * exist by construction (disjoint pages mean a page-plus landed in between), so
+ * 「there is nothing older」 is exactly what stopped being true. If the log has
+ * since evicted them, the next 加载更早 comes back short and sets it again.
+ */
+export const feedAfterHeadRead = (onScreen: EventFeed, headPage: ResolutionEvent[]): EventFeed =>
+ headReadGapped(headPage, onScreen.events)
+ ? { events: headPage, exhausted: false }
+ : {
+ events: mergeEventFeed(headPage, onScreen.events),
+ exhausted: onScreen.exhausted,
+ };
+
+/**
+ * The feed after a read from the TAIL end — 加载更早, and the first page at mount,
+ * which is a tail read too: it reaches the end exactly when it comes back short.
+ *
+ * `pageSize` is passed rather than baked in because the page owns that constant;
+ * a short page is the only evidence either read has that there is nothing older.
+ *
+ * `requestedAfter` is the cursor the page was FETCHED with, and a page whose
+ * cursor is no longer this feed's tail is dropped whole. A tail page is not 「the
+ * older rows」 — it is 「the rows below THIS one」, so it only means anything about a
+ * feed that still ends there. Merging one that does not is the hole this exists to
+ * prevent: while 加载更早 is in flight, a head re-read can find the feed gapped and
+ * REPLACE it, and appending the old tail's page under the new head splices the two
+ * ends of a feed together with everything between them missing — and worse than
+ * the head-replacement case, unrecoverably so, because the next 加载更早 then pages
+ * on from that old cursor and never comes back for the middle.
+ *
+ * Dropped means dropped, both halves: a page that may not speak for the rows may
+ * not speak for「nothing older」either. The user is left where the replacement put
+ * them, with 加载更早 still offered, and pressing it reads from the new tail.
+ */
+export const feedAfterTailRead = (
+ onScreen: EventFeed,
+ tailPage: ResolutionEvent[],
+ pageSize: number,
+ requestedAfter: string | null,
+): EventFeed =>
+ feedTailCursor(onScreen) !== requestedAfter
+ ? onScreen
+ : {
+ events: mergeEventFeed(onScreen.events, tailPage),
+ exhausted: tailPage.length < pageSize,
+ };
diff --git a/ui/src/components/settings/models/featureFlags.ts b/ui/src/components/settings/models/featureFlags.ts
index fd8b17c6e..1c95cd7e2 100644
--- a/ui/src/components/settings/models/featureFlags.ts
+++ b/ui/src/components/settings/models/featureFlags.ts
@@ -28,6 +28,17 @@ export const MODELS_API_MODE: 'mock' | 'live' = 'live';
*/
export const MODEL_MENUS_ENABLED = true;
+/**
+ * Offers 试跑 in the 来源顺序 drawer — one real turn through the chain.
+ *
+ * ON: `POST /api/models/agents/<backend>/probe` landed with the
+ * provenance/channel-aware-probe lane, which is the merge this flip was waiting
+ * for — the same way MODEL_MENUS_ENABLED above waited for the drawers it opens.
+ * The route answers per channel: hub attempts the request upstream and times it,
+ * native_cli re-verifies the CLI's readiness and times nothing.
+ */
+export const DRY_RUN_ENABLED = true;
+
/**
* Offers the consent-gated hub-held subscription option (`subscription_hub_
* experimental`, spec §4.1/§7) inside the connect-subscription dialog. OFF by
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
index a948236be..039b1a20b 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 { canReauth, canReplaceKey, wasBlocked } from './repair';
import { isUnhealthy } from './supply';
import type {
AdoptedBy,
@@ -30,6 +31,7 @@ import type {
AgentSourcesPut,
AgentSupply,
ApiKeySourceCreate,
+ CredentialReplace,
CustomModelCreate,
MigrationApplyResult,
MigrationScan,
@@ -39,9 +41,11 @@ import type {
RuntimeDependency,
Source,
SourcePatch,
+ SourceRepaired,
SupplyChannel,
+ SupplyGap,
} from './types';
-import { CONTRACT_VERSION } from './types';
+import { AGENT_CHAIN_CONTRACT_VERSION, PROBE_RESULT_CONTRACT_VERSION } from './types';
/**
* The terminal result of BOTH creation paths (api.md 「The terminal result of both
@@ -67,20 +71,42 @@ export type SourceCreated = { source: Source; adopted_by: AdoptedBy[] };
* `/sources` to "finalize" gets `flow_not_found` on a connection that in fact
* succeeded. `null` means this response did not report a creation (still
* pending, failed, cancelled, or a `reauth` flow, which reports recovery
- * instead and which no UI path starts yet) — NOT that nothing adopted the
- * source. That distinction is why this is nullable rather than `[]`.
+ * instead) — NOT that nothing adopted the source. That distinction is why this
+ * is nullable rather than `[]`.
+ *
+ * `repaired` is the other terminal arm, keyed on the payload's own `intent`: a
+ * `reauth` flow succeeds into `{source, recovered, interrupted_pairs}` (api.md,
+ * "recovery symmetry") rather than an adoption list. At most one arm is ever
+ * non-null, because a flow has exactly one intent.
*/
-export type OAuthResult = { flow: OAuthFlow; created: SourceCreated | null };
+export type OAuthResult = {
+ flow: OAuthFlow;
+ created: SourceCreated | null;
+ repaired: SourceRepaired | null;
+};
export type ModelsApi = {
listSources(): Promise<Source[]>;
createApiKeySource(draft: ApiKeySourceCreate): Promise<SourceCreated>;
/** Rename / re-point a source (display_name, base_url). */
patchSource(id: string, patch: SourcePatch): Promise<Source>;
- /** Re-run discovery on a hub source; resolves with the discovered count. */
+ /** Re-run discovery on a hub source; resolves with the discovered count.
+ * Contractually ALSO the recovery test: run on a needs_action / error source
+ * it clears the blocker and returns the source to standby. v3 adds no second
+ * 「recover」 endpoint, so this is the whole retry affordance. */
testSource(id: string): Promise<number>;
/** Delete a source. `force` overrides the only-supplier guard. */
deleteSource(id: string, force?: boolean): Promise<void>;
+ /** Replace the credential of a hub-channel api_key source. Refuses with
+ * `source_last_supplier` + `would_interrupt` when the replacement set would
+ * strand a selected model; `force` commits anyway. */
+ replaceCredential(id: string, body: CredentialReplace): Promise<SourceRepaired>;
+ /** Start re-authorization for a subscription source. Irreversible once it
+ * begins, which is why the acknowledgement is sent unconditionally — the
+ * server rejects a native source without it (`reauth_confirmation_required`).
+ * Resolves with the flow to drive; the repair tail arrives on its terminal
+ * status/submit response as `OAuthResult.repaired`. */
+ reauthSource(id: string): Promise<OAuthFlow>;
listAgents(): Promise<AgentSupply[]>;
/** Per-backend enabled subset + order + policy (the 来源顺序 drawer's read). */
getAgentSources(backend: AgentBackend): Promise<AgentSupply>;
@@ -115,24 +141,124 @@ const isLive = () => MODELS_API_MODE === 'live';
class ApiCallError extends Error {
code: string;
detail?: string;
- constructor(code: string, detail?: string) {
+ /**
+ * The `source_last_supplier` payload half. Carried on the error rather than
+ * looked up afterwards for the same reason `adopted_by` travels with a
+ * creation: it is the server's evaluation of the write it just refused, and
+ * no later read of `/agents` reproduces it — that read describes today's
+ * supply, not the supply the refused write would have left behind.
+ *
+ * `[]` on every other code, so a call site can render the gap report without
+ * first proving which error it has.
+ */
+ wouldInterrupt: SupplyGap[];
+ /**
+ * The OTHER half, and deliberately not the same field: `would_interrupt` names
+ * what a REFUSED write would have stranded (nothing changed, the copy is future
+ * tense), while `interrupted_pairs` on an error names what a write that already
+ * COMMITTED did strand. A native reauth is where that difference is not
+ * academic — `_materialize_reauth` clears the source, marks it unavailable, and
+ * only then answers `discovery_failed` with the pairs beside it, so these gaps
+ * are a report about the past, not a confirm about the future. Collapsed into
+ * one field, the caller would have no way to pick the right tense.
+ */
+ interrupted: SupplyGap[];
+ /**
+ * Whether the ROUTE named this failure, i.e. whether `code` came off the wire.
+ *
+ * Two of the codes here are this client's own summary of a response that never
+ * said what happened: `bad_response` when the body would not parse, `http_<n>`
+ * when it parsed and carried no `error`. They are not outcomes — a route that
+ * names a failure has already decided what it did, while these say only that
+ * the answer did not arrive intact, which the server having written first is
+ * entirely consistent with. Anything downstream that skips a corrective re-read
+ * because 「the route said so」 has to ask this rather than 「is it one of ours?」.
+ *
+ * `true` by default because every other throw in this module IS an outcome: the
+ * local mock raises the same codes the routes do. Only `call` invents any, and
+ * it says so at both sites.
+ */
+ serverNamed: boolean;
+ constructor(
+ code: string,
+ detail?: string,
+ serverNamed = true,
+ wouldInterrupt: SupplyGap[] = [],
+ interrupted: SupplyGap[] = [],
+ ) {
super(detail || code);
this.name = 'ApiCallError';
this.code = code;
this.detail = detail;
+ this.serverNamed = serverNamed;
+ this.wouldInterrupt = wouldInterrupt;
+ this.interrupted = interrupted;
}
}
+/** Normalize to the FULL contract shape: a gap without `agents` is a gap whose
+ * confirm copy has nothing to name, and `[]` renders as 「无」 rather than
+ * crashing the dialog that was opened to explain the refusal. */
+const supplyGaps = (raw: unknown): SupplyGap[] =>
+ Array.isArray(raw)
+ ? raw
+ .filter((g): g is Record<string, unknown> => Boolean(g) && typeof g === 'object')
+ .map((g) => ({
+ backend: g.backend as SupplyGap['backend'],
+ model_id: String(g.model_id ?? ''),
+ agents: Array.isArray(g.agents) ? g.agents.map(String) : [],
+ }))
+ : [];
+
+/**
+ * The one reader every call site uses instead of casting a caught `unknown`.
+ *
+ * Both clients throw `ApiCallError`, but a caught value is still `unknown` to
+ * TypeScript, and `(err as {code?: string}).code` spread across call sites is
+ * how a renamed field goes silently unread. Returns null for anything that is
+ * not one of ours — a TypeError from our own render code must not be reported
+ * to the user as a supply refusal.
+ */
+export const apiFailure = (
+ err: unknown,
+): {
+ code: string;
+ detail?: string;
+ serverNamed: boolean;
+ wouldInterrupt: SupplyGap[];
+ interrupted: SupplyGap[];
+} | null =>
+ err instanceof ApiCallError
+ ? {
+ code: err.code,
+ detail: err.detail,
+ serverNamed: err.serverNamed,
+ wouldInterrupt: err.wouldInterrupt,
+ interrupted: err.interrupted,
+ }
+ : null;
+
async function call<T>(path: string, init?: RequestInit): Promise<T> {
const res = await apiFetch(path, init);
let payload: any = null;
try {
payload = await res.json();
} catch {
- throw new ApiCallError('bad_response', `Non-JSON response from ${path}`);
+ // Invented here, not read off the wire: the request may well have been
+ // carried out and its answer lost coming back.
+ throw new ApiCallError('bad_response', `Non-JSON response from ${path}`, false);
}
if (!res.ok || payload?.ok === false) {
- throw new ApiCallError(payload?.error || `http_${res.status}`, payload?.detail);
+ throw new ApiCallError(
+ payload?.error || `http_${res.status}`,
+ payload?.detail,
+ // `payload.error` is the only thing that carries a route's own verdict, so
+ // its presence IS the answer. `http_502` is this client summarizing a
+ // response that never gave one.
+ Boolean(payload?.error),
+ supplyGaps(payload?.would_interrupt),
+ supplyGaps(payload?.interrupted_pairs),
+ );
}
return payload as T;
}
@@ -153,8 +279,22 @@ const created = (r: SourceCreatedResponse): SourceCreated => ({
adopted_by: r.adopted_by ?? [],
});
-/** The oauth terminal envelope, unwrapped without discarding the create half. */
-export type OAuthResultResponse = { flow?: OAuthFlow } & OAuthFlow & { source?: Source; adopted_by?: AdoptedBy[] };
+/** api.md "recovery symmetry": both repair routes answer with this same tail,
+ * so both unwrap through one reader. */
+type SourceRepairedResponse = { source?: Source; recovered?: boolean; interrupted_pairs?: SupplyGap[] } & Source;
+const repaired = (r: SourceRepairedResponse): SourceRepaired => ({
+ source: (r.source ?? r) as Source,
+ recovered: r.recovered === true,
+ interrupted_pairs: supplyGaps(r.interrupted_pairs),
+});
+
+/** The oauth terminal envelope, unwrapped without discarding either tail. */
+export type OAuthResultResponse = { flow?: OAuthFlow } & OAuthFlow & {
+ source?: Source;
+ adopted_by?: AdoptedBy[];
+ recovered?: boolean;
+ interrupted_pairs?: SupplyGap[];
+ };
/** Exported for its own test: this is where the create half was being dropped. */
export const oauthResult = (r: OAuthResultResponse): OAuthResult => {
const flow = (r.flow ?? r) as OAuthFlow;
@@ -162,7 +302,8 @@ export const oauthResult = (r: OAuthResultResponse): OAuthResult => {
// `reauth` also terminates with a `source` but carries recovery counts instead
// of adoption, and reading those as an adoption list would report the wrong
// thing about the wrong flow. Absent `intent` is a `create` flow (the field
- // postdates the first shipped payloads, and create is all this UI starts).
+ // postdates the first shipped payloads, and create is the flow this UI starts
+ // from the vendor buttons).
const isCreate = flow.intent !== 'reauth';
return {
flow,
@@ -170,6 +311,17 @@ export const oauthResult = (r: OAuthResultResponse): OAuthResult => {
// 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,
+ // 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.
+ repaired:
+ !isCreate && r.source
+ ? {
+ source: r.source,
+ recovered: r.recovered === true,
+ interrupted_pairs: supplyGaps(r.interrupted_pairs),
+ }
+ : null,
};
};
@@ -181,7 +333,16 @@ const liveApi: ModelsApi = {
createApiKeySource: (draft) => call<SourceCreatedResponse>('/api/models/sources', jsonInit('POST', draft)).then(created),
patchSource: (id, patch) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(id)}`, jsonInit('PATCH', patch)).then((r) => (r.source ?? r) as Source),
testSource: (id) => call<{ discovered: number }>(`/api/models/sources/${encodeURIComponent(id)}/test`, jsonInit('POST')).then((r) => r.discovered),
- deleteSource: (id, force) => call(`/api/models/sources/${encodeURIComponent(id)}${force ? '?force=1' : ''}`, jsonInit('DELETE')).then(() => undefined),
+ deleteSource: (id, force) => call(`/api/models/sources/${encodeURIComponent(id)}${force ? '?force=true' : ''}`, jsonInit('DELETE')).then(() => undefined),
+ // Both repair routes reject unknown body keys outright (`discovery_failed` /
+ // `reauth_confirmation_required`), so these bodies are exactly the contract's
+ // and carry no `contract_version` — the same closed-body rule as putAgentSources.
+ replaceCredential: (id, body) => call<SourceRepairedResponse>(`/api/models/sources/${encodeURIComponent(id)}/credential`, jsonInit('PUT', body)).then(repaired),
+ // The acknowledgement is unconditional by design: the server enforces it for
+ // native sources pre-login, and api.md's per-channel truth makes a hub grant
+ // replacement equally irreversible once new material is written. One confirm,
+ // no channel branch.
+ reauthSource: (id) => call<{ flow?: OAuthFlow } & OAuthFlow>(`/api/models/sources/${encodeURIComponent(id)}/reauth`, jsonInit('POST', { acknowledge_irreversible: true })).then((r) => (r.flow ?? r) as OAuthFlow),
listAgents: () => call<{ agents: AgentSupply[] }>('/api/models/agents').then((r) => r.agents),
getAgentSources: (backend) => call<{ agent: AgentSupply }>(`/api/models/agents/${backend}/sources`).then((r) => r.agent),
// The body is TOTAL and closed: the route rejects unknown keys, so
@@ -214,7 +375,10 @@ const liveApi: ModelsApi = {
// ── Mock client ─────────────────────────────────────────────────────────
// A single mutable store so reorder / add / mode-switch stick across calls
// within a session, giving a realistic demo without a backend.
-type MockFlow = { flow: OAuthFlow; polls: number; submitted: boolean };
+/** `recovered` is captured when a reauth flow STARTS, like the server's own
+ * `recovered = source.state.status in {needs_action, error}` — read before the
+ * native irreversible step rewrites that very status. */
+type MockFlow = { flow: OAuthFlow; polls: number; submitted: boolean; recovered?: boolean };
const rid = (prefix: string) => `${prefix}_${Math.random().toString(36).slice(2, 10)}`;
const delay = <T>(value: T, ms = 260): Promise<T> => new Promise((r) => setTimeout(() => r(value), ms));
@@ -353,17 +517,125 @@ class MockStore {
return delay({ source: structuredClone(source), adopted_by: this.adoptionOf(source.id) }, 900);
}
- deleteSource(id: string, force = false) {
- // Mirror the server's only-supplier guard (mode_switch_blocked): a source
- // currently bound as some agent's supply can't be dropped without force.
- if (!force && this.agents.some((a) => a.current?.source_id === id)) {
- throw new ApiCallError('mode_switch_blocked');
+ /**
+ * The supply guard, evaluated the way the server evaluates it: against the
+ * CANDIDATE config the write would produce, not against a live binding.
+ *
+ * The old version asked 「is this source some agent's `current`?」, which is a
+ * different and weaker question: deleting the second source of a two-source
+ * chain strands nothing (the head still serves), while deleting the only
+ * supplier of a *cooling* head strands a model that has no `current` at all.
+ * Reporting per (backend, model) with the Agents that run it is also what makes
+ * the confirm copy nameable — 「删除后 pm 将没有可用来源」.
+ */
+ private wouldInterrupt(candidate: Source[]): SupplyGap[] {
+ const byId = new Map(candidate.map((s) => [s.id, s]));
+ const gaps: SupplyGap[] = [];
+ for (const a of this.agents) {
+ if (a.mode !== 'hub') continue;
+ const model = a.selected_model_id;
+ if (!model) continue;
+ const mapping = a.mappings?.find((x) => x.builtin_id === model && x.enabled && x.target_model_id);
+ const resolved = mapping ? mapping.target_model_id : model;
+ // A `follow` order only ever LOSES the removed id (the recommendation never
+ // gains a source from a write), so filtering the live order through the
+ // candidate set is the same answer refresh_follow_orders would give.
+ const survives = (a.sources?.order ?? [])
+ .map((id) => byId.get(id))
+ .some((s) => s !== undefined && s.models.some((mm) => mm.id === resolved) && isRunnable(s));
+ if (survives) continue;
+ gaps.push({
+ backend: a.backend,
+ model_id: model,
+ agents: (a.named_agents ?? []).filter((n) => n.effective_model_id === model).map((n) => n.name),
+ });
}
- this.sources = this.sources.filter((s) => s.id !== id);
+ return gaps;
+ }
+
+ deleteSource(id: string, force = false) {
+ this.syncAgents();
+ const remaining = this.sources.filter((s) => s.id !== id);
+ // `source_last_supplier` — the code the contract actually sends here.
+ // `mode_switch_blocked` belongs to the mode route, and a client written
+ // against it retried nothing on a real refusal.
+ const gaps = this.wouldInterrupt(remaining);
+ if (gaps.length > 0 && !force)
+ throw new ApiCallError('source_last_supplier', undefined, true, gaps);
+ this.sources = remaining;
// Orders and the rollup are recomputed on the next read (syncAgents).
return delay(undefined);
}
+ replaceCredential(id: string, body: CredentialReplace) {
+ this.syncAgents();
+ const source = this.sources.find((s) => s.id === id);
+ if (!source) throw new ApiCallError('source_not_found');
+ // The server's preconditions, restated rather than assumed: the menu offers
+ // this only where they hold, but a mock that failed open would hide a wiring
+ // mistake until it reached a real backend.
+ if (!canReplaceKey(source) || !body.key.trim()) throw new ApiCallError('discovery_failed');
+ const recovered = wasBlocked(source.state);
+ const previousMask = source.masked_credential;
+ const previousState = { ...source.state };
+ // Atomic commit, standby-clearing semantics shared with testSource: a
+ // replacement re-discovers and lands on standby, never straight to active.
+ source.masked_credential = maskKey(body.key);
+ source.credential_ref = rid('cred');
+ source.state = { status: 'standby', retry_at: null, detail_key: null };
+ const interrupted = this.wouldInterrupt(this.sources);
+ // A RECOVERING write is exempt from the guard and merely reports what is
+ // still stranded; only an elective one can be refused.
+ if (interrupted.length > 0 && !recovered && !body.force) {
+ source.masked_credential = previousMask;
+ source.state = previousState;
+ throw new ApiCallError('source_last_supplier', undefined, true, interrupted);
+ }
+ this.syncAgents();
+ return delay(
+ { source: structuredClone(source), recovered, interrupted_pairs: interrupted },
+ 700,
+ );
+ }
+
+ reauthSource(id: string) {
+ const source = this.sources.find((s) => s.id === id);
+ if (!source) throw new ApiCallError('source_not_found');
+ if (!canReauth(source)) throw new ApiCallError('discovery_failed');
+ // Read BEFORE the irreversible step below, which sets needs_action itself and
+ // would otherwise make every native re-auth report a recovery.
+ const recovered = wasBlocked(source.state);
+ // Native re-auth is irreversible from the first step: the server clears the
+ // discovered models and drops the account label BEFORE any login happens, so
+ // the row goes to 需处理 even if the user abandons the browser tab. Mirrored
+ // here, because a mock that kept the old models would make the confirm dialog
+ // look like a formality.
+ if (source.supply_channel === 'native_cli') {
+ source.models = [];
+ source.account_label = null;
+ source.state = { status: 'needs_action', retry_at: null, detail_key: 'models.source.needs_action.oauth_expired' };
+ }
+ const isDevice = source.vendor === 'openai';
+ const flow: OAuthFlow = {
+ flow_id: rid('oaf'),
+ intent: 'reauth',
+ // A reauth flow binds to the EXISTING source, which is what makes its
+ // terminal response a repair rather than a creation.
+ source_id: source.id,
+ vendor: source.vendor,
+ channel: source.supply_channel,
+ state: 'awaiting_action',
+ presentation: isDevice
+ ? { auth_url: 'https://chatgpt.com/device', device_code: 'RFTQ-MPZK', expects: 'none', instructions_key: 'settings.models.oauth.deviceCode.hint' }
+ : { auth_url: 'https://claude.ai/oauth/authorize?code=true&client_id=avibe&scope=org%3Acreate_api_key', device_code: null, expects: 'paste_code', instructions_key: 'settings.models.oauth.pasteCode.hint' },
+ error_key: null,
+ expires_at: new Date(Date.now() + 15 * 60_000).toISOString(),
+ };
+ this.flows.set(flow.flow_id, { flow, polls: 0, submitted: false, recovered });
+ this.syncAgents();
+ return delay(structuredClone(flow), 400);
+ }
+
listAgents() {
this.syncAgents();
return delay(structuredClone(this.agents));
@@ -403,12 +675,14 @@ class MockStore {
return delay(structuredClone(agent), 380);
}
- getAgentChain(backend: AgentBackend, model: string) {
- this.syncAgents();
- const agent = this.agentOr404(backend);
- // AC-7: direct mode has no src_* identity to report, so the route refuses
- // rather than answering with an empty (falsely alarming) chain.
- if (agent.mode === 'direct') throw new ApiCallError('direct_mode');
+ /**
+ * The chain both hub-only routes answer from, shared the way the server shares
+ * it: `probe_agent` calls `_agent_chain` and takes its first runnable member.
+ * Deriving the head a second time is how the mock's probe and chain would
+ * disagree about the same supply — and `supply_state` is a rollup the v4 schema
+ * now pins to this very array, so it cannot be restated per route either.
+ */
+ private chainFor(agent: AgentSupply, model: string) {
const byId = new Map(this.sources.map((s) => [s.id, s]));
const mapping = agent.mappings?.find((x) => x.builtin_id === model && x.enabled && x.target_model_id);
const resolved = mapping ? mapping.target_model_id : model;
@@ -417,19 +691,42 @@ class MockStore {
.filter((s): s is Source => s !== undefined && s.models.some((mm) => mm.id === resolved))
.map((s) => ({
source_id: s.id,
+ channel: s.supply_channel,
via_mapping: Boolean(mapping),
resolved_model_id: mapping ? resolved : null,
health: chainHealth(s),
runnable: isRunnable(s),
+ // v4: process availability is a fact about the serving process — which
+ // native CLI it can launch under its own login — and a browser mock has
+ // no way to observe it. So it stands in for a runtime where every
+ // configured CLI is launchable, rather than inventing an outage. The
+ // unavailable branch is asserted in the unit tests, which can state the
+ // fact instead of guessing it.
+ reason: null,
retry_at: s.state.status === 'cooldown' ? s.state.retry_at ?? null : null,
}));
- const runnable = chain.some((l) => l.runnable);
- const supply_state: AgentChain['supply_state'] = runnable
+ const supply_state: AgentChain['supply_state'] = chain.some((l) => l.runnable)
? 'ok'
- : chain.length > 0 && chain.every((l) => l.health === 'cooldown')
+ : chain.length > 0 && chain.every((l) => l.health === 'cooldown' && l.reason === null)
? 'waiting'
: 'interrupted';
- return delay({ contract_version: CONTRACT_VERSION, backend, model_id: model, chain, supply_state });
+ return { chain, supply_state };
+ }
+
+ getAgentChain(backend: AgentBackend, model: string) {
+ this.syncAgents();
+ const agent = this.agentOr404(backend);
+ // AC-7: direct mode has no src_* identity to report, so the route refuses
+ // rather than answering with an empty (falsely alarming) chain.
+ if (agent.mode === 'direct') throw new ApiCallError('direct_mode');
+ const { chain, supply_state } = this.chainFor(agent, model);
+ return delay({
+ contract_version: AGENT_CHAIN_CONTRACT_VERSION,
+ backend,
+ model_id: model,
+ chain,
+ supply_state,
+ });
}
probeAgent(backend: AgentBackend, model?: string) {
@@ -438,27 +735,36 @@ class MockStore {
if (agent.mode === 'direct') throw new ApiCallError('direct_mode');
const modelId = model ?? agent.selected_model_id;
if (!modelId) throw new ApiCallError('model_unsupported');
- const byId = new Map(this.sources.map((s) => [s.id, s]));
- const mapping = agent.mappings?.find((x) => x.builtin_id === modelId && x.enabled && x.target_model_id);
- const resolved = mapping ? mapping.target_model_id : modelId;
- const head = (agent.sources?.order ?? [])
- .map((id) => byId.get(id))
- .find((s): s is Source => s !== undefined && s.models.some((mm) => mm.id === resolved) && isRunnable(s));
+ const { chain, supply_state } = this.chainFor(agent, modelId);
+ const head = chain.find((l) => l.runnable);
// `probe_no_candidate` is the contract's code for this; `no_runnable_source`
// was invented here and is in no error vocabulary, so the L5 dry-run button
- // would have been written against a code the server never sends.
- if (!head) throw new ApiCallError('probe_no_candidate');
+ // would have been written against a code the server never sends. The server
+ // also names WHICH blocked family it is in the 409's detail, and the drawer
+ // renders that key — a detail-less throw would leave it unreachable here.
+ // `ok` cannot occur on this branch: it is the rollup's word for "some member
+ // is runnable", which is exactly what failing to find a head rules out.
+ if (!head) throw new ApiCallError('probe_no_candidate', `models.probe.no_candidate.${supply_state}`);
+ // The native_cli half is a readiness answer, not a request: nothing upstream
+ // is attempted, so there is no latency to report and a measured local number
+ // would impersonate completion evidence. Readiness itself follows `reason`
+ // above — every configured CLI is launchable in the mock.
+ const native = head.channel === 'native_cli';
const probe: ProbeResult = {
- contract_version: CONTRACT_VERSION,
+ contract_version: PROBE_RESULT_CONTRACT_VERSION,
backend,
+ channel: head.channel,
reachable: true,
- source_id: head.id,
- model_id: modelId,
- latency_ms: 180 + Math.floor(Math.random() * 420),
- via_mapping: Boolean(mapping),
+ source_id: head.source_id,
+ // The resolved id, mapping applied — what the server reports, and not the
+ // requested id it was rewritten from.
+ model_id: head.resolved_model_id ?? modelId,
+ latency_ms: native ? null : 180 + Math.floor(Math.random() * 420),
+ via_mapping: head.via_mapping,
error: null,
};
- return delay(probe, 1200); // one real request takes a real moment
+ // A real upstream request takes a real moment; a local readiness check does not.
+ return delay(probe, native ? 400 : 1200);
}
setAgentMode(backend: AgentBackend, mode: AgentMode) {
@@ -646,10 +952,30 @@ class MockStore {
const flow = entry.flow;
const id = flow.source_id ?? rid('src');
flow.source_id = id;
+ const isOpenai = flow.vendor === 'openai';
+ if (flow.intent === 'reauth') {
+ // A reauth flow REPAIRS the source it bound to; it creates nothing. The
+ // login is what puts the credential back, so the blocker clears and the
+ // supply a native start had wiped comes back with it.
+ const source = this.sources.find((s) => s.id === id);
+ if (!source) return;
+ source.account_label = '[email protected]';
+ source.state = { status: 'standby', retry_at: null, detail_key: null };
+ if (source.models.length === 0) {
+ source.models = [
+ {
+ id: isOpenai ? 'gpt-5.6' : 'claude-opus-4-6',
+ display_name: isOpenai ? 'GPT-5.6' : 'Opus 4.6',
+ provenance: 'discovered',
+ discovered_at: new Date().toISOString(),
+ },
+ ];
+ }
+ return;
+ }
// Idempotent, like `_create_oauth_source(idempotent=True)`: re-polling a
// completed flow re-echoes the same source instead of creating a second one.
if (this.sources.some((s) => s.id === id)) return;
- const isOpenai = flow.vendor === 'openai';
this.sources.push({
id,
created_at: new Date().toISOString(),
@@ -684,9 +1010,25 @@ class MockStore {
private oauthResult(entry: MockFlow): OAuthResult {
const flow = structuredClone(entry.flow);
const source = flow.state === 'success' ? this.sources.find((s) => s.id === flow.source_id) : undefined;
+ if (!source) return { flow, created: null, repaired: null };
+ // One intent, one tail — the same discrimination the live unwrap makes, so a
+ // reauth never reports an adoption list and a create never reports recovery.
+ if (flow.intent === 'reauth') {
+ this.syncAgents();
+ return {
+ flow,
+ created: null,
+ repaired: {
+ source: structuredClone(source),
+ recovered: entry.recovered === true,
+ interrupted_pairs: this.wouldInterrupt(this.sources),
+ },
+ };
+ }
return {
flow,
- created: source ? { source: structuredClone(source), adopted_by: this.adoptionOf(source.id) } : null,
+ created: { source: structuredClone(source), adopted_by: this.adoptionOf(source.id) },
+ repaired: null,
};
}
@@ -756,6 +1098,8 @@ const mockApi: ModelsApi = {
patchSource: (id, patch) => mockStore.patchSource(id, patch),
testSource: (id) => mockStore.testSource(id),
deleteSource: (id, force) => mockStore.deleteSource(id, force),
+ replaceCredential: (id, body) => mockStore.replaceCredential(id, body),
+ reauthSource: (id) => mockStore.reauthSource(id),
listAgents: () => mockStore.listAgents(),
getAgentSources: (backend) => mockStore.getAgentSources(backend),
putAgentSources: (backend, body) => mockStore.putAgentSources(backend, body),
diff --git a/ui/src/components/settings/models/oauthResult.test.ts b/ui/src/components/settings/models/oauthResult.test.ts
index 2502ccf8d..8a868ade7 100644
--- a/ui/src/components/settings/models/oauthResult.test.ts
+++ b/ui/src/components/settings/models/oauthResult.test.ts
@@ -30,7 +30,7 @@ const adopted: AdoptedBy[] = [{ backend: 'claude', policy: 'follow', position: 1
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 } });
+ expect(oauthResult(r)).toEqual({ flow: r.flow, created: { source, adopted_by: adopted }, repaired: null });
});
it('reads an absent adopted_by beside a source as nothing adopted it', () => {
@@ -53,6 +53,48 @@ describe('oauthResult', () => {
expect(oauthResult(r).created).toBeNull();
});
+ it('keeps the repair tail a terminal reauth reports', () => {
+ // The other half of the same discrimination: dropping this is the L5 version
+ // of the bug above — the user re-authorizes, the server reports which Agents
+ // are still stranded, and the dialog would close saying nothing about them.
+ const gaps = [{ backend: 'claude' as const, model_id: 'claude-opus-4-6', agents: ['pm'] }];
+ const r = {
+ flow: flow({ intent: 'reauth' }),
+ source,
+ recovered: true,
+ interrupted_pairs: gaps,
+ } as OAuthResultResponse;
+ expect(oauthResult(r).repaired).toEqual({ source, recovered: true, interrupted_pairs: gaps });
+ });
+
+ it('reads an absent recovered as "the server did not say so"', () => {
+ // Never as a client guess that it did: `recovered` drives 「已恢复」 copy, and
+ // claiming a recovery the server never reported is the one lie this tail can
+ // tell. An absent `interrupted_pairs` normalizes to [], which is the same
+ // statement the server makes by sending an empty array.
+ const r = { flow: flow({ intent: 'reauth' }), source } as OAuthResultResponse;
+ expect(oauthResult(r).repaired).toEqual({ source, recovered: false, interrupted_pairs: [] });
+ });
+
+ it('fills a gap missing its agents rather than dropping the gap', () => {
+ // A gap with no nameable Agent is still a stranded model, and the confirm
+ // dialog was opened to report it. `agents: []` renders as 「无」; a dropped
+ // entry renders as 「nothing was stranded」, which is the opposite.
+ const r = {
+ flow: flow({ intent: 'reauth' }),
+ source,
+ interrupted_pairs: [{ backend: 'codex', model_id: 'gpt-5.6' }],
+ } as unknown as OAuthResultResponse;
+ expect(oauthResult(r).repaired?.interrupted_pairs).toEqual([
+ { backend: 'codex', model_id: 'gpt-5.6', agents: [] },
+ ]);
+ });
+
+ it('reports no repair while a reauth flow is still running', () => {
+ const r = { flow: flow({ intent: 'reauth', state: 'awaiting_action' }) } as OAuthResultResponse;
+ expect(oauthResult(r).repaired).toBeNull();
+ });
+
it('treats a flow without `intent` as a create flow', () => {
// The field postdates the first shipped payloads and the schema keeps it
// optional, so absent must not mean "unknown, report nothing".
diff --git a/ui/src/components/settings/models/repair.test.ts b/ui/src/components/settings/models/repair.test.ts
new file mode 100644
index 000000000..e47927254
--- /dev/null
+++ b/ui/src/components/settings/models/repair.test.ts
@@ -0,0 +1,976 @@
+// Tests for the supply journeys' decisions.
+//
+// One block per question, because each one is a place a component would
+// otherwise improvise: which tap a stopped row offers, what the server's repair
+// answer means, and whether 试跑 has anything real to run. The last block is the
+// grep guard that keeps those questions from growing a second answer next door —
+// the same shape, and the same reason, as `sufficiency.test.ts`.
+import { readFileSync, readdirSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { describe, expect, it } from 'vitest';
+
+import en from '../../../i18n/en.json';
+import zh from '../../../i18n/zh.json';
+import {
+ disprovedDrawnHead,
+ dryRunChainKey,
+ dryRunOutcome,
+ dryRunPlan,
+ dryRunRowView,
+ mayHaveWritten,
+ probeArrival,
+ probeWroteState,
+ reauthBodyKey,
+ reauthCost,
+ repairAction,
+ REPAIR_LABEL_KEY,
+ REPAIR_LINE_KEY,
+ REPAIR_TOAST,
+ repairOutcome,
+ repairSettles,
+} from './repair';
+import type { RepairOutcome } from './repair';
+import { PROBE_RESULT_CONTRACT_VERSION } from './types';
+import type { AgentSupply, ProbeResult, Source, SourceDetailKey, SourcePolicy, SupplyGap } from './types';
+
+/** A healthy hub api_key with a credential to replace — the base every case
+ * below narrows, so each test names only what it is actually about. */
+const source = (over: Partial<Source> = {}): Source => ({
+ id: 'src_a',
+ kind: 'api_key',
+ vendor: 'anthropic',
+ display_name: 'Key A',
+ protocol: 'anthropic',
+ supply_channel: 'hub',
+ billing: 'metered',
+ credential_ref: 'cred_a',
+ state: { status: 'active' },
+ models: [],
+ ...over,
+});
+
+const blocked = (detail_key: SourceDetailKey, over: Partial<Source> = {}): Source =>
+ source({ state: { status: 'needs_action', detail_key }, ...over });
+
+const subscription = { kind: 'subscription', vendor: 'anthropic', account_label: '[email protected]' } as const;
+const native = { supply_channel: 'native_cli', credential_ref: null } as const;
+
+/** A locale leaf by its full dotted key — the same path the components hand to
+ * `t`, so a key that only exists as a prefix fails the same way it would there. */
+const translated = (bundle: unknown, key: string): unknown =>
+ key.split('.').reduce<unknown>((node, part) => {
+ if (!node || typeof node !== 'object') return undefined;
+ return (node as Record<string, unknown>)[part];
+ }, bundle);
+
+describe('repairAction — the one tap a stopped row offers (SourceRowMenu)', () => {
+ it('offers nothing to a source that is running', () => {
+ // Not a disabled button: a healthy row has no problem, and an affordance for
+ // a problem it does not have is noise the V6 row has no slot for.
+ expect(repairAction(source())).toBeNull();
+ });
+
+ it('offers nothing to a cooldown, which heals itself', () => {
+ // 额度用完 earns the gold sub-line through `needsAttention`, and that is all it
+ // earns. §4.5 makes cooldown the ONLY self-healing blocker; putting a repair
+ // button on it would ask the user to fix the one state that fixes itself.
+ expect(
+ repairAction(
+ source({ state: { status: 'cooldown', detail_key: 'models.source.cooldown.quota_exhausted', retry_at: '2030-01-01T00:00:00Z' } }),
+ ),
+ ).toBeNull();
+ });
+
+ it('sends an expired subscription to re-auth on the native channel', () => {
+ // AC-2's journey. The state here is exactly what `mark_native_irreversible_
+ // start` writes, so this is the row the user comes back to after a login
+ // stopped working.
+ expect(repairAction(blocked('models.source.needs_action.oauth_expired', { ...subscription, ...native }))).toBe('reauth');
+ });
+
+ it('sends an expired subscription to re-auth on the hub channel too', () => {
+ // `POST …/reauth` accepts both channels: a hub-held grant is re-obtained by
+ // logging in again just as a CLI login is, so the remedy does not fork.
+ expect(repairAction(blocked('models.source.needs_action.oauth_expired', subscription))).toBe('reauth');
+ });
+
+ it('sends a revoked api_key to key replacement', () => {
+ expect(repairAction(blocked('models.source.needs_action.credential_revoked'))).toBe('replace_key');
+ });
+
+ it('offers nothing when the credential failed and there is no route to replace it', () => {
+ // A native api_key: the credential is the CLI's, not Avibe's. The point of the
+ // assertion is that this does NOT fall through to 「retry」 — the cause is
+ // named, it is the credential, and a re-test would just re-report it.
+ expect(repairAction(blocked('models.source.needs_action.credential_revoked', native))).toBeNull();
+ });
+
+ it('offers a re-check when the cause lives upstream', () => {
+ // Balance run out, account restricted: Avibe cannot fix either, and no contract
+ // field carries a vendor billing URL. What it can do is stop guessing once the
+ // user says they handled it.
+ expect(repairAction(blocked('models.source.needs_action.balance_exhausted'))).toBe('retest');
+ expect(repairAction(blocked('models.source.needs_action.account_banned'))).toBe('retest');
+ });
+
+ it('treats an unclassified error as an upstream cause, not a credential one', () => {
+ // `error` is a blocker with no diagnosis. Guessing 「replace your key」 from it
+ // would ask the user to throw away a working credential.
+ expect(repairAction(source({ state: { status: 'error', detail_key: 'models.source.error.unclassified' } }))).toBe(
+ 'retest',
+ );
+ });
+
+ it('offers nothing to a native source with an upstream cause', () => {
+ // Nothing to re-discover (`POST …/test` rejects native), and NOT the re-login
+ // that the unclassified case below gets: a native re-login invalidates the
+ // working sign-in up front, so offering it for 账号被封 would charge the user
+ // that price for a blocker it cannot clear. This is rule 3's boundary.
+ expect(repairAction(blocked('models.source.needs_action.account_banned', { ...subscription, ...native }))).toBeNull();
+ expect(repairAction(blocked('models.source.needs_action.balance_exhausted', { ...subscription, ...native }))).toBeNull();
+ });
+
+ it('sends a native source back to sign-in when the last one produced nothing usable', () => {
+ // The state two backend paths write onto a native source, both from INSIDE a
+ // re-login: `completed_source_status` threw, or discovery came back empty. The
+ // row must keep a tap — before this it fell through rule 2 to `canRetest`,
+ // which native can never satisfy, and the remedy survived only in the overflow
+ // menu even though `canReauth` was true the whole time.
+ expect(
+ repairAction(
+ source({
+ ...subscription,
+ ...native,
+ state: { status: 'error', detail_key: 'models.source.error.unclassified' },
+ }),
+ ),
+ ).toBe('reauth');
+ });
+
+ it('does not invent a remedy for a native api_key with no sign-in to redo', () => {
+ // Same cause, no reauth route (`canReauth` is subscription-only), so rule 3
+ // must not hand it the subscription's button.
+ expect(
+ repairAction(
+ source({ ...native, state: { status: 'error', detail_key: 'models.source.error.unclassified' } }),
+ ),
+ ).toBeNull();
+ });
+});
+
+const gap = (backend: SupplyGap['backend'], model_id: string): SupplyGap => ({ backend, model_id });
+
+describe('repairOutcome — 「did that fix it?」 (OAuthConnectDialog, ReplaceKeyDialog)', () => {
+ it('reports a repair of a source that had been blocked', () => {
+ expect(repairOutcome({ source: source(), recovered: true, interrupted_pairs: [] })).toEqual({ kind: 'repaired' });
+ });
+
+ it('reports an elective replacement as a refresh, not a repair', () => {
+ // `recovered` is the server's own judgement (prior status in {needs_action,
+ // error}). A user who rotated a working key is not owed 「已恢复」.
+ expect(repairOutcome({ source: source(), recovered: false, interrupted_pairs: [] })).toEqual({ kind: 'refreshed' });
+ });
+
+ it('reports the stranded pairs even when the source itself recovered', () => {
+ // The ranking that matters: a forced write that fixed this source while
+ // stranding another Agent's model is not a success story, and the report is
+ // the whole reason the user was asked to confirm.
+ expect(
+ repairOutcome({ source: source(), recovered: true, interrupted_pairs: [gap('codex', 'gpt-5.6')] }),
+ ).toEqual({ kind: 'gaps', gaps: [gap('codex', 'gpt-5.6')] });
+ });
+
+ it('refuses to call a still-blocked source repaired', () => {
+ // The case that makes this more than a passthrough: a native reauth commits
+ // `needs_action`/`oauth_expired` when the CLI still reports itself signed out
+ // and answers 200 with `recovered: true` beside it, because `recovered` is a
+ // statement about the state BEFORE the attempt. Reading it alone would put
+ // 「已恢复可用」 on a row that is still stopped — and dismiss the dialog over it.
+ expect(
+ repairOutcome({
+ source: blocked('models.source.needs_action.oauth_expired'),
+ recovered: true,
+ interrupted_pairs: [],
+ }),
+ ).toEqual({ kind: 'unresolved' });
+ });
+
+ it('reports an unclassified error state as unresolved too', () => {
+ // The other half of `wasBlocked`: a discovery that came back empty leaves the
+ // source on `error`, which is no more 「已更新」 than `needs_action` is.
+ expect(
+ repairOutcome({
+ source: source({ state: { status: 'error', detail_key: 'models.source.error.unclassified' } }),
+ recovered: false,
+ interrupted_pairs: [],
+ }),
+ ).toEqual({ kind: 'unresolved' });
+ });
+
+ it('still ranks the gap report above a source that came back blocked', () => {
+ expect(
+ repairOutcome({
+ source: blocked('models.source.needs_action.oauth_expired'),
+ recovered: true,
+ interrupted_pairs: [gap('claude', 'claude-opus-4-6')],
+ }),
+ ).toEqual({ kind: 'gaps', gaps: [gap('claude', 'claude-opus-4-6')] });
+ });
+
+ it('lets a clean repair close itself and holds every other verdict open', () => {
+ expect(repairSettles({ kind: 'repaired' })).toBe(true);
+ expect(repairSettles({ kind: 'refreshed' })).toBe(true);
+ expect(repairSettles({ kind: 'unresolved' })).toBe(false);
+ expect(repairSettles({ kind: 'gaps', gaps: [gap('codex', 'gpt-5.6')] })).toBe(false);
+ });
+
+ /**
+ * The verdict a dialog renders has no compile-time link to the bundles, so a
+ * fourth kind could ship with no string. `REPAIR_LINE_KEY` is exhaustive over
+ * the union by type — a new kind fails the typecheck at its definition — and
+ * this proves each key it names is actually translated, in both locales.
+ *
+ * `gaps` is absent from the map by design (a heading over a list, not a line),
+ * which the `Exclude` in its type states and the union check below re-proves.
+ */
+ it.each(Object.entries(REPAIR_LINE_KEY))('has copy in both locales for the %s verdict', (_kind, key) => {
+ for (const bundle of [en, zh]) expect(typeof translated(bundle, key)).toBe('string');
+ });
+
+ it('covers every verdict that renders as one line', () => {
+ const kinds: RepairOutcome['kind'][] = ['repaired', 'refreshed', 'unresolved', 'gaps'];
+ expect(kinds.filter((k) => k !== 'gaps').sort()).toEqual(Object.keys(REPAIR_LINE_KEY).sort());
+ // The toast has no list to fall back on, so it answers for the full union —
+ // including the one kind the line map leaves to the panel.
+ expect(kinds.sort()).toEqual(Object.keys(REPAIR_TOAST).sort());
+ });
+
+ it.each(Object.entries(REPAIR_TOAST))('has toast copy in both locales for the %s verdict', (_kind, toast) => {
+ for (const bundle of [en, zh]) expect(typeof translated(bundle, toast.key)).toBe('string');
+ });
+
+ /**
+ * The finding this map exists for: written at the call site as 「warning if
+ * unresolved, success otherwise」, a gap report got the green tone — a toast
+ * saying 连接成功 over a dialog reporting that Agents now have no source at all.
+ *
+ * Asserted as pairs rather than as `!== 'success'`, because the mistake to catch
+ * is a tone that contradicts its own sentence, and only naming both halves
+ * catches it.
+ */
+ it('never celebrates a verdict whose own line is bad news', () => {
+ expect(REPAIR_TOAST.gaps.tone).toBe('warning');
+ expect(REPAIR_TOAST.unresolved.tone).toBe('warning');
+ expect(REPAIR_TOAST.repaired.tone).toBe('success');
+ expect(REPAIR_TOAST.refreshed.tone).toBe('success');
+ // And the tone tracks the verdict, not the branch: exactly the verdicts that
+ // may auto-dismiss are the ones allowed to be green.
+ for (const [kind, toast] of Object.entries(REPAIR_TOAST))
+ expect(toast.tone === 'success', kind).toBe(
+ repairSettles(kind === 'gaps' ? { kind: 'gaps', gaps: [] } : ({ kind } as RepairOutcome)),
+ );
+ });
+
+ it('reuses the line copy where a line exists', () => {
+ // One sentence per verdict on this page: the toast and the panel must not
+ // drift into two wordings of the same finding.
+ for (const kind of Object.keys(REPAIR_LINE_KEY) as (keyof typeof REPAIR_LINE_KEY)[])
+ expect(REPAIR_TOAST[kind].key).toBe(REPAIR_LINE_KEY[kind]);
+ // `gaps` is the exception, and deliberately not `gapsDone`: that string ends
+ // in a colon because a list follows it, and a toast has no list.
+ expect(REPAIR_TOAST.gaps.key).not.toBe('settings.models.repair.gapsDone');
+ for (const bundle of [en, zh]) expect(translated(bundle, REPAIR_TOAST.gaps.key)).not.toMatch(/[::]$/);
+ });
+});
+
+describe('the copy each remedy names', () => {
+ // The bug this replaces: `t(`settings.models.repair.${kind}`)` compiled for
+ // every RepairKind and rendered the literal key path for `replace_key`, whose
+ // bundle spelling is `replaceKey` — on the inline button AND its aria-label, so
+ // a screen reader read out the key path too.
+ it.each(Object.entries(REPAIR_LABEL_KEY))('has a %s label in both locales', (_kind, key) => {
+ for (const bundle of [en, zh]) expect(typeof translated(bundle, key)).toBe('string');
+ });
+
+ it('warns up front on a native re-login and only about failure on a hub one', () => {
+ // `mark_native_irreversible_start` rewrites every native source of that
+ // vendor's backend to 需要处理 as the login spawns, so 「开始后旧的登录立即失效」
+ // is true there. The hub route writes NOTHING at start — the held credential
+ // keeps working — and only `_fail_closed_hub_reauth` marks the source, on a
+ // flow that came back `failed`. One sentence over both is false on one.
+ expect(reauthCost(source({ ...subscription, ...native }))).toBe('immediate');
+ expect(reauthCost(source(subscription))).toBe('on_failure');
+ });
+
+ it('has both confirm bodies in both locales', () => {
+ for (const s of [source({ ...subscription, ...native }), source(subscription)])
+ for (const bundle of [en, zh]) expect(typeof translated(bundle, reauthBodyKey(s))).toBe('string');
+ });
+
+ it('says the native cost is not paid back in full', () => {
+ // Round 19. The start strips EVERY native source of that backend, and only the
+ // one that finishes comes back: `_materialize_completed_oauth` re-discovers
+ // onto the selected source and its siblings keep the empty inventory and the
+ // 需处理 (test_native_reauth_invalidates_sibling_sources_for_shared_cli). The
+ // sentence said they were unavailable 「until you finish」, which reads as a
+ // wait — so the user could confirm an irreversible action without learning
+ // that finishing leaves the rest needing their own sign-in.
+ const key = reauthBodyKey(source({ ...subscription, ...native }));
+ expect(translated(en, key)).toMatch(/only this one/i);
+ expect(translated(zh, key)).toMatch(/只恢复这一个/);
+ for (const bundle of [en, zh]) expect(translated(bundle, key)).not.toMatch(/until you finish|完成前/);
+ });
+});
+
+const agent = (over: Partial<AgentSupply> = {}): AgentSupply => ({
+ backend: 'claude',
+ mode: 'hub',
+ menu_kind: 'fixed',
+ sources: { policy: 'follow', order: ['src_a'] },
+ current: { model_id: 'claude-opus-4-6', source_id: 'src_a', channel: 'hub' },
+ ...over,
+});
+
+const probe = (over: Partial<ProbeResult> = {}): ProbeResult => ({
+ contract_version: PROBE_RESULT_CONTRACT_VERSION,
+ backend: 'claude',
+ // v4's conditionals are channel-scoped, so the default has to name a channel:
+ // a reachable `hub` result owes an integer latency, and only `native_cli` may
+ // answer with none. The cases below that vary the latency vary this with it.
+ channel: 'hub',
+ reachable: true,
+ source_id: 'src_a',
+ model_id: 'claude-opus-4-6',
+ latency_ms: 412,
+ via_mapping: false,
+ error: null,
+ ...over,
+});
+
+describe('dryRunPlan — whether 试跑 has anything to run (SourceOrderDrawer)', () => {
+ it('probes an Agent with a resolved chain head', () => {
+ expect(dryRunPlan(agent())).toEqual({ kind: 'probe', backend: 'claude' });
+ expect(dryRunPlan(agent({ backend: 'codex' }))).toEqual({ kind: 'probe', backend: 'codex' });
+ });
+
+ it('runs nothing in direct mode', () => {
+ // AC-7: the route refuses with `direct_mode`, because there is no `src_*`
+ // identity to report a turn against.
+ expect(dryRunPlan(agent({ mode: 'direct', sources: null, current: null }))).toEqual({ kind: 'none' });
+ });
+
+ it('runs nothing when there is no head', () => {
+ // A null `current` IS waiting/interrupted. The page already says so with the
+ // remedy attached; a probe would only re-report it as a failure the user has
+ // to re-read.
+ expect(dryRunPlan(agent({ current: null, supply_status: 'interrupted' }))).toEqual({ kind: 'none' });
+ });
+});
+
+describe('dryRunChainKey — which edits make a 试跑 report stop being about anything', () => {
+ const base = agent({
+ selected_model_id: 'claude-opus-4-6',
+ mappings: [{ builtin_id: 'claude-opus-4-6', target_model_id: 'glm-5.2', enabled: true }],
+ menu: { view: 'featured', checked: ['zhipuai/glm-5.2'] },
+ });
+ const key = (
+ over: Partial<AgentSupply> = {},
+ policy: SourcePolicy = 'follow',
+ order = ['src_a'],
+ sources: Source[] = [source({ id: 'src_a', models: [{ id: 'glm-5.2', provenance: 'discovered' }] })],
+ ) => dryRunChainKey({ ...base, ...over }, policy, order, sources);
+
+ it('moves for every surface the user selects the probed turn with', () => {
+ // The chain is not only its order: the probe takes no model, so the server
+ // resolves one from the same config the mapping drawer next door edits. Edit
+ // that and the sentence on screen is about a turn the button would no longer
+ // make.
+ const same = key();
+ expect(key()).toBe(same);
+ expect(key({}, 'custom')).not.toBe(same);
+ expect(key({}, 'follow', ['src_b', 'src_a'])).not.toBe(same);
+ expect(key({ selected_model_id: 'claude-sonnet-5' })).not.toBe(same);
+ expect(key({ mappings: [] })).not.toBe(same);
+ expect(key({ mappings: [{ builtin_id: 'claude-opus-4-6', target_model_id: 'glm-5.2', enabled: false }] })).not.toBe(
+ same,
+ );
+ expect(key({ menu: { view: 'featured', checked: [] } })).not.toBe(same);
+ });
+
+ 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
+ // health behind it. Key on any of those and the failing run is the one whose
+ // answer erases itself. The head moving is what a failing report is FOR.
+ const same = key();
+ expect(key({ current: { model_id: 'glm-5.2', source_id: 'src_b', channel: 'hub' } })).toBe(same);
+ expect(key({ current: null, supply_status: 'interrupted' })).toBe(same);
+ expect(key({ supply_status: 'degraded' })).toBe(same);
+ });
+
+ it('moves for an inventory the user never touched from this page', () => {
+ // Round 18. Everything else in this key is a surface of THIS drawer, so the
+ // key was blind to the one chain change that arrives from outside it: a
+ // discovery, a key replacement or a re-auth in another client changes what a
+ // source supplies, eligibility runs over that inventory, and membership moves
+ // with every surface here identical. The two lists above only notice it by
+ // being pruned — and an agent with neither has nothing inventory-derived left.
+ const withGlm = [source({ id: 'src_a', models: [{ id: 'glm-5.2', provenance: 'discovered' }] })];
+ const same = key({}, 'follow', ['src_a'], withGlm);
+ expect(key({}, 'follow', ['src_a'], withGlm)).toBe(same);
+ // Discovered a second model: same policy, order, model, mappings and menu.
+ expect(
+ key({}, 'follow', ['src_a'], [
+ source({
+ id: 'src_a',
+ models: [
+ { id: 'glm-5.2', provenance: 'discovered' },
+ { id: 'glm-5.3', provenance: 'discovered' },
+ ],
+ }),
+ ]),
+ ).not.toBe(same);
+ // Stripped back to nothing — what a fail-closed re-auth leaves behind.
+ expect(key({}, 'follow', ['src_a'], [source({ id: 'src_a', models: [] })])).not.toBe(same);
+ // A source that `order` does not name still counts, because under `follow`
+ // order is a recommendation and eligibility is what puts a source in the chain.
+ expect(
+ key({}, 'follow', ['src_a'], [...withGlm, source({ id: 'src_b', models: [{ id: 'gpt-6', provenance: 'discovered' }] })]),
+ ).not.toBe(same);
+ });
+
+ it('holds still for a source whose health moved but whose inventory did not', () => {
+ // The reason the member above is safe to key on, and it is the same argument
+ // as the opencode exclusion read the other way: an inventory is not health.
+ // `_cooldown` and `_set_source_blocker` — the only two writers a failing 试跑
+ // reaches — assign `source.state` and nothing else. If this ever moved, the
+ // probe would erase its own answer.
+ const models = [{ id: 'glm-5.2', provenance: 'discovered' as const }];
+ const same = key({}, 'follow', ['src_a'], [source({ id: 'src_a', models })]);
+ expect(
+ key({}, 'follow', ['src_a'], [
+ source({ id: 'src_a', models, state: { status: 'cooldown', retry_at: '2026-07-30T13:00:00Z' } }),
+ ]),
+ ).toBe(same);
+ expect(
+ key({}, 'follow', ['src_a'], [
+ source({ id: 'src_a', models, state: { status: 'needs_action', detail_key: 'models.source.oauth_expired' } }),
+ ]),
+ ).toBe(same);
+ // Nor for the order the inventory happens to come back in.
+ expect(
+ key({}, 'follow', ['src_a'], [
+ source({
+ id: 'src_a',
+ models: [
+ { id: 'b', provenance: 'discovered' },
+ { id: 'a', provenance: 'discovered' },
+ ],
+ }),
+ ]),
+ ).toBe(
+ key({}, 'follow', ['src_a'], [
+ source({
+ id: 'src_a',
+ models: [
+ { id: 'a', provenance: 'discovered' },
+ { id: 'b', provenance: 'discovered' },
+ ],
+ }),
+ ]),
+ );
+ });
+
+ 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.
+ expect(key({ ...oc, menu: { view: 'full', checked: ['openai/gpt-6'] } })).not.toBe(key(oc));
+ });
+
+ it('does not move for the order the mappings were written in', () => {
+ // `mappings` is a set the user edits by toggling; the API makes no ordering
+ // promise about it, and a re-read that returns the same overrides in another
+ // order would otherwise clear the report.
+ expect(
+ key({
+ mappings: [
+ { builtin_id: 'b', target_model_id: 'y', enabled: true },
+ { builtin_id: 'a', target_model_id: 'x', enabled: true },
+ ],
+ }),
+ ).toBe(
+ key({
+ mappings: [
+ { builtin_id: 'a', target_model_id: 'x', enabled: true },
+ { builtin_id: 'b', target_model_id: 'y', enabled: true },
+ ],
+ }),
+ );
+ });
+
+ it('moves for the order menu.checked was written in, because there order IS the pick', () => {
+ // Round 19, and this test used to assert the opposite — `checked` was
+ // canonicalized beside `mappings` as though both were sets. On opencode with
+ // no explicit request the resolver walks `checked` and takes the FIRST
+ // identifier whose source is runnable (`resolver.py:171-182`), so [A, B] and
+ // [B, A] are different turns — different model, possibly different source —
+ // with identical membership. `selected_model_id` is excluded there, so this
+ // list is the only thing in the key that can carry the difference. Nothing on
+ // this page writes `checked`, so a re-order arrives the way an inventory
+ // change does: from another client. `savedMenuKey` reads it in order too.
+ const oc = { backend: 'opencode' as const, menu_kind: 'open' as const };
+ expect(key({ ...oc, menu: { view: 'full', checked: ['a', 'b'] } })).not.toBe(
+ key({ ...oc, menu: { view: 'full', checked: ['b', 'a'] } }),
+ );
+ // The fixed-menu backends resolve through `selected_model_id`, so the order
+ // decides nothing for them — this member stays sensitive anyway rather than
+ // branching per backend. The whole cost is a still-true report cleared by an
+ // edit that did not matter, and the user answers that by re-running; the other
+ // direction is a sentence about a chain that moved. Only one is a wrong answer.
+ expect(key({ menu: { view: 'featured', checked: ['a', 'b'] } })).not.toBe(
+ key({ menu: { view: 'featured', checked: ['b', 'a'] } }),
+ );
+ });
+
+ it('keeps the parts apart', () => {
+ // A key is only as good as its separators: 「order a, model b」 and 「order a>b,
+ // no model」 are different chains and must not collide.
+ expect(key({ selected_model_id: 'src_b' }, 'follow', ['src_a'])).not.toBe(
+ key({ selected_model_id: '' }, 'follow', ['src_a', 'src_b']),
+ );
+ });
+});
+
+describe('dryRunOutcome — what the probe came back with (SourceOrderDrawer)', () => {
+ it('names the source the server actually started from', () => {
+ // Not the first row in the order: the point of a dry run is which source the
+ // chain resolved to, which can differ from what the list suggests.
+ expect(dryRunOutcome(probe({ source_id: 'src_b' }), [source(), source({ id: 'src_b', display_name: 'Key B' })])).toEqual({
+ kind: 'ok',
+ sourceName: 'Key B',
+ latencyMs: 412,
+ });
+ });
+
+ it('falls back to the id when the source is gone', () => {
+ // Same tolerance `chainChips` keeps: an id that no longer resolves is still
+ // more informative than an empty name.
+ expect(dryRunOutcome(probe({ source_id: 'src_gone' }), [])).toEqual({
+ kind: 'ok',
+ sourceName: 'src_gone',
+ latencyMs: 412,
+ });
+ });
+
+ it('keeps a null latency null instead of inventing a zero', () => {
+ // This is the native_cli answer: the server reports the CLI's readiness and
+ // measures nothing, because it never sent a request. 「可用」 without a number
+ // is the honest line; a 0 ms would be a measurement nobody took. The channel
+ // travels with it — v4 makes null latency the native branch's ALWAYS and the
+ // reachable-hub branch's never, so a hub fixture here would assert the copy
+ // over a result the contract cannot produce.
+ expect(dryRunOutcome(probe({ channel: 'native_cli', latency_ms: null }), [source()])).toEqual({
+ kind: 'ok',
+ sourceName: 'Key A',
+ latencyMs: null,
+ });
+ });
+
+ it('carries the native unavailability key, which no source-state key spells', () => {
+ // v4's other native outcome, and the reason `detailKey` is widened past
+ // `state.detail_key`: process unavailability is a fact about this serving
+ // process, not about the account, so the ten source-state keys cannot say it.
+ // Typing it is not enough — a mirror that is only `cast` is exactly how the
+ // last drift got through, so the value is asserted end to end here.
+ expect(
+ dryRunOutcome(
+ probe({ channel: 'native_cli', reachable: false, latency_ms: null, error: 'models.probe.native_cli_unavailable' }),
+ [source()],
+ ),
+ ).toEqual({ kind: 'failed', sourceName: 'Key A', detailKey: 'models.probe.native_cli_unavailable' });
+ });
+
+ it('carries the server’s reason through on a failure', () => {
+ expect(
+ dryRunOutcome(probe({ reachable: false, latency_ms: null, error: 'models.source.needs_action.credential_revoked' }), [
+ source(),
+ ]),
+ ).toEqual({ kind: 'failed', sourceName: 'Key A', detailKey: 'models.source.needs_action.credential_revoked' });
+ });
+
+ it('still reports a failure when the server named no reason', () => {
+ // `error` is null iff reachable, so this pair should not occur — but the copy
+ // must not depend on that, and a null key degrades to the generic line rather
+ // than rendering 「undefined」.
+ expect(dryRunOutcome(probe({ reachable: false, error: null }), [source()])).toEqual({
+ kind: 'failed',
+ sourceName: 'Key A',
+ detailKey: null,
+ });
+ });
+});
+
+describe('probeWroteState — whether 试跑 left a mark the page has to re-read', () => {
+ it('treats a failing probe as a write', () => {
+ // `probe_agent` cools the head down or blocks it on the way out, so the row
+ // states and ● 当前 behind the sheet are stale the moment this returns. The
+ // key here is one of the five `_cooldown` reasons, i.e. the branch that
+ // writes `retry_at` onto the source the chain resolved to.
+ expect(
+ probeWroteState(probe({ reachable: false, latency_ms: null, error: 'models.source.cooldown.server_error' })),
+ ).toBe(true);
+ });
+
+ it('treats a failing NATIVE probe as a write too, deliberately', () => {
+ // The native branch returns before the write block, so today this is a read
+ // the rule over-counts. Pinned as a decision rather than left implicit:
+ // keying on the channel would oblige every caller to track which branch of
+ // `probe_agent` writes, and the failure modes are not symmetric — being
+ // wrong this way costs one request on a button the user pressed, the other
+ // way it costs a page that silently disagrees with the server.
+ expect(
+ probeWroteState(
+ probe({ channel: 'native_cli', reachable: false, latency_ms: null, error: 'models.probe.native_cli_unavailable' }),
+ ),
+ ).toBe(true);
+ });
+
+ it.each(['hub', 'native_cli'] as const)('reads a reachable %s probe as a pure read', (channel) => {
+ // The write block sits entirely under `if not reachable`, and no path clears
+ // a cooldown on success — so a green 试跑 must NOT refetch, or every check
+ // costs the page two extra requests for nothing.
+ expect(probeWroteState(probe({ channel, latency_ms: channel === 'hub' ? 412 : null }))).toBe(false);
+ });
+});
+
+describe('probeArrival — an answer nobody wants can still be one the page owes', () => {
+ const failing = probe({ reachable: false, latency_ms: null, error: 'models.source.cooldown.server_error' });
+
+ it('shows and re-reads when the failure is still the answer to the question asked', () => {
+ expect(probeArrival({ kind: 'result', probe: failing }, true)).toEqual({ report: true, reread: true });
+ });
+
+ it('re-reads a failure the row will NOT draw', () => {
+ // The case: the user reorders while the probe is out. That edit bumped `seq`,
+ // so this response is no longer about the chain on screen — but it cooled a
+ // source down, and the edit's own PUT refetch went out BEFORE this returned, so
+ // it read the source back healthy. Dropping the arrival wholesale is what left
+ // the row green under a head the server had already moved.
+ expect(probeArrival({ kind: 'result', probe: failing }, false)).toEqual({ report: false, reread: true });
+ });
+
+ it('re-reads nothing for a reachable probe, current or stale', () => {
+ // Provably no write: the block sits entirely under `if not reachable`, and no
+ // path clears a cooldown on success.
+ expect(probeArrival({ kind: 'result', probe: probe() }, true)).toEqual({ report: true, reread: false });
+ expect(probeArrival({ kind: 'result', probe: probe() }, false)).toEqual({ report: false, reread: false });
+ });
+
+ it('trusts a throw the server NAMED to have written nothing', () => {
+ // An engine failure propagates out above the write block — one of the outcomes
+ // `probeWroteState` checked one by one, and every one of them arrives as a
+ // structured failure.
+ expect(probeArrival({ kind: 'thrown', serverNamed: true, code: 'engine_down' }, true)).toEqual({
+ report: true,
+ reread: false,
+ });
+ });
+
+ it('re-reads a throw the server did not name', () => {
+ // Not one of the route's outcomes at all — a lost connection, an unparseable
+ // body. The probe may have run and written with the answer lost on the way
+ // back, and unknown is not the same as no. Owed even when the row is stale and
+ // will draw no error line.
+ const unnamed = { kind: 'thrown', serverNamed: false, code: 'bad_response' } as const;
+ expect(probeArrival(unnamed, true)).toEqual({ report: true, reread: true });
+ expect(probeArrival(unnamed, false)).toEqual({ report: false, reread: true });
+ });
+
+ it('re-reads a refusal that wrote nothing and disproved the head anyway', () => {
+ // The second, independent reason. `probe_no_candidate` is raised before any
+ // write — so 「did it write?」 says no, correctly — and yet the 试跑 button the
+ // user pressed was drawn from a chain WITH a runnable head, so the refusal is
+ // the server reporting that head gone. Left un-reread, the chip keeps naming a
+ // source and the button keeps inviting a run that cannot happen.
+ expect(probeArrival({ kind: 'thrown', serverNamed: true, code: 'probe_no_candidate' }, true)).toEqual({
+ report: true,
+ reread: true,
+ });
+ // `direct_mode` is the same sentence about the mode the drawer believes it is in.
+ expect(probeArrival({ kind: 'thrown', serverNamed: true, code: 'direct_mode' }, false)).toEqual({
+ report: false,
+ reread: true,
+ });
+ });
+
+ it('keeps the two reasons independent', () => {
+ // Neither subsumes the other: an unnamed failure with no code still re-reads,
+ // and a named refusal that is not state-precondition still does not.
+ expect(probeArrival({ kind: 'thrown', serverNamed: false, code: null }, true).reread).toBe(true);
+ expect(probeArrival({ kind: 'thrown', serverNamed: true, code: 'source_last_supplier' }, true).reread).toBe(
+ false,
+ );
+ });
+
+ it('is how the drawer reads its own probe, at both arrivals', () => {
+ // The regression this replaces was a `return` on the staleness guard ABOVE the
+ // refetch, so the shape matters as much as the rule: no early exit may sit
+ // between a probe arriving and the page being corrected.
+ const drawer = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'SourceOrderDrawer.tsx'), 'utf8');
+
+ expect(drawer).not.toMatch(/if \(seq\.current !== mine\) return;/);
+ expect((drawer.match(/probeArrival\(/g) ?? []).length).toBe(2);
+ expect(drawer).toMatch(/if \(arrival\.reread\) reread\(\);/);
+ // And takes `serverNamed` from the error rather than inferring it from 「is it
+ // one of ours?」 — `bad_response` is one of ours and names nothing, so that
+ // inference skipped the reread in the one case it was added for.
+ expect(drawer).toMatch(/serverNamed: failure\?\.serverNamed \?\? false/);
+ expect(drawer).not.toMatch(/serverNamed: failure !== null/);
+ // The code rides along so the second reason can be asked at all.
+ expect(drawer).toMatch(/code: failure\?\.code \?\? null/);
+ });
+});
+
+describe('disprovedDrawnHead — a refusal that is news about the chain', () => {
+ it('names the two state-precondition refusals', () => {
+ expect(disprovedDrawnHead('probe_no_candidate')).toBe(true);
+ expect(disprovedDrawnHead('direct_mode')).toBe(true);
+ });
+
+ it('leaves every other refusal alone', () => {
+ // A supply refusal or an engine outage says nothing about whether the head this
+ // page drew is still there.
+ expect(disprovedDrawnHead('source_last_supplier')).toBe(false);
+ expect(disprovedDrawnHead('engine_down')).toBe(false);
+ expect(disprovedDrawnHead(null)).toBe(false);
+ });
+
+ it('matches the codes the server actually raises', () => {
+ // Both are `ModelHubError` codes on the probe route (`probe_no_candidate` at the
+ // no-runnable-candidate branch, `direct_mode` from `_direct_mode_error`), so a
+ // rename server-side has a test here to fail against.
+ expect(['probe_no_candidate', 'direct_mode'].every((code) => disprovedDrawnHead(code))).toBe(true);
+ });
+});
+
+describe('mayHaveWritten — the same unknown, wherever it is caught', () => {
+ it('calls a named refusal a decided outcome', () => {
+ expect(mayHaveWritten({ serverNamed: true })).toBe(false);
+ });
+
+ it('calls an unnamed failure unknown', () => {
+ // `bad_response` / `http_<n>`: minted by the transport for an answer that never
+ // said what happened, which is as consistent with 「committed」 as with 「never ran」.
+ expect(mayHaveWritten({ serverNamed: false })).toBe(true);
+ });
+
+ it('calls a throw that is not ours unknown too', () => {
+ // Reaching it means our own code threw AFTER the await, which puts the write
+ // strictly in the past.
+ expect(mayHaveWritten(null)).toBe(true);
+ });
+
+ it('is what 更换 API Key re-reads on', () => {
+ // The write is atomic and re-discovers on commit, so a lost answer leaves the
+ // row showing the old key's state while 更换 would provision a second
+ // replacement. Reporting the error and re-reading the rows are not alternatives.
+ const dialog = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'ReplaceKeyDialog.tsx'), 'utf8');
+
+ expect(dialog).toMatch(/if \(mayHaveWritten\(failure\)\) onReplaced\(\);\n\s*setPhase\('error'\);/);
+ // The named refusal above it still returns before this, and still writes nothing.
+ expect(dialog).toMatch(/failure\?\.code === 'source_last_supplier' && !force/);
+ });
+
+ it('is one owner, not a predicate re-derived per caller', () => {
+ const here = dirname(fileURLToPath(import.meta.url));
+ for (const file of ['ReplaceKeyDialog.tsx', 'SourceOrderDrawer.tsx', 'SourceRowMenu.tsx']) {
+ expect(readFileSync(join(here, file), 'utf8')).not.toMatch(/!\(?failure\?\.serverNamed/);
+ }
+ });
+
+ it('is not the question 删除 asks, so 删除 does not ask it', () => {
+ // Round 17's finding, and why it is answered without a gate rather than with
+ // this one. 更换 API Key asks 「did MY write land?」, because the cost of getting
+ // it wrong is provisioning a second replacement — `mayHaveWritten` is that
+ // question. A failed DELETE asks 「are the rows I am drawing still right?」, and
+ // the two come apart on both sides: a commit whose answer was lost is unknown
+ // AND stale, while `source_not_found` is server-NAMED, wrote nothing, and is
+ // news precisely because the row is already gone — the same shape
+ // `disprovedDrawnHead` above exists for. Gating on 「may it have written」 would
+ // leave that phantom row on screen until something else happened to refetch.
+ //
+ // So it re-reads either way, for the reason `releaseFlow` gives: a redundant
+ // re-read is inert, a missing one is the bug. The guarded refusal still leaves
+ // through the branch above this one, having provably written nothing.
+ const menu = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'SourceRowMenu.tsx'), 'utf8');
+
+ expect(menu).not.toMatch(/mayHaveWritten/);
+ expect(menu).toMatch(/onChanged\(\);\n\s*showToast\(t\('settings\.models\.sourceActions\.deleteFailed'/);
+ // Both delete outcomes now reach the page: the refusal escalates to a second
+ // confirm, everything else closes and re-reads.
+ expect(menu).toMatch(/failure\?\.code === 'source_last_supplier' && !forceMode/);
+ });
+});
+
+describe('dryRunRowView — a report that outlives the chain it was about', () => {
+ const idle = { line: null, saving: false, running: false };
+
+ it('offers a live control while the chain has a head', () => {
+ expect(dryRunRowView(dryRunPlan(agent()), idle)).toEqual({ backend: 'claude', enabled: true, report: false });
+ });
+
+ it('keeps the answer on screen after 试跑 itself took the head away', () => {
+ // The case the row creates: probing the chain's last runnable source and
+ // failing cools that source down, so the re-read `probeWroteState` demands
+ // comes back with `current: null` — and the plan the row is drawn from turns
+ // `none` under the sentence the click just produced. Dropping it there would
+ // make the failing run the only one whose answer flashes past.
+ const headless = dryRunPlan(agent({ current: null, supply_status: 'interrupted' }));
+
+ expect(dryRunRowView(headless, { ...idle, line: 'Key A 没跑通' })).toEqual({
+ backend: null,
+ enabled: false,
+ report: true,
+ });
+ });
+
+ it('draws nothing when there is neither a head nor an answer', () => {
+ // Direct mode, or a chain that was already stopped when the drawer opened. The
+ // page states that one level up with the remedy attached; an empty row here, or
+ // a disabled button, would only repeat it.
+ expect(dryRunRowView(dryRunPlan(agent({ mode: 'direct', sources: null, current: null })), idle)).toEqual({
+ backend: null,
+ enabled: false,
+ report: false,
+ });
+ });
+
+ it('holds the probe while the order PUT is still in flight', () => {
+ // The save is optimistic: the list and the chain key the report is filed under
+ // have already moved to the order the user dropped, while the server still
+ // answers for the old one. A probe in that window reports on the superseded
+ // chain under the new one's key — and the key cannot clear it, because it IS
+ // the new key. The control stays drawn and goes disabled, like every other
+ // control in this drawer.
+ expect(dryRunRowView(dryRunPlan(agent()), { ...idle, saving: true })).toEqual({
+ backend: 'claude',
+ enabled: false,
+ report: false,
+ });
+ });
+
+ it('holds it while a probe is already running', () => {
+ expect(dryRunRowView(dryRunPlan(agent()), { ...idle, running: true })).toEqual({
+ backend: 'claude',
+ enabled: false,
+ report: false,
+ });
+ });
+});
+
+describe('the class: no component decides a repair for itself', () => {
+ const here = dirname(fileURLToPath(import.meta.url));
+ const files = readdirSync(here, { recursive: true, encoding: 'utf8' }).filter(
+ (f) => /\.tsx?$/.test(f) && !/\.test\.tsx?$/.test(f),
+ );
+ const read = (f: string) => readFileSync(join(here, f), 'utf8');
+
+ it('sweeps a non-trivial file set', () => {
+ // Without this the two rules below pass over an empty list after any move.
+ expect(files.length).toBeGreaterThan(15);
+ expect(files).toContain('SourceRowMenu.tsx');
+ });
+
+ /**
+ * 「is this source stopped?」 as a component's own comparison. `wasBlocked` owns
+ * it, and it is deliberately narrower than `needsAttention` next door by exactly
+ * one cooldown — a component that re-asks with `===` will get that boundary
+ * wrong in one direction or the other. Comparisons against 'cooldown' are a
+ * different question (the retry ETA) and stay allowed.
+ */
+ const BLOCKED_PROXY = /\.state\.status\s*[=!]==?\s*'(?:needs_action|error)'/;
+
+ it.each(files.filter((f) => f.endsWith('.tsx')))('%s asks wasBlocked instead of the status', (name) => {
+ expect(read(name)).not.toMatch(BLOCKED_PROXY);
+ });
+
+ /**
+ * 「did anything get stranded?」 as an emptiness test. `repairOutcome` owns it,
+ * and it ranks the gap report ABOVE `recovered` — a site that reads the array
+ * itself is one `if` away from congratulating the user on a repair that broke
+ * another Agent.
+ */
+ const GAP_PROXY = /interrupted_pairs\)?(?:\s*\?)?\.length/;
+
+ it('leaves the gap verdict to its owner', () => {
+ const offenders = files.filter((f) => f !== 'repair.ts' && GAP_PROXY.test(read(f)));
+ expect(offenders).toEqual([]);
+ });
+
+ /**
+ * An ASSEMBLED repair locale key. This is the class round 2 caught: a template
+ * literal over a union typechecks for every member, so the one member the bundle
+ * spells differently (`replace_key` → `replaceKey`) shipped as a raw key path on
+ * screen. `REPAIR_LABEL_KEY` / `REPAIR_LINE_KEY` are the versions the compiler
+ * checks and the tests above prove translated; the maps are where a repair key
+ * gets composed, and nowhere else.
+ *
+ * A LITERAL `t('settings.models.repair.gapsDone')` is not this bug and stays
+ * allowed: the failure mode is the substitution, not the namespace.
+ *
+ * `repair.ts` is exempt because its own docs QUOTE the bad form to explain why
+ * the maps exist, and it holds no `t` to render one with.
+ */
+ const ASSEMBLED_KEY = /settings\.models\.repair\.\$\{/;
+
+ it.each(files.filter((f) => f !== 'repair.ts'))('%s looks a repair key up instead of building it', (name) => {
+ expect(read(name)).not.toMatch(ASSEMBLED_KEY);
+ });
+
+ /**
+ * A hand-assembled 试跑 chain key. This is the class round 14 caught: the drawer
+ * built `${policy}|${order.join('>')}` inline, which is a complete statement of
+ * the chain only while nothing else selects the probed turn — and the model menu
+ * next door always did. Inline, the omission is invisible; behind
+ * `dryRunChainKey` it is one function's business, and the test above says which
+ * surfaces belong to it.
+ */
+ const INLINE_CHAIN_KEY = /chainKey=\{`/;
+
+ it('leaves the chain key to its owner', () => {
+ const offenders = files.filter((f) => INLINE_CHAIN_KEY.test(read(f)));
+ expect(offenders).toEqual([]);
+ expect(read('SourceOrderDrawer.tsx')).toMatch(
+ /chainKey=\{dryRunChainKey\(agent, policy, order, sources\)\}/,
+ );
+ });
+
+ /**
+ * A translated sentence put into state. `serverText` needs `t`, so whatever it
+ * returns is copy in ONE language — stored, it survives the language switch that
+ * re-renders everything around it, and the row ends up bilingual with itself. The
+ * reason keeps; the sentence is built where it is read.
+ */
+ const STORED_SENTENCE = /set[A-Z][A-Za-z]*\(\s*(?:serverText|failedLine|t)\(/;
+
+ it.each(files)('%s stores the reason and renders the sentence', (name) => {
+ expect(read(name)).not.toMatch(STORED_SENTENCE);
+ });
+
+ it('keeps the dry-run failure as a reason, three states and all', () => {
+ const src = read('SourceOrderDrawer.tsx');
+ // `{ key: null }` is not the same as `null`: 「it failed and nobody named why」
+ // has a sentence (the generic line), 「nothing ran yet」 has none.
+ expect(src).toMatch(/useState<\{ key: string \| null \} \| null>\(null\)/);
+ expect(src).toMatch(/setErrorReason\(\{ key: failure\?\.detail \?\? null \}\)/);
+ expect(src).toMatch(/errorReason && serverText\(t, errorReason\.key, 'settings\.models\.dryRun\.error'\)/);
+ });
+});
diff --git a/ui/src/components/settings/models/repair.ts b/ui/src/components/settings/models/repair.ts
new file mode 100644
index 000000000..2ec63fce7
--- /dev/null
+++ b/ui/src/components/settings/models/repair.ts
@@ -0,0 +1,609 @@
+// The supply JOURNEYS' decisions — which remedy a stopped source actually has,
+// what the server's answer to a repair means, and whether 试跑 has anything real
+// to run. Same shape and same reason as `supply.ts` / `sufficiency.ts`: each of
+// these is a judgement the components are not free to improvise, this repo's
+// vitest has no DOM, so they are plain functions over the contract types.
+//
+// §4.5 is what makes the first one load-bearing: `needs_action` 「carries a
+// detail_key naming the cause, so the row can offer ONE TAP to fix it (re-auth,
+// top up, replace key) instead of a dead-end error string」. A row that renders
+// the cause and stops is the dead end that sentence forbids.
+import type {
+ AgentBackend,
+ AgentSupply,
+ ProbeErrorKey,
+ ProbeResult,
+ Source,
+ SourceDetailKey,
+ SourcePolicy,
+ SourceRepaired,
+ SourceState,
+ SupplyGap,
+} from './types';
+
+/**
+ * The two statuses a repair can recover from, and the exact set the server calls
+ * `recovered` over (`state.status in {needs_action, error}`).
+ *
+ * Deliberately NOT `needsAttention`, which is wider by one: an 额度用完 cooldown
+ * earns the gold sub-line but heals itself on the billing cycle, and offering it
+ * a repair button would put a one-tap fix on the one blocker that does not need
+ * one. Deliberately NOT `isUnhealthy` either, which is wider by all three
+ * cooldowns. Three predicates, three different questions.
+ */
+export const wasBlocked = (state: SourceState): boolean =>
+ state.status === 'needs_action' || state.status === 'error';
+
+// ── Which remedy a source HAS (independent of whether it needs one) ──────
+// These three mirror the server's own preconditions, one for one, so the menu
+// offers exactly the actions the routes accept. The elective entries read these;
+// the blocked row's inline button reads `repairAction` below.
+
+/** `POST …/reauth` accepts subscriptions on BOTH channels — a hub-held grant is
+ * re-obtained by logging in again just as a native CLI login is. */
+export const canReauth = (source: Source): boolean => source.kind === 'subscription';
+
+/** `PUT …/credential` is hub-channel api_key only, and needs an existing
+ * credential to replace (`kind != api_key || channel != hub || !credential_ref`
+ * ⇒ `discovery_failed`). */
+export const canReplaceKey = (source: Source): boolean =>
+ source.kind === 'api_key' && source.supply_channel === 'hub' && Boolean(source.credential_ref);
+
+/** `POST …/test` is the contract's ONE recovery endpoint (「v3 does not add a
+ * second 'recover' endpoint」) and rejects native sources, which have nothing to
+ * re-discover. */
+export const canRetest = (source: Source): boolean => source.supply_channel === 'hub';
+
+/** What a stopped row offers as its one tap. */
+export type RepairKind = 'reauth' | 'replace_key' | 'retest';
+
+/** Causes whose fix is a NEW credential, held by Avibe: the grant or the key
+ * itself stopped working, and only replacing it can help. */
+const CREDENTIAL_CAUSES: ReadonlySet<SourceDetailKey> = new Set<SourceDetailKey>([
+ 'models.source.needs_action.oauth_expired',
+ 'models.source.needs_action.credential_revoked',
+]);
+
+/** 「The last sign-in produced nothing usable」 — the whole of `ErrorDetailKey`,
+ * and on a native source the only blocker another sign-in can actually clear.
+ * Rule 3 in `repairAction` is what reads it. */
+const SIGN_IN_INCOMPLETE: SourceDetailKey = 'models.source.error.unclassified';
+
+/**
+ * The one-tap remedy for a blocked source, or null when it genuinely has none.
+ *
+ * Two rules, no per-cause table:
+ *
+ * 1. The credential itself failed → replace it, by the route that owns that
+ * source's kind of credential (login for a subscription, key for an api_key).
+ * 2. Anything else → Avibe cannot name the cause and must not pretend to; what
+ * it can do is stop guessing and re-check, which is exactly what the recovery
+ * test is for. The row's affordance is 「handled it — retry」, not 「top up
+ * here」, because no contract field carries a vendor billing URL and a button
+ * that cannot go there would be the dead end again.
+ * 3. …unless the source has no recovery test at all (native) AND its blocker is
+ * the one a fresh sign-in clears — then re-login, because rule 2 would
+ * otherwise leave that row with no tap whatsoever. Narrow on purpose: the
+ * branch comment carries the cost argument for why it is not every cause.
+ *
+ * A healthy source has no remedy to offer because it has no problem — the caller
+ * renders nothing, not a disabled button.
+ */
+export function repairAction(source: Source): RepairKind | null {
+ if (!wasBlocked(source.state)) return null;
+ const credentialFailed = Boolean(source.state.detail_key && CREDENTIAL_CAUSES.has(source.state.detail_key));
+ if (credentialFailed) {
+ if (canReauth(source)) return 'reauth';
+ if (canReplaceKey(source)) return 'replace_key';
+ return null;
+ }
+ if (canRetest(source)) return 'retest';
+ // Native has no recovery test — `test_source` refuses `native_cli` outright — so
+ // rules 1 and 2 together leave a stopped native row with no tap at all, its
+ // remedy surviving only in the overflow menu. Rule 3 covers the one cause where
+ // signing in again is the answer rather than a guess, and the cause matters
+ // because this fallback SPENDS something: a native re-login invalidates the
+ // current sign-in before the vendor page even loads (`reauthCost` below), so
+ // offering it for a blocker it cannot fix is the §4.5 dead end plus a bill.
+ //
+ // `error.unclassified` earns it. It is the only key `ErrorDetailKey` holds, and
+ // it reaches a NATIVE source from exactly two places, both inside a native
+ // re-login: `completed_source_status` threw, or post-login discovery came back
+ // empty. It means 「that sign-in produced nothing usable」, so another one is the
+ // convergent recovery — and without this the two sibling writes of one backend
+ // helper contradict each other, `_mark_native_reauth_unavailable`'s needs_action
+ // branch keeping the button (its key is a credential cause) while its error
+ // branch loses it. A declared upstream cause like 余额耗尽 does NOT earn it, and
+ // the native/`account_banned` case in `repair.test.ts` is that boundary.
+ return source.state.detail_key === SIGN_IN_INCOMPLETE && canReauth(source) ? 'reauth' : null;
+}
+
+/**
+ * A remedy's label key. A Record over the union, never a template literal:
+ * `t(`settings.models.repair.${kind}`)` compiles for every member and then
+ * renders the raw key path for the one the bundle spells differently
+ * (`replace_key` → `replaceKey`), which is what a blocked api_key row showed. As
+ * a Record the compiler refuses a new RepairKind that has no label, and
+ * `repair.test.ts` proves each one is translated in both locales.
+ */
+export const REPAIR_LABEL_KEY: Record<RepairKind, string> = {
+ reauth: 'settings.models.repair.reauth',
+ replace_key: 'settings.models.repair.replaceKey',
+ retest: 'settings.models.repair.retest',
+};
+
+/**
+ * What STARTING a re-login costs on this source's channel — the confirm's whole
+ * subject, and the one thing about it the two channels do not share.
+ *
+ * `immediate`: a native re-login is irreversible up front.
+ * `mark_native_irreversible_start` runs as the login spawns and rewrites every
+ * native source of that vendor's backend to 需要处理 with its discovered models
+ * stripped; it is rolled back only when the login fails to SPAWN. The price is
+ * paid on 「开始」, whatever happens next.
+ *
+ * And it is not paid back in full: the sentence has to say so, because success
+ * restores only the source the dialog is about. `_materialize_completed_oauth`
+ * re-discovers onto THAT one; its siblings on the shared CLI keep the empty
+ * inventory and the 需处理 the start wrote, each needing its own sign-in
+ * (`tests/test_model_hub_api.py::test_native_reauth_invalidates_sibling_sources_for_shared_cli`).
+ * 「until you finish」 alone reads as a wait, which is the one thing this is not.
+ *
+ * `on_failure`: a hub re-login writes nothing at start — the held credential goes
+ * on working while the user signs in. The cost arrives only if the flow comes
+ * back `failed`, where `_fail_closed_hub_reauth` marks the source 需要处理 because
+ * Avibe cannot tell whether the vendor invalidated the old grant. Closing the
+ * dialog cancels the flow, and a cancelled flow is not a failed one.
+ *
+ * Two costs, two sentences. One sentence over both is false on one of them, and
+ * 「the old sign-in stops working as soon as you start」 is false on hub in the
+ * direction that matters: it warns about a loss that does not happen, and says
+ * nothing about the one that does.
+ */
+export type ReauthCost = 'immediate' | 'on_failure';
+
+export const reauthCost = (source: Source): ReauthCost =>
+ source.supply_channel === 'native_cli' ? 'immediate' : 'on_failure';
+
+const REAUTH_BODY_KEY: Record<ReauthCost, string> = {
+ immediate: 'settings.models.repair.reauthBody.immediate',
+ on_failure: 'settings.models.repair.reauthBody.onFailure',
+};
+
+/** The confirm body that is TRUE for this source. */
+export const reauthBodyKey = (source: Source): string => REAUTH_BODY_KEY[reauthCost(source)];
+
+// ── What the server's repair answer MEANS ────────────────────────────────
+
+/**
+ * The verdict over a repair tail — the single owner of 「did that fix it?」, so
+ * the toast, the dialog's closing behaviour and the gap report cannot disagree.
+ *
+ * All three inputs are the server's own: `interrupted_pairs` is the output of the
+ * very guard that would have refused the write, `source.state` is where the write
+ * left the source, and `recovered` is its judgement that the source HAD been
+ * blocked. Nothing is re-derived here — a client that recomputed 「is anything
+ * stranded?」 from `/agents` would be answering a different question (today's
+ * supply) than the one it renders.
+ *
+ * The order is the point:
+ *
+ * 1. `gaps` outranks everything. A forced replacement that fixed this source
+ * while stranding another Agent's model is not a success story, and the
+ * report is the whole reason the user was asked to confirm.
+ * 2. Then the RETURNED STATE, because `recovered` is a statement about the past
+ * — 「it was blocked when this started」 — and cannot claim the source works
+ * now. A native reauth reaches exactly that case: `_materialize_reauth`
+ * commits `needs_action`/`oauth_expired` when the CLI still reports itself
+ * signed out, and answers 200 with `recovered: true` beside it. Reading
+ * `recovered` alone would put 「已恢复可用」 on a row that is still stopped and
+ * dismiss the dialog over it.
+ * 3. Only then 「was it broken before?」, which separates a repair from the
+ * elective rotation of a working credential.
+ */
+export type RepairOutcome =
+ | { kind: 'repaired' }
+ | { kind: 'refreshed' }
+ | { kind: 'unresolved' }
+ | { kind: 'gaps'; gaps: SupplyGap[] };
+
+export const repairOutcome = (tail: SourceRepaired): RepairOutcome =>
+ tail.interrupted_pairs.length > 0
+ ? { kind: 'gaps', gaps: tail.interrupted_pairs }
+ : wasBlocked(tail.source.state)
+ ? { kind: 'unresolved' }
+ : tail.recovered
+ ? { kind: 'repaired' }
+ : { kind: 'refreshed' };
+
+/**
+ * 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.
+ *
+ * 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
+ * that 1.4s is not long enough to read」. Written as an exclusion, the next verdict
+ * added would inherit the auto-close silently, which is the wrong default for a
+ * verdict that exists because something did not work.
+ */
+export const repairSettles = (outcome: RepairOutcome): boolean =>
+ outcome.kind === 'repaired' || outcome.kind === 'refreshed';
+
+/**
+ * A verdict's one line, by the same rule as `REPAIR_LABEL_KEY` above: the key is
+ * looked up, never assembled.
+ *
+ * `gaps` is absent deliberately, and the type says so — a gap report is a heading
+ * (`gapsDone`) over a list of pairs, not a sentence, so every caller branches on
+ * it before reaching this map and the compiler holds them to it.
+ */
+export type RepairLine = Exclude<RepairOutcome['kind'], 'gaps'>;
+
+export const REPAIR_LINE_KEY: Record<RepairLine, string> = {
+ repaired: 'settings.models.repair.repaired',
+ refreshed: 'settings.models.repair.refreshed',
+ unresolved: 'settings.models.repair.unresolved',
+};
+
+/**
+ * A verdict's TOAST — the line and the tone, decided together, for every kind.
+ *
+ * The toast is not the panel. A gap report renders there as a heading over a list
+ * of pairs, which is why the map above has no `gaps` entry; a toast has no list, so
+ * it needs a sentence for the one verdict that panel handles structurally.
+ *
+ * Tone belongs here for the reason the gap case proves: written at the call site as
+ * 「warning if unresolved, success otherwise」, the gap report got the one tone that
+ * contradicts its own text — a green 「连接成功」 over a dialog reporting that Agents
+ * now have no source at all. Tone is a property OF the verdict, not of the branch
+ * that happens to render it, and a Record over the full union makes the next
+ * verdict added answer for its own tone instead of inheriting green.
+ */
+export const REPAIR_TOAST: Record<RepairOutcome['kind'], { key: string; tone: 'success' | 'warning' }> = {
+ repaired: { key: REPAIR_LINE_KEY.repaired, tone: 'success' },
+ refreshed: { key: REPAIR_LINE_KEY.refreshed, tone: 'success' },
+ // The call succeeded and the source is still stopped: this page's gold 需处理
+ // tone, not a red failure.
+ unresolved: { key: REPAIR_LINE_KEY.unresolved, tone: 'warning' },
+ gaps: { key: 'settings.models.repair.gaps', tone: 'warning' },
+};
+
+// ── 试跑 (dry run) ───────────────────────────────────────────────────────
+
+/**
+ * Whether a dry run has anything real to run for this Agent.
+ *
+ * `none` covers direct mode (no `src_*` identity to report — the route refuses
+ * with `direct_mode`, AC-7) and a null `current`, which is precisely
+ * waiting/interrupted: there is no head, the page already says so with the
+ * remedy attached, and a probe would only re-report it as a failure.
+ *
+ * No `model` in the request on purpose. `current.model_id` is the RESOLVED id
+ * (post-mapping), while the route treats its `model` argument as the REQUESTED
+ * one and maps it again — passing the head back would resolve twice and probe a
+ * different model than the drawer displays. Omitted, the server uses the very
+ * `_requested_model(agent)` that produced `current`, so the probe and the row
+ * agree by construction rather than by a client-side guess.
+ *
+ * Note there is no `native` branch: 「don't fake a native test」 is honoured by
+ * the SERVER, which answers a native_cli head with its CLI readiness and
+ * `latency_ms: null` instead of sending a request. A client-side branch would
+ * have to invent that readiness — the copy keys on the null latency instead.
+ */
+export type DryRunPlan = { kind: 'probe'; backend: AgentBackend } | { kind: 'none' };
+
+/** A source's name for copy, falling back to its id — the same tolerance
+ * `chainChips` keeps for an id that no longer resolves. */
+const nameOf = (sources: Source[], id: string): string =>
+ sources.find((s) => s.id === id)?.display_name || id;
+
+export function dryRunPlan(agent: AgentSupply): DryRunPlan {
+ if (agent.mode !== 'hub') return { kind: 'none' };
+ if (!agent.current) return { kind: 'none' };
+ return { kind: 'probe', backend: agent.backend };
+}
+
+/**
+ * The identity of the chain a 试跑 report is ABOUT, so that a report outlives every
+ * refresh except the ones that make it answer for something else.
+ *
+ * The rule this obeys, and the reason it is not just 「everything on `agent`」: key
+ * on the surface the USER selects with, never on the pick the server RESOLVES from
+ * it. The probe deliberately sends no model, so the server resolves whichever
+ * selection is live at request time — which makes the selection part of the chain
+ * the report describes, not context around it. But resolution outputs move for a
+ * second reason: a failing probe cools its own head down, and keying on anything
+ * that moves for THAT reason erases the sentence the click just produced (the
+ * mistake this key was already once rebuilt to escape — see the reset effect in
+ * `SourceOrderDrawer.tsx`).
+ *
+ * So the members are the config-level ones, verified against the server rather than
+ * assumed:
+ *
+ * - `policy` / `order` as the USER currently has them, not as `agent.sources` holds
+ * them: a drag has already moved them before any PUT lands.
+ * - `mappings` — pruned only by `_available_model_ids`, which is
+ * `source_eligible_for_backend` over the inventory and reads no `state.status`
+ * and no cooldown. An inventory change is a real chain change; a cooldown cannot
+ * fake one.
+ * - `menu.checked` — same pruning via `_available_opencode_identifiers`, and for
+ * opencode this IS the selection surface. It goes in IN ORDER, unsorted, because
+ * on opencode the order is the selection: with no explicit request the resolver
+ * walks `checked` and takes the first identifier whose source is runnable
+ * (`resolver.py:171-182`), so `[A, B]` and `[B, A]` are different turns — a
+ * different model and possibly a different source — with the same membership.
+ * Nothing on this page writes `checked`, so a re-order arrives the way the
+ * inventory does, from another client; canonicalizing it here would hide exactly
+ * the change the member exists to catch. On the fixed-menu backends the order
+ * carries nothing, and the sensitivity costs at most a still-true report cleared
+ * 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.
+ *
+ * - 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
+ * paragraph on `mappings` claims 「an inventory change is a real chain change」
+ * while relying on the pruning of two lists to notice one. It does not always
+ * notice: an agent with no mappings and an empty `checked` has nothing
+ * inventory-derived in the key, and under the `follow` policy `order` is a
+ * recommendation rather than the membership — eligibility runs over the
+ * inventory (`source_eligible_for_backend`), so a discovery, a key replacement
+ * or a re-auth elsewhere can move a source in or out of the chain with every
+ * surface on this page untouched. Another client is enough; so is the same user
+ * in a second tab.
+ *
+ * Keying on it is safe for the reason the `selected_model_id` paragraph above is
+ * about, read the other way: an inventory is not health. The two writers a
+ * failing 试跑 reaches — `_cooldown` and `_set_source_blocker` — assign
+ * `source.state` and nothing else, so the probe cannot move this member and the
+ * self-erasing report that killed both remedies for the OpenCode gap cannot
+ * happen here. It is `models[].id` only: no `state`, no `usage`, no
+ * `retry_at`, no `provenance` (which changes without changing eligibility).
+ *
+ * Scope is every source, not the ones `order` names, precisely because of the
+ * `follow` case above — under that policy a source can join the chain without
+ * appearing in `order` first. The cost of being that broad is an unrelated
+ * source's discovery clearing a report that was still true, and the user re-runs
+ * 一次试跑; the cost of being narrow is a sentence that answers for a supplier
+ * chain that no longer exists. Only one of those two is a wrong answer.
+ *
+ * Excluded on purpose: `agent.current` and everything else about head health. The
+ * head moving is what a failing report is FOR.
+ */
+export const dryRunChainKey = (
+ agent: AgentSupply,
+ policy: SourcePolicy,
+ order: string[],
+ sources: Source[],
+): string =>
+ [
+ policy,
+ order.join('>'),
+ agent.backend === 'opencode' ? '' : (agent.selected_model_id ?? ''),
+ (agent.mappings ?? [])
+ .map((m) => `${m.builtin_id}>${m.target_model_id}:${m.enabled ? 'on' : 'off'}`)
+ .sort()
+ .join(','),
+ (agent.menu?.checked ?? []).join(','),
+ sources
+ .map((s) => `${s.id}:${s.models.map((m) => m.id).sort().join('+')}`)
+ .sort()
+ .join(';'),
+ ].join('|');
+
+/**
+ * The probe's own verdict, named for copy. `reachable` is the discriminator the
+ * contract pins (`error` is null iff reachable), so nothing else is consulted.
+ *
+ * A null `latencyMs` is not a missing measurement, it is the answer for a head
+ * the Hub does not carry the request for: the caller says 「可用」 without a
+ * number rather than printing a zero it did not measure.
+ *
+ * One copy constraint the key names badly: `models.probe.native_cli_unavailable`
+ * is NOT 「you are not signed in」. `_default_native_cli_ready` returns false when
+ * an ANTHROPIC_/OPENAI_ key or base-url overrides the CLI's own sign-in, when a
+ * codex login is genuinely absent, AND for every backend that has no native
+ * channel at all. The first case is the common one, and there the sign-in is
+ * perfectly valid — so the string states that the sign-in cannot be used and
+ * instructs nothing, the same rule that stopped `oauth_expired` from claiming a
+ * wall-clock expiry it cannot prove.
+ */
+export type DryRunOutcome =
+ | { kind: 'ok'; sourceName: string; latencyMs: number | null }
+ /** v4 widened the key set past `state.detail_key`: the native branch reports
+ * process unavailability, the case the paragraph above is about, and no
+ * source-state key can express it. */
+ | { kind: 'failed'; sourceName: string; detailKey: ProbeErrorKey | null };
+
+export function dryRunOutcome(probe: ProbeResult, sources: Source[]): DryRunOutcome {
+ const sourceName = nameOf(sources, probe.source_id);
+ return probe.reachable
+ ? { kind: 'ok', sourceName, latencyMs: probe.latency_ms }
+ : { kind: 'failed', sourceName, detailKey: probe.error };
+}
+
+/**
+ * Did that probe leave a mark on the server? 试跑 is a real turn, so a failing
+ * one is not a read: `probe_agent` routes the failure through `_cooldown` or
+ * `_set_source_blocker`, which changes the source's health and can move the
+ * Agent's head and supply rollup with it. A caller that only stores the verdict
+ * shows the row states the failure just invalidated.
+ *
+ * Deliberately 「any unreachable probe」 rather than 「an unreachable hub probe」.
+ * The native branch answers from `native_source_ready` and returns before the
+ * write block, so today it writes nothing — but keying on the channel would
+ * oblige every reader to track which branch writes, and the cost of being wrong
+ * is a stale page, while the cost of the extra read is one request on a button
+ * the user pressed. A reachable probe is the case that provably writes nothing:
+ * the write block sits entirely under `if not reachable`, and no path clears a
+ * cooldown on success.
+ *
+ * A thrown probe the server NAMED needs no re-read for the same reason, checked
+ * outcome by outcome: `probe_no_candidate` is raised before any write, and an
+ * engine failure propagates out of `_engine_call` above the write block. A throw
+ * the server did not name is not one of those outcomes — see `probeArrival`.
+ */
+export const probeWroteState = (probe: ProbeResult): boolean => !probe.reachable;
+
+/**
+ * Whether a caught failure leaves the server's state UNKNOWN to us — the one
+ * question two dialogs and this drawer all had to answer, so it lives once.
+ *
+ * `serverNamed` is the error's own account of where its code came from: the
+ * transport mints `bad_response` for a body that would not parse and `http_<n>`
+ * for one that parsed saying nothing, and a request that reached the route and
+ * lost its answer coming back is exactly as consistent with 「it committed」 as
+ * with 「it never ran」. A failure with no name is not one of the route's
+ * enumerated outcomes, so nothing about it can be checked outcome by outcome.
+ *
+ * `null` — a throw that is not an `ApiCallError` at all — counts as unknown for
+ * the same reason and one more: reaching it means our own code threw AFTER the
+ * await, which puts the server's write strictly in the past.
+ */
+export const mayHaveWritten = (failure: { serverNamed: boolean } | null): boolean =>
+ !(failure?.serverNamed ?? false);
+
+/**
+ * Refusals whose ARRIVAL disproves what the page was already drawing, whether or
+ * not they wrote anything.
+ *
+ * `probe_no_candidate` is the case: it is raised before any write (the chain
+ * payload is computed, no runnable item is found, nothing is saved), so
+ * `mayHaveWritten` is correctly false for it — and yet the 试跑 control the user
+ * pressed was rendered from a loaded chain WITH a head, so the refusal is the
+ * server saying that head is gone. Another turn, or another client, cooled or
+ * blocked it in between. `direct_mode` is the same sentence about the mode: the
+ * drawer only offers a chain for an agent it believes is in hub mode.
+ *
+ * Leaving those two un-reread is the one stale state the user cannot clear by
+ * looking: the chip still names a source and the button still invites a run that
+ * cannot happen. A write is one reason to re-read; being contradicted is another,
+ * and they are independent.
+ */
+const STATE_PRECONDITION_REFUSALS = new Set(['probe_no_candidate', 'direct_mode']);
+
+export const disprovedDrawnHead = (code: string | null): boolean =>
+ code !== null && STATE_PRECONDITION_REFUSALS.has(code);
+
+/**
+ * What a probe's arrival still gets to do. Two questions that look like one and
+ * are not: whether this answer may be SHOWN, and whether the page behind the
+ * sheet has to be RE-READ.
+ *
+ * They come apart the moment the user edits the chain while a probe is in flight.
+ * The edit bumps the sequence, so the response stops being the answer to anything
+ * on screen — and dropping it there dropped the acknowledgment that it WROTE.
+ * Nothing else covers that: the edit's own PUT refetch is issued while this probe
+ * is still out, so it can read the source back exactly as it was before the
+ * cooldown landed, leaving a healthy row and a ● 当前 the server has already
+ * moved. Staleness is a fact about the QUESTION; the write is a fact about the
+ * server, and no guard over the first may decide the second.
+ *
+ * A THROW is the same split with a different answer to the second half.
+ * `probeWroteState`'s outcome-by-outcome check covers the failures the route
+ * NAMES, and every one of those arrives as a structured `ApiCallError`. A throw
+ * with no server name is not one of the route's outcomes at all — a lost
+ * connection, an unparseable body — so the probe may have run and written with
+ * the response never reaching us. Unknown is not the same as no, and this takes
+ * `probeWroteState`'s own trade: one extra read costs a request, while being
+ * wrong the other way costs a page that silently disagrees with the server.
+ *
+ * And a re-read is owed for a SECOND reason that has nothing to do with writing:
+ * a refusal can arrive that contradicts the state the page is drawing from
+ * (`disprovedDrawnHead`). The two are independent — `probe_no_candidate` writes
+ * nothing and still disproves the head — so they are asked separately and only
+ * their answers are combined.
+ */
+export type ProbeAnswer =
+ | { kind: 'result'; probe: ProbeResult }
+ /** `serverNamed` is the error's OWN account of where its code came from
+ * (`ApiCallError.serverNamed`), which is what makes it one of the checked
+ * outcomes. Not 「is it one of ours?」: the transport mints `bad_response` and
+ * `http_<n>` itself for a response that never said what happened, and those
+ * are the exact answers this exists for — a probe that ran, wrote, and lost
+ * its reply on the way back throws one of ours with nothing named in it.
+ * `code` is that name when there is one, for the refusals whose arrival is
+ * itself news about the chain. */
+ | { kind: 'thrown'; serverNamed: boolean; code: string | null };
+
+export type ProbeArrival = {
+ /** Whether this answer is still the answer to what the row is asking. */
+ report: boolean;
+ /** Whether the source rows and ● 当前 behind this sheet are now stale. */
+ reread: boolean;
+};
+
+export const probeArrival = (answer: ProbeAnswer, stillCurrent: boolean): ProbeArrival => ({
+ report: stillCurrent,
+ reread:
+ answer.kind === 'result'
+ ? probeWroteState(answer.probe)
+ : mayHaveWritten(answer) || disprovedDrawnHead(answer.code),
+});
+
+/**
+ * What the 试跑 row IS right now — which is not the same question as what the
+ * chain is, because the row outlives the chain it reported on.
+ *
+ * Two rules, and neither is visible from `dryRunPlan` alone:
+ *
+ * 1. A REPORT survives losing its head. 试跑 is what takes the head away:
+ * probing the chain's last runnable source and failing cools that source
+ * down (`probeWroteState`), so the re-read that failure demands comes back
+ * with `current: null` and the plan turns `none`. Dropping the row there
+ * erases the sentence the click produced — making the failing run, the one
+ * the user most needs to read, the only one whose answer flashes past. So
+ * the CONTROL goes (there is nothing runnable to reach, and the page states
+ * that one level up with the remedy attached) while the LINE stays.
+ * 2. The control waits for the drawer's save. That PUT is optimistic: the list
+ * — and the chain key the report is filed under — have already moved to the
+ * order the user dropped while the server still answers for the old one. A
+ * probe launched in that window reports on the superseded chain under the
+ * new one's key, and the key cannot clear it because it IS already the new
+ * key. Every other control in this drawer is disabled for that window; this
+ * one is not special.
+ */
+export type DryRunRowView = {
+ /** The backend to probe, or `null` when there is nothing runnable to reach. */
+ backend: AgentBackend | null;
+ /** Whether the control may be pressed now. */
+ enabled: boolean;
+ /** Whether the last answer is still worth drawing. */
+ report: boolean;
+};
+
+export const dryRunRowView = (
+ plan: DryRunPlan,
+ row: { line: string | null; saving: boolean; running: boolean },
+): DryRunRowView => {
+ const backend = plan.kind === 'probe' ? plan.backend : null;
+ return {
+ backend,
+ enabled: backend !== null && !row.saving && !row.running,
+ report: row.line !== null,
+ };
+};
diff --git a/ui/src/components/settings/models/serverCopy.test.ts b/ui/src/components/settings/models/serverCopy.test.ts
index 861c75115..a5628ccbd 100644
--- a/ui/src/components/settings/models/serverCopy.test.ts
+++ b/ui/src/components/settings/models/serverCopy.test.ts
@@ -11,7 +11,7 @@ import { describe, expect, it } from 'vitest';
import en from '../../../i18n/en.json';
import zh from '../../../i18n/zh.json';
-import { serverText } from './serverCopy';
+import { oauthFailureKey, serverText } from './serverCopy';
const t = (lng: 'en' | 'zh'): TFunction => {
const i18n = createInstance();
@@ -60,3 +60,70 @@ describe('serverText', () => {
);
});
});
+
+describe('oauthFailureKey', () => {
+ // The codes raised while MATERIALIZING the terminal flow. Listed here, not
+ // imported: the test's job is to fail when the module's list and the contract's
+ // POST /sources errors drift apart, which a shared constant cannot do.
+ const MATERIALIZE = ['discovery_failed', 'migration_item_conflict'] as const;
+
+ it('keeps the consent remedy for both journeys', () => {
+ // consent_required is answered by a control the user can still reach, so its
+ // copy is the same instruction whichever journey asked.
+ expect(oauthFailureKey('consent_required', 'connect')).toBe('settings.models.oauth.error.consent');
+ expect(oauthFailureKey('consent_required', 'reauth')).toBe('settings.models.oauth.error.consent');
+ });
+
+ it.each(MATERIALIZE)('names the right object for %s', (code) => {
+ // The whole reason the journey is a required argument: a connect has no
+ // Source yet, a reauth has one the server just cleared and marked unavailable.
+ expect(oauthFailureKey(code, 'connect')).toBe('settings.models.oauth.error.finalize');
+ expect(oauthFailureKey(code, 'reauth')).toBe('settings.models.oauth.error.finalizeReauth');
+ });
+
+ it.each(['connect', 'reauth'] as const)(
+ 'refuses to read an engine outage as a finished sign-in in a %s',
+ (journey) => {
+ // `engine_down` is the engine-outage catch-all, not a phase: every
+ // `_oauth_call` maps EngineUnavailableError (and any unexpected exception)
+ // onto it, and `_oauth_status` is one of its callers — so a poll can carry
+ // it while the flow is still pending, with nothing authorized and nothing
+ // materialized. Claiming 「已重新登录,但…」 there is unverifiable by the user.
+ expect(oauthFailureKey('engine_down', journey)).toBe('settings.models.oauth.error.generic');
+ // And the generic line rather than one naming the engine, because the same
+ // code covers NativeOAuthUnavailableError, where 「中枢没有响应」 is false.
+ expect(oauthFailureKey('engine_down', journey)).not.toBe(
+ 'settings.models.oauth.error.finalizeReauth',
+ );
+ },
+ );
+
+ it.each(['connect', 'reauth'] as const)('degrades an unrecognized code to the generic line in a %s', (journey) => {
+ expect(oauthFailureKey('some_future_code', journey)).toBe('settings.models.oauth.error.generic');
+ expect(oauthFailureKey(undefined, journey)).toBe('settings.models.oauth.error.generic');
+ });
+
+ it.each(['zh', 'en'] as const)('resolves every key it can return in %s', (lng) => {
+ const keys = [
+ oauthFailureKey('consent_required', 'connect'),
+ oauthFailureKey('discovery_failed', 'connect'),
+ oauthFailureKey('discovery_failed', 'reauth'),
+ oauthFailureKey(undefined, 'connect'),
+ ];
+ for (const key of keys) {
+ // `serverText`'s fallback would hide a missing key behind the generic line;
+ // these are OURS, so they must translate outright.
+ const text = t(lng)(key, { defaultValue: '' }) as string;
+ expect(text, key).not.toBe('');
+ expect(text).not.toContain('settings.models');
+ }
+ });
+
+ it('does not tell a reauth its source could not be created', () => {
+ // The finding this branch exists for, asserted as the user-visible claim
+ // rather than as a key: 「创建来源失败」 names an object a repair never had.
+ const reauth = t('zh')(oauthFailureKey('discovery_failed', 'reauth')) as string;
+ expect(reauth).not.toContain('创建');
+ expect(t('en')(oauthFailureKey('discovery_failed', 'reauth')) as string).not.toMatch(/creat/i);
+ });
+});
diff --git a/ui/src/components/settings/models/serverCopy.ts b/ui/src/components/settings/models/serverCopy.ts
index f899e0f48..cb09a3c6e 100644
--- a/ui/src/components/settings/models/serverCopy.ts
+++ b/ui/src/components/settings/models/serverCopy.ts
@@ -39,3 +39,52 @@ export const serverText = (
const generic = t(fallbackKey, { defaultValue: '' }) as string;
return generic || null;
};
+
+/**
+ * Which journey a terminal OAuth failure belongs to. Required, not optional: the
+ * SAME server code means two different things to the user depending on it, and a
+ * default would silently pick one.
+ */
+export type OAuthJourney = 'connect' | 'reauth';
+
+/**
+ * The failure codes raised while MATERIALIZING the terminal flow, not while
+ * authorizing it (api.md → POST /sources errors). The vendor said yes; what came
+ * after it didn't.
+ *
+ * Membership is 「this code can ONLY arise after terminal success」, and that is
+ * what disqualified `engine_down`. It is the engine-outage catch-all: every
+ * `_oauth_call` maps `EngineUnavailableError` — and any unexpected exception —
+ * onto it, and `_oauth_status` is one of its callers, so a plain outage during
+ * polling produces it while the flow is still pending. Reading it as
+ * materialization made a reauth announce 「已重新登录,但这个来源还是不可用」 for a
+ * sign-in that had not happened, which is the one claim the user cannot check.
+ *
+ * It falls through to `generic` (「连接失败,请重试」) rather than to a line naming
+ * the engine, because the same code is also raised for
+ * `NativeOAuthUnavailableError`: 「中枢没有响应」 would be false on the native
+ * channel, the same false-on-the-channel-reading-it problem the copy in this
+ * lane keeps hitting. Generic states the outage and asks for a retry, which is
+ * true whichever phase it interrupted.
+ */
+const MATERIALIZE_CODES = ['discovery_failed', 'migration_item_conflict'];
+
+/**
+ * A terminal-response failure code → the copy for it, for THIS journey.
+ *
+ * Keeping 「授权没成」 apart from 「授权成了,后面没成」 is why the second branch
+ * exists at all. The journey argument is why it is right: a create that gets there
+ * has no Source yet, so 「couldn't create the source」 is the whole truth — but a
+ * reauth is repairing a source that already exists, and `_materialize_reauth`
+ * clears it and marks it unavailable before answering `discovery_failed`. Telling
+ * that user their source could not be CREATED names the wrong object and hides the
+ * thing that just happened to the one they have.
+ */
+export const oauthFailureKey = (code: string | undefined, journey: OAuthJourney): string =>
+ code === 'consent_required'
+ ? 'settings.models.oauth.error.consent'
+ : code && MATERIALIZE_CODES.includes(code)
+ ? journey === 'reauth'
+ ? 'settings.models.oauth.error.finalizeReauth'
+ : 'settings.models.oauth.error.finalize'
+ : 'settings.models.oauth.error.generic';
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index b31b62c85..2dbf8fbf3 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -2,10 +2,19 @@
// (`avibe/docs/plans/model-hub-contracts/*`). Field names are exact
// (case included); the UI consumes these types and never edits the schemas.
//
-// Contract version pinned to the frozen v3. If the orchestrator bumps a
-// contract, this file changes in lockstep — never ahead of it.
+// Contract versions are PER OBJECT, not per file. `_model_hub_success` stamps
+// the envelope and nests the payload, so one response carries both numbers: the
+// envelope is still v3 while the two payload schemas below moved to v4. Mirrored
+// under the backend's own constant names (`core/handlers/model_hub/service.py`
+// spells them CONTRACT_VERSION / AGENT_CHAIN_CONTRACT_VERSION /
+// PROBE_RESULT_CONTRACT_VERSION) so a bump is greppable across the boundary.
+// Never bump one of these to cover another: a shared constant would claim v4
+// for every route that did not move. This file changes in lockstep with the
+// schemas — never ahead of them.
export const CONTRACT_VERSION = 3 as const;
+export const AGENT_CHAIN_CONTRACT_VERSION = 4 as const;
+export const PROBE_RESULT_CONTRACT_VERSION = 4 as const;
// ── source.schema.json ──────────────────────────────────────────────────
export type SourceKind = 'subscription' | 'api_key';
@@ -300,15 +309,32 @@ export type ResolutionEvent = {
// ── agent-chain.schema.json ─────────────────────────────────────────────
export type ChainHealth = 'healthy' | 'cooldown' | 'needs_action' | 'error';
+/** v4: the only process-unavailability state in v2. `chain[].reason` is its
+ * VOCABULARY HOME; `ProbeResult.error` carries the i18n spelling of the same
+ * fact (`models.probe.native_cli_unavailable`), a mapping registered as M8 in
+ * mirror-registry.json. */
+export type ChainUnavailableReason = 'native_cli_unavailable';
+
export type AgentChainLink = {
source_id: string;
+ /** v4: the source's serving channel, mirroring `Source.supply_channel`. `hub`
+ * is definitionally process-available; `native_cli` is additionally gated by
+ * whether this process can launch the sanctioned CLI under its own login. */
+ channel: SupplyChannel;
via_mapping: boolean;
/** The id actually sent upstream. Non-null whenever `via_mapping` is true. */
resolved_model_id: string | null;
health: ChainHealth;
- /** false for cooldown / needs_action / error; true only for healthy. */
+ /** Health permits the turn AND this process can serve the channel. Always
+ * false for needs_action / error, and whenever `reason` is non-null; true for
+ * healthy, and for a cooldown whose `retry_at` has already passed. */
runnable: boolean;
- /** Non-null only on `cooldown`. */
+ /** v4: process availability, orthogonal to the source-global `health`.
+ * Non-null exactly when this process cannot launch the native_cli source — at
+ * ANY health — and it forces `runnable: false`. Hub is always null. */
+ reason: ChainUnavailableReason | null;
+ /** Non-null only on `cooldown`. Retained once the stamp has passed, so a
+ * non-null `retry_at` does not imply `runnable: false`. */
retry_at: string | null;
};
@@ -317,26 +343,43 @@ export type AgentChainLink = {
* `chain: []` would be a false Hub-starvation alarm about a backend whose
* native CLI runs the model fine (AC-7). */
export type AgentChain = {
- contract_version: typeof CONTRACT_VERSION;
+ contract_version: typeof AGENT_CHAIN_CONTRACT_VERSION;
backend: AgentBackend;
model_id: string;
chain: AgentChainLink[];
+ /** v4 pins this to the array it summarises: `ok` iff some member is runnable,
+ * the two blocked values iff none is. */
supply_state: 'ok' | 'waiting' | 'interrupted';
};
// ── probe-result.schema.json ────────────────────────────────────────────
+/** v4 widened this beyond `state.detail_key`: the native_cli branch reports
+ * process unavailability, which no source-state key can express. */
+export type ProbeErrorKey = SourceDetailKey | 'models.probe.native_cli_unavailable';
+
/** POST /api/models/agents/<backend>/probe — hub mode only, same reason as the
* chain route: there is no `src_*` identity to report in direct mode. */
export type ProbeResult = {
- contract_version: typeof CONTRACT_VERSION;
+ contract_version: typeof PROBE_RESULT_CONTRACT_VERSION;
backend: AgentBackend;
+ /** v4: which channel's truth this result reports. The two halves are not
+ * comparable — see `reachable` and `latency_ms`. */
+ channel: SupplyChannel;
+ /** Channel-scoped usability right now. hub: the upstream request succeeded.
+ * native_cli: process READINESS only — this process can launch the CLI under
+ * its own login — which is never completion evidence. */
reachable: boolean;
source_id: string;
model_id: string;
+ /** Hub round trip of the minimal upstream request; null there means the attempt
+ * never completed. ALWAYS null for native_cli, in both readiness outcomes,
+ * because nothing upstream is timed — a local number would impersonate
+ * completion evidence. */
latency_ms: number | null;
via_mapping: boolean;
- /** Mirrors the `state.detail_key` vocabulary; null iff reachable. */
- error: SourceDetailKey | null;
+ /** Closed vocabulary, null on every reachable result. hub: the ten
+ * `state.detail_key` values. native_cli: only the unavailability key. */
+ error: ProbeErrorKey | null;
};
/** api.md — returned by the source-creation routes: which backends adopted the
@@ -423,6 +466,18 @@ export type ApiErr = {
contract_version: typeof CONTRACT_VERSION;
error: string;
detail?: string;
+ /** Present on `source_last_supplier`: the (backend, model) pairs the refused
+ * write would have left with no source, and the named Agents that run them. */
+ would_interrupt?: SupplyGap[];
+};
+
+/** api.md supply guard — one (backend, model) pair the write would strand, plus
+ * the named Agents affected. `agents` is what the confirm copy names, because
+ * 「删除后 pm 将没有可用来源」 is actionable where a bare pair is not. */
+export type SupplyGap = {
+ backend: AgentBackend;
+ model_id: string;
+ agents: string[];
};
/** POST /api/models/sources — api_key create validates + discovers models. */
@@ -464,6 +519,36 @@ export type SourcePatch = {
* rejects unknown keys, so `contract_version` is deliberately NOT part of it. */
export type AgentSourcesPut = { policy: 'follow' } | { policy: 'custom'; order: string[] };
+/**
+ * PUT /api/models/sources/<id>/credential — hub-channel api_key sources only.
+ * Also a TOTAL body that rejects unknown keys (`contract_version` included), so
+ * `force` is omitted rather than sent false on the unguarded first attempt.
+ */
+export type CredentialReplace = { key: string; force?: boolean };
+
+/**
+ * POST /api/models/sources/<id>/reauth. The acknowledgement is server-enforced
+ * and unconditional for native sources — pre-login, before anything is
+ * destroyed — so the client always confirms and always sends it. Same
+ * closed-body rule: nothing else may appear.
+ */
+export type ReauthRequest = { acknowledge_irreversible: true };
+
+/**
+ * The shared tail of both repair routes (api.md "recovery symmetry"), and of a
+ * terminal `reauth` OAuth flow.
+ *
+ * `recovered` is the server's own judgement that the prior state was
+ * needs_action/error — the client never re-derives it, and it is also the reason
+ * a repair is exempt from the supply guard: `interrupted_pairs` on a recovering
+ * write is a report of what is still stranded, not a refusal.
+ */
+export type SourceRepaired = {
+ source: Source;
+ recovered: boolean;
+ interrupted_pairs: SupplyGap[];
+};
+
/** POST /api/models/custom-models — appends a manual-provenance model entry to
* a source's supply list (frame 08). */
export type CustomModelCreate = {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 075d8cdf0..7bd3a814c 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -778,11 +778,16 @@
"xai": "xAI"
}
},
+ "field": {
+ "apiKeyPlaceholder": "sk-…",
+ "baseUrlPlaceholder": "https://api.example.com/v1"
+ },
"oauth": {
"title": {
"anthropic": "Connect Claude subscription",
"openai": "Connect ChatGPT subscription",
- "generic": "Connect subscription"
+ "generic": "Connect subscription",
+ "reauth": "Sign in to “{{name}}” again"
},
"starting": "Preparing…",
"connected": "Connected — added to your sources",
@@ -810,6 +815,7 @@
"timeout": "Authorization timed out, please reconnect",
"generic": "Connection failed, please retry",
"finalize": "Authorized, but couldn't create the source — please retry",
+ "finalizeReauth": "Signed in, but this source still isn't working — please retry",
"consent": "A hub-hosted subscription needs experimental consent — restart the connect and enable the hub option."
},
"hubOption": {
@@ -955,6 +961,8 @@
"more": "More actions",
"rename": "Rename",
"rediscover": "Re-discover models",
+ "reauth": "Sign in again",
+ "replaceKey": "Replace API key",
"delete": "Delete source",
"renameTitle": "Rename source",
"renameLabel": "Display name",
@@ -973,7 +981,44 @@
"deleteFailed": "Couldn't delete, please retry",
"renameHint": "Changes the display name only — the credential is untouched",
"rediscoverHint": "Re-fetch the models this source can supply",
- "deleteHint": "You'll be asked to confirm first"
+ "deleteHint": "You'll be asked to confirm first",
+ "reauthHint": "The old sign-in stops working right away",
+ "replaceKeyHint": "Enter a new key — the endpoint and name stay"
+ },
+ "repair": {
+ "reauth": "Sign in",
+ "replaceKey": "Replace key",
+ "retest": "Retry",
+ "reauthTitle": "Sign in to “{{name}}” again?",
+ "reauthBody": {
+ "immediate": "The old sign-in stops working as soon as you start, and every source using it goes unavailable. Finishing restores only this one — the others need their own sign-in.",
+ "onFailure": "If this sign-in doesn’t go through, the source needs attention until you sign in again."
+ },
+ "reauthConfirm": "Start sign-in",
+ "replaceTitle": "Replace the API key for “{{name}}”",
+ "replaceBody": "Enter a new key — everything else stays the same.",
+ "replaceLabel": "New API key",
+ "replaceSubmit": "Replace",
+ "replacing": "Replacing…",
+ "replaceFailed": "Couldn't replace the key, please retry",
+ "forceTitle": "Replace it anyway?",
+ "forceConfirm": "Replace anyway",
+ "gapsTitle": "These agents will have no source left:",
+ "gapsDone": "These agents now have no source left:",
+ "gaps": "Some agents now have no source left",
+ "repaired": "Working again",
+ "refreshed": "Updated",
+ "unresolved": "Still not working",
+ "failed": "Couldn't do that, please retry"
+ },
+ "dryRun": {
+ "action": "Run a test turn",
+ "running": "Testing…",
+ "ok": "{{name}} is reachable · {{ms}} ms",
+ "okNoLatency": "{{name}} is reachable",
+ "failed": "{{name}} didn't go through · {{detail}}",
+ "failedUnknown": "{{name}} didn't go through",
+ "error": "Couldn't run the test, please retry"
},
"migrationBanner": {
"title": "Native configs ready to import",
@@ -1035,8 +1080,20 @@
"opencode_api_key_only": "OpenCode can only be supplied by API-key sources",
"consent_required": "Needs your consent for experimental hub supply first"
},
+ "oauth": {
+ "upstream_failed": "The vendor didn't complete this sign-in, please retry",
+ "engine_unavailable": "The Hub isn't responding, please retry",
+ "submission_failed": "Couldn't submit what you pasted, please retry",
+ "ambiguous_engine_binding": "Couldn't tell which account signed in — do one at a time, then retry",
+ "binding_failed": "That account is already used by another source",
+ "expired": "Authorization timed out, please reconnect"
+ },
"probe": {
- "native_cli_unavailable": "CLI login is not available in this process"
+ "native_cli_unavailable": "Can't use the CLI's sign-in",
+ "no_candidate": {
+ "waiting": "Every source is cooling down",
+ "interrupted": "No source can serve this model right now"
+ }
},
"source": {
"cooldown": {
@@ -1047,7 +1104,7 @@
"server_error": "Upstream server error"
},
"needs_action": {
- "oauth_expired": "Sign-in expired — reauthorize it",
+ "oauth_expired": "Needs a new sign-in",
"balance_exhausted": "Out of balance — top it up",
"credential_revoked": "Credential revoked — enter a new one",
"account_banned": "Account is restricted"
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index f56450537..2d60a3072 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -778,11 +778,16 @@
"xai": "xAI"
}
},
+ "field": {
+ "apiKeyPlaceholder": "sk-…",
+ "baseUrlPlaceholder": "https://api.example.com/v1"
+ },
"oauth": {
"title": {
"anthropic": "连接 Claude 订阅",
"openai": "连接 ChatGPT 订阅",
- "generic": "连接订阅"
+ "generic": "连接订阅",
+ "reauth": "重新登录「{{name}}」"
},
"starting": "正在准备…",
"connected": "连接成功,已加入来源列表",
@@ -810,6 +815,7 @@
"timeout": "授权超时,请重新连接",
"generic": "连接失败,请重试",
"finalize": "已完成授权,但创建来源失败,请重试",
+ "finalizeReauth": "已重新登录,但这个来源还是不可用,请重试",
"consent": "连接中枢托管订阅需先同意实验条款;请重新发起连接并在弹窗中开启「中枢托管」选项。"
},
"hubOption": {
@@ -955,6 +961,8 @@
"more": "更多操作",
"rename": "重命名",
"rediscover": "重新发现模型",
+ "reauth": "重新登录",
+ "replaceKey": "更换 API Key",
"delete": "删除来源",
"renameTitle": "重命名来源",
"renameLabel": "显示名",
@@ -973,7 +981,44 @@
"deleteFailed": "删除失败,请重试",
"renameHint": "只改显示名,不动凭证",
"rediscoverHint": "重新拉取这个来源能供给的模型",
- "deleteHint": "删除前会再确认一次"
+ "deleteHint": "删除前会再确认一次",
+ "reauthHint": "旧登录立即失效",
+ "replaceKeyHint": "填入新 Key,地址与显示名不变"
+ },
+ "repair": {
+ "reauth": "重新登录",
+ "replaceKey": "更换 Key",
+ "retest": "重试",
+ "reauthTitle": "重新登录「{{name}}」?",
+ "reauthBody": {
+ "immediate": "开始后旧的登录立即失效,用它登录的来源都会不可用。完成后只恢复这一个,其它的需要各自重新登录。",
+ "onFailure": "这次登录如果没成功,这个来源会需要处理,直到你重新登录。"
+ },
+ "reauthConfirm": "开始登录",
+ "replaceTitle": "更换「{{name}}」的 API Key",
+ "replaceBody": "填入新的 Key,其他设置不变。",
+ "replaceLabel": "新的 API Key",
+ "replaceSubmit": "更换",
+ "replacing": "更换中…",
+ "replaceFailed": "更换失败,请重试",
+ "forceTitle": "仍要更换?",
+ "forceConfirm": "强制更换",
+ "gapsTitle": "继续后这些 Agent 将没有来源可用:",
+ "gapsDone": "这些 Agent 现在没有来源可用:",
+ "gaps": "有 Agent 现在没有来源可用",
+ "repaired": "已恢复可用",
+ "refreshed": "已更新",
+ "unresolved": "仍然不可用",
+ "failed": "没能处理,请重试"
+ },
+ "dryRun": {
+ "action": "试跑一次",
+ "running": "试跑中…",
+ "ok": "{{name}} 可用 · {{ms}} ms",
+ "okNoLatency": "{{name}} 可用",
+ "failed": "{{name}} 没跑通 · {{detail}}",
+ "failedUnknown": "{{name}} 没跑通",
+ "error": "试跑没能进行,请重试"
},
"migrationBanner": {
"title": "发现可导入中枢的原生配置",
@@ -1035,8 +1080,20 @@
"opencode_api_key_only": "OpenCode 只能由 API Key 来源供给",
"consent_required": "需要先同意实验性中枢供给"
},
+ "oauth": {
+ "upstream_failed": "厂商没有完成这次登录,请重试",
+ "engine_unavailable": "中枢没有响应,请重试",
+ "submission_failed": "粘贴的内容没能提交,请重试",
+ "ambiguous_engine_binding": "分不清登录的是哪个账号,请一次只登一个再重试",
+ "binding_failed": "该账号已被另一来源使用",
+ "expired": "授权超时,请重新连接"
+ },
"probe": {
- "native_cli_unavailable": "当前进程无法使用 CLI 登录"
+ "native_cli_unavailable": "用不上 CLI 的登录",
+ "no_candidate": {
+ "waiting": "所有来源都在冷却",
+ "interrupted": "现在没有来源能提供这个模型"
+ }
},
"source": {
"cooldown": {
@@ -1047,7 +1104,7 @@
"server_error": "上游服务异常"
},
"needs_action": {
- "oauth_expired": "登录已过期,需要重新授权",
+ "oauth_expired": "需要重新登录",
"balance_exhausted": "余额不足,需要充值",
"credential_revoked": "凭据已失效,需要重新填写",
"account_banned": "账号被限制使用"