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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(onboarding): hold the connection contract across brands, credentials and short windows (#2052)
Maxcf3def4ab917
diff --git a/ui/e2e/onboarding-fidelity/connections.spec.ts b/ui/e2e/onboarding-fidelity/connections.spec.tsindex d27efa0b5..c3f7fadac 100644--- a/ui/e2e/onboarding-fidelity/connections.spec.ts+++ b/ui/e2e/onboarding-fidelity/connections.spec.ts@@ -1,6 +1,6 @@import { writeFile } from 'node:fs/promises';-import { expect, test, type Page } from '@playwright/test';-import { openOnboarding, openSetup, serveProduct, settleEffects } from './support';+import { expect, test, type Locator, type Page, type Route } from '@playwright/test';+import { openOnboarding, openSetup, serveProduct, settleEffects, size } from './support';async function authFixtures(page: Page) {const cancellations: string[] = [];@@ -89,29 +89,119 @@ const anchorBoxes = (page: Page) => page.evaluate(() => {frame: read('.connection-dialog'),heading: read('.connection-heading'),description: read('.connection-description'),- // The method tabs are the dialog's first radio group; a credential group, when a- // method has one, lives inside the scrolling middle and is not an anchor.- tabs: read('.connection-dialog [role="radiogroup"]'),+ // Row three, whichever control an assistant puts there: the method tabs, or — for+ // OpenCode, which has to choose a provider first — the search field and then the+ // chosen-provider capsule. A credential group, when a method has one, lives inside+ // the scrolling middle and is not an anchor.+ controls: read('.connection-dialog .connection-controls, .connection-dialog .backend-connection-form > .connection-radio > [role="radiogroup"]'),close: read('.connection-dialog > button:last-of-type'),footer: read('.connection-actions'),};});-/** Only the middle may scroll: a scroller inside the frame's other rows — or the frame- * itself — would mean it had been asked to hold more than it has room for. */+/** Everything in the frame that genuinely scrolls, named — the frame and the middle+ * included. Which of them owns the scroll IS the question in a room too small for five+ * rows, so nothing here is exempt from being counted: exempting the middle would answer+ * it in advance, and exempting the frame would hide the room it cannot fit in. The two+ * are named rather than spelled out because the middle carries a second class while it+ * holds the provider list and is still the middle. */const scrollers = (page: Page) => page.evaluate(() => [...document.querySelectorAll('.connection-dialog, .connection-dialog *')].filter((node) => node.scrollHeight > node.clientHeight + 1 && ['auto', 'scroll'].includes(getComputedStyle(node).overflowY))- .map((node) => node.className.toString())- .filter((name) => name !== 'connection-body'));+ .map((node) => node.classList.contains('connection-body') ? 'body'+ : node.classList.contains('connection-dialog') ? 'frame' : node.className.toString()));/**- * What the window leaves a frame. The dialog asks for its assistant's own height and the- * shared primitive caps it — `100dvh - 32` on a desktop, and below 768 the mobile sheet's- * `90dvh`. Deriving that here keeps the check about the ASSISTANT deciding the height- * while staying exact at a window too short to grant it.+ * Who is allowed to scroll, by room — one policy, asserted the same way everywhere.+ *+ * In a room that fits, the frame never scrolls and the middle is the only one that may.+ * WHETHER the middle needs to is a property of the method on screen, not of the room, so+ * that is the one thing left open; everything else is named and nothing is exempt.+ *+ * In a room below the floor it is the other way round and nothing is open: the frame owns+ * the scroll and the middle has stopped being a scroller at all. Two scrollers in a+ * 158px window is the defect — the middle clipped to nothing inside a frame that scrolls+ * — so "the frame, and nothing else" is the whole claim.*/-const room = (viewport: { width: number; height: number }) =>- (viewport.width < 768 ? viewport.height * 0.9 : viewport.height - 32);+async function expectScrollOwner(page: Page, tight: boolean, because = '') {+ const owners = await scrollers(page);+ if (!tight) {+ expect(owners.filter((owner) => owner !== 'body'), `${because} the middle, and nothing else`).toEqual([]);+ return;+ }+ expect(owners, `${because} the frame, and nothing else`).toEqual(['frame']);+ // And the middle is holding nothing back. This is the half a scroller count cannot+ // see: a box that overflows WITHOUT scrolling is not a second scroller, it is a clip —+ // and one whose content paints over whatever comes after it. A middle clipped to a+ // sliver inside a frame that scrolls is the defect, not the fallback.+ const hidden = await page.evaluate(() => {+ const middle = document.querySelector('.connection-body')!;+ return middle.scrollHeight - middle.clientHeight;+ });+ expect(hidden, `${because} the middle shows all of itself`).toBeLessThanOrEqual(1);+}++/** The design's margin. The frame is centred, so each edge owes half of it. */+const CLEARANCE = 16;++/**+ * The room the window actually leaves this frame, read from the browser rather than+ * recomputed from the stylesheet.+ *+ * It is the VISUAL viewport, not `100dvh`: on iOS the layout viewport does not shrink+ * when the soft keyboard opens, so a frame measured against `100dvh` can be "inside the+ * window" and still have its footer under the keyboard. The insets are whatever the+ * device reserves for a notch or a home indicator, which are room the frame does not+ * have either.+ */+const usableViewport = (page: Page) => page.evaluate(() => {+ const probe = document.createElement('div');+ probe.style.cssText = 'position:fixed;visibility:hidden;pointer-events:none;top:0;left:0;'+ + 'width:env(safe-area-inset-left,0px);height:env(safe-area-inset-top,0px);'+ + 'border-right:env(safe-area-inset-right,0px) solid transparent;'+ + 'border-bottom:env(safe-area-inset-bottom,0px) solid transparent';+ document.body.append(probe);+ const style = getComputedStyle(probe);+ const inset = {+ left: parseFloat(style.width) || 0, top: parseFloat(style.height) || 0,+ right: parseFloat(style.borderRightWidth) || 0, bottom: parseFloat(style.borderBottomWidth) || 0,+ };+ probe.remove();+ const view = window.visualViewport;+ const x = view?.offsetLeft ?? 0;+ const y = view?.offsetTop ?? 0;+ return {+ left: x + inset.left, top: y + inset.top,+ right: x + (view?.width ?? window.innerWidth) - inset.right,+ bottom: y + (view?.height ?? window.innerHeight) - inset.bottom,+ };+});++/** The anchors once the dialog's own entrance has finished: Radix animates the frame in+ * with a transform, so a box read mid-animation is the animation's, not the layout's. */+const settled = async (page: Page) => { await settleEffects(page); return anchorBoxes(page); };++/**+ * The frame's bound, stated as what a person gets rather than as the expression that+ * produces it. Three things, and together they leave the height no freedom: it never+ * grows past what its assistant asked for; it is never pushed against an edge of the+ * room; and when it does have to give height back, it gives back only what the margins+ * need. A frame that shrank for any other reason fails the third, and one that ignored+ * the window fails the second — so neither the assistant's number nor the window's has+ * to be restated here.+ */+async function expectFitsItsRoom(page: Page, assistant: number) {+ await settleEffects(page);+ const room = await usableViewport(page);+ const frame = (await anchorBoxes(page)).frame!;+ const clearance = {+ left: frame.x - room.left, top: frame.y - room.top,+ right: room.right - (frame.x + frame.width), bottom: room.bottom - (frame.y + frame.height),+ };+ expect(frame.height, 'height its assistant asked for').toBeLessThanOrEqual(assistant + 0.5);+ for (const [edge, value] of Object.entries(clearance)) expect(value, `${edge} clearance`).toBeGreaterThanOrEqual(CLEARANCE - 0.5);+ if (frame.height < assistant - 0.5) expect(clearance.top + clearance.bottom, 'height given back').toBeLessThanOrEqual(2 * CLEARANCE + 0.5);+ return frame;+}for (const viewport of [{ width: 1200, height: 800 }, { width: 390, height: 640 }]) {test(`the connection frame holds while its methods change ${viewport.width}x${viewport.height}`, async ({ page }, info) => {@@ -126,7 +216,7 @@ for (const viewport of [{ width: 1200, height: 800 }, { width: 390, height: 640const baseline = await anchorBoxes(page);// The height is the assistant's, so it cannot be a function of what is on screen.- expect(baseline.frame!.height).toBeCloseTo(Math.min(620, room(viewport)), 0);+ await expectFitsItsRoom(page, 620);for (const anchor of Object.values(baseline)) expect(anchor).not.toBeNull();expect(baseline.frame!.y + baseline.frame!.height).toBeLessThanOrEqual(viewport.height);@@ -136,7 +226,7 @@ for (const viewport of [{ width: 1200, height: 800 }, { width: 390, height: 640await expect(method.getByRole('radio', { name: label, exact: true })).toHaveAttribute('aria-checked', 'true');await settleEffects(page);expect(await anchorBoxes(page)).toEqual(baseline);- expect(await scrollers(page)).toEqual([]);+ await expectScrollOwner(page, false, `after ${label}:`);}// API Key ⇄ Auth Token, the second switch the contract names. It lives inside the@@ -183,7 +273,7 @@ for (const viewport of [{ width: 1200, height: 800 }, { width: 390, height: 640await expect(dialog.getByLabel('Base URL (optional)')).toBeVisible();await settleEffects(page);const codex = await anchorBoxes(page);- expect(codex.frame!.height).toBeCloseTo(Math.min(580, room(viewport)), 0);+ await expectFitsItsRoom(page, 580);for (const label of ['Sign in with ChatGPT', 'OpenAI API Key', 'Sign in with ChatGPT']) {await dialog.getByRole('radiogroup', { name: 'Connection method' }).getByRole('radio', { name: label, exact: true }).click();await settleEffects(page);@@ -194,6 +284,710 @@ for (const viewport of [{ width: 1200, height: 800 }, { width: 390, height: 640});}+/** Each assistant's dialog, the height its own frame is sized for, and the two methods+ * whose switch the contract names. OpenCode has no method row — it chooses a provider+ * first, and that choice is the larger change: it replaces row three AND the middle. */+const ASSISTANTS = [+ { slug: 'claude', label: 'Claude Code', height: 620, methods: ['API credentials', 'Claude account'] },+ { slug: 'codex', label: 'Codex', height: 580, methods: ['OpenAI API Key', 'Sign in with ChatGPT'] },+ { slug: 'opencode', label: 'OpenCode', height: 640, methods: [] },+] as const;++/** Non-ASCII, because a failure message is user-facing copy and the row it lands in is+ * one of the things the frame has to stay the same size around. */+const READ_FAILURE = '读取失败 · fixture read failure';++/**+ * The connection reads, with a switch on them. Registered AFTER `authFixtures`, which is+ * what makes them win — Playwright matches routes newest-first.+ *+ * Nothing is stubbed at the component level: loading is a response still in flight, the+ * error state is the product's own read rejecting a body it was given, and retry is the+ * product asking again. The refusal is a 200 carrying `ok: false` rather than a 5xx on+ * purpose — that is the shape this endpoint really answers with, and it keeps the global+ * error toast out of a measurement of the dialog.+ */+async function switchableReads(page: Page) {+ let waiting: (() => void)[] = [];+ let open = true;+ let failing = false;+ let asked = 0;+ const answer = async (route: Route, json: object) => {+ asked += 1;+ if (!open) await new Promise<void>((resolve) => { waiting.push(resolve); });+ return route.fulfill({ json: failing ? { ok: false, message: READ_FAILURE } : json });+ };+ await page.route('**/api/backend/*/auth', (route) => answer(route, { ok: true, active_auth_mode: 'none', auth_mode: 'oauth', has_api_key: false, base_url: null }));+ await page.route('**/api/backend/opencode/providers', (route) => answer(route, { ok: true, providers: [+ { id: 'openai', name: 'OpenAI', description: 'ChatGPT subscription or API Key', oauth_available: true, configured: false, local: false, models: [] },+ // A prioritised brand under one of its aliases, and one provider that is not+ // prioritised at all — so the picker has both a shortlist and a More to open.+ { id: 'alibaba-cn', name: 'Alibaba (China)', description: '', oauth_available: false, configured: true, local: false, models: [] },+ { id: 'cerebras', name: 'Cerebras', description: '', oauth_available: false, configured: false, local: false, models: [] },+ ] }));+ return {+ hold: () => { open = false; },+ release: () => { open = true; const pending = waiting; waiting = []; for (const resolve of pending) resolve(); },+ fail: (value: boolean) => { failing = value; },+ // How many reads this fixture has actually been asked for. A state that owed nothing+ // to a request would prove nothing about the state it is standing in for, so where a+ // test claims a read failed or recovered it says which request that was.+ asked: () => asked,+ };+}++/** Reachable is hit-testable at its own centre, not merely present: the way out and the+ * action are what a short window is most likely to have pushed under an edge.+ *+ * `scrolling` is the claim a room too small for five rows makes instead: there the frame+ * owns the scroll, so these two are reached rather than already in sight. It is the same+ * claim about the same two controls — a control that scrolling cannot bring into view,+ * or that is covered once it is there, still fails. */+const hitsItsOwnCentre = (target: Locator) => target.evaluate((node) => {+ const rect = node.getBoundingClientRect();+ return node.contains(document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2));+});++async function expectReachable(dialog: Locator, { scrolling = false } = {}) {+ for (const control of [dialog.getByRole('button', { name: 'Close' }), dialog.locator('.connection-actions button').last()]) {+ if (scrolling) await control.scrollIntoViewIfNeeded();+ await expect(control).toBeInViewport();+ expect(await hitsItsOwnCentre(control), 'hit-testable at its centre').toBe(true);+ }+}++/** A field a person can get to AND use. Being in the viewport is not enough on its own:+ * a field under something else passes that and fails the person, so the centre it would+ * be tapped at has to reach the field itself — and then it has to take what they type. */+async function expectEditable(field: Locator, value: string) {+ await field.scrollIntoViewIfNeeded();+ await expect(field).toBeInViewport();+ expect(await hitsItsOwnCentre(field), 'hit-testable at its centre').toBe(true);+ await field.fill('');+ await field.pressSequentially(value, { delay: 5 });+ await expect(field).toHaveValue(value);+ await expect(field).toBeFocused();+}++/**+ * The narrowest phone the matrix names, and a window shorter than a landscape phone —+ * which is also roughly what a soft keyboard leaves one. Both are windows that cannot+ * grant an assistant the height it asked for, so they are where the frame has to decide+ * what to give back, and every state has to survive that decision.+ *+ * The second is past the point where there is anything to decide: 300 tall leaves the+ * middle less than one control, so the frame hands the scroll over instead of clipping a+ * field into a sliver. Loading, failure, retry and every method still have to hold there+ * — that is what `tight` changes about the expectations below, and all it changes: the+ * frame, the heading, the description and row three stay exactly where they were, and the+ * footer is reached by scrolling rather than already in sight.+ */+for (const viewport of [{ width: 320, height: 568, tight: false }, { width: 390, height: 300, tight: true }]) {+ test(`every assistant holds its anchors through loading, failure and retry ${size(viewport)}`, async ({ page }, info) => {+ const denied = await serveProduct(page);+ await authFixtures(page);+ const reads = await switchableReads(page);+ await page.setViewportSize(viewport);+ await openOnboarding(page);+ await openSetup(page, 'en');+ const dialog = page.getByRole('dialog');+ // Where the frame owns the scroll, two things about the comparison change and only+ // two. The reader's own scroll position is theirs, not the layout's — reaching the+ // footer moves every anchor on screen and must not read as the frame moving — so the+ // frame is returned to the top before anything is measured. And the footer follows+ // the content it comes after, so what holds still about it is its size rather than+ // its place. Everything else in the frame is compared exactly, in both rooms.+ const stableBoxes = async () => {+ if (viewport.tight) await dialog.evaluate((node) => { node.scrollTop = 0; });+ const boxes = await settled(page);+ if (viewport.tight && boxes.footer) boxes.footer = { ...boxes.footer, y: 0 };+ return boxes;+ };+ for (const assistant of ASSISTANTS) {+ reads.hold(); reads.fail(true);+ await page.getByLabel(assistant.label, { exact: true }).getByRole('button', { name: 'Add API Key' }).click();++ // Loading, with the read still in flight. All five rows are already there: an+ // anchor that arrived with the data would move everything under it when it did.+ await expect(dialog.getByRole('status')).toBeVisible();+ const anchors = await stableBoxes();+ for (const [row, box] of Object.entries(anchors)) expect(box, `${assistant.slug} ${row} while loading`).not.toBeNull();+ await expectFitsItsRoom(page, assistant.height);+ await expectReachable(dialog, { scrolling: viewport.tight });++ // The failure, then the retry the product offers for it.+ reads.release();+ await expect(dialog.getByRole('alert')).toContainText(READ_FAILURE);+ expect(await stableBoxes(), `${assistant.slug} anchors on failure`).toEqual(anchors);+ await expectFitsItsRoom(page, assistant.height);+ await expectReachable(dialog, { scrolling: viewport.tight });+ await settleEffects(page);+ await dialog.screenshot({ path: info.outputPath(`${assistant.slug}-read-failed-${size(viewport)}.png`) });++ reads.fail(false);+ await dialog.getByRole('button', { name: 'Retry' }).click();+ await expect(dialog.getByRole('alert')).toHaveCount(0);+ expect(await stableBoxes(), `${assistant.slug} anchors after retry`).toEqual(anchors);+ await expectScrollOwner(page, viewport.tight, `${assistant.slug} after retry:`);+ await expectReachable(dialog, { scrolling: viewport.tight });++ // Whatever row three can do on this assistant, twice in each direction.+ for (const label of [...assistant.methods, ...assistant.methods]) {+ await dialog.getByRole('radiogroup', { name: 'Connection method' }).getByRole('radio', { name: label, exact: true }).click();+ await expect(dialog.getByRole('radiogroup', { name: 'Connection method' }).getByRole('radio', { name: label, exact: true })).toHaveAttribute('aria-checked', 'true');+ await settleEffects(page);+ expect(await stableBoxes(), `${assistant.slug} anchors after ${label}`).toEqual(anchors);+ await expectScrollOwner(page, viewport.tight, `${assistant.slug} after ${label}:`);+ }+ if (!assistant.methods.length) {+ // Opening More is the biggest thing the middle can be asked to hold, and+ // choosing a provider replaces both row three and the middle at once.+ await dialog.getByRole('button', { name: 'More providers (1)' }).click();+ await expect(dialog.getByRole('button', { name: /Cerebras/ })).toBeVisible();+ expect(await stableBoxes(), 'OpenCode anchors with More open').toEqual(anchors);+ await expectScrollOwner(page, viewport.tight, 'OpenCode with More open:');+ await dialog.getByRole('button', { name: /Cerebras/ }).click();+ await expect(dialog.getByLabel('Base URL (optional)')).toBeVisible();+ expect(await stableBoxes(), 'OpenCode anchors after choosing a provider').toEqual(anchors);+ await expectReachable(dialog, { scrolling: viewport.tight });+ }+ await settleEffects(page);+ await dialog.screenshot({ path: info.outputPath(`${assistant.slug}-settled-${size(viewport)}.png`) });+ await page.keyboard.press('Escape');+ await expect(dialog).toHaveCount(0);+ }+ expect(denied).toEqual([]);+ });+}++/**+ * The case `100dvh` cannot see. On iOS the layout viewport stays full height while the+ * soft keyboard is up — only the VISUAL viewport shrinks — so a frame sized in `dvh`+ * keeps its footer exactly where the keyboard now is. The keyboard is simulated the only+ * way a headless browser can: the visual viewport really does report a smaller height,+ * and the product's own listener is what has to notice.+ *+ * It needs a touch context, because that is the gate the shared hook uses to decide a+ * soft keyboard can exist at all — and on a desktop it must NOT move, which is the+ * second half of this test.+ */+/**+ * The visual viewport, made drivable — installed before the bundle, so the resting height+ * the product measures at start-up is the real one and only what happens afterwards is+ * simulated.+ *+ * All five parts of it, because the product now reads all five. A keyboard takes height;+ * a pan moves the room over the layout viewport on BOTH axes, without changing its size,+ * and sends `scroll` rather than `resize`; and a pinch-zoom shrinks width and height+ * together while raising `scale`. A height alone says how much a person can see and not+ * which part, so anything centred on the height alone is left behind by exactly the pan.+ */+type Viewport = { keyboard: number; narrow: number; top: number; left: number; scale: number };+const simulateSoftKeyboard = (page: Page) => page.addInitScript(() => {+ const view = window.visualViewport;+ if (!view) return;+ const real = (name: string) => Object.getOwnPropertyDescriptor(Object.getPrototypeOf(view), name)!.get!;+ const height = real('height');+ const width = real('width');+ const state = { keyboard: 0, narrow: 0, top: 0, left: 0, scale: 1 };+ const own = (name: string, get: () => number) => Object.defineProperty(view, name, { configurable: true, get });+ own('height', () => height.call(view) - state.keyboard);+ own('width', () => width.call(view) - state.narrow);+ own('offsetTop', () => state.top);+ own('offsetLeft', () => state.left);+ own('scale', () => state.scale);+ Object.defineProperty(window, '__vv', {+ value: (patch: Partial<typeof state>, event: string) => {+ Object.assign(state, patch);+ view.dispatchEvent(new Event(event));+ },+ });+});+const drive = (page: Page, patch: Partial<Viewport>, event: 'resize' | 'scroll') => page.evaluate(([value, name]) =>+ (window as unknown as { __vv: (patch: object, event: string) => void }).__vv(value as object, name as string), [patch, event] as const);+const softKeyboard = (page: Page, height: number) => drive(page, { keyboard: height }, 'resize');+const panTo = (page: Page, top: number, left = 0) => drive(page, { top, left }, 'scroll');+const viewportVar = (page: Page, name: string) => page.evaluate((property) =>+ document.documentElement.style.getPropertyValue(property), name);+const viewportVars = (page: Page) => page.evaluate(() => Object.fromEntries(+ ['--app-vvw', '--app-vvh', '--app-vvl', '--app-vvt'].map((name) => [name, document.documentElement.style.getPropertyValue(name)])));++for (const touch of [true, false]) {+ test(`the frame ${touch ? 'gives way to the soft keyboard' : 'ignores a viewport no keyboard shrank'}`, async ({ browser }, info) => {+ const context = await browser.newContext({ viewport: { width: 390, height: 844 }, hasTouch: touch });+ const page = await context.newPage();+ await simulateSoftKeyboard(page);+ const denied = await serveProduct(page);+ await authFixtures(page);+ await openOnboarding(page, { realTime: true });+ await openSetup(page, 'en');+ await page.getByLabel('Claude Code', { exact: true }).getByRole('button', { name: 'Add API Key' }).click();+ const dialog = page.getByRole('dialog');+ const key = dialog.getByLabel('API Key', { exact: true });+ await expect(key).toBeVisible();+ const before = await expectFitsItsRoom(page, 620);+ expect(before.height, 'a window this tall grants the assistant its own height').toBeCloseTo(620, 0);++ // A keyboard opens because a field was focused, which is also what tells the shared+ // helper that this shrink is a keyboard and not a resized window.+ const resting = await page.evaluate(() => window.visualViewport!.height);+ await key.focus();+ await softKeyboard(page, 420);+ if (touch) {+ await expect.poll(() => viewportVar(page, '--app-vvh')).toBe(`${resting - 420}px`);+ const anchored = await expectFitsItsRoom(page, 620);+ // The field being typed into lives in the middle, and a keyboard this large+ // leaves the middle too short to show all of it at once. Reachable therefore+ // means it can be brought into view by the one part that is allowed to scroll,+ // without any of the anchors — or the frame itself — moving to make room.+ await key.scrollIntoViewIfNeeded();+ await expect(key).toBeInViewport();+ expect((await settled(page)).frame).toEqual(anchored);+ await expectReachable(dialog);+ await expectScrollOwner(page, false, 'with the keyboard up:');++ // Then the pan. The room keeps its size and moves down the screen, and the frame+ // is `position: fixed` — laid out against the layout viewport, which did not move+ // at all. So it has to be told, and it has to follow by the whole distance: a+ // centre computed from the height alone stays exactly where it was, which is the+ // half of this that a keyboard test measuring only `height` can never fail on.+ await panTo(page, 120);+ await expect.poll(() => viewportVar(page, '--app-vvt')).toBe('120px');+ const panned = await expectFitsItsRoom(page, 620);+ expect(panned.y - anchored.y, 'follows the room it is centred in').toBeCloseTo(120, 0);+ expect(panned.height, 'a pan moves the room, it does not shrink it').toBeCloseTo(anchored.height, 0);+ await expectReachable(dialog);++ // The point of all of it: the field is still being typed into. Non-ASCII because+ // the value is a person's, not the fixture's, and an IME is the common way this+ // field gets one — and read back from the DOM rather than from what was typed.+ await key.fill('');+ await key.pressSequentially('密钥-测试-值', { delay: 10 });+ await expect(key).toHaveValue('密钥-测试-值');+ await expect(key).toBeFocused();+ await expect(dialog.getByRole('button', { name: 'Save and connect' })).toBeEnabled();++ // And back: the pan returns, the keyboard closes, and the frame returns with them+ // — carrying what was typed and the focus that typed it. A recovery that re-read+ // the connection, or re-mounted the form to re-measure it, would lose both.+ await panTo(page, 0);+ await expect.poll(() => viewportVar(page, '--app-vvt')).toBe('0px');+ expect((await settled(page)).frame).toEqual(anchored);+ await softKeyboard(page, 0);+ await expect.poll(() => viewportVar(page, '--app-vvh')).toBe(`${resting}px`);+ expect((await settled(page)).frame).toEqual(before);+ await expect(key).toHaveValue('密钥-测试-值');+ await expect(key).toBeFocused();+ await expectReachable(dialog);+ } else {+ // No soft keyboard exists here, so nothing may move: a shrunken visual viewport on+ // a desktop is a pinch-zoom or a trackpad gesture, not room the frame lost.+ await page.waitForTimeout(100);+ // All four, not just the height: the frame is centred on all four now, so one of+ // them left behind on a desktop would move it just as surely.+ expect(await viewportVars(page)).toEqual({ '--app-vvw': '', '--app-vvh': '', '--app-vvl': '', '--app-vvt': '' });+ expect((await settled(page)).frame!.height).toBeCloseTo(620, 0);+ }+ await settleEffects(page);+ await dialog.screenshot({ path: info.outputPath(`claude-key-${touch ? 'keyboard' : 'desktop'}-390x844.png`) });+ expect(denied).toEqual([]);+ await context.close();+ });+}++/** What `100vw` and `100dvh` are worth on this page, measured rather than assumed — the+ * layout viewport, which is what the frame falls back to when nothing is mirroring the+ * visual one. `innerWidth` is not the same thing when a scrollbar is showing. */+const layoutViewport = (page: Page) => page.evaluate(() => {+ const probe = document.createElement('div');+ probe.style.cssText = 'position:fixed;visibility:hidden;pointer-events:none;top:0;left:0;width:100vw;height:100dvh';+ document.body.append(probe);+ const rect = probe.getBoundingClientRect();+ probe.remove();+ return { width: rect.width, height: rect.height, left: 0, top: 0 };+});++/** The visual viewport as the BROWSER reports it — the independent half of every bound+ * asserted below. Nothing the dialog computed is read to check the dialog. */+const visualViewport = (page: Page) => page.evaluate(() => {+ const view = window.visualViewport!;+ return { width: view.width, height: view.height, left: view.offsetLeft, top: view.offsetTop };+});++/**+ * One rectangle, both axes.+ *+ * Width, height, left and top are the same room described four ways, so they have to be+ * taken from the same moment and inset by the same edges. The defect a half-done version+ * has is specific: a frame bound in height and centred on height alone is correct on a+ * phone held upright and wrong the instant the room is not where the window is — a notch+ * down one side, or iOS panning the visible band sideways to keep a field in sight.+ *+ * A safe area cannot be driven from a test: `env()` is the device's answer and nothing may+ * set it. The dialog names each edge in a variable of its own, which is what lets the same+ * arithmetic a notch goes through be exercised here with four numbers this test chose. The+ * expected box is built from those four, the assistant's own height, the design's margin+ * and the window the browser reports — never from anything the dialog computed, which+ * would let a wrong answer agree with itself.+ */+for (const device of [{ width: 900, height: 700 }, { width: 620, height: 700 }]) {+ test(`the frame is bound and centred in one rectangle ${size(device)}`, async ({ browser }, info) => {+ // Deliberately unequal on every edge, and different between the axes: any pair of+ // them swapped, or either one applied twice, moves the frame somewhere this cannot+ // agree with. A notch and a home indicator are this shape.+ const inset = { t: 30, r: 24, b: 20, l: 40 };+ const MARGIN = 2 * CLEARANCE;+ const context = await browser.newContext({ viewport: device, hasTouch: true });+ const page = await context.newPage();+ await simulateSoftKeyboard(page);+ const denied = await serveProduct(page);+ await authFixtures(page);+ await openOnboarding(page, { realTime: true });+ await openSetup(page, 'en');+ await page.getByLabel('Claude Code', { exact: true }).getByRole('button', { name: 'Add API Key' }).click();+ const dialog = page.getByRole('dialog');+ const key = dialog.getByLabel('API Key', { exact: true });+ await expect(key).toBeVisible();+ await dialog.evaluate((node, edges) => {+ for (const [edge, value] of Object.entries(edges)) node.style.setProperty(`--connection-inset-${edge}`, `${value}px`);+ }, inset);++ const expectBox = async (because: string, view: { width: number; height: number; left: number; top: number }) => {+ await settleEffects(page);+ const room = { width: view.width - inset.l - inset.r, height: view.height - inset.t - inset.b };+ const want = { width: Math.min(568, room.width - MARGIN), height: Math.min(620, room.height - MARGIN) };+ const box = { ...want, x: view.left + inset.l + room.width / 2 - want.width / 2, y: view.top + inset.t + room.height / 2 - want.height / 2 };+ const frame = (await anchorBoxes(page)).frame!;+ for (const edge of ['x', 'y', 'width', 'height'] as const) expect(frame[edge], `${because} ${edge}`).toBeCloseTo(box[edge], 0);+ return frame;+ };++ // At rest. 900 wide leaves more room than the design wants, so the width is the+ // design's; 620 wide leaves less, so it is the room's — and the height is the room's+ // in both, because 700 less two unequal insets and the margin is under what Claude+ // asked for. Both bounds and both origins, in one window each.+ const rest = await expectBox('at rest', await visualViewport(page));+ expect(rest.width, 'bound by whichever is smaller').toBeCloseTo(Math.min(568, device.width - inset.l - inset.r - 2 * CLEARANCE), 0);+ expect(rest.height, 'the room gave less than the assistant asked for').toBeLessThan(620);++ // The pan, on both axes at once and by different amounts. The room keeps its size+ // and changes place; the frame is `position: fixed`, laid out against a layout+ // viewport that did not move at all, so it has to be told — and it has to follow by+ // the whole distance on each axis independently.+ await panTo(page, 60, 45);+ await expect.poll(() => viewportVar(page, '--app-vvt')).toBe('60px');+ expect(await viewportVar(page, '--app-vvl')).toBe('45px');+ const panned = await expectBox('panned', await visualViewport(page));+ expect(panned.x - rest.x, 'follows the room sideways').toBeCloseTo(45, 0);+ expect(panned.y - rest.y, 'follows the room downwards').toBeCloseTo(60, 0);++ // The keyboard, while the pan is still on. Height is the only thing it takes, so the+ // frame gives height back and stays exactly as centred sideways as it was.+ await key.focus();+ await softKeyboard(page, 300);+ await expect.poll(() => viewportVar(page, '--app-vvh')).toBe(`${device.height - 300}px`);+ const typing = await expectBox('with the keyboard up', await visualViewport(page));+ expect(typing.x, 'a keyboard takes height, not width').toBeCloseTo(panned.x, 0);+ await expect(key).toBeFocused();++ // A zoom ON TOP of the keyboard is still a keyboard: the room really is smaller and+ // the frame still needs to follow it. This is the case the shared helper multiplies+ // the delta back up by the scale for, and the frame must not lose the mirror here.+ await drive(page, { scale: 2 }, 'resize');+ await expect.poll(() => viewportVar(page, '--app-vvh')).toBe(`${device.height - 300}px`);+ expect((await settled(page)).frame, 'a zoom that takes no room changes nothing').toEqual(typing);++ // And the half of that claim the step above cannot make: it moves `scale` alone, so+ // the width never changes and the width mirror is never asked for anything. A zoom+ // into a corner is the case that does take width, and with the keyboard still up the+ // mirrors are on — so the frame has to follow this axis too, from a room whose left+ // edge has not moved. Both bounds come from the browser's own visual viewport; the+ // frame is never checked against a number it computed.+ const narrow = Math.round(device.width / 3);+ await drive(page, { scale: 2, narrow }, 'resize');+ await expect.poll(() => viewportVar(page, '--app-vvw')).toBe(`${device.width - narrow}px`);+ const band = await visualViewport(page);+ expect(band.width, 'the browser really is narrower').toBe(device.width - narrow);+ const narrowed = await expectBox('narrowed with the keyboard up', band);+ // A band this narrow leaves less than the design asked for on both devices, so the+ // width is the room's — which pins the left edge to one inset and one clearance,+ // wherever the room itself is. Said independently of the centring `expectBox` checks.+ expect(narrowed.width, 'bound by the room the narrowing left').toBeCloseTo(band.width - inset.l - inset.r - MARGIN, 0);+ expect(narrowed.width, 'and narrower than the band it came from').toBeLessThan(typing.width);+ expect(narrowed.x, 'left edge is the inset plus its clearance').toBeCloseTo(band.left + inset.l + CLEARANCE, 0);+ expect(narrowed.height, 'width is all a narrowing takes').toBeCloseTo(typing.height, 0);++ // Given back the same way, with the keyboard still up: the width mirror is the room's+ // current width and not a low-water mark of it.+ await drive(page, { narrow: 0 }, 'resize');+ await expect.poll(() => viewportVar(page, '--app-vvw')).toBe(`${device.width}px`);+ expect((await settled(page)).frame, 'and the width comes back with the room').toEqual(typing);++ // A zoom with NO keyboard is the opposite claim, and the one that used to lift the+ // composer: the visual viewport shrinks, but no room was lost — so every mirror is+ // dropped and the frame centres in the layout viewport again. All four go together;+ // one left behind would leave the frame centred on a moment that has passed.+ await key.blur();+ await drive(page, { scale: 2, keyboard: device.height / 2, narrow: device.width / 2 }, 'resize');+ await expect.poll(() => viewportVars(page)).toEqual({ '--app-vvw': '', '--app-vvh': '', '--app-vvl': '', '--app-vvt': '' });+ await expectBox('zoomed with no keyboard', await layoutViewport(page));++ // And back. Nothing about the mirror is one-way.+ await drive(page, { scale: 1, keyboard: 0, narrow: 0 }, 'resize');+ await panTo(page, 0, 0);+ await expect.poll(() => viewportVar(page, '--app-vvt')).toBe('0px');+ expect(await viewportVar(page, '--app-vvl')).toBe('0px');+ expect((await settled(page)).frame).toEqual(rest);+ await expectReachable(dialog);++ await settleEffects(page);+ await dialog.screenshot({ path: info.outputPath(`claude-key-rectangle-${size(device)}.png`) });+ expect(denied).toEqual([]);+ await context.close();+ });+}++/**+ * The room below the floor, which no band can size its way out of.+ *+ * A phone held sideways is 390 tall before a keyboard takes any of it, and the shortest+ * band still owes 272 of that to five rows, four gaps, two paddings and one whole control+ * for the middle to show. The middle is what gives way, and here there is not enough left+ * for it to show anything with — so it is the FRAME that has to give. The bands cannot see+ * this coming either: they are `max-height` on the layout viewport, which a soft keyboard+ * never moves.+ *+ * What must survive is the part a person cannot recover from on their own. A clipped+ * footer is a dialog with no way out, and a field clipped to a sliver is a form that+ * cannot be filled in; a frame they can scroll is one they can finish.+ */+test('a room smaller than the frame scrolls rather than clipping what it cannot hold', async ({ browser }, info) => {+ const context = await browser.newContext({ viewport: { width: 844, height: 390 }, hasTouch: true });+ const page = await context.newPage();+ await simulateSoftKeyboard(page);+ const denied = await serveProduct(page);+ await authFixtures(page);+ await openOnboarding(page, { realTime: true });+ await openSetup(page, 'en');+ await page.getByLabel('Claude Code', { exact: true }).getByRole('button', { name: 'Add API Key' }).click();+ const dialog = page.getByRole('dialog');+ const key = dialog.getByLabel('API Key', { exact: true });+ await expect(key).toBeVisible();+ // Sideways with no keyboard is still a room the frame fits, and nothing scrolls but+ // the middle. Everything below is what the keyboard alone does to it.+ await expectFitsItsRoom(page, 620);+ await expectReachable(dialog);+ await expectScrollOwner(page, false, 'sideways with no keyboard:');++ const resting = await page.evaluate(() => window.visualViewport!.height);+ await key.focus();+ await softKeyboard(page, 200);+ await expect.poll(() => viewportVar(page, '--app-vvh')).toBe(`${resting - 200}px`);++ // The frame still holds its room — centred in what is visible, margins on every side,+ // never pushed against an edge. It just cannot hold itself.+ const frame = await expectFitsItsRoom(page, 620);+ const chrome = await dialog.evaluate((node) => node.scrollHeight);+ expect(chrome, 'more frame than there is room').toBeGreaterThan(frame.height);++ // So the frame is the scroller, and the only one: nothing else inside it was asked+ // to hold more than it has room for.+ await expectScrollOwner(page, true, 'with the keyboard up:');++ // And everything a person has to be able to get to is reachable — by scrolling, which+ // is the whole point, rather than by luck of where the clip happened to land. The way+ // out, the action, and the field the dialog exists to collect.+ await expectReachable(dialog, { scrolling: true });+ await expectEditable(key, '密钥-sideways');+ await expect(dialog.getByRole('button', { name: 'Save and connect' })).toBeEnabled();++ // The other method's own field, because a method switch must not undo any of it — and+ // the mode is decided by the room, so switching may not change who owns the scroll.+ await dialog.getByRole('radiogroup', { name: 'Credential type' }).getByRole('radio', { name: 'Auth Token', exact: true }).click();+ await expectScrollOwner(page, true, 'after switching credential type:');+ await expectEditable(dialog.getByLabel('Auth Token', { exact: true }), 'sk-ant-fixture-只读');+ await expectReachable(dialog, { scrolling: true });++ await settleEffects(page);+ await dialog.screenshot({ path: info.outputPath('claude-key-keyboard-844x390.png') });+ expect(denied).toEqual([]);+ await context.close();+});++/**+ * The floor, from both sides of it.+ *+ * "Too small" cannot mean "the middle came out at zero". One pixel above that is a form+ * with a 1px field in it, which is reachable in the way a locked door is openable. The+ * line is the room the anchored chrome needs PLUS one whole control for the middle to+ * show — five rows, four gaps, two paddings and a second control row: 40 + 40 + 40 + 40+ * + 56, four 8px gaps and 12px of padding on each side, which is 272 for the shortest+ * band and the one a window this short is in. The frame is the room less the 32px margin,+ * and the 272 has to fit inside its padding box, which is the frame less its own 2px of+ * border — so 306 of visible window is the exact line. 305 is below it, 307 is above it,+ * and at 306 the middle is one control tall and nothing has changed hands yet.+ *+ * What the floor buys, precisely: the middle it reserves is one 40px control, and the+ * credential field is 42px, so at the line the field is usable rather than shown end to+ * end — its centre is where a tap lands and it takes what is typed. Above the line the+ * middle grows with the room; below it the frame takes the scroll and carries all of the+ * content instead. The requirement is a control a person can reach and use, by sight or+ * by scrolling, not a whole form on screen in a room that has no space for one.+ *+ * Crossed in both directions, because a mode that latches is a mode that is wrong on the+ * way back, and with the credential and a real read failure changed at each stop: the+ * room decides this, so nothing on screen may move the line. 158px is one room below the+ * floor; this is the floor itself.+ */+test('the scroll changes hands at the floor, in both directions, whatever is on screen', async ({ browser }, info) => {+ const context = await browser.newContext({ viewport: { width: 844, height: 390 }, hasTouch: true });+ const page = await context.newPage();+ await simulateSoftKeyboard(page);+ const denied = await serveProduct(page);+ await authFixtures(page);+ const reads = await switchableReads(page);+ await openOnboarding(page, { realTime: true });+ await openSetup(page, 'en');+ await page.getByLabel('Claude Code', { exact: true }).getByRole('button', { name: 'Add API Key' }).click();+ const dialog = page.getByRole('dialog');+ const key = dialog.getByLabel('API Key', { exact: true });+ await expect(key).toBeVisible();+ await key.focus();++ const FLOOR = 306;+ const CONTROL = 40;+ const middle = () => dialog.locator('.connection-body').evaluate((node) => node.getBoundingClientRect().height);++ for (const visible of [305, 306, 307, 306, 305]) {+ const tight = visible < FLOOR;+ await softKeyboard(page, 390 - visible);+ await expect.poll(() => viewportVar(page, '--app-vvh')).toBe(`${visible}px`);+ await settleEffects(page);++ // The frame's own box is the room's either way — the fallback changes who scrolls,+ // never where the frame is or how big it is.+ await expectFitsItsRoom(page, 620);+ await expectScrollOwner(page, tight, `at ${visible}:`);+ await expectReachable(dialog, { scrolling: tight });+ if (tight) {+ // Below the line the middle has stopped being a box with its own leftovers: it is+ // as tall as what is in it, and the frame carries all of it.+ expect(await middle(), `at ${visible} the middle is its content`).toBeGreaterThan(CONTROL);+ } else {+ // At the line, exactly one control. Above it, one control and the pixel that took+ // it there — which is the whole difference the line is drawn on.+ expect(await middle(), `at ${visible} the middle is one control tall`).toBeCloseTo(CONTROL + visible - FLOOR, 0);+ // And what that control is worth, said as what it is rather than more. The field+ // asks for more than the floor reserves, so at the line the middle holds most of+ // one and not all of it. The claim the floor earns is the one `expectEditable`+ // makes below — a control reachable at the point it would be tapped, that takes+ // what is typed into it — and not that a whole field is in sight.+ expect(await key.evaluate((node) => node.getBoundingClientRect().height), `at ${visible} the field asks for more than the floor reserves`).toBeGreaterThan(CONTROL);+ }+ await expectEditable(key, `密钥-${visible}`);++ // Nothing on screen may move the line, and the middle's two biggest changes are the+ // other credential and a failed read with its alert and its Retry.+ await dialog.getByRole('radiogroup', { name: 'Credential type' }).getByRole('radio', { name: 'Auth Token', exact: true }).click();+ await expectScrollOwner(page, tight, `at ${visible} on Auth Token:`);+ await dialog.getByRole('radiogroup', { name: 'Credential type' }).getByRole('radio', { name: 'API Key', exact: true }).click();+ await expectScrollOwner(page, tight, `at ${visible} back on API Key:`);++ // The second of those, reached the way a person reaches it. Nothing re-reads while+ // the dialog is up — switching method only clears the error — so the honest route to+ // a failed read is to leave and come back to a refusal, and the alert and the Retry+ // it offers are then really on screen rather than assumed. Counted as well as seen.+ await page.keyboard.press('Escape');+ await expect(dialog).toHaveCount(0);+ reads.fail(true);+ const failing = reads.asked();+ await page.getByLabel('Claude Code', { exact: true }).getByRole('button', { name: 'Add API Key' }).click();+ await expect(dialog.getByRole('alert')).toContainText(READ_FAILURE);+ expect(reads.asked(), `at ${visible} the failed read was really asked for`).toBeGreaterThan(failing);+ const retry = dialog.getByRole('button', { name: 'Retry' });+ await expect(retry).toBeVisible();+ await expect.poll(() => viewportVar(page, '--app-vvh')).toBe(`${visible}px`);+ await expectFitsItsRoom(page, 620);+ await expectScrollOwner(page, tight, `at ${visible} with the read failed:`);+ await expectReachable(dialog, { scrolling: tight });++ // And back out of it by the control the product offers for it, which is a second+ // real read. Recovery is the half that a latch would pass the first time and fail+ // here: the alert goes, the form is the form again, and the room still decides.+ reads.fail(false);+ const retrying = reads.asked();+ if (tight) await retry.scrollIntoViewIfNeeded();+ await retry.click();+ await expect(dialog.getByRole('alert')).toHaveCount(0);+ expect(reads.asked(), `at ${visible} the retry was really asked for`).toBeGreaterThan(retrying);+ await expect(key).toBeVisible();+ await expectScrollOwner(page, tight, `at ${visible} after the read recovered:`);+ await key.focus();+ }++ await settleEffects(page);+ await dialog.screenshot({ path: info.outputPath('claude-key-floor-844x390.png') });+ expect(denied).toEqual([]);+ await context.close();+});++/**+ * The same form, rendered where there is no dialog.+ *+ * `.connection-dialog` has exactly one consumer — the setup dialog — and what Settings+ * and onboarding actually share is `.backend-connection-form`. The dialog's five-row+ * grid is what hoists that form's three regions into place, and every rule that does so+ * is scoped under `.connection-dialog`; this is the browser saying so, because a jsdom+ * render resolves no stylesheet and therefore cannot tell a hoisted region from an+ * ordinary one. Settings has to keep the plain column it always had.+ */+test('the Settings form keeps its own column and never inherits the dialog grid', async ({ page }, info) => {+ const denied = await serveProduct(page);+ await page.route('**/api/codex/models', (route) => route.fulfill({ json: { ok: true, models: [] } }));+ await page.route('**/api/backend/codex/auth', (route) => route.fulfill({ json: { ok: true, active_auth_mode: 'api_key', auth_mode: 'api_key', has_api_key: true, api_key_masked: 'sk-••••fixture', base_url: 'https://fixture.invalid/v1', file_store_active: true } }));+ await page.setViewportSize({ width: 390, height: 844 });+ await page.goto('/e2e/onboarding-fidelity/fixture.html?surface=disabled-settings&lang=en&theme=dark');+ const form = page.locator('.backend-connection-form');+ await expect(form).toBeVisible();++ const layout = await form.evaluate((node) => {+ const style = getComputedStyle(node);+ return {+ dialogs: document.querySelectorAll('.connection-dialog').length,+ // The dialog's own rows belong to the dialog: Settings has its own page heading.+ dialogRows: document.querySelectorAll('.connection-heading, .connection-description').length,+ display: style.display,+ flow: style.flexDirection,+ overflowX: node.scrollWidth - node.clientWidth,+ regions: [...node.children].map((child) => {+ const own = getComputedStyle(child);+ const box = child.getBoundingClientRect();+ return { name: child.className.toString().split(' ')[0], row: own.gridRowStart, overflowY: own.overflowY, top: Math.round(box.top), height: Math.round(box.height) };+ }),+ };+ });+ expect(layout.dialogs).toBe(0);+ expect(layout.dialogRows).toBe(0);+ // `display: contents` is how the dialog hoists these three into its grid. Here the+ // form is a box of its own, its regions are placed by flow and not by row, and the+ // middle is not a scroller — it has the whole page to grow into.+ expect(layout.display).toBe('flex');+ expect(layout.flow).toBe('column');+ expect(layout.regions.map((region) => region.name)).toEqual(['connection-radio', 'connection-body', 'connection-actions']);+ expect(layout.regions.map((region) => region.row)).toEqual(['auto', 'auto', 'auto']);+ expect(layout.regions.map((region) => region.overflowY)).toEqual(['visible', 'visible', 'visible']);+ for (const region of layout.regions) expect(region.height, region.name).toBeGreaterThan(0);+ expect(layout.regions.map((region) => region.top)).toEqual([...layout.regions.map((region) => region.top)].sort((left, right) => left - right));+ expect(layout.overflowX).toBeLessThanOrEqual(1);++ const save = form.getByRole('button', { name: 'Save', exact: true });+ await save.scrollIntoViewIfNeeded();+ await expect(save).toBeInViewport();+ await settleEffects(page);+ await page.screenshot({ path: info.outputPath('settings-form-column-390x844.png') });+ expect(denied).toEqual([]);+});+for (const lang of ['en', 'zh']) {test(`corrected compact labels and Light action ${lang}`, async ({ page }, info) => {const denied = await serveProduct(page); await authFixtures(page);diff --git a/ui/src/components/onboarding/BackendConnection.test.tsx b/ui/src/components/onboarding/BackendConnection.test.tsxindex 3654e67e8..1f665fe87 100644--- a/ui/src/components/onboarding/BackendConnection.test.tsx+++ b/ui/src/components/onboarding/BackendConnection.test.tsx@@ -9,7 +9,7 @@ import { CodexProviderConfig } from '../settings/providers/CodexProviderConfig';import { BackendConnectionForm } from '../settings/providers/BackendConnectionForm';import { BackendConnectionDialog } from './BackendConnectionDialog';import en from '../../i18n/en.json';-import type { BackendConnectionState, ClaudeAuthState, CodexAuthState } from '../../context/ApiContext';+import type { BackendConnectionState, ClaudeAuthState, CodexAuthState, OpencodeProvider } from '../../context/ApiContext';const mock = vi.hoisted(() => ({ toast: vi.fn(), api: {getConfig: vi.fn(), detectCli: vi.fn(), mutateConfig: vi.fn(), getBackendRuntime: vi.fn(), restartBackend: vi.fn(), claudeModels: vi.fn(), codexModels: vi.fn(),@@ -28,6 +28,24 @@ const connection = (patch: Partial<BackendConnectionState> = {}): BackendConnectconst native = (): ClaudeAuthState => ({ ok: true, auth_mode: 'api_key', active_auth_mode: 'api_key', has_api_key: true, api_key_length: 20, api_key_masked: 'sk-•••old', base_url: 'https://old.example', credential_type: 'api_key', has_oauth_credentials: true, settings_path: '/fixture/claude/settings.json', settings_exists: true, settings_env_has_key: true, settings_env_key_length: 20, settings_env_key_var: 'ANTHROPIC_API_KEY', settings_env_base_url: 'https://old.example', settings_conflict: false });const codexNative = (patch: Partial<CodexAuthState> = {}): CodexAuthState => ({ ok: true, auth_mode: 'api_key', active_auth_mode: 'api_key', has_api_key: true, api_key_length: 20, api_key_masked: 'sk-•••old', base_url: 'https://old.example', has_chatgpt_tokens: true, credentials_store: 'file', file_store_active: true, ...patch });const deferred = <T,>() => { let resolve!: (value: T) => void; const promise = new Promise<T>((done) => { resolve = done; }); return { promise, resolve }; };+/**+ * A radio group, once it will actually answer.+ *+ * The method row is rendered while the connection read behind it is still in+ * flight, and `BackendConnectionForm` disables its radios until that read lands+ * (`disabled={busy || loading}`, and `onChange` refuses for the same reason). A+ * click fired on existence alone is therefore not dropped by the test — it is+ * refused by the product, the switch never happens, and whatever the test waits+ * for next can never arrive. How many ticks the read takes is not this file's+ * business, so every interaction starts where a person's would: at the point the+ * control can be acted on.+ */+const interactiveRadios = async (name: string) => {+ const group = await screen.findByRole('radiogroup', { name });+ await waitFor(() => expect(within(group).getAllByRole('radio')+ .every((radio) => !(radio as HTMLButtonElement).disabled)).toBe(true));+ return group;+};beforeEach(() => {vi.resetAllMocks();mock.api.getClaudeAuth.mockResolvedValue(native());@@ -512,6 +530,512 @@ describe('shared Settings and onboarding connection owner', () => {fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.saveConnect }));await waitFor(() => expect(mock.api.saveClaudeAuth).toHaveBeenCalledWith({ auth_mode: 'api_key', credential_type: 'auth_token', api_key: 'fixture-token', base_url: 'https://old.example' }));});+ // An API key and an auth token are different credentials, not two spellings+ // of one. So the two sides of the credential switch own their own unsent+ // value AND their own answer to "is something already stored here" — a mask+ // saved as an API key says nothing about the token side.+ it('keeps the Claude API Key and Auth Token drafts independent of each other', async () => {+ mock.api.getClaudeAuth.mockResolvedValue(native());+ render(wrap(<BackendConnectionForm backend="claude" compact initialMethod="api_key" />));+ const credential = async (id: 'API Key' | 'Auth Token') => {+ const group = await interactiveRadios(en.onboarding.connection.credentialType);+ fireEvent.click(within(group).getByRole('radio', { name: id }));+ };+ // The stored key is an API key, so that side opens on its mask.+ fireEvent.click(await screen.findByRole('button', { name: 'Replace' }));+ fireEvent.change(screen.getByLabelText('API Key', { exact: true }), { target: { value: 'sk-ant-半成品' } });++ await credential('Auth Token');+ // Nothing stored under this type, so no mask to replace and nothing typed.+ expect(screen.queryByRole('button', { name: 'Replace' })).toBeNull();+ expect((screen.getByLabelText('Auth Token', { exact: true }) as HTMLInputElement).value).toBe('');+ // Saving is not allowed on the strength of the other type's stored key.+ expect((screen.getByRole('button', { name: en.onboarding.connection.saveConnect }) as HTMLButtonElement).disabled).toBe(true);+ fireEvent.change(screen.getByLabelText('Auth Token', { exact: true }), { target: { value: '中转令牌' } });++ await credential('API Key');+ expect((screen.getByLabelText('API Key', { exact: true }) as HTMLInputElement).value).toBe('sk-ant-半成品');+ await credential('Auth Token');+ expect((screen.getByLabelText('Auth Token', { exact: true }) as HTMLInputElement).value).toBe('中转令牌');++ fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.saveConnect }));+ await waitFor(() => expect(mock.api.saveClaudeAuth).toHaveBeenCalledWith({ auth_mode: 'api_key', credential_type: 'auth_token', api_key: '中转令牌', base_url: 'https://old.example' }));+ });+ // Saving is the other half of keeping the two drafts apart. A receipt settles+ // ONE submission, so it may only spend the draft that submission actually sent:+ // the type that was not saved still holds work nobody has stored anywhere, and+ // clearing it is the same loss as typing it into the wrong field.+ const settingsCredential = async (label: string) => {+ const group = await interactiveRadios(en.settings.backends.claudeCredentialTypeLabel);+ fireEvent.click(within(group).getByRole('radio', { name: label }));+ };+ const API_KEY = en.settings.backends.claudeCredentialTypeApiKey;+ const AUTH_TOKEN = en.settings.backends.claudeCredentialTypeAuthToken;+ const draftValue = (label: string) => (screen.getByLabelText(label, { exact: true }) as HTMLInputElement).value;+ const REPLACE = en.settings.backends.replaceApiKey;+ const noDraft = (label: string) => screen.queryByLabelText(label, { exact: true });+ /**+ * A save the next read can see.+ *+ * The plain fixture answers every read with the same pre-save account, which+ * lets a draft test agree with itself: the type just saved still reports the+ * OTHER one as stored, so its field stays an empty textbox and a spent draft+ * looks exactly like an untouched one. A real save moves the stored type, its+ * mask and its URL, and the very next read says so — which is also what puts a+ * mask and a Replace in front of the field somebody comes back to, and what+ * makes a read that DISAGREES with the write a thing a test can stage at all.+ *+ * No credential is modelled here. The mask is a shape that changes when the+ * account changes, derived from the write's ordinal rather than from anything+ * that was sent, so nothing in this fixture can be read back as a secret.+ */+ const statefulClaudeAuth = () => {+ let stored = native();+ let writes = 0;+ let view: ((state: ClaudeAuthState) => ClaudeAuthState) | null = null;+ let restart: { ok: boolean; message?: string } = { ok: true };+ mock.api.getClaudeAuth.mockImplementation(async () => (view ? view({ ...stored }) : { ...stored }));+ mock.api.saveClaudeAuth.mockImplementation(async (payload: { credential_type?: 'api_key' | 'auth_token'; base_url?: string | null }) => {+ const credential_type = payload.credential_type || 'api_key';+ writes += 1;+ stored = { ...stored, credential_type, has_api_key: true, base_url: payload.base_url ?? null,+ api_key_masked: `${credential_type === 'auth_token' ? 'tok' : 'sk'}-•••${writes}` };+ return { ok: true, restart };+ });+ return {+ stored: () => stored,+ /** Answer reads with something other than what is stored. */+ show: (lens: (state: ClaudeAuthState) => ClaudeAuthState) => { view = lens; },+ /** And go back to answering with the account itself. */+ truth: () => { view = null; },+ /** Whether the runtime manages to pick the write up. Storage is unaffected. */+ applies: (next: { ok: boolean; message?: string }) => { restart = next; },+ };+ };+ it('a Settings save spends only the credential it sent, in both directions', async () => {+ const account = statefulClaudeAuth();+ const saved = vi.fn();+ render(wrap(<BackendConnectionForm backend="claude" initialMethod="api_key" onConnected={saved} />));+ // The stored credential is an API key, so that side opens on its mask.+ fireEvent.click(await screen.findByRole('button', { name: REPLACE }));+ fireEvent.change(screen.getByLabelText(API_KEY, { exact: true }), { target: { value: 'sk-ant-半成品' } });+ await settingsCredential(AUTH_TOKEN);+ // Nothing is stored under this type, so there is no mask on this side to replace.+ expect(screen.queryByRole('button', { name: REPLACE })).toBeNull();+ fireEvent.change(screen.getByLabelText(AUTH_TOKEN, { exact: true }), { target: { value: '中转令牌' } });++ fireEvent.click(screen.getByRole('button', { name: en.common.save }));+ await waitFor(() => expect(mock.api.saveClaudeAuth).toHaveBeenCalledWith({ auth_mode: 'api_key', credential_type: 'auth_token', api_key: '中转令牌', base_url: 'https://old.example' }));+ await waitFor(() => expect(saved).toHaveBeenCalledOnce());+ // The account really moved, and the read that confirmed it is the read that+ // says so: this is the stored type now, so where the draft was there is the+ // mask a save leaves behind — not an empty box that could equally mean the+ // write never happened.+ expect(account.stored().credential_type).toBe('auth_token');+ await waitFor(() => expect(noDraft(AUTH_TOKEN)).toBeNull());+ expect(screen.getByRole('button', { name: REPLACE })).toBeTruthy();+ expect(screen.getByText(account.stored().api_key_masked!)).toBeTruthy();+ // And the type nobody saved still holds the work nobody stored anywhere.+ await settingsCredential(API_KEY);+ expect(draftValue(API_KEY)).toBe('sk-ant-半成品');++ // The other direction, with fresh work waiting on the token side — reached the+ // way it is now reached, through the mask that side is showing.+ await settingsCredential(AUTH_TOKEN);+ fireEvent.click(screen.getByRole('button', { name: REPLACE }));+ fireEvent.change(screen.getByLabelText(AUTH_TOKEN, { exact: true }), { target: { value: '中转令牌-改' } });+ await settingsCredential(API_KEY);+ fireEvent.click(screen.getByRole('button', { name: en.common.save }));+ await waitFor(() => expect(mock.api.saveClaudeAuth).toHaveBeenLastCalledWith({ auth_mode: 'api_key', credential_type: 'api_key', api_key: 'sk-ant-半成品', base_url: 'https://old.example' }));+ await waitFor(() => expect(saved).toHaveBeenCalledTimes(2));+ // Spending the API key draft returns that side to the mask this write left...+ expect(account.stored().credential_type).toBe('api_key');+ await waitFor(() => expect(noDraft(API_KEY)).toBeNull());+ expect(screen.getByText(account.stored().api_key_masked!)).toBeTruthy();+ // ...and leaves the token nobody saved untouched, in a field again because the+ // stored type moved back and there is no token mask to stand in front of it.+ await settingsCredential(AUTH_TOKEN);+ expect(draftValue(AUTH_TOKEN)).toBe('中转令牌-改');+ });+ // A confirmation can arrive long after the write: through Refresh, and with the+ // person now looking at the other credential. What it settles is the submission,+ // so the type on screen at that moment decides nothing.+ it('a deferred confirmation spends the credential that was submitted, not the one on screen', async () => {+ const account = statefulClaudeAuth();+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'claude', application: 'draining', ready: false }));+ const saved = vi.fn();+ render(wrap(<BackendConnectionForm backend="claude" initialMethod="api_key" onConnected={saved} />));+ await settingsCredential(AUTH_TOKEN);+ fireEvent.change(await screen.findByLabelText(AUTH_TOKEN, { exact: true }), { target: { value: '中转令牌' } });+ fireEvent.click(screen.getByRole('button', { name: en.common.save }));+ await waitFor(() => expect(mock.api.saveClaudeAuth).toHaveBeenCalledWith({ auth_mode: 'api_key', credential_type: 'auth_token', api_key: '中转令牌', base_url: 'https://old.example' }));+ // The write landed — the account stores a token now, and the field shows the+ // mask it left — but the runtime has not confirmed it took effect, so nothing+ // has been spent and nobody has been told the connection works.+ const refresh = await screen.findByRole('button', { name: en.onboarding.connection.refresh });+ expect(saved).not.toHaveBeenCalled();+ expect(noDraft(AUTH_TOKEN)).toBeNull();+ expect(screen.getByText(account.stored().api_key_masked!)).toBeTruthy();++ // Meanwhile the other side is filled in, and left on screen. It is an open+ // field now rather than a mask: the account this form has read moved to the+ // token, so there is no API key stored under the type on screen to replace.+ await settingsCredential(API_KEY);+ expect(screen.queryByRole('button', { name: REPLACE })).toBeNull();+ fireEvent.change(screen.getByLabelText(API_KEY, { exact: true }), { target: { value: 'sk-ant-半成品' } });++ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'claude' }));+ fireEvent.click(refresh);+ await waitFor(() => expect(saved).toHaveBeenCalledOnce());+ // The API key on screen was never submitted, so the receipt has no claim on it.+ expect(draftValue(API_KEY)).toBe('sk-ant-半成品');+ // The token that was submitted is spent, and the account says why: the mask+ // this write left is what stands there now.+ await settingsCredential(AUTH_TOKEN);+ expect(noDraft(AUTH_TOKEN)).toBeNull();+ expect(screen.getByText(account.stored().api_key_masked!)).toBeTruthy();+ expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce();+ });+ // The narrower version of the same rule: the submitted type is right, but the+ // value is not the one that was sent any more. A receipt settles the write it+ // belongs to, and a replacement typed since is a newer intention than that write.+ it('a newer edit outlives the receipt for the write it replaced, and keeps the field it is in', async () => {+ const account = statefulClaudeAuth();+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'claude', application: 'draining', ready: false }));+ const saved = vi.fn();+ const props = (revision: number) => ({ backend: 'claude' as const, initialMethod: 'api_key' as const, onConnected: saved, connectionRevision: revision });+ const view = render(wrap(<BackendConnectionForm {...props(0)} />));+ await settingsCredential(AUTH_TOKEN);+ fireEvent.change(await screen.findByLabelText(AUTH_TOKEN, { exact: true }), { target: { value: '中转令牌' } });+ fireEvent.click(screen.getByRole('button', { name: en.common.save }));+ await waitFor(() => expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce());+ const refresh = await screen.findByRole('button', { name: en.onboarding.connection.refresh });++ // Typing again goes through Replace, because the write did land — the account+ // now stores a token and shows its mask — it simply has not been confirmed to+ // have taken effect. So this is a second intention, later than the write.+ fireEvent.click(screen.getByRole('button', { name: REPLACE }));+ fireEvent.change(screen.getByLabelText(AUTH_TOKEN, { exact: true }), { target: { value: '中转令牌-改' } });+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'claude' }));+ fireEvent.click(refresh);+ await waitFor(() => expect(saved).toHaveBeenCalledOnce());+ expect(draftValue(AUTH_TOKEN)).toBe('中转令牌-改');+ expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce();++ // Surviving the receipt is only half of surviving. Work the receipt kept must+ // keep its claim on the field it is in, or the very next observation — the+ // revision this write's own restart will raise — seeds the server's answer+ // straight over it: the type it reports takes the radio, and the address it+ // reports takes the box. The read is deferred and resolved here so the moment+ // it lands is a moment this test chooses, rather than one it infers from a+ // call count that was already past any threshold three reads ago. That the+ // mechanism can reseed at all is the matched Cancel test below; here it must+ // not, and the only difference between the two is whether anything was left.+ const late = deferred<ClaudeAuthState>();+ const before = mock.api.getClaudeAuth.mock.calls.length;+ mock.api.getClaudeAuth.mockImplementationOnce(() => late.promise);+ view.rerender(wrap(<BackendConnectionForm {...props(1)} />));+ await waitFor(() => expect(mock.api.getClaudeAuth.mock.calls.length).toBeGreaterThan(before));+ await act(async () => { late.resolve({ ...account.stored(), credential_type: 'api_key', base_url: 'https://server-moved.example' }); await late.promise; });++ const group = await interactiveRadios(en.settings.backends.claudeCredentialTypeLabel);+ expect(within(group).getByRole('radio', { name: AUTH_TOKEN }).getAttribute('aria-checked')).toBe('true');+ expect(draftValue(AUTH_TOKEN)).toBe('中转令牌-改');+ expect((screen.getByLabelText(en.onboarding.connection.baseUrl, { exact: true }) as HTMLInputElement).value).toBe('https://old.example');+ expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce();+ });+ // The narrowest version again, and the one that says what a draft actually is.+ // A field somebody has deliberately reopened is not the field that was sent,+ // even when they then retype the very same characters into it: the value agrees+ // and the state does not, and the state is the half that says whether there is+ // an editor on screen to close.+ it('an editor reopened on the same value is still later work than the write that carried it', async () => {+ statefulClaudeAuth();+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'claude', application: 'draining', ready: false }));+ const saved = vi.fn();+ render(wrap(<BackendConnectionForm backend="claude" initialMethod="api_key" onConnected={saved} />));+ await settingsCredential(AUTH_TOKEN);+ fireEvent.change(await screen.findByLabelText(AUTH_TOKEN, { exact: true }), { target: { value: '中转令牌' } });+ fireEvent.click(screen.getByRole('button', { name: en.common.save }));+ await waitFor(() => expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce());+ const refresh = await screen.findByRole('button', { name: en.onboarding.connection.refresh });++ // The write landed, so the field is behind its mask again. Reopening it and+ // typing the same thing is a second intention that happens to look identical.+ fireEvent.click(screen.getByRole('button', { name: REPLACE }));+ fireEvent.change(screen.getByLabelText(AUTH_TOKEN, { exact: true }), { target: { value: '中转令牌' } });+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'claude' }));+ fireEvent.click(refresh);+ await waitFor(() => expect(saved).toHaveBeenCalledOnce());+ expect(draftValue(AUTH_TOKEN)).toBe('中转令牌');+ expect(screen.queryByRole('button', { name: REPLACE })).toBeNull();+ expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce();+ });+ // The other side of that pair. Cancel puts the field back exactly as an+ // untouched one, so there is nothing left to protect — and a form that went on+ // protecting it would quietly stop following the server for the rest of its+ // life. Same staged read as above, opposite outcome, and the only difference is+ // whether any work survived.+ it('cancelling a replacement hands the field back, so the form follows the server again', async () => {+ const account = statefulClaudeAuth();+ const props = (revision: number) => ({ backend: 'claude' as const, initialMethod: 'api_key' as const, connectionRevision: revision });+ const view = render(wrap(<BackendConnectionForm {...props(0)} />));+ const url = () => screen.getByLabelText(en.onboarding.connection.baseUrl, { exact: true }) as HTMLInputElement;+ await waitFor(() => expect(url().value).toBe('https://old.example'));+ fireEvent.click(await screen.findByRole('button', { name: REPLACE }));+ fireEvent.click(screen.getByRole('button', { name: en.common.cancel }));+ expect(noDraft(API_KEY)).toBeNull();+ expect(screen.getByText('sk-•••old')).toBeTruthy();++ const late = deferred<ClaudeAuthState>();+ const before = mock.api.getClaudeAuth.mock.calls.length;+ mock.api.getClaudeAuth.mockImplementationOnce(() => late.promise);+ view.rerender(wrap(<BackendConnectionForm {...props(1)} />));+ await waitFor(() => expect(mock.api.getClaudeAuth.mock.calls.length).toBeGreaterThan(before));+ await act(async () => { late.resolve({ ...account.stored(), base_url: 'https://server-moved.example' }); await late.promise; });+ await waitFor(() => expect(url().value).toBe('https://server-moved.example'));+ expect(mock.api.saveClaudeAuth).not.toHaveBeenCalled();+ });+ // A save does not have to carry a credential at all: leaving the stored key+ // alone and changing only the address sends no key, and its receipt therefore+ // has no credential work to spend. An empty field nobody has opened and a field+ // just opened by Replace read the same value, so a receipt that recognised its+ // own submission by value alone could not tell "what I sent" from "what somebody+ // started after I was sent" — and cancelled the replacement to prove it.+ it('a save that carries no credential has none to spend, and cannot cancel a replacement begun after it', async () => {+ statefulClaudeAuth();+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'claude', application: 'draining', ready: false }));+ const saved = vi.fn();+ render(wrap(<BackendConnectionForm backend="claude" initialMethod="api_key" onConnected={saved} />));+ const url = () => screen.getByLabelText(en.onboarding.connection.baseUrl, { exact: true }) as HTMLInputElement;+ await waitFor(() => expect(url().value).toBe('https://old.example'));+ // The stored key is left where it is — the field is showing its mask, not an+ // editor — and only the address is changed.+ expect(screen.getByText('sk-•••old')).toBeTruthy();+ fireEvent.change(url(), { target: { value: 'https://relay.example' } });+ fireEvent.click(screen.getByRole('button', { name: en.common.save }));+ await waitFor(() => expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce());+ expect(mock.api.saveClaudeAuth.mock.calls[0]![0].api_key).toBeUndefined();++ // The runtime has not picked it up yet, so the receipt is still outstanding —+ // and that is exactly when somebody starts replacing the key. An editor opened+ // and not yet typed into is the literal state this is about: an empty field+ // with somebody's hand on it, which reads the same as an empty field nobody+ // has touched and is not the same thing at all.+ const refresh = await screen.findByRole('button', { name: en.onboarding.connection.refresh });+ fireEvent.click(screen.getByRole('button', { name: REPLACE }));+ expect(draftValue(API_KEY)).toBe('');+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'claude' }));+ fireEvent.click(refresh);+ await waitFor(() => expect(saved).toHaveBeenCalledOnce());++ // The receipt spent the address it carried. The editor it never carried is+ // still open, and still nobody's to close.+ expect(draftValue(API_KEY)).toBe('');+ expect(screen.queryByRole('button', { name: REPLACE })).toBeNull();+ expect(url().value).toBe('https://relay.example');+ // And it is still a live field: what goes into it stays there.+ fireEvent.change(screen.getByLabelText(API_KEY, { exact: true }), { target: { value: 'sk-ant-新' } });+ expect(draftValue(API_KEY)).toBe('sk-ant-新');+ expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce();+ });+ // What a Claude receipt has to observe is not "a key is in use" — both credential+ // types answer that identically, so a token write that never landed reads exactly+ // like one that did. Only the stored type can tell them apart.+ it('a readback still reporting the other credential type confirms nothing, and a later matching one settles it once', async () => {+ const account = statefulClaudeAuth();+ // Everything except the type agrees with the write: the runtime is applied and+ // reports api_key in use, which is what a landed token looks like too. So the+ // only thing left that can refuse this receipt is the type itself.+ account.show((state) => ({ ...state, credential_type: 'api_key' }));+ const saved = vi.fn();+ const view = render(wrap(<BackendConnectionForm backend="claude" initialMethod="api_key" onConnected={saved} connectionRevision={0} />));+ // Half-finished work on the side this write will not carry.+ fireEvent.click(await screen.findByRole('button', { name: REPLACE }));+ fireEvent.change(screen.getByLabelText(API_KEY, { exact: true }), { target: { value: 'sk-ant-半成品' } });+ await settingsCredential(AUTH_TOKEN);+ fireEvent.change(screen.getByLabelText(AUTH_TOKEN, { exact: true }), { target: { value: '中转令牌' } });+ fireEvent.click(screen.getByRole('button', { name: en.common.save }));+ await waitFor(() => expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce());++ // Refused. Nobody is told the connection works, the submitted work is still on+ // screen to retry with, and the observational way back is offered.+ await screen.findByText(en.onboarding.connection.unconfirmed);+ expect(saved).not.toHaveBeenCalled();+ expect(draftValue(AUTH_TOKEN)).toBe('中转令牌');+ const refresh = await screen.findByRole('button', { name: en.onboarding.connection.refresh });+ await settingsCredential(API_KEY);+ expect(draftValue(API_KEY)).toBe('sk-ant-半成品');+ await settingsCredential(AUTH_TOKEN);++ // The readback catches up with the account. The submission that has been+ // pending all along settles — on an observation, not on a second write.+ account.truth();+ fireEvent.click(refresh);+ await waitFor(() => expect(saved).toHaveBeenCalledOnce());+ expect(noDraft(AUTH_TOKEN)).toBeNull();+ expect(screen.getByText(account.stored().api_key_masked!)).toBeTruthy();+ expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce();+ await settingsCredential(API_KEY);+ expect(draftValue(API_KEY)).toBe('sk-ant-半成品');++ // Once, and once only: the runtime settling again is an observation with+ // nothing left to settle. Waited out on a read whose result reaches the screen,+ // so this is the state after that read rather than before it.+ account.show((state) => ({ ...state, api_key_masked: 'sk-•••again' }));+ view.rerender(wrap(<BackendConnectionForm backend="claude" initialMethod="api_key" onConnected={saved} connectionRevision={1} />));+ await settingsCredential(AUTH_TOKEN);+ await screen.findByText('sk-•••again');+ expect(saved).toHaveBeenCalledOnce();+ });+ // And the same answer when there is nothing to compare at all. The producer emits+ // this field for every stored credential, so a read without one has not observed+ // the account — which is a reason to keep asking, not a reason to fall back on the+ // half of the question both types answer the same way.+ it('a readback carrying no credential type at all confirms nothing either', async () => {+ const account = statefulClaudeAuth();+ account.show(({ credential_type: _dropped, ...rest }) => rest as ClaudeAuthState);+ const saved = vi.fn();+ render(wrap(<BackendConnectionForm backend="claude" initialMethod="api_key" onConnected={saved} />));+ await settingsCredential(AUTH_TOKEN);+ fireEvent.change(await screen.findByLabelText(AUTH_TOKEN, { exact: true }), { target: { value: '中转令牌' } });+ fireEvent.click(screen.getByRole('button', { name: en.common.save }));+ await waitFor(() => expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce());+ await screen.findByText(en.onboarding.connection.unconfirmed);+ expect(saved).not.toHaveBeenCalled();+ expect(draftValue(AUTH_TOKEN)).toBe('中转令牌');++ // Still the same submission, and still settled by observation alone.+ account.truth();+ fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.refresh }));+ await waitFor(() => expect(saved).toHaveBeenCalledOnce());+ expect(noDraft(AUTH_TOKEN)).toBeNull();+ expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce();+ });+ // Storage and application are separate observations, and a form that is going+ // away is neither.+ it('a write the runtime cannot pick up keeps its submission, and leaving with one pending settles nothing', async () => {+ const account = statefulClaudeAuth();+ account.applies({ ok: false, message: 'restart refused' });+ const saved = vi.fn();+ const view = render(wrap(<BackendConnectionForm backend="claude" initialMethod="api_key" onConnected={saved} />));+ await settingsCredential(AUTH_TOKEN);+ fireEvent.change(await screen.findByLabelText(AUTH_TOKEN, { exact: true }), { target: { value: '中转令牌' } });+ fireEvent.click(screen.getByRole('button', { name: en.common.save }));+ await screen.findByText(/restart refused/);+ expect(saved).not.toHaveBeenCalled();+ // The credential did land, so the field is showing its mask — but the receipt+ // is unspent, which is why the retry below costs no second write.+ expect(noDraft(AUTH_TOKEN)).toBeNull();+ account.applies({ ok: true });+ fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.refresh }));+ await waitFor(() => expect(saved).toHaveBeenCalledOnce());+ expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce();++ // And a second form taken off screen with a submission of its OWN still+ // outstanding, which is the state worth proving: the read that would have+ // settled it is still in flight when the form goes, so the answer arrives for+ // nobody. No consumer is called and nothing throws into the void.+ view.unmount();+ account.applies({ ok: false, message: 'restart refused again' });+ const second = vi.fn();+ const leaving = render(wrap(<BackendConnectionForm backend="claude" initialMethod="api_key" onConnected={second} />));+ // A token is what is stored now, so the API Key side is an empty field again.+ await settingsCredential(API_KEY);+ fireEvent.change(await screen.findByLabelText(API_KEY, { exact: true }), { target: { value: 'sk-ant-未定' } });+ fireEvent.click(screen.getByRole('button', { name: en.common.save }));+ await screen.findByText(/restart refused again/);+ expect(second).not.toHaveBeenCalled();++ const late = deferred<ClaudeAuthState>();+ const before = mock.api.getClaudeAuth.mock.calls.length;+ mock.api.getClaudeAuth.mockImplementation(() => late.promise);+ account.applies({ ok: true });+ fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.refresh }));+ await waitFor(() => expect(mock.api.getClaudeAuth.mock.calls.length).toBeGreaterThan(before));+ leaving.unmount();+ await act(async () => { late.resolve(account.stored()); await late.promise; });+ expect(second).not.toHaveBeenCalled();+ expect(mock.api.saveClaudeAuth).toHaveBeenCalledTimes(2);+ });+ // Signing in settles the account. It sends no credential at all, so there is+ // nothing for its receipt to spend — including the key someone was part-way+ // through typing when they decided to try the subscription instead.+ it('an OAuth confirmation spends neither credential draft, nor the address beside them', async () => {+ const account = statefulClaudeAuth();+ account.show((state) => ({ ...state, active_auth_mode: 'api_key' }));+ const saved = vi.fn();+ render(wrap(<BackendConnectionForm backend="claude" compact initialMethod="api_key" onConnected={saved} />));+ fireEvent.click(await screen.findByRole('button', { name: REPLACE }));+ fireEvent.change(screen.getByLabelText('API Key', { exact: true }), { target: { value: 'sk-ant-半成品' } });+ const credentials = await interactiveRadios(en.onboarding.connection.credentialType);+ fireEvent.click(within(credentials).getByRole('radio', { name: 'Auth Token' }));+ fireEvent.change(screen.getByLabelText('Auth Token', { exact: true }), { target: { value: '中转令牌' } });+ const url = () => screen.getByLabelText(en.onboarding.connection.baseUrl, { exact: true }) as HTMLInputElement;+ fireEvent.change(url(), { target: { value: 'https://newer.example' } });++ const method = await interactiveRadios(en.onboarding.connection.method);+ fireEvent.click(within(method).getByRole('radio', { name: en.onboarding.connection.claudeLogin }));+ mock.api.startOAuthWeb.mockResolvedValue({ ok: true, flow_id: 'draft-safe', state: 'success' });+ account.show((state) => ({ ...state, active_auth_mode: 'oauth' }));+ fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.claudeSignIn }));+ await waitFor(() => expect(saved).toHaveBeenCalledOnce());++ fireEvent.click(within(await interactiveRadios(en.onboarding.connection.method)).getByRole('radio', { name: en.onboarding.connection.claudeCredentials }));+ expect(draftValue('Auth Token')).toBe('中转令牌');+ fireEvent.click(within(await interactiveRadios(en.onboarding.connection.credentialType)).getByRole('radio', { name: 'API Key' }));+ expect(draftValue('API Key')).toBe('sk-ant-半成品');+ // Signing in carried no address either, so the one being typed is still there+ // and the server's is still only the server's.+ expect(url().value).toBe('https://newer.example');+ expect(account.stored().base_url).toBe('https://old.example');+ expect(mock.api.saveClaudeAuth).not.toHaveBeenCalled();+ });+ // The same rule, reaching past the credential drafts to the other thing on this+ // form a person can type into. A receipt releases the work it carried; a URL+ // typed after the write went out was never in it, and the next observation —+ // which a settling runtime causes by itself — must not seed over it.+ it('a newer Base URL outlives the receipt for the write it was typed after', async () => {+ const account = statefulClaudeAuth();+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'claude', application: 'draining', ready: false }));+ const saved = vi.fn();+ const props = (revision: number) => ({ backend: 'claude' as const, initialMethod: 'api_key' as const, onConnected: saved, connectionRevision: revision });+ const view = render(wrap(<BackendConnectionForm {...props(0)} />));+ await settingsCredential(AUTH_TOKEN);+ fireEvent.change(await screen.findByLabelText(AUTH_TOKEN, { exact: true }), { target: { value: '中转令牌' } });+ fireEvent.click(screen.getByRole('button', { name: en.common.save }));+ await waitFor(() => expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce());+ const refresh = await screen.findByRole('button', { name: en.onboarding.connection.refresh });++ // Typed while the write is still unconfirmed, so no save has ever carried it.+ const url = () => screen.getByLabelText(en.onboarding.connection.baseUrl, { exact: true }) as HTMLInputElement;+ fireEvent.change(url(), { target: { value: 'https://newer.example' } });+ expect(url().value).toBe('https://newer.example');++ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'claude' }));+ fireEvent.click(refresh);+ await waitFor(() => expect(saved).toHaveBeenCalledOnce());+ expect(url().value).toBe('https://newer.example');++ // And the runtime settles, which is what a save is for: the consumer bumps the+ // revision and the form observes again. The credential this receipt paid for is+ // gone, the URL it never carried is not.+ //+ // Counting reads would not prove that: three have already gone out by here, so+ // any threshold is satisfied before the one this rerender causes has come back.+ // So this read is made recognisable instead — a mask nothing else in this test+ // produces, and a server address that has moved on — and the wait is for its+ // result to be ON SCREEN. That is the moment a reseed would have happened, and+ // the only moment at which "the URL survived" means anything.+ account.show((state) => ({ ...state, api_key_masked: 'tok-•••moved', base_url: 'https://server-moved.example' }));+ view.rerender(wrap(<BackendConnectionForm {...props(1)} />));+ await screen.findByText('tok-•••moved');+ expect(url().value).toBe('https://newer.example');+ expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce();+ // Nobody saved the newer address, so the account still holds the one the write+ // carried. The field is a pending intention, not a claim about the server.+ expect(account.stored().base_url).toBe('https://old.example');+ });it('Codex saves through its native owner and refuses uncertain keychain readback', async () => {mock.api.getCodexAuth.mockResolvedValue(codexNative({ auth_mode_uncertain: true }));mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'codex', ok: true, application: 'applied', ready: false, entry_eligible: false, auth: 'unknown' }));@@ -559,12 +1083,12 @@ describe('connection dialog frame', () => {it.each(['claude', 'codex'] as const)('%s keeps one heading, description and footer across every method switch', async (backend) => {mock.api.getBackendConnection.mockResolvedValue(connection({ backend, auth: 'none', ready: false, entry_eligible: false }));render(wrap(<BackendConnectionDialog backend={backend} method="oauth" onConnected={vi.fn()} onClose={vi.fn()} onWriteState={vi.fn()} />));- await screen.findByRole('radiogroup', { name: en.onboarding.connection.method });+ const group = await interactiveRadios(en.onboarding.connection.method);const opened = frame();expect(opened.title).toBe(`Connect ${backend === 'claude' ? 'Claude Code' : 'Codex'}`);expect(opened.rows).toEqual([1, 1, 1]);- const tabs = screen.getAllByRole('radio');+ const tabs = within(group).getAllByRole('radio');// Repeatedly, both directions: a heading computed from the method would// change here, and a changed heading is what used to move the frame.for (const tab of [...tabs].reverse().concat(tabs, [...tabs].reverse(), tabs)) {@@ -572,18 +1096,41 @@ describe('connection dialog frame', () => {expect(frame()).toEqual(opened);}// The method still actually changed the body underneath the fixed frame.- fireEvent.click(screen.getByRole('radio', { name: backend === 'claude' ? en.onboarding.connection.claudeCredentials : en.onboarding.connection.openaiKey }));+ fireEvent.click(within(group).getByRole('radio', { name: backend === 'claude' ? en.onboarding.connection.claudeCredentials : en.onboarding.connection.openaiKey }));// `find`, not `get`: the dialog's own readiness read resolves on its own schedule and// re-renders the body, so the credential form is not guaranteed on the click's tick.expect(await screen.findByRole('button', { name: en.onboarding.connection.saveConnect })).toBeTruthy();expect(frame()).toEqual(opened);});+ // The readiness the helper waits for, made deterministic rather than left to+ // how many ticks a resolved mock happens to take: while the connection read is+ // in flight the method row is already on screen and refuses to switch, so+ // acting on its mere presence changes nothing — and nothing that a switch+ // would have produced can ever arrive.+ it('refuses a method switch until the connection read lands, then takes it', async () => {+ const pending = deferred<BackendConnectionState>();+ mock.api.getBackendConnection.mockReturnValue(pending.promise);+ render(wrap(<BackendConnectionDialog backend="claude" method="oauth" onConnected={vi.fn()} onClose={vi.fn()} onWriteState={vi.fn()} />));+ const group = await screen.findByRole('radiogroup', { name: en.onboarding.connection.method });+ const credentials = () => within(group).getByRole('radio', { name: en.onboarding.connection.claudeCredentials });+ expect((credentials() as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(credentials());+ expect(credentials().getAttribute('aria-checked')).toBe('false');+ expect(screen.queryByRole('button', { name: en.onboarding.connection.saveConnect })).toBeNull();++ await act(async () => pending.resolve(connection({ backend: 'claude', auth: 'none', ready: false, entry_eligible: false })));+ await interactiveRadios(en.onboarding.connection.method);+ fireEvent.click(credentials());+ expect(credentials().getAttribute('aria-checked')).toBe('true');+ expect(await screen.findByRole('button', { name: en.onboarding.connection.saveConnect })).toBeTruthy();+ });+it('moves the method with arrows, Home and End, and leaves focus on the selected tab', async () => {mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'claude', auth: 'none', ready: false, entry_eligible: false }));render(wrap(<BackendConnectionDialog backend="claude" method="oauth" onConnected={vi.fn()} onClose={vi.fn()} onWriteState={vi.fn()} />));- const group = await screen.findByRole('radiogroup', { name: en.onboarding.connection.method });- const [subscription, apiKey] = screen.getAllByRole('radio');+ const group = await interactiveRadios(en.onboarding.connection.method);+ const [subscription, apiKey] = within(group).getAllByRole('radio');expect(subscription.getAttribute('aria-checked')).toBe('true');// One tab stop, so Tab lands on the selection the arrows then continue from — the// other half of the pattern, and what stops focus resting on an unselected tab.@@ -599,50 +1146,227 @@ describe('connection dialog frame', () => {expect(subscription.getAttribute('aria-checked')).toBe('true');});- it('offers the eight setup providers first, keeps a configured one out of More, and lets search reach the rest', async () => {- const entry = (id: string, name: string, patch: Partial<{ configured: boolean; models: string[] }> = {}) =>- ({ id, name, description: '', configured: false, oauth_available: false, local: false, models: [], ...patch });- mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [- // `alibaba-cn`, `moonshot` and `google` arrive as bare ids — the case the- // brand table exists for. `mistral` arrives with a real name of its own.- entry('mistral', 'Mistral AI'), entry('openrouter', 'OpenRouter'), entry('alibaba-cn', 'alibaba-cn', { configured: true }),- entry('openai', 'OpenAI'), entry('moonshot', 'moonshot'), entry('google', 'google'),- entry('deepseek', 'DeepSeek'), entry('anthropic', 'Anthropic'), entry('xai', 'xAI'),- entry('cerebras', 'Cerebras', { configured: true }), entry('groq', 'Groq', { models: ['llama-3.3-70b'] }),- entry('ollama', 'Ollama local', { configured: false }),- ] });+ // The picker's whole job in one fixture: every alias the brand table knows,+ // two brands that arrive under more than one id, a configured provider that+ // is NOT one of the eight, and the two ids the contract refuses to promote.+ const PICKER = [+ ['mistral', 'Mistral AI', { configured: true }], ['openrouter', 'OpenRouter', {}],+ ['alibaba-cn', 'Alibaba (China)', {}], ['alibaba', 'alibaba', {}], ['dashscope', 'Alibaba DashScope', { configured: true }],+ ['openai', 'OpenAI', {}], ['moonshot', 'moonshot', {}], ['moonshotai', 'Moonshot AI', {}],+ ['google', 'google', {}], ['google-vertex', 'google-vertex', {}], ['zhipu', 'zhipu', {}],+ ['deepseek', 'DeepSeek', {}], ['anthropic', 'Anthropic', {}], ['xai', 'xAI', {}],+ ['cerebras', 'Cerebras', {}], ['groq', 'Groq', { models: ['llama-3.3-70b'] }],+ ['zen', 'Zen', {}], ['go', 'Go', {}],+ ['ollama', 'Ollama local', { local: true }],+ ] as const;+ const pickerProvider = ([id, name, patch]: (typeof PICKER)[number]) =>+ ({ id, name, description: '', configured: false, oauth_available: false, local: false, models: [] as string[], ...patch });++ it('gives each prioritised brand exactly one row, and keeps every other native provider reachable', async () => {+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: PICKER.map(pickerProvider) });mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'opencode', auth: 'none', ready: false, entry_eligible: false }));render(wrap(<BackendConnectionDialog backend="opencode" method="api_key" onConnected={vi.fn()} onClose={vi.fn()} onWriteState={vi.fn()} />));- const names = () => screen.getAllByRole('button').map((node) => node.querySelector('strong')?.textContent).filter(Boolean);+ // A row is its title and the id it is filed under — the second line, which+ // is what the rest of OpenCode, its config and its model ids actually use.+ const rows = () => screen.getAllByRole('button').filter((node) => node.querySelector('strong'))+ .map((node) => ({ title: node.querySelector('strong')?.textContent ?? '', id: node.querySelector('small')?.textContent ?? '' }));+ const names = () => rows().map((row) => row.title);await waitFor(() => expect(names().length).toBeGreaterThan(0));- // The ratified default order, by friendly name rather than by the internal- // id: `google`, `moonshot` and `alibaba-cn` are not what anyone calls them.- expect(names().slice(0, 8)).toEqual(['OpenAI', 'Anthropic', 'xAI', 'Gemini', 'DeepSeek', 'Qwen', 'Kimi', 'OpenRouter']);- // A configured provider outside the eight stays reachable without More.- expect(names()).toContain('Cerebras');++ // Eight rows, one per brand, in the approved order and under the approved+ // names — `google`, `moonshot` and the Alibaba ids are not what anyone+ // calls them, and none of them may appear twice.+ expect(names()).toEqual(['OpenAI', 'Anthropic', 'xAI', 'Gemini', 'DeepSeek', 'Qwen', 'Kimi', 'OpenRouter']);+ // Which entry stands in a slot is decided, not incidental: the configured+ // one where a brand has one, else the lowest id.+ expect(rows().map((row) => row.id)).toEqual(['openai', 'anthropic', 'xai', 'google', 'deepseek', 'dashscope', 'moonshot', 'openrouter']);+ // Being configured is not a promotion: Mistral holds credentials and still+ // does not take a ninth slot.expect(names()).not.toContain('Mistral AI');- // The id it is filed under stays on the row, next to the brand name.- expect(screen.getByRole('button', { name: /Qwen/ }).textContent).toContain('alibaba-cn');+ // And the two ids the contract refuses to offer as an official choice+ // cannot reach the default list, because only the eight brands can.+ expect(names()).not.toContain('Zen');+ expect(names()).not.toContain('Go');- fireEvent.click(screen.getByRole('button', { name: /More providers \(3\)/ }));- // A server that already sent a friendly name keeps it; nothing is renamed- // to a catalog brand it did not claim.- expect(names()).toContain('Mistral AI');+ const eligible = PICKER.filter(([, , patch]) => !('local' in patch)).map(([id]) => id);+ fireEvent.click(screen.getByRole('button', { name: new RegExp(`More providers \\(${eligible.length - 8}\\)`) }));+ // Nothing the runtime offers is unreachable: the two lists together are+ // exactly the providers an API key can be saved for, each one once.+ expect(rows().map((row) => row.id).sort()).toEqual([...eligible].sort());+ const [shortlist, more] = [rows().slice(0, 8), rows().slice(8)];+ // Credentials already held are a reason to be easy to find, so More opens+ // on them; the rest follow by name.+ expect(more[0]).toEqual({ title: 'Mistral AI', id: 'mistral' });+ const rest = more.slice(1).map((row) => row.title);+ expect(rest).toEqual([...rest].sort((left, right) => left.localeCompare(right)));+ expect(more.map((row) => row.title)).toContain('Zen');+ expect(more.map((row) => row.title)).toContain('Go');+ // No two rows may read the same. A brand's remaining entries keep their own+ // name when the server sent one, and fall back to their id when it did not+ // — `alibaba` would otherwise read "Qwen" twice over.+ expect(new Set(names()).size).toBe(names().length);+ expect(more).toContainEqual({ title: 'Alibaba (China)', id: 'alibaba-cn' });+ expect(more).toContainEqual({ title: 'alibaba', id: 'alibaba' });+ expect(more).toContainEqual({ title: 'Moonshot AI', id: 'moonshotai' });+ expect(more).toContainEqual({ title: 'Zhipu AI', id: 'zhipu' });+ expect(shortlist).toContainEqual({ title: 'Gemini', id: 'google' });- // Search reaches a provider that More would otherwise hold, by model id too.- fireEvent.change(screen.getByLabelText(en.settings.backends.opencodeSearchPlaceholder), { target: { value: 'llama-3.3' } });- expect(names()).toEqual(['Groq']);+ // Search reaches every variant, under the brand name as well as the id.+ const search = () => screen.getByLabelText(en.settings.backends.opencodeSearchPlaceholder);+ const shortlistNames = names();+ fireEvent.change(search(), { target: { value: 'qwen' } });+ expect(rows().map((row) => row.id)).toEqual(['alibaba-cn', 'alibaba', 'dashscope']);expect(screen.queryByRole('button', { name: /More providers/ })).toBeNull();+ // And every row still reads what it read a moment ago. A name that changed+ // when the list narrowed would mean the one way to look for what you can see+ // is the one way to make it unrecognisable.+ expect(rows().map((row) => row.title)).toEqual(['Alibaba (China)', 'alibaba', 'Qwen']);+ fireEvent.change(search(), { target: { value: 'llama-3.3' } });+ expect(names()).toEqual(['Groq']);+ // Including the eight: searching them finds them by the names they wear.+ for (const brand of shortlistNames) {+ fireEvent.change(search(), { target: { value: brand } });+ expect(names()).toContain(brand);+ }// Picking one hands the middle to the form and keeps the same frame rows.- fireEvent.change(screen.getByLabelText(en.settings.backends.opencodeSearchPlaceholder), { target: { value: 'Qwen' } });+ fireEvent.change(search(), { target: { value: 'dashscope' } });fireEvent.click(screen.getByRole('button', { name: /Qwen/ }));expect(await screen.findByLabelText(en.onboarding.connection.apiKeyLabel)).toBeTruthy();expect(frame().title).toBe('Connect OpenCode');expect(frame().rows).toEqual([1, 1, 1]);- // The internal id the rest of OpenCode uses stays visible after the choice.+ // The capsule names the row that was picked, not a second opinion about the+ // same entry: this is Qwen's own endpoint, standing in Qwen's slot, and the+ // key is being written to `dashscope` either way.expect(screen.getByRole('button', { name: en.onboarding.connection.changeProvider }).closest('.connection-chosen')?.textContent).toContain('Qwen');+ expect(mock.api.setOpencodeProviderAuth).not.toHaveBeenCalled();+ fireEvent.change(screen.getByLabelText(en.onboarding.connection.apiKeyLabel), { target: { value: 'sk-relay' } });+ fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.saveConnect }));+ await waitFor(() => expect(mock.api.setOpencodeProviderAuth).toHaveBeenCalledWith('dashscope', 'sk-relay', null));+ });++ // A custom provider's id is whatever its author typed into Settings, and+ // OpenCode reserves only the ids it ships itself — so a personal relay can be+ // filed under `dashscope`, and every custom provider is reported configured,+ // which is exactly what decides a brand slot. Left alone, the relay would BE+ // the row someone picks to connect Qwen, and the key would go to the relay.+ it('never lets a custom provider stand in for, or be named as, a native brand', async () => {+ const entry = (id: string, name: string, patch: Partial<OpencodeProvider> = {}) =>+ ({ id, name, description: '', configured: false, oauth_available: false, local: false, models: [] as string[], ...patch });+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [+ entry('openai', 'OpenAI'), entry('alibaba-cn', 'Alibaba (China)'),+ // Filed under a brand's alias, and holding a name of its author's own.+ entry('dashscope', '内部中转', { configured: true, custom: true }),+ // And one whose author left the name blank: the server echoes the id back,+ // so the only thing left to read it as a brand with is the id itself.+ entry('gemini', 'gemini', { configured: true, custom: true }),+ ] });+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'opencode', auth: 'none', ready: false, entry_eligible: false }));+ render(wrap(<BackendConnectionDialog backend="opencode" method="api_key" onConnected={vi.fn()} onClose={vi.fn()} onWriteState={vi.fn()} />));+ const nodes = () => screen.getAllByRole('button').filter((node) => node.querySelector('strong'));+ const rows = () => nodes().map((node) => ({ title: node.querySelector('strong')?.textContent ?? '', id: node.querySelector('small')?.textContent ?? '' }));+ await waitFor(() => expect(rows().length).toBeGreaterThan(0));++ // The slot goes to the entry OpenCode ships, even though the relay is the+ // configured one; and a brand with nothing but a relay behind it gets no+ // row at all, rather than one that would name an endpoint after it.+ expect(rows()).toEqual([{ title: 'OpenAI', id: 'openai' }, { title: 'Qwen', id: 'alibaba-cn' }]);++ fireEvent.click(screen.getByRole('button', { name: /More providers \(2\)/ }));+ // Both stay reachable under More, under what they were configured as.+ expect(rows().slice(2)).toEqual([{ title: 'gemini', id: 'gemini' }, { title: '内部中转', id: 'dashscope' }]);+ // And they are drawn as what they are — an address you supply, the same+ // mark the custom vendor has always used — not as the brand they sit next to.+ const mark = (id: string) => nodes().find((node) => node.querySelector('small')?.textContent === id)+ ?.querySelector('.connection-provider-mark')?.innerHTML;+ expect(mark('dashscope')).toBe(mark('gemini'));+ expect(mark('dashscope')).not.toBe(mark('alibaba-cn'));++ // Searching a brand reaches the entries that brand actually ships — under the+ // same name they wear in the list, so what was found is recognisably what was+ // there — and never the relay wearing its id.+ fireEvent.change(screen.getByLabelText(en.settings.backends.opencodeSearchPlaceholder), { target: { value: 'qwen' } });+ expect(rows()).toEqual([{ title: 'Qwen', id: 'alibaba-cn' }]);+ // ...and the relay is found by the name its author gave it.+ fireEvent.change(screen.getByLabelText(en.settings.backends.opencodeSearchPlaceholder), { target: { value: '内部' } });+ expect(rows()).toEqual([{ title: '内部中转', id: 'dashscope' }]);++ // Including where it matters most: the capsule over the key field names the+ // endpoint the key is about to be written to.+ fireEvent.click(screen.getByRole('button', { name: /内部中转/ }));+ expect(await screen.findByLabelText(en.onboarding.connection.apiKeyLabel)).toBeTruthy();+ const capsule = screen.getByRole('button', { name: en.onboarding.connection.changeProvider }).closest('.connection-chosen');+ expect(capsule?.textContent).toContain('内部中转');+ expect(capsule?.textContent).not.toContain('Qwen');+ });++ // A custom provider's name is whatever its author typed, so it can spell another+ // row's brand, another row's id, or the composition of the two. Each of those is+ // a name this list would otherwise hand out twice — and two rows reading alike is+ // two endpoints a person cannot choose between, holding different keys.+ it('hands out one name per row even when a custom name spells the fallback of another', async () => {+ const entry = (id: string, name: string, patch: Partial<OpencodeProvider> = {}) =>+ ({ id, name, description: '', configured: false, oauth_available: false, local: false, models: [] as string[], ...patch });+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [+ // Already holding credentials, so this is the entry that takes Qwen's slot.+ entry('openai', 'OpenAI'), entry('alibaba-cn', 'Alibaba (China)', { configured: true }),+ // Named for the very id the native `alibaba` row falls back to...+ entry('mirror', 'alibaba', { configured: true, custom: true }),+ // ...and named for the composition after that, so the ladder has to widen.+ entry('decoy', 'Qwen (alibaba)', { configured: true, custom: true }),+ // Which leaves this one — a real Qwen entry — with nothing of its own left:+ // the brand went to the slot, the id and the composition to the two above.+ entry('alibaba', 'alibaba'),+ ] });+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'opencode', auth: 'none', ready: false, entry_eligible: false }));+ render(wrap(<BackendConnectionDialog backend="opencode" method="api_key" onConnected={vi.fn()} onClose={vi.fn()} onWriteState={vi.fn()} />));+ const nodes = () => screen.getAllByRole('button').filter((node) => node.querySelector('strong'));+ const rows = () => nodes().map((node) => ({ title: node.querySelector('strong')?.textContent ?? '', id: node.querySelector('small')?.textContent ?? '' }));+ await waitFor(() => expect(rows().length).toBeGreaterThan(0));++ // The slots are untouched by any of it: native entries, brand order, brand names.+ expect(rows()).toEqual([{ title: 'OpenAI', id: 'openai' }, { title: 'Qwen', id: 'alibaba-cn' }]);+ fireEvent.click(screen.getByRole('button', { name: /More providers \(3\)/ }));+ const all = rows();+ // Every eligible provider is reachable, each once, under its real id.+ expect(all.map((row) => row.id).sort()).toEqual(['alibaba', 'alibaba-cn', 'decoy', 'mirror', 'openai']);+ // And no two of them read alike, however the names were spelled.+ const titles = all.map((row) => row.title.toLowerCase());+ expect(new Set(titles).size).toBe(titles.length);+ // Each row got the first name still free when its turn came: the custom pair+ // kept what they were configured as, and the row they crowded out says which+ // brand it is AND which entry of it, which is the whole point of falling back.+ expect(all).toContainEqual({ title: 'alibaba', id: 'mirror' });+ expect(all).toContainEqual({ title: 'Qwen (alibaba)', id: 'decoy' });+ expect(all).toContainEqual({ title: 'Qwen (alibaba 2)', id: 'alibaba' });+ // Neither relay took a brand's mark on the way past.+ const mark = (id: string) => nodes().find((node) => node.querySelector('small')?.textContent === id)+ ?.querySelector('.connection-provider-mark')?.innerHTML;+ expect(mark('mirror')).toBe(mark('decoy'));+ expect(mark('mirror')).not.toBe(mark('alibaba-cn'));+ expect(mark('alibaba')).toBe(mark('alibaba-cn'));++ // Search finds each of them by the exact text it is showing — including the+ // one whose name this list invented, which nothing but the list could know.+ const search = () => screen.getByLabelText(en.settings.backends.opencodeSearchPlaceholder);+ for (const row of all) {+ fireEvent.change(search(), { target: { value: row.title } });+ expect(rows()).toContainEqual(row);+ }+ // A brand search still reaches every entry of that brand, unchanged by having+ // been searched for.+ // The brand's own entries lead, then the relay that matched only because the+ // name this list gave it happens to contain the word.+ fireEvent.change(search(), { target: { value: 'qwen' } });+ expect(rows().map((row) => row.id)).toEqual(['alibaba-cn', 'alibaba', 'decoy']);++ // And the name is only ever a name: the key goes to the id that was picked.+ fireEvent.click(screen.getByRole('button', { name: /Qwen \(alibaba 2\)/ }));+ fireEvent.change(await screen.findByLabelText(en.onboarding.connection.apiKeyLabel), { target: { value: 'sk-qwen' } });+ expect(screen.getByRole('button', { name: en.onboarding.connection.changeProvider }).closest('.connection-chosen')?.textContent).toContain('Qwen (alibaba 2)');+ fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.saveConnect }));+ await waitFor(() => expect(mock.api.setOpencodeProviderAuth).toHaveBeenCalledWith('alibaba', 'sk-qwen', null));});it('never offers a local provider for an API Key, and follows OAuth capability for subscriptions', async () => {diff --git a/ui/src/components/onboarding/BackendConnectionDialog.tsx b/ui/src/components/onboarding/BackendConnectionDialog.tsxindex 6e98dfb71..80fedddb8 100644--- a/ui/src/components/onboarding/BackendConnectionDialog.tsx+++ b/ui/src/components/onboarding/BackendConnectionDialog.tsx@@ -21,24 +21,79 @@ import { useTranslation } from 'react-i18next';import { useApi, type OpencodeProvider } from '@/context/ApiContext';import { errorMessage } from '@/lib/errorMessage';import { getBackendUiMeta } from '@/lib/agentBackends';+import { useViewportHeightVar } from '@/lib/useViewportHeightVar';import { Dialog, DialogContent, DialogDescription, DialogTitle } from '../ui/dialog';import { Button } from '../ui/button';import { Input } from '../ui/input';import { BackendIcon } from '../visual';import { VendorGlyph } from '../settings/models/vendorGlyph';-import { providerLabel, providerVendorId, setupPrimaryRank } from '../settings/providers/providerIdentity';+import { CUSTOM_VENDOR } from '../settings/models/apiKeyVendors';+import { providerBrandLabel, providerLabel, providerVendorId, setupPrimaryRank, SETUP_PRIMARY_VENDORS } from '../settings/providers/providerIdentity';import { BackendConnectionForm } from '../settings/providers/BackendConnectionForm';import type { BackendId } from '../settings/shared/useBackendRuntime';/** One provider choice: its brand mark, the name a person recognises, and the id* OpenCode files it under — shown because that id is what the rest of OpenCode,- * its config file and its model identifiers use. */-function ProviderRow({ entry, onPick }: { entry: OpencodeProvider; onPick: () => void }) {+ * its config file and its model identifiers use. The name is not the row's to+ * compute: it is handed out once for the whole list by `allocate` below, because+ * what a row may be called depends on what every other row is already called. */+type PickerRow = { entry: OpencodeProvider; label: string };++// A custom provider's id is whatever its author typed into Settings, and OpenCode+// only reserves the ids it ships itself — so someone's own relay can be filed+// under `dashscope`, or under a brand's own name. That id is not evidence of a+// brand, and the catalog alias must not read it as one: a relay that inherited+// Qwen's slot, name and mark would be the row a person picks to connect Qwen,+// and the credential would be written to the relay. So identity for these rows+// comes from what they were configured as, and they are never brand candidates.++/** The mark a row draws. 自定义 has never had a logo — it takes the field's own+ * subject, an address you supply — and that is exactly what a custom provider+ * is, so it draws the same thing rather than borrowing a brand's. */+const providerMark = (entry: OpencodeProvider) => entry.custom ? CUSTOM_VENDOR : providerVendorId(entry.id);++/** What a row is called where it is not standing in a brand slot. `providerLabel`+ * would read a relay filed under `dashscope` as "Qwen" the moment its author+ * left the name blank, because the server echoes the id back as the name. */+const providerTitle = (entry: OpencodeProvider) => entry.custom+ ? entry.name?.trim() || entry.id+ : providerLabel(entry.id, entry.name);++/**+ * The name a row is allowed to show, given the names already handed out.+ *+ * The rule is that no two rows may read alike: a person choosing between them has+ * nothing else to act on, and the two are different endpoints that will be sent+ * different credentials. What a row asks for is `natural` — a brand's own name in+ * a brand slot, a custom provider's configured name anywhere else — and asking+ * first wins, which is why brand slots are allocated first.+ *+ * A row that loses falls back to the id OpenCode files it under, which is unique+ * within one catalog and is the thing that actually tells two entries of a brand+ * apart. But that id may itself already be on screen, because a custom provider's+ * *name* is whatever its author typed and may spell another row's id exactly. So+ * every candidate is checked before it is taken, including the fallback and the+ * composition after it — a candidate that is merely emitted rather than reserved+ * is how two rows come to read the same in the first place.+ *+ * The widening at the end terminates for the same reason the ladder is needed:+ * each attempt produces a string no earlier attempt did, and only finitely many+ * names have been handed out, so some attempt is free.+ */+const allocate = (natural: string, id: string, used: Set<string>): string => {+ let label = natural;+ for (let attempt = 0; used.has(label.toLowerCase()); attempt += 1) {+ label = attempt === 0 ? id : attempt === 1 ? `${natural} (${id})` : `${natural} (${id} ${attempt})`;+ }+ used.add(label.toLowerCase());+ return label;+};++function ProviderRow({ entry, label, onPick }: PickerRow & { onPick: () => void }) {const { t } = useTranslation();- const label = providerLabel(entry.id, entry.name);return (<button type="button" className="connection-provider focus-visible:outline-2 focus-visible:outline-ring" onClick={onPick}>- <span className="connection-provider-mark"><VendorGlyph vendor={providerVendorId(entry.id)} /></span>+ <span className="connection-provider-mark"><VendorGlyph vendor={providerMark(entry)} /></span><span className="connection-provider-text"><strong>{label}</strong><small>{label.toLowerCase() === entry.id.toLowerCase() ? entry.description || entry.id : entry.id}</small>@@ -49,6 +104,82 @@ function ProviderRow({ entry, onPick }: { entry: OpencodeProvider; onPick: () =>);}+// Which of the two layouts in `connection.css` the room can actually hold.+//+// Five fixed rows work until the room is smaller than what those rows cost plus+// something worth putting between them. Stopping at the rows alone would only+// move the defect: a middle of one pixel is as unusable as a middle of none, and+// a scroll container with no height scrolls nothing, so the fields inside it+// become unreachable rather than merely small. The floor is therefore the four+// fixed rows, the gaps between them, the padding on both sides — and one more+// control row, the height this dialog already gives every control it owns, so+// that what is left is a usable amount of room rather than a sliver.+//+// One control row is not one field, and this floor does not claim to be: a field+// is a label, an input taller than a control row, and a hint under it, so the+// reserve is deliberately the smaller, load-bearing half of that. What it buys is+// that the middle always has room worth scrolling, not that any one field fits.+//+// CSS cannot ask the question: media queries read the layout viewport, which is+// the very measurement a soft keyboard leaves wrong. So it is asked here, from+// the metrics the stylesheet resolved for the band actually in force, and the+// answer is written back as an attribute. Every term is a plain length in the+// stylesheet, so this needs nothing of the browser beyond reading them.+//+// Both sides of the comparison are independent of what the body holds: the+// metrics belong to the band, and the height belongs to the room. A method+// switch or an error cannot flip the layout — the same guarantee the fixed frame+// exists to give.+const ROOM_FLOOR: ReadonlyArray<readonly [string, number]> = [+ ['--connection-head', 1], ['--connection-desc', 1], ['--connection-footer', 1],+ ['--connection-gap', 4], ['--connection-pad', 2],+ // Twice: the method row, and one more for the middle to show a whole control in.+ ['--connection-controls', 2],+];++function useRoomFloor() {+ const stop = useRef<(() => void) | undefined>(undefined);+ // A callback ref, not an effect: the frame is rendered through a portal that+ // arrives a commit later than this component, so an effect would run while the+ // ref was still empty and never measure anything. This runs exactly when the+ // frame attaches, and again with `null` when it goes away.+ return useCallback((node: HTMLDivElement | null) => {+ stop.current?.();+ stop.current = undefined;+ if (!node || typeof ResizeObserver === 'undefined') return;+ const measure = () => {+ const style = getComputedStyle(node);+ let floor = 0;+ for (const [name, count] of ROOM_FLOOR) floor += (parseFloat(style.getPropertyValue(name)) || 0) * count;+ // `clientHeight` is the padding box, which is what the rows, the gaps and+ // the padding have to fit inside; the frame's border sits outside both, so+ // neither side counts it.+ const tight = floor > node.clientHeight;+ if (tight === (node.dataset.room === 'tight')) return;+ if (tight) node.dataset.room = 'tight'; else delete node.dataset.room;+ };+ measure();+ // The observer catches every room the frame is resized into — a rotation, a+ // window resize, the band changing underneath it. The visual viewport catches+ // the one thing that resizes nothing: a soft keyboard, which leaves the layout+ // viewport exactly as it was.+ //+ // Neither can feed back. The attribute changes which row absorbs the middle,+ // not the frame's box, so the observer is not re-armed by its own answer, and+ // a repeat answer returns above without touching the DOM at all.+ const observer = new ResizeObserver(measure);+ observer.observe(node);+ const vv = window.visualViewport;+ vv?.addEventListener('resize', measure);+ vv?.addEventListener('scroll', measure);+ stop.current = () => {+ observer.disconnect();+ vv?.removeEventListener('resize', measure);+ vv?.removeEventListener('scroll', measure);+ };+ }, []);+}+export function BackendConnectionDialog({ backend, method, onClose, onConnected, onWriteState }: {backend: BackendId;method: 'oauth' | 'api_key';@@ -57,6 +188,15 @@ export function BackendConnectionDialog({ backend, method, onClose, onConnected,onWriteState: (pending: boolean) => void;}) {const api = useApi(); const { t } = useTranslation();+ // The frame is bound and centred in the USABLE viewport — a rectangle, not a+ // height: on a phone that is what the soft keyboard leaves, and iOS also pans+ // it sideways to keep a focused field in sight. `dvh` and `vw` cannot see+ // either, and this route is the setup wizard rather than the app shell that+ // normally keeps those four variables current, so the dialog keeps them+ // current itself. It is not the only consumer, and the hook is written for+ // that: both may be mounted at once.+ useViewportHeightVar();+ const frame = useRoomFloor();const [providers, setProviders] = useState<OpencodeProvider[]>([]);const [provider, setProvider] = useState<OpencodeProvider>();const [loading, setLoading] = useState(backend === 'opencode');@@ -89,33 +229,100 @@ export function BackendConnectionDialog({ backend, method, onClose, onConnected,: backend === 'codex' ? 'onboarding.connection.codexDialogIntro': 'onboarding.connection.opencodeDialogIntro');- const { shortlist, more } = useMemo(() => {- const term = query.trim().toLowerCase();+ // What every row is called, decided once for the whole catalog and before any+ // query narrows it.+ //+ // Two things have to hold at the same time, and only one place can hold both.+ // No two rows may read alike, and a row must read the same whether or not+ // somebody typed in the search box — otherwise searching for the name you can+ // see is the one way to make it disappear. So names are handed out here, over+ // every eligible provider, and the search below matches the name that was handed+ // out rather than recomputing one of its own.+ //+ // Order is the whole of the policy: a brand slot asks first, so the eight always+ // read as their brand; everything else asks in catalog order, which no sort or+ // query can disturb. What each row asks for is its own, and `allocate` decides+ // what it actually gets.+ const naming = useMemo(() => {// Subscriptions follow OpenCode's real OAuth capability; the eight brands// below are an API-key presentation order, not an authentication catalog.const eligible = providers.filter((entry) => (method === 'api_key' ? !entry.local : entry.oauth_available));- const matching = eligible.filter((entry) => !term- || `${providerLabel(entry.id, entry.name)} ${entry.name} ${entry.id} ${entry.models.join(' ')}`.toLowerCase().includes(term));- const rank = (entry: OpencodeProvider) => method === 'api_key' ? setupPrimaryRank(entry.id) : null;- const ordered = [...matching].sort((left, right) => {- const [a, b] = [rank(left), rank(right)];- if (a !== null && b !== null) return a - b;- if (a !== null) return -1;- if (b !== null) return 1;- // Providers already holding credentials stay reachable without More.- if (left.configured !== right.configured) return left.configured ? -1 : 1;- return providerLabel(left.id, left.name).localeCompare(providerLabel(right.id, right.name));+ const byVendor = new Map<string, OpencodeProvider[]>();+ for (const entry of eligible) {+ if (entry.custom) continue;+ const vendor = providerVendorId(entry.id);+ const group = byVendor.get(vendor);+ if (group) group.push(entry); else byVendor.set(vendor, [entry]);+ }+ // Exactly one row per prioritised brand, in the approved order, and only+ // for the brands this runtime actually offers — an absent brand leaves no+ // slot behind rather than a row that cannot be connected. Which entry+ // represents a brand is decided rather than incidental: one already holding+ // credentials, else the id that IS the brand, else the lowest id. So two+ // aliases of one brand can never both take the shortlist, and two reads of+ // the same catalog can never trade them. Only entries OpenCode ships are+ // candidates: a brand with nothing but a custom relay behind it gets no row+ // rather than a row that would name someone's endpoint after it.+ const chosen = method !== 'api_key' ? [] : SETUP_PRIMARY_VENDORS.flatMap((vendor) => {+ const group = byVendor.get(vendor);+ if (!group?.length) return [];+ const exact = (entry: OpencodeProvider) => entry.id.trim().toLowerCase() === vendor;+ return [[...group].sort((left, right) => {+ if (left.configured !== right.configured) return left.configured ? -1 : 1;+ if (exact(left) !== exact(right)) return exact(left) ? -1 : 1;+ return left.id.localeCompare(right.id);+ })[0]];});+ const slots = new Set(chosen.map((entry) => entry.id));+ const used = new Set<string>();+ const labels = new Map<string, string>();+ for (const entry of [...chosen, ...eligible.filter((entry) => !slots.has(entry.id))]) {+ labels.set(entry.id, allocate(slots.has(entry.id) ? providerBrandLabel(entry.id, entry.name) : providerTitle(entry), entry.id, used));+ }+ // A provider this allocation never saw — the one already chosen, when the+ // method has since changed under it — still has to be callable something.+ return { eligible, chosen, slots, label: (entry: OpencodeProvider) => labels.get(entry.id) ?? providerTitle(entry) };+ }, [providers, method]);++ const { shortlist, more } = useMemo(() => {+ const { eligible, chosen, slots, label } = naming;+ const term = query.trim().toLowerCase();+ // Every name this row answers to is searchable: the one it shows, the one+ // OpenCode gave it, its id, its models — so "qwen" finds the row the catalog+ // calls "Alibaba (China)" and "alibaba" still finds it too. A custom provider+ // is searched by what it is and not by the brand its id happens to spell.+ const haystack = (entry: OpencodeProvider) => [label(entry), providerTitle(entry), entry.name, entry.id, entry.models.join(' '),+ entry.custom ? '' : `${providerBrandLabel(entry.id, entry.name)} ${providerLabel(entry.id, entry.name)}`].join(' ').toLowerCase();+ const matching = eligible.filter((entry) => !term || haystack(entry).includes(term));+ const rank = (entry: OpencodeProvider) => method === 'api_key' && !entry.custom ? setupPrimaryRank(entry.id) : null;+ const row = (entry: OpencodeProvider): PickerRow => ({ entry, label: label(entry) });// A search has to reach every provider, so it collapses nothing. Neither// does the subscription list: it is already only what can sign in, and- // there is no shortlist to be the remainder of.- if (term || method !== 'api_key') return { shortlist: ordered, more: [] as OpencodeProvider[] };- const promoted = (entry: OpencodeProvider) => rank(entry) !== null || entry.configured;- return { shortlist: ordered.filter(promoted), more: ordered.filter((entry) => !promoted(entry)) };- }, [providers, method, query]);+ // there is no shortlist to be the remainder of. Both keep the brand order+ // in front, then whatever already holds credentials.+ if (term || method !== 'api_key') return {+ shortlist: [...matching].sort((left, right) => {+ const [a, b] = [rank(left), rank(right)];+ if (a !== null && b !== null) return a - b;+ if (a !== null) return -1;+ if (b !== null) return 1;+ if (left.configured !== right.configured) return left.configured ? -1 : 1;+ return label(left).localeCompare(label(right));+ }).map(row),+ more: [] as PickerRow[],+ };+ // Holding credentials is a reason to be easy to find, not a reason to take+ // a brand's slot — so a configured provider opens More instead of growing+ // the eight. Everything the shortlist did not take is here, which is what+ // keeps every native provider reachable without a search.+ return { shortlist: chosen.map(row), more: matching.filter((entry) => !slots.has(entry.id)).map(row).sort((left, right) => {+ if (left.entry.configured !== right.entry.configured) return left.entry.configured ? -1 : 1;+ return left.label.localeCompare(right.label);+ }) };+ }, [naming, method, query]);return <Dialog open onOpenChange={(open) => { if (!open) onClose(); }}>- <DialogContent className="connection-dialog" data-backend={backend} closeLabel={t('common.close')}>+ <DialogContent ref={frame} className="connection-dialog" data-backend={backend} closeLabel={t('common.close')}><div className="connection-heading"><div className="connection-logo"><BackendIcon backend={backend} variant="brand" brandFit="mark" size={28} aria-hidden="true" /></div><div><DialogTitle>{title}</DialogTitle><p>{t(`onboarding.setup.${backend}Description`)}</p></div></div>@@ -128,8 +335,10 @@ export function BackendConnectionDialog({ backend, method, onClose, onConnected,</div>) : provider ? (<div className="connection-controls connection-chosen">- <span className="connection-provider-mark"><VendorGlyph vendor={providerVendorId(provider.id)} /></span>- <span className="connection-provider-text"><strong>{providerLabel(provider.id, provider.name)}</strong><small>{t('onboarding.connection.providerDescription')}</small></span>+ <span className="connection-provider-mark"><VendorGlyph vendor={providerMark(provider)} /></span>+ {/* The row that was picked, still reading exactly as it read when it was+ picked — one row, one name, everywhere it appears. */}+ <span className="connection-provider-text"><strong>{naming.label(provider)}</strong><small>{t('onboarding.connection.providerDescription')}</small></span><Button variant="ghost" size="xs" disabled={busy} onClick={() => setProvider(undefined)}>{t('onboarding.connection.changeProvider')}</Button></div>) : null}@@ -139,13 +348,13 @@ export function BackendConnectionDialog({ backend, method, onClose, onConnected,{error && <div className="connection-error" role="alert">{error}<Button variant="secondary" onClick={() => void load()}>{t('common.retry')}</Button></div>}<p className="connection-intro">{t(method === 'api_key' ? 'onboarding.connection.pickKey' : 'onboarding.connection.pickSubscription')}</p><div className="connection-provider-list">- {shortlist.map((entry) => <ProviderRow key={entry.id} entry={entry} onPick={() => setProvider(entry)} />)}+ {shortlist.map(({ entry, label }) => <ProviderRow key={entry.id} entry={entry} label={label} onPick={() => setProvider(entry)} />)}{more.length > 0 && <><Button type="button" variant="secondary" className="connection-more" aria-expanded={showMore} onClick={() => setShowMore((open) => !open)}>{showMore ? <ChevronDown size={15} /> : <ChevronRight size={15} />}{t('onboarding.connection.moreProviders')} ({more.length})</Button>- {showMore && more.map((entry) => <ProviderRow key={entry.id} entry={entry} onPick={() => setProvider(entry)} />)}+ {showMore && more.map(({ entry, label }) => <ProviderRow key={entry.id} entry={entry} label={label} onPick={() => setProvider(entry)} />)}</>}</div>{!loading && !error && shortlist.length === 0 && more.length === 0 && <p className="connection-intro">{t('onboarding.connection.noProviders')}</p>}diff --git a/ui/src/components/settings/providers/BackendConnectionForm.tsx b/ui/src/components/settings/providers/BackendConnectionForm.tsxindex 235818cde..32c16ac54 100644--- a/ui/src/components/settings/providers/BackendConnectionForm.tsx+++ b/ui/src/components/settings/providers/BackendConnectionForm.tsx@@ -15,8 +15,97 @@ import { OAuthDeviceCodeRow, OAuthLinkRow } from '../oauth/OAuthFlowParts';import './connection.css';type Method = 'oauth' | 'api_key';+type Credential = 'api_key' | 'auth_token';type NativeState = ClaudeAuthState | CodexAuthState;-export type ConnectionHeading = { method: Method; active: boolean; credential: 'api_key' | 'auth_token' };+export type ConnectionHeading = { method: Method; active: boolean; credential: Credential };++/**+ * One unsent secret, per credential type.+ *+ * An API key and an auth token are different credentials, not two spellings of+ * one: they are issued separately, formatted differently and sent under+ * different keys. A single draft therefore carried a half-typed key into the+ * Auth Token field the moment someone checked what the other option was — and+ * the same shared `editing` flag decided, for both, whether the stored mask was+ * showing. Keeping a draft per credential type means switching only ever+ * changes which draft is on screen, which is also what makes switching back+ * safe.+ */+type Draft = { value: string; editing: boolean };+const CREDENTIALS: readonly Credential[] = ['api_key', 'auth_token'];+const EMPTY_DRAFTS: Readonly<Record<Credential, Draft>> = {+ api_key: { value: '', editing: false },+ auth_token: { value: '', editing: false },+};+/** Typed, or asked to replace what is stored — either way, something is on screen to lose. */+const unsaved = (draft: Draft) => draft.value !== '' || draft.editing;++/**+ * What a confirmation is allowed to spend, and what it has to prove.+ *+ * A receipt settles one submission, so the only work it may release is the work+ * that submission actually carried: signing in sends no credential and no URL at+ * all, and a save sends at most one type's value alongside one URL. Carrying the+ * work itself as well as its name is what makes a late receipt safe — anything+ * changed since the write went out is no longer what was sent, so it outlives+ * its own submission's receipt rather than being erased by it. A deferred+ * confirmation therefore settles what was submitted rather than whatever happens+ * to be on screen when it lands.+ *+ * `sent` is the **whole draft** that went out, not its value, because a draft is+ * a value *and* whether someone is part-way through replacing what is stored.+ * Those two states can share a value: an empty field nobody has opened and a+ * field just opened by Replace both read `''`, and only one of them is the state+ * that was submitted. It is `null` when the payload omitted the credential+ * altogether — a save that changes only the address sends no key, so its receipt+ * has no credential work to spend, and modelling that as an empty draft would+ * make it spend one.+ *+ * `credential` is the type the write *declared*, which is not the same question:+ * Claude sends `credential_type` on every save, including one that carries no+ * key, so the type a receipt must prove outlives the draft it may or may not+ * have sent. `null` says this write declared no type at all.+ *+ * `baseUrl` is the URL exactly as it stood in the field, not the trimmed payload:+ * the question it answers is whether the person has moved on since, and `null`+ * says this write carried no URL to settle.+ */+type Submission = { method: Method; baseUrl: string | null; credential: Credential | null; sent: Draft | null };+const sameDraft = (left: Draft, right: Draft) => left.value === right.value && left.editing === right.editing;++/**+ * What one receipt releases, decided once.+ *+ * Every question here is the same question — did this submission carry this+ * editable, and does the screen still read the way it was sent — and the answers+ * are wanted in three places: the drafts to keep, the ownership to give back, and+ * whether the form may follow the server again. Answering it once and reading the+ * answer three times is the whole point of the type; computing it once by+ * comparison and again by assumption is how a retained draft lost its ownership.+ */+type Settlement = { drafts: Record<Credential, Draft>; baseUrl: boolean; method: boolean; credentialType: boolean };+const settle = (submission: Submission, showing: { baseUrl: string; method: Method; credential: Credential; drafts: Record<Credential, Draft> }): Settlement => {+ const { credential, sent } = submission;+ const released = credential !== null && sent !== null && sameDraft(showing.drafts[credential], sent);+ return {+ drafts: released && credential !== null ? { ...showing.drafts, [credential]: EMPTY_DRAFTS[credential] } : showing.drafts,+ baseUrl: submission.baseUrl !== null && showing.baseUrl === submission.baseUrl,+ method: showing.method === submission.method,+ credentialType: credential !== null && showing.credential === credential,+ };+};++/**+ * Something on this form a person can change, and an observation can seed over.+ *+ * The four are one list because they share one rule — a reseed follows the+ * server only where nobody has said otherwise — and they are tracked apart+ * because they are released apart. One shared flag would answer "has anything+ * been touched", which is the right question to ask before seeding and the wrong+ * one to answer after a receipt: settling a credential would clear a URL that+ * write never carried.+ */+type Editable = Credential | 'base_url' | 'method' | 'credential_type';/** Settings and onboarding share persistence, validation, effective readback and cancellation. */export function BackendConnectionForm({ backend, provider, initialMethod = 'oauth', compact = false,@@ -39,9 +128,9 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oautconst [native, setNative] = useState<NativeState | null>(null);const [currentProvider, setCurrentProvider] = useState(provider);const [method, setMethod] = useState<Method>(backend === 'opencode' && !provider?.oauth_available ? 'api_key' : initialMethod);- const [credential, setCredential] = useState<'api_key' | 'auth_token'>('api_key');- const [key, setKey] = useState('');- const [editing, setEditing] = useState(false);+ const [credential, setCredential] = useState<Credential>('api_key');+ const [drafts, setDrafts] = useState<Record<Credential, Draft>>(EMPTY_DRAFTS);+ const { value: key, editing } = drafts[credential];const [reveal, setReveal] = useState(false);const [baseUrl, setBaseUrl] = useState('');const [loading, setLoading] = useState(true);@@ -53,8 +142,34 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oautconst [applyPending, setApplyPending] = useState(false);const [authReadable, setAuthReadable] = useState(false);const observation = useRef(0);- const draftTouched = useRef(false);- const pendingConfirmation = useRef<Method | null>(null);+ const touched = useRef(new Set<Editable>());+ /**+ * What the person is looking at right now.+ *+ * A receipt is read in the render that dispatched the write, and the gap this+ * whole type closes is exactly the one where the field moved on while that+ * write was in flight. So the comparison a receipt makes is against the live+ * values, kept the same way `onConnectedRef` is.+ */+ const onScreen = useRef({ baseUrl, method, credential, drafts });+ onScreen.current = { baseUrl, method, credential, drafts };+ /**+ * Edits only ever reach the credential type currently on screen.+ *+ * Ownership is read off the draft the edit produces rather than asserted by the+ * act of editing, because not every edit leaves something to lose: Cancel puts+ * the field back exactly as an untouched one, and a form that still claimed it+ * would stop following the server for the rest of its life over nothing.+ */+ const patchDraft = useCallback((patch: Partial<Draft>) => {+ setDrafts((current) => {+ const next = { ...current[credential], ...patch };+ if (unsaved(next)) touched.current.add(credential);+ else touched.current.delete(credential);+ return { ...current, [credential]: next };+ });+ }, [credential]);+ const pendingConfirmation = useRef<Submission | null>(null);const writeState = useRef(onWriteState); writeState.current = onWriteState;const lifetime = useRef({ mounted: true, busy: false });const onConnectedRef = useRef(onConnected); onConnectedRef.current = onConnected;@@ -76,20 +191,21 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut}, [api, backend, provider?.id, t]);// Native persistence and controller application are independent observations.// A failed IPC read must not discard a successful post-commit credential read.- const observe = useCallback(async ({ expectedMethod, receiptError = '' }: {- expectedMethod?: Method; receiptError?: string;+ const observe = useCallback(async ({ expected, receiptError = '' }: {+ expected?: Submission; receiptError?: string;} = {}) => {const token = ++observation.current;const current = () => lifetime.current.mounted && token === observation.current;setConnected(false); setSavedDisabled(false); setError(receiptError);+ const pristine = () => touched.current.size === 0;const nativeRead = read().then((fresh) => {if (current()) {setNative(fresh.native); setCurrentProvider(fresh.provider); setAuthReadable(true);- if (!draftTouched.current) {+ if (pristine()) {setBaseUrl(fresh.native?.base_url || fresh.provider?.base_url || '');if (fresh.native && 'credential_type' in fresh.native) setCredential(fresh.native.credential_type || 'api_key');}- if (!compact && !draftTouched.current) {+ if (!compact && pristine()) {const effective = fresh.native?.active_auth_mode;setMethod(effective && effective !== 'none' ? effective : fresh.provider?.active_auth_type === 'api' ? 'api_key' : backend === 'opencode' && !provider?.oauth_available ? 'api_key' : initialMethod);}@@ -115,7 +231,22 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oautconst uncertain = fresh.native && 'auth_mode_uncertain' in fresh.native && fresh.native.auth_mode_uncertain;hasAuth = ['oauth', 'api_key'].includes(effective) && !uncertain;keylessSettings = !compact && Boolean(fresh.provider?.custom && fresh.provider.configured && effective === 'none');- if (expectedMethod && ((!keylessSettings && effective !== expectedMethod) || uncertain)) messages.push(t('onboarding.connection.unconfirmed'));+ if (expected && ((!keylessSettings && effective !== expected.method) || uncertain)) messages.push(t('onboarding.connection.unconfirmed'));+ // Claude's two credential types are one method. `active_auth_mode` reads+ // `api_key` for a token exactly as it does for a key, so the method above+ // cannot tell a token write that landed from one that did not — only the+ // type the readback reports can. Absent or mismatched is unconfirmed: the+ // producer emits this field for every stored credential, including its+ // legacy API-key fallback, so nothing to compare means nothing observed,+ // not licence to settle on the weaker half of the question. Backends with+ // no such discriminator keep the method answer they have always had. The+ // claim is the type the write DECLARED, not the draft it happened to carry:+ // a save that only changes the address still declares one, and a receipt+ // that cannot see it land has still not seen the write land.+ if (expected?.credential && backend === 'claude') {+ const stored = fresh.native && 'credential_type' in fresh.native ? fresh.native.credential_type : null;+ if (stored !== expected.credential) messages.push(t('onboarding.connection.unconfirmed'));+ }}setError([...new Set(messages)].join(' '));setApplyPending(messages.length > 0);@@ -136,19 +267,44 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oautreturn () => { observation.current += 1; };}, [connectionRevision, observe]);- const confirm = async (expectedMethod: Method = method, receiptError = '') => {- pendingConfirmation.current = expectedMethod;- if (!await observe({ expectedMethod, receiptError })) return false;+ // Release what this receipt paid for, and only that. One settlement decides it,+ // and the drafts it hands back are the same ones the ownership is then read off+ // — so a credential the comparison refused to release cannot lose its ownership+ // to a second, more optimistic answer. Anything the submission did not carry, or+ // that has changed since it went out, is newer work than the receipt and stays.+ //+ // It is done inside the updater because `current` is the only authoritative+ // draft state, and everything it writes is derived from the state it returns+ // rather than added to what was there before — so an updater React chooses to+ // run twice reaches the same answer both times.+ const consume = (submission: Submission) => {+ setDrafts((current) => {+ const settled = settle(submission, { ...onScreen.current, drafts: current });+ // A credential counts as work only while something is on screen to lose, so+ // one emptied by this receipt — or by the person — stops counting either way.+ for (const type of CREDENTIALS) if (!unsaved(settled.drafts[type])) touched.current.delete(type);+ if (settled.baseUrl) touched.current.delete('base_url');+ if (settled.method) touched.current.delete('method');+ if (settled.credentialType) touched.current.delete('credential_type');+ return settled.drafts;+ });+ };+ const confirm = async (submission: Submission, receiptError = '') => {+ pendingConfirmation.current = submission;+ if (!await observe({ expected: submission, receiptError })) return false;pendingConfirmation.current = null;- setKey(''); setEditing(false); draftTouched.current = false;+ consume(submission);await onConnectedRef.current?.();return true;};+ // Signing in settles the account, not the key someone was part-way through+ // typing, and not an address they were part-way through changing either.+ const OAUTH: Submission = { method: 'oauth', baseUrl: null, credential: null, sent: null };const confirmOAuth = async () => {- if (!await confirm('oauth')) throw new Error(t('onboarding.connection.applyPending'));+ if (!await confirm(OAUTH)) throw new Error(t('onboarding.connection.applyPending'));};const observeOAuthFailure = async (receiptError: string) => {- pendingConfirmation.current = 'oauth';+ pendingConfirmation.current = OAUTH;await observe({ receiptError });};const oauth = useBackendOAuth({ backend, opencodeProviderId: provider?.id, onSuccess: confirmOAuth,@@ -166,7 +322,13 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oautconst busy = saving || active;useEffect(() => { onBusyChange?.(busy); }, [busy, onBusyChange]);useEffect(() => { onHeading?.({ method, active, credential }); }, [method, active, credential, onHeading]);- const hasKey = authReadable && (backend === 'opencode' ? Boolean(currentProvider?.api_key_masked) : Boolean(native?.has_api_key));+ // What is stored is one credential of one type. A mask only answers for the+ // type it was saved under, so selecting Auth Token while an API key is stored+ // shows an empty field to fill rather than a mask that means something else —+ // and `canSave` then requires a real token instead of accepting "keep".+ const storedCredential: Credential = native && 'credential_type' in native ? native.credential_type || 'api_key' : 'api_key';+ const hasKey = authReadable && (backend === 'opencode' ? Boolean(currentProvider?.api_key_masked)+ : Boolean(native?.has_api_key) && (backend !== 'claude' || storedCredential === credential));const mask = native?.api_key_masked || currentProvider?.api_key_masked || '••••••••';const uncertain = native && 'auth_mode_uncertain' in native && native.auth_mode_uncertain;const signedIn = authReadable && (native?.active_auth_mode === 'oauth' || currentProvider?.active_auth_type === 'oauth');@@ -179,8 +341,13 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oautconst save = async () => {if (!canSave || lifetime.current.busy) return;lifetime.current.busy = true; observation.current += 1; writeState.current?.(true); setSaving(true); setError(''); setConnected(false); setSavedDisabled(false);+ // What this write carries, decided here rather than when the receipt lands: by+ // then the visible type may be the other one, and the draft or the address may+ // be newer work than the one that went out. `sent` follows the payload exactly+ // — an omitted key is no credential work, not empty credential work.+ const payload = { auth_mode: 'api_key' as const, api_key: key.trim() || undefined, base_url: baseUrl.trim() || null };+ const submitted: Submission = { method: 'api_key', baseUrl, credential, sent: payload.api_key ? drafts[credential] : null };try {- const payload = { auth_mode: 'api_key' as const, api_key: key.trim() || undefined, base_url: baseUrl.trim() || null };const result = backend === 'claude' ? await api.saveClaudeAuth({ ...payload, credential_type: credential }): backend === 'codex' ? await api.saveCodexAuth(payload): await api.setOpencodeProviderAuth(provider!.id, payload.api_key, payload.base_url);@@ -188,10 +355,10 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oautif (!result.ok) throw new Error(result.message || t('onboarding.connection.saveFailed'));if ('notices' in result) surfaceBackendNotices(result.notices, showToast, t);if ('partial' in result && result.partial) showToast(result.detail || result.warning || t('onboarding.connection.partial'), 'warning');- await confirm('api_key', result.restart?.ok === false ? result.restart.message || t('onboarding.connection.applyFailed') : '');+ await confirm(submitted, result.restart?.ok === false ? result.restart.message || t('onboarding.connection.applyFailed') : '');} catch (err) {if (lifetime.current.mounted) {- pendingConfirmation.current = 'api_key';+ pendingConfirmation.current = submitted;await observe({ receiptError: errorMessage(err) || t('onboarding.connection.saveFailed') });}}@@ -234,7 +401,7 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut// footer still while the body changes underneath them.return <div className="backend-connection-form">{!(compact && active && backend !== 'codex') && (backend !== 'opencode' || (!compact && provider?.oauth_available)) && <MethodRadio- value={method} onChange={(value) => { if (!busy && !loading) { pendingConfirmation.current = null; draftTouched.current = true; setMethod(value); setError(''); setConnected(false); } }} disabled={busy || loading}+ value={method} onChange={(value) => { if (!busy && !loading) { pendingConfirmation.current = null; touched.current.add('method'); setMethod(value); setError(''); setConnected(false); } }} disabled={busy || loading}ariaLabel={t('onboarding.connection.method')}options={[{ id: 'oauth', label: backend === 'claude' ? t('onboarding.connection.claudeLogin') : backend === 'codex' ? t('onboarding.connection.codexSignIn') : t('onboarding.connection.subscription') },{ id: 'api_key', label: backend === 'claude' ? t('onboarding.connection.claudeCredentials') : backend === 'codex' ? t('onboarding.connection.openaiKey') : apiKeyLabel }]} />}@@ -274,17 +441,17 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut</div>}</>)}{method === 'api_key' && <>- {backend === 'claude' && <div className="connection-field"><Label>{credentialLabel}</Label><MethodRadio value={credential} onChange={(value) => { draftTouched.current = true; setCredential(value); }} disabled={busy} ariaLabel={credentialLabel}+ {backend === 'claude' && <div className="connection-field"><Label>{credentialLabel}</Label><MethodRadio value={credential} onChange={(value) => { touched.current.add('credential_type'); setCredential(value); setReveal(false); }} disabled={busy} ariaLabel={credentialLabel}options={[{ id: 'api_key', label: apiKeyLabel }, { id: 'auth_token', label: tokenLabel }]} /></div>}<div className="connection-field"><Label htmlFor={`${prefix}-connection-key`}>{secretLabel}</Label>- {hasKey && !editing ? <div className="connection-secret"><KeyRound size={15} /><code>{mask}</code><Button variant="ghost" size="xs" disabled={busy} onClick={() => { draftTouched.current = true; setEditing(true); setKey(''); }}><Pencil size={14} />{t('settings.backends.replaceApiKey')}</Button></div>- : <div className="connection-secret"><KeyRound size={15} /><Input id={`${prefix}-connection-key`} type={reveal ? 'text' : 'password'} value={key} onChange={(event) => { draftTouched.current = true; setKey(event.target.value); }} disabled={busy} autoComplete="off" spellCheck={false} placeholder={credential === 'auth_token' ? t('settings.backends.claudeAuthTokenPlaceholder') : backend === 'claude' ? 'sk-ant-…' : 'sk-…'} />+ {hasKey && !editing ? <div className="connection-secret"><KeyRound size={15} /><code>{mask}</code><Button variant="ghost" size="xs" disabled={busy} onClick={() => patchDraft({ editing: true, value: '' })}><Pencil size={14} />{t('settings.backends.replaceApiKey')}</Button></div>+ : <div className="connection-secret"><KeyRound size={15} /><Input id={`${prefix}-connection-key`} type={reveal ? 'text' : 'password'} value={key} onChange={(event) => patchDraft({ value: event.target.value })} disabled={busy} autoComplete="off" spellCheck={false} placeholder={credential === 'auth_token' ? t('settings.backends.claudeAuthTokenPlaceholder') : backend === 'claude' ? 'sk-ant-…' : 'sk-…'} /><Button variant="ghost" size="icon" aria-label={t(reveal ? 'onboarding.connection.hideKey' : 'onboarding.connection.showKey')} onClick={() => setReveal(!reveal)}>{reveal ? <EyeOff size={15} /> : <Eye size={15} />}</Button></div>}<p>{backend === 'opencode' ? t('onboarding.connection.providerCredentialHint', { name: provider?.name }) : t(backend === 'claude' && credential === 'auth_token' ? 'onboarding.connection.tokenHint' : 'onboarding.connection.keyHint')}</p>- {editing && hasKey && <Button variant="link" size="xs" onClick={() => { setEditing(false); setKey(''); }}>{t('common.cancel')}</Button>}+ {editing && hasKey && <Button variant="link" size="xs" onClick={() => patchDraft({ editing: false, value: '' })}>{t('common.cancel')}</Button>}</div><div className="connection-field"><Label htmlFor={`${prefix}-connection-url`}>{t('onboarding.connection.baseUrl')}</Label>- <Input id={`${prefix}-connection-url`} type="url" value={baseUrl} onChange={(event) => { draftTouched.current = true; setBaseUrl(event.target.value); }} disabled={busy} autoComplete="off" placeholder={backend === 'claude' ? 'https://api.anthropic.com' : backend === 'codex' ? 'https://api.openai.com/v1' : t('onboarding.connection.providerDefault')} />+ <Input id={`${prefix}-connection-url`} type="url" value={baseUrl} onChange={(event) => { touched.current.add('base_url'); setBaseUrl(event.target.value); }} disabled={busy} autoComplete="off" placeholder={backend === 'claude' ? 'https://api.anthropic.com' : backend === 'codex' ? 'https://api.openai.com/v1' : t('onboarding.connection.providerDefault')} /><p>{t(backend === 'claude' ? 'onboarding.connection.claudeUrlHint' : 'onboarding.connection.urlHint')}</p>{!urlValid && <p className="connection-error">{t('onboarding.connection.invalidUrl')}</p>}</div>diff --git a/ui/src/components/settings/providers/connection.css b/ui/src/components/settings/providers/connection.cssindex 1f1c4bb4d..d3ee2979b 100644--- a/ui/src/components/settings/providers/connection.css+++ b/ui/src/components/settings/providers/connection.css@@ -25,18 +25,109 @@--connection-desc: 40px;--connection-controls: 40px;--connection-footer: 56px;- width: min(568px, calc(100vw - 32px)); max-width: 568px;- height: min(var(--connection-h), calc(100dvh - 32px));+ /* The room: the one rectangle this frame is allowed to live in. It is stated+ once, as four edges, because every term below is a different reading of the+ same thing and correcting one axis without the other is what keeps going+ wrong.++ `100dvh` / `100vw` are the LAYOUT viewport: on iOS it does not shrink when+ the soft keyboard opens, so a frame sized to it would put its own footer+ under the keyboard. `--app-vv*` are the VISUAL viewport, mirrored by+ `useViewportHeightVar` — `w`/`h` for how much of the window a person can+ see and `l`/`t` for where that band starts, since iOS also pans it over the+ layout viewport while `position: fixed` stays measured against the layout+ one. Each falls back to its layout-viewport equivalent, so this reads the+ usable rectangle on a phone and the window everywhere else.++ The insets are the notch and the home indicator, named rather than inlined+ so the whole rectangle is one vocabulary — and so a test can drive an+ asymmetric safe area, which `env()` alone gives no way to do. 32px is the+ design's margin, which the frame owes on every side it can be pushed+ against; the room is what exists, `fit` is what the frame may occupy. */+ --connection-margin: 32px;+ --connection-inset-t: env(safe-area-inset-top, 0px);+ --connection-inset-r: env(safe-area-inset-right, 0px);+ --connection-inset-b: env(safe-area-inset-bottom, 0px);+ --connection-inset-l: env(safe-area-inset-left, 0px);+ --connection-room-w: calc(var(--app-vvw, 100vw) - var(--connection-inset-l) - var(--connection-inset-r));+ --connection-room-h: calc(var(--app-vvh, 100dvh) - var(--connection-inset-t) - var(--connection-inset-b));+ --connection-fit-w: calc(var(--connection-room-w) - var(--connection-margin));+ --connection-fit-h: calc(var(--connection-room-h) - var(--connection-margin));+ /* The middle of that room, which is not the middle of the window. A soft+ keyboard takes the bottom of the screen without moving the layout viewport,+ so a frame centred on the window keeps its lower half under the keyboard+ even after it has shrunk enough to fit above it. A notch does the same+ sideways: a room narrowed from one edge has its middle nearer the other.+ Off a phone every measured term is its default and both of these are+ exactly 50% again — the room is the whole window. */+ --connection-centre-x: calc(var(--app-vvl, 0px) + var(--connection-inset-l) + var(--connection-room-w) / 2);+ --connection-centre-y: calc(var(--app-vvt, 0px) + var(--connection-inset-t) + var(--connection-room-h) / 2);+ width: min(568px, var(--connection-fit-w)); max-width: 568px;+ height: min(var(--connection-h), var(--connection-fit-h));grid-template-columns: minmax(0, 1fr);grid-template-rows: var(--connection-head) var(--connection-desc) var(--connection-controls) minmax(0, 1fr) var(--connection-footer);- /* The frame never scrolls; its middle does. */- overflow: hidden;+ /* The frame does not scroll; its middle does. Every band below sizes the rows+ down as the room shrinks, and at each one the middle still absorbs what is+ left — so in every room the design describes, this axis has nothing to do+ and stays here only as the last resort for the rooms it does not. */+ overflow-x: hidden; overflow-y: auto;padding: var(--connection-pad); gap: var(--connection-gap); border-radius: 16px;border-color: var(--border-strong); background: var(--surface-2);box-shadow: 0 18px 48px var(--desktop-overlay-shadow, var(--connection-overlay-shadow));}+/* The shared dialog primitive caps every dialog it owns at `100dvh - 2rem`, and+ below its `md` edge at `90dvh` — its own defaults for dialogs that size to+ their content, and both of them layout-viewport units that a soft keyboard+ never moves. It also centres on the window for the same reason. This frame+ has its own bound and its own centre, so it states both here rather than+ inheriting them: the doubled class only exists to outweigh a utility class,+ because the primitive's file belongs to another surface. The primitive's own+ `-translate-x-1/2 -translate-y-1/2` still does the centring on both axes; only+ the point it is centred on changes. */+.connection-dialog.connection-dialog {+ max-height: var(--connection-fit-h); top: var(--connection-centre-y); bottom: auto;+ /* Stated here rather than beside the width because the phone band below also+ re-centres the frame, and a single class there would outrank a single class+ here on exactly the screens this room is measured for. */+ left: var(--connection-centre-x); right: auto;+}.connection-dialog[data-backend='codex'] { --connection-h: 580px; }.connection-dialog[data-backend='opencode'] { --connection-h: 640px; }+/* Below the floor — the room cannot hold the five rows and one whole control+ between them. There the middle is at or near nothing, and a scroll container+ with no height scrolls nothing, so the fields inside it are not merely small+ but impossible to reach. A phone held sideways is 390 tall before a keyboard+ takes any of it, so this is a room a person really does land in.+ `useRoomFloor` measures it and writes the answer here.++ The dialog then hands the scroll over instead of splitting it. Exactly one+ thing changes: the middle stops being clamped to what is left and stops being+ a scroll container, so it takes the height its content needs and the frame —+ the one box that was always allowed to scroll — becomes the single scroll+ owner. Every field, the provider choice, the instructions, Close and the+ footer action are then reachable in one column.++ The other four rows keep their heights, and the frame keeps the height and+ the centre the room gives it — deliberately not `auto`. A box that sizes to+ its content moves its own top edge by half of every content change, which is+ the defect the fixed frame exists to prevent; the fallback changes who+ scrolls, not whether the frame holds still. So the heading, the description+ and the method row do not move at all, and only the footer travels with the+ content it follows. With the mode decided by the room alone, switching method+ or raising an error can move neither the mode nor the frame — and while the+ middle still fits, this row behaves exactly as `1fr` did. */+.connection-dialog[data-room='tight'] {+ grid-template-rows: var(--connection-head) var(--connection-desc) var(--connection-controls) auto var(--connection-footer);+}+/* The floor and the scrolling are one decision: `min-height: 0` is what lets the+ middle shrink below its content, and it is also what holds the `auto` row at+ the leftover space — a grid item whose minimum is zero contributes nothing for+ the row to be sized from. Handing the scroll over means restoring the real+ minimum, so the row is sized by the content rather than by what was left. */+.connection-dialog[data-room='tight'] .connection-body {+ min-height: auto;+ overflow-y: visible;+}/* `display: contents` keeps the form one component while its three regions sitin the dialog's own rows. Settings renders the same form as an ordinarycolumn, so both rules stay scoped to the dialog. */@@ -117,9 +208,12 @@between the two. The description gets a third line here because the samesentence wraps further at phone width. */@media (max-width: 767px) {+ /* Neither edge of the centre is restored here: the frame is centred on its+ room above, on both axes, because that and its size answer the same+ question. Only the transform the phone layout drops is put back. */.connection-dialog {- left: 50%; right: auto; top: 50%; bottom: auto; transform: translate(-50%, -50%);- max-width: 568px; width: calc(100vw - 32px); border-radius: 16px;+ transform: translate(-50%, -50%);+ border-radius: 16px;--connection-pad: 20px; --connection-gap: 16px; --connection-desc: 60px;}.connection-dialog > div[aria-hidden='true']:first-child { display: none; }@@ -133,6 +227,16 @@.connection-dialog { --connection-pad: 16px; --connection-gap: 12px; --connection-head: 44px; --connection-desc: 40px; }.connection-heading h2 { font-size: 18px; line-height: 22px; }}+/* Shorter than a landscape phone — a soft keyboard on a small screen reaches+ here too. There is no longer room for both breathing space and the anchors,+ so the breathing space goes: tighter padding, tighter gaps, a smaller mark+ and heading. The method row and the footer keep their full height, because+ they are what has to stay usable, and the middle still gives way first. */+@media (max-height: 480px) {+ .connection-dialog { --connection-pad: 12px; --connection-gap: 8px; --connection-head: 40px; }+ .connection-heading h2 { font-size: 17px; line-height: 20px; }+ .connection-logo { width: 34px; height: 34px; border-radius: 9px; }+}.connection-auth-steps > div > a[data-slot="button"] { height: 38px; border-radius: 8px; padding: 0 14px; font-size: 13px; font-weight: 600; }.connection-dialog .connection-auth-steps > div > a:not(:has(+ button)) { height: 38px; border-radius: 8px; padding: 0 14px; font-size: 13px; font-weight: 600; }diff --git a/ui/src/components/settings/providers/providerIdentity.test.ts b/ui/src/components/settings/providers/providerIdentity.test.tsindex 8282b7110..98646fb13 100644--- a/ui/src/components/settings/providers/providerIdentity.test.ts+++ b/ui/src/components/settings/providers/providerIdentity.test.ts@@ -10,6 +10,7 @@ import {CATALOG_VENDOR_IDS,PROVIDER_VENDOR_ALIAS,SETUP_PRIMARY_VENDORS,+ providerBrandLabel,providerLabel,providerVendorId,setupPrimaryRank,@@ -74,6 +75,26 @@ describe('providerLabel', () => {});});+describe('providerBrandLabel', () => {+ it('names the brand, not the variant, when a row stands in a brand slot', () => {+ // The same row reads two ways on purpose: "Qwen" in the slot it fills,+ // "Alibaba (China)" under More where its job is to be told apart from the+ // other Qwen rows.+ expect(providerBrandLabel('alibaba-cn', 'Alibaba (China)')).toBe(apiKeyVendorPreset('qwen')?.label);+ expect(providerLabel('alibaba-cn', 'Alibaba (China)')).toBe('Alibaba (China)');+ });++ it('agrees with providerLabel when the server added nothing', () => {+ expect(providerBrandLabel('google')).toBe(providerLabel('google'));+ expect(providerBrandLabel('moonshot', 'moonshot')).toBe(providerLabel('moonshot', 'moonshot'));+ });++ it('leaves a provider with no brand slot exactly as it was', () => {+ expect(providerBrandLabel('my-internal-relay', '内部中转')).toBe('内部中转');+ expect(providerBrandLabel('my-internal-relay')).toBe('my-internal-relay');+ });+});+describe('the setup shortlist', () => {it('names only providers the shipped catalog can render', () => {for (const vendor of SETUP_PRIMARY_VENDORS) {diff --git a/ui/src/components/settings/providers/providerIdentity.ts b/ui/src/components/settings/providers/providerIdentity.tsindex f1152b226..da58cca2b 100644--- a/ui/src/components/settings/providers/providerIdentity.ts+++ b/ui/src/components/settings/providers/providerIdentity.ts@@ -55,6 +55,27 @@ export function providerLabel(providerId: string, serverName?: string | null): sreturn apiKeyVendorPreset(providerVendorId(id))?.label ?? name ?? id;}+/**+ * What to call a provider that is standing in a *named brand slot*.+ *+ * The setup shortlist offers eight brands in an approved order, so those rows+ * carry the brand's own name and mark: an OpenCode catalog row that calls Qwen+ * "Alibaba (China)" is the right label for a variant listed under More and the+ * wrong one for the Qwen slot. Where there is no slot, `providerLabel` stays+ * correct, because there the job is to tell two rows of the same brand apart+ * rather than to name the brand. A provider the catalog does not know has no+ * brand slot to fill, so it falls back to the same label it would show anywhere+ * else.+ *+ * Both of these say what a row may ASK to be called. What it is actually called+ * also depends on what every other row is called, so the picker settles that in+ * one place and every surface — the list, More, search and the chosen-provider+ * capsule — reads the answer rather than recomputing one.+ */+export function providerBrandLabel(providerId: string, serverName?: string | null): string {+ return apiKeyVendorPreset(providerVendorId(providerId))?.label ?? providerLabel(providerId, serverName);+}+/*** The API-key providers the setup picker offers before More.*diff --git a/ui/src/lib/useViewportHeightVar.ts b/ui/src/lib/useViewportHeightVar.tsindex 6dfb2fc06..f69fabe7e 100644--- a/ui/src/lib/useViewportHeightVar.ts+++ b/ui/src/lib/useViewportHeightVar.ts@@ -5,15 +5,23 @@ import { isSoftKeyboardOpen, isTouchCapableDevice } from './softKeyboard';// virtual keyboard opens — only the VISUAL viewport shrinks — so a bottom-pinned// chat composer ends up stranded with a large gap above the keyboard (dvh alone// doesn't fix it on iOS, and interactive-widget=resizes-content isn't supported-// there). Mirror window.visualViewport.height into the --app-vvh CSS var-// (rAF-throttled).+// there). Mirror window.visualViewport into four CSS vars (rAF-throttled): the+// part of the window a person can actually see, as a rectangle — --app-vvw /+// --app-vvh for its size and --app-vvl / --app-vvt for where it starts, since+// iOS also PANS the visual viewport to keep a focused field in sight and+// `position: fixed` is laid out against the layout viewport. A size alone says+// how much can be seen but not which part, so all four are written together.//// NB: the MOBILE shell deliberately does NOT consume this — sizing the shell to// it mid-focus fought iOS's own scroll-into-view and flung the input off the top// (the mobile shell is a static locked column instead, see AppShell/index.css).-// The ONLY consumer is the md+ chat (iPad / phone-landscape), which uses the-// desktop layout and so cannot use the mobile body-lock; sizing that chat to the-// visual viewport keeps its composer above the soft keyboard.+// Consumers are the md+ chat (iPad / phone-landscape), which uses the desktop+// layout and so cannot use the mobile body-lock — sizing that chat to the visual+// viewport keeps its composer above the soft keyboard — and the setup+// connection dialog, which is reached before that shell exists and so keeps the+// same vars current itself. Both may be mounted at once: they write identical+// values, and the cleanup below deliberately removes only this effect's+// listeners, never the properties, so one unmounting cannot strand the other.//// Gated so it tracks ONLY the soft keyboard: (1) touch devices — non-touch desktops// have no keyboard, so the var must stay at its 100dvh default; (2) skip a@@ -25,6 +33,8 @@ import { isSoftKeyboardOpen, isTouchCapableDevice } from './softKeyboard';// no keyboard. Refs:// https://www.bram.us/2021/09/13/prevent-items-from-being-hidden-underneath-the-virtual-keyboard-by-means-of-the-virtualkeyboard-api/// https://dev.to/franciscomoretti/fix-mobile-keyboard-overlap-with-visualviewport-3a4a+const VARS = ['--app-vvh', '--app-vvt', '--app-vvw', '--app-vvl'] as const;+export function useViewportHeightVar(): void {useEffect(() => {// Non-touch desktops have no soft keyboard, so this var must never move there;@@ -40,15 +50,28 @@ export function useViewportHeightVar(): void {raf = 0;// Touch devices can pinch-zoom too (iPad, touch laptops), which also shrinks// vv.height with scale > 1. A keyboard-less zoom must NOT drive the inset (it- // would lift the composer off the bottom), so drop the override and fall back- // to 100dvh. But zoom and the keyboard can be up together (zoom, then focus the+ // would lift the composer off the bottom), so drop the overrides and fall back+ // to the layout-viewport defaults. But zoom and the keyboard can be up together+ // (zoom, then focus the// composer) — then we still need the inset, so only bail when the keyboard is// closed; isSoftKeyboardOpen() is scale-aware, so it still fires while zoomed.+ const root = document.documentElement.style;if (vv.scale > 1 && !isSoftKeyboardOpen()) {- document.documentElement.style.removeProperty('--app-vvh');+ for (const name of VARS) root.removeProperty(name);return;}- document.documentElement.style.setProperty('--app-vvh', `${Math.round(vv.height)}px`);+ // Where the visible band starts, beside how big it is. iOS pans the visual+ // viewport over the layout viewport to keep a focused field in sight, and+ // `position: fixed` is laid out against the LAYOUT viewport — so a size+ // alone describes how much a person can see but not which part, and+ // anything centred on it drifts by the pan. All four are written and+ // cleared together, so no two of them can be read from different moments.+ // (`scroll` is already listened to: a pan moves the offsets without+ // changing the size.)+ root.setProperty('--app-vvh', `${Math.round(vv.height)}px`);+ root.setProperty('--app-vvt', `${Math.round(vv.offsetTop)}px`);+ root.setProperty('--app-vvw', `${Math.round(vv.width)}px`);+ root.setProperty('--app-vvl', `${Math.round(vv.offsetLeft)}px`);};const schedule = () => {if (raf) return;