fix(web): clarify pairing recovery feedback

Keep the primary action readable while pairing is busy, and distinguish
rate limits from connection failures during recovery. After the retry
budget is exhausted, tell users to wait before requesting again.

(cherry picked from commit 3c8ef5f6cb6f9e76d0a22614c608d59107bf6bf0)
This commit is contained in:
EricMoin committed 2026-11-19 21:25:58 +08:00
1 parent b331a96b18
commit 2a799fe712
7 files changed
+170 -6

No files matched your search

@@ -0,0 +1,6 @@
- region "Pair this device":
- heading "Pair this device" [level=2]
- paragraph: After requesting, open Settings → Remote connection on another signed-in device. Match the pairing code and approve to sign in here automatically.
- button "Requesting approval…" [disabled]
- button "Cancel request"
- status: Too many requests. Retrying shortly…
@@ -0,0 +1,6 @@
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
- button "正在申请配对…" [disabled]
- button "取消申请"
- status: 请求过于频繁,稍后自动重试…
+83
View File
@@ -327,6 +327,89 @@ describe('web e2e: one-use QR browser login', () => {
}
})
it.each([
{ language: 'zh', locale: ZH_BROWSER_LOCALE, limited: '请求过于频繁,稍后自动重试…', creating: '正在申请配对…', again: '重新申请' },
{ language: 'en', locale: 'en-US', limited: 'Too many requests. Retrying shortly…', creating: 'Requesting approval…', again: 'Request again' },
])('keeps the pairing action readable during rate-limit recovery in $language', async ({ language, locale, limited, creating, again }) => {
const context = await browser.newContext({ ignoreHTTPSErrors: true, locale, viewport: MOBILE, colorScheme: 'light', hasTouch: true })
const page = await context.newPage()
const releaseRetry = Promise.withResolvers<undefined>()
try {
const console = watchConsole(page)
await page.clock.install()
expect((await page.goto(secure.url))?.status()).toBe(401)
const request = page.locator('#auth-pair-request')
const panel = page.locator('#auth-pair-panel')
await request.click()
await page.locator('#auth-pair-code').waitFor()
const originalCode = await page.locator('#auth-pair-code').innerText()
await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now() + 1000)))
let limitedOnce = false
const retryStarted = Promise.withResolvers<undefined>()
await page.route('**/pairing/request', async (route) => {
if (!limitedOnce) {
limitedOnce = true
await route.fulfill({ status: 429, contentType: 'application/json', body: '{"status":"busy"}' })
return
}
retryStarted.resolve(undefined)
await releaseRetry.promise
await route.continue()
})
await request.click()
const status = panel.getByRole('status')
await status.getByText(limited, { exact: true }).waitFor()
await page.clock.fastForward(2000)
await retryStarted.promise
expect(await request.isDisabled()).toBe(true)
expect(await request.textContent()).toBe(creating)
expect(await status.textContent()).toBe(limited)
await compareOrRefreshGolden(join(EXPECTED, `pairing-rate-limited.${language}.expected.md`),
await captureStableAria(page, 'dsh-device-pairing', secure.root), MODE)
const screenshots = process.env['DSH_REMOTE_CONNECTION_SCREENSHOTS']
const screenshotDirectory = screenshots === undefined ? undefined : join(screenshots, 'pairing-rate-limited')
if (screenshotDirectory !== undefined) await mkdir(screenshotDirectory, { recursive: true })
for (const colorScheme of ['light', 'dark'] as const) {
await page.emulateMedia({ colorScheme })
const contrast = await request.evaluate((element) => {
const style = getComputedStyle(element)
const canvas = document.createElement('canvas')
canvas.width = canvas.height = 1
const drawing = canvas.getContext('2d')!
drawing.fillStyle = style.backgroundColor
drawing.fillRect(0, 0, 1, 1)
const luminance = (pixel: Uint8ClampedArray) => {
const linear = Array.from(pixel.slice(0, 3), (value) => {
const channel = value / 255
return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4
})
return linear[0]! * 0.2126 + linear[1]! * 0.7152 + linear[2]! * 0.0722
}
const background = luminance(drawing.getImageData(0, 0, 1, 1).data)
drawing.fillStyle = style.color
drawing.fillRect(0, 0, 1, 1)
const foreground = luminance(drawing.getImageData(0, 0, 1, 1).data)
return (Math.max(foreground, background) + 0.05) / (Math.min(foreground, background) + 0.05)
})
expect(contrast, colorScheme).toBeGreaterThanOrEqual(3)
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(MOBILE.width)
if (screenshotDirectory !== undefined) await page.screenshot({ path: join(screenshotDirectory, `${language}-${colorScheme}.png`) })
}
releaseRetry.resolve(undefined)
await page.clock.resume()
await page.locator('#auth-pair-panel[data-state="waiting"]').waitFor()
expect(await request.isEnabled()).toBe(true)
expect(await request.textContent()).toBe(again)
expect(await page.locator('#auth-pair-code').innerText()).not.toBe(originalCode)
expect(console.pageErrors).toEqual([])
expect(console.warnings).toEqual([])
} finally {
releaseRetry.resolve(undefined)
await page.unrouteAll({ behavior: 'wait' })
await context.close()
}
})
it.each([
{
name: 'unreachable', hostname: '127.0.0.1', options: {},
@@ -9,6 +9,8 @@ const en = {
pairReplacing: 'Cancelling the previous request before requesting again…',
pairChecking: 'Checking sign-in status…',
pairRecovering: 'Reconnecting automatically…',
pairRateLimited: 'Too many requests. Retrying shortly…',
pairRateLimitError: 'Too many requests. Wait a moment, then request again.',
pairCheckError: 'Could not confirm sign-in. Check your connection, then request again.',
pairCode: 'Pairing code',
pairRemaining: 'Expires in {time}',
@@ -32,6 +34,8 @@ const zh: Record<PairingLocaleKey, string> = {
pairReplacing: '正在取消原申请,随后重新申请…',
pairChecking: '正在确认登录状态…',
pairRecovering: '正在自动重新连接…',
pairRateLimited: '请求过于频繁,稍后自动重试…',
pairRateLimitError: '请求过于频繁,请稍后重新申请',
pairCheckError: '无法确认登录状态,请检查网络后重新申请',
pairCode: '配对码',
pairRemaining: '剩余时间:{time}',
@@ -162,13 +162,13 @@ export function mountPairing(
return exchange(operation, held, signal).then((reply) => {
if (signal.aborted) return undefined
if (reply !== undefined && reply.status !== 429 && reply.status < 500) return reply
if (failures === recovery.maxRetries) return undefined
show(state, t.pairRecovering)
if (failures === recovery.maxRetries) return reply
show(state, reply?.status === 429 ? t.pairRateLimited : t.pairRecovering)
return pause(Math.min(recovery.retryMaxDelayMs, recovery.pollIntervalMs * 2 ** failures), signal)
.then(() => signal.aborted ? undefined : read(operation, held, state, signal, failures + 1))
})
},
fail(this: void, text: string): void { stop(); show('error', text) },
fail(this: void, text: string, reply?: Reply): void { stop(); show('error', reply?.status === 429 ? t.pairRateLimitError : text) },
navigate(this: void): void {
stop()
credential = undefined
@@ -197,7 +197,7 @@ export function mountPairing(
const admission = expiring ? read('check', held, state, signal).then((reply) => {
if (!current(version)) return
if (reply?.status === 200) { navigate(); return }
if (reply?.status !== 401) fail(t.pairCheckError)
if (reply?.status !== 401) fail(t.pairCheckError, reply)
// A 401 alone cannot retire a Host request that outlives the browser's deadline.
}) : Promise.resolve()
return admission.then(() => {
@@ -206,7 +206,7 @@ export function mountPairing(
const creation = ticket === undefined ? read('request', held, state, signal).then((reply) => {
if (!current(version)) return undefined
const received = reply?.status === 200 ? ticketOf(reply.value, held) : undefined
if (received === undefined) { fail(t.pairCreateError); return undefined }
if (received === undefined) { fail(t.pairCreateError, reply); return undefined }
ticket = received
deadline = Math.min(deadline, performance.now() + received.expiresInMs)
clearTimeout(countdown)
@@ -241,7 +241,7 @@ export function mountPairing(
if (next === 'status' && reply?.status === 200 && status === 'pending') {
show('waiting')
timer = setTimeout(() => { void execute('status', held) }, received.pollIntervalMs)
} else fail(t.pairError)
} else fail(t.pairError, reply)
})
})
})
@@ -107,6 +107,9 @@ dsh-device-pairing {
.dsh-device-pairing-button:disabled {
cursor: default;
}
.dsh-device-pairing-button:disabled:not(.dsh-device-pairing-primary) {
color: var(--dsw-alias-label-tertiary, color-mix(in srgb, currentColor 48%, transparent));
}
@@ -108,6 +108,68 @@ it('retries a lost creation response with the same credentials without duplicati
expect(state()).toBe('waiting')
})
it.each(['zh', 'en'] as const)('shows rate limiting during creation and status recovery with the same credentials in %s', async (language) => {
const f = fixture(language)
const locale = pairingLocales[language]
f.request.mockResolvedValueOnce(new Response('{"status":"busy"}', { status: 429 }))
await create()
const held = payload(f.request.mock.calls[0]?.[1])
expect(state()).toBe('creating')
expect(document.querySelector('[role="status"]')?.textContent).toBe(locale.pairRateLimited)
expect(document.querySelector('[role="alert"]')).toBeNull()
expect(document.body.innerHTML).not.toContain(held.secret)
expect(button('request').disabled).toBe(true)
await vi.advanceTimersByTimeAsync(1000)
expect(payload(f.request.mock.calls[1]?.[1])).toEqual(held)
expect(f.pool.list()).toHaveLength(1)
expect(state()).toBe('waiting')
expect(document.querySelector('[role="status"]')?.textContent).toBe(locale.pairWaiting)
f.request.mockResolvedValueOnce(new Response('{"status":"slow-down"}', { status: 429 }))
await vi.advanceTimersByTimeAsync(1000)
expect(document.querySelector('[role="status"]')?.textContent).toBe(locale.pairRateLimited)
expect(document.querySelector('[role="alert"]')).toBeNull()
await vi.advanceTimersByTimeAsync(1000)
expect(f.request.mock.calls.slice(2).map(([, init]) => payload(init))).toEqual([held, held])
expect(document.body.innerHTML).not.toContain(held.secret)
expect(state()).toBe('waiting')
expect(document.querySelector('[role="status"]')?.textContent).toBe(locale.pairWaiting)
f.approve()
await vi.advanceTimersByTimeAsync(1000)
expect(f.navigate).toHaveBeenCalledOnce()
})
it.each([
['zh', 'request', 2], ['en', 'status', 0],
] as const)('offers Request again when rate limits exhaust %s %s recovery with %s retries', async (language, operation, maxRetries) => {
const f = fixture(language, { maxRetries })
if (operation === 'status') await create()
const before = f.request.mock.calls.length
for (let attempt = 0; attempt <= maxRetries; attempt++) {
f.request.mockResolvedValueOnce(new Response('{"status":"busy"}', { status: 429 }))
}
if (operation === 'request') await create()
else await vi.advanceTimersByTimeAsync(1000)
await vi.advanceTimersByTimeAsync(3000)
const attempts = f.request.mock.calls.slice(before)
const held = payload(attempts[0]?.[1])
expect(attempts).toHaveLength(maxRetries + 1)
expect(attempts.map(([, init]) => payload(init))).toEqual(Array.from({ length: maxRetries + 1 }, () => held))
expect(state()).toBe('error')
expect(document.querySelector('[role="alert"]')?.textContent).toBe(pairingLocales[language].pairRateLimitError)
expect(document.body.innerHTML).not.toContain(held.secret)
expect(button('request').disabled).toBe(false)
expect(vi.getTimerCount()).toBe(0)
await create()
await vi.advanceTimersByTimeAsync(1000)
const cancellation = f.request.mock.calls.find(([input]) => url(input).endsWith('/cancel'))
expect(payload(cancellation?.[1])).toEqual(held)
expect(f.pool.decide(held.id, 'allow')).toBe('unavailable')
expect(f.ticket().id).not.toBe(held.id)
expect(f.pool.list().map(row => row.id)).toEqual([f.ticket().id])
expect(state()).toBe('waiting')
})
it.each(['zh', 'en'])('automatically backs off status failures and exposes only Request again after exhaustion in %s', async (language) => {
const f = fixture(language)
await create()