Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(model-hub): close the source dialog on removal and land its missing copy (#1962)

Max49813f734717
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 6da5693e2..29615b6b1 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -156,6 +156,20 @@ scenarios:
kind: mutation
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_order
+ # The removal the user performs has a second half the transaction above cannot
+ # state: what the surface they performed it from does next. Keyed to one
+ # selected source, the detail dialog had nothing left to render and stayed open
+ # over a placeholder, so the row states where each ending belongs — a removal
+ # of ours closes, and only a disappearance we did not cause is worth a sentence.
+ - id: MH-SRC-DELETE-002
+ name: A committed removal returns the source detail dialog to the list, leaving the placeholder to a disappearance the user did not cause
+ status: covered
+ kind: presentation
+ layer: unit
+ test: ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-SRC-DELETE-002
+ related_tests:
+ - ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::states in the dialog that a source disappeared with no removal of ours
+ - ui/src/i18n/modelHubKeys.test.ts
- id: MH-SUPPLY-GAP-001
name: Inventory loss preserves an explicit API-key route target
status: covered
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 8d0e2d377..5a642cb8c 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -12,7 +12,7 @@ import i18n from '@/i18n';
import { OWNER_INSTANCE_CAPABILITIES } from '@/lib/sessionInfo';
import { MANAGE_COMMIT_ACTIONS } from './manage';
import type { ModelsSurfaceKind } from './modelHubSurfaceState';
-import { modelsApi } from './modelsApi';
+import { ApiCallError, modelsApi } from './modelsApi';
import { SOURCE_MUTATION_REPORT_PROJECTIONS } from './mutationSettlement';
import { SettingsModelsPage } from './SettingsModelsPage';
import { hasNativeSubscriptionCustody, SUBSCRIPTION_VENDORS } from './subscriptionOptions';
@@ -1181,6 +1181,57 @@ describe('SettingsModelsPage surface branches', () => {
},
);
+ it('[MH-SRC-DELETE-002] returns to the list once a removal commits, whichever way the route answered', async () => {
+ // The dialog renders one selected source, so a committed removal leaves it
+ // nothing to show, and returning to the list is the whole outcome the user
+ // asked for. Both commit shapes run here rather than as two cases because
+ // the property is that the route's answer does not change the ending: the
+ // second removal also proves the first close left the list operable.
+ const secondSource: Source = { ...retainedSource, id: 'src_second', display_name: 'Second source' };
+ const sourceRead = vi.spyOn(modelsApi, 'listSources');
+ renderPage([retainedSource, secondSource]);
+ const deleteWrite = vi.spyOn(modelsApi, 'deleteSource')
+ .mockResolvedValueOnce({ removed_hops: [], interrupted: [] })
+ .mockRejectedValueOnce(new ApiCallError('source_not_found'));
+
+ for (const removed of [retainedSource, secondSource]) {
+ const survivors = removed === retainedSource ? [secondSource] : [];
+ await userEvent.click((await screen.findByText(removed.display_name)).closest('button') as HTMLButtonElement);
+ expect(await screen.findByRole('dialog', { name: removed.display_name })).toBeTruthy();
+ sourceRead.mockResolvedValue(survivors);
+
+ await userEvent.click(screen.getByRole('button', {
+ name: new RegExp(`(?:Manage|管理) ${removed.display_name}`, 'i'),
+ }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove source$|^移除供应商$/i }));
+ await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除供应商$/i }));
+
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(deleteWrite).toHaveBeenLastCalledWith(removed.id, undefined);
+ // Not merely closed: the placeholder never became something to read past.
+ expect(screen.queryByText(/no longer available|已经不在了/i)).toBeNull();
+ }
+ });
+
+ it('states in the dialog that a source disappeared with no removal of ours', async () => {
+ // The other half of the same behavior: a refetch that finds the source gone
+ // is not a removal this dialog can close on, so it holds the placeholder —
+ // and the placeholder has to be a sentence, which is the bug that opened
+ // this lane: it rendered the raw key.
+ renderPage([retainedSource]);
+ vi.spyOn(modelsApi, 'refreshSource').mockRejectedValueOnce(new ApiCallError('source_not_found'));
+
+ await userEvent.click((await screen.findByText('Retained source')).closest('button') as HTMLButtonElement);
+ const sourceDialog = await screen.findByRole('dialog', { name: 'Retained source' });
+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);
+
+ await userEvent.click(within(sourceDialog).getByRole('button', { name: /^Refetch$|^重新拉取$/i }));
+
+ const placeholder = await screen.findByRole('dialog', { name: /no longer available|已经不在了/i });
+ expect(placeholder.textContent).toMatch(/no longer available|已经不在了/);
+ expect(placeholder.textContent).not.toContain('settings.models.sourceDetail.gone');
+ });
+
it('cannot restore chains after the authoritative supply leaves hub mode', async () => {
const head = { ...retainedSource, id: 'src_head', display_name: 'Paused source', state: { status: 'cooldown' as const, retry_at: '2099-01-01T00:00:00Z', detail_key: null } };
const relay = { ...retainedSource, id: 'src_relay', display_name: 'Replacement source', state: { status: 'active' as const, retry_at: null, detail_key: null } };
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index 8a602607a..a3cd85bba 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -43,6 +43,7 @@ import { convergeMutation, createIntentAuthority } from './mutationConvergence';
import {
readSurfaceLanding,
sourceMutationLanding,
+ type PresentSourceMutationCommit,
type SourceMutationLanding,
type SourceMutationLandingReads,
type SourceMutationSettlement,
@@ -938,6 +939,21 @@ export const SettingsModelsPage: React.FC = () => {
const selectSource = React.useCallback((selection: SourceDetailSelection | null) => {
sourceIntentAuthority.commit(() => applySourceDetailSelection(selection));
}, [applySourceDetailSelection, sourceIntentAuthority]);
+ /**
+ * A committed delete leaves the detail dialog with no entity to render, so the
+ * page closes it and returns the user to the list. It goes through
+ * `selectSource` rather than a panel-owned flag because selection is page
+ * state, and the same commit supersedes any older continuation still holding
+ * an intent to re-open this row.
+ *
+ * `sourceDetail.gone` stays for the case a close cannot cover: the source
+ * disappeared out of band — removed from another surface, or found missing by
+ * an edit or a refetch — with no delete of ours to close the dialog.
+ */
+ const presentSourceMutation = React.useCallback<PresentSourceMutationCommit>(async (commit) => {
+ if (commit.action === 'delete') selectSource(null);
+ await sourceMutationReport.present(commit);
+ }, [selectSource, sourceMutationReport.present]);
const selectedSource = sources.find((source) => source.id === selectedSourceId) ?? null;
const sourceDetailOpen = selectedSourceId !== null && subscriptionVendor === null;
const orderAgent = agents.find((agent) => agent.backend === orderBackend && agent.mode === 'hub') ?? null;
@@ -1386,7 +1402,7 @@ export const SettingsModelsPage: React.FC = () => {
headingRef={sourceDetailHeadingRef}
trackMutation={trackSourceMutation(selectedSource.id)}
onReauth={setReauthSource}
- onMutationCommitted={sourceMutationReport.present}
+ onMutationCommitted={presentSourceMutation}
/>
: <section className="grid min-h-0 flex-1 place-items-center px-5 py-12 text-center text-[12px] text-muted">{t('settings.models.sourceDetail.gone')}</section>}
</DialogContent>
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 6ac1b1f80..91cbe9624 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1687,6 +1687,7 @@
"advanced": "Advanced settings",
"back": "Back to sources",
"close": "Close provider details",
+ "gone": "This provider is no longer available.",
"modelsHeading": "Models",
"usageSummary_one": "{{count}} model · used by {{backends}}",
"usageSummary_other": "{{count}} models · used by {{backends}}",
diff --git a/ui/src/i18n/modelHubKeys.test.ts b/ui/src/i18n/modelHubKeys.test.ts
new file mode 100644
index 000000000..3e96bd32b
--- /dev/null
+++ b/ui/src/i18n/modelHubKeys.test.ts
@@ -0,0 +1,209 @@
+// The Model Hub draws its copy through `t('settings.models…')` literals, and a
+// key that never reached the bundles renders as the raw key: removing a provider
+// showed `settings.models.sourceDetail.gone` where a sentence belonged.
+//
+// So the guard states the property — every literal key those components ask for
+// has copy in BOTH locales — and EXTRACTS the key list from the components
+// themselves. A key or a whole new component added later is covered without
+// editing this file, which a hand-written list could never promise.
+//
+// Resolution runs through a real i18next instance instead of walking the JSON,
+// because the bundles use two shapes a plain path walk reports as missing and
+// the page depends on: plural families (`usageSummary_one` with no plain key)
+// and flat dotted keys (`"vendor.hint"` sitting inside `field`, found by
+// `ignoreJSONStructure`). The audit that opened this lane walked paths, and
+// called 12 keys missing that the runtime resolves.
+//
+// A key alone does not say which copy it needs, though, which is why the sweep
+// reads the syntax tree rather than the bytes: `count` is what selects a plural
+// family, and each plural CATEGORY of the locale is a separate string. So a call
+// site's arguments are part of what is collected, and every piece of copy the
+// call can reach has to be present — never merely one of them. Requiring only
+// one let a half-translated family pass: a locale that keeps `_one` and loses
+// `_other` renders the raw key the moment a real call passes 2, and a call
+// passing no count renders the raw key against a family that has no plain key.
+import { readdirSync, readFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { createInstance, type i18n as I18n } from 'i18next';
+import * as ts from 'typescript';
+import { describe, expect, it } from 'vitest';
+
+import en from './en.json';
+import zh from './zh.json';
+
+const MODEL_HUB = resolve(dirname(fileURLToPath(import.meta.url)), '../components/settings/models');
+
+/** A `t()` call site: the key it names, and whether it hands i18next a `count`. */
+type Reference = { key: string; counted: boolean };
+
+/** How a reference reads in a failure report: the key, and how it was called. */
+const label = (reference: Reference): string =>
+ (reference.counted ? `${reference.key} (count)` : reference.key);
+
+const passesCount = (options: ts.Expression | undefined): boolean =>
+ options !== undefined
+ && ts.isObjectLiteralExpression(options)
+ && options.properties.some((property) => {
+ const name = property.name;
+ return name !== undefined
+ && (ts.isIdentifier(name) || ts.isStringLiteralLike(name))
+ && name.text === 'count';
+ });
+
+/**
+ * Every key a source file names as a literal first argument to `t()`, with the
+ * argument shape that decides which copy that key needs.
+ *
+ * Read from the syntax tree, so the callee itself is the whole test of what a
+ * translation call is: the page's own `jsonInit('POST')` and a `request.t(…)`
+ * member call are not one, and a key built from a variable or an interpolated
+ * template is invisible here by construction. The ones a frozen contract
+ * declares are covered by the models page's own `contractLocaleKeys.test.ts`.
+ *
+ * `counted` is what the call can be SEEN to pass — a `count` property, written
+ * long or shorthand. An options object that hides one behind a spread reads as
+ * uncounted and is probed without one, which against a plural-only key fails
+ * this guard rather than passing it: the residual risk stays a loud failure
+ * someone looks at, never a raw key shipped past a green CI.
+ */
+export const collectReferences = (source: string, fileName = 'fixture.tsx'): Reference[] => {
+ const file = ts.createSourceFile(
+ fileName,
+ source,
+ ts.ScriptTarget.Latest,
+ true,
+ fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
+ );
+ const found = new Map<string, Reference>();
+ const visit = (node: ts.Node) => {
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 't') {
+ const [key, options] = node.arguments;
+ if (key && ts.isStringLiteralLike(key)) {
+ // Keyed by the shape too, because one key named by a counted and by an
+ // uncounted call site needs both kinds of copy to be there.
+ const reference: Reference = { key: key.text, counted: passesCount(options) };
+ found.set(label(reference), reference);
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(file);
+ return [...found.values()].sort((a, b) => label(a).localeCompare(label(b)));
+};
+
+const sourceFiles = (dir: string): string[] =>
+ readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) return sourceFiles(path);
+ if (!/\.tsx?$/.test(entry.name) || /\.test\.tsx?$/.test(entry.name)) return [];
+ return [path];
+ });
+
+const referencedCallSites = (): Reference[] => {
+ const found = new Map<string, Reference>();
+ for (const file of sourceFiles(MODEL_HUB)) {
+ for (const reference of collectReferences(readFileSync(file, 'utf8'), file)) {
+ found.set(label(reference), reference);
+ }
+ }
+ return [...found.values()].sort((a, b) => label(a).localeCompare(label(b)));
+};
+
+/** One locale, resolved with no fallback: a zh gap must not be filled by en. */
+const localeInstance = (lng: 'en' | 'zh'): I18n => {
+ const instance = createInstance();
+ void instance.init({
+ lng,
+ fallbackLng: false,
+ resources: { [lng]: { translation: lng === 'en' ? en : zh } },
+ });
+ return instance;
+};
+
+/**
+ * One count per plural category the locale can select, taken from
+ * `Intl.PluralRules` — the same source i18next resolves its `_one` / `_other`
+ * suffixes from. So en asks for both halves of a family, and zh, which selects
+ * only `other`, asks for the half it can actually reach; a locale added later
+ * brings its own categories instead of a number this file guessed. A category
+ * no count in range selects would drop out of the requirement silently, so it
+ * throws instead.
+ */
+const representativeCounts = (lng: string): number[] => {
+ const rules = new Intl.PluralRules(lng);
+ const categories = rules.resolvedOptions().pluralCategories;
+ const reached = new Map<string, number>();
+ for (let count = 0; count <= 200 && reached.size < categories.length; count += 1) {
+ const category = rules.select(count);
+ if (!reached.has(category)) reached.set(category, count);
+ }
+ const unreached = categories.filter((category) => !reached.has(category));
+ if (unreached.length > 0) throw new Error(`no probe count selects ${lng} plural ${unreached.join(', ')}`);
+ return [...reached.values()];
+};
+
+/** Every options object the call site can reach, and so must have copy for. */
+const probes = (lng: string, reference: Reference): Record<string, unknown>[] =>
+ (reference.counted ? representativeCounts(lng).map((count) => ({ count })) : [{}]);
+
+/** The symptom this guard exists for, stated exactly: no copy renders as the key. */
+const missingCopy = (instance: I18n, lng: string, reference: Reference): boolean =>
+ probes(lng, reference).some((options) => {
+ const rendered: unknown = instance.t(reference.key, options);
+ return typeof rendered !== 'string' || rendered === '' || rendered === reference.key;
+ });
+
+describe('Model Hub i18n key coverage', () => {
+ const referenced = referencedCallSites();
+
+ it('collects the literal keys and how they are called, and only those, from a source file', () => {
+ // The forward guard on the collector itself: a coverage test whose collector
+ // silently stops matching reports coverage it never had. The call shape is
+ // part of that now — a sweep that stopped seeing `count` would quietly stop
+ // asking for the plural copy, which is the hole this case also closes.
+ const fixture = `
+ const label = t('settings.models.fixture.literal');
+ const quoted = t("settings.models.fixture.double");
+ const wrapped = t(
+ 'settings.models.fixture.wrapped',
+ { count: 2 },
+ );
+ const shorthand = t('settings.models.fixture.shorthand', { count });
+ const alongside = t('settings.models.fixture.alongside', { count: total, name: 'x' });
+ const interpolated = t('settings.models.fixture.interpolated', { name: 'x' });
+ const spread = t('settings.models.fixture.spread', { ...options });
+ const nested = t('settings.models.fixture.outer', { hint: t('settings.models.fixture.inner', { count: 3 }) });
+ void jsonInit('POST');
+ void request.t('settings.models.fixture.member');
+ void t(\`settings.models.fixture.\${dynamic}\`);
+ `;
+ expect(collectReferences(fixture)).toEqual([
+ { key: 'settings.models.fixture.alongside', counted: true },
+ { key: 'settings.models.fixture.double', counted: false },
+ { key: 'settings.models.fixture.inner', counted: true },
+ { key: 'settings.models.fixture.interpolated', counted: false },
+ { key: 'settings.models.fixture.literal', counted: false },
+ { key: 'settings.models.fixture.outer', counted: false },
+ { key: 'settings.models.fixture.shorthand', counted: true },
+ { key: 'settings.models.fixture.spread', counted: false },
+ { key: 'settings.models.fixture.wrapped', counted: true },
+ ]);
+ });
+
+ it('reads its key list out of the live components', () => {
+ // Not a floor on the count, which would only say the scan found something:
+ // the scan must have walked the tree, and produced both the key whose
+ // absence put a raw `settings.models.sourceDetail.gone` on the remove flow
+ // and a counted call site, which needs copy no bare probe asks for.
+ expect(sourceFiles(MODEL_HUB).length).toBeGreaterThan(1);
+ expect(referenced).toContainEqual({ key: 'settings.models.sourceDetail.gone', counted: false });
+ expect(referenced.some((reference) => reference.counted)).toBe(true);
+ });
+
+ it.each(['en', 'zh'] as const)('translates every referenced call site in %s', (lng) => {
+ const instance = localeInstance(lng);
+ expect(referenced.filter((reference) => missingCopy(instance, lng, reference)).map(label)).toEqual([]);
+ });
+});
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 339e0ee9c..d952a8828 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1687,6 +1687,7 @@
"advanced": "高级设置",
"back": "返回模型供应商列表",
"close": "关闭供应商详情",
+ "gone": "这个供应商已经不在了。",
"modelsHeading": "模型",
"usageSummary_one": "{{count}} 个模型 · 被 {{backends}} 使用",
"usageSummary_other": "{{count}} 个模型 · 被 {{backends}} 使用",