fix(web): remove the empty pairing request badge

This commit is contained in:
EricMoin committed 2026-11-19 21:25:59 +08:00
1 parent 39a9b14a47
commit dc3a25f0ef
8 files changed
+27 -36

No files matched your search

+2 -2
View File
@@ -199,7 +199,7 @@ it('lets a paired mobile browser approve another device and keeps denied or canc
.getByRole('button', { name: '远程连接', exact: true }).click()
const mobileSection = applicant.getByRole('region', { name: '远程连接', exact: true })
const mobileApprovals = mobileSection.getByRole('region', { name: '配对申请', exact: true })
await mobileApprovals.getByText('暂无待审批的申请', { exact: true }).waitFor()
await mobileApprovals.waitFor()
expect(await mobileSection.getByRole('img', { name: '一次性登录二维码', exact: true }).count()).toBe(0)
const third = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
@@ -352,7 +352,7 @@ it('keeps one Remote connection panel, its QR invitation, and login link while a
const loginLink = section.getByRole('region', { name: '链接登录', exact: true }).locator('code')
await expect.poll(() => loginLink.innerText()).toBe(fixture.authenticatedUrl)
const approvals = section.getByRole('region', { name: '配对申请', exact: true })
await approvals.getByText('暂无待审批的申请', { exact: true }).waitFor()
await approvals.waitFor()
const created = owner.waitForResponse(response => new URL(response.url()).pathname === '/api/remoteConnection/create')
await section.getByRole('button', { name: '生成二维码', exact: true }).click()
const invitation = await (await created).json() as { result: { ok: boolean; value: { url: string } } }
@@ -1,10 +1,8 @@
- region "配对申请":
- heading "配对申请" [level=3]
- status: 暂无待审批的申请
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- alert: 已批准申请
- region "配对申请":
- heading "配对申请" [level=3]
- status: 暂无待审批的申请
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- alert: 已拒绝申请
+7
View File
@@ -130,6 +130,12 @@ async function createCode(page: Page, section: Locator): Promise<string> {
return url
}
async function waitForPairingList(pairing: Locator): Promise<void> {
await pairing.waitFor()
await pairing.getByRole('status', { name: '正在加载配对申请', exact: true }).waitFor({ state: 'hidden' })
expect(await pairing.getByRole('alert').count()).toBe(0)
}
async function snapshot(page: Page, fixture: RemoteConnectionFixture, name: string, addressUrl = fixture.authenticatedUrl): Promise<void> {
await expect.poll(() => page.getByRole('region', { name: '访问地址', exact: true }).locator('code').textContent()).toBe(addressUrl)
const section = page.getByRole('region', { name: '远程连接', exact: true })
@@ -1284,6 +1290,7 @@ describe('web e2e: one-use QR browser login', () => {
expect(await svg.innerHTML()).toBe(initialSvg)
const loginUrl = await section.getByRole('region', { name: '访问地址', exact: true }).locator('code').textContent()
expect(loginUrl).not.toBeNull()
await waitForPairingList(section.getByRole('region', { name: '配对申请', exact: true }))
const extendedAria = await captureStableAria(page, '[data-slot="settings.section"]', scaffold.workspaceCwd, {
replacements: [[loginUrl!, '{{access-address}}?token={{login-token}}'], [invitationId, '{{invitation-id}}']],
})
@@ -3,11 +3,6 @@
line-height: 20px;
}
.status {
display: flex;
min-width: 0;
}
.sourceIp,
.error {
margin: 0;
@@ -1,6 +1,6 @@
/** Approval controls and persistent outcome notices, independent of Cordis contexts. */
import { useId, useState } from 'react'
import { Button, IconWarningOutlineMedium, StateDot, Tag, Toast } from '@deepseek-ai/dsh-client-ui-primitives'
import { Button, IconWarningOutlineMedium, StateDot, Toast } from '@deepseek-ai/dsh-client-ui-primitives'
import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'
import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type {} from '@deepseek-ai/dsh-client-resources/client'
@@ -26,19 +26,17 @@ type Face = InjectFace<PairingInjected> & PropsLocale<'remoteConnection'>
/**
* Render pending request codes and connection source IP addresses within Remote connection settings.
* @param props - standard resource hook, owner actions, mutation state and localized copy.
* @returns the approval card with an empty status or pending requests and their permission warning.
* @returns the approval card with pairing instructions and any pending requests.
*/
export function PairingRequests({ useResource, useApproval, decide, t }: Pick<RemoteConnectionContentProps, 'useResource'> & Face) {
const title = useId()
const [retry, setRetry] = useState(0)
const requests = useResource<'device-pairing'>(`dsh-resource://device-pairing/requests?retry=${String(retry)}`)
const busy = useApproval(value => value.busy)
const empty = requests.status === 'live' && requests.value?.requests.length === 0
const hasRequests = requests.value !== undefined && requests.value.requests.length > 0
return <section className={`${card.card} ${css.section}`} aria-labelledby={title}>
<header className={card.cardHeader}>
<h3 className={card.methodTitle} id={title}>{t('pairing.title')}</h3>
{empty && <span className={css.status} role="status"><Tag tone="neutral">{t('pairing.empty')}</Tag></span>}
</header>
<p className={card.description}>{t('pairing.description')}</p>
{hasRequests && <div className={card.caution} role="note">
@@ -3,7 +3,6 @@ export const en = {
'pairing.title': 'Pairing requests',
'pairing.description': 'Open this app on the other device and request pairing. Compare the codes before approving.',
'pairing.permission': 'Approval gives that browser full access to this app, including approving other devices.',
'pairing.empty': 'No requests awaiting approval.',
'pairing.code': 'Pairing code',
'pairing.sourceIp': 'Source IP',
'pairing.sourceIpUnknown': 'Unknown',
@@ -27,7 +26,7 @@ export const zh: Record<PairingLocaleKey, string> = {
'pairing.title': '配对申请',
'pairing.description': '在另一台设备上打开此应用并申请配对,核对两端配对码后再批准',
'pairing.permission': '批准后,该浏览器将获得此应用的完整访问权限,也可以批准其他设备',
'pairing.empty': '暂无待审批的申请', 'pairing.code': '配对码', 'pairing.approve': '批准', 'pairing.deny': '拒绝', 'pairing.retry': '重试', 'pairing.loading': '正在加载配对申请',
'pairing.code': '配对码', 'pairing.approve': '批准', 'pairing.deny': '拒绝', 'pairing.retry': '重试', 'pairing.loading': '正在加载配对申请',
'pairing.readFailed': '无法加载申请,请重试以刷新列表', 'pairing.approved': '已批准申请', 'pairing.denied': '已拒绝申请',
'pairing.unavailable': '此申请已不在待审批状态', 'pairing.failed': '无法确认审批结果,请刷新列表后再试',
}
@@ -37,7 +36,7 @@ export const ja: Record<PairingLocaleKey, string> = {
'pairing.sourceIp': '接続元 IP', 'pairing.sourceIpUnknown': '不明',
'pairing.title': 'ペアリング申請', 'pairing.description': '別のデバイスでこのアプリを開き、ペアリングを申請してください。承認する前に両方のコードを照合してください。',
'pairing.permission': '承認すると、そのブラウザーはこのアプリへのフルアクセス権を得て、他のデバイスも承認できます。',
'pairing.empty': '承認待ちの申請はありません。', 'pairing.code': 'ペアリングコード', 'pairing.approve': '承認', 'pairing.deny': '拒否', 'pairing.retry': '再試行', 'pairing.loading': 'ペアリング申請を読み込み中',
'pairing.code': 'ペアリングコード', 'pairing.approve': '承認', 'pairing.deny': '拒否', 'pairing.retry': '再試行', 'pairing.loading': 'ペアリング申請を読み込み中',
'pairing.readFailed': '申請を読み込めませんでした。再試行して一覧を更新してください。', 'pairing.approved': '申請を承認しました', 'pairing.denied': '申請を拒否しました',
'pairing.unavailable': 'この申請は承認待ちではありません', 'pairing.failed': '審査結果を確認できませんでした。一覧を更新してから再試行してください。',
}
@@ -47,7 +46,7 @@ export const es: Record<PairingLocaleKey, string> = {
'pairing.sourceIp': 'IP de origen', 'pairing.sourceIpUnknown': 'Desconocida',
'pairing.title': 'Solicitudes de vinculación', 'pairing.description': 'Abra esta aplicación en el otro dispositivo y solicite la vinculación. Compare los códigos antes de aprobar.',
'pairing.permission': 'La aprobación concede a ese navegador acceso completo a esta aplicación, incluida la capacidad de aprobar otros dispositivos.',
'pairing.empty': 'No hay solicitudes pendientes de aprobación.', 'pairing.code': 'Código de vinculación', 'pairing.approve': 'Aprobar', 'pairing.deny': 'Rechazar', 'pairing.retry': 'Reintentar', 'pairing.loading': 'Cargando solicitudes de vinculación',
'pairing.code': 'Código de vinculación', 'pairing.approve': 'Aprobar', 'pairing.deny': 'Rechazar', 'pairing.retry': 'Reintentar', 'pairing.loading': 'Cargando solicitudes de vinculación',
'pairing.readFailed': 'No se pudieron cargar las solicitudes. Reintente para actualizar la lista.', 'pairing.approved': 'Solicitud aprobada', 'pairing.denied': 'Solicitud rechazada',
'pairing.unavailable': 'Esta solicitud ya no está pendiente de aprobación', 'pairing.failed': 'No se pudo confirmar su decisión. Actualice la lista antes de reintentar.',
}
@@ -57,7 +56,7 @@ export const fr: Record<PairingLocaleKey, string> = {
'pairing.sourceIp': 'IP source', 'pairing.sourceIpUnknown': 'Inconnue',
'pairing.title': 'Demandes d’association', 'pairing.description': 'Ouvrez cette application sur l’autre appareil et demandez une association. Comparez les codes avant d’approuver.',
'pairing.permission': 'L’approbation donne à ce navigateur un accès complet à cette application, y compris la possibilité d’approuver d’autres appareils.',
'pairing.empty': 'Aucune demande en attente d’approbation.', 'pairing.code': 'Code d’association', 'pairing.approve': 'Approuver', 'pairing.deny': 'Refuser', 'pairing.retry': 'Réessayer', 'pairing.loading': 'Chargement des demandes d’association',
'pairing.code': 'Code d’association', 'pairing.approve': 'Approuver', 'pairing.deny': 'Refuser', 'pairing.retry': 'Réessayer', 'pairing.loading': 'Chargement des demandes d’association',
'pairing.readFailed': 'Impossible de charger les demandes. Réessayez pour actualiser la liste.', 'pairing.approved': 'Demande approuvée', 'pairing.denied': 'Demande refusée',
'pairing.unavailable': 'Cette demande n’est plus en attente d’approbation', 'pairing.failed': 'Impossible de confirmer votre décision. Actualisez la liste avant de réessayer.',
}
@@ -67,7 +66,7 @@ export const de: Record<PairingLocaleKey, string> = {
'pairing.sourceIp': 'Quell-IP', 'pairing.sourceIpUnknown': 'Unbekannt',
'pairing.title': 'Kopplungsanfragen', 'pairing.description': 'Öffnen Sie diese App auf dem anderen Gerät und fordern Sie eine Kopplung an. Vergleichen Sie die Codes vor der Genehmigung.',
'pairing.permission': 'Die Genehmigung gewährt diesem Browser vollständigen Zugriff auf diese App, einschließlich der Genehmigung weiterer Geräte.',
'pairing.empty': 'Keine Anfragen warten auf Genehmigung.', 'pairing.code': 'Kopplungscode', 'pairing.approve': 'Genehmigen', 'pairing.deny': 'Ablehnen', 'pairing.retry': 'Erneut versuchen', 'pairing.loading': 'Kopplungsanfragen werden geladen',
'pairing.code': 'Kopplungscode', 'pairing.approve': 'Genehmigen', 'pairing.deny': 'Ablehnen', 'pairing.retry': 'Erneut versuchen', 'pairing.loading': 'Kopplungsanfragen werden geladen',
'pairing.readFailed': 'Anfragen konnten nicht geladen werden. Versuchen Sie es erneut, um die Liste zu aktualisieren.', 'pairing.approved': 'Anfrage genehmigt', 'pairing.denied': 'Anfrage abgelehnt',
'pairing.unavailable': 'Diese Anfrage wartet nicht mehr auf Genehmigung', 'pairing.failed': 'Ihre Entscheidung konnte nicht bestätigt werden. Aktualisieren Sie die Liste, bevor Sie es erneut versuchen.',
}
@@ -77,7 +76,7 @@ export const ru: Record<PairingLocaleKey, string> = {
'pairing.sourceIp': 'IP-адрес источника', 'pairing.sourceIpUnknown': 'Неизвестен',
'pairing.title': 'Запросы на сопряжение', 'pairing.description': 'Откройте приложение на другом устройстве и запросите сопряжение. Перед одобрением сравните коды.',
'pairing.permission': 'Одобрение предоставляет этому браузеру полный доступ к приложению, включая возможность одобрять другие устройства.',
'pairing.empty': 'Нет запросов, ожидающих одобрения.', 'pairing.code': 'Код сопряжения', 'pairing.approve': 'Одобрить', 'pairing.deny': 'Отклонить', 'pairing.retry': 'Повторить', 'pairing.loading': 'Загрузка запросов на сопряжение',
'pairing.code': 'Код сопряжения', 'pairing.approve': 'Одобрить', 'pairing.deny': 'Отклонить', 'pairing.retry': 'Повторить', 'pairing.loading': 'Загрузка запросов на сопряжение',
'pairing.readFailed': 'Не удалось загрузить запросы. Повторите попытку, чтобы обновить список.', 'pairing.approved': 'Запрос одобрен', 'pairing.denied': 'Запрос отклонён',
'pairing.unavailable': 'Этот запрос больше не ожидает одобрения', 'pairing.failed': 'Не удалось подтвердить решение. Обновите список перед повторной попыткой.',
}
@@ -87,7 +86,7 @@ export const pt: Record<PairingLocaleKey, string> = {
'pairing.sourceIp': 'IP de origem', 'pairing.sourceIpUnknown': 'Desconhecido',
'pairing.title': 'Pedidos de emparelhamento', 'pairing.description': 'Abra esta aplicação no outro dispositivo e solicite o emparelhamento. Compare os códigos antes de aprovar.',
'pairing.permission': 'A aprovação dá a esse navegador acesso completo a esta aplicação, incluindo a possibilidade de aprovar outros dispositivos.',
'pairing.empty': 'Nenhum pedido aguarda aprovação.', 'pairing.code': 'Código de emparelhamento', 'pairing.approve': 'Aprovar', 'pairing.deny': 'Recusar', 'pairing.retry': 'Tentar novamente', 'pairing.loading': 'A carregar pedidos de emparelhamento',
'pairing.code': 'Código de emparelhamento', 'pairing.approve': 'Aprovar', 'pairing.deny': 'Recusar', 'pairing.retry': 'Tentar novamente', 'pairing.loading': 'A carregar pedidos de emparelhamento',
'pairing.readFailed': 'Não foi possível carregar os pedidos. Tente novamente para atualizar a lista.', 'pairing.approved': 'Pedido aprovado', 'pairing.denied': 'Pedido recusado',
'pairing.unavailable': 'Este pedido já não aguarda aprovação', 'pairing.failed': 'Não foi possível confirmar a decisão. Atualize a lista antes de tentar novamente.',
}
@@ -124,8 +124,7 @@ describe('remote connection settings registration', () => {
const { ctx, slots, fiber } = await bench(call)
render(createElement(Fragment, null, slots.renderSlot('root', {})))
await screen.findByRole('button', { name: '生成二维码' })
await screen.findByText('暂无待审批的申请')
expect(screen.getByRole('region', { name: '配对申请' })).toBeTruthy()
expect(await screen.findByRole('region', { name: '配对申请' })).toBeTruthy()
expect(screen.getByRole('region', { name: zh.qrTitle })).toBeTruthy()
expect(screen.getByRole('region', { name: zh.linkTitle })).toBeTruthy()
expect(slots.entries('settings.section')).toHaveLength(1)
@@ -137,8 +136,7 @@ describe('remote connection settings registration', () => {
expect(screen.getByRole('region', { name: 'Custom connection' })).toBeTruthy()
expect(slots.entries('settings.section')).toHaveLength(1)
await act(async () => { await replacement.dispose() })
await screen.findByText('暂无待审批的申请')
expect(screen.getByRole('region', { name: '配对申请' })).toBeTruthy()
expect(await screen.findByRole('region', { name: '配对申请' })).toBeTruthy()
expect(screen.getByRole('button', { name: '生成二维码' })).toBeTruthy()
expect(screen.getByRole('region', { name: zh.linkTitle })).toBeTruthy()
await act(async () => { await fiber.dispose() })
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
/** Owner decisions remain visible outside Settings; read failures preserve the last request list. */
import { afterEach, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import type { ComponentProps } from 'react'
import { allowAllAccess, bindSnapshotSelector, contextMenuHook, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import type { ResourceSnapshot } from '@deepseek-ai/dsh-client-resources/client'
@@ -48,7 +48,6 @@ it('shows the code and source IP, then announces the decision after Settings clo
expect(screen.getByRole('heading', { level: 3, name: en['pairing.title'] })).toBeTruthy()
expect(screen.getByRole('region', { name: en['pairing.title'] })).toBeTruthy()
expect(screen.getByRole('note').textContent).toBe(en['pairing.permission'])
expect(screen.queryByText(en['pairing.empty'])).toBeNull()
expect(screen.getAllByRole('button').map(button => button.textContent)).toEqual([en['pairing.approve'], en['pairing.deny']])
expect(screen.getByText('ABCD 2345')).toBeTruthy()
expect(screen.getByText(en['pairing.sourceIp'])).toBeTruthy()
@@ -113,7 +112,7 @@ it('retains loaded requests during a read failure and disables decisions until r
} finally { approval.dispose() }
})
it('shows a loading indicator, then a read-only empty status in the card header without a permission warning', async () => {
it('shows only pairing instructions once an empty list loads', () => {
const { props, approval, snapshot, useResource } = fixture()
useResource.mockReturnValue({ status: 'loading', value: undefined, failure: undefined })
try {
@@ -123,17 +122,14 @@ it('shows a loading indicator, then a read-only empty status in the card header
useResource.mockReturnValue({ ...snapshot, value: { requests: [], pollIntervalMs: 1000 } })
view.rerender(<PairingRequests {...props} t={makeTranslate(zh)} />)
expect(screen.getByRole('heading', { level: 3, name: zh['pairing.title'] })).toBeTruthy()
await waitFor(() => { expect(screen.getByText(zh['pairing.empty'])).toBeTruthy() })
const status = screen.getByRole('status')
expect(status.textContent).toBe(zh['pairing.empty'])
expect(screen.getByRole('heading', { level: 3, name: zh['pairing.title'] }).closest('header')?.contains(status)).toBe(true)
expect(status.querySelector('button')).toBeNull()
expect(screen.getByText(zh['pairing.description'])).toBeTruthy()
expect(screen.queryByRole('status')).toBeNull()
expect(screen.queryByRole('note')).toBeNull()
expect(screen.queryByRole('button', { name: zh['pairing.approve'] })).toBeNull()
expect(screen.queryByRole('button')).toBeNull()
useResource.mockReturnValue({ ...snapshot, status: 'failed', value: { requests: [], pollIntervalMs: 1000 } })
view.rerender(<PairingRequests {...props} t={makeTranslate(zh)} />)
expect(screen.getByRole('alert').textContent).toBe(zh['pairing.readFailed'])
expect(screen.queryByText(zh['pairing.empty'])).toBeNull()
expect(screen.queryByRole('status')).toBeNull()
} finally { approval.dispose() }
})
@@ -146,6 +142,6 @@ it('removes the permission warning when the last pending request leaves the list
view.rerender(<PairingRequests {...props} />)
expect(screen.queryByRole('note')).toBeNull()
expect(screen.queryByText('ABCD 2345')).toBeNull()
expect(screen.getByRole('status').textContent).toBe(en['pairing.empty'])
expect(screen.queryByRole('status')).toBeNull()
} finally { approval.dispose() }
})