diff --git a/.gitignore b/.gitignore index 0892f7ef..f256ffdc 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ dist release/ test-results/ coverage/ +*.tsbuildinfo # agent tooling state .agents .claude diff --git a/docs/screenshots/en/activity-dark.webp b/docs/screenshots/en/activity-dark.webp index ce62ee8c..085f423d 100644 Binary files a/docs/screenshots/en/activity-dark.webp and b/docs/screenshots/en/activity-dark.webp differ diff --git a/docs/screenshots/en/activity-light.webp b/docs/screenshots/en/activity-light.webp index 7d091d0f..5cfb7e77 100644 Binary files a/docs/screenshots/en/activity-light.webp and b/docs/screenshots/en/activity-light.webp differ diff --git a/docs/screenshots/en/policies-light.webp b/docs/screenshots/en/policies-light.webp index 2431fc77..dfe84042 100644 Binary files a/docs/screenshots/en/policies-light.webp and b/docs/screenshots/en/policies-light.webp differ diff --git a/docs/screenshots/en/rules-light.webp b/docs/screenshots/en/rules-light.webp index 9cf8f783..3c179df3 100644 Binary files a/docs/screenshots/en/rules-light.webp and b/docs/screenshots/en/rules-light.webp differ diff --git a/docs/screenshots/palettes.webp b/docs/screenshots/palettes.webp index 67f92c25..c84abbba 100644 Binary files a/docs/screenshots/palettes.webp and b/docs/screenshots/palettes.webp differ diff --git a/docs/screenshots/zh-CN/activity-dark.webp b/docs/screenshots/zh-CN/activity-dark.webp index 7fd147b5..87cc8bc4 100644 Binary files a/docs/screenshots/zh-CN/activity-dark.webp and b/docs/screenshots/zh-CN/activity-dark.webp differ diff --git a/docs/screenshots/zh-CN/activity-light.webp b/docs/screenshots/zh-CN/activity-light.webp index 0ffdf0cd..6041c9c0 100644 Binary files a/docs/screenshots/zh-CN/activity-light.webp and b/docs/screenshots/zh-CN/activity-light.webp differ diff --git a/docs/screenshots/zh-CN/policies-light.webp b/docs/screenshots/zh-CN/policies-light.webp index fd435fbc..39077fe3 100644 Binary files a/docs/screenshots/zh-CN/policies-light.webp and b/docs/screenshots/zh-CN/policies-light.webp differ diff --git a/docs/screenshots/zh-CN/rules-light.webp b/docs/screenshots/zh-CN/rules-light.webp index 73eadfc7..8d4cb079 100644 Binary files a/docs/screenshots/zh-CN/rules-light.webp and b/docs/screenshots/zh-CN/rules-light.webp differ diff --git a/docs/screenshots/zh-TW/activity-dark.webp b/docs/screenshots/zh-TW/activity-dark.webp index 60697e12..6196d349 100644 Binary files a/docs/screenshots/zh-TW/activity-dark.webp and b/docs/screenshots/zh-TW/activity-dark.webp differ diff --git a/docs/screenshots/zh-TW/activity-light.webp b/docs/screenshots/zh-TW/activity-light.webp index 00c59eff..3404f0b1 100644 Binary files a/docs/screenshots/zh-TW/activity-light.webp and b/docs/screenshots/zh-TW/activity-light.webp differ diff --git a/docs/screenshots/zh-TW/policies-light.webp b/docs/screenshots/zh-TW/policies-light.webp index 83dfb2bd..dba63efa 100644 Binary files a/docs/screenshots/zh-TW/policies-light.webp and b/docs/screenshots/zh-TW/policies-light.webp differ diff --git a/docs/screenshots/zh-TW/rules-light.webp b/docs/screenshots/zh-TW/rules-light.webp index 072ac66d..2590aadc 100644 Binary files a/docs/screenshots/zh-TW/rules-light.webp and b/docs/screenshots/zh-TW/rules-light.webp differ diff --git a/e2e/activity.spec.ts b/e2e/activity.spec.ts index 66bfc0f5..3687cc7e 100644 --- a/e2e/activity.spec.ts +++ b/e2e/activity.spec.ts @@ -54,11 +54,11 @@ test('home charts collect memory polls and change the traffic history range', as const request = page.waitForRequest( request => request.url().includes('/runtime/traffic/history?') && new URL(request.url()).searchParams.get('window_seconds') === '3600' ); - await traffic.getByRole('radio', {name: '1H', exact: true}).click(); + await traffic.getByRole('radio', {name: '1 h', exact: true}).click(); await request; await expect(traffic.locator('.recharts-surface')).toBeVisible(); await expect(memory.locator('.recharts-area-curve').first()).toHaveAttribute('d', memoryCurve!); - await traffic.getByRole('radio', {name: '7D', exact: true}).click(); + await traffic.getByRole('radio', {name: '7 d', exact: true}).click(); await expect(memory.locator('.recharts-area-curve').first()).toHaveAttribute('d', memoryCurve!); }); @@ -304,7 +304,7 @@ test('optional runtime does not block independent activity sections or poll an u await expect(page.getByRole('button', {name: 'Node', exact: true})).toBeVisible(); await expect(page.getByRole('region', {name: 'Memory', exact: true}).locator('.recharts-surface')).toBeVisible(); await expect(page.getByRole('heading', {name: 'Outbound downloads', exact: true})).toBeVisible(); - await expect(page.getByText('Not offered by the backend', {exact: true})).toBeVisible(); + await expect(page.getByText('Not provided by this backend', {exact: true})).toBeVisible(); await page.clock.fastForward(10100); expect(requests.filter(request => new URL(request.url()).pathname === '/api/v1/runtime')).toEqual([]); }); diff --git a/e2e/architecture.spec.ts b/e2e/architecture.spec.ts index 631fb224..bb939456 100644 --- a/e2e/architecture.spec.ts +++ b/e2e/architecture.spec.ts @@ -1,4 +1,4 @@ -import {test as httpTest, type Page} from '@playwright/test'; +import {test as httpTest, type Locator, type Page} from '@playwright/test'; import {createMockApi} from '../src/api/mock'; import {sha256} from '../src/api/hash'; import {ApiError} from '../src/api/error'; @@ -96,7 +96,7 @@ for (const tab of ['source', 'setup']) { else { await expect(page.getByLabel('Subscription URL', {exact: true})).toBeDisabled(); await expect(page.getByRole('button', {name: /Rules$/})).toBeDisabled(); - await expect(page.getByRole('button', {name: 'Add a subscription', exact: true})).toBeDisabled(); + await expect(page.getByRole('button', {name: 'Add subscription', exact: true})).toBeDisabled(); } const writing = page.waitForRequest(request => request.method() === 'PUT'); releaseValidation(); @@ -114,7 +114,7 @@ for (const tab of ['source', 'setup']) { } for (const all of [false, true]) { - test(`navigation cancels ${all ? 'bulk' : 'single'} close without announcing success`, async ({page}) => { + test(`${all ? 'Cancel abandons bulk' : 'navigation cancels single'} close without announcing success`, async ({page}) => { await backend(page); let release!: () => void; const gate = new Promise(resolve => { @@ -133,6 +133,8 @@ for (const all of [false, true]) { } else await page.getByRole('button', {name: 'Close connection', exact: true}).click(); await request; await expect(page).toHaveURL(/connections\?id=1$/); + // A pending confirmation covers the page; its Cancel abandons the bulk close. + if (all) await page.getByRole('alertdialog').getByRole('button', {name: 'Cancel', exact: true}).click(); await page.locator('.rp-nav[href="#/settings"]').click(); await expect(page.locator('[name=api]')).toBeVisible(); release(); @@ -517,8 +519,8 @@ test('new group validation refusal retains the dialog and its name without a suc }); await page.goto('/#/nodes?provider=inline'); await page.getByRole('button', {name: 'Add hk-01 to a group', exact: true}).click(); - await page.getByRole('menuitemradio', {name: 'New group...', exact: true}).click(); - const dialog = page.getByRole('dialog', {name: 'New group...', exact: true}); + await page.getByRole('menuitemradio', {name: 'New group…', exact: true}).click(); + const dialog = page.getByRole('dialog', {name: 'New group…', exact: true}); await dialog.getByLabel('Name', {exact: true}).fill('retained-group'); const validating = page.waitForRequest('**/api/v1/config/validate'); await dialog.getByRole('button', {name: 'Add', exact: true}).click(); @@ -633,6 +635,30 @@ httpTest('backend inventory failures expose independent retries without claiming await expect(card.getByRole('button', {name: 'Close all', exact: true})).toBeEnabled(); }); +httpTest('failed reads on activity, DNS and settings each offer a retry', async ({page}) => { + const api = await backend(page); + await page.addInitScript(() => localStorage.setItem('doona-lang', 'en')); + let fail = true; + const failure = (message: string) => ({status: 503, json: {request_id: 'retry', error: {code: 'service_unavailable', message, details: null}}}); + await page.route('**/api/v1/runtime/outbounds', async route => route.fulfill(fail ? failure('Outbounds unavailable') : {json: await api.runtimeOutbounds()})); + await page.route('**/api/v1/dns/cache{,?*}', async route => route.fulfill(fail ? failure('Cache unavailable') : {json: await api.dnsCache()})); + await page.route('**/api/v1/geodata', async route => route.fulfill(fail ? failure('Geodata unavailable') : {json: await api.geodata()})); + const retried = async (alert: Locator) => { + await expect(alert).toBeVisible(); + fail = false; + await alert.getByRole('button', {name: 'Retry', exact: true}).click(); + await expect(alert).toHaveCount(0); + fail = true; + }; + await page.goto('/#/activity'); + await retried(page.getByRole('alert').filter({hasText: 'Outbounds unavailable'})); + await page.goto('/#/dns?tab=cache'); + await retried(page.getByRole('alert').filter({hasText: 'Cache unavailable'})); + await expect(page.getByRole('grid', {name: 'Cache', exact: true}).getByRole('rowheader').first()).toBeVisible(); + await page.goto('/#/settings'); + await retried(page.getByRole('alert').filter({hasText: 'Geodata unavailable'})); +}); + test('routing map selections separate missing outbounds from a backend name of unknown', async ({page}) => { const api = await backend(page); const snapshot = await api.flows(); @@ -762,7 +788,7 @@ test('a large routing dictionary reveals bounded batches without changing tile g await page.goto('/#/rules?tab=map'); const leaves = page.locator('.rp-tree-tile[data-stage="rule"]'); await expect(leaves).toHaveCount(30); - await expect(page.locator('.rp-tree-tile[data-stage="outbound"]').filter({hasText: groups[0].name})).toContainText('min_avg10'); + await expect(page.locator('.rp-tree-tile[data-stage="outbound"]').filter({hasText: groups[0].name})).toContainText('Fastest on average'); const first = await leaves.first().boundingBox(); await page.getByRole('button', {name: 'Show 30 more items', exact: true}).click(); await expect(leaves).toHaveCount(60); diff --git a/e2e/builder.spec.ts b/e2e/builder.spec.ts index 95a674a1..f8c14471 100644 --- a/e2e/builder.spec.ts +++ b/e2e/builder.spec.ts @@ -8,10 +8,10 @@ test('a node joins an existing group or a new one through the name filter', asyn await menu.getByRole('menuitemradio', {name: /^resilient/}).click(); await expect(page.locator('.rp-toast.positive')).toContainText('jp-01 added to resilient'); await page.getByRole('button', {name: 'Add sg-01 to a group', exact: true}).click(); - await page.getByRole('menuitemradio', {name: 'New group...', exact: true}).click(); + await page.getByRole('menuitemradio', {name: 'New group…', exact: true}).click(); const dialog = page.getByRole('dialog'); await dialog.getByLabel('Name').fill('backup'); - await expect(dialog.getByRole('button', {name: /How it chooses/})).toContainText('Fastest on average'); + await expect(dialog.getByRole('button', {name: /Selection policy/})).toContainText('Fastest on average'); await dialog.getByRole('button', {name: 'Add', exact: true}).click(); await expect(page.locator('.rp-toast.positive', {hasText: 'sg-01 added to backup'})).toBeVisible(); await page.goto('/#/config?tab=source'); @@ -25,15 +25,15 @@ test('a group card edits its policy and filters in the main source', async ({pag await card.getByRole('button', {name: 'Edit', exact: true}).click(); const dialog = page.getByRole('dialog', {name: 'Edit group gaming'}); await expect(dialog.getByRole('textbox', {name: 'Filter 1'})).toHaveValue('name(jp-01, hk-02)'); - const policy = dialog.getByRole('button', {name: /How it chooses/}); + const policy = dialog.getByRole('button', {name: /Selection policy/}); // A policy the picker does not offer stays selected as written. await expect(policy).toContainText('min_last_delay'); await policy.click(); - await page.getByRole('option', {name: /^First that works/}).click(); + await page.getByRole('option', {name: /^First available/}).click(); await dialog.getByRole('button', {name: 'Add filter', exact: true}).click(); await dialog.getByRole('textbox', {name: 'Filter 2'}).fill("subtag('sub-c')"); await dialog.getByRole('button', {name: 'Save', exact: true}).click(); - await expect(page.locator('.rp-toast.positive')).toContainText('Config updated for gaming'); + await expect(page.locator('.rp-toast.positive')).toContainText('Configuration updated for gaming'); await page.goto('/#/config?tab=source'); await expect(page.locator('.cm-content')).toContainText("gaming {\n filter: name(jp-01, hk-02)\n filter: subtag('sub-c')\n policy: fallback\n }"); }); @@ -42,10 +42,10 @@ test('editing only filters preserves the native policy spelling', async ({page}) await page.goto('/#/policies'); await page.getByRole('region', {name: 'resilient'}).getByRole('button', {name: 'Edit', exact: true}).click(); const dialog = page.getByRole('dialog', {name: 'Edit group resilient'}); - await expect(dialog.getByRole('button', {name: /How it chooses/})).toContainText('min_avg10'); + await expect(dialog.getByRole('button', {name: /Selection policy/})).toContainText('min_avg10'); await dialog.getByRole('textbox', {name: 'Filter 1'}).fill('name(hk-01, sg-01)'); await dialog.getByRole('button', {name: 'Save', exact: true}).click(); - await expect(page.locator('.rp-toast.positive')).toContainText('Config updated for resilient'); + await expect(page.locator('.rp-toast.positive')).toContainText('Configuration updated for resilient'); await page.goto('/#/config?tab=source'); await expect(page.locator('.cm-content')).toContainText('resilient {\n filter: name(hk-01, sg-01)\n policy: min_avg10\n }'); }); diff --git a/e2e/capabilities.spec.ts b/e2e/capabilities.spec.ts index eb60ba87..58969aae 100644 --- a/e2e/capabilities.spec.ts +++ b/e2e/capabilities.spec.ts @@ -78,7 +78,7 @@ test('a login draft cannot be saved after another tab changes the challenged end }); await other.close(); await page.getByRole('button', {name: 'Connect', exact: true}).click(); - await expect(page.getByRole('alert')).toContainText('The backend settings changed'); + await expect(page.getByRole('alert')).toContainText('The profile changed'); await page.getByRole('button', {name: 'Show token'}).click(); await expect(token).toHaveValue('challenge-secret'); expect(await page.evaluate(() => localStorage.getItem('doona-profiles'))).toBe(saved); diff --git a/e2e/charts.spec.ts b/e2e/charts.spec.ts index 9482286d..b72d1852 100644 --- a/e2e/charts.spec.ts +++ b/e2e/charts.spec.ts @@ -12,7 +12,7 @@ test('DNS opens on its statistics, with each figure labelled and its sample coun await page.goto('/#/dns'); await expect(page.getByRole('tab', {name: 'Statistics'})).toHaveAttribute('aria-selected', 'true'); await expect(page.getByRole('heading', {name: 'Cache', exact: true})).toBeVisible(); - await expect(page.getByText(/^\d+ cache entries; the backend reports no capacity$/)).toBeVisible(); + await expect(page.getByText(/^\d+ cache entries; this backend does not provide a capacity limit$/)).toBeVisible(); await expect(fact(page, 'Median')).toHaveText(/^\d+ ms$/); await expect(fact(page, 'P95')).toHaveText(/^\d+ ms$/); await expect(fact(page, 'Cache hit rate')).toHaveText(/^\d+%$/); @@ -33,7 +33,7 @@ test('node latency groups two ways, shortens long groups and shows a tip on hove await expect(fact(page, 'Unavailable')).toHaveText(/^\d+ nodes?$/); const plot = page.getByRole('group', {name: 'Node latency'}); for (const label of ['Latest latency', 'Moving average', 'Average of the last 10']) await expect(plot.getByText(label, {exact: true})).toBeVisible(); - const row = plot.getByRole('img', {name: /^.+: latest \d+ ms, moving average \d+ ms, average of the last 10 \d+ ms$/}).first(); + const row = plot.getByRole('img', {name: /^.+, latest: \d+ ms, moving average: \d+ ms, average of the last 10: \d+ ms$/}).first(); await row.hover(); await expect(page.locator('.rp-charttip')).toContainText('Moving average'); const showAll = plot.getByRole('button', {name: /^Show all \d+$/}); diff --git a/e2e/chunks.spec.ts b/e2e/chunks.spec.ts index 30a7cbbe..4be5a25c 100644 --- a/e2e/chunks.spec.ts +++ b/e2e/chunks.spec.ts @@ -177,3 +177,38 @@ test('a search dialog that fails to load leaves nothing open and says so', async await expect(page.getByRole('dialog')).toHaveCount(0); await expect(page.locator('.rp-alert')).toHaveCount(0); }); + +test('pressing Control inside a field loads the search dialog', async ({page}) => { + await page.addInitScript(() => { + window.requestIdleCallback = () => 0; + }); + await page.goto('/#/settings'); + await page.locator('[name=api]').focus(); + const requested = page.waitForRequest(/\/SearchDialog-[^/]+\.js$/); + await page.keyboard.down('Control'); + await requested; + await page.keyboard.up('Control'); +}); + +test('Escape while the search dialog loads keeps it from opening late', async ({page}) => { + await page.addInitScript(() => { + window.requestIdleCallback = () => 0; + }); + let release!: () => void; + const gate = new Promise(resolve => (release = resolve)); + await page.route('**/assets/SearchDialog-*.js', async route => { + await gate; + await route.fallback(); + }); + await page.goto('/#/activity'); + await expect(page.locator('.rp-strip')).toBeVisible(); + const loaded = page.waitForResponse(/\/SearchDialog-[^/]+\.js$/); + await page.keyboard.press('Control+K'); + await page.keyboard.press('Escape'); + release(); + await loaded; + await page.waitForTimeout(300); + await expect(page.getByRole('dialog')).toHaveCount(0); + await page.keyboard.press('Control+K'); + await expect(page.getByRole('dialog')).toBeVisible(); +}); diff --git a/e2e/config.spec.ts b/e2e/config.spec.ts index 9bd38a05..8c9d4cf2 100644 --- a/e2e/config.spec.ts +++ b/e2e/config.spec.ts @@ -86,7 +86,7 @@ test('editing validates, shows diagnostics on errors, and saves through a reload await expect(page.locator('.cm-content[aria-label="/etc/honk/rules.dae"]')).toHaveAttribute('contenteditable', 'false'); await expect(page.locator('.cm-content[aria-label="/etc/honk/rules.dae"]')).toContainText('domain(geosite: netflix) -> proxy'); await expect(page.locator('.rp-toolbar').first()).toContainText('41'); - await expect(page.locator('.rp-toolbar').nth(1)).toContainText('Line count: 8,'); + await expect(page.locator('.rp-toolbar').nth(1)).toContainText('Lines: 8,'); }); test('the validation tab lists kept diagnostics and opens the source at the line', async ({page}) => { @@ -114,7 +114,7 @@ test.describe('without configuration readback', () => { test('the page is hidden from navigation and says so when opened', async ({page}) => { await page.goto('/#/config'); await expect(page.locator('.rp-nav[href="#/config"]')).toHaveAttribute('data-unavailable', ''); - await expect(page.locator('.rp-content')).toContainText('The backend does not offer this page.'); + await expect(page.locator('.rp-content')).toContainText('This backend does not provide this page'); }); }); @@ -338,7 +338,7 @@ test('modules list top-level counts and edit only routing through reload', async await expect(modules.getByRole('region', {name: 'subscription', exact: true})).toContainText('1 subscription'); await expect(modules.getByRole('region', {name: 'node', exact: true})).toContainText('5 nodes'); await expect(modules.getByRole('region', {name: 'group', exact: true})).toContainText( - '4 groups: proxy: fixed(0), resilient: min_avg10, gaming: min_last_delay, skylink: min_moving_avg' + '4 groups: proxy: fixed(0), resilient: min_avg10, gaming: min_last_delay, skylink: Fastest on average' ); await expect(modules.getByRole('region', {name: 'dns', exact: true})).toContainText('2 upstreams, 1 request rule, 0 response rules'); const routing = modules.getByRole('region', {name: 'routing', exact: true}); @@ -414,7 +414,7 @@ test('quick setup preserves dotted tags and rejects duplicate subscription names await expect(page.getByLabel('Name', {exact: true})).toHaveValue('sub.eu'); await page.getByLabel('Subscription URL', {exact: true}).fill('https://example.org/new'); await expect(page.locator('.cm-content')).toContainText("sub.eu: 'https://example.org/new'"); - await page.getByRole('button', {name: 'Add a subscription', exact: true}).click(); + await page.getByRole('button', {name: 'Add subscription', exact: true}).click(); await page.getByLabel('Name', {exact: true}).last().fill('sub.eu'); await page.getByLabel('Subscription URL', {exact: true}).last().fill('https://duplicate.example/sub'); await expect(page.getByRole('button', {name: 'Apply and reload', exact: true})).toBeDisabled(); diff --git a/e2e/connections.spec.ts b/e2e/connections.spec.ts index 6cb4b2d9..93d5510e 100644 --- a/e2e/connections.spec.ts +++ b/e2e/connections.spec.ts @@ -1,5 +1,5 @@ import type {Locator} from '@playwright/test'; -import {expect, mockBackend, test} from './fixtures'; +import {expect, expectLoadFailures, mockBackend, test} from './fixtures'; import {createMockApi} from '../src/api/mock'; // The flat list exercises the virtualizer; grouping (the default) gets its own test below. @@ -206,7 +206,7 @@ test('column visibility, sorting and grouping persist without expanding the virt expect(await grid.getByRole('row').count()).toBeLessThan(60); } await page.getByRole('button', {name: 'Group by'}).click(); - await page.getByRole('option', {name: 'By client', exact: true}).click(); + await page.getByRole('option', {name: 'By device', exact: true}).click(); await grid.evaluate(element => { element.scrollTop = 0; }); @@ -216,7 +216,7 @@ test('column visibility, sorting and grouping persist without expanding the virt test('group slots stay expanded and unselectable across virtual keyboard navigation', async ({page}) => { await page.goto('/#/connections?tab=list'); await page.getByRole('button', {name: 'Group by'}).click(); - await page.getByRole('option', {name: 'By client', exact: true}).click(); + await page.getByRole('option', {name: 'By device', exact: true}).click(); const grid = page.getByRole('treegrid', {name: 'Connections'}); const groups = grid.locator('[role=row][aria-level="1"]'); const selected = grid.locator('[aria-selected="true"]'); @@ -255,7 +255,7 @@ test.describe('short connection lists', () => { const grid = page.getByRole('grid', {name: 'Connections'}); await expect(grid).toHaveAttribute('aria-rowcount', '9'); expect(await grid.evaluate(element => element.tagName)).toBe('DIV'); - const source = grid.getByRole('columnheader', {name: 'Source'}); + const source = grid.getByRole('columnheader', {name: 'Device'}); const chain = grid.getByRole('columnheader', {name: 'Chain'}); await expect(source).toBeVisible(); await expect.poll(async () => (await source.boundingBox())!.width / (await chain.boundingBox())!.width).toBeCloseTo(128 / 168, 2); @@ -287,7 +287,7 @@ test.describe('default view', () => { await page.setViewportSize({width: 1440, height: 900}); await grid.locator('[role=row][aria-level="2"]').first().click(); await expect(page.locator('.rp-panel').getByRole('heading')).toBeVisible(); - await page.locator('.rp-panel').getByRole('button', {name: 'Only this client', exact: true}).click(); + await page.locator('.rp-panel').getByRole('button', {name: 'Only this device', exact: true}).click(); await expect(page).toHaveURL(/src=10\.0\.0\.\d+/); await expect(groups).toHaveCount(1); }); @@ -472,6 +472,42 @@ test('close confirmation freezes listed IDs above the bulk limit and excludes ne await expect(page.locator('[data-key="later"]')).toBeVisible(); }); +test('close all reports skipped connections as information, as Settings does', async ({page}) => { + const api = createMockApi(); + const capabilities = await api.capabilities(); + capabilities.resources.events.available = false; + capabilities.resources.connections.max_bulk_close = 1; + const list = await api.connections(); + list.tcp = [ + {...list.tcp[0], id: 'first'}, + {...list.tcp[0], id: 'gone'} + ]; + list.udp = []; + list.truncated = false; + const responses: Record = { + '/capabilities': capabilities, + '/version': await api.version(), + '/runtime': await api.runtime(), + '/groups': await api.groups(), + '/nodes': await api.nodes() + }; + await page.addInitScript(() => localStorage.setItem('doona-api', location.origin)); + await page.route('**/api/v1/**', async route => { + const path = new URL(route.request().url()).pathname.replace('/api/v1', ''); + if (route.request().method() === 'DELETE') { + if (path.endsWith('/gone')) return route.fulfill({status: 404, json: {error: {code: 'resource_not_found', message: 'Gone'}, request_id: 'e2e'}}); + list.tcp = list.tcp.filter(row => row.id !== 'first'); + return route.fulfill({status: 204}); + } + return route.fulfill({json: path === '/connections' ? list : responses[path]}); + }); + expectLoadFailures(page, /\/connections\/gone$/); + await page.goto('/#/connections?tab=list'); + await page.getByRole('button', {name: 'Close all', exact: true}).click(); + await page.getByRole('alertdialog').getByRole('button', {name: 'Close all', exact: true}).click(); + await expect(page.locator('.rp-toast.info')).toContainText('Closed 1, skipped 1'); +}); + test('a hidden tab keeps its detail drawer closed when the window narrows', async ({page}) => { await page.goto('/#/connections?tab=list'); await page.locator('.rp-table [data-key="c-0002"]').click(); @@ -490,3 +526,31 @@ test('clearing the filter that opened the table keeps the table open', async ({p await expect(page).toHaveURL(/#\/connections\?tab=list$/); await expect(page.getByRole('grid').first()).toBeVisible(); }); + +test('an empty connection list keeps its message in view on a narrow screen', async ({page}) => { + const {api, handlers} = await mockBackend(page); + handlers['GET connections'] = async () => ({...(await api.connections()), tcp: [], udp: [], truncated: false}); + await page.setViewportSize({width: 360, height: 800}); + await page.goto('/#/connections?tab=list'); + // Inside the same sticky wrapper DataTable uses, so a table wider than the screen cannot carry it out of view. + const message = page.locator('.rp-table-empty').getByText('No matching connections', {exact: true}); + await expect(message).toBeVisible(); + const box = (await message.boundingBox())!; + expect(box.x).toBeGreaterThanOrEqual(0); + expect(box.x + box.width).toBeLessThanOrEqual(360); +}); + +test('plain connection cells truncate with a tooltip like other tables', async ({page}) => { + await page.addInitScript(() => localStorage.setItem('doona-connections-view', JSON.stringify({hidden: [], sort: null, group: 'none'}))); + await page.setViewportSize({width: 1600, height: 1000}); + await page.goto('/#/connections?tab=list'); + const grid = page.getByRole('grid', {name: 'Connections'}); + await expect(grid.locator('[role="row"][data-key]').first()).toBeVisible(); + const headers = await grid.getByRole('columnheader').allTextContents(); + const row = grid.locator('[role="row"][data-key]').first().locator('[role="rowheader"], [role="gridcell"]'); + for (const column of ['State', 'Download']) { + const index = headers.findIndex(text => text.trim() === column); + expect(index, column).toBeGreaterThanOrEqual(0); + await expect(row.nth(index).locator('.rp-truncate')).toHaveCount(1); + } +}); diff --git a/e2e/contrast.spec.ts b/e2e/contrast.spec.ts index 9353a681..f0180988 100644 --- a/e2e/contrast.spec.ts +++ b/e2e/contrast.spec.ts @@ -1,7 +1,8 @@ import {expect, test} from './fixtures'; import type {PaletteId} from '../src/shell/preferences'; -// Every palette, both schemes: the accent as text on the base and surface, text on an accent fill, and body text. +// Every palette, both schemes: the accent and the status tones as text on the base and surface, text on an accent fill, +// and body text. // Palettes keep their official values, so a failing pair is fixed by the token a use reads, never by a new colour. // Glass is left out: its surfaces are translucent over a gradient. Kary's own light text on its light base is 4.1:1. const palettes = { @@ -17,17 +18,23 @@ const palettes = { 'arco/arco': 1, 'semi/semi': 1 } satisfies Record; -// Kary's light accent text falls back to that same body text. -const known = new Set(['kary/kary light text on base', 'kary/kary light accent text on base', 'kary/kary light accent text on surface']); +const roles = ['accent', 'negative', 'notice', 'positive', 'info']; +// Kary's light tones sit at that same 4.1:1, and its accent and info text fall back to the body text; its body text on +// its own overlay is 3.9:1. Each known pair keeps a floor of its own. +const known = new Map([ + ['kary/kary light text on base', 4], + ['kary/kary light text on overlay', 3.8], + ...roles.flatMap(role => [[`kary/kary light ${role} text on base`, 4] as const, [`kary/kary light ${role} text on surface`, 4] as const]) +]); -test('accent text and accent fills reach 4.5:1 in every palette', async ({page}) => { +test('accent and status text and accent fills reach 4.5:1 in every palette', async ({page}) => { await page.goto('/#/activity'); const failures: string[] = []; for (const [palette, checked] of Object.entries(palettes)) { if (!checked) continue; for (const scheme of ['light', 'dark']) { const ratios = await page.evaluate( - ([palette, scheme]) => { + ([palette, scheme, roles]) => { const [family, flavour] = palette.split('/'); Object.assign(document.documentElement.dataset, {family, flavour, scheme}); const rgb = (value: string) => { @@ -56,16 +63,23 @@ test('accent text and accent fills reach 4.5:1 in every palette', async ({page}) return (hi + 0.05) / (lo + 0.05); }; return { - 'accent text on base': ratio('var(--rp-accent-text)', 'var(--rp-base)'), - 'accent text on surface': ratio('var(--rp-accent-text)', 'var(--rp-surface)'), + // An undefined token falls back to transparent, which measures 1:1 instead of passing as inherited text. + ...Object.fromEntries( + roles.flatMap(role => [ + [`${role} text on base`, ratio(`var(--rp-${role}-text, transparent)`, 'var(--rp-base)')], + [`${role} text on surface`, ratio(`var(--rp-${role}-text, transparent)`, 'var(--rp-surface)')] + ]) + ), 'text on accent': ratio('var(--rp-on-accent)', 'var(--rp-accent)'), - 'text on base': ratio('var(--rp-text)', 'var(--rp-base)') + 'text on base': ratio('var(--rp-text)', 'var(--rp-base)'), + // Tab and segmented labels sit on the overlay track. + 'text on overlay': ratio('var(--rp-text)', 'var(--rp-overlay)') }; }, - [palette, scheme] + [palette, scheme, roles] as const ); for (const [pair, value] of Object.entries(ratios)) - if (value < 4.5 && !known.has(`${palette} ${scheme} ${pair}`)) failures.push(`${palette} ${scheme} ${pair}: ${value.toFixed(2)}`); + if (value < (known.get(`${palette} ${scheme} ${pair}`) ?? 4.5)) failures.push(`${palette} ${scheme} ${pair}: ${value.toFixed(2)}`); } } expect(failures).toEqual([]); diff --git a/e2e/dns-actions.spec.ts b/e2e/dns-actions.spec.ts index df44864b..ad210c67 100644 --- a/e2e/dns-actions.spec.ts +++ b/e2e/dns-actions.spec.ts @@ -24,7 +24,7 @@ test('cache deletion removes one entry and flushing requires confirmation', asyn await page.getByRole('button', {name: 'Clear all cache', exact: true}).click(); await dialog.getByRole('button', {name: 'Clear all cache', exact: true}).click(); await expect(page.getByText('No cache entries', {exact: true})).toBeVisible(); - await expect(page.locator('.rp-toast.positive').last()).toContainText(`matched / deleted: ${entries.length - 1} / ${entries.length - 1}`); + await expect(page.locator('.rp-toast.positive').last()).toContainText(`matched: ${entries.length - 1}, deleted: ${entries.length - 1}`); expect(requests.filter(request => request.method() !== 'GET').map(request => [request.method(), new URL(request.url()).pathname])).toEqual([ ['DELETE', `/api/v1/dns/cache/${encodeURIComponent(entries[0].entry_id)}`], ['POST', '/api/v1/dns/cache/flush'] @@ -41,9 +41,82 @@ test('a failed cache flush preserves rows and reports failure', async ({page}) = const rows = page.getByRole('grid', {name: 'Cache', exact: true}).getByRole('rowheader'); await expect(rows).toHaveCount(entries.length); await page.getByRole('button', {name: 'Clear all cache', exact: true}).click(); - await page.getByRole('alertdialog').getByRole('button', {name: 'Clear all cache', exact: true}).click(); - await expect(page.locator('.rp-toast.negative')).toContainText('Cache is locked'); - await expect(page.locator('.rp-toast.positive')).toHaveCount(0); + const dialog = page.getByRole('alertdialog', {name: 'Clear all cache', exact: true}); + await dialog.getByRole('button', {name: 'Clear all cache', exact: true}).click(); + // The failure stays in the open dialog, where the action was confirmed. + await expect(dialog.getByRole('alert')).toContainText('Cache is locked'); + await expect(dialog.getByRole('alert')).toBeFocused(); + await expect(page.locator('.rp-toast')).toHaveCount(0); await expect(rows).toHaveText(entries.map(entry => entry.domain)); expect(requests.filter(request => request.method() === 'POST')).toHaveLength(1); + await dialog.getByRole('button', {name: 'Cancel', exact: true}).click(); + await expect(dialog).toHaveCount(0); +}); + +test('a confirmation stays open while its action is pending', async ({page}) => { + const {api, handlers} = await mockBackend(page); + let release!: () => void; + const gate = new Promise(resolve => (release = resolve)); + handlers['POST dns/cache/flush'] = async () => { + await gate; + return api.flushDnsCache(); + }; + await page.goto('/#/dns?tab=cache'); + await page.getByRole('button', {name: 'Clear all cache', exact: true}).click(); + const dialog = page.getByRole('alertdialog', {name: 'Clear all cache', exact: true}); + await dialog.getByRole('button', {name: 'Clear all cache', exact: true}).click(); + await expect(dialog.locator('.rp-spinner')).toBeVisible(); + release(); + await expect(dialog).toHaveCount(0); + await expect(page.locator('.rp-toast.positive')).toContainText('Cache cleared, matched: '); +}); + +for (const way of ['Cancel', 'Escape'] as const) { + test(`${way} leaves a confirmation whose action never answers and drops its late result`, async ({page}) => { + const {api, handlers} = await mockBackend(page); + let release!: () => void; + const gate = new Promise(resolve => (release = resolve)); + handlers['POST dns/cache/flush'] = async () => { + await gate; + return api.flushDnsCache(); + }; + await page.goto('/#/dns?tab=cache'); + const trigger = page.getByRole('button', {name: 'Clear all cache', exact: true}); + await trigger.click(); + const dialog = page.getByRole('alertdialog', {name: 'Clear all cache', exact: true}); + const flushing = page.waitForRequest(request => request.method() === 'POST'); + await dialog.getByRole('button', {name: 'Clear all cache', exact: true}).click(); + await flushing; + if (way === 'Cancel') await dialog.getByRole('button', {name: 'Cancel', exact: true}).click(); + else await page.keyboard.press('Escape'); + await expect(dialog).toHaveCount(0); + await expect(trigger).toBeEnabled(); + release(); + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + await expect(page.locator('.rp-toast')).toHaveCount(0); + }); +} + +test('Cancel on a pending flush reads the cache again, since the flush may already have landed', async ({page}) => { + const {api, handlers} = await mockBackend(page); + const entries = (await api.dnsCache()).entries; + let flushed!: () => void; + const landed = new Promise(resolve => (flushed = resolve)); + handlers['POST dns/cache/flush'] = async () => { + const value = await api.flushDnsCache(); + flushed(); + await new Promise(() => {}); + return value; + }; + await page.goto('/#/dns?tab=cache'); + const rows = page.getByRole('grid', {name: 'Cache', exact: true}).getByRole('rowheader'); + await expect(rows).toHaveCount(entries.length); + await page.getByRole('button', {name: 'Clear all cache', exact: true}).click(); + const dialog = page.getByRole('alertdialog', {name: 'Clear all cache', exact: true}); + await dialog.getByRole('button', {name: 'Clear all cache', exact: true}).click(); + await landed; + await dialog.getByRole('button', {name: 'Cancel', exact: true}).click(); + await expect(dialog).toHaveCount(0); + // The cache polls every 15 s; the empty table must come from the read that Cancel starts. + await expect(page.getByText('No cache entries', {exact: true})).toBeVisible(); }); diff --git a/e2e/dns.spec.ts b/e2e/dns.spec.ts index 1137009e..35d1ea41 100644 --- a/e2e/dns.spec.ts +++ b/e2e/dns.spec.ts @@ -1,5 +1,6 @@ import {downloadText, expect, mockBackend, test} from './fixtures'; import {createMockApi} from '../src/api/mock'; +import {ApiError} from '../src/api/error'; import {test as browserTest} from '@playwright/test'; test('a resolution record opens beside the log with its answers', async ({page}) => { @@ -174,7 +175,7 @@ test('DNS source filters send IP literals only on head and older requests', asyn next_cursor: new URL(request.url()).searchParams.has('cursor') ? null : 'older' }); await page.goto('/#/dns?tab=log'); - const source = page.getByRole('searchbox', {name: 'Source', exact: true}); + const source = page.getByRole('searchbox', {name: 'Device', exact: true}); await source.fill('2001:db8::1'); await expect.poll(() => requests.filter(request => new URL(request.url()).searchParams.get('src') === '2001:db8::1').length).toBeGreaterThan(0); await page.getByRole('button', {name: 'Load older records'}).click(); @@ -193,3 +194,51 @@ test('DNS source filters send IP literals only on head and older requests', asyn const logRequests = requests.filter(request => new URL(request.url()).pathname === '/api/v1/dns/log'); expect(logRequests.every(request => !new URL(request.url()).searchParams.get('src')?.includes('53211'))).toBe(true); }); + +test('the resolution log refresh shows its request pending', async ({page}) => { + const {api, handlers} = await mockBackend(page); + await page.goto('/#/dns?tab=log'); + await expect(page.getByRole('grid', {name: 'Resolution log'}).getByRole('rowheader').first()).toBeVisible(); + let release!: () => void; + const gate = new Promise(resolve => (release = resolve)); + handlers['GET dns/log'] = async () => { + await gate; + return api.dnsLog({}); + }; + // The top bar has a Refresh icon button of its own; this is the one in the log's toolbar. + const refresh = page.locator('.rp-toolbar').getByRole('button', {name: 'Refresh', exact: true}); + await refresh.click(); + await expect(refresh).toHaveAttribute('data-pending'); + release(); + await expect(refresh).not.toHaveAttribute('data-pending'); +}); + +test('Retry after a failed older page asks for that page again and keeps the loaded records', async ({page}) => { + const {api, capabilities, handlers} = await mockBackend(page); + capabilities.resources.dns_log.max_page_size = 2; + const seed = await api.dnsLog(); + const record = seed.records[0]; + let fail = true; + const cursors: string[] = []; + handlers['GET dns/log'] = async request => { + const cursor = new URL(request.url()).searchParams.get('cursor'); + if (cursor) { + cursors.push(cursor); + if (fail) throw new ApiError(500, 'internal', 'Older records unavailable'); + } + const ids = cursor ? ['d2', 'd1'] : ['d4', 'd3']; + return {...seed, records: ids.map(id => ({...record, id, question: {...record.question, name: id + '.test'}})), next_cursor: cursor ? null : 'older'}; + }; + await page.clock.install(); + await page.goto('/#/dns?tab=log'); + const rows = page.getByRole('grid', {name: 'Resolution log'}).getByRole('rowheader'); + await expect(rows).toHaveText(['d4.test', 'd3.test']); + await page.getByRole('button', {name: 'Load older records'}).click(); + const alert = page.getByRole('alert').filter({hasText: 'Older records unavailable'}); + await expect(alert).toBeVisible(); + fail = false; + await alert.getByRole('button', {name: 'Retry', exact: true}).click(); + await expect(rows).toHaveText(['d4.test', 'd3.test', 'd2.test', 'd1.test']); + await expect(alert).toHaveCount(0); + expect(cursors).toEqual(['older', 'older']); +}); diff --git a/e2e/honest.spec.ts b/e2e/honest.spec.ts index b1b5e515..ba4be79f 100644 --- a/e2e/honest.spec.ts +++ b/e2e/honest.spec.ts @@ -103,7 +103,7 @@ test('refresh remains pending until completion, refetches non-polling resources, const actionError = page.locator('.rp-content').getByRole('alert'); await expect(actionError).toBeVisible(); // Said once, on the page: a failed query adds no toast of its own. - await expect(actionError).toContainText('Query failed'); + await expect(actionError).toContainText('Could not run the query'); await expect(page.locator('.rp-toast.negative')).toHaveCount(0); const actionFailure = await actionError.textContent(); await refresh.click(); diff --git a/e2e/keyboard.spec.ts b/e2e/keyboard.spec.ts index ad6cb48c..b81f0c59 100644 --- a/e2e/keyboard.spec.ts +++ b/e2e/keyboard.spec.ts @@ -110,7 +110,7 @@ test('idle traffic has distinct fractional rate labels', async ({page}) => { }); await page.goto('/#/activity'); const traffic = page.getByRole('region', {name: 'Traffic', exact: true}); - await expect(traffic.locator('.recharts-yAxis-tick-labels .recharts-cartesian-axis-tick-value')).toHaveText(['0.6 KB/s', '1.2 KB/s']); + await expect(traffic.locator('.recharts-yAxis-tick-labels .recharts-cartesian-axis-tick-value')).toHaveText(['600 B/s', '1.2 KB/s']); }); test('charts are named and icon buttons show their tooltip on keyboard focus', async ({page}) => { diff --git a/e2e/manage.spec.ts b/e2e/manage.spec.ts index 7c54d55e..19366bfd 100644 --- a/e2e/manage.spec.ts +++ b/e2e/manage.spec.ts @@ -28,7 +28,7 @@ test('the backend actions card gathers reload, DNS, subscriptions, connections a test('a pairing link fills the backend form and leaves the address bar clean', async ({page}) => { await page.goto('/#/settings?api=http://127.0.0.1:9527&token=secret-token'); - await expect(page.getByLabel('Server URL', {exact: true})).toHaveValue('http://127.0.0.1:9527'); + await expect(page.getByLabel('Backend URL', {exact: true})).toHaveValue('http://127.0.0.1:9527'); await expect(page.locator('.rp-content')).toContainText('filled in from the link'); await expect(page).toHaveURL(/#\/settings$/); }); diff --git a/e2e/nodes.spec.ts b/e2e/nodes.spec.ts index 1ebe355c..4a96c034 100644 --- a/e2e/nodes.spec.ts +++ b/e2e/nodes.spec.ts @@ -190,3 +190,31 @@ test('without a node list the page shows providers alone, with no latency tab', await expect(page.getByRole('tab')).toHaveCount(0); await expect(page.locator('.rp-content').getByRole('status')).toHaveCount(0); }); + +test('while a cancelled removal is still pending, no other node dialog can submit', async ({page}) => { + const {api, handlers} = await mockBackend(page); + const node = (await api.nodes()).nodes.find(item => item.provider_id === 'inline')!; + let release!: () => void; + const gate = new Promise(resolve => (release = resolve)); + handlers[`DELETE nodes/${encodeURIComponent(node.id)}`] = async () => { + await gate; + return api.deleteNode(node.id); + }; + await page.goto('/#/nodes?provider=inline'); + await page.getByRole('button', {name: `Remove ${node.name}`, exact: true}).click(); + const confirmation = page.getByRole('alertdialog'); + const removing = page.waitForRequest(request => request.method() === 'DELETE'); + await confirmation.getByRole('button', {name: `Remove ${node.name}`, exact: true}).click(); + await removing; + await confirmation.getByRole('button', {name: 'Cancel', exact: true}).click(); + await expect(confirmation).toHaveCount(0); + await page.getByRole('button', {name: 'Paste node link', exact: true}).click(); + const dialog = page.getByRole('dialog'); + await dialog.getByLabel('Name').fill('hk-03'); + await dialog.getByLabel('Node link').fill('vless://uuid@example.com:443?security=tls#hk-03'); + const add = dialog.getByRole('button', {name: 'Add', exact: true}); + await expect(add).toBeDisabled(); + release(); + await expect(page.locator('.rp-toast.positive', {hasText: `${node.name} removed`})).toBeVisible(); + await expect(add).toBeEnabled(); +}); diff --git a/e2e/profiles.spec.ts b/e2e/profiles.spec.ts index 20c93e1b..e26d6f62 100644 --- a/e2e/profiles.spec.ts +++ b/e2e/profiles.spec.ts @@ -19,7 +19,7 @@ test('profiles add, rename, switch, and delete without losing the route', async await expect(page.locator('[name=token]')).toHaveValue(''); await page.locator('[name=token]').fill('office-secret'); await Promise.all([page.waitForEvent('load'), page.getByRole('button', {name: 'Save', exact: true}).click()]); - await page.getByRole('button', {name: 'Backend profile'}).click(); + await page.getByRole('button', {name: /Profile$/}).click(); await Promise.all([page.waitForEvent('load'), page.getByRole('option', {name: 'Home', exact: true}).click()]); await expect(page).toHaveURL(/#\/settings\?from=connections$/); await expect(page.locator('[name=token]')).toHaveValue('home-secret'); @@ -84,3 +84,27 @@ browserTest('a token draft survives persistence failure and can be retried', asy await Promise.all([page.waitForEvent('load'), page.getByRole('button', {name: 'Connect', exact: true}).click()]); expect(await page.evaluate(() => JSON.parse(localStorage.getItem('doona-profiles')!)[0].token)).toBe('retain-this-token'); }); + +test('a profile that cannot be saved says so in its dialog, again on each attempt', async ({page}) => { + await page.goto('/#/settings'); + await page.evaluate(() => { + const setItem = Storage.prototype.setItem; + Storage.prototype.setItem = function (key: string, value: string) { + if (key === 'doona-profiles') throw new DOMException('Blocked', 'SecurityError'); + return setItem.call(this, key, value); + }; + }); + await page.getByRole('button', {name: 'Add profile', exact: true}).click(); + const dialog = page.getByRole('dialog', {name: 'Add profile'}); + const name = dialog.getByRole('textbox', {name: 'Profile name'}); + await name.fill('Home'); + const save = dialog.getByRole('button', {name: 'Save', exact: true}); + const alert = dialog.getByRole('alert'); + for (let attempt = 0; attempt < 2; attempt++) { + await name.focus(); + await save.click(); + await expect(alert).toContainText('Could not save settings'); + await expect(alert).toBeFocused(); + } + await expect(page.locator('.rp-toast')).toHaveCount(0); +}); diff --git a/e2e/rules.spec.ts b/e2e/rules.spec.ts index 79422dde..f9ee1e94 100644 --- a/e2e/rules.spec.ts +++ b/e2e/rules.spec.ts @@ -1,5 +1,6 @@ import {createMockApi} from '../src/api/mock'; -import {expect, test} from './fixtures'; +import {ApiError} from '../src/api/error'; +import {expect, mockBackend, test} from './fixtures'; // Without the backend's rule dictionary the list falls back to the flows grouped by rule. test('the rule list filters by source without accumulating polls, sorted in config order', async ({page}) => { @@ -89,7 +90,7 @@ test.describe('without flow capability', () => { test('the page leaves the navigation and a deep link says so', async ({page}) => { await page.goto('/#/rules'); await expect(page.locator('.rp-nav[href="#/rules"]')).toHaveAttribute('data-unavailable', ''); - await expect(page.locator('.rp-content')).toContainText('The backend does not offer this page.'); + await expect(page.locator('.rp-content')).toContainText('This backend does not provide this page'); await expect(page.getByRole('tab')).toHaveCount(0); await expect(page).toHaveURL(/#\/rules$/); }); @@ -134,3 +135,46 @@ test('trace query mode validates ports and shows evaluations for both DNS addres await expect(page.getByRole('grid', {name: 'Rule evaluation 2', exact: true})).toBeVisible(); expect(requested).toEqual([['A'], ['AAAA']]); }); + +test('without a rule dictionary, Retry refetches the flows the distribution is built from', async ({page}) => { + const {api, capabilities, handlers} = await mockBackend(page); + capabilities.resources.rules.available = false; + let fail = true; + handlers['GET flows'] = async () => { + if (fail) throw new ApiError(500, 'internal', 'Flows unavailable'); + return api.flows(); + }; + // Frozen timers: only the retry, not the next poll, can bring the flows back. + await page.clock.install(); + await page.goto('/#/rules?tab=list'); + const panel = page.getByRole('tabpanel', {name: 'Rule list'}); + const alert = panel.getByRole('alert').filter({hasText: 'Flows unavailable'}); + await expect(alert).toBeVisible(); + fail = false; + await alert.getByRole('button', {name: 'Retry', exact: true}).click(); + await expect(alert).toHaveCount(0); + await expect(panel.locator('.rp-table [role=rowgroup]:last-child [role=row][data-key]').first()).toBeVisible(); +}); + +test('Cancel on a rule write that has landed reads the sources again, so the next write starts from it', async ({page}) => { + const {api} = await mockBackend(page); + // The page's polls of the accepted write never answer; only the backend finishes it. + await page.route('**/api/v1/operations/**', () => {}); + await page.goto('/#/rules?tab=list'); + const add = page.getByRole('button', {name: 'Add rule', exact: true}); + const dialog = page.getByRole('dialog'); + const write = async (value: string) => { + await add.click(); + await dialog.getByRole('textbox', {name: 'Values', exact: true}).fill(value); + const written = page.waitForResponse(response => response.request().method() === 'PUT'); + await dialog.getByRole('button', {name: 'Add rule', exact: true}).click(); + return written; + }; + const first = await write('example.org'); + expect(first.status()).toBe(202); + const {operation_id} = await first.json(); + await expect.poll(async () => (await api.operation(operation_id)).status).toBe('succeeded'); + await dialog.getByRole('button', {name: 'Cancel', exact: true}).click(); + await expect(dialog).toHaveCount(0); + expect((await write('example.net')).status()).toBe(202); +}); diff --git a/e2e/settings.spec.ts b/e2e/settings.spec.ts index bd8c0c66..f10b7af7 100644 --- a/e2e/settings.spec.ts +++ b/e2e/settings.spec.ts @@ -217,14 +217,14 @@ test('profile switching confirms draft loss without saving edits to the profile localStorage.setItem('doona-profile', 'a'); }, profiles); await page.goto('/#/settings'); - await page.getByLabel('Server URL', {exact: true}).fill('https://unsaved.example'); + await page.getByLabel('Backend URL', {exact: true}).fill('https://unsaved.example'); await page.locator('[name=token]').fill('unsaved-token'); - const picker = page.getByRole('button', {name: /Backend profile$/}); + const picker = page.getByRole('button', {name: /Profile$/}); await picker.click(); await page.getByRole('option', {name: /Backend B/}).click(); const confirm = page.getByRole('alertdialog', {name: 'Discard unsaved changes?'}); await confirm.getByRole('button', {name: 'Cancel', exact: true}).click(); - await expect(page.getByLabel('Server URL', {exact: true})).toHaveValue('https://unsaved.example'); + await expect(page.getByLabel('Backend URL', {exact: true})).toHaveValue('https://unsaved.example'); expect(await page.evaluate(() => localStorage.getItem('doona-profile'))).toBe('a'); await picker.click(); await page.getByRole('option', {name: /Backend B/}).click(); @@ -256,3 +256,38 @@ test('a recorder can be pinned on or off and the state light follows the backend await expect(recording.getByText(t('settings.recordingIdle'))).toHaveCount(1); expect((await api.runtimeSettings()).recording?.flows.mode).toBe('off'); }); + +test('a confirmation removed while its action is pending abandons the action', async ({page}) => { + const {api, capabilities, handlers} = await mockBackend(page); + capabilities.resources.events.available = true; + let changed!: () => void; + const generation = new Promise(resolve => (changed = resolve)); + await page.route('**/api/v1/events**', async route => { + await generation; + await route.fulfill({contentType: 'text/event-stream', body: 'event: generation.changed\ndata: {}\n\n'}); + }); + let release!: () => void; + const gate = new Promise(resolve => (release = resolve)); + handlers['POST dns/cache/flush'] = async () => { + await gate; + return api.flushDnsCache(); + }; + await page.goto('/#/settings'); + const card = page.getByRole('region', {name: 'Backend actions'}); + const trigger = card.getByRole('button', {name: 'Clear all cache', exact: true}); + await trigger.click(); + const dialog = page.getByRole('alertdialog', {name: 'Clear all cache', exact: true}); + const flushing = page.waitForRequest(request => request.method() === 'POST'); + await dialog.getByRole('button', {name: 'Clear all cache', exact: true}).click(); + const request = await flushing; + // A new generation withdraws the flush, so the button and its open dialog unmount mid-action. + capabilities.resources.dns_cache.flush = false; + changed(); + await expect(trigger).toHaveCount(0); + await expect(dialog).toHaveCount(0); + const settled = Promise.race([request.response(), page.waitForEvent('requestfailed', failed => failed === request)]); + release(); + await settled; + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + await expect(page.locator('.rp-toast')).toHaveCount(0); +}); diff --git a/src/api/client.ts b/src/api/client.ts index 69122c83..4be2987a 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -20,10 +20,10 @@ function accepted(result: {data?: Omit; respons return {...data(result), retryAfter: retryAfter(result.response)}; } -/** Base is the server root, optionally including a reverse-proxy prefix. */ // Control requests and DNS queries retry explicit transient refusals this many times. const MAX_REFUSALS = 3; +/** Base is the server root, optionally including a reverse-proxy prefix. */ export function createApi(base: string, token?: string): Api { const baseUrl = base.replace(/\/+$/, ''); const headers: Record = {Accept: 'application/json'}; @@ -89,7 +89,8 @@ export function createApi(base: string, token?: string): Api { delay = retryAfter(response); } } - // Both SSE feeds resume with Last-Event-ID and honor Retry-After; cursor expiry restarts at the head, definitive 4xx stops, and transient failures back off to 30 seconds. + // Both SSE feeds resume with Last-Event-ID and honour Retry-After; cursor expiry restarts at the head, a definitive + // 4xx stops, and transient failures back off to 30 seconds. async function subscribeStream( url: URL, lastEventId: string | undefined, diff --git a/src/api/error.test.ts b/src/api/error.test.ts new file mode 100644 index 00000000..615bcd50 --- /dev/null +++ b/src/api/error.test.ts @@ -0,0 +1,10 @@ +import {expect, it} from 'vitest'; +import {translate} from '../i18n'; +import {LocalError, errorText} from './error'; + +it('joins a local error and its detail with the colon of the active language', () => { + const error = new LocalError('ui.operationFailed', 'member refused'); + // U+FF1A is the full-width colon. + expect(errorText(error, (key, params) => translate('zh-TW', key, params))).toBe(`${translate('zh-TW', 'ui.operationFailed')}:member refused`); + expect(errorText(error, (key, params) => translate('en', key, params))).toBe('The operation did not succeed: member refused'); +}); diff --git a/src/api/error.ts b/src/api/error.ts index 4fd2cdd4..040f25a3 100644 --- a/src/api/error.ts +++ b/src/api/error.ts @@ -57,7 +57,7 @@ export class LocalError extends Error { export function errorText(error: unknown, t: Translator): string { if (error instanceof LocalError) { const text = t(error.key); - return error.detail ? `${text}: ${error.detail}` : text; + return error.detail ? t('ui.valuePair', {label: text, value: error.detail}) : text; } if (error instanceof ApiError && error.text) return t(error.text.key, error.text.params); const message = error instanceof Error ? error.message : String(error); diff --git a/src/api/mock/index.ts b/src/api/mock/index.ts index 02e7857f..e3adbede 100644 --- a/src/api/mock/index.ts +++ b/src/api/mock/index.ts @@ -13,14 +13,18 @@ export function createMockApi(): Api { const value = localStorage.getItem('doona-mock-big'); big = value !== null; if (value !== null) count = Math.max(0, Math.floor(Number(value) || 0)); - } catch {} + } catch { + /* Storage can be unavailable. */ + } let capabilities = fullCapabilities; let profile: string | null = null; try { profile = localStorage.getItem('doona-mock-profile'); if (profile === 'base') capabilities = capabilitiesBase; if (profile === 'm1') capabilities = capabilitiesM1; - } catch {} + } catch { + /* Storage can be unavailable. */ + } const runtime = createRuntime(capabilities, big); const configuration = createConfiguration( capabilities, diff --git a/src/api/rings.ts b/src/api/rings.ts index e62209fd..7174cd60 100644 --- a/src/api/rings.ts +++ b/src/api/rings.ts @@ -1,7 +1,8 @@ import {useEffect, useSyncExternalStore} from 'react'; import {readProfiles} from './profiles'; -// Extend the backend's ten-minute history with session polls: one hour at poll cadence, then a week of minute buckets persisted per profile. +// Session polls extend the backend's ten-minute history: an hour at poll cadence, a week of stored minute buckets +// per profile. export type Timed = {time: number}; export type Rings = {fine: T[]; coarse: T[]}; // How a bucket summarises its samples: the mean of a rate, the peak of a count. @@ -141,11 +142,14 @@ export function record(name: string, sample: T | undefined, fol } return store.rings; } +// For tests. export function resetRings() { for (const store of stores.values()) { try { localStorage.removeItem(store.key); - } catch {} + } catch { + /* Storage can be unavailable. */ + } } stores.clear(); resets++; diff --git a/src/api/selectors.ts b/src/api/selectors.ts index b449aad5..dcf43774 100644 --- a/src/api/selectors.ts +++ b/src/api/selectors.ts @@ -3,7 +3,7 @@ import {formatNumber, LOCALE, readLang} from '../i18n'; import type {ApiEvent, Connection, ConnectionList, EventKind, Group, GroupSummary, HealthObservation, LogLevel, Node, Runtime, RuntimeOutbounds} from './model'; import {addU64, parseU64, pctU64} from './u64'; -// Backends expose different TCP data probes, so rank by warmth, measurement cost, then IPv4; unknown future values sort last. +// Backends offer different TCP data probes: rank by warmth, measurement cost, then IPv4; unknown values sort last. const warmthRank: Record = {warm: 0, unknown: 1, mixed: 2, cold: 3}; const measurementRank: Record = { tcp_connect: 0, @@ -71,6 +71,8 @@ export const lifecycleStates: Record = { failed: 'lifecycle.failed' }; export const lifecycleTone = (state: Runtime['lifecycle']['state'] | undefined) => (state === 'running' ? 'ok' : state === 'failed' ? 'err' : 'warn'); +// Nothing closed is a failure; some skipped (already gone or not closable) is worth a look. +export const closedAllTone = (tally: {closed: number; skipped: number}) => (!tally.closed ? 'negative' : tally.skipped ? 'info' : 'positive'); export const connectionStates: Record = { observed: 'conn.state.observed', routing: 'conn.state.routing', diff --git a/src/api/u64.test.ts b/src/api/u64.test.ts index 210ac0c8..0d61f92f 100644 --- a/src/api/u64.test.ts +++ b/src/api/u64.test.ts @@ -1,5 +1,6 @@ import {describe, expect, it} from 'vitest'; -import {addU64, formatBytes, formatRate, parseU64, pctU64} from './u64'; +import {addU64, parseU64, pctU64} from './u64'; +import {formatBytes, formatRate} from '../i18n/format'; describe('UInt64 counters', () => { it('preserves exact counters and carries above 2^53', () => { @@ -12,28 +13,28 @@ describe('UInt64 counters', () => { it('keeps unknown separate from zero', () => { expect(parseU64(null)).toBeNull(); expect(parseU64('0')).toBe(0n); - expect(formatBytes(null)).toBe('—'); - expect(formatRate(null)).toBe('—'); - expect(formatBytes('0')).toBe('0 B'); + expect(formatBytes(null, 'en')).toBe('—'); + expect(formatRate(null, 'en')).toBe('—'); + expect(formatBytes('0', 'en')).toBe('0 B'); expect(addU64('10', null)).toBeNull(); expect(pctU64(null, '10')).toBeNull(); expect(pctU64('1', null)).toBeNull(); expect(pctU64('0', '0')).toBe(0); }); it('formats decimal units without floating-point counters', () => { - expect(formatBytes('1100000000')).toBe('1.1 GB'); - expect(formatRate('3400000')).toBe('3.4 MB/s'); - expect(formatRate('257000')).toBe('257 KB/s'); - expect(formatBytes('9007199254740993')).toBe('9 PB'); - expect(formatBytes('18446744073709551615')).toBe('18 EB'); - expect(formatBytes(9999500000000000n)).toBe('10 PB'); + expect(formatBytes('1100000000', 'en')).toBe('1.1 GB'); + expect(formatRate('3400000', 'en')).toBe('3.4 MB/s'); + expect(formatRate('257000', 'en')).toBe('257 KB/s'); + expect(formatBytes('9007199254740993', 'en')).toBe('9 PB'); + expect(formatBytes('18446744073709551615', 'en')).toBe('18 EB'); + expect(formatBytes(9999500000000000n, 'en')).toBe('10 PB'); }); it.each(['-1', '01', '', '1.5', '1e3', '18446744073709551616'])('rejects noncanonical or out-of-range counter %s', value => { expect(parseU64(value)).toBeNull(); }); it('renders malformed counters as unknown and propagates them through aggregates', () => { - expect(formatBytes('broken')).toBe('—'); - expect(formatRate('broken')).toBe('—'); + expect(formatBytes('broken', 'en')).toBe('—'); + expect(formatRate('broken', 'en')).toBe('—'); expect(addU64('1', 'broken')).toBeNull(); expect(pctU64('broken', '10')).toBeNull(); }); diff --git a/src/api/u64.ts b/src/api/u64.ts index 24be0ee1..80ce96f0 100644 --- a/src/api/u64.ts +++ b/src/api/u64.ts @@ -35,26 +35,5 @@ export function pctU64(part: U64, whole: U64): number | null { return Number(((p > w ? w : p) * 10000n + w / 2n) / w) / 100; } -export function formatBytes(input: U64): string { - const value = valueOf(input); - if (value === null) return '—'; - if (value === 0n) return '0 B'; - const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB']; - let unit = 0, - scale = 1n; - while (unit < units.length - 1 && value >= scale * 1000n) { - unit++; - scale *= 1000n; - } - const tenths = (value * 10n + scale / 2n) / scale; - const text = unit > 0 && value < scale * 10n && tenths % 10n !== 0n ? `${tenths / 10n}.${tenths % 10n}` : String((value + scale / 2n) / scale); - return `${text} ${units[unit]}`; -} - -export function formatRate(input: U64): string { - const text = formatBytes(input); - return text === '—' ? text : text + '/s'; -} - /** Round displayed milliseconds to 0.1 below 10 ms and whole milliseconds otherwise. */ export const millis = (value: number): number => (value < 10 ? Math.round(value * 10) / 10 : Math.round(value)); diff --git a/src/dae/groups.ts b/src/dae/groups.ts index e9ff2942..08299d37 100644 --- a/src/dae/groups.ts +++ b/src/dae/groups.ts @@ -238,7 +238,7 @@ export const groupAdmits = (filters: string[], node: FilterNode) => compileFilte export type GroupChange = | {kind: 'addNode' | 'removeNode' | 'addSubscription' | 'removeSubscription'; group: string; value: string} | {kind: 'createGroup'; group: string; policy: string}; -export function applyChange(text: string, change: GroupChange): string { +function applyChange(text: string, change: GroupChange): string { switch (change.kind) { case 'addNode': return addNamesToGroup(text, change.group, [change.value]); diff --git a/src/dae/templates.ts b/src/dae/templates.ts index 22d02fd5..e0fec588 100644 --- a/src/dae/templates.ts +++ b/src/dae/templates.ts @@ -21,7 +21,8 @@ const media = (target: string) => [ ]; const gfw = (target: string) => ['# ProxyGFWlist', `domain(geosite:gfw) -> ${target}`]; -// Selector groups include nested groups and all proxy nodes. Exclude injected direct/block nodes because an unfiltered honk group would select them too. +// Selector groups include nested groups and all proxy nodes. Exclude injected direct/block nodes because an +// unfiltered honk group would select them too. type GroupSpec = {name: string; label: string; lines: string[]}; const everyNode = "filter: !name('direct', 'block')"; const selectGroup = (name: string, label: string, nested: string[], fallback = nested[0]): GroupSpec => ({ @@ -58,7 +59,8 @@ const auto: GroupSpec = {name: 'auto', label: templateText.auto, lines: [everyNo const regions = (['hk', 'jp', 'us', 'tw', 'sg', 'kr'] as const).map(id => region(id, templateText[id][0], templateText[id][1])); const service = (name: string, label: string, nested: string[] = ['proxy', 'auto'], fallback?: string) => selectGroup(name, label, nested, fallback); -// Preserve ACL4SSR rule order using dae's default geosite/geoip data. honk groups cannot contain direct, so DIRECT services remain direct and {group} names the file's first group. +// Preserve ACL4SSR rule order using dae's default geosite/geoip data. honk groups cannot contain direct, so DIRECT +// services remain direct and {group} names the file's first group. export const templates: Record = { global: {rules: [...preset], fallback: '{group}', groups: []}, bypass: {rules: [...preset, ...ads, ...chinaVendors, ...china], fallback: '{group}', groups: []}, diff --git a/src/features/activity/Activity.tsx b/src/features/activity/Activity.tsx index 021e55ee..28e1e77c 100644 --- a/src/features/activity/Activity.tsx +++ b/src/features/activity/Activity.tsx @@ -3,7 +3,7 @@ import Upload from '../../ui/icons/Upload'; import LinkIcon from '../../ui/icons/Link'; import Data from '../../ui/icons/Data'; import {useT} from '../../i18n'; -import {CardLink, Segmented, Light, ErrorMessage, Loading, Empty, Link} from '../../ui/ui'; +import {Card, CardLink, Segmented, Light, ErrorMessage, Loading, Empty, Link} from '../../ui/ui'; import {href} from '../../shell/route'; import {AreaChart, Legend, Spark} from '../../ui/charts'; import {ModeCards} from './ModeSwitch'; @@ -18,7 +18,7 @@ export function Activity() { const vm = useActivity(); const {p, locale, range, setRange, traffic, spark, chartRate, memorySeries, memoryBytes, notices} = vm; const alert = vm.error && ; - if (!vm.ready) return alert || {t('act.loading')}; + if (!vm.ready) return alert || {t('ui.loading')}; return ( <> {alert} @@ -99,11 +99,9 @@ export function Activity() {
-
-
-

- {t('act.traffic')} -

+ -
+ } + > {vm.history.error && vm.history.state !== 'ready' ? ( - + ) : vm.history.state === 'unavailable' ? (
- {t('act.noHistory')} + {t('act.noHistory')}
) : vm.history.state === 'loading' ? (
- {t('act.loading')} + {t('ui.loading')}
) : vm.history.state === 'empty' ? (
@@ -147,23 +146,22 @@ export function Activity() { /> )} -
+
-
-
-

- {t('act.memory')} -

+ {t('act.viewDetails')} -
+ } + > {vm.memoryState.error ? ( - + ) : vm.memoryState.state === 'ready' ? ( <> @@ -186,7 +184,7 @@ export function Activity() { {t('act.sampling')}
)} - + diff --git a/src/features/activity/ModeSwitch.tsx b/src/features/activity/ModeSwitch.tsx index e1b743b5..44a02441 100644 --- a/src/features/activity/ModeSwitch.tsx +++ b/src/features/activity/ModeSwitch.tsx @@ -14,6 +14,7 @@ type ModeCardsModel = { targets: Array<{id: string; label: string}>; busy: boolean; error: Error | null; + retry: () => void; pick: (mode: string) => void; pickTarget: (target: string) => void; apply: () => void; @@ -23,7 +24,7 @@ export function ModeCards({model: vm}: {model: ModeCardsModel}) { const t = useT(); return ( <> - {vm.error && } + {vm.error && }
diff --git a/src/features/activity/Notices.tsx b/src/features/activity/Notices.tsx index 976908c8..78e3fa52 100644 --- a/src/features/activity/Notices.tsx +++ b/src/features/activity/Notices.tsx @@ -2,6 +2,7 @@ type NoticesModel = { rows: Array<{id: string; tone: 'warn' | 'info'; kindText: string; summaryText: string}>; total: number; error: Error | null; + retry: () => void; loading: boolean; empty: string; }; @@ -9,7 +10,7 @@ import {useT} from '../../i18n'; import {href} from '../../shell/route'; import {Empty, ErrorMessage, Light, Link, Loading, TextTooltip} from '../../ui/ui'; -export function Notices({rows, total, error, loading, empty}: NoticesModel) { +export function Notices({rows, total, error, retry, loading, empty}: NoticesModel) { const t = useT(); return (
@@ -25,7 +26,7 @@ export function Notices({rows, total, error, loading, empty}: NoticesModel) { {t('act.viewAll')}
- {error && } + {error && } {loading ? (
diff --git a/src/features/activity/OutboundsCard.tsx b/src/features/activity/OutboundsCard.tsx index c163b167..3b565d7f 100644 --- a/src/features/activity/OutboundsCard.tsx +++ b/src/features/activity/OutboundsCard.tsx @@ -6,7 +6,7 @@ import {useOutboundsCard} from './useOutboundsCard'; // Outbound usage polls on its own, so its tick does not re-render the charts beside it. export function OutboundsCard() { const t = useT(); - const {view, state, error} = useOutboundsCard(); + const {view, state, error, retry} = useOutboundsCard(); return (
@@ -16,14 +16,14 @@ export function OutboundsCard() {
{error && state !== 'ready' ? ( - + ) : state === 'unavailable' ? (
- {t('act.noOutbounds')} + {t('act.noOutbounds')}
) : state === 'loading' ? (
- {t('act.loading')} + {t('ui.loading')}
) : state === 'empty' ? (
diff --git a/src/features/activity/RankingCard.tsx b/src/features/activity/RankingCard.tsx index 93a05e64..10664931 100644 --- a/src/features/activity/RankingCard.tsx +++ b/src/features/activity/RankingCard.tsx @@ -6,7 +6,7 @@ import {useRankingCard} from './useRankingCard'; // re-renders this card alone, not the traffic charts or the tiles beside it. export function RankingCard() { const t = useT(); - const {ref, by, setBy, rows, state, error, truncated} = useRankingCard(); + const {ref, by, setBy, rows, state, error, retry, truncated} = useRankingCard(); return (
@@ -23,7 +23,7 @@ export function RankingCard() { ]} />
- {error && } + {error && } {truncated && ( {t('act.truncated')} @@ -31,11 +31,11 @@ export function RankingCard() { )} {state === 'error' ? null : state === 'loading' ? (
- {t('act.loading')} + {t('ui.loading')}
) : state === 'unavailable' ? (
- {t('shell.notOfferedShort')} + {t('act.noConnections')}
) : state === 'empty' ? (
diff --git a/src/features/activity/messages.ts b/src/features/activity/messages.ts index 9dfbf403..c299a1f5 100644 --- a/src/features/activity/messages.ts +++ b/src/features/activity/messages.ts @@ -3,9 +3,10 @@ import {defineMessages} from '../../i18n/defineMessages'; export const messages = defineMessages({ 'zh-TW': { 'act.noOutbounds': '此後端不提供出站統計', + 'act.noConnections': '此後端不提供連線', 'act.emptyHistory': '尚無歷史樣本', 'act.historyRange': '歷史範圍', - 'act.noHistory': '此後端不提供歷史', + 'act.noHistory': '此後端不提供歷史資料', 'act.unknown': '未知', 'act.latency': '延遲', 'act.upload': '上傳', @@ -28,11 +29,10 @@ export const messages = defineMessages({ 'mode.global': '全域', 'act.apply': '套用', 'act.modeApplied': '出站模式已寫入組態並重載:{mode}', - 'act.modeInvalid': '驗證發現 {n} 個錯誤,未寫入', 'act.modeNoRouting': '主組態未包含 routing 區段', 'act.modeInterleaved': '一般規則位於 must 規則之前,無法安全切換出站模式。', 'act.modeNeedsWrite': '需要可寫入的主組態', - 'act.modeUnavailable': '後端未提供', + 'act.modeUnavailable': '此後端不提供', 'act.viewAll': '查看全部', 'act.noticeRepeat': '重複 {n} 次', 'act.since': '自 {t} 起', @@ -50,7 +50,6 @@ export const messages = defineMessages({ 'act.issues': '通知與問題', 'act.noIssues': '目前沒有需要處理的問題', 'act.unavailable': '無法使用', - 'act.loading': '載入中…', 'act.d7': '7 天', 'act.rankingScope': '依目前可見連線的下載量排序,佔比以全部可見資料計算。', 'act.rankingTruncated': '連線清單已截斷,排行僅涵蓋已取得的資料。', @@ -58,9 +57,10 @@ export const messages = defineMessages({ }, 'zh-CN': { 'act.noOutbounds': '此后端不提供出站统计', - 'act.emptyHistory': '尚无历史样本', + 'act.noConnections': '此后端不提供连接', + 'act.emptyHistory': '暂无历史样本', 'act.historyRange': '历史范围', - 'act.noHistory': '此后端不提供历史', + 'act.noHistory': '此后端不提供历史数据', 'act.unknown': '未知', 'act.latency': '延迟', 'act.upload': '上传', @@ -83,11 +83,10 @@ export const messages = defineMessages({ 'mode.global': '全局', 'act.apply': '应用', 'act.modeApplied': '出站模式已写入配置并重载:{mode}', - 'act.modeInvalid': '校验发现 {n} 个错误,未写入', 'act.modeNoRouting': '主配置未包含 routing 区段', 'act.modeInterleaved': '普通规则位于 must 规则之前,无法安全切换出站模式。', 'act.modeNeedsWrite': '需要可写入的主配置', - 'act.modeUnavailable': '后端未提供', + 'act.modeUnavailable': '此后端不提供', 'act.viewAll': '查看全部', 'act.noticeRepeat': '重复 {n} 次', 'act.since': '自 {t} 起', @@ -105,14 +104,14 @@ export const messages = defineMessages({ 'act.issues': '通知与问题', 'act.noIssues': '当前没有需要处理的问题', 'act.unavailable': '不可用', - 'act.loading': '加载中…', 'act.d7': '7 天', 'act.rankingScope': '按当前可见连接的下载量排序,占比以全部可见数据计算。', - 'act.rankingTruncated': '连接列表已截断,排名仅涵盖已获取的数据。', - 'act.rankingEmpty': '暂无可排名的连接数据' + 'act.rankingTruncated': '连接列表已截断,排行仅涵盖已获取的数据。', + 'act.rankingEmpty': '暂无可排行的连接数据' }, en: { 'act.noOutbounds': 'This backend does not provide outbound counters', + 'act.noConnections': 'This backend does not provide connections', 'act.emptyHistory': 'No history samples yet', 'act.historyRange': 'History range', 'act.noHistory': 'This backend does not provide history', @@ -130,7 +129,7 @@ export const messages = defineMessages({ 'act.memoryHigh': 'High', 'act.memoryNearLimit': 'Near limit', 'act.traffic': 'Traffic', - 'act.viewDetails': 'Details', + 'act.viewDetails': 'View details', 'act.mode': 'Outbound mode', 'act.global': 'Global target', 'mode.rule': 'Rule', @@ -138,20 +137,19 @@ export const messages = defineMessages({ 'mode.global': 'Global', 'act.apply': 'Apply', 'act.modeApplied': 'Outbound mode written to the configuration and reloaded: {mode}', - 'act.modeInvalid': {one: 'Validation found {n} error; nothing written', other: 'Validation found {n} errors; nothing written'}, 'act.modeNoRouting': 'The main configuration has no routing section', 'act.modeInterleaved': 'Ordinary rules precede must rules; the outbound mode cannot be changed safely.', 'act.modeNeedsWrite': 'Needs a writable main configuration', - 'act.modeUnavailable': 'Not offered by the backend', + 'act.modeUnavailable': 'Not provided by this backend', 'act.viewAll': 'View all', 'act.noticeRepeat': {one: '{n} time', other: '{n} times'}, 'act.since': 'Since {t}', 'act.good': 'Good', 'act.live': 'Live', 'act.m10': '10 min', - 'act.h1': '1H', - 'act.h6': '6H', - 'act.h24': '24H', + 'act.h1': '1 h', + 'act.h6': '6 h', + 'act.h24': '24 h', 'act.outUsage': 'Outbound downloads', 'act.topDevices': 'Top traffic', 'act.devices': 'Devices', @@ -160,8 +158,7 @@ export const messages = defineMessages({ 'act.issues': 'Notifications and issues', 'act.noIssues': 'No issues require attention', 'act.unavailable': 'Unavailable', - 'act.loading': 'Loading...', - 'act.d7': '7D', + 'act.d7': '7 d', 'act.rankingScope': 'Ranked by download totals for visible connections. Shares use all visible data.', 'act.rankingTruncated': 'The connection list is truncated. Rankings cover only the retrieved data.', 'act.rankingEmpty': 'No connection data to rank' diff --git a/src/features/activity/traffic.ts b/src/features/activity/traffic.ts index b9f2bb41..a7720071 100644 --- a/src/features/activity/traffic.ts +++ b/src/features/activity/traffic.ts @@ -3,7 +3,8 @@ import {mean, useRings, window, type Fold, type Rings} from '../../api/rings'; import {parseU64} from '../../api/u64'; type TrafficSample = {time: number; up: number | null; down: number | null; connections: number | null}; -// Windows are seconds; live is two minutes at full resolution. Backend history covers ten minutes, then session polls provide minute buckets for longer spans. +// Windows are seconds; live is two minutes at full resolution. Backend history covers ten minutes, then session polls +// provide minute buckets for longer spans. export const trafficWindows: Record = {live: 120, m10: 600, h1: 3600, h6: 21600, h24: 86400, d7: 604800}; const rate = (value: string | null | undefined) => { const parsed = parseU64(value ?? null); diff --git a/src/features/activity/useActivity.ts b/src/features/activity/useActivity.ts index f3c63886..a552fc22 100644 --- a/src/features/activity/useActivity.ts +++ b/src/features/activity/useActivity.ts @@ -1,8 +1,7 @@ import {useCallback, useMemo, useState} from 'react'; import {useCapabilities, useRuntime, useRuntimeMemory, useTrafficHistory} from '../../store'; -import {formatBytes} from '../../api/u64'; import {useT, useLang, LOCALE} from '../../i18n'; -import {fmtRate} from '../../i18n/format'; +import {formatBytes, formatRate} from '../../i18n/format'; import {usePalette} from '../../ui/charts'; import {useMemorySeries} from './useMemorySeries'; import {historyTrafficSamples, trafficWindow, trafficWindows, useTrafficSamples} from './traffic'; @@ -43,8 +42,9 @@ export function useActivity() { ); const trafficBounds = useMemo(() => ({since: series.since, until: series.until}), [series.since, series.until]); const memoryBounds = useMemo(() => ({since: memoryHistory.since, until: memoryHistory.until}), [memoryHistory.since, memoryHistory.until]); - const chartRate = useCallback((value: number | null | undefined) => fmtRate(value, locale, t), [locale, t]); - const memoryBytes = useCallback((value: number | null | undefined) => formatBytes(value == null ? null : BigInt(Math.round(value))), []); + // Traffic series are in KB/s. + const chartRate = useCallback((value: number | null | undefined) => formatRate(value == null ? null : value * 1000, locale), [locale]); + const memoryBytes = useCallback((value: number | null | undefined) => formatBytes(value ?? null, locale), [locale]); const view = useMemo( () => activityView(runtime.data, memory.data, t, resources?.runtime.available, locale), [runtime.data, memory.data, t, resources?.runtime.available, locale] @@ -77,10 +77,12 @@ export function useActivity() { showMemory: !!resources?.runtime_memory.available, history: { error: history.error, + retry: history.refetch, state: trafficState(series, resources?.traffic_history.available, !!history.data, offered(resources, 'runtime', {whileLoading: false})) }, memoryState: { error: memory.error ?? memoryHistory.error, + retry: memory.error ? memory.refetch : memoryHistory.retry, state: memoryHistory.samples.length > 1 ? 'ready' : resources?.runtime_memory.available === false ? 'unavailable' : 'loading' } }; diff --git a/src/features/activity/useMemorySeries.ts b/src/features/activity/useMemorySeries.ts index 5ab952f9..d1323f1c 100644 --- a/src/features/activity/useMemorySeries.ts +++ b/src/features/activity/useMemorySeries.ts @@ -11,5 +11,5 @@ export function useMemorySeries(capabilities: Capabilities | undefined, memory: const windowSeconds = advertised ? Math.min(600, capabilities?.resources.memory_history.max_window_seconds ?? 600) : 600; const converted = useMemo(() => (history.data ? historySamples(history.data) : []), [history.data]); const series = useMemo(() => memoryWindow(rings, advertised ? converted : [], windowSeconds), [rings, converted, advertised, windowSeconds]); - return {...series, error: advertised ? history.error : undefined}; + return {...series, error: advertised ? history.error : undefined, retry: history.refetch}; } diff --git a/src/features/activity/useMode.ts b/src/features/activity/useMode.ts index b5813681..b7df5eed 100644 --- a/src/features/activity/useMode.ts +++ b/src/features/activity/useMode.ts @@ -12,7 +12,7 @@ export function useMode() { const t = useT(); const resources = useCapabilities().data?.resources; const groups = useGroups(offered(resources, 'groups', {whileLoading: false})); - const {main, writable, busy, error, apply: write} = useMainSourceEdit(); + const {main, writable, busy, error, retry, apply: write} = useMainSourceEdit(); const content = main?.content; const current = useMemo(() => (content == null ? {mode: 'rule'} : readMode(content)), [content]); const [staged, setStaged] = useState(null); @@ -27,12 +27,13 @@ export function useMode() { setStaged(current => (current === submitted ? null : current)); toast('positive', t('act.modeApplied', {mode: t(modeLabels[submitted.mode])})); } - const problem = editProblem(result, 'act.modeInvalid', t); + const problem = editProblem(result, t); if (problem) toast('negative', problem); }; return { ...view, error, + retry, busy, pick: (mode: string) => { if (mode === 'global') setStaged({mode, target: view.target}); diff --git a/src/features/activity/useNotices.ts b/src/features/activity/useNotices.ts index e18153b7..e056af24 100644 --- a/src/features/activity/useNotices.ts +++ b/src/features/activity/useNotices.ts @@ -2,7 +2,7 @@ import {useMemo, useSyncExternalStore} from 'react'; import {getApi} from '../../api'; import type {Api} from '../../api/api'; import type {ApiEvent} from '../../api/model'; -import {EVENT_FEED_LIMIT} from '../../store'; +import {EVENT_FEED_LIMIT, refetchAll} from '../../store'; import {useEvents} from '../../store/events'; import {createFeed} from '../../store/feed'; import {useT} from '../../i18n'; @@ -29,6 +29,8 @@ export function useNotices() { rows, total: snapshot.records.length, error: feed.error, + // A failed stream reopens once the capabilities are read again. + retry: () => void refetchAll(), loading: !feed.error && feed.available === null, empty: t(feed.available === false ? 'event.unavailable' : 'act.noIssues') }; diff --git a/src/features/activity/useOutboundsCard.ts b/src/features/activity/useOutboundsCard.ts index f16bc023..75d0d9e5 100644 --- a/src/features/activity/useOutboundsCard.ts +++ b/src/features/activity/useOutboundsCard.ts @@ -12,5 +12,5 @@ export function useOutboundsCard() { const outbounds = useRuntimeOutbounds(available === true); const view = useMemo(() => activityOutbounds(outbounds.data, locale, p, t), [outbounds.data, locale, p, t]); const state = available === false ? 'unavailable' : !outbounds.data ? 'loading' : !view.rows.length ? 'empty' : 'ready'; - return {view, state, error: outbounds.error}; + return {view, state, error: outbounds.error, retry: outbounds.refetch}; } diff --git a/src/features/activity/useRankingCard.ts b/src/features/activity/useRankingCard.ts index d55597eb..fa1db860 100644 --- a/src/features/activity/useRankingCard.ts +++ b/src/features/activity/useRankingCard.ts @@ -1,12 +1,13 @@ import {useCallback, useMemo, useState} from 'react'; import {useCapabilities, useConnections} from '../../store'; -import {useT} from '../../i18n'; +import {LOCALE, useLang, useT} from '../../i18n'; import {usePalette} from '../../ui/charts'; import {activityRanking} from './view'; // The poll runs only while the card is near the viewport; off screen it is paused and keeps its last list. export function useRankingCard() { const t = useT(); + const locale = LOCALE[useLang()]; const p = usePalette(); const [by, setBy] = useState('dev'); const available = useCapabilities().data?.resources.connections.available; @@ -21,7 +22,16 @@ export function useRankingCard() { const [loaded, setLoaded] = useState(false); const connections = useConnections(undefined, available === true, !near && loaded); if (connections.data && !loaded) setLoaded(true); - const rows = useMemo(() => activityRanking(connections.data, by, p, t), [connections.data, by, p, t]); + const rows = useMemo(() => activityRanking(connections.data, by, p, locale, t), [connections.data, by, p, locale, t]); const state = connections.data ? (rows.length ? 'ready' : 'empty') : connections.error ? 'error' : available === true ? 'loading' : 'unavailable'; - return {ref, by, setBy, rows, state, error: connections.data ? undefined : connections.error, truncated: !!connections.data?.truncated}; + return { + ref, + by, + setBy, + rows, + state, + error: connections.data ? undefined : connections.error, + retry: connections.refetch, + truncated: !!connections.data?.truncated + }; } diff --git a/src/features/activity/view.test.ts b/src/features/activity/view.test.ts index 3892ef0e..2d697116 100644 --- a/src/features/activity/view.test.ts +++ b/src/features/activity/view.test.ts @@ -18,7 +18,7 @@ it('distinguishes missing metrics from zero and keeps block traffic separate fro expect(model.connections).toBe('0'); expect(model.memoryBadge?.tone).toBe('err'); expect(activityOutbounds(runtimeOutbounds, 'en-US', colors, t).rows.find(row => row.name === t('ui.block'))?.color).toBe('red'); - const ranking = activityRanking(connections, 'dev', colors, t); + const ranking = activityRanking(connections, 'dev', colors, 'en', t); expect(ranking[0].pct).toBeGreaterThan(ranking[1].pct); }); @@ -79,5 +79,5 @@ it('distinguishes unsupported runtime from loading without hiding independent me const view = activityView(undefined, runtimeMemory, t, false); expect(view.status.text).toBe(t('act.modeUnavailable')); expect(view.rss).not.toBe('—'); - expect(activityView(undefined, undefined, t).status.text).toBe(t('act.loading')); + expect(activityView(undefined, undefined, t).status.text).toBe(t('ui.loading')); }); diff --git a/src/features/activity/view.ts b/src/features/activity/view.ts index 0ffe538e..c3704a3f 100644 --- a/src/features/activity/view.ts +++ b/src/features/activity/view.ts @@ -11,9 +11,9 @@ import { routineGap, shortId } from '../../api/selectors'; -import {localTime} from '../../i18n/format'; +import {localTime, formatBytes, formatRate, formatLatency} from '../../i18n/format'; import {formatNumber, type Translator as LabelFn} from '../../i18n'; -import {formatBytes, formatRate, millis, pctU64} from '../../api/u64'; +import {pctU64} from '../../api/u64'; import {connectionRanking} from './ranking'; import {sameMode, type OutboundMode} from './mode'; @@ -44,7 +44,7 @@ export function modeView( export const interestingNotice = (event: ApiEvent) => event.event !== 'runtime.updated' && event.event !== 'flow.updated' && !routineGap(event); // The home card holds this many rows; the rest is one click away on the events page. -export const NOTICE_ROWS = 8; +const NOTICE_ROWS = 8; // A run of identical notices (same kind, same resource, same reason) folds into one row with a count, so a // backend dropping records at pace does not push everything else off the card. Two notices that differ in // any of those never fold: a failure must not disappear behind a neighbouring success. @@ -88,7 +88,6 @@ export function trafficState(series: {down: Array; up: Array(); for (const node of nodes) counts.set(node.name, (counts.get(node.name) ?? 0) + 1); @@ -114,7 +113,7 @@ export function nodeView(nodes: Node[], chosen: string, t: LabelFn) { big: options.length > 12, id: node?.id ?? '', name: node?.name ?? '', - latency: node?.alive && node.tcp !== undefined ? t('ui.latency', {n: millis(node.tcp)}) : '—', + latency: node?.alive && node.tcp !== undefined ? formatLatency(node.tcp, t) : '—', tone: node?.alive ? ('ok' as const) : node?.unavailable ? ('err' as const) : ('muted' as const), status: t(node?.alive ? 'act.good' : node?.unavailable ? 'act.unavailable' : 'act.unknown'), healthError: node?.healthError @@ -125,12 +124,12 @@ export function activityView(runtime: Runtime | undefined, memory: RuntimeMemory return { status: { tone: lifecycleTone(runtime?.lifecycle.state) as 'ok' | 'err' | 'warn', - text: runtime ? t(lifecycleStates[runtime.lifecycle.state]) : t(runtimeAvailable === false ? 'act.modeUnavailable' : 'act.loading') + text: runtime ? t(lifecycleStates[runtime.lifecycle.state]) : t(runtimeAvailable === false ? 'act.modeUnavailable' : 'ui.loading') }, - download: formatRate(runtime?.traffic.rates?.download_bytes_per_second ?? null), - upload: formatRate(runtime?.traffic.rates?.upload_bytes_per_second ?? null), + download: formatRate(runtime?.traffic.rates?.download_bytes_per_second ?? null, locale), + upload: formatRate(runtime?.traffic.rates?.upload_bytes_per_second ?? null, locale), connections: runtime?.traffic.connections.total == null ? '—' : formatNumber(runtime.traffic.connections.total, locale), - rss: formatBytes(memory?.process?.rss_bytes ?? null), + rss: formatBytes(memory?.process?.rss_bytes ?? null, locale), memoryBadge: percent === null ? null @@ -145,20 +144,20 @@ export function activityOutbounds(outbounds: RuntimeOutbounds | undefined, local const usage = outboundUsage(outbounds); return { since: outbounds ? t('act.since', {t: localTime(outbounds.counter_since, locale)}) : '', - total: formatBytes(usage.total), + total: formatBytes(usage.total, locale), rows: usage.rows.map((row, i) => ({ name: outboundLabel(row.name, t), value: row.percent === null ? null : Math.round(row.percent), - text: formatBytes(row.bytes), + text: formatBytes(row.bytes, locale), color: row.kind === 'builtin' && row.name === 'block' ? colors.love : colors.cat[i % colors.cat.length] })) }; } -export function activityRanking(connections: ConnectionList | undefined, by: string, colors: {cat: string[]}, t: LabelFn) { +export function activityRanking(connections: ConnectionList | undefined, by: string, colors: {cat: string[]}, locale: string, t: LabelFn) { return connectionRanking(connections, by).map((row, i) => ({ name: row.name, - value: row.percent === null ? formatBytes(row.download) : t('ui.share', {bytes: formatBytes(row.download), percent: row.percent}), + value: row.percent === null ? formatBytes(row.download, locale) : t('ui.share', {bytes: formatBytes(row.download, locale), percent: row.percent}), pct: row.percent ?? 0, color: colors.cat[i % colors.cat.length] })); diff --git a/src/features/config/messages.ts b/src/features/config/messages.ts index 15241749..94ec055d 100644 --- a/src/features/config/messages.ts +++ b/src/features/config/messages.ts @@ -5,7 +5,7 @@ export const messages = defineMessages({ 'config.tabModules': '模組', 'config.moduleOpen': '開啟頁面', 'config.moduleManual': '手動編輯', - 'config.moduleManualTip': '在來源分頁開啟整個檔案,游標停在這個區段', + 'config.moduleManualTip': '在來源分頁開啟整個檔案,游標位於此區段', 'config.moduleAbsent': '未設定此區段;可加入 {file}。', 'config.moduleSettings': '{n} 項設定', 'config.moduleSubscriptions': '{n} 個訂閱', @@ -16,7 +16,7 @@ export const messages = defineMessages({ 'config.wizardListenerPort': '透明代理連接埠', 'config.wizardDefaultDns': '預設 DNS 上游', 'config.wizardChinaDns': '中國大陸網域 DNS 上游', - 'config.wizardNetworkError': '連接埠須介於 1–65535,兩個 DNS 上游均須填寫。', + 'config.wizardNetworkError': '連接埠須介於 1 至 65535,兩個 DNS 上游均須填寫。', 'config.moduleDnsRequests': '{n} 條請求規則', 'config.moduleDnsResponses': '{n} 條回應規則', 'config.moduleRules': '{n} 條規則', @@ -37,7 +37,7 @@ export const messages = defineMessages({ 'config.save': '套用並重載', 'config.incomplete': '內容不完整或已遮蔽,不能在此編輯', 'config.unquotable': '無法寫入:值含單引號、換行或結尾反斜線,無法無損轉為單引號字串。', - 'config.contentHidden': '後端未提供內容;capabilities.resources.config.content 為 false。', + 'config.contentHidden': '此後端不提供組態內容(capabilities.resources.config.content 為 false)', 'config.contentWithheld': '後端未回傳此來源的文字,因此不能在此編輯。請檢查後端的內容可見性原則。', 'config.valid': '驗證通過', 'config.invalid': '驗證發現 {n} 個錯誤', @@ -87,7 +87,7 @@ export const messages = defineMessages({ 'config.lastRun': '最近一次驗證:{time}', 'config.acceptedDiagnostics': '生效組態(代次 {generation})保留的診斷', 'config.revalidate': '重新驗證', - 'config.validateNote': '解析階段採寬鬆模式並記錄所有問題,再由驗證判定致命錯誤。若有錯誤,套用操作不會寫入檔案,重載操作不會套用設定。', + 'config.validateNote': '解析階段採寬鬆模式並記錄所有問題,再由驗證判定致命錯誤。若有錯誤,套用操作不會寫入檔案,重載操作不會套用組態。', 'config.level': '等級', 'config.levelAll': '全部 {n}', 'config.levelErrors': '錯誤 {n}', @@ -100,21 +100,22 @@ export const messages = defineMessages({ 'config.openSource': '開啟來源', 'config.openSourceAt': '開啟來源:{where}', 'config.source': '來源', - 'config.sourceFacts': '{lines} 行,{size},{time} 載入', + 'config.sourceFacts': '行數:{lines},大小:{size},載入時間:{time}', 'config.unsaved': '未儲存', - 'config.unsavedHint': '重新整理或關閉頁面會遺失修改', + 'config.unsavedHint': '重新載入或關閉頁面會遺失修改', 'config.editNote': '後端可能隱藏來源文字、路徑或診斷;顯示與匯出的文字仍可能含有憑證。僅在內容完整且雜湊值符合 content_sha256 時允許編輯。儲存請求包含 If-Match;若磁碟上的檔案已變更,後端會回傳 HTTP 412,且不會覆寫檔案。', 'config.readNote': '此來源由引擎寫入或後端未開放編輯,只能檢視。', 'config.level.error': '錯誤', 'config.level.warning': '警告', - 'config.level.info': '提示' + 'config.level.info': '提示', + 'config.previewFailed': '無法產生組態:{error}' }, 'zh-CN': { 'config.tabModules': '模块', 'config.moduleOpen': '打开页面', 'config.moduleManual': '手动编辑', - 'config.moduleManualTip': '在来源标签页打开整个文件,光标停在这个区段', + 'config.moduleManualTip': '在来源标签页打开整个文件,光标位于此区段', 'config.moduleAbsent': '未设置此区段;可加入 {file}。', 'config.moduleSettings': '{n} 项设置', 'config.moduleSubscriptions': '{n} 个订阅', @@ -125,7 +126,7 @@ export const messages = defineMessages({ 'config.wizardListenerPort': '透明代理端口', 'config.wizardDefaultDns': '默认 DNS 上游', 'config.wizardChinaDns': '中国大陆域名 DNS 上游', - 'config.wizardNetworkError': '端口须介于 1–65535,两个 DNS 上游均须填写。', + 'config.wizardNetworkError': '端口须介于 1 至 65535,两个 DNS 上游均须填写。', 'config.moduleDnsRequests': '{n} 条请求规则', 'config.moduleDnsResponses': '{n} 条响应规则', 'config.moduleRules': '{n} 条规则', @@ -146,7 +147,7 @@ export const messages = defineMessages({ 'config.save': '应用并重载', 'config.incomplete': '内容不完整或已脱敏,不能在此编辑', 'config.unquotable': '无法写入:值含单引号、换行或结尾反斜线,无法无损转为单引号字符串。', - 'config.contentHidden': '后端未提供内容;capabilities.resources.config.content 为 false。', + 'config.contentHidden': '此后端不提供配置内容(capabilities.resources.config.content 为 false)', 'config.contentWithheld': '后端未返回此来源的文本,因此不能在此编辑。请检查后端的内容可见性策略。', 'config.valid': '校验通过', 'config.invalid': '校验发现 {n} 个错误', @@ -157,7 +158,7 @@ export const messages = defineMessages({ 'config.wizard': '快速设置', 'config.wizardSubscriptions': '订阅', 'config.wizardSubscriptionName': '名称', - 'config.wizardAddSubscription': '新增订阅', + 'config.wizardAddSubscription': '添加订阅', 'config.wizardRemove': '移除 {name}', 'config.wizardKeep': '保留当前规则', 'config.wizardKeepHelp': 'routing 区段不变', @@ -209,15 +210,16 @@ export const messages = defineMessages({ 'config.openSource': '打开来源', 'config.openSourceAt': '打开来源:{where}', 'config.source': '来源', - 'config.sourceFacts': '{lines} 行,{size},{time} 加载', + 'config.sourceFacts': '行数:{lines},大小:{size},加载时间:{time}', 'config.unsaved': '未保存', - 'config.unsavedHint': '刷新或关闭页面会丢失修改', + 'config.unsavedHint': '重新加载或关闭页面会丢失修改', 'config.editNote': - '后端可能隐藏来源文本、路径或诊断;显示与导出的文本仍可能包含凭据。仅在内容完整且哈希值符合 content_sha256 时允许编辑。保存请求包含 If-Match;若磁盘上的文件已更改,后端会返回 HTTP 412,且不会覆盖文件。', + '后端可能隐藏来源文本、路径或诊断;显示与导出的文本仍可能包含凭据。仅在内容完整且哈希值与 content_sha256 一致时允许编辑。保存请求包含 If-Match;若磁盘上的文件已更改,后端会返回 HTTP 412,且不会覆盖文件。', 'config.readNote': '此来源由引擎写入或后端未开放编辑,只能查看。', 'config.level.error': '错误', 'config.level.warning': '警告', - 'config.level.info': '提示' + 'config.level.info': '提示', + 'config.previewFailed': '无法生成配置:{error}' }, en: { 'config.tabModules': 'Modules', @@ -235,7 +237,7 @@ export const messages = defineMessages({ 'config.wizardListenerPort': 'Transparent proxy port', 'config.wizardDefaultDns': 'Default DNS upstream', 'config.wizardChinaDns': 'Mainland-China domain DNS upstream', - 'config.wizardNetworkError': 'Enter a port from 1–65535 and both DNS upstreams.', + 'config.wizardNetworkError': 'Enter a port from 1 to 65535 and both DNS upstreams.', 'config.moduleDnsRequests': {one: '{n} request rule', other: '{n} request rules'}, 'config.moduleDnsResponses': {one: '{n} response rule', other: '{n} response rules'}, 'config.moduleRules': {one: '{n} rule', other: '{n} rules'}, @@ -256,7 +258,7 @@ export const messages = defineMessages({ 'config.save': 'Apply and reload', 'config.incomplete': 'The text is incomplete or redacted; it cannot be edited here', 'config.unquotable': 'Cannot write this value losslessly as a single-quoted string: it contains an apostrophe, line break, or trailing backslash.', - 'config.contentHidden': 'The backend withholds the text; capabilities.resources.config.content is false.', + 'config.contentHidden': 'This backend does not provide the configuration text (capabilities.resources.config.content is false)', 'config.contentWithheld': 'The backend did not return this source’s text, so it cannot be edited here. Check the backend’s content visibility policy.', 'config.valid': 'Validation passed', 'config.invalid': {one: 'Validation found {n} error', other: 'Validation found {n} errors'}, @@ -267,7 +269,7 @@ export const messages = defineMessages({ 'config.wizard': 'Quick setup', 'config.wizardSubscriptions': 'Subscriptions', 'config.wizardSubscriptionName': 'Name', - 'config.wizardAddSubscription': 'Add a subscription', + 'config.wizardAddSubscription': 'Add subscription', 'config.wizardRemove': 'Remove {name}', 'config.wizardKeep': 'Keep the current rules', 'config.wizardKeepHelp': 'The routing section stays as it is', @@ -323,7 +325,7 @@ export const messages = defineMessages({ 'config.openSource': 'Open source', 'config.openSourceAt': 'Open source: {where}', 'config.source': 'Source', - 'config.sourceFacts': 'Line count: {lines}, {size}, loaded {time}', + 'config.sourceFacts': 'Lines: {lines}, size: {size}, loaded: {time}', 'config.unsaved': 'Unsaved', 'config.unsavedHint': 'Reloading or closing the page loses the changes', 'config.editNote': @@ -331,6 +333,7 @@ export const messages = defineMessages({ 'config.readNote': 'This source is written by the engine or the backend does not allow editing; view only.', 'config.level.error': 'Error', 'config.level.warning': 'Warning', - 'config.level.info': 'Info' + 'config.level.info': 'Info', + 'config.previewFailed': 'Could not generate the configuration: {error}' } }); diff --git a/src/features/config/useConfigPage.ts b/src/features/config/useConfigPage.ts index 7d89a5ed..391467a4 100644 --- a/src/features/config/useConfigPage.ts +++ b/src/features/config/useConfigPage.ts @@ -36,8 +36,8 @@ function useConfigEditorController(refetch: () => void) { useEffect(() => { if (!editor.error) return; if (diagnostics) { - toast('negative', t('config.invalid', {n: diagnostics.filter(d => d.level === 'error').length})); - } else toast('negative', errorText(editor.error, t)); + toast('negative', t('ui.writeInvalid', {n: diagnostics.filter(d => d.level === 'error').length})); + } else toast('negative', t('ui.writeFailed', {error: errorText(editor.error, t)})); }, [editor.error, diagnostics, t]); return {...editor, diagnostics}; } diff --git a/src/features/config/useWizard.ts b/src/features/config/useWizard.ts index 9d2ff232..ce382332 100644 --- a/src/features/config/useWizard.ts +++ b/src/features/config/useWizard.ts @@ -20,7 +20,8 @@ const templateLabels: Record = { standard: ['config.wizardStandard', 'config.wizardStandardHelp'], full: ['config.wizardFull', 'config.wizardFullHelp'] }; -// Edit subscriptions and optional routing templates while preserving existing groups. Never write back redacted text whose digest does not match. +// Edits subscriptions and optional routing templates, keeping existing groups. Redacted text whose digest does not +// match is never written back. export function useWizard({main, editor, onDone}: {main: ConfigSource; editor: ConfigEditor; onDone: () => void}) { const t = useT(); const lang = useLang(); @@ -67,14 +68,14 @@ export function useWizard({main, editor, onDone}: {main: ConfigSource; editor: C const apply = async () => { if (busy || !valid) return; if (preview.error) { - toast('negative', errorText(preview.error, t)); + toast('negative', t('config.previewFailed', {error: errorText(preview.error, t)})); return; } const result = await editor.apply(origin, text); if (!result) return; if (result.diagnostics) { setFound(result.diagnostics); - toast('negative', t('config.invalid', {n: result.diagnostics.filter(d => d.level === 'error').length})); + toast('negative', t('ui.writeInvalid', {n: result.diagnostics.filter(d => d.level === 'error').length})); return; } toast('positive', t('config.saved', {path: label})); diff --git a/src/features/config/view.ts b/src/features/config/view.ts index 2b229ac3..cc47ecf5 100644 --- a/src/features/config/view.ts +++ b/src/features/config/view.ts @@ -1,6 +1,5 @@ import type {Capabilities, ConfigDiagnostic, ConfigSource} from '../../api/model'; -import {formatBytes} from '../../api/u64'; -import {localTime} from '../../i18n/format'; +import {localTime, formatBytes} from '../../i18n/format'; import {formatList, formatNumber, type Lang, type Translator} from '../../i18n'; import type {Key} from '../../i18n'; import {fileName, redacted} from './names'; @@ -8,6 +7,7 @@ import {defaultGroup, isSubscriptionUrl, readState, type WizardState} from '../. import {defaultTemplate, templates} from '../../dae/templates'; import {blockFields, isBareName, isQuotable, scanConfig, type TextBlock, type TextToken} from '../../dae/text'; import {href as routeHref} from '../../shell/route'; +import {policyLabel} from '../policies/policies'; import type {EditorMark} from '../../ui/code/CodeEditor'; // Quick setup needs a writable main source with its text; a redacted text is shown but cannot be written back. @@ -97,7 +97,7 @@ function sectionSummary(kind: SectionKind, text: string, block: TextBlock, token lang, block.children.map(child => { const policy = blockFields(text, child, tokens).find(field => field.name === 'policy')?.value; - return policy ? `${child.name}: ${policy}` : child.name; + return policy ? t('ui.valuePair', {label: child.name, value: policyLabel(policy, t)}) : child.name; }) ) }); @@ -201,7 +201,7 @@ export function sourceView(source: ConfigSource, locale: string, t: Translator): tone: source.writable ? ('ok' as const) : ('muted' as const), facts: t('config.sourceFacts', { lines: formatNumber(source.line_count, locale), - size: formatBytes(String(source.bytes)), + size: formatBytes(String(source.bytes), locale), time: localTime(source.loaded_at, locale) }), hasContent: source.content !== undefined diff --git a/src/features/connections/CloseAll.tsx b/src/features/connections/CloseAll.tsx deleted file mode 100644 index f1af44ab..00000000 --- a/src/features/connections/CloseAll.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import {useState} from 'react'; -import {useT} from '../../i18n'; -import {Button, ModalDialog} from '../../ui/ui'; - -type CloseAllAction = {confirmationText: string; disabled: boolean; pending: boolean; run: () => void; open?: boolean; setOpen?: (open: boolean) => void}; -// One open state only: a DialogTrigger around a controlled dialog keeps a second one that never closes. The -// connections page controls it to snapshot the selection on open; other callers leave it local. -export function CloseAllButton({confirmationText, disabled, pending, run, open, setOpen}: CloseAllAction) { - const t = useT(); - const [local, setLocal] = useState(false); - const isOpen = open ?? local; - const change = setOpen ?? setLocal; - return ( - <> - - ( - <> - - - - )} - > - {confirmationText} - - - ); -} diff --git a/src/features/connections/ConnectionTable.tsx b/src/features/connections/ConnectionTable.tsx index 60d9ddab..cc05bc1c 100644 --- a/src/features/connections/ConnectionTable.tsx +++ b/src/features/connections/ConnectionTable.tsx @@ -9,6 +9,9 @@ type Props = Pick>, 'loading' view: ConnectionView; collection: ConnectionTableRow[]; }; +// Plain text truncates with a tooltip, as in DataTable. +const text = (cell: ReactNode) => (typeof cell === 'string' ? {cell} : cell); + export function ConnectionTable({collection, view, loading, selected, onSelect, selectOnFocus, onSort}: Props) { const t = useT(); const [ref, height] = useFillHeight(442); @@ -40,7 +43,7 @@ export function ConnectionTable({collection, view, loading, selected, onSelect, {shown.map(column => ( - {column.render(row)} + {text(column.render(row))} ))} @@ -77,7 +80,11 @@ export function ConnectionTable({collection, view, loading, selected, onSelect, (loading ? :
{t('conn.empty')}
)} + renderEmptyState={() => ( +
+ {loading ? :
{t('conn.empty')}
} +
+ )} > {row => { if ('connection' in row) return renderRow(row.connection); @@ -85,7 +92,7 @@ export function ConnectionTable({collection, view, loading, selected, onSelect, {shown.map((column, index) => ( - {index === 0 ? {row.label} : row.totals[column.id]} + {index === 0 ? {row.label} : text(row.totals[column.id])} ))} {row.children.map(renderRow)} diff --git a/src/features/connections/Connections.tsx b/src/features/connections/Connections.tsx index 69a8853d..1d148a12 100644 --- a/src/features/connections/Connections.tsx +++ b/src/features/connections/Connections.tsx @@ -1,11 +1,13 @@ -import {Menu, MenuSection, Header} from 'react-aria-components'; +import {Menu} from 'react-aria-components'; import { Badge, Button, + ConfirmButton, DetailPanel, Kv, LabeledSelect, Light, + ChoiceMenu, MenuButton, MenuChoice, RuleRef, @@ -18,7 +20,6 @@ import { import Download from '../../ui/icons/Download'; import {Traffic} from './Traffic'; import {ConnectionTable} from './ConnectionTable'; -import {CloseAllButton} from './CloseAll'; import type {PageProps} from '../../shell/routes'; import {useT} from '../../i18n'; import {useConnectionsPage} from './useConnectionsPage'; @@ -32,27 +33,12 @@ export function Connections(props: PageProps) { <> {vm.error && }
- + - - {vm.picks.map(section => ( - -
{section.title}
- {section.items.map(item => ( - - ))} -
- ))} - - } - > + {t('conn.pick')} -
+ )} - {vm.canClose && } + {vm.canClose && }