diff --git a/apps/web/tests/expected/remote-connection/unreachable-desktop.expected.md b/apps/web/tests/expected/remote-connection/unreachable-desktop.expected.md new file mode 100644 index 0000000000..18375c40a1 --- /dev/null +++ b/apps/web/tests/expected/remote-connection/unreachable-desktop.expected.md @@ -0,0 +1,7 @@ +- region "远程连接": + - heading "远程连接" [level=2] + - status: + - paragraph: 当前地址不能用于其他设备登录,请配置其他设备可访问的地址,例如能连通的局域网地址或已配置的公网、VPN 地址 + - region "访问地址": + - heading "访问地址" [level=3] + - code: {{access-address}} diff --git a/apps/web/tests/expected/remote-connection/unreachable-load-failed.expected.md b/apps/web/tests/expected/remote-connection/unreachable-load-failed.expected.md new file mode 100644 index 0000000000..bbe3d7c419 --- /dev/null +++ b/apps/web/tests/expected/remote-connection/unreachable-load-failed.expected.md @@ -0,0 +1,6 @@ +- region "远程连接": + - heading "远程连接" [level=2] + - region "访问地址": + - heading "访问地址" [level=3] + - alert: 无法加载远程连接设置,请重试 + - button "重试" diff --git a/apps/web/tests/expected/remote-connection/unreachable-mobile-dark.expected.md b/apps/web/tests/expected/remote-connection/unreachable-mobile-dark.expected.md new file mode 100644 index 0000000000..18375c40a1 --- /dev/null +++ b/apps/web/tests/expected/remote-connection/unreachable-mobile-dark.expected.md @@ -0,0 +1,7 @@ +- region "远程连接": + - heading "远程连接" [level=2] + - status: + - paragraph: 当前地址不能用于其他设备登录,请配置其他设备可访问的地址,例如能连通的局域网地址或已配置的公网、VPN 地址 + - region "访问地址": + - heading "访问地址" [level=3] + - code: {{access-address}} diff --git a/apps/web/tests/expected/remote-connection/untrusted-desktop.expected.md b/apps/web/tests/expected/remote-connection/untrusted-desktop.expected.md new file mode 100644 index 0000000000..13dfa30488 --- /dev/null +++ b/apps/web/tests/expected/remote-connection/untrusted-desktop.expected.md @@ -0,0 +1,7 @@ +- region "远程连接": + - heading "远程连接" [level=2] + - status: + - paragraph: 请先将此访问地址加入 Host 的可信主机配置,才能使用下方的登录方式 + - region "访问地址": + - heading "访问地址" [level=3] + - code: {{access-address}} diff --git a/apps/web/tests/expected/remote-connection/untrusted-mobile-dark.expected.md b/apps/web/tests/expected/remote-connection/untrusted-mobile-dark.expected.md new file mode 100644 index 0000000000..13dfa30488 --- /dev/null +++ b/apps/web/tests/expected/remote-connection/untrusted-mobile-dark.expected.md @@ -0,0 +1,7 @@ +- region "远程连接": + - heading "远程连接" [level=2] + - status: + - paragraph: 请先将此访问地址加入 Host 的可信主机配置,才能使用下方的登录方式 + - region "访问地址": + - heading "访问地址" [level=3] + - code: {{access-address}} diff --git a/apps/web/tests/remote-connection-untrusted.overlay.yml b/apps/web/tests/remote-connection-untrusted.overlay.yml new file mode 100644 index 0000000000..40c50865cb --- /dev/null +++ b/apps/web/tests/remote-connection-untrusted.overlay.yml @@ -0,0 +1,11 @@ +- id: web-runtime + disabled: true +- insert: + - id: untrusted-test-web-runtime + name: '@deepseek-ai/dsh-web-app' + inject: [webServer] + config: + openBrowser: false + printUrl: false + surfaceContext: false + publicUrl: !!js ctx.webServer.getOrigin().replace('127.0.0.1', 'untrusted-remote.test') diff --git a/apps/web/tests/remote-connection.e2e.ts b/apps/web/tests/remote-connection.e2e.ts index 4df1675da5..46e797354b 100644 --- a/apps/web/tests/remote-connection.e2e.ts +++ b/apps/web/tests/remote-connection.e2e.ts @@ -14,6 +14,7 @@ const MOBILE = { width: 390, height: 844 } const REPLACEMENT_FIXTURE = fileURLToPath(new URL('./fixtures/plugins/fixture-remote-connection', import.meta.url)) const EXTENSION_FIXTURE = fileURLToPath(new URL('./fixtures/plugins/fixture-remote-connection-extension', import.meta.url)) const REPLACEMENT_OVERLAY = fileURLToPath(new URL('./remote-connection-replacement.overlay.yml', import.meta.url)) +const UNTRUSTED_OVERLAY = fileURLToPath(new URL('./remote-connection-untrusted.overlay.yml', import.meta.url)) async function remoteSettings(page: Page): Promise { await openSettings(page, 'zh') @@ -145,6 +146,98 @@ describe('web e2e: one-use QR browser login', () => { } }) + it.each([ + { + name: 'unreachable', hostname: '127.0.0.1', options: {}, + warning: '当前地址不能用于其他设备登录,请配置其他设备可访问的地址,例如能连通的局域网地址或已配置的公网、VPN 地址', + }, + { + name: 'untrusted', hostname: 'untrusted-remote.test', options: { extraOverlayPath: UNTRUSTED_OVERLAY }, + warning: '请先将此访问地址加入 Host 的可信主机配置,才能使用下方的登录方式', + }, + ])('explains unavailable address prerequisites before sign-in methods for $name', async ({ name, hostname, options, warning }) => { + const scaffold = await launchWebScaffold(options) + onTestFinished(() => scaffold.close()) + // The shared QR browser's proxy setup rejects the scaffold's loopback URL. + const localBrowser = await chromium.launch() + onTestFinished(() => localBrowser.close()) + const plainUrl = scaffold.ctx.webApp.getAdvertisedUrl() + expect(new URL(plainUrl).hostname).toBe(hostname) + for (const [viewport, colorScheme, suffix] of [ + [{ width: 1200, height: 1000 }, 'light', 'desktop'], + [MOBILE, 'dark', 'mobile-dark'], + ] as const) { + const context = await localBrowser.newContext({ locale: ZH_BROWSER_LOCALE, viewport, colorScheme }) + try { + const page = await context.newPage() + const console = watchConsole(page) + await page.goto(scaffold.authenticatedUrl) + await openSettings(page, 'zh') + await page.getByRole('dialog', { name: '设置', exact: true }) + .getByRole('button', { name: '远程连接', exact: true }).click() + const section = page.getByRole('region', { name: '远程连接', exact: true }) + const address = section.getByRole('region', { name: '访问地址', exact: true }) + await expect.poll(() => address.locator('code').textContent()).toBe(plainUrl) + const notice = section.getByRole('status').filter({ hasText: warning }) + await notice.getByText(warning, { exact: true }).waitFor() + expect(await section.getByRole('region').count()).toBe(1) + expect(await section.getByRole('heading', { level: 3 }).allTextContents()).toEqual(['访问地址']) + expect(await address.getByText(warning, { exact: true }).count()).toBe(0) + expect(await section.getByRole('region', { name: '二维码登录', exact: true }).count()).toBe(0) + expect(await section.getByRole('img').count()).toBe(0) + expect(await address.getByRole('button').count()).toBe(0) + expect(await section.getByText('请勿公开分享登录链接', { exact: true }).count()).toBe(0) + expect(await section.getByText('请勿分享登录二维码', { exact: true }).count()).toBe(0) + expect(new URL((await address.locator('code').textContent())!).searchParams.has('token')).toBe(false) + const titleBox = await section.getByRole('heading', { level: 2 }).boundingBox() + const noticeBox = await notice.boundingBox() + const addressBox = await address.boundingBox() + expect(titleBox).not.toBeNull() + expect(noticeBox).not.toBeNull() + expect(addressBox).not.toBeNull() + expect(noticeBox!.y).toBeGreaterThan(titleBox!.y + titleBox!.height) + expect(addressBox!.y).toBeGreaterThan(noticeBox!.y + noticeBox!.height) + expect(noticeBox!.x).toBeCloseTo(addressBox!.x) + expect(noticeBox!.x).toBeGreaterThanOrEqual(0) + expect(noticeBox!.x + noticeBox!.width).toBeLessThanOrEqual(viewport.width) + await compareOrRefreshGolden(join(EXPECTED, `${name}-${suffix}.expected.md`), + await captureStableAria(page, 'section[aria-label="远程连接"]', scaffold.workspaceCwd, { + replacements: [[plainUrl, '{{access-address}}']], + }), MODE) + const screenshots = process.env['DSH_REMOTE_CONNECTION_SCREENSHOTS'] + if (screenshots !== undefined) { + await mkdir(screenshots, { recursive: true }) + await page.screenshot({ path: join(screenshots, `${name}-${suffix}.png`) }) + } + if (name === 'unreachable' && suffix === 'desktop') { + await page.route('**/api/remoteConnection/status', route => route.abort('failed')) + await page.reload() + await openSettings(page, 'zh') + await page.getByRole('dialog', { name: '设置', exact: true }) + .getByRole('button', { name: '远程连接', exact: true }).click() + const failure = address.getByRole('alert') + await failure.waitFor() + expect(await failure.textContent()).toBe('无法加载远程连接设置,请重试') + const retry = address.getByRole('button', { name: '重试', exact: true }) + expect(await retry.isEnabled()).toBe(true) + expect(await section.getByRole('region', { name: '二维码登录', exact: true }).count()).toBe(0) + await compareOrRefreshGolden(join(EXPECTED, 'unreachable-load-failed.expected.md'), + await captureStableAria(page, 'section[aria-label="远程连接"]', scaffold.workspaceCwd), MODE) + if (screenshots !== undefined) await page.screenshot({ path: join(screenshots, 'unreachable-load-failed.png') }) + await page.unroute('**/api/remoteConnection/status') + await retry.click() + await expect.poll(() => address.locator('code').textContent()).toBe(plainUrl) + await notice.getByText(warning, { exact: true }).waitFor() + expect(await address.getByRole('alert').count()).toBe(0) + } + expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(viewport.width) + expect(console.pageErrors).toEqual([]) + } finally { + await context.close() + } + } + }) + it('retries in the copy button, shows a fading tokenized link, and keeps credential warnings independent', async () => { const desktop = await browser.newContext({ ignoreHTTPSErrors: true, locale: ZH_BROWSER_LOCALE, viewport: { width: 1200, height: 1000 }, diff --git a/packages/client/remote-connection/README.i18n.yaml b/packages/client/remote-connection/README.i18n.yaml index 1ef170b60e..d5d3256d88 100644 --- a/packages/client/remote-connection/README.i18n.yaml +++ b/packages/client/remote-connection/README.i18n.yaml @@ -15,8 +15,8 @@ en: ee070d32177b96d9 zh: f946b0eba6746ffd /deepseek-ai-dsh-client-remote-connection/use-this-package: - en: d2802227f1461f13 - zh: 4f6823bf57d429ea + en: 92fbca02e66944fc + zh: 0beda81b3e086690 /deepseek-ai-dsh-client-remote-connection/authentication-and-failures: en: 6ddc2e3a6b363916 zh: 9fef62a3722d1899 diff --git a/packages/client/remote-connection/README.md b/packages/client/remote-connection/README.md index 4afad49b1d..b98e535d3e 100644 --- a/packages/client/remote-connection/README.md +++ b/packages/client/remote-connection/README.md @@ -27,6 +27,8 @@ The Web bundle mounts this plugin. Its Host half requires `connection`, `connect The advertised application URL supports HTTP and HTTPS, must name a non-loopback address reachable by the phone, and must pass Connection's trusted-host checks. Configure the listener, optional certificate or reverse proxy, `publicUrl`, and trusted hosts through the existing [Web application](../../bundle/web-app/README.md) configuration. This plugin never changes the listening interface or discovers a network address. A reverse proxy must preserve the external Host, remove its configured path prefix, and protect its upstream connection. A plain HTTP listener issuing a cookie for an HTTP public URL omits `Secure`; HTTPS listeners and HTTPS public URLs behind a TLS-terminating proxy retain `Secure`. An HTTPS proxy must enforce HTTPS for its public origin. The settings panel allows HTTP login and reminds the user that HTTP transmits login credentials without encryption. +The panel shows unmet address prerequisites in a shared notice above the cards. An unreachable or untrusted address displays only its clean URL in the address card, with no copy action or credential warning, and hides QR login. Deployment-read failures remain retryable in the address card while QR login is unavailable. Reconnecting checks the address prerequisites again. + `cookieMaxAgeDays` defaults to 30 and fixes each Remote cookie's absolute lifetime. `ticketLifetimeMs` defaults to 120000. `pollIntervalMs` defaults to 1000 and controls the settings panel's status checks while its code is displayed. Only one invitation is outstanding per plugin instance: generating another replaces the previous one, and cancelling an old invitation does not cancel its replacement. ## Authentication and failures diff --git a/packages/client/remote-connection/README.zh.md b/packages/client/remote-connection/README.zh.md index 0eaf65cade..aa2797bdbc 100644 --- a/packages/client/remote-connection/README.zh.md +++ b/packages/client/remote-connection/README.zh.md @@ -28,6 +28,8 @@ Web bundle 挂载此插件。Host 端依赖 `connection`、`connection.authentic 公布的应用 URL 支持 HTTP 和 HTTPS,必须指向手机可访问的非回环地址,并通过 Connection 的可信 Host 检查。通过现有 [Web 应用](../../bundle/web-app/README.zh.md) 配置设置监听器、可选证书或反向代理、`publicUrl` 和可信 Host。此插件不会更改监听接口或发现网络地址。反向代理必须保留外部 Host、移除配置的路径前缀,并保护上游连接。普通 HTTP 监听器为 HTTP 公布地址签发的 cookie 不带 `Secure`;HTTPS 监听器以及终止 TLS 的代理后的 HTTPS 公布地址仍使用 `Secure`。HTTPS 代理必须对外部源强制使用 HTTPS。设置面板允许 HTTP 登录,并提醒用户 HTTP 会明文传输登录凭据。 +面板在卡片上方以共用提示说明尚未满足的地址前提。地址不可达或不受信任时,访问地址卡片只显示不带凭据的 URL,不提供复制操作或凭据告警,并隐藏二维码登录。二维码登录不可用时,部署信息的读取错误和重试操作保留在访问地址卡片中。重连后会重新检查地址前提。 + `cookieMaxAgeDays` 默认为 30,固定每份 Remote cookie 的绝对有效期。`ticketLifetimeMs` 默认为 120000。`pollIntervalMs` 默认为 1000,控制设置面板显示二维码时的状态检查间隔。每个插件实例同一时间只有一个待使用邀请:生成新邀请会替换旧邀请,取消旧邀请不会取消替代它的新邀请。 diff --git a/packages/client/remote-connection/src/client/RemoteConnectionSection.tsx b/packages/client/remote-connection/src/client/RemoteConnectionSection.tsx index 3699df8205..e24b6a6a01 100644 --- a/packages/client/remote-connection/src/client/RemoteConnectionSection.tsx +++ b/packages/client/remote-connection/src/client/RemoteConnectionSection.tsx @@ -1,4 +1,4 @@ -/** Access address and QR login controls for browser sign-in. */ +/** Access address and QR login for browser sign-in. */ import { QRCodeSVG } from 'qrcode.react' import { Button, IconWarningOutlineMedium, StateDot } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' @@ -9,43 +9,53 @@ import css from './RemoteConnectionSection.module.css' export type RemoteConnectionSectionProps = RemoteConnectionContentProps & PropsLocale<'remoteConnection'> /** - * Present shared sign-in guidance followed by access address and QR login cards. + * Present address prerequisites, an access address, available QR login. * @param props - Section injection and standard slot props. * @returns Remote connection settings content. */ export function RemoteConnectionSection(props: RemoteConnectionSectionProps) { const { t, useRemoteConnection } = props + const available = useRemoteConnection(state => state.deployment?.availability === 'available') const loading = useRemoteConnection(state => state.phase === 'loading' && state.deployment === null) if (loading) return
return

{t('title')}

-

{t('addressDescription')}

+
- + {available && }
} +function ConnectionNotice({ t, useRemoteConnection }: Pick) { + const deployment = useRemoteConnection(state => state.deployment) + if (deployment === null) return null + if (deployment.availability === 'available') return

{t('addressDescription')}

+ return
+ +

{t(deployment.availability)}

+
+} + function QrLoginCard({ t, useRemoteConnection, create, cancel, reload }: Pick) { const { deployment, phase, ticket, error, remainingSeconds, retainDetails } = useRemoteConnection(state => state) const busy = phase === 'loading' || phase === 'creating' || phase === 'cancelling' - const available = deployment?.availability === 'available' const http = deployment?.url.startsWith('http:') === true const visibleTicket = phase === 'pending' && ticket !== null ? ticket : null const showQrPreview = visibleTicket !== null || busy const showDetails = visibleTicket !== null || retainDetails - const showQrBody = (phase !== 'ready' && phase !== 'cancelled') || !available + const showQrBody = phase !== 'ready' && phase !== 'cancelled' return

{t('qrTitle')}

- {(available || ticket !== null) &&
- {available && } + {(ticket !== null || phase === 'creating') && } -
} +
{showQrBody &&
{showQrPreview &&
@@ -60,7 +70,6 @@ function QrLoginCard({ t, useRemoteConnection, create, cancel, reload }: Pick
} - {deployment !== null && deployment.availability !== 'available' &&

{t(deployment.availability)}

} {phase === 'expired' &&

{t('expired')}

@@ -76,9 +85,10 @@ function QrLoginCard({ t, useRemoteConnection, create, cancel, reload }: Pick } -function AccessAddressCard({ t, useRemoteConnection, useLoginLink, copyLink, reloadLink }: Pick) { +function AccessAddressCard({ t, useRemoteConnection, useLoginLink, copyLink, reloadLink, reload }: Pick) { const deployment = useRemoteConnection(state => state.deployment) + const error = useRemoteConnection(state => state.error) const link = useLoginLink(state => state) const available = deployment?.availability === 'available' const http = deployment?.url.startsWith('http:') === true @@ -87,9 +97,13 @@ function AccessAddressCard({ t, useRemoteConnection, useLoginLink, copyLink, rel

{t('addressTitle')}

+ {!available && error !== null && <> +

{t(error)}

+
+ } {deployment !== null &&
- {link.url ?? deployment.url} + {(available ? link.url : null) ?? deployment.url}
{available && }
} {available && retryLink &&

{t('linkFailed')}

} - {link.copied && } + {available && link.copied && }
} diff --git a/packages/client/remote-connection/src/client/index.ts b/packages/client/remote-connection/src/client/index.ts index bb095511a1..0637be3e77 100644 --- a/packages/client/remote-connection/src/client/index.ts +++ b/packages/client/remote-connection/src/client/index.ts @@ -53,7 +53,7 @@ export async function apply(ctx: Context): Promise { }), 'remote-connection: link availability') scope.on('connection/reset', () => { if (linkAvailable) void link.refresh() - else void controller.load() + void controller.load() }) scope.slots.inject('settings.section', () => scope.slots.register({ name: 'settings.section', id: 'remote-connection', order: 25, diff --git a/packages/client/remote-connection/src/client/locales.ts b/packages/client/remote-connection/src/client/locales.ts index 2a21f9d2ca..20fa1a3d2c 100644 --- a/packages/client/remote-connection/src/client/locales.ts +++ b/packages/client/remote-connection/src/client/locales.ts @@ -30,8 +30,8 @@ export const en = { loading: 'Loading remote connection', creating: 'Creating login code', cancelling: 'Cancelling login code', - 'unreachable-host': 'Set an access address your phone can reach. A localhost or unspecified address cannot be used.', - 'untrusted-host': 'Add this access address to the Host’s trusted hosts before creating a code.', + 'unreachable-host': 'This address cannot be used to sign in from another device; configure a reachable address, such as a LAN address or an already configured public or VPN address.', + 'untrusted-host': 'Allow this address in the Host’s trusted hosts before using either login method.', loadFailed: 'Could not load remote connection settings. Try again.', createFailed: 'Could not confirm code creation. A code may still be valid; creating a new one replaces it.', cancelFailed: 'Could not confirm cancellation. This code may still work; try cancelling again.', @@ -71,8 +71,8 @@ export const zh: Record = { loading: '正在加载远程连接', creating: '正在生成登录二维码', cancelling: '正在取消登录二维码', - 'unreachable-host': '请配置手机可访问的地址,不能使用 localhost 或未指定的监听地址', - 'untrusted-host': '请先将此访问地址加入 Host 的可信主机配置', + 'unreachable-host': '当前地址不能用于其他设备登录,请配置其他设备可访问的地址,例如能连通的局域网地址或已配置的公网、VPN 地址', + 'untrusted-host': '请先将此访问地址加入 Host 的可信主机配置,才能使用下方的登录方式', loadFailed: '无法加载远程连接设置,请重试', createFailed: '无法确认二维码是否生成,可能仍有有效二维码;生成新二维码会将其替换', cancelFailed: '无法确认是否已取消,此二维码可能仍然有效,请重试取消', @@ -109,8 +109,8 @@ export const ja: Record = { loading: 'リモート接続を読み込み中', creating: 'ログイン用コードを生成中', cancelling: 'ログイン用コードをキャンセル中', - 'unreachable-host': 'スマートフォンからアクセスできるアドレスを設定してください。localhostや未指定のアドレスは使用できません。', - 'untrusted-host': 'コードを生成する前に、このアドレスをHostの信頼するホストに追加してください。', + 'unreachable-host': 'このアドレスでは別の端末からログインできないため、アクセス可能な LAN アドレスや設定済みの公開アドレスまたは VPN アドレスなど、別の端末からアクセス可能なアドレスを設定してください。', + 'untrusted-host': 'どちらのログイン方法を使う場合も、先にこのアドレスを Host の信頼するホストに追加してください。', loadFailed: 'リモート接続設定を読み込めませんでした。再試行してください。', createFailed: 'コードの生成を確認できませんでした。有効なコードが残っている可能性があります。新しく生成すると置き換わります。', cancelFailed: 'キャンセルを確認できませんでした。このコードはまだ有効かもしれません。再度キャンセルしてください。', @@ -147,8 +147,8 @@ export const es: Record = { loading: 'Cargando conexión remota', creating: 'Creando código de inicio de sesión', cancelling: 'Cancelando código de inicio de sesión', - 'unreachable-host': 'Configura una dirección accesible desde el teléfono. No se puede usar localhost ni una dirección sin especificar.', - 'untrusted-host': 'Añade esta dirección a los hosts de confianza del Host antes de crear un código.', + 'unreachable-host': 'Esta dirección no permite iniciar sesión desde otro dispositivo; configura una dirección accesible, como una dirección LAN accesible o una dirección pública o de VPN ya configurada.', + 'untrusted-host': 'Añade esta dirección a los hosts de confianza del Host antes de usar cualquiera de los dos métodos de inicio de sesión.', loadFailed: 'No se pudo cargar la configuración de conexión remota. Reinténtalo.', createFailed: 'No se pudo confirmar la creación. Puede que aún haya un código válido; al crear otro se sustituirá.', cancelFailed: 'No se pudo confirmar la cancelación. Este código puede seguir funcionando; vuelve a cancelarlo.', @@ -185,8 +185,8 @@ export const fr: Record = { loading: 'Chargement de la connexion à distance', creating: 'Création du code de connexion', cancelling: 'Annulation du code de connexion', - 'unreachable-host': 'Définissez une adresse accessible depuis votre téléphone. localhost et les adresses non spécifiées ne sont pas utilisables.', - 'untrusted-host': 'Ajoutez cette adresse aux hôtes de confiance du Host avant de créer un code.', + 'unreachable-host': 'Cette adresse ne permet pas de se connecter depuis un autre appareil ; configurez une adresse accessible, comme une adresse LAN accessible ou une adresse publique ou VPN déjà configurée.', + 'untrusted-host': 'Ajoutez cette adresse aux hôtes de confiance du Host avant d’utiliser l’une ou l’autre des méthodes de connexion.', loadFailed: 'Impossible de charger les paramètres de connexion à distance. Réessayez.', createFailed: 'La création du code n’a pas pu être confirmée. Un code peut encore être valide ; en créer un nouveau le remplacera.', cancelFailed: 'L’annulation n’a pas pu être confirmée. Ce code peut encore fonctionner ; réessayez de l’annuler.', @@ -223,8 +223,8 @@ export const de: Record = { loading: 'Fernverbindung wird geladen', creating: 'Anmeldecode wird erstellt', cancelling: 'Anmeldecode wird widerrufen', - 'unreachable-host': 'Legen Sie eine vom Smartphone erreichbare Adresse fest. localhost und nicht angegebene Adressen sind nicht verwendbar.', - 'untrusted-host': 'Fügen Sie diese Adresse vor dem Erstellen eines Codes den vertrauenswürdigen Hosts des Host hinzu.', + 'unreachable-host': 'Mit dieser Adresse ist die Anmeldung von einem anderen Gerät nicht möglich; konfigurieren Sie eine erreichbare Adresse, etwa eine erreichbare LAN-Adresse oder eine bereits konfigurierte öffentliche Adresse oder VPN-Adresse.', + 'untrusted-host': 'Fügen Sie diese Adresse den vertrauenswürdigen Hosts des Host hinzu, bevor Sie eine der beiden Anmeldemethoden verwenden.', loadFailed: 'Die Einstellungen für die Fernverbindung konnten nicht geladen werden. Versuchen Sie es erneut.', createFailed: 'Die Erstellung konnte nicht bestätigt werden. Ein Code könnte noch gültig sein; ein neuer Code ersetzt ihn.', cancelFailed: 'Der Widerruf konnte nicht bestätigt werden. Dieser Code könnte noch funktionieren; widerrufen Sie ihn erneut.', @@ -261,8 +261,8 @@ export const ru: Record = { loading: 'Загрузка удалённого подключения', creating: 'Создание кода для входа', cancelling: 'Отмена кода для входа', - 'unreachable-host': 'Укажите адрес, доступный с телефона. localhost и неопределённый адрес использовать нельзя.', - 'untrusted-host': 'Перед созданием кода добавьте этот адрес в доверенные хосты Host.', + 'unreachable-host': 'Этот адрес нельзя использовать для входа с другого устройства; настройте доступный адрес, например доступный адрес LAN или уже настроенный публичный адрес либо адрес VPN.', + 'untrusted-host': 'Добавьте этот адрес в доверенные хосты Host, прежде чем использовать любой из двух способов входа.', loadFailed: 'Не удалось загрузить настройки удалённого подключения. Повторите попытку.', createFailed: 'Не удалось подтвердить создание кода. Код может оставаться действительным; создание нового заменит его.', cancelFailed: 'Не удалось подтвердить отмену. Код может ещё работать; повторите отмену.', @@ -299,8 +299,8 @@ export const pt: Record = { loading: 'Carregando conexão remota', creating: 'Criando código de login', cancelling: 'Cancelando código de login', - 'unreachable-host': 'Defina um endereço acessível pelo celular. localhost ou um endereço não especificado não podem ser usados.', - 'untrusted-host': 'Adicione este endereço aos hosts confiáveis do Host antes de criar um código.', + 'unreachable-host': 'Este endereço não permite entrar de outro dispositivo; configure um endereço acessível, como um endereço LAN acessível ou um endereço público ou de VPN já configurado.', + 'untrusted-host': 'Adicione este endereço aos hosts confiáveis do Host antes de usar qualquer um dos dois métodos de login.', loadFailed: 'Não foi possível carregar as configurações de conexão remota. Tente novamente.', createFailed: 'Não foi possível confirmar a criação. Um código ainda pode ser válido; criar outro o substitui.', cancelFailed: 'Não foi possível confirmar o cancelamento. Este código ainda pode funcionar; tente cancelar novamente.', diff --git a/packages/client/remote-connection/tests/apply.client.spec.ts b/packages/client/remote-connection/tests/apply.client.spec.ts index df483ac41e..6a345e542e 100644 --- a/packages/client/remote-connection/tests/apply.client.spec.ts +++ b/packages/client/remote-connection/tests/apply.client.spec.ts @@ -349,7 +349,7 @@ describe('remote connection settings registration', () => { } }) - it('prefetches the login link only after deployment becomes available', async () => { + it('refreshes deployment on every reconnect and prefetches the login link once available', async () => { let available = false const call = vi.fn().mockImplementation(async (_channel, endpoint) => ({ ok: true, value: endpoint === 'remoteConnection/loginUrl' ? 'https://host.example/?token=private' @@ -365,11 +365,13 @@ describe('remote connection settings registration', () => { await vi.waitFor(() => { expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/loginUrl')).toHaveLength(1) }) const face = slots.spec('settings.remoteConnection.content')!.inject available = false - act(() => { face.reload() }) + act(() => { ctx.emit('connection/reset') }) await vi.waitFor(() => { expect(face.hooks.remoteConnection.getSnapshot().deployment?.availability).toBe('untrusted-host') }) + expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/status')).toHaveLength(4) + await vi.waitFor(() => { expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/loginUrl')).toHaveLength(2) }) act(() => { ctx.emit('connection/reset') }) await vi.waitFor(() => { expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/status')).toHaveLength(5) }) - expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/loginUrl')).toHaveLength(1) + expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/loginUrl')).toHaveLength(2) }) it('keeps plugin disposal pending until a clipboard write settles', async () => { diff --git a/packages/client/remote-connection/tests/controller.client.spec.ts b/packages/client/remote-connection/tests/controller.client.spec.ts index bf51bce43e..f8f9def806 100644 --- a/packages/client/remote-connection/tests/controller.client.spec.ts +++ b/packages/client/remote-connection/tests/controller.client.spec.ts @@ -119,6 +119,25 @@ describe('Remote connection invitation state', () => { expect(vi.getTimerCount()).toBe(0) }) + it.each(['unreachable-host', 'untrusted-host'] as const)('forgets a pending credential and stops polling when the address becomes %s', async (availability) => { + const { remote, controller, state } = setup() + await controller.load() + await controller.create() + expect(state()).toMatchObject({ phase: 'pending', ticket }) + remote.status.mockResolvedValueOnce({ ok: true, value: { ...deployment, availability, ticket: 'pending' } }) + await vi.advanceTimersByTimeAsync(1000) + expect(state()).toMatchObject({ deployment: { availability }, ticket: null, retainDetails: false }) + expect(vi.getTimerCount()).toBe(0) + const reads = remote.status.mock.calls.length + await vi.advanceTimersByTimeAsync(10_000) + expect(remote.status).toHaveBeenCalledTimes(reads) + remote.status.mockResolvedValueOnce({ ok: true, value: { ...deployment, ticket: 'pending' } }) + await controller.load() + expect(remote.status).toHaveBeenLastCalledWith(null) + expect(state()).toMatchObject({ phase: 'ready', ticket: null }) + expect(vi.getTimerCount()).toBe(0) + }) + it('polls a live code and drops it if another owner replaces it', async () => { const { remote, controller, state } = setup() await controller.load() diff --git a/packages/client/remote-connection/tests/section.client.spec.tsx b/packages/client/remote-connection/tests/section.client.spec.tsx index 9697f430e3..429bd2891e 100644 --- a/packages/client/remote-connection/tests/section.client.spec.tsx +++ b/packages/client/remote-connection/tests/section.client.spec.tsx @@ -90,12 +90,29 @@ describe('Remote connection section', () => { expect(cancel).toHaveBeenCalledOnce() }) - it.each(['unreachable-host', 'untrusted-host'] as const)('explains the %s prerequisite and offers no code', (availability) => { - panel({ deployment: { ...ready.deployment!, availability } }) - expect(screen.getByRole('status').textContent).toBe(en[availability]) - expect(screen.queryByRole('button')).toBeNull() + it.each([ + ['en', 'unreachable-host'], ['en', 'untrusted-host'], + ['zh', 'unreachable-host'], ['zh', 'untrusted-host'], + ] as const)('shows %s guidance for %s before the address', (language, availability) => { + const copy = language === 'en' ? en : zh + const url = availability === 'unreachable-host' ? 'http://127.0.0.1:5432/' : 'https://untrusted.example/app/' + panel({ deployment: { ...ready.deployment!, url, availability } }, language, { copied: true }) + const section = screen.getByRole('region', { name: copy.title }) + const notice = within(section).getByText(copy[availability]) + expect(notice.closest('[role="status"]')).not.toBeNull() + for (const card of within(section).getAllByRole('region')) { + expect(within(card).queryByText(copy[availability])).toBeNull() + expect(notice.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + } + const address = within(section).getByRole('region', { name: copy.addressTitle }) + expect(within(address).getByText(url)).toBeTruthy() + expect(within(address).queryByRole('button')).toBeNull() + expect(within(section).queryByRole('region', { name: copy.qrTitle })).toBeNull() expect(screen.queryByRole('img')).toBeNull() - expect(screen.queryByText(en.warning)).toBeNull() + expect(screen.queryByText(copy.addressDescription)).toBeNull() + expect(screen.queryByText(copy.warning)).toBeNull() + expect(screen.queryByText(copy.linkWarning)).toBeNull() + expect(document.body.textContent).not.toContain('private-login-token') }) it.each(['en', 'zh'] as const)('allows HTTP code creation with a plaintext reminder in %s', (language) => { @@ -195,14 +212,23 @@ describe('Remote connection section', () => { expect(cancel).toHaveBeenCalledOnce() }) - it('allows retry when deployment loading failed and shows a centered pending state while reading', () => { - const { reload } = panel({ phase: 'error', deployment: null, error: 'loadFailed' }) - expect(screen.getByRole('alert').textContent).toBe(en.loadFailed) - fireEvent.click(screen.getByRole('button', { name: en.retry })) + it.each([ + { language: 'en', cached: false }, { language: 'zh', cached: false }, + { language: 'en', cached: true }, { language: 'zh', cached: true }, + ] as const)('keeps a failed address read recoverable in $language (cached address: $cached)', ({ language, cached }) => { + const copy = language === 'en' ? en : zh + const deployment = cached ? { ...ready.deployment!, availability: 'untrusted-host' as const } : null + const { reload } = panel({ phase: 'error', deployment, error: 'loadFailed' }, language) + const address = screen.getByRole('region', { name: copy.addressTitle }) + expect(within(address).getByRole('alert').textContent).toBe(copy.loadFailed) + if (deployment !== null) expect(within(address).getByText(deployment.url)).toBeTruthy() + expect(screen.queryByRole('region', { name: copy.qrTitle })).toBeNull() + expect(screen.queryByText(copy.addressDescription)).toBeNull() + fireEvent.click(within(address).getByRole('button', { name: copy.retry })) expect(reload).toHaveBeenCalledOnce() cleanup() - panel({ phase: 'loading', deployment: null }) - expect(screen.getByRole('status', { name: en.loading })).toBeTruthy() + panel({ phase: 'loading', deployment: null }, language) + expect(screen.getByRole('status', { name: copy.loading })).toBeTruthy() expect(screen.queryByRole('button')).toBeNull() })