fix(ui): stabilize loading states, edits and responsive pages

Hold card and table geometry while data or fonts load. Keep configuration edits inside their source lines and address regressions across the feature pages.
This commit is contained in:
Zakk committed 2026-09-23 04:03:45 +10:00
1 parent 6333b757d6
commit cc6bfe99f7
168 files changed
+2463 -1264

No files matched your search

+2
View File
@@ -1,3 +1,5 @@
Pin: 01a6575 + 952e2e0 (PR #12)
openapi.yaml is the generated bundle (`npm run bundle`) of daeuniverse/api-standardize, branch honk, commit 01a6575 plus PR #12 (`952e2e0`, recorder modes and the unredacted administrative surface, open as of 2026-09-22).
That commit includes, all merged: PR #4 client fixes, #5 config, #6 observability with provider, node and geodata management, #7 connection close, #8 GroupOverrideCleared with the native outbound mode dropped.
+1 -1
View File
@@ -9,7 +9,7 @@ The parts of the [README](../README.md) that are only needed once: what doona ru
| Component | Requirement |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Backend | An engine implementing the native API contract pinned in [SOURCE.md](../contract/api-standardize/SOURCE.md), with its API listener enabled (see [Install](#install)) |
| Browser | Chrome or Edge 120, Firefox 120, Safari 17 or later. These are the CSS build targets; the JavaScript target is ES2022. Automated tests use Chromium |
| Browser | Chrome or Edge 120, Firefox 121, Safari 17 or later. These are the CSS build targets; the JavaScript target is ES2022. Automated tests use Chromium |
| Build | Node `^22.13.0 \|\| ^24.0.0 \|\| >=26.0.0` and pnpm 11.15.1; GNU tar, gzip and sha256sum for the archives |
## Install
+1 -1
View File
@@ -9,7 +9,7 @@
| 组件 | 要求 |
| ------ | ----------------------------------------------------------------------------------------------------------------------------- |
| 后端 | 实现 [SOURCE.md](../contract/api-standardize/SOURCE.md) 所钉契约并启用 API 监听的引擎(见[安装](#安装)) |
| 浏览器 | Chrome 或 Edge 120、Firefox 120、Safari 17 及以后。这些是 CSS 构建目标;JavaScript 构建目标是 ES2022。自动化测试只用 Chromium |
| 浏览器 | Chrome 或 Edge 120、Firefox 121、Safari 17 及以后。这些是 CSS 构建目标;JavaScript 构建目标是 ES2022。自动化测试只用 Chromium |
| 构建 | Node `^22.13.0 \|\| ^24.0.0 \|\| >=26.0.0`、pnpm 11.15.1;打包需要 GNU tar、gzip 与 sha256sum |
## 安装
+1 -1
View File
@@ -9,7 +9,7 @@
| 元件 | 要求 |
| ------ | ----------------------------------------------------------------------------------------------------------------------------- |
| 後端 | 實作 [SOURCE.md](../contract/api-standardize/SOURCE.md) 所釘契約並啟用 API 監聽的引擎(見[安裝](#安裝)) |
| 瀏覽器 | Chrome 或 Edge 120、Firefox 120、Safari 17 及以後。這些是 CSS 建置目標;JavaScript 建置目標是 ES2022。自動化測試只用 Chromium |
| 瀏覽器 | Chrome 或 Edge 120、Firefox 121、Safari 17 及以後。這些是 CSS 建置目標;JavaScript 建置目標是 ES2022。自動化測試只用 Chromium |
| 建置 | Node `^22.13.0 \|\| ^24.0.0 \|\| >=26.0.0`、pnpm 11.15.1;打包需要 GNU tar、gzip 與 sha256sum |
## 安裝
+26 -2
View File
@@ -102,7 +102,7 @@ test('the validation tab lists kept diagnostics and opens the source at the line
await expect(rows).toHaveCount(0);
await page.reload();
await rows.filter({hasText: 'rules.dae:3'}).click();
await page.getByRole('button', {name: 'Open source', exact: true}).click();
await page.getByRole('button', {name: 'Open source: rules.dae:3', exact: true}).click();
await expect(page).toHaveURL(/tab=source&source=src-rules&line=3$/);
await expect(page.locator('.cm-content[aria-label="/etc/honk/rules.dae"]')).toBeVisible();
await expect(page.locator('.cm-activeLine')).toContainText('mac(aa:bb:cc:dd:ee:ff)');
@@ -482,7 +482,7 @@ httpTest('rejected saves show cross-source diagnostics without marking the edite
await expect(diagnostics).toContainText('config.dae');
await expect(diagnostics).toContainText('Error in main source');
await expect(editor.locator('.cm-diag-line-error')).toHaveCount(0);
await diagnostics.getByRole('button', {name: 'Open source', exact: true}).click();
await diagnostics.getByRole('button', {name: /^Open source: config\.dae/}).click();
await page.getByRole('alertdialog').getByRole('button', {name: 'Discard changes', exact: true}).click();
await expect(page).toHaveURL(/source=src-main.*line=2/);
});
@@ -605,3 +605,27 @@ for (const appearance of ['light', 'dark', 'glass'] as const) {
expect(await raw.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true);
});
}
httpTest('a module draft refused with 412 is rebased and saves on the next attempt', async ({page}) => {
const {api} = await configBackend(page);
await page.goto('/#/config');
const routing = page.getByRole('tabpanel', {name: 'Modules'}).getByRole('region', {name: 'routing', exact: true});
await routing.getByRole('button', {name: 'Edit', exact: true}).click();
const editor = routing.locator('.cm-content');
const section = await editor.innerText();
await editor.fill(section.replace(' fallback:', ' domain(example.org) -> proxy\n fallback:'));
const main = (await api.config()).sources.find(source => source.kind === 'main')!;
await api.replaceConfigSource(main.id, '# concurrent edit\n' + main.content, `"${main.content_sha256}"`);
const rejected = page.waitForResponse(response => response.request().method() === 'PUT' && response.status() === 412);
await routing.getByRole('button', {name: 'Apply and reload', exact: true}).click();
await rejected;
await expect(editor).toContainText('domain(example.org) -> proxy');
// The second attempt carries the refetched digest; the concurrent edit outside the section is kept.
await expect(async () => {
await routing.getByRole('button', {name: 'Apply and reload', exact: true}).click();
await expect(page.locator('.rp-toast.positive')).toContainText('configuration reloaded', {timeout: 2000});
}).toPass({timeout: 15000});
const saved = (await api.config()).sources.find(source => source.kind === 'main')!.content!;
expect(saved).toContain('# concurrent edit');
expect(saved).toContain('domain(example.org) -> proxy');
});
+2 -2
View File
@@ -11,8 +11,8 @@ test('cache deletion removes one entry and flushing requires confirmation', asyn
const deleteHeader = page.getByRole('columnheader', {name: /^Delete /}).locator('.rp-th');
await page.evaluate(() => document.fonts.ready.then(() => undefined));
expect(await deleteHeader.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true);
await page.getByRole('button', {name: `Delete cache entry ${entries[0].entry_id}`, exact: true}).click();
await expect(page.getByRole('button', {name: `Delete cache entry ${entries[0].entry_id}`, exact: true})).toHaveCount(0);
await page.getByRole('button', {name: `Delete the ${entries[0].type} cache entry for ${entries[0].domain}`, exact: true}).click();
await expect(page.getByRole('button', {name: `Delete the ${entries[0].type} cache entry for ${entries[0].domain}`, exact: true})).toHaveCount(0);
await expect(rows).toHaveCount(entries.length - 1);
await expect(page.locator('.rp-toast.positive')).toContainText('Deleted 1 cache entry');
await page.getByRole('button', {name: 'Clear all cache', exact: true}).click();
+3
View File
@@ -156,6 +156,9 @@ test('refresh remains pending until completion, refetches non-polling resources,
await page.getByRole('button', {name: 'Query', exact: true}).click();
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(page.locator('.rp-toast.negative')).toHaveCount(0);
const actionFailure = await actionError.textContent();
await refresh.click();
await expect(refresh).not.toHaveAttribute('data-pending');
+11
View File
@@ -108,3 +108,14 @@ test('idle traffic has distinct fractional rate labels', async ({page}) => {
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']);
});
test('charts are named and icon buttons show their tooltip on keyboard focus', async ({page}) => {
await page.goto('/#/activity');
// The three cards' charts take focus under their card's name; the tile sparks are decoration and do not.
for (const name of ['Traffic', 'Memory', 'Outbound downloads']) await expect(page.getByRole('application', {name, exact: true})).toBeVisible();
await expect(page.getByRole('application')).toHaveCount(3);
await page.locator('.rp-search').focus();
await page.keyboard.press('Tab');
await expect(page.locator('.rp-actions button[aria-label]:focus')).toHaveCount(1);
await expect(page.getByRole('tooltip')).toBeVisible();
});
+2 -2
View File
@@ -34,8 +34,8 @@ test('logs filter the stream, pause incoming rows, export and clear', async ({pa
await page.goto('/#/logs');
const rows = page.getByRole('grid', {name: 'Logs'}).getByRole('rowheader');
await expect(rows).toHaveText(['Route failed', 'DNS slow', 'DNS answered']);
await page.getByRole('button', {name: 'info Level', exact: true}).click();
await page.getByRole('option', {name: 'warn', exact: true}).click();
await page.getByRole('button', {name: 'Info Level', exact: true}).click();
await page.getByRole('option', {name: 'Warning', exact: true}).click();
await expect(rows).toHaveText(['Route failed', 'DNS slow']);
await page.getByRole('searchbox', {name: 'Module', exact: true}).fill('honk::dns');
await expect(rows).toHaveText(['DNS slow']);
+10
View File
@@ -0,0 +1,10 @@
import {expect, test} from './fixtures';
// The narrowest supported phone: every page fits without scrolling sideways.
test.use({viewport: {width: 320, height: 640}});
for (const route of ['activity', 'overview', 'connections', 'nodes', 'policies', 'rules', 'flows', 'dns', 'config', 'logs', 'events', 'settings']) {
test(`no horizontal overflow at 320px on ${route}`, async ({page}) => {
await page.goto(`/#/${route}`);
await expect(page.locator('.rp-content > *').first()).toBeVisible();
expect(await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth)).toBeLessThanOrEqual(0);
});
}
+2
View File
@@ -160,6 +160,8 @@ test('built-in and unattributed provenance stay separate without granting inline
const list = rows(page.locator('.rp-table').nth(1));
const sources = rows(page.locator('.rp-table').first());
await expect(sources.first()).toContainText('Built-in');
// The first real source is the default; the built-in row is chosen explicitly.
await sources.first().click();
await expect(list).toHaveCount(2);
await expect(list).toContainText(['block', 'direct']);
await expect(sources.first().getByRole('button', {name: /Refresh|Remove/})).toHaveCount(0);
+1 -1
View File
@@ -72,7 +72,7 @@ test('the rule list keeps exact loss counts and replaces an empty snapshot', asy
expect(ids.slice(0, 3)).toEqual(['domain(full: rule-0.example)', 'domain(full: rule-1.example)', 'domain(full: rule-2.example)']);
expect(ids.slice(-2)).toEqual(['Unknown rule', 'Unknown rule']);
await expect(rows.first()).toContainText('6.7%');
await expect(panel.getByText('18446744073709551615 dropped records', {exact: true})).toBeVisible();
await expect(panel.getByText('18,446,744,073,709,551,615 dropped records', {exact: true})).toBeVisible();
await panel.getByRole('radio', {name: 'Unknown', exact: true}).click();
await expect(rows).toHaveCount(1);
snapshot.flows = [];
+12
View File
@@ -103,3 +103,15 @@ test('search respects destination capabilities, preserves loose-node ownership a
await expect(page).toHaveURL(/#\/connections$/);
await expect(page.getByRole('searchbox', {name: 'Filter'})).toBeVisible();
});
test('search results are reached with arrow keys while the field keeps focus', async ({page}) => {
await page.goto('/#/activity');
await expect(page.locator('.rp-nav').first()).toBeVisible();
const dialog = await open(page, 'valid');
const field = dialog.locator('input');
await expect(field).toBeFocused();
await page.keyboard.press('ArrowDown');
await expect(field).toHaveAttribute('aria-activedescendant', /.+/);
await page.keyboard.press('Enter');
await expect(page).toHaveURL(/#\/config\?tab=validate$/);
});
@@ -21,6 +21,7 @@ IUSE="+fonts"
src_install() {
dodoc NOTICE README.md CHANGELOG.md
dodoc -r LICENSES
rm -r LICENSE LICENSES NOTICE README.md CHANGELOG.md || die
insinto /usr/share/"${PN}"
doins -r .
-3
View File
@@ -35,6 +35,3 @@ contents:
- src: build/stage/doona-fonts/usr/share/doc/doona/OFL.txt
dst: /usr/share/doc/doona/OFL.txt
packager: archlinux
- src: build/stage/doona-fonts/usr/share/doc/doona/OFL.txt
dst: /usr/share/doc/doona/OFL.txt
packager: apk
-4
View File
@@ -57,7 +57,3 @@ contents:
dst: /usr/share/doc/doona
type: tree
packager: archlinux
- src: build/stage/doona/usr/share/doc/doona
dst: /usr/share/doc/doona
type: tree
packager: apk
+2
View File
@@ -79,6 +79,8 @@ endef
define Package/doona/install
$(INSTALL_DIR) $(1)/usr/share/doona
$(CP) $(PKG_BUILD_DIR)/web/* $(1)/usr/share/doona/
$(INSTALL_DIR) $(1)/usr/share/doc/doona
$(CP) $(PKG_BUILD_DIR)/web/LICENSE $(PKG_BUILD_DIR)/web/LICENSES $(PKG_BUILD_DIR)/web/NOTICE $(1)/usr/share/doc/doona/
rm -rf $(1)/usr/share/doona/LICENSE $(1)/usr/share/doona/LICENSES $(1)/usr/share/doona/NOTICE $(1)/usr/share/doona/*.md
endef
+1 -1
View File
@@ -39,7 +39,7 @@
"check": "pnpm typecheck && pnpm lint && pnpm check:i18n && pnpm format:check && pnpm test && pnpm check:gen"
},
"sizeBudget": {
"js": 600000,
"js": 610000,
"shell": 290000,
"css": 240000
},
+16 -6
View File
@@ -4,20 +4,30 @@ const PRECACHE = '__PRECACHE__';
const ROOT = new URL(self.registration.scope);
// A new build takes over on the next online load, including open dashboard tabs.
// Each build records when it was installed, so activation can tell the build it replaces from older ones.
const STAMP = new URL('__installed__', ROOT);
self.addEventListener('install', event => {
event.waitUntil(
caches
.open(CACHE)
.then(cache => cache.addAll(PRECACHE))
.then(cache => Promise.all([cache.addAll(PRECACHE), cache.put(STAMP, new Response(String(Date.now())))]))
.then(() => self.skipWaiting())
);
});
// The build just replaced stays: tabs still showing it load their remaining chunks from it until reloaded.
self.addEventListener('activate', event => {
event.waitUntil(
caches
.keys()
.then(keys => Promise.all(keys.filter(key => key.startsWith(PREFIX) && key !== CACHE).map(key => caches.delete(key))))
.then(() => self.clients.claim())
(async () => {
const older = [];
for (const key of await caches.keys()) {
if (!key.startsWith(PREFIX) || key === CACHE) continue;
const stamp = await (await caches.open(key)).match(STAMP);
older.push({key, installed: stamp ? Number(await stamp.text()) : 0});
}
older.sort((a, b) => b.installed - a.installed);
await Promise.all(older.slice(1).map(({key}) => caches.delete(key)));
await self.clients.claim();
})()
);
});
@@ -44,7 +54,7 @@ self.addEventListener('fetch', event => {
return hit(await cache.match(new URL('index.html', ROOT)));
}
}
const response = await cache.match(request);
const response = (await cache.match(request)) ?? (await caches.match(request));
if (response) return hit(response);
const fresh = await fetch(request);
if (fresh.ok && fresh.type === 'basic' && !fresh.redirected) await cache.put(request, fresh.clone());
+15 -5
View File
@@ -2,7 +2,7 @@ import createClient from 'openapi-fetch';
import type {paths} from './types';
import type {Api} from './api';
import type {ApiEvent, EventKind, EventOptions, FlowDetail, LogOptions, LogRecord, OperationAccepted, OperationState, RoutingTraceResponse} from './model';
import {ApiError, responseError} from './error';
import {ApiError, clientError, responseError} from './error';
import {uuid} from './hash';
import {readSse} from './sse';
import {wait} from './wait';
@@ -12,7 +12,7 @@ import {normalizeCapabilities} from './capabilities';
const retryAfter = (response: Response) => Math.max(1, Number(response.headers.get('Retry-After')) || 1);
function data<T>(result: {data?: T; response: Response}): T {
if (result.data === undefined) throw new ApiError(result.response.status, 'empty_response', 'Response has no JSON body');
if (result.data === undefined) throw clientError(result.response.status, 'empty_response', 'Response has no JSON body', 'ui.errNoJson');
return result.data;
}
@@ -58,15 +58,25 @@ export function createApi(base: string, token?: string): Api {
const resolveHref = (href: string) => {
const root = new URL(baseUrl + '/', globalThis.location?.href);
const url = new URL(href.replace(/^\/+/, ''), root);
if (url.origin !== root.origin) throw new ApiError(0, 'invalid_location', 'Operation URL has a different origin');
if (url.origin !== root.origin) throw clientError(0, 'invalid_location', 'Operation URL has a different origin', 'ui.errOtherOrigin');
return url;
};
async function pollOperation(accepted: OperationAccepted, signal?: AbortSignal): Promise<OperationState> {
let delay = accepted.retryAfter;
let dropped = 0;
const url = resolveHref(accepted.href);
while (true) {
await wait(delay, signal);
const response = await fetch(url, {headers, cache: 'no-store', signal});
let response: Response;
try {
response = await fetch(url, {headers, cache: 'no-store', signal});
dropped = 0;
} catch (error) {
// A dropped connection says nothing about the accepted operation; ask again a few times before giving up.
if (signal?.aborted || ++dropped > 3) throw error;
delay = Math.min(delay * 2, 30);
continue;
}
if (!response.ok) {
const error = await responseError(response);
// Rate limited or briefly unavailable: the accepted operation is still running, so keep polling.
@@ -106,7 +116,7 @@ export function createApi(base: string, token?: string): Api {
pause = retryAfter(response);
throw error;
}
if (!response.body) throw new ApiError(response.status, 'empty_stream', 'Response has no event stream');
if (!response.body) throw clientError(response.status, 'empty_stream', 'Response has no event stream', 'ui.errNoStream');
await readSse(
response.body,
frame => {
+9 -2
View File
@@ -1,6 +1,7 @@
import type {ErrorResponse} from './model';
import type {Key} from '../i18n/messages';
import type {Params} from '../i18n/index';
export class ApiError extends Error {
constructor(
@@ -10,7 +11,9 @@ export class ApiError extends Error {
public requestId: string | null = null,
public details: unknown = null,
// Seconds the backend asked to wait before trying again, when it said so.
public retryAfter: number | null = null
public retryAfter: number | null = null,
// Set when doona raised the error itself, so the text shown is translated rather than the English message.
public text: {key: Key; params?: Params} | null = null
) {
super(message);
this.name = 'ApiError';
@@ -28,13 +31,17 @@ export async function responseError(response: Response): Promise<ApiError> {
return new ApiError(
response.status,
body?.error?.code ?? '',
body?.error?.message ?? response.statusText,
body?.error?.message ?? (response.statusText || `HTTP ${response.status}`),
body?.request_id ?? null,
body?.error?.details ?? null,
retryAfter > 0 ? retryAfter : null
);
}
// A contract failure detected by doona: it keeps the status and code callers branch on, and a translated text.
export const clientError = (status: number, code: string, message: string, key: Key, params?: Params) =>
new ApiError(status, code, message, null, null, null, {key, params});
// Local failures carry a message key; detail preserves backend text.
export class LocalError extends Error {
constructor(
+30 -6
View File
@@ -81,6 +81,33 @@ function load<T extends Timed>(name: string): {key: string; rings: Rings<T>; sav
stores.set(name, store);
return store;
}
// Rings of other backends are the first thing to give up when storage is full: the profiles and settings
// share the same quota and matter more than a curve's past.
function save(key: string, value: string) {
for (let attempt = 0; attempt < 2; attempt++) {
try {
localStorage.setItem(key, value);
return;
} catch {
if (attempt || !prune(key)) return;
}
}
}
function prune(keep: string) {
const current = new Set([...stores.values()].map(store => store.key).concat(keep));
let freed = false;
try {
for (const key of Object.keys(localStorage)) {
if (key.startsWith('doona-rings-') && !current.has(key)) {
localStorage.removeItem(key);
freed = true;
}
}
} catch {
// Unavailable storage: nothing to free.
}
return freed;
}
const listeners = new Set<() => void>();
const subscribe = (listener: () => void) => {
listeners.add(listener);
@@ -98,11 +125,7 @@ export function record<T extends Timed>(name: string, sample: T | undefined, fol
const now = Date.now();
if (now - store.saved >= minute) {
store.saved = now;
try {
localStorage.setItem(store.key, JSON.stringify(next));
} catch {
// Full or unavailable storage: the rings live on in memory.
}
save(store.key, JSON.stringify(next));
}
}
return store.rings;
@@ -123,5 +146,6 @@ export function useRings<S, T extends Timed>(name: string, source: S | undefined
useEffect(() => {
record(name, source && sample(source), fold);
}, [name, source, sample, fold]);
return useSyncExternalStore(subscribe, () => load<T>(name).rings);
// A render reads the ring already loaded; the next record re-checks the profile, so storage is not read per render.
return useSyncExternalStore(subscribe, () => ((stores.get(name) as {rings: Rings<T>} | undefined) ?? load<T>(name)).rings);
}
+6 -3
View File
@@ -157,9 +157,12 @@ export function eventSummary(event: ApiEvent, t?: (key: Key) => string): Message
case 'runtime.updated':
return {key: 'event.resource', params: {resource: event.data.href}};
case 'flow.updated':
return {key: 'event.flow', params: {id: event.data.resource_id, revision: event.data.revision}};
case 'operation.updated':
return {key: 'event.operation', params: {id: event.data.resource_id, status: event.data.status}};
return {key: 'event.flow', params: {id: event.data.resource_id, revision: String(event.data.revision)}};
case 'operation.updated': {
const status = event.data.status;
const label = status === 'running' || status === 'succeeded' || status === 'failed' ? (`ov.${status}` as Key) : null;
return {key: 'event.operation', params: {id: event.data.resource_id, status: t && label ? t(label) : status}};
}
case 'generation.changed':
return {key: 'event.generation', params: {previous: event.data.previous_generation_id, current: event.data.generation_id}};
case 'flow.gap':
+22
View File
@@ -125,3 +125,25 @@ group {
expect(written).toContain('# keep {');
expect(readGroupEntries(written).at(-1)).toMatchObject({filters: ['name("a}#b", node)'], policy: 'min_last_delay'});
});
describe('group edits keep the rest of the source intact', () => {
it('replaces a filter that spans several lines as one value', () => {
const text = 'group {\n hk {\n filter: name(\n a,\n b)\n policy: min\n }\n}\n';
const next = writeGroupEntry(text, 'hk', {filters: ["name('c')"], policy: 'fixed(0)'});
expect(next).toBe("group {\n hk {\n filter: name('c')\n policy: fixed(0)\n }\n}\n");
});
it('removes whole lines in a file with CRLF line endings', () => {
const text = 'group {\r\n hk {\r\n filter: name(a)\r\n policy: min\r\n }\r\n}\r\n';
const once = writeGroupEntry(text, 'hk', {filters: ['name(b)'], policy: 'min'});
const twice = writeGroupEntry(once, 'hk', {filters: ['name(c)'], policy: 'min'});
expect(twice.split('\n').filter(line => /^[ \t\r]*$/.test(line) && line !== '').length).toBe(0);
expect(twice).toContain('filter: name(c)');
expect(twice).not.toContain('name(b)');
});
});
it('quotes IPv6 ranges in address rules and leaves IPv4 bare', () => {
expect(ruleCondition('dip', '10.0.0.0/8, ff00::/8')).toBe("dip(10.0.0.0/8, 'ff00::/8')");
expect(ruleCondition('sip', '2001:db8::1')).toBe("sip('2001:db8::1')");
});
+4 -3
View File
@@ -46,13 +46,13 @@ export function writeGroupEntry(text: string, name: string, next: {filters: stri
let to = field.to - bodyStart;
const start = old.lastIndexOf('\n', from - 1) + 1;
const end = old.indexOf('\n', to);
if (/^[ \t]*$/.test(old.slice(start, from)) && end !== -1 && /^[ \t]*$/.test(old.slice(to, end))) {
if (/^[ \t\r]*$/.test(old.slice(start, from)) && end !== -1 && /^[ \t\r]*$/.test(old.slice(to, end))) {
from = start;
to = end + 1;
}
kept = kept.slice(0, from) + kept.slice(to);
}
const rest = entry.line === entry.endLine ? (kept.trim() ? `${inner}${kept.trim()}\n` : '') : kept.replace(/^[ \t]*\n/, '').replace(/[ \t]*$/, '');
const rest = entry.line === entry.endLine ? (kept.trim() ? `${inner}${kept.trim()}\n` : '') : kept.replace(/^[ \t\r]*\n/, '').replace(/[ \t\r]*$/, '');
const body = [...next.filters.map(filter => `${inner}filter: ${filter}`), ...(next.policy ? [`${inner}policy: ${next.policy}`] : [])];
const replacement = '\n' + (body.length ? body.join('\n') + '\n' : '') + rest + indent;
return text.slice(0, bodyStart) + replacement + text.slice(entry.close);
@@ -119,7 +119,8 @@ export function ruleCondition(kind: ConditionKind, value: string): string {
.split(/[,\s]+/)
.map(v => v.trim())
.filter(Boolean);
const list = values.join(', ');
// A value with a colon (an IPv6 range) is quoted, as the presets write 'ff00::/8'; bare, dae reads it as a key.
const list = values.map(v => (v.includes(':') ? quote(v) : v)).join(', ');
const qualified = (prefix: string) => values.map(value => `${prefix}: ${value}`).join(', ');
switch (kind) {
case 'domain':
+13 -4
View File
@@ -22,15 +22,24 @@ export function validNetwork(state: WizardState): boolean {
export const isSubscriptionUrl = (value: string) => /^https?:\/\/\S+$/.test(value.trim());
export function validSubscriptions(subscriptions: Subscription[]): boolean {
const names = subscriptions.map(item => item.name || item.tag).filter((name): name is string => !!name);
const names = subscriptions.map(item => item.name.trim() || item.tag).filter((name): name is string => !!name);
return new Set(names).size === names.length && subscriptions.every(item => item.raw !== undefined || (!!item.name.trim() && isSubscriptionUrl(item.url)));
}
// The first free `sub-N`: counting rows alone repeats a name once one was removed or already taken.
export function nextSubscriptionName(subscriptions: Subscription[]): string {
const taken = new Set(subscriptions.map(item => item.name.trim() || item.tag));
let n = subscriptions.length + 1;
while (taken.has(`sub-${n}`)) n++;
return `sub-${n}`;
}
export function readState(text: string): WizardState {
const {blocks, tokens} = scanConfig(text);
const subscriptions: Subscription[] = [];
for (const [section, block] of blocks.filter(block => block.name === 'subscription').entries()) {
const fields = blockFields(text, block, tokens);
if (!text.slice(block.open + 1, block.close).trim()) continue;
for (const entry of blockEntries(text, block)) {
const line = text.slice(entry.from, entry.to);
const entryFields = fields.filter(field => field.from >= entry.from && field.to <= entry.to);
@@ -47,13 +56,13 @@ export function readState(text: string): WizardState {
}
function subscriptionBlock(state: WizardState): string[] {
return ['subscription {', ...state.subscriptions.map(s => s.raw ?? ` ${quoteName(s.name)}: ${quote(s.url.trim())}`), '}'];
return ['subscription {', ...state.subscriptions.map(s => s.raw ?? ` ${quoteName(s.name.trim())}: ${quote(s.url.trim())}`), '}'];
}
export const defaultGroup = 'proxy';
function routingBlock(state: WizardState, rules: RuleTemplate): string[] {
// The name as written: the templates must route to the group the file already has.
const first = state.group ?? defaultGroup;
const fill = (line: string) => ' ' + line.replaceAll('{group}', first);
const fill = (line: string) => ' ' + line.replaceAll('{group}', quoteName(first));
return ['routing {', ...templates[rules].rules.map(fill), fill(`fallback: ${templates[rules].fallback}`), '}'];
}
function dnsBlock(state: WizardState): string[] {
@@ -114,7 +123,7 @@ export function writeState(current: string, state: WizardState): string {
const subscriptionSections = blocks.filter(block => block.name === 'subscription');
for (const [section, block] of subscriptionSections.entries()) {
const subscriptions = state.subscriptions.filter(item => (item.section ?? subscriptionSections.length - 1) === section);
const body = subscriptions.map(item => item.raw ?? ` ${quoteName(item.name)}: ${quote(item.url.trim())}`);
const body = subscriptions.map(item => item.raw ?? ` ${quoteName(item.name.trim())}: ${quote(item.url.trim())}`);
if (body.join('\n') !== blockBody(current, block).join('\n')) {
edits.push({from: block.open + 1, to: block.close, text: '\n' + body.join('\n') + '\n'});
}
+16 -2
View File
@@ -1,5 +1,5 @@
import {expect, it} from 'vitest';
import {blockFields, scanConfig, uncomment} from './text';
import {describe, expect, it} from 'vitest';
import {blockFields, scanConfig, uncomment, isFragment} from './text';
import {groupNames} from '../features/config/names';
it('keeps source ranges through quoted braces, escaped quotes, comments and repeated inline sections', () => {
@@ -32,3 +32,17 @@ it('keeps comments adjacent to braces out of section headers and depth', () => {
expect(scanConfig(text).blocks.map(block => block.name)).toEqual(['group', 'routing']);
expect(groupNames(text)).toEqual(['a']);
});
describe('isFragment', () => {
it('accepts one balanced line and rejects text that would escape it', () => {
for (const ok of ['domain(geosite: cn)', 'name(\'a # b\', "c}")', 'min_moving_avg', "!name('direct')"]) expect(isFragment(ok)).toBe(true);
for (const bad of ['domain(a) # x', 'domain(a', 'domain(a))', 'a } routing {', 'domain(a)\nb', 'name({a})']) expect(isFragment(bad)).toBe(false);
});
});
it('scans the routing arrow as its own token when written without spaces', () => {
const text = 'routing { dip(geoip:private)->direct\n domain(a)->proxy(must) }';
const arrows = scanConfig(text).tokens.filter(token => text.slice(token.from, token.to) === '->');
expect(arrows).toHaveLength(2);
expect(scanConfig('a-b c->d').tokens.map(token => 'a-b c->d'.slice(token.from, token.to))).toEqual(['a-b', 'c', '->', 'd']);
});
+32 -2
View File
@@ -5,6 +5,14 @@ export function quote(value: string): string {
if (value.includes("'") || /[\r\n]|(^|[^\\])(?:\\\\)*\\$/.test(value)) throw new LocalError('config.unquotable');
return `'${value}'`;
}
export function isQuotable(value: string): boolean {
try {
quote(value);
return true;
} catch {
return false;
}
}
export type TextToken = {from: number; to: number; line: number; kind: 'text' | 'quoted' | 'comment' | 'symbol'; depth: number; parens: number};
export type TextBlock = {
name: string;
@@ -53,8 +61,11 @@ export function scanConfig(text: string) {
} else if ('{}:(),'.includes(c)) {
kind = 'symbol';
i++;
} else if (c === '-' && text[i + 1] === '>') {
// The routing arrow is its own token even when written flush against its neighbours, as in `dip(x)->direct`.
i += 2;
} else {
while (i < text.length && !/[\s{}:(),'"]/.test(text[i])) i++;
while (i < text.length && !/[\s{}:(),'"]/.test(text[i]) && !(text[i] === '-' && text[i + 1] === '>')) i++;
}
const token = {from, to: i, line: startLine, kind, depth: stack.length, parens};
if (kind === 'symbol' && c === '{') {
@@ -88,6 +99,25 @@ export function scanConfig(text: string) {
return {blocks, tokens};
}
/**
* Whether typed text can be written as one field value or rule without changing the file's structure: a single
* line with balanced parentheses and no comment or brace outside quotes. `domain(a) # x` would comment out the
* outbound written after it; a brace would open or close a section.
*/
export function isFragment(text: string): boolean {
if (/[\r\n]/.test(text)) return false;
let depth = 0;
for (const token of scanConfig(text).tokens) {
if (token.kind === 'comment') return false;
if (token.kind === 'quoted') continue;
const raw = text.slice(token.from, token.to);
if (raw.includes('{') || raw.includes('}')) return false;
if (raw === '(') depth++;
if (raw === ')' && --depth < 0) return false;
}
return depth === 0;
}
export const unquote = (text: string) => (/^['"]/.test(text) ? text.slice(1, -1) : text);
export function uncomment(text: string): string {
const comments = scanConfig(text).tokens.filter(token => token.kind === 'comment');
@@ -102,7 +132,7 @@ export function blockFields(text: string, block: TextBlock, tokens: TextToken[])
const token = tokens[i];
if (token.from <= block.open || token.from >= block.close) continue;
const raw = text.slice(token.from, token.to);
if (token.kind === 'comment' || (field && text.slice(field.valueTo, token.from).includes('\n'))) field = undefined;
if (token.kind === 'comment' || (field && token.parens === 0 && text.slice(field.valueTo, token.from).includes('\n'))) field = undefined;
if (token.depth !== block.depth + 1 || token.kind === 'comment') continue;
const next = tokens[i + 1];
if (token.parens === 0 && (token.kind === 'text' || token.kind === 'quoted') && next && text.slice(next.from, next.to) === ':') {
+28 -62
View File
@@ -3,18 +3,20 @@ import Upload from '../../ui/icons/Upload';
import LinkIcon from '../../ui/icons/Link';
import Data from '../../ui/icons/Data';
import {useT} from '../../i18n';
import {Badge, CardLink, Segmented, Light, Bar, ErrorMessage, Loading, TextTooltip, Empty, Link} from '../../ui/ui';
import {CardLink, Segmented, Light, ErrorMessage, Loading, Empty, Link} from '../../ui/ui';
import {buildHash} from '../../shell/route';
import {AreaChart, Donut, Legend, Spark} from '../../ui/Charts';
import {AreaChart, Legend, Spark} from '../../ui/Charts';
import {ModeCards} from './ModeSwitch';
import {Notices} from './Notices';
import {useActivity} from './useActivity';
import {NodeCard} from './NodeCard';
import {OutboundsCard} from './OutboundsCard';
import {RankingCard} from './RankingCard';
export function Activity() {
const t = useT();
const vm = useActivity();
const {p, locale, range, setRange, by, setBy, traffic, spark, chartRate, memorySeries, memoryBytes, notices} = vm;
const {p, locale, range, setRange, traffic, spark, chartRate, memorySeries, memoryBytes, notices} = vm;
const alert = vm.error && <ErrorMessage error={vm.error} onRetry={vm.retry} />;
if (!vm.ready) return alert || <Loading>{t('act.loading')}</Loading>;
return (
@@ -116,78 +118,41 @@ export function Activity() {
]}
/>
</div>
{vm.history.error ? (
{vm.history.error && vm.history.state !== 'ready' ? (
<ErrorMessage error={vm.history.error} />
) : vm.history.state === 'unavailable' ? (
<span className="rp-label">{t('act.noHistory')}</span>
<div className="rp-chart-wait tall">
<span className="rp-label">{t('act.noHistory')}</span>
</div>
) : vm.history.state === 'loading' ? (
<Loading>{t('act.loading')}</Loading>
<div className="rp-chart-wait tall">
<Loading>{t('act.loading')}</Loading>
</div>
) : vm.history.state === 'empty' ? (
<Empty>{t('act.emptyHistory')}</Empty>
<div className="rp-chart-wait tall">
<Empty>{t('act.emptyHistory')}</Empty>
</div>
) : (
<>
<Legend series={traffic} fmt={chartRate} />
<AreaChart series={traffic} timestamps={vm.trafficTimestamps} fmt={chartRate} locale={locale} height={120} fill window={vm.trafficBounds} />
<AreaChart
label={t('act.traffic')}
series={traffic}
timestamps={vm.trafficTimestamps}
fmt={chartRate}
locale={locale}
height={120}
fill
window={vm.trafficBounds}
/>
</>
)}
</section>
<div className="rp-card">
<div className="rp-row">
<div className="rp-cluster">
<h3 className="rp-h3">{t('act.outUsage')}</h3>
{vm.outbounds.since && <span className="rp-label">{vm.outbounds.since}</span>}
</div>
</div>
{vm.outboundState.error ? (
<ErrorMessage error={vm.outboundState.error} />
) : vm.outboundState.state === 'unavailable' ? (
<span className="rp-label">{t('act.noOutbounds')}</span>
) : vm.outboundState.state === 'loading' ? (
<Loading>{t('act.loading')}</Loading>
) : vm.outboundState.state === 'empty' ? (
<Empty>{t('ui.empty')}</Empty>
) : (
<Donut rows={vm.outbounds.rows} total={vm.outbounds.total} />
)}
</div>
<OutboundsCard />
</div>
<div className="rp-g3">
<div className="rp-card">
<div className="rp-row">
<TextTooltip text={t('act.rankingScope')}>
<h3 className="rp-h3">{t('act.topDevices')}</h3>
</TextTooltip>
<Segmented
label={t('act.topDevices')}
value={by}
onChange={setBy}
items={[
['dev', t('act.devices')],
['host', t('act.domains')]
]}
/>
</div>
{vm.rankingState.error && <ErrorMessage error={vm.rankingState.error} />}
{vm.rankingState.truncated && (
<TextTooltip text={t('act.rankingTruncated')}>
<Badge tone="warn">{t('act.truncated')}</Badge>
</TextTooltip>
)}
{vm.rankingState.state === 'error' ? null : vm.rankingState.state === 'loading' ? (
<Loading>{t('act.loading')}</Loading>
) : vm.rankingState.state === 'unavailable' ? (
<Empty>{t('shell.notOfferedShort')}</Empty>
) : vm.rankingState.state === 'empty' ? (
<Empty>{t('act.rankingEmpty')}</Empty>
) : (
<div className="rp-list">
{vm.ranking.map(row => (
<Bar key={row.name} label={row.name} value={row.value} pct={row.pct} color={row.color} />
))}
</div>
)}
</div>
<RankingCard />
<section className="rp-card" aria-labelledby="activity-memory">
<div className="rp-row">
<h3 className="rp-h3" id="activity-memory">
@@ -203,6 +168,7 @@ export function Activity() {
<>
<Legend series={memorySeries} fmt={memoryBytes} />
<AreaChart
label={t('act.memory')}
series={memorySeries}
timestamps={vm.memoryTimestamps}
fmt={memoryBytes}
+40 -29
View File
@@ -1,39 +1,17 @@
import {useMemo} from 'react';
import {Autocomplete, Header, ListLayout, Menu, MenuSection, Virtualizer, useFilter} from 'react-aria-components';
import {MenuButton, MenuChoice, pickMenuKey, TextField} from '../../ui/ui';
import {useT} from '../../i18n';
import {menuViews} from '../policies/view';
import type {ActivityNodeMenu} from './view';
export function NodeMenu({model: vm, label}: {model: ActivityNodeMenu & {setChosen: (id: string) => void}; label: string}) {
type Model = ActivityNodeMenu & {setChosen: (id: string) => void};
export function NodeMenu({model: vm, label}: {model: Model; label: string}) {
const t = useT();
const {contains} = useFilter({sensitivity: 'base'});
const item = (node: (typeof vm.menu.items)[number]) => (
<MenuChoice key={node.id} item={node}>
<span className={node.className}>{node.description}</span>
</MenuChoice>
);
const menu = (
<Menu
aria-label={label}
className="rp-menu-scroll"
selectionMode={vm.big ? undefined : 'single'}
selectedKeys={vm.big ? undefined : [vm.id]}
onSelectionChange={vm.big ? undefined : pickMenuKey(vm.setChosen)}
>
{vm.big
? vm.menu.sections.map(section => (
<MenuSection key={section.title} id={section.title} selectionMode="single" selectedKeys={[vm.id]} onSelectionChange={pickMenuKey(vm.setChosen)}>
<Header className="rp-sec-h">
<span className="rp-il">
{section.title}
<span className="rp-muted">{section.count}</span>
</span>
</Header>
{section.items.map(item)}
</MenuSection>
))
: vm.menu.items.map(item)}
</Menu>
);
// The popover renders its content only while open, so the list below is not rebuilt on polls while closed.
const menu = <NodeList model={vm} label={label} />;
return (
<MenuButton
appearance="select"
@@ -59,3 +37,36 @@ export function NodeMenu({model: vm, label}: {model: ActivityNodeMenu & {setChos
</MenuButton>
);
}
function NodeList({model: vm, label}: {model: Model; label: string}) {
const t = useT();
const views = useMemo(() => menuViews(vm.options, t), [vm.options, t]);
const item = (node: (typeof views.items)[number]) => (
<MenuChoice key={node.id} item={node}>
<span className={node.className}>{node.description}</span>
</MenuChoice>
);
return (
<Menu
aria-label={label}
className="rp-menu-scroll"
selectionMode={vm.big ? undefined : 'single'}
selectedKeys={vm.big ? undefined : [vm.id]}
onSelectionChange={vm.big ? undefined : pickMenuKey(vm.setChosen)}
>
{vm.big
? views.sections.map(section => (
<MenuSection key={section.title} id={section.title} selectionMode="single" selectedKeys={[vm.id]} onSelectionChange={pickMenuKey(vm.setChosen)}>
<Header className="rp-sec-h">
<span className="rp-il">
{section.title}
<span className="rp-muted">{section.count}</span>
</span>
</Header>
{section.items.map(item)}
</MenuSection>
))
: views.items.map(item)}
</Menu>
);
}
+3 -2
View File
@@ -1,5 +1,6 @@
type NoticesModel = {
rows: Array<{id: string; tone: 'warn' | 'info'; kindText: string; summaryText: string}>;
total: number;
error: Error | null;
loading: boolean;
empty: string;
@@ -8,14 +9,14 @@ import {useT} from '../../i18n';
import {buildHash} from '../../shell/route';
import {Empty, ErrorMessage, Light, Link, Loading} from '../../ui/ui';
export function Notices({rows, error, loading, empty}: NoticesModel) {
export function Notices({rows, total, error, loading, empty}: NoticesModel) {
const t = useT();
return (
<section className="rp-card" aria-label={t('act.issues')}>
<div className="rp-row">
<div className="rp-cluster">
<h3 className="rp-h3">{t('act.issues')}</h3>
{rows.length > 0 && <span className="rp-label">{rows.length}</span>}
{total > 0 && <span className="rp-label">{total}</span>}
</div>
<Link appearance="button" className="quiet sm" href={buildHash('events')}>
{t('act.viewAll')}
+45
View File
@@ -0,0 +1,45 @@
import {useMemo} from 'react';
import {useCapabilities, useRuntimeOutbounds} from '../../store';
import {LOCALE, useLang, useT} from '../../i18n';
import {Donut, usePalette} from '../../ui/Charts';
import {Empty, ErrorMessage, Loading} from '../../ui/ui';
import {activityOutbounds} from './view';
// Outbound usage polls on its own, so its tick does not re-render the charts beside it.
export function OutboundsCard() {
const t = useT();
const locale = LOCALE[useLang()];
const p = usePalette();
const capabilities = useCapabilities();
const available = capabilities.data?.resources.runtime_outbounds.available;
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 (
<div className="rp-card">
<div className="rp-row">
<div className="rp-cluster">
<h3 className="rp-h3">{t('act.outUsage')}</h3>
{view.since && <span className="rp-label">{view.since}</span>}
</div>
</div>
{outbounds.error && state !== 'ready' ? (
<ErrorMessage error={outbounds.error} />
) : state === 'unavailable' ? (
<div className="rp-chart-wait tall">
<span className="rp-label">{t('act.noOutbounds')}</span>
</div>
) : state === 'loading' ? (
<div className="rp-chart-wait tall">
<Loading>{t('act.loading')}</Loading>
</div>
) : state === 'empty' ? (
<div className="rp-chart-wait tall">
<Empty>{t('ui.empty')}</Empty>
</div>
) : (
<Donut label={t('act.outUsage')} rows={view.rows} total={view.total} />
)}
</div>
);
}
+62
View File
@@ -0,0 +1,62 @@
import {useMemo, useState} from 'react';
import {useCapabilities, useConnections} from '../../store';
import {useT} from '../../i18n';
import {usePalette} from '../../ui/Charts';
import {Badge, Bar, Empty, ErrorMessage, Loading, Segmented, TextTooltip} from '../../ui/ui';
import {activityRanking} from './view';
// Top clients owns its own connections subscription: a five-second tick over up to 1,000 connections
// re-renders this card alone, not the traffic charts or the tiles beside it.
export function RankingCard() {
const t = useT();
const p = usePalette();
const [by, setBy] = useState('dev');
const capabilities = useCapabilities();
const available = capabilities.data?.resources.connections.available;
const connections = useConnections(undefined, available === true);
const rows = useMemo(() => activityRanking(connections.data, by, p, t), [connections.data, by, p, t]);
const state = connections.data ? (rows.length ? 'ready' : 'empty') : connections.error ? 'error' : available === true ? 'loading' : 'unavailable';
return (
<div className="rp-card">
<div className="rp-row">
<TextTooltip text={t('act.rankingScope')}>
<h3 className="rp-h3">{t('act.topDevices')}</h3>
</TextTooltip>
<Segmented
label={t('act.topDevices')}
value={by}
onChange={setBy}
items={[
['dev', t('act.devices')],
['host', t('act.domains')]
]}
/>
</div>
{connections.error && !connections.data && <ErrorMessage error={connections.error} />}
{connections.data?.truncated && (
<TextTooltip text={t('act.rankingTruncated')}>
<Badge tone="warn">{t('act.truncated')}</Badge>
</TextTooltip>
)}
{state === 'error' ? null : state === 'loading' ? (
<div className="rp-chart-wait bars">
<Loading>{t('act.loading')}</Loading>
</div>
) : state === 'unavailable' ? (
<div className="rp-chart-wait bars">
<Empty>{t('shell.notOfferedShort')}</Empty>
</div>
) : state === 'empty' ? (
<div className="rp-chart-wait bars">
<Empty>{t('act.rankingEmpty')}</Empty>
</div>
) : (
<div className="rp-list">
{rows.map(row => (
<Bar key={row.name} label={row.name} value={row.value} pct={row.pct} color={row.color} />
))}
</div>
)}
</div>
);
}
+3
View File
@@ -34,6 +34,7 @@ export const messages = defineMessages({
'act.modeNeedsWrite': '需要可寫入的主組態',
'act.modeUnavailable': '後端未提供',
'act.viewAll': '查看全部',
'act.noticeRepeat': '重複 {n} 次',
'act.since': '自 {t} 起',
'act.good': '良好',
'act.live': '即時',
@@ -88,6 +89,7 @@ export const messages = defineMessages({
'act.modeNeedsWrite': '需要可写入的主配置',
'act.modeUnavailable': '后端未提供',
'act.viewAll': '查看全部',
'act.noticeRepeat': '重复 {n} 次',
'act.since': '自 {t} 起',
'act.good': '良好',
'act.live': '实时',
@@ -142,6 +144,7 @@ export const messages = defineMessages({
'act.modeNeedsWrite': 'Needs a writable main configuration',
'act.modeUnavailable': 'Not offered by the backend',
'act.viewAll': 'View all',
'act.noticeRepeat': {one: '{n} time', other: '{n} times'},
'act.since': 'Since {t}',
'act.good': 'Good',
'act.live': 'Live',
+1 -1
View File
@@ -5,7 +5,7 @@ import {scanConfig, type TextBlock, type TextToken} from '../../dae/text';
export type OutboundMode = {mode: 'rule'} | {mode: 'direct'} | {mode: 'global'; target: string};
const MODE_MARK = '# doona: outbound mode';
const modeLine = /^(\s*)l4proto\(tcp, udp\) -> (\S+)\s*# doona: outbound mode\s*$/;
const modeLine = /^(\s*)l4proto\(tcp, udp\) -> (.+?)\s*# doona: outbound mode\s*$/;
function modeRanges(text: string, blocks: TextBlock[], tokens: TextToken[]) {
return tokens
+5 -31
View File
@@ -1,5 +1,5 @@
import {useCallback, useMemo, useState} from 'react';
import {useCapabilities, useConnections, useRuntime, useRuntimeMemory, useRuntimeOutbounds, useTrafficHistory} from '../../store';
import {useCapabilities, useRuntime, useRuntimeMemory, useTrafficHistory} from '../../store';
import {formatBytes} from '../../api/u64';
import {useT, useLang, LOCALE} from '../../i18n';
import {fmtRate, usePalette} from '../../ui/Charts';
@@ -7,7 +7,7 @@ import {useMemorySeries} from './useMemorySeries';
import {historyTrafficSamples, trafficWindow, trafficWindows, useTrafficSamples} from './traffic';
import {useNotices} from './useNotices';
import {useMode} from './useMode';
import {activityOutbounds, activityRanking, activityView, trafficState} from './view';
import {activityView, trafficState} from './view';
export function useActivity() {
const t = useT();
@@ -16,13 +16,10 @@ export function useActivity() {
const capabilities = useCapabilities();
const resources = capabilities.data?.resources;
const runtime = useRuntime(resources?.runtime.available === true);
const outbounds = useRuntimeOutbounds(resources?.runtime_outbounds.available === true);
const memory = useRuntimeMemory(resources?.runtime_memory.available === true);
const [range, setRange] = useState('live');
const [by, setBy] = useState('dev');
const windowSeconds = trafficWindows[range] ?? 120;
const memoryHistory = useMemorySeries(capabilities.data, memory.data);
const connections = useConnections(undefined, resources?.connections.available === true);
const history = useTrafficHistory(windowSeconds, capabilities.data);
const polledTraffic = useTrafficSamples(runtime.data);
const historySamples = useMemo(() => (history.data ? historyTrafficSamples(history.data) : []), [history.data]);
@@ -47,23 +44,17 @@ export function useActivity() {
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))), []);
const view = useMemo(
() => activityView(runtime.data, memory.data, t, resources?.runtime.available),
[runtime.data, memory.data, t, resources?.runtime.available]
() => activityView(runtime.data, memory.data, t, resources?.runtime.available, locale),
[runtime.data, memory.data, t, resources?.runtime.available, locale]
);
const outboundView = useMemo(() => activityOutbounds(outbounds.data, locale, p, t), [outbounds.data, locale, p, t]);
const ranking = useMemo(() => activityRanking(connections.data, by, p, t), [connections.data, by, p, t]);
const notices = useNotices();
const mode = useMode();
return {
...view,
outbounds: outboundView,
ranking,
mode,
notices,
range,
setRange,
by,
setBy,
locale,
p,
spark,
@@ -84,24 +75,7 @@ export function useActivity() {
showMemory: !!resources?.runtime_memory.available,
history: {
error: history.error,
state: trafficState(series, resources?.traffic_history.available, !!history.data)
},
outboundState: {
error: outbounds.error,
state: resources?.runtime_outbounds.available === false ? 'unavailable' : !outbounds.data ? 'loading' : !outboundView.rows.length ? 'empty' : 'ready'
},
rankingState: {
error: connections.error,
truncated: !!connections.data?.truncated,
state: connections.data
? ranking.length
? 'ready'
: 'empty'
: connections.error
? 'error'
: resources?.connections.available === true
? 'loading'
: 'unavailable'
state: trafficState(series, resources?.traffic_history.available, !!history.data, resources?.runtime.available === true)
},
memoryState: {
error: memory.error ?? memoryHistory.error,
+2
View File
@@ -9,5 +9,7 @@ export function useActivityNode() {
const nodes = useNodes(capabilities.data?.resources.nodes.available === true);
const [chosen, setChosen] = useState('');
const view = useMemo(() => nodeView(nodes.data ?? [], chosen, t), [nodes.data, chosen, t]);
// Nothing chosen yet: keep the node picked first, so a later poll does not switch the card to another node.
if (!chosen && view.id) setChosen(view.id);
return {...view, setChosen, loading: capabilities.loading || (nodes.loading && !nodes.data), error: nodes.error, retry: nodes.refetch};
}
+1 -1
View File
@@ -10,5 +10,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, loading: advertised && !history.data && history.loading, error: advertised ? history.error : undefined};
return {...series, error: advertised ? history.error : undefined};
}
+1 -1
View File
@@ -24,7 +24,7 @@ export function useMode() {
try {
const written = await write(
text => writeMode(text, submitted),
errors => toast('negative', t('act.modeInvalid', {n: String(errors)}))
errors => toast('negative', t('act.modeInvalid', {n: errors}))
);
if (written) {
guard.clear();
+19 -4
View File
@@ -1,5 +1,6 @@
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 {useEvents} from '../../store/events';
@@ -7,14 +8,28 @@ import {createFeed} from '../../store/feed';
import {useT} from '../../i18n';
import {interestingNotice, noticeRows} from './view';
// Held per backend rather than per mount: the stream does not replay, so a fresh buffer on every return to the
// home page would forget the notices it had already shown.
const buffers = new WeakMap<Api, ReturnType<typeof createFeed<ApiEvent, Record<string, never>>>>();
function noticeBuffer(api: Api) {
let buffer = buffers.get(api);
if (!buffer) buffers.set(api, (buffer = createFeed<ApiEvent, Record<string, never>>(EVENT_FEED_LIMIT, {}, 'replace')));
return buffer;
}
export function useNotices() {
const t = useT();
const api = getApi();
const buffer = useMemo(() => ({api, ...createFeed<ApiEvent, Record<string, never>>(EVENT_FEED_LIMIT, {}, 'replace')}), [api]);
const buffer = noticeBuffer(getApi());
const snapshot = useSyncExternalStore(buffer.subscribe, buffer.getSnapshot);
const feed = useEvents(event => {
if (interestingNotice(event)) buffer.append(event);
});
const rows = useMemo(() => noticeRows(snapshot.records.slice(0, 30), t), [snapshot.records, t]);
return {rows, error: feed.error, loading: !feed.error && feed.available === null, empty: t(feed.available === false ? 'event.unavailable' : 'act.noIssues')};
const rows = useMemo(() => noticeRows(snapshot.records, t), [snapshot.records, t]);
return {
rows,
total: snapshot.records.length,
error: feed.error,
loading: !feed.error && feed.available === null,
empty: t(feed.available === false ? 'event.unavailable' : 'act.noIssues')
};
}
+5 -3
View File
@@ -1,6 +1,7 @@
import {expect, it} from 'vitest';
import {connections, nodeFixtures, runtime, runtimeMemory, runtimeOutbounds} from '../../api/mock/fixtures';
import {translate, type Translator} from '../../i18n';
import {menuViews} from '../policies/view';
import {activityOutbounds, activityRanking, activityView, interestingNotice, modeView, nodeView, noticeRows, trafficState} from './view';
const t: Translator = (key, params) => translate('en', key, params);
const colors = {cat: ['blue', 'green'], love: 'red'};
@@ -14,7 +15,7 @@ it('distinguishes missing metrics from zero and keeps block traffic separate fro
{...runtimeMemory, cgroup: {...runtimeMemory.cgroup!, current_bytes: '91', limit_bytes: '100'}},
t
);
expect(model.connections).toBe(0);
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);
@@ -61,8 +62,9 @@ it('selects duplicate node labels by ID and preserves independent health', () =>
const view = nodeView([first, second], second.id, t);
expect(view.id).toBe(second.id);
expect(view.tone).toBe('err');
expect(view.menu.items.map(item => item.id)).toEqual([first.id, second.id]);
expect(new Set(view.menu.items.map(item => item.label)).size).toBe(2);
const menu = menuViews(view.options, t);
expect(menu.items.map(item => item.id)).toEqual([first.id, second.id]);
expect(new Set(menu.items.map(item => item.label)).size).toBe(2);
expect(nodeView([first, second], first.id, t).tone).toBe('ok');
});
+35 -15
View File
@@ -12,11 +12,10 @@ import {
routineGap,
shortId
} from '../../api/selectors';
import type {Translator as LabelFn} from '../../i18n';
import {formatNumber, type Translator as LabelFn} from '../../i18n';
import {formatBytes, formatRate, millis, pctU64} from '../../api/u64';
import {connectionRanking} from './ranking';
import {sameMode, type OutboundMode} from './mode';
import {menuViews} from '../policies/view';
export const modeLabels = {rule: 'mode.rule', direct: 'mode.direct', global: 'mode.global'} as const;
export function modeView(
@@ -44,35 +43,56 @@ 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;
// 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.
export function noticeRows(events: ApiEvent[], t: LabelFn) {
return events.map(event => {
const rows: Array<{id: string; tone: 'warn' | 'info'; kindText: string; summaryText: string; key: string; count: number}> = [];
for (const event of events) {
const summary = eventSummary(event, t);
const key = [event.event, summary.key, ...Object.entries(summary.params ?? {}).map(([name, value]) => `${name}=${String(value)}`)].join('|');
const last = rows[rows.length - 1];
if (last && last.key === key) {
last.count += 1;
continue;
}
if (rows.length === NOTICE_ROWS) break;
const params = Object.fromEntries(Object.entries(summary.params ?? {}).map(([key, value]) => [key, typeof value === 'string' ? shortId(value) : value]));
return {
rows.push({
id: event.id,
tone: event.event === 'flow.gap' ? ('warn' as const) : ('info' as const),
kindText: t(event.event === 'flow.gap' ? 'ui.warning' : 'ui.notice'),
summaryText: `${t(eventKindLabels[event.event])} · ${t(summary.key, params)}`
};
});
summaryText: `${t(eventKindLabels[event.event])} · ${t(summary.key, params)}`,
key,
count: 1
});
}
return rows.map(({key: _key, count, summaryText, ...row}) => ({
...row,
summaryText: count > 1 ? `${summaryText} · ${t('act.noticeRepeat', {n: count})}` : summaryText
}));
}
type NodeMenuItem = {id: string; label: string; description: string; className: string};
export type ActivityNodeMenu = {
menu: {items: NodeMenuItem[]; sections: Array<{title: string; count: string; items: NodeMenuItem[]}>};
options: NodeOption[];
big: boolean;
id: string;
name: string;
};
export function trafficState(series: {down: Array<number | null>; up: Array<number | null>}, available: boolean | undefined, loaded: boolean) {
export function trafficState(series: {down: Array<number | null>; up: Array<number | null>}, available: boolean | undefined, loaded: boolean, live = false) {
if (series.down.some(value => value !== null) || series.up.some(value => value !== null)) return 'ready';
return available === false ? 'unavailable' : !loaded ? 'loading' : 'empty';
if (available === false) return live ? 'loading' : 'unavailable';
return !loaded ? 'loading' : 'empty';
}
type NodeOption = {id: string; name: string; label: string; tcp?: number; alive?: boolean; unavailable: boolean; healthError?: string};
// The picker's menu is built from `options` only while it is open (see NodeMenu), not on every poll.
export function nodeView(nodes: Node[], chosen: string, t: LabelFn) {
const counts = new Map<string, number>();
for (const node of nodes) counts.set(node.name, (counts.get(node.name) ?? 0) + 1);
const options = nodes.map(node => {
const options = nodes.map((node): NodeOption => {
const health = preferredHealth(node);
return {
id: node.id,
@@ -87,7 +107,7 @@ export function nodeView(nodes: Node[], chosen: string, t: LabelFn) {
const node =
options.find(n => n.id === chosen) ?? options.find(n => n.tcp !== undefined) ?? options.find(n => n.name !== 'direct' && n.name !== 'block') ?? options[0];
return {
menu: menuViews(options, t),
options,
big: options.length > 12,
id: node?.id ?? '',
name: node?.name ?? '',
@@ -97,7 +117,7 @@ export function nodeView(nodes: Node[], chosen: string, t: LabelFn) {
healthError: node?.healthError
};
}
export function activityView(runtime: Runtime | undefined, memory: RuntimeMemory | undefined, t: LabelFn, runtimeAvailable?: boolean) {
export function activityView(runtime: Runtime | undefined, memory: RuntimeMemory | undefined, t: LabelFn, runtimeAvailable?: boolean, locale = 'en') {
const percent = pctU64(memory?.cgroup?.current_bytes ?? null, memory?.cgroup?.limit_bytes ?? null);
return {
status: {
@@ -106,7 +126,7 @@ export function activityView(runtime: Runtime | undefined, memory: RuntimeMemory
},
download: formatRate(runtime?.traffic.rates?.download_bytes_per_second ?? null),
upload: formatRate(runtime?.traffic.rates?.upload_bytes_per_second ?? null),
connections: runtime?.traffic.connections.total ?? '—',
connections: runtime?.traffic.connections.total == null ? '—' : formatNumber(runtime.traffic.connections.total, locale),
rss: formatBytes(memory?.process?.rss_bytes ?? null),
memoryBadge:
percent === null
+7 -5
View File
@@ -193,7 +193,7 @@ function Modules(props: ModulesProps) {
}
function SourceCard(props: SourceCardProps) {
const {canValidate, canWrite, contentOffered, focusLine} = props;
const {canValidate, canWrite, contentOffered} = props;
const t = useT();
const {
editing,
@@ -201,7 +201,7 @@ function SourceCard(props: SourceCardProps) {
marks,
text,
outbounds,
jump,
focus,
dirty,
validate,
save,
@@ -260,7 +260,7 @@ function SourceCard(props: SourceCardProps) {
<Light small tone={item.tone}>
{item.detail}
</Light>
<Button small quiet onPress={() => props.open(item.sourceId, item.line)}>
<Button small quiet label={t('config.openSourceAt', {where: item.where})} onPress={() => props.open(item.sourceId, item.line)}>
{t('config.openSource')}
</Button>
</div>
@@ -276,7 +276,7 @@ function SourceCard(props: SourceCardProps) {
readOnly={!editing || busy}
onChange={editing ? change : undefined}
marks={marks}
focusLine={jump ?? focusLine}
focusLine={focus}
outbounds={outbounds}
onSave={editing && dirty && !busy ? () => void save() : undefined}
/>
@@ -342,7 +342,9 @@ function ValidateTab(props: ValidateTabProps) {
<Light small tone={cur.tone}>
{cur.detail}
</Light>
<Button onPress={() => open(cur.sourceId, cur.line)}>{t('config.openSource')}</Button>
<Button label={t('config.openSourceAt', {where: cur.where})} onPress={() => open(cur.sourceId, cur.line)}>
{t('config.openSource')}
</Button>
</div>
)}
</>
+30 -3
View File
@@ -1,7 +1,7 @@
import {useT} from '../../i18n';
import type {ConfigSource} from '../../api/model';
import type {ConfigEditor} from './useConfigPage';
import {Button, LabeledSelect, TextField} from '../../ui/ui';
import {Button, LabeledSelect, Light, TextField} from '../../ui/ui';
import Close from '../../ui/icons/Close';
import {CodeEditor} from '../../ui/code/CodeEditor';
import type {WizardState} from '../../dae/setup';
@@ -13,6 +13,9 @@ export function Wizard(props: {main: ConfigSource; editor: ConfigEditor; onDone:
text,
busy,
rows,
diagnostics,
defaultDnsError,
chinaDnsError,
groupUsedText,
templateHelp,
networkError,
@@ -46,6 +49,7 @@ export function Wizard(props: {main: ConfigSource; editor: ConfigEditor; onDone:
label={t('config.wizardSubscriptionName')}
value={item.name}
width={140}
error={item.nameError}
onChange={name => setSubscription(item.index, {name})}
/>
<TextField
@@ -106,13 +110,36 @@ export function Wizard(props: {main: ConfigSource; editor: ConfigEditor; onDone:
onChange={listenerPort => patch({listenerPort})}
error={networkError}
/>
<TextField isDisabled={busy} label={t('config.wizardDefaultDns')} value={state.defaultDns} onChange={defaultDns => patch({defaultDns})} />
<TextField isDisabled={busy} label={t('config.wizardChinaDns')} value={state.chinaDns} onChange={chinaDns => patch({chinaDns})} />
<TextField
isDisabled={busy}
label={t('config.wizardDefaultDns')}
value={state.defaultDns}
error={defaultDnsError}
onChange={defaultDns => patch({defaultDns})}
/>
<TextField
isDisabled={busy}
label={t('config.wizardChinaDns')}
value={state.chinaDns}
error={chinaDnsError}
onChange={chinaDns => patch({chinaDns})}
/>
</div>
)}
<h3 className="rp-h3">{t('config.wizardPreview')}</h3>
<CodeEditor label={t('config.wizardPreview')} value={text} readOnly compact />
{diagnostics.length > 0 && (
<div className="rp-list rp-config-diagnostics" role="list" aria-label={t('config.diagnostics')}>
{diagnostics.map(item => (
<div key={item.id} role="listitem">
<Light small tone={item.tone}>
{item.detail}
</Light>
</div>
))}
</div>
)}
<div className="rp-toolbar">
<Button accent isDisabled={saveDisabled} isPending={saving} tip={saveTip} onPress={() => void apply()}>
{t('config.save')}
+1 -1
View File
@@ -24,7 +24,7 @@ export function useMainSourceEdit(): MainSourceEdit {
const complete = useSourceComplete(source);
const main = complete ? source : null;
// While the digest check is still running nothing is wrong yet; the notice waits for a verdict.
const incomplete = complete === false || (!!config.data && !source);
const incomplete = complete === false;
const error = useMemo(() => config.error ?? (incomplete ? new LocalError('config.incomplete') : null), [config.error, incomplete]);
const {apply} = editor;
return {
+3
View File
@@ -99,6 +99,7 @@ export const messages = defineMessages({
'config.code': '代碼',
'config.noDiagnostics': '沒有此等級的項目',
'config.openSource': '開啟來源',
'config.openSourceAt': '開啟來源:{where}',
'config.source': '來源',
'config.sourceFacts': '{lines} 行,{size},{time} 載入',
'config.unsaved': '未儲存',
@@ -208,6 +209,7 @@ export const messages = defineMessages({
'config.code': '代码',
'config.noDiagnostics': '没有此级别的项目',
'config.openSource': '打开来源',
'config.openSourceAt': '打开来源:{where}',
'config.source': '来源',
'config.sourceFacts': '{lines} 行,{size},{time} 加载',
'config.unsaved': '未保存',
@@ -322,6 +324,7 @@ export const messages = defineMessages({
'config.code': 'Code',
'config.noDiagnostics': 'No items at this level',
'config.openSource': 'Open source',
'config.openSourceAt': 'Open source: {where}',
'config.source': 'Source',
'config.sourceFacts': 'Line count: {lines}, {size}, loaded {time}',
'config.unsaved': 'Unsaved',
+12 -7
View File
@@ -35,7 +35,7 @@ function useConfigEditorController(refetch: () => void) {
useEffect(() => {
if (!editor.error) return;
if (diagnostics) {
toast('negative', t('config.invalid', {n: String(diagnostics.filter(d => d.level === 'error').length)}));
toast('negative', t('config.invalid', {n: diagnostics.filter(d => d.level === 'error').length}));
} else toast('negative', errorText(editor.error));
}, [editor.error, diagnostics, t]);
return {...editor, diagnostics};
@@ -57,9 +57,11 @@ export function useConfigPage({go, query}: PageProps) {
const tab =
requested === 'modules' || requested === 'source' || requested === 'validate' || (requested === 'setup' && setupAvailable)
? requested
: params.has('source') || !mainSource?.content
: params.has('source') || mainSource?.content === undefined
? 'source'
: 'modules';
: !mainSource.content.trim() && setupAvailable
? 'setup'
: 'modules';
// A stale link to a source that no longer exists opens the first one rather than an empty card.
const source = sources.find(item => item.id === params.get('source')) ?? sources[0] ?? null;
const selectedId = source?.id ?? null;
@@ -67,6 +69,7 @@ export function useConfigPage({go, query}: PageProps) {
const n = (value: number) => formatNumber(value, locale);
const focusLine = Number(params.get('line')) || null;
const groupList = useMemo(() => groupNames(mainSource?.content ?? ''), [mainSource]);
const sourceDiagnostics = useMemo(() => (config.data?.diagnostics ?? []).filter(item => item.source_id === selectedId), [config.data, selectedId]);
const counts = useMemo(() => {
const all = config.data?.diagnostics ?? [];
return {error: all.filter(d => d.level === 'error').length, warning: all.filter(d => d.level === 'warning').length};
@@ -76,7 +79,7 @@ export function useConfigPage({go, query}: PageProps) {
source,
sources,
open: (sourceId, line) => go('config', within(query, {tab: 'source', source: sourceId, line: line === null ? null : String(line)})),
diagnostics: (config.data?.diagnostics ?? []).filter(item => item.source_id === source.id),
diagnostics: sourceDiagnostics,
canValidate,
canWrite: resources?.config.writable === true && source.writable,
contentOffered: resources?.config.content === true,
@@ -149,7 +152,7 @@ export type SourceCardProps = {
focusLine: number | null;
};
export function useSourceCard({source, sources, diagnostics, canValidate, editor, groups}: SourceCardProps) {
export function useSourceCard({source, sources, diagnostics, canValidate, editor, groups, focusLine}: SourceCardProps) {
const t = useT();
const locale = LOCALE[useLang()];
// If-Match uses the draft's original digest to reject changes made on disk while editing.
@@ -167,6 +170,8 @@ export function useSourceCard({source, sources, diagnostics, canValidate, editor
return own.length ? own : groups;
};
const [jump, setJump] = useState<number | null>(null);
// A line asked for through the address (a diagnostic's "open source") wins over the last validation's first error.
useLinked(focusLine, () => setJump(null));
const dirty = editing && draft.text !== source.content;
const guard = useDraftGuard(dirty);
useLinked(guard.revision, () => {
@@ -182,7 +187,7 @@ export function useSourceCard({source, sources, diagnostics, canValidate, editor
// Put the cursor on the first error so the problem is on screen, not below a long file.
const first = result.diagnostics.find(d => d.source_id === source.id && d.level === 'error' && d.line !== null);
setJump(first ? first.line : null);
if (!result.valid) toast('negative', t('config.invalid', {n: String(result.diagnostics.filter(d => d.level === 'error').length)}));
if (!result.valid) toast('negative', t('config.invalid', {n: result.diagnostics.filter(d => d.level === 'error').length}));
else if (announce) toast('positive', t('config.valid'));
return result.valid;
};
@@ -218,7 +223,7 @@ export function useSourceCard({source, sources, diagnostics, canValidate, editor
marks,
text,
outbounds,
jump,
focus: jump ?? focusLine,
dirty,
validate,
save,
+32 -10
View File
@@ -1,5 +1,6 @@
import {useEffect, useMemo, useState} from 'react';
import {completeSource} from '../../store/config';
import {ApiError} from '../../api/error';
import type {ConfigDiagnostic, ConfigSource, EffectiveConfig} from '../../api/model';
import {LOCALE, useLang, useT} from '../../i18n';
import {toast, useLinked} from '../../ui/ui';
@@ -17,16 +18,22 @@ export type ModulesProps = {
canValidate: boolean;
open: (sourceId: string, line: number | null) => void;
};
const checkKey = (source: ConfigSource) => JSON.stringify([source.id, source.content_sha256, source.content ?? null]);
type Draft = {section: ModuleSection & {source: ConfigSource; block: NonNullable<ModuleSection['block']>}; text: string};
export function useModules({config, editor, canWrite, canValidate, open}: ModulesProps) {
const t = useT();
const locale = LOCALE[useLang()];
const sections = useMemo(() => sectionSummaries(config.sources, t), [config, t]);
const [checked, setChecked] = useState<Map<ConfigSource, boolean>>(new Map());
const lang = useLang();
const locale = LOCALE[lang];
const sections = useMemo(() => sectionSummaries(config.sources, lang, t), [config, lang, t]);
// Keyed by digest, not by object: a refetch returns new objects for the same text, and the edit buttons would drop
// out until the check reran.
const [checked, setChecked] = useState<Map<string, boolean>>(new Map());
const keys = useMemo(() => new Map(config.sources.map(source => [source, checkKey(source)])), [config]);
const isComplete = (source: ConfigSource | null) => (source ? checked.get(keys.get(source) ?? checkKey(source)) : undefined);
useEffect(() => {
let live = true;
void Promise.all(config.sources.map(async source => [source, await completeSource(source)] as const)).then(entries => {
void Promise.all(config.sources.map(async source => [checkKey(source), await completeSource(source)] as const)).then(entries => {
if (live) setChecked(new Map(entries));
});
return () => {
@@ -36,6 +43,17 @@ export function useModules({config, editor, canWrite, canValidate, open}: Module
const [draft, setDraft] = useState<Draft | null>(null);
const [found, setFound] = useState<ConfigDiagnostic[] | null>(null);
const dirty = draft !== null && draft.text !== draft.section.source.content!.slice(draft.section.block.from, draft.section.block.to);
// A save refused because the file changed on disk: the refetched section becomes the base and the typed text
// stays, so the next save carries the new digest instead of failing with 412 again.
const stale = editor.error instanceof ApiError && editor.error.status === 412 && !!draft && editor.errorSource === draft.section.source.id;
const rebased = stale
? sections.find(
section => section.id === draft.section.id && section.source && section.block && section.source.content_sha256 !== draft.section.source.content_sha256
)
: undefined;
useLinked(rebased ?? null, next => {
if (next?.source && next.block) setDraft(current => current && {...current, section: {...next, source: next.source!, block: next.block!}});
});
const guard = useDraftGuard(dirty);
const {clear} = guard;
useLinked(guard.revision, () => {
@@ -48,7 +66,9 @@ export function useModules({config, editor, canWrite, canValidate, open}: Module
const candidates = useValidationSources(config.sources, sourceId && fullText !== null ? {id: sourceId, content: fullText} : undefined);
useBackgroundValidation(canValidate && fullText !== null ? candidates : null, setFound);
const shown = (editor.errorSource === sourceId ? editor.diagnostics : null) ?? found ?? config.diagnostics;
const marks = useMemo(() => (draft ? sectionMarks(shown, draft.section.source.id, draft.section.block, draft.text) : []), [shown, draft]);
// The editor holds one file; diagnostics from other sources belong to their own cards.
const own = useMemo(() => shown.filter(item => item.source_id === sourceId), [shown, sourceId]);
const marks = useMemo(() => (draft ? sectionMarks(own, draft.section.source.id, draft.section.block, draft.text) : []), [own, draft]);
const outbounds = useMemo(() => groupNames(fullText ?? config.sources.find(source => source.kind === 'main')?.content ?? ''), [fullText, config]);
const cancel = () => {
editor.cancel();
@@ -78,18 +98,20 @@ export function useModules({config, editor, canWrite, canValidate, open}: Module
setDraft(null);
setFound(null);
};
// A section removed on disk while being edited keeps its card, so the draft is not stranded out of sight.
const cards = draft && !sections.some(section => section.id === draft.section.id) ? [...sections, draft.section] : sections;
return {
cards: sections.map(section => ({
cards: cards.map(section => ({
...section,
editing: draft?.section.id === section.id,
canEdit: canWrite && !!section.source?.writable && !!section.block && checked.get(section.source) === true,
canEdit: canWrite && !!section.source?.writable && !!section.block && isComplete(section.source) === true,
editDisabled: dirty || !!editor.busy,
note: section.note ?? (section.source && section.block && checked.get(section.source) === false ? t('config.incomplete') : null),
note: section.note ?? (section.source && section.block && isComplete(section.source) === false ? t('config.incomplete') : null),
muted: !section.block,
// The whole file in the Sources tab, at this section's first line; a missing section opens the main file.
manual: section.source && section.source.content !== undefined ? () => open(section.source!.id, section.block ? section.block.line + 1 : null) : null,
edit: () => {
if (dirty || editor.busy || !canWrite || !section.source?.writable || !section.block || checked.get(section.source) !== true) return;
if (dirty || editor.busy || !canWrite || !section.source?.writable || !section.block || isComplete(section.source) !== true) return;
setFound(null);
setDraft({
section: {...section, source: section.source, block: section.block},
@@ -103,7 +125,7 @@ export function useModules({config, editor, canWrite, canValidate, open}: Module
setDraft(previous => (previous ? {...previous, text} : null));
},
marks,
diagnostics: diagnosticRows(shown, config.sources, locale, t),
diagnostics: diagnosticRows(own, config.sources, locale, t),
outbounds: () => outbounds,
dirty,
busy: !!editor.busy,
+36 -11
View File
@@ -1,13 +1,15 @@
import {ApiError} from '../../api/error';
import {useEffect, useMemo, useState} from 'react';
import {useT} from '../../i18n';
import {LOCALE, useLang, useT} from '../../i18n';
import type {Key} from '../../i18n/messages';
import type {ConfigSource} from '../../api/model';
import type {ConfigDiagnostic, ConfigSource} from '../../api/model';
import type {ConfigEditor} from './useConfigPage';
import {useSourceComplete} from '../../store/config';
import {errorText, toast, useLinked} from '../../ui/ui';
import {validNetwork, validSubscriptions, writeState, type WizardState} from '../../dae/setup';
import {nextSubscriptionName, validNetwork, validSubscriptions, writeState, type WizardState} from '../../dae/setup';
import {isQuotable} from '../../dae/text';
import {type RuleTemplate} from '../../dae/templates';
import {wizardInitial, wizardRows} from './view';
import {diagnosticRows, sourceView, wizardInitial, wizardRows} from './view';
import {useDraftGuard} from './useDraftGuard';
const templateIds: RuleTemplate[] = ['global', 'bypass', 'gfw', 'mini', 'standard', 'full'];
const templateLabels: Record<RuleTemplate, [Key, Key]> = {
@@ -21,6 +23,8 @@ const templateLabels: Record<RuleTemplate, [Key, Key]> = {
// Edit subscriptions and optional routing templates while preserving existing groups. Never write back redacted text whose digest does not match.
export function useWizard({main, editor, onDone}: {main: ConfigSource; editor: ConfigEditor; onDone: () => void}) {
const t = useT();
const lang = useLang();
const locale = LOCALE[lang];
// Keep the accepted snapshot so a concurrent file change is rejected by If-Match.
const [origin, setOrigin] = useState(() => main);
const complete = useSourceComplete(origin);
@@ -37,14 +41,27 @@ export function useWizard({main, editor, onDone}: {main: ConfigSource; editor: C
const {text} = preview;
const busy = !!editor.busy;
const dirty = preview.error !== null || (complete === true && text !== baseline);
// An empty file is written as generated, so the untouched form is already something to save; it does not count as
// a draft to guard.
const pending = dirty || (complete === true && !current.trim());
const [found, setFound] = useState<ConfigDiagnostic[] | null>(null);
const guard = useDraftGuard(dirty);
useLinked(guard.revision, () => {
setOrigin(main);
setState(wizardInitial(main.content ?? ''));
setFound(null);
});
useEffect(() => editor.cancel, [editor.cancel, guard.revision]);
// A save refused because the file changed on disk: the refetched file becomes the base, the form stays as typed.
const stale = editor.error instanceof ApiError && editor.error.status === 412;
useLinked(stale && main.content_sha256 !== origin.content_sha256 ? main : null, next => {
if (next) setOrigin(next);
});
const valid = validSubscriptions(state.subscriptions) && (!!current.trim() || validNetwork(state));
const patch = (next: Partial<WizardState>) => setState(prev => ({...prev, ...next}));
const patch = (next: Partial<WizardState>) => {
setFound(null);
setState(prev => ({...prev, ...next}));
};
// Editing a line hands it to the form; the original text is no longer written back for it.
const setSubscription = (index: number, value: Partial<WizardState['subscriptions'][number]>) =>
patch({subscriptions: state.subscriptions.map((item, i) => (i === index ? {...item, ...value, raw: undefined} : item))});
@@ -57,36 +74,44 @@ export function useWizard({main, editor, onDone}: {main: ConfigSource; editor: C
const result = await editor.apply(origin, text);
if (!result) return;
if (result.diagnostics) {
toast('negative', t('config.invalid', {n: String(result.diagnostics.filter(d => d.level === 'error').length)}));
setFound(result.diagnostics);
toast('negative', t('config.invalid', {n: result.diagnostics.filter(d => d.level === 'error').length}));
return;
}
toast('positive', t('config.saved', {path: main.path}));
toast('positive', t('config.saved', {path: label}));
guard.clear();
onDone();
};
const rows = wizardRows(state, preview.error ? errorText(preview.error) : undefined, t);
const label = sourceView(main, locale, t).label;
const rows = wizardRows(state, lang, t);
// A save refused with 422 carries the same diagnostics as a validation refusal.
const diagnostics = (editor.errorSource === origin.id ? editor.diagnostics : null) ?? found ?? [];
const dnsError = (value: string) => (isQuotable(value.trim()) ? undefined : t('config.unquotable'));
return {
state,
current,
text,
busy,
rows: rows.rows,
diagnostics: diagnosticRows(diagnostics, [main], locale, t),
defaultDnsError: dnsError(state.defaultDns),
chinaDnsError: dnsError(state.chinaDns),
groupUsedText: rows.groupUsedText,
templateHelp: state.rules === 'keep' ? null : t('config.wizardPresetHelp'),
networkError: !current.trim() && !validNetwork(state) ? t('config.wizardNetworkError') : undefined,
patch,
setSubscription,
apply,
saveDisabled: !complete || !valid || busy || !dirty,
saveDisabled: !complete || !valid || busy || !pending,
saving: editor.busy === 'save',
saveTip: complete === false ? t('config.incomplete') : undefined,
writeHelp: current.trim() ? t('config.wizardWriteHelp', {path: main.path}) : null,
writeHelp: current.trim() ? t('config.wizardWriteHelp', {path: label}) : null,
showLan: !current.trim(),
templates: [
...(current.trim() ? [{id: 'keep', label: t('config.wizardKeep'), desc: t('config.wizardKeepHelp')}] : []),
...templateIds.map(id => ({id, label: t(templateLabels[id][0]), desc: t(templateLabels[id][1])}))
],
add: () => patch({subscriptions: [...state.subscriptions, {name: `sub-${state.subscriptions.length + 1}`, url: ''}]}),
add: () => patch({subscriptions: [...state.subscriptions, {name: nextSubscriptionName(state.subscriptions), url: ''}]}),
remove: (index: number) => patch({subscriptions: state.subscriptions.filter((_, i) => i !== index)})
};
}
+49 -6
View File
@@ -35,7 +35,7 @@ it('initializes empty setup and preserves opaque subscription lines while hiding
{name: '', url: '', raw: 'file: /etc/nodes'},
{name: 'bad', url: 'ftp://example.org'}
];
const view = wizardRows(state, undefined, t);
const view = wizardRows(state, 'en', t);
expect(view.rows.map(row => row.index)).toEqual([1, 2]);
expect(view.rows[0].raw).toBe('file: /etc/nodes');
expect(view.rows[1].error).toBe(t('config.wizardSubscriptionHelp'));
@@ -85,7 +85,7 @@ routing {
fallback: proxy
}`);
const include = source('routing { fallback: direct }', 'include');
const cards = sectionSummaries([main, include], t);
const cards = sectionSummaries([main, include], 'en', t);
expect(cards.map(card => card.kind)).toEqual(['global', 'subscription', 'node', 'group', 'dns', 'routing', 'routing']);
expect(cards.find(card => card.kind === 'dns')?.summary).toBe('1 upstream, 1 request rule, 1 response rule');
expect(cards.filter(card => card.kind === 'routing').map(card => [card.range, card.summary])).toEqual([
@@ -121,9 +121,52 @@ it('maps only diagnostics within the edited section using its current line count
it('withholds editing for missing source text and native_api sections', () => {
const hidden = {...source(''), content: undefined};
const cards = sectionSummaries([hidden, source('experimental { native_api { token: redacted } }', 'include')], t);
const cards = sectionSummaries([hidden, source('experimental { native_api { token: redacted } }', 'include')], 'en', t);
expect(cards.filter(card => card.kind === 'experimental.native_api')).toMatchObject([{block: null, note: t('config.incomplete')}]);
expect(cards.find(card => card.id === 'main')).toMatchObject({block: null, note: t('config.contentWithheld')});
// One card says the main text is withheld; no per-section cards repeat it.
expect(cards.filter(card => card.note === t('config.contentWithheld'))).toHaveLength(1);
});
it('counts untagged entries and arrows written without spaces', () => {
const main = source(`subscription {
tagged: 'https://example.org/a'
'https://example.org/b'
}
node {
'vless://x'
}
routing {
dip(geoip:private)->direct
domain(example.org) -> proxy
fallback: proxy
}`);
const cards = sectionSummaries([main], 'en', t);
expect(cards.find(card => card.kind === 'subscription')?.summary).toBe('2 subscriptions');
expect(cards.find(card => card.kind === 'node')?.summary).toBe('1 node');
expect(cards.find(card => card.kind === 'routing')?.summary).toBe('2 rules · fallback: proxy');
});
it('keeps a card id when text before the section changes', () => {
const id = (text: string) => sectionSummaries([source(text)], 'en', t).find(card => card.kind === 'routing')!.id;
expect(id('# a\nrouting { fallback: direct }')).toBe(id('# a longer comment\n\nrouting { fallback: direct }'));
});
it('flags only the row whose value cannot be quoted', () => {
const state = {
...wizardInitial(''),
subscriptions: [
{name: 'good', url: 'https://example.org/a'},
{name: 'bad', url: "https://example.org/it's"},
{name: "o'neil", url: 'https://example.org/c'}
]
};
const rows = wizardRows(state, 'en', t).rows;
expect(rows.map(row => [row.nameError, row.error])).toEqual([
[undefined, undefined],
[undefined, t('config.unquotable')],
[t('config.unquotable'), undefined]
]);
});
it('marks only the edited source while retaining cross-source diagnostic locations', () => {
@@ -157,9 +200,9 @@ it('does not submit pathless includes or validate an omitted replacement source'
it('describes only the selected template’s groups and omits routing changes for keep', () => {
const state = {...wizardInitial('group { mix {} }'), group: 'mix'};
expect(wizardRows(state, undefined, t).groupUsedText).toBeNull();
expect(wizardRows({...state, rules: 'global'}, undefined, t).groupUsedText).toContain('mix');
const named = wizardRows({...state, rules: 'standard'}, undefined, t).groupUsedText;
expect(wizardRows(state, 'en', t).groupUsedText).toBeNull();
expect(wizardRows({...state, rules: 'global'}, 'en', t).groupUsedText).toContain('mix');
const named = wizardRows({...state, rules: 'standard'}, 'en', t).groupUsedText;
expect(named).toContain('proxy, auto, telegram, media, apple');
expect(named).not.toContain('mix');
});
+62 -32
View File
@@ -1,12 +1,12 @@
import type {ConfigDiagnostic, ConfigSource} from '../../api/model';
import {formatBytes} from '../../api/u64';
import {localTime} from '../../api/selectors';
import {formatNumber, type Translator} from '../../i18n';
import {formatList, formatNumber, type Lang, type Translator} from '../../i18n';
import type {Key} from '../../i18n/messages';
import {fileName, redacted} from './names';
import {defaultGroup, isSubscriptionUrl, readState, type WizardState} from '../../dae/setup';
import {defaultTemplate, templates} from '../../dae/templates';
import {blockFields, scanConfig, type TextBlock, type TextToken} from '../../dae/text';
import {blockFields, isQuotable, scanConfig, type TextBlock, type TextToken} from '../../dae/text';
import {buildHash} from '../../shell/route';
import type {EditorMark} from '../../ui/code/CodeEditor';
@@ -48,29 +48,45 @@ function ruleCount(text: string, block: TextBlock, tokens: TextToken[]): number
token.from > block.open &&
token.to <= block.close &&
token.depth === block.depth + 1 &&
token.parens === 0 &&
token.kind === 'text' &&
text.slice(token.from, token.to) === '->'
).length;
}
function sectionSummary(kind: SectionKind, text: string, block: TextBlock, tokens: TextToken[], t: Translator): string {
// Subscription and node entries may be a bare link without a tag; each such value is an entry of its own.
function entryCount(block: TextBlock, tokens: TextToken[], fields: ReturnType<typeof blockFields>): number {
const untagged = tokens.filter(
token =>
token.from > block.open &&
token.to <= block.close &&
token.depth === block.depth + 1 &&
token.parens === 0 &&
(token.kind === 'quoted' || token.kind === 'text') &&
!fields.some(field => token.from >= field.from && token.to <= field.to)
);
return fields.length + untagged.length;
}
function sectionSummary(kind: SectionKind, text: string, block: TextBlock, tokens: TextToken[], lang: Lang, t: Translator): string {
const fields = blockFields(text, block, tokens);
switch (kind) {
case 'global':
return t('config.moduleSettings', {n: fields.length});
case 'subscription':
return t('config.moduleSubscriptions', {n: fields.length});
return t('config.moduleSubscriptions', {n: entryCount(block, tokens, fields)});
case 'node':
return t('config.moduleNodes', {n: fields.length});
return t('config.moduleNodes', {n: entryCount(block, tokens, fields)});
case 'group':
return t('config.moduleGroups', {
n: block.children.length,
policies: block.children
.map(child => {
policies: formatList(
lang,
block.children.map(child => {
const policy = blockFields(text, child, tokens).find(field => field.name === 'policy')?.value;
return policy ? `${child.name}: ${policy}` : child.name;
})
.join(', ')
)
});
case 'dns': {
const upstreams = block.children.filter(child => child.name === 'upstream');
@@ -90,7 +106,8 @@ function sectionSummary(kind: SectionKind, text: string, block: TextBlock, token
}
}
export function sectionSummaries(sources: ConfigSource[], t: Translator): ModuleSection[] {
// Card ids count occurrences rather than offsets, so an edit elsewhere in the file keeps an open editor on its card.
export function sectionSummaries(sources: ConfigSource[], lang: Lang, t: Translator): ModuleSection[] {
const eligible = sources.filter(source => source.kind === 'main' || (source.kind === 'include' && source.writable));
const parsed = eligible.map(source => ({source, ...scanConfig(source.content ?? '')}));
const main = sources.find(source => source.kind === 'main') ?? null;
@@ -99,31 +116,31 @@ export function sectionSummaries(sources: ConfigSource[], t: Translator): Module
const occurrences = parsed.flatMap(({source, blocks, tokens}) =>
blocks
.filter(block => block.name === kind)
.map(block => ({
id: `${source.id}:${block.from}`,
.map((block, index) => ({
id: `${source.id}:${kind}:${index}`,
kind,
source,
block,
href,
range: sectionRange(source, block),
summary: sectionSummary(kind, source.content!, block, tokens, t),
summary: sectionSummary(kind, source.content!, block, tokens, lang, t),
note: null
}))
);
return occurrences.length
? occurrences
: [
{
id: kind,
kind,
source: main,
block: null,
href,
range: main ? fileName(main) : 'config.dae',
summary: main?.content === undefined ? '' : t('config.moduleAbsent', {file: fileName(main)}),
note: main?.content === undefined ? t('config.contentWithheld') : null
}
];
// A main file whose text is withheld gets one card of its own below; absence cannot be told from it.
if (occurrences.length || (main && main.content === undefined)) return occurrences;
return [
{
id: kind,
kind,
source: main,
block: null,
href,
range: main ? fileName(main) : 'config.dae',
summary: main?.content === undefined ? '' : t('config.moduleAbsent', {file: fileName(main)}),
note: main?.content === undefined ? t('config.contentWithheld') : null
}
];
});
const withheld: ModuleSection[] = parsed.flatMap(({source, blocks}) => {
if (source.content === undefined)
@@ -141,8 +158,8 @@ export function sectionSummaries(sources: ConfigSource[], t: Translator): Module
];
return blocks
.filter(block => block.name === 'experimental' && block.children.some(child => child.name === 'native_api'))
.map(block => ({
id: `${source.id}:${block.from}`,
.map((block, index) => ({
id: `${source.id}:experimental:${index}`,
kind: 'experimental.native_api',
source,
block: null,
@@ -191,7 +208,7 @@ type DiagnosticRow = {
inline: string;
detail: string;
};
type WizardRow = {index: number; name: string; url: string; raw: string | null; error?: string; description?: string; removeLabel: string};
type WizardRow = {index: number; name: string; url: string; raw: string | null; nameError?: string; error?: string; description?: string; removeLabel: string};
const tones = {error: 'err', warning: 'warn', info: 'info'} as const;
const levels: Record<ConfigDiagnostic['level'], Key> = {error: 'config.level.error', warning: 'config.level.warning', info: 'config.level.info'};
export function diagnosticRows(diagnostics: ConfigDiagnostic[], sources: ConfigSource[], locale: string, t: Translator): DiagnosticRow[] {
@@ -217,13 +234,20 @@ export function wizardInitial(content: string): WizardState {
const read = readState(content);
return {...read, rules: content.trim() ? 'keep' : defaultTemplate};
}
export function wizardRows(state: WizardState, error: string | undefined, t: Translator): {groupUsedText: string | null; rows: WizardRow[]} {
// A value the file cannot hold is flagged on its own field, not on every row.
const writableName = (name: string) => /^[\w.-]+$/.test(name.trim()) || isQuotable(name.trim());
export function wizardRows(state: WizardState, lang: Lang, t: Translator): {groupUsedText: string | null; rows: WizardRow[]} {
return {
groupUsedText:
state.rules === 'keep'
? null
: templates[state.rules].groups.length
? t('config.wizardNamedGroups', {names: templates[state.rules].groups.map(group => group.name).join(', ')})
? t('config.wizardNamedGroups', {
names: formatList(
lang,
templates[state.rules].groups.map(group => group.name)
)
})
: t('config.wizardGroupUsed', {name: state.group ?? defaultGroup}),
rows: state.subscriptions.flatMap((item, index) =>
item.raw !== undefined && !item.raw.trim()
@@ -234,7 +258,13 @@ export function wizardRows(state: WizardState, error: string | undefined, t: Tra
name: item.name,
url: item.url,
raw: item.raw !== undefined && !item.name ? item.raw.trim() : null,
error: item.url !== '' && !isSubscriptionUrl(item.url) ? t('config.wizardSubscriptionHelp') : error,
nameError: item.raw === undefined && !writableName(item.name) ? t('config.unquotable') : undefined,
error:
item.url !== '' && !isSubscriptionUrl(item.url)
? t('config.wizardSubscriptionHelp')
: item.raw === undefined && !isQuotable(item.url.trim())
? t('config.unquotable')
: undefined,
description: index === 0 ? t('config.wizardSubscriptionHelp') : undefined,
removeLabel: t('config.wizardRemove', {name: item.name || item.raw?.trim() || ''})
}
+40 -1
View File
@@ -1,5 +1,5 @@
import {describe, expect, it} from 'vitest';
import {readState, validNetwork, validSubscriptions, writeState} from '../../dae/setup';
import {nextSubscriptionName, readState, validNetwork, validSubscriptions, writeState} from '../../dae/setup';
import {readGroupEntries} from '../../dae/groups';
it('keeps template groups inside an inline group section', () => {
@@ -198,3 +198,42 @@ it('writes explicit first-run network inputs and rejects missing or invalid list
expect(validNetwork({...state, listenerPort: '53\nnode {}'})).toBe(false);
expect(validNetwork({...state, defaultDns: ' '})).toBe(false);
});
describe('setup writes what dae reads back', () => {
it('quotes a group name that needs quotes where the templates route to it', () => {
const text = "group {\n 'my group' {\n policy: min\n }\n}\nrouting {\n fallback: direct\n}\n";
const out = writeState(text, {...readState(text), rules: 'global'});
expect(out).toContain("fallback: 'my group'");
expect(out).not.toMatch(/fallback: my group/);
});
it('writes subscription names trimmed and treats trimmed names as duplicates', () => {
const state = readState('');
const subscriptions = [
{name: 'a ', url: 'https://example.org/a'},
{name: 'a', url: 'https://example.org/b'}
];
expect(validSubscriptions(subscriptions)).toBe(false);
const out = writeState('', {...state, subscriptions: [{name: ' paid ', url: 'https://example.org/sub'}]});
expect(out).toContain("paid: 'https://example.org/sub'");
});
it('adds to an empty subscription block without a blank first line', () => {
const text = 'subscription {}\n';
const state = readState(text);
expect(state.subscriptions).toEqual([]);
const out = writeState(text, {...state, subscriptions: [{name: 'paid', url: 'https://example.org/sub'}]});
expect(out).toContain("subscription {\n paid: 'https://example.org/sub'\n}");
});
});
it('names a new subscription after the first free sub-N', () => {
expect(nextSubscriptionName([])).toBe('sub-1');
expect(nextSubscriptionName([{name: 'sub-2', url: ''}])).toBe('sub-3');
expect(
nextSubscriptionName([
{name: 'a', url: ''},
{name: '', url: '', raw: 'sub-3 {}', tag: 'sub-3'}
])
).toBe('sub-4');
});
+34 -28
View File
@@ -1,37 +1,43 @@
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 (
<ModalDialog
title={t('conn.closeAll')}
narrow
alert
isOpen={open}
onOpenChange={setOpen}
trigger={
<Button negative quiet isDisabled={disabled} isPending={pending} onPress={setOpen ? () => setOpen(true) : undefined}>
{t('conn.closeAll')}
</Button>
}
footer={close => (
<>
<Button onPress={close}>{t('ui.cancel')}</Button>
<Button
negative
onPress={() => {
close();
run();
}}
>
{t('conn.closeAll')}
</Button>
</>
)}
>
<span className="rp-label">{confirmationText}</span>
</ModalDialog>
<>
<Button negative quiet isDisabled={disabled} isPending={pending} onPress={() => change(true)}>
{t('conn.closeAll')}
</Button>
<ModalDialog
title={t('conn.closeAll')}
narrow
alert
isOpen={isOpen}
onOpenChange={change}
footer={close => (
<>
<Button onPress={close}>{t('ui.cancel')}</Button>
<Button
negative
onPress={() => {
close();
run();
}}
>
{t('conn.closeAll')}
</Button>
</>
)}
>
<span className="rp-label">{confirmationText}</span>
</ModalDialog>
</>
);
}
+6 -3
View File
@@ -1,4 +1,4 @@
import {useMemo, type ComponentProps, type ReactNode} from 'react';
import {useMemo, type ComponentProps, type ReactNode, useState} from 'react';
import {Table, ResizableTableContainer, TableBody, Row, Cell, Virtualizer, TableLayout} from 'react-aria-components';
import {useT} from '../../i18n';
import {Badge, DataTable, TextTooltip, useFillHeight, useContentWidth, RuleRef, Loading, type TableColumn} from '../../ui/ui';
@@ -12,6 +12,9 @@ type Props = Pick<ComponentProps<typeof DataTable<ConnectionRowView>>, 'loading'
export function ConnectionTable({collection, view, loading, selected, onSelect, selectOnFocus, onSort}: Props) {
const t = useT();
const [ref, height] = useFillHeight<HTMLDivElement>(442);
// As in DataTable: once the box has shown its full height while loading, it keeps it.
const [reserved, setReserved] = useState(!!loading && !collection.length);
if (!reserved && loading && !collection.length) setReserved(true);
const [gridRef, width] = useContentWidth<HTMLElement>();
const definitions = useMemo(() => {
const renderers: Record<string, (c: ConnectionRowView) => ReactNode> = {
@@ -33,7 +36,7 @@ export function ConnectionTable({collection, view, loading, selected, onSelect,
const shown: TableColumn<ConnectionRowView>[] = useMemo(() => fitColumns(definitions, width), [definitions, width]);
const flatRows = useMemo(() => collection.flatMap(row => ('connection' in row ? [row.connection] : [null, ...row.children])), [collection]);
const groupKeys = useMemo(() => collection.filter(row => !('connection' in row)).map(row => row.id), [collection]);
useTableReveal(selected ? flatRows.findIndex(row => row?.id === selected) : -1, gridRef);
useTableReveal(selected ?? null, selected ? flatRows.findIndex(row => row?.id === selected) : -1, gridRef);
const renderRow = (row: ConnectionRowView) => (
<Row key={row.id} id={row.id} textValue={row.target}>
{shown.map(column => (
@@ -54,7 +57,7 @@ export function ConnectionTable({collection, view, loading, selected, onSelect,
>
<ResizableTableContainer
className="rp-table"
style={{height: Math.min(height, 2 + tableLayout.headingHeight + Math.max(flatRows.length, 2) * tableLayout.rowHeight)}}
style={{height: reserved ? height : Math.min(height, 2 + tableLayout.headingHeight + Math.max(flatRows.length, 2) * tableLayout.rowHeight)}}
>
<Virtualizer layout={TableLayout} layoutOptions={tableLayout}>
<Table
+9
View File
@@ -46,6 +46,9 @@ export const messages = defineMessages({
'conn.f.ingress': '入口',
'conn.f.domainSource': '網域來源',
'conn.f.observedBy': '觀測來源',
'conn.observed.userspace': '使用者空間',
'conn.observed.ebpf': 'eBPF',
'conn.observed.mixed': '使用者空間與 eBPF',
'conn.f.uploadRate': '上傳速率',
'conn.f.downloadRate': '下載速率',
'conn.f.started': '開始時間'
@@ -95,6 +98,9 @@ export const messages = defineMessages({
'conn.f.ingress': '入口',
'conn.f.domainSource': '域名来源',
'conn.f.observedBy': '观测来源',
'conn.observed.userspace': '用户空间',
'conn.observed.ebpf': 'eBPF',
'conn.observed.mixed': '用户空间与 eBPF',
'conn.f.uploadRate': '上传速率',
'conn.f.downloadRate': '下载速率',
'conn.f.started': '开始时间'
@@ -150,6 +156,9 @@ export const messages = defineMessages({
'conn.f.ingress': 'Ingress',
'conn.f.domainSource': 'Domain source',
'conn.f.observedBy': 'Observed by',
'conn.observed.userspace': 'Userspace',
'conn.observed.ebpf': 'eBPF',
'conn.observed.mixed': 'Userspace and eBPF',
'conn.f.uploadRate': 'Upload rate',
'conn.f.downloadRate': 'Download rate',
'conn.f.started': 'Start time'
+18 -8
View File
@@ -1,8 +1,8 @@
import {useMemo, useState} from 'react';
import {useDeferredValue, useEffect, useMemo, useRef, useState} from 'react';
import {useCapabilities, useConnectionClose, useConnections as useConnectionResource, useOutboundNames} from '../../store';
import {ApiError} from '../../api/error';
import {chainNames, connectionRows, ipLiteral} from '../../api/selectors';
import {downloadFile, errorText, exportName, panelQuery, toast, useDebounced, useLinked, useMediaQuery} from '../../ui/ui';
import {chainNames, connectionRows, ipLiteral, outboundLabel} from '../../api/selectors';
import {downloadFile, errorText, exportName, panelQuery, toast, useLinked, useMediaQuery} from '../../ui/ui';
import {within} from '../../shell/route';
import {useT, useLang, LOCALE} from '../../i18n';
import type {PageProps} from '../types';
@@ -47,8 +47,15 @@ export function useConnections({go, query}: PageProps) {
const sel = q.get('id');
const [confirmed, setConfirmed] = useState<CloseSelection | null>(null);
useLinked(q.get('q'), value => setText(value ?? ''));
const select = (id: string | null) => go('connections', within(query, {id}));
const settledText = useDebounced(text, 300);
// A close resolves after the person may have changed the filters; navigating from the query captured when it
// started would put the old ones back.
const latest = useRef(query);
useEffect(() => {
latest.current = query;
});
const select = (id: string | null) => go('connections', within(latest.current, {id}));
// Filtering follows typing at React's pace, not a fixed delay, so an export or close right after typing sees the new list.
const settledText = useDeferredValue(text);
const src = ipLiteral(q.get('src') ?? '');
const resource = useConnectionResource(src);
const capabilities = useCapabilities();
@@ -58,7 +65,7 @@ export function useConnections({go, query}: PageProps) {
const names = useOutboundNames();
const closing = useConnectionClose(resource.refetch);
const rows = useMemo(() => connectionRows(resource.data), [resource.data]);
const needle = text.trim().toLowerCase();
const needle = settledText.trim().toLowerCase();
const shown = useMemo(
() =>
rows.filter(
@@ -67,9 +74,12 @@ export function useConnections({go, query}: PageProps) {
(out === 'all' || c.outbound === out) &&
(rule === 'all' || c.rule_expression === rule) &&
(!needle ||
[c.dst, c.domain, c.src, c.pname, c.outbound, chainNames(c.chain, names).join(' '), c.rule_expression].join(' ').toLowerCase().includes(needle))
[c.dst, c.domain, c.src, c.pname, outboundLabel(c.outbound, t), chainNames(c.chain, names).join(' '), c.rule_expression]
.join(' ')
.toLowerCase()
.includes(needle))
),
[rows, network, out, rule, needle, names]
[rows, network, out, rule, needle, names, t]
);
const cur = sel ? rows.find(c => c.id === sel) : undefined;
const model = useMemo(
+22 -1
View File
@@ -15,7 +15,8 @@ it('groups by client address without losing IPv6 hosts or UInt64 precision', ()
{...c, id: 'd', src: '10.0.0.7:456', state: 'closed', download_bytes: '2'}
],
{hidden: [], sort: null, group: 'source'},
'en-US'
'en-US',
t
);
expect(rows.map(row => ('group' in row ? [row.group, row.children.length, row.active, row.download] : row.id))).toEqual([
['2001:db8::1', 2, 2, 9007199254741000n],
@@ -23,6 +24,26 @@ it('groups by client address without losing IPv6 hosts or UInt64 precision', ()
]);
});
it('groups, sorts and describes by the displayed labels', () => {
const c = connections.tcp[0];
const list = [
{...c, id: 'a', outbound: 'direct', state: 'dialing' as const},
{...c, id: 'b', outbound: null, state: 'active' as const},
{...c, id: 'c', outbound: 'unknown', state: 'blocked' as const}
];
const groups = tableRows(list, {hidden: [], sort: null, group: 'outbound'}, 'en-US', t);
expect(groups.map(row => ('group' in row ? [row.group, row.children.length] : row.id))).toEqual([
[t('ui.direct'), 1],
[t('ui.unknown'), 2]
]);
const sorted = tableRows(list, {hidden: [], sort: {column: 'state', direction: 'ascending'}, group: 'none'}, 'en-US', t);
expect(sorted.map(row => row.id)).toEqual(
[...list].sort((x, y) => t(`conn.state.${x.state}`).localeCompare(t(`conn.state.${y.state}`), 'en-US')).map(row => row.id)
);
const fields = connectionDetails({...c, observed_by: 'ebpf'}, 'en-US');
expect(fields.find(([key]) => key === 'conn.f.observedBy')?.[1]).toEqual({key: 'conn.observed.ebpf'});
});
it('drops columns by priority until the minimum widths fit, keeping the target', () => {
const ids = (width: number | null, hidden: string[] = []) =>
fitColumns(
+14 -9
View File
@@ -11,11 +11,12 @@ import {
type MessageRef,
type OutboundNames
} from '../../api/selectors';
import type {Translator as LabelFn} from '../../i18n';
import {formatNumber, type Translator as LabelFn} from '../../i18n';
import {word} from '../flows/view';
import type {Key} from '../../i18n/messages';
import type {SortDescriptor} from 'react-aria-components';
import {csvLine} from '../../ui/ui';
const observers: Record<Connection['observed_by'], Key> = {userspace: 'conn.observed.userspace', ebpf: 'conn.observed.ebpf', mixed: 'conn.observed.mixed'};
export function connectionDetails(c: Connection, locale: string): Array<[Key, string | MessageRef]> {
return [
['ui.source', c.src ?? '—'],
@@ -24,7 +25,7 @@ export function connectionDetails(c: Connection, locale: string): Array<[Key, st
['conn.f.ingress', word(c.ingress)],
['conn.f.domainSource', word(c.domain_source)],
['ui.process', c.pname ?? '—'],
['conn.f.observedBy', c.observed_by],
['conn.f.observedBy', observers[c.observed_by] ? {key: observers[c.observed_by]} : c.observed_by],
['ui.upload', formatBytes(c.upload_bytes)],
['ui.download', formatBytes(c.download_bytes)],
['conn.f.uploadRate', formatRate(c.upload_bytes_per_second)],
@@ -69,7 +70,8 @@ export function readView(stored: string | null): ConnectionView {
}
}
export function tableRows(rows: Connection[], view: ConnectionView, locale: string): TableRow[] {
// Sorts and groups by what the table shows: a state sorts by its label, not the wire value.
export function tableRows(rows: Connection[], view: ConnectionView, locale: string, t: LabelFn): TableRow[] {
let sorted = rows;
if (view.sort) {
const {column, direction} = view.sort;
@@ -80,7 +82,7 @@ export function tableRows(rows: Connection[], view: ConnectionView, locale: stri
case 'src':
return row.src;
case 'state':
return row.state;
return t(connectionStates[row.state]);
case 'down':
return parseU64(row.download_bytes);
case 'age':
@@ -103,7 +105,7 @@ export function tableRows(rows: Connection[], view: ConnectionView, locale: stri
// Source groups key on the address without the port, so one client is one group.
const groups = new Map<string, Connection[]>();
for (const row of sorted) {
const key = (view.group === 'source' ? (sourceIp(row.src ?? undefined) ?? row.src) : row.outbound) ?? '—';
const key = view.group === 'source' ? (sourceIp(row.src ?? undefined) ?? row.src ?? '—') : outboundLabel(row.outbound, t);
const group = groups.get(key);
if (group) group.push(row);
else groups.set(key, [row]);
@@ -149,7 +151,7 @@ export function connectionTableView(
download: formatBytes(c.download_bytes),
age: relativeStart(c.started_at, locale)
});
return tableRows(rows, view, locale).map(row =>
return tableRows(rows, view, locale, t).map(row =>
'connection' in row
? {id: row.id, connection: project(row.connection)}
: {
@@ -184,17 +186,20 @@ export function connectionsView(
['tcp', t('ui.tcp')],
['udp', t('ui.udp')]
] as Array<[string, string]>,
outbounds: [{id: 'all', label: t('conn.allOutbounds')}, ...[...new Set(rows.flatMap(c => (c.outbound ? [c.outbound] : [])))].map(id => ({id, label: id}))],
outbounds: [
{id: 'all', label: t('conn.allOutbounds')},
...[...new Set(rows.flatMap(c => (c.outbound ? [c.outbound] : [])))].map(id => ({id, label: outboundLabel(id, t)}))
],
picks: [
{
title: t('ui.source'),
value: 'src:' + src,
items: seen(rows.map(c => sourceIp(c.src))).map(([ip, n]) => ({id: 'src:' + ip, label: ip, desc: String(n)}))
items: seen(rows.map(c => sourceIp(c.src))).map(([ip, n]) => ({id: 'src:' + ip, label: ip, desc: formatNumber(n, locale)}))
},
{
title: t('conn.rule'),
value: 'rule:' + rule,
items: seen(rows.map(c => c.rule_expression)).map(([expression, n]) => ({id: 'rule:' + expression, label: expression, desc: String(n)}))
items: seen(rows.map(c => c.rule_expression)).map(([expression, n]) => ({id: 'rule:' + expression, label: expression, desc: formatNumber(n, locale)}))
}
],
visibility: data && data.visibility !== 'full' ? t(data.visibility === 'none' ? 'conn.visibilityNone' : 'conn.visibilityPartial') : null,
+60 -36
View File
@@ -1,11 +1,29 @@
import {useMemo} from 'react';
import {useT} from '../../i18n';
import Delete from '../../ui/icons/Delete';
import Download from '../../ui/icons/Download';
import {Badge, Button, DataTable, ErrorMessage, Light, TextTooltip, Kv, LabeledSelect, Tabs, TextField, DetailPanel, Empty} from '../../ui/ui';
import {
Badge,
Button,
DataTable,
ErrorMessage,
errorText,
Light,
TextTooltip,
Kv,
LabeledSelect,
Tabs,
TextField,
DetailPanel,
Empty,
type TableColumn
} from '../../ui/ui';
import type {PageProps} from '../types';
import {FlushCacheButton} from './FlushCache';
import {useDns, useDnsCache, useDnsLog} from './useDns';
type DnsLogRow = ReturnType<typeof useDnsLog>['rows'][number];
export function Dns(props: PageProps) {
const t = useT();
const vm = useDns(props);
@@ -68,6 +86,7 @@ export function Dns(props: PageProps) {
return (
<div className="rp-page">
{vm.error && <ErrorMessage error={vm.error} />}
{vm.queryError && <ErrorMessage error={vm.queryError} message={t('dns.queryFailed', {error: errorText(vm.queryError)})} />}
<Tabs label={t('nav.dns')} items={vm.tabs.map(tab => ({...tab, content: content[tab.id]}))} value={vm.tab} onChange={vm.setTab} />
</div>
);
@@ -136,6 +155,45 @@ function DnsCache({domain, clearFilter}: {domain: string; clearFilter: () => voi
function DnsLog({enabled, initialName}: {enabled: boolean | undefined; initialName: string}) {
const t = useT();
const vm = useDnsLog(enabled, initialName);
// Stable column definitions: a new array on every poll would re-render every visible row.
const columns = useMemo(
(): TableColumn<DnsLogRow>[] => [
{id: 't', label: t('ui.time'), minWidth: 96, grow: 0, render: record => <TextTooltip text={record.timeTooltip}>{record.time}</TextTooltip>},
{id: 'q', label: t('ui.domain'), minWidth: 200, grow: 2, isRowHeader: true, render: record => <TextTooltip>{record.name}</TextTooltip>},
{id: 'ty', label: t('ui.type'), minWidth: 64, grow: 0, drop: 3, render: record => record.type},
{id: 's', label: t('ui.source'), minWidth: 128, drop: 2, render: record => <TextTooltip className="rp-code">{record.source}</TextTooltip>},
{
id: 'r',
label: t('dns.result'),
minWidth: 160,
grow: 2,
render: record =>
record.resultError ? (
<Light small tone="err">
{record.result}
</Light>
) : (
<TextTooltip className="rp-code">{record.result}</TextTooltip>
)
},
{
id: 'u',
label: t('ui.upstream'),
minWidth: 128,
drop: 1,
render: record =>
record.cached ? (
<Light small tone="ok">
{record.upstream}
</Light>
) : (
<TextTooltip>{record.upstream}</TextTooltip>
)
},
{id: 'e', label: t('ui.elapsed'), minWidth: 72, grow: 0, align: 'end', drop: 4, render: record => record.elapsed}
],
[t]
);
return (
<>
<div className="rp-toolbar">
@@ -168,41 +226,7 @@ function DnsLog({enabled, initialName}: {enabled: boolean | undefined; initialNa
selectOnFocus={vm.wide}
loading={vm.loading}
empty={vm.empty}
cols={[
{id: 't', label: t('ui.time'), minWidth: 96, grow: 0, render: record => <TextTooltip text={record.timeTooltip}>{record.time}</TextTooltip>},
{id: 'q', label: t('ui.domain'), minWidth: 200, grow: 2, isRowHeader: true, render: record => <TextTooltip>{record.name}</TextTooltip>},
{id: 'ty', label: t('ui.type'), minWidth: 64, grow: 0, drop: 3, render: record => record.type},
{id: 's', label: t('ui.source'), minWidth: 128, drop: 2, render: record => <TextTooltip className="rp-code">{record.source}</TextTooltip>},
{
id: 'r',
label: t('dns.result'),
minWidth: 160,
grow: 2,
render: record =>
record.resultError ? (
<Light small tone="err">
{record.result}
</Light>
) : (
<TextTooltip className="rp-code">{record.result}</TextTooltip>
)
},
{
id: 'u',
label: t('ui.upstream'),
minWidth: 128,
drop: 1,
render: record =>
record.cached ? (
<Light small tone="ok">
{record.upstream}
</Light>
) : (
<TextTooltip>{record.upstream}</TextTooltip>
)
},
{id: 'e', label: t('ui.elapsed'), minWidth: 72, grow: 0, align: 'end', drop: 4, render: record => record.elapsed}
]}
cols={columns}
/>
<DetailPanel open={!!vm.detail} title={vm.detailTitle} onClose={() => vm.setSelected(null)}>
{vm.detail && (
+12 -3
View File
@@ -13,6 +13,9 @@ export const messages = defineMessages({
'dns.hit': '快取命中',
'dns.miss': '未命中快取',
'dns.routeSource': '路由來源',
'dns.route.forced': '強制指定',
'dns.route.rules': 'DNS 路由規則',
'dns.route.default': '預設',
'dns.routeRule': '路由規則',
'dns.noAnswers': '沒有回答記錄',
'dns.positive': '正快取',
@@ -23,7 +26,7 @@ export const messages = defineMessages({
'dns.cacheUnavailable': '不支援快取清單',
'dns.expires': '到期時間',
'dns.staleUntil': '過期後仍可用至',
'dns.deleteEntry': '刪除快取 {id}',
'dns.deleteEntry': '刪除 {domain} 的 {type} 快取',
'dns.entries': '快取記錄',
'dns.viewCache': '查看快取',
'dns.log': '解析記錄',
@@ -54,6 +57,9 @@ export const messages = defineMessages({
'dns.hit': '缓存命中',
'dns.miss': '缓存未命中',
'dns.routeSource': '路由来源',
'dns.route.forced': '强制指定',
'dns.route.rules': 'DNS 路由规则',
'dns.route.default': '默认',
'dns.routeRule': '路由规则',
'dns.noAnswers': '没有应答记录',
'dns.positive': '正缓存',
@@ -64,7 +70,7 @@ export const messages = defineMessages({
'dns.cacheUnavailable': '不支持缓存列表',
'dns.expires': '到期时间',
'dns.staleUntil': '过期后仍可用至',
'dns.deleteEntry': '删除缓存 {id}',
'dns.deleteEntry': '删除 {domain} 的 {type} 缓存',
'dns.entries': '缓存记录',
'dns.viewCache': '查看缓存',
'dns.log': '解析记录',
@@ -98,6 +104,9 @@ export const messages = defineMessages({
'dns.hit': 'Cache hit',
'dns.miss': 'Cache miss',
'dns.routeSource': 'Route source',
'dns.route.forced': 'Forced',
'dns.route.rules': 'DNS routing rule',
'dns.route.default': 'Default',
'dns.routeRule': 'Route rule',
'dns.noAnswers': 'No answers',
'dns.positive': 'Positive cache',
@@ -108,7 +117,7 @@ export const messages = defineMessages({
'dns.cacheUnavailable': 'Cache listing unavailable',
'dns.expires': 'Expires',
'dns.staleUntil': 'Stale until',
'dns.deleteEntry': 'Delete cache entry {id}',
'dns.deleteEntry': 'Delete the {type} cache entry for {domain}',
'dns.entries': 'Cache entries',
'dns.viewCache': 'View cache',
'dns.log': 'Resolution log',
+9 -34
View File
@@ -1,10 +1,8 @@
import {afterEach, expect, it, vi} from 'vitest';
import {expect, it, vi} from 'vitest';
import {createMockApi} from '../../api/mock';
import {queryTypes} from './query';
import {ApiError} from '../../api/error';
afterEach(() => vi.useRealTimers());
it('queries every requested type within the advertised bound and preserves all results', async () => {
const api = createMockApi();
const types = ['A', 'AAAA', 'MX', 'TXT', 'HTTPS'];
@@ -45,44 +43,21 @@ it('does not issue another batch or return partial success after cancellation',
expect(requested).toEqual(['A']);
});
it('waits out a refused later batch without losing or repeating completed batches', async () => {
// Refusals are waited out by the API client for every dns/query request; the batching layer neither retries
// nor swallows them, so a refused later batch surfaces after exactly one attempt per batch.
it('surfaces a refused later batch without repeating completed batches', async () => {
const api = createMockApi();
const answer = await api.dnsQuery('example.com', ['A', 'AAAA']);
vi.useFakeTimers();
const refusal = new ApiError(429, 'rate_limited', 'Wait', null, null, 2);
const query = vi
.fn()
.mockResolvedValueOnce({...answer, results: [answer.results[0]]})
.mockRejectedValueOnce(new ApiError(429, 'rate_limited', 'Wait', null, null, 2))
.mockResolvedValueOnce({...answer, results: [answer.results[1]]});
const pending = queryTypes(query, 'example.com', ['A', 'AAAA'], 1, new AbortController().signal);
await vi.advanceTimersByTimeAsync(1999);
expect(query).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(1);
expect((await pending).results.map(result => result.type)).toEqual(['A', 'AAAA']);
expect(query.mock.calls.map(call => call[1])).toEqual([['A'], ['AAAA'], ['AAAA']]);
.mockRejectedValueOnce(refusal);
await expect(queryTypes(query, 'example.com', ['A', 'AAAA'], 1, new AbortController().signal)).rejects.toBe(refusal);
expect(query.mock.calls.map(call => call[1])).toEqual([['A'], ['AAAA']]);
});
it('cancels the refusal wait without issuing another request', async () => {
vi.useFakeTimers();
const controller = new AbortController();
const query = vi.fn().mockRejectedValue(new ApiError(503, 'temporarily_unavailable', 'Wait', null, null, 1));
const pending = queryTypes(query, 'example.com', ['A'], 1, controller.signal);
const rejected = expect(pending).rejects.toMatchObject({name: 'AbortError'});
await vi.advanceTimersByTimeAsync(0);
controller.abort();
await rejected;
await vi.advanceTimersByTimeAsync(2000);
expect(query).toHaveBeenCalledTimes(1);
});
it('bounds transient retries and fails permanent refusals immediately', async () => {
vi.useFakeTimers();
const error = new ApiError(503, 'temporarily_unavailable', 'Wait', null, null, 1);
const query = vi.fn().mockRejectedValue(error);
const rejected = expect(queryTypes(query, 'example.com', ['A'], 1, new AbortController().signal)).rejects.toBe(error);
await vi.advanceTimersByTimeAsync(3000);
await rejected;
expect(query).toHaveBeenCalledTimes(4);
it('fails permanent refusals immediately', async () => {
const permanent = vi.fn().mockRejectedValue(new ApiError(400, 'invalid_request', 'Invalid'));
await expect(queryTypes(permanent, 'example.com', ['A'], 1, new AbortController().signal)).rejects.toMatchObject({status: 400});
expect(permanent).toHaveBeenCalledTimes(1);
+2 -13
View File
@@ -1,7 +1,5 @@
import type {Api} from '../../api/api';
import type {DnsQueryResponse} from '../../api/model';
import {ApiError} from '../../api/error';
import {wait} from '../../api/wait';
export async function queryTypes(query: Api['dnsQuery'], domain: string, types: string[], limit: number, signal: AbortSignal): Promise<DnsQueryResponse> {
const size = Math.max(1, Math.floor(limit));
@@ -9,17 +7,8 @@ export async function queryTypes(query: Api['dnsQuery'], domain: string, types:
for (let start = 0; start < types.length; start += size) {
signal.throwIfAborted();
const batch = types.slice(start, start + size);
let part: DnsQueryResponse;
for (let refused = 0; ; refused++) {
try {
part = await query(domain, batch, signal);
break;
} catch (error) {
signal.throwIfAborted();
if (!(error instanceof ApiError) || !error.transient || refused >= 3) throw error;
await wait(error.retryAfter!, signal);
}
}
// Transient refusals are waited out by the client itself; this only batches record types.
const part = await query(domain, batch, signal);
signal.throwIfAborted();
if (response) response.results.push(...part.results);
else response = {...part, results: [...part.results]};
+8 -8
View File
@@ -40,8 +40,8 @@ export function useDns({go, query}: PageProps) {
if (!signal.aborted) setResult(value);
return value;
});
} catch (error) {
toast('negative', t('dns.queryFailed', {error: errorText(error)}));
} catch {
// The failure stays on the page as its banner until the next query; a toast would say it twice.
}
};
return {
@@ -51,7 +51,8 @@ export function useDns({go, query}: PageProps) {
type,
setType,
pending: busy === 'query',
error: error ?? capabilities.error,
error: capabilities.error,
queryError: error,
submit: () => void submit(),
setTab,
tab: view.tabs.some(item => item.id === params.get('tab')) ? params.get('tab')! : (view.tabs[0]?.id ?? 'query'),
@@ -89,7 +90,8 @@ export function useDnsCache(domain: string) {
};
return {
...view,
error: dns.error ?? dns.cache.error ?? dns.capabilities.error,
// Delete and flush failures arrive as toasts, and the page above already reports the capabilities.
error: dns.cache.error,
loading: (dns.cache.loading || dns.capabilities.loading) && !dns.cache.data,
flushPending: dns.busy === 'flush',
remove: (id: string) => void remove(id),
@@ -111,10 +113,8 @@ export function useDnsLog(enabled: boolean | undefined, initialName: string) {
const log = useDnsLogResource(filter, enabled === true);
const [held, setHeld] = useState<DnsLogList | null>(null);
const paging = useAction<'older'>({scope: key});
useLinked(key, () => {
setHeld(null);
paging.cancel();
});
// A new filter drops the held pages; useAction's scope aborts the paging for that filter after the commit.
useLinked(key, () => setHeld(null));
const {data, newerWaiting} = useMemo(() => dnsLogWindow(log.data, held), [log.data, held]);
const loadOlder = () =>
void paging.run('older', async signal => {
+7
View File
@@ -98,3 +98,10 @@ it('holds the loaded window when a poll advances the head after the final older
expect(dnsLogWindow(page(['d4', 'd3'], 'd3'), held).newerWaiting).toBe(false);
expect(dnsLogWindow(head, null)).toEqual({data: head, newerWaiting: false});
});
it('names the route source and the cache entry a delete button removes', () => {
expect(dnsAnswerView({...record, route: {source: 'dns.routing', rule: 'r1'}}, t).fields).toContainEqual([t('dns.routeSource'), t('dns.route.rules')]);
const entry = dnsCacheView(dnsCache, capabilities.resources, '', null, 'en-US', t).rows[0];
expect(entry.deleteLabel).toBe(t('dns.deleteEntry', {domain: entry.domain, type: entry.type}));
expect(entry.deleteLabel).not.toContain(entry.id);
});
+6 -4
View File
@@ -1,16 +1,18 @@
import type {Capabilities, DnsCacheList, DnsLogList, DnsLogRecord, DnsQueryResponse} from '../../api/model';
import {localTime, relativeStart} from '../../api/selectors';
import type {Translator as LabelFn} from '../../i18n';
import {formatNumber, type Translator as LabelFn} from '../../i18n';
import {millis} from '../../api/u64';
import {csvLine} from '../../ui/ui';
import type {Key} from '../../i18n/messages';
const routeSources: Record<string, Key> = {forced: 'dns.route.forced', 'dns.routing': 'dns.route.rules', default: 'dns.route.default'};
type Result = Pick<DnsQueryResponse['results'][number], 'status' | 'upstream' | 'route' | 'elapsed_ms' | 'answers' | 'cached'>;
export function dnsAnswerView(result: Result, t: LabelFn) {
return {
fields: [
[t('ui.state'), result.status],
[t('ui.upstream'), result.upstream ?? '—'],
[t('dns.routeSource'), result.route.source],
[t('dns.routeSource'), routeSources[result.route.source] ? t(routeSources[result.route.source]) : result.route.source],
[t('dns.routeRule'), result.route.rule ?? '—'],
[t('ui.elapsed'), t('ui.latency', {n: millis(result.elapsed_ms)})]
] as Array<[string, string]>,
@@ -52,7 +54,7 @@ export function dnsCacheView(
) {
const filter = domain.toLowerCase();
return {
fields: [[t('dns.entries'), data ? String(data.total) : '—']] as Array<[string, string]>,
fields: [[t('dns.entries'), data ? formatNumber(data.total, locale) : '—']] as Array<[string, string]>,
coverage: data
? (['positive', 'negative', 'persistent'] as const)
.filter(key => !data.coverage[key])
@@ -81,7 +83,7 @@ export function dnsCacheView(
expiresTooltip: entry.expires_at,
stale: relativeStart(entry.stale_until, locale),
staleTooltip: entry.stale_until ?? undefined,
deleteLabel: t('dns.deleteEntry', {id: entry.entry_id}),
deleteLabel: t('dns.deleteEntry', {domain: entry.domain, type: entry.type}),
pending: busy === entry.entry_id,
disabled: !!busy || !resources?.dns_cache.available || !resources.dns_cache.delete_entry
}))
+31 -30
View File
@@ -1,11 +1,40 @@
import {useMemo} from 'react';
import {useT} from '../../i18n';
import {Button, DataTable, LabeledSelect, Light, ErrorMessage, TextTooltip} from '../../ui/ui';
import {Button, DataTable, LabeledSelect, Light, ErrorMessage, TextTooltip, type TableColumn} from '../../ui/ui';
import {useEvents} from './useEvents';
import Download from '../../ui/icons/Download';
type EventRow = ReturnType<typeof useEvents>['rows'][number];
export function Events() {
const t = useT();
const vm = useEvents();
// Stable column definitions: a new array on every stream tick would re-render every visible row.
const columns = useMemo(
(): TableColumn<EventRow>[] => [
{
id: 't',
label: t('ui.time'),
minWidth: 200,
grow: 0,
drop: 1,
render: event => (
<TextTooltip className="rp-code" text={event.timeTooltip}>
{event.timestamp}
</TextTooltip>
)
},
{id: 'k', label: t('event.kind'), minWidth: 168, drop: 2, render: event => <TextTooltip text={event.kind}>{event.kindText}</TextTooltip>},
{
id: 'm',
label: t('event.summary'),
minWidth: 240,
isRowHeader: true,
render: event => event.summary
}
],
[t]
);
return (
<div className="rp-page">
<div className="rp-toolbar">
@@ -26,35 +55,7 @@ export function Events() {
</Button>
</div>
{vm.error && <ErrorMessage error={vm.error} onRetry={vm.retry} />}
<DataTable
label={t('nav.events')}
height={442}
loading={vm.loading}
rows={vm.rows}
empty={t('event.empty')}
cols={[
{
id: 't',
label: t('ui.time'),
minWidth: 200,
grow: 0,
drop: 1,
render: event => (
<TextTooltip className="rp-code" text={event.timeTooltip}>
{event.timestamp}
</TextTooltip>
)
},
{id: 'k', label: t('event.kind'), minWidth: 168, drop: 2, render: event => <TextTooltip text={event.kind}>{event.kindText}</TextTooltip>},
{
id: 'm',
label: t('event.summary'),
minWidth: 240,
isRowHeader: true,
render: event => event.summary
}
]}
/>
<DataTable label={t('nav.events')} stream height={442} loading={vm.loading} rows={vm.rows} empty={t('event.empty')} cols={columns} />
</div>
);
}
+3
View File
@@ -15,6 +15,7 @@ export const messages = defineMessages({
'event.unavailable': '不支援事件串流',
'event.connected': '已連線',
'event.reconnecting': '重新連線中',
'event.disconnected': '已中斷連線',
'event.cursor': '可從上次位置續傳',
'event.limit': '顯示最近 {n} 筆事件,新事件在前。',
'event.empty': '沒有符合的事件',
@@ -43,6 +44,7 @@ export const messages = defineMessages({
'event.unavailable': '不支持事件流',
'event.connected': '已连接',
'event.reconnecting': '重新连接中',
'event.disconnected': '已断开连接',
'event.cursor': '可从上次位置续传',
'event.limit': '显示最近 {n} 条事件,新事件在前。',
'event.empty': '没有匹配的事件',
@@ -71,6 +73,7 @@ export const messages = defineMessages({
'event.unavailable': 'Event stream unavailable',
'event.connected': 'Connected',
'event.reconnecting': 'Reconnecting',
'event.disconnected': 'Disconnected',
'event.cursor': 'Resumes from the last position',
'event.limit': {one: 'Showing the latest {n} event, newest first.', other: 'Showing the latest {n} events, newest first.'},
'event.empty': 'No matching events',
+5 -3
View File
@@ -10,10 +10,12 @@ export function useEvents() {
const capabilities = useCapabilities();
const kinds = capabilities.data?.resources.events.kinds;
const [kind, setKind] = useState('without-runtime');
const feed = useEventFeed(kind !== 'without-runtime');
// Heartbeats are only fetched for a view that can show them; an unadvertised kind falls back to all.
const single = kind !== 'all' && kind !== 'runtime.updated' && (kinds as string[] | undefined)?.includes(kind);
const feed = useEventFeed(kind !== 'without-runtime' && !single);
const view = useMemo(
() => eventsView(feed.events, kind, feed.connected, feed.available, EVENT_FEED_LIMIT, locale, t, kinds ?? []),
[feed.events, kind, feed.connected, feed.available, locale, t, kinds]
() => eventsView(feed.events, kind, feed.connected, feed.available, EVENT_FEED_LIMIT, locale, t, kinds ?? [], !!feed.error),
[feed.events, kind, feed.connected, feed.available, feed.error, locale, t, kinds]
);
useLinked(view.kind, setKind);
return {
+1
View File
@@ -20,6 +20,7 @@ it('exports only the selected event kind while preserving raw data', () => {
it('offers only advertised event kinds and resets an unsupported selection', () => {
const view = eventsView([], 'flow.updated', true, true, 200, 'en-US', t, ['stream.ready', 'runtime.updated']);
expect(view.kind).toBe('all');
expect(eventsView([], 'all', false, true, 200, 'en-US', t, [], true).status.text).toBe(t('event.disconnected'));
expect(view.kinds.map(item => item.id)).toEqual(['without-runtime', 'all', 'stream.ready', 'runtime.updated']);
});
+31 -17
View File
@@ -2,6 +2,25 @@ import type {ApiEvent, EventKind} from '../../api/model';
import {eventKindLabels, eventSummary, localTime} from '../../api/selectors';
import {formatNumber, type Translator as LabelFn} from '../../i18n';
type EventRow = {id: string; timestamp: string; timeTooltip: string; kind: ApiEvent['event']; kindText: string; summary: string};
// An event never changes once received, so its row is built once per locale and the table sees the same object.
const rows = new WeakMap<ApiEvent, {locale: string; row: EventRow}>();
function eventRow(event: ApiEvent, locale: string, t: LabelFn): EventRow {
const hit = rows.get(event);
if (hit && hit.locale === locale) return hit.row;
const summary = eventSummary(event, t);
const row = {
id: event.id,
timestamp: localTime(event.data.observed_at, locale),
timeTooltip: event.data.observed_at,
kind: event.event,
kindText: t(eventKindLabels[event.event]),
summary: t(summary.key, summary.params)
};
rows.set(event, {locale, row});
return row;
}
export function eventsView(
events: ApiEvent[],
selected: string,
@@ -10,7 +29,8 @@ export function eventsView(
limit: number,
locale: string,
t: LabelFn,
advertised: EventKind[]
advertised: EventKind[],
failed = false
) {
const kind = selected === 'without-runtime' || advertised.includes(selected as EventKind) ? selected : 'all';
const shown = events
@@ -18,27 +38,21 @@ export function eventsView(
.slice(0, limit);
return {
kind,
rows: shown.map(event => {
const summary = eventSummary(event, t);
return {
id: event.id,
timestamp: localTime(event.data.observed_at, locale),
timeTooltip: event.data.observed_at,
kind: event.event,
kindText: t(eventKindLabels[event.event]),
summary: t(summary.key, summary.params)
};
}),
rows: shown.map(event => eventRow(event, locale, t)),
kinds: [
{id: 'without-runtime', label: t('event.withoutRuntime')},
{id: 'all', label: t('event.allKinds')},
...advertised.map(id => ({id, label: t(eventKindLabels[id])}))
],
// Before capabilities answer nothing has failed yet; a warning only fits a stream that was expected.
status: {
tone: connected ? ('ok' as const) : available === null ? ('muted' as const) : ('warn' as const),
text: t(available === false ? 'event.unavailable' : connected ? 'event.connected' : available === null ? 'ui.loading' : 'event.reconnecting')
},
// Before capabilities answer nothing has failed yet; a warning only fits a stream that was expected. A failed
// stream waits for a retry, so it is not reconnecting.
status:
failed && available !== false
? {tone: 'err' as const, text: t('event.disconnected')}
: {
tone: connected ? ('ok' as const) : available === null ? ('muted' as const) : ('warn' as const),
text: t(available === false ? 'event.unavailable' : connected ? 'event.connected' : available === null ? 'ui.loading' : 'event.reconnecting')
},
limitText: t('event.limit', {n: formatNumber(limit, locale)}),
shown
};
+44 -21
View File
@@ -1,5 +1,21 @@
import {useMemo} from 'react';
import Tree from './Tree';
import {Badge, Button, DataTable, DetailPanel, ErrorMessage, Loading, TextTooltip, Kv, LabeledSelect, Segmented, RuleRef, Empty, Link} from '../../ui/ui';
import {
Badge,
Button,
DataTable,
DetailPanel,
ErrorMessage,
Loading,
TextTooltip,
Kv,
LabeledSelect,
Segmented,
RuleRef,
Empty,
Link,
type TableColumn
} from '../../ui/ui';
import {Coverage} from './Coverage';
import type {PageProps} from '../types';
import {useT} from '../../i18n';
@@ -7,6 +23,8 @@ import Close from '../../ui/icons/Close';
import {useRoutingMap} from './useRoutingMap';
import {useFlowRecords} from './useFlowRecords';
type FlowRow = ReturnType<typeof useFlowRecords>['rows'][number];
export function RoutingMap(props: PageProps) {
const t = useT();
const view = useRoutingMap(props);
@@ -48,6 +66,30 @@ export function FlowRecords(props: PageProps) {
const t = useT();
const view = useFlowRecords(props);
const detail = view.detail;
// Stable column definitions: a new array on every poll would re-render every visible row.
const columns = useMemo(
(): TableColumn<FlowRow>[] => [
{id: 'target', label: t('ui.target'), minWidth: 128, grow: 2, isRowHeader: true, render: row => <TextTooltip>{row.target}</TextTooltip>},
{id: 'chain', label: t('conn.chain'), minWidth: 96, drop: 2, render: row => <TextTooltip className="rp-chain">{row.chain}</TextTooltip>},
{
id: 'rule',
label: t('conn.rule'),
minWidth: 152,
grow: 2,
drop: 1,
render: row => (
<span className="rp-rule">
<RuleRef expression={row.expression} ruleId={row.ruleId} linked={view.rulesListed} />
{row.recomputed && <small className="rp-provenance">{t('conn.recomputed')}</small>}
</span>
)
},
{id: 'network', label: t('ui.protocol'), minWidth: 64, grow: 0, drop: 3, render: row => row.network},
{id: 'state', label: t('ui.state'), minWidth: 80, grow: 0, drop: 5, render: row => row.state},
{id: 'started', label: t('ui.started'), minWidth: 80, grow: 0, drop: 4, render: row => row.started}
],
[t, view.rulesListed]
);
return (
<>
<ErrorMessage error={view.error} />
@@ -87,26 +129,7 @@ export function FlowRecords(props: PageProps) {
onSelect={view.select}
selectOnFocus={view.wide}
empty={t('flow.empty')}
cols={[
{id: 'target', label: t('ui.target'), minWidth: 128, grow: 2, isRowHeader: true, render: row => <TextTooltip>{row.target}</TextTooltip>},
{id: 'chain', label: t('conn.chain'), minWidth: 96, drop: 2, render: row => <TextTooltip className="rp-chain">{row.chain}</TextTooltip>},
{
id: 'rule',
label: t('conn.rule'),
minWidth: 152,
grow: 2,
drop: 1,
render: row => (
<span className="rp-rule">
<RuleRef expression={row.expression} ruleId={row.ruleId} linked={view.rulesListed} />
{row.recomputed && <small className="rp-provenance">{t('conn.recomputed')}</small>}
</span>
)
},
{id: 'network', label: t('ui.protocol'), minWidth: 64, grow: 0, drop: 3, render: row => row.network},
{id: 'state', label: t('ui.state'), minWidth: 80, grow: 0, drop: 5, render: row => row.state},
{id: 'started', label: t('ui.started'), minWidth: 80, grow: 0, drop: 4, render: row => row.started}
]}
cols={columns}
/>
<DetailPanel open={view.panelOpen} title={view.panelTitle} onClose={() => view.select(null)}>
<ErrorMessage error={view.detailError} onRetry={view.detailRetry} />
+1 -1
View File
@@ -5,7 +5,7 @@ import type {RoutingTree} from './map';
import type {TreePlacement, TileView} from './view';
import {useTree} from './useTree';
// Stable tile props keep unrelated hover changes from rerendering each tile.
// Views, placements and callbacks keep their identity across hover and pin changes, so only a tile whose dim or selected state flips rerenders.
const TreeTile = memo(function TreeTile({
view,
style,
+11 -11
View File
@@ -1,7 +1,7 @@
import {expect, it} from 'vitest';
import {createMockApi} from '../../api/mock';
import type {GroupSummary} from '../../api/model';
import {flowsThrough, nodeNames, parentOf, pinnedLabel, routingTree, treeRows} from './map';
import {flowsThrough, nodeNames, pinnedLabel, routingTree, treeIndex, treeRows} from './map';
it('lays the config out as a tree and weights it with retained flows', async () => {
const api = createMockApi();
@@ -28,11 +28,11 @@ it('lays the config out as a tree and weights it with retained flows', async ()
expect(tree.outbounds.find(outbound => outbound.id === 'outbound:direct')).toMatchObject({kind: 'direct', node: null});
expect(tree.links.some(link => link.source === 'outbound:direct')).toBe(false);
const direct = flows.flows.filter(flow => flow.outbound === 'direct');
expect(flowsThrough(flows.flows, 'outbound:direct', nodeNames(nodes.nodes), rules.rules)).toHaveLength(direct.length);
expect(flowsThrough(flows.flows, 'outbound:direct', rules.rules)).toHaveLength(direct.length);
// A flow that names a rule id lands on that entry rather than on a second one with the same text.
const matched = flows.flows.find(flow => flow.rule_id && flow.rule_expression)!;
expect(tree.leaves.filter(rule => rule.id === 'rule:' + matched.rule_id)).toHaveLength(1);
expect(flowsThrough(flows.flows, 'rule:' + matched.rule_id, nodeNames(nodes.nodes), rules.rules)).toContain(matched);
expect(flowsThrough(flows.flows, 'rule:' + matched.rule_id, rules.rules)).toContain(matched);
const label = (name: string | null) => (name === 'direct' ? 'Direct' : String(name));
expect(pinnedLabel('rule:' + matched.rule_id, rules.rules, nodeNames(nodes.nodes), label)).toBe(matched.rule_expression);
expect(pinnedLabel('outbound:direct', rules.rules, nodeNames(nodes.nodes), label)).toBe('Direct');
@@ -70,18 +70,18 @@ it('rows the tree with rules as leaves under their outbound and parents level wi
const tree = routingTree(flows.flows, groups, nodes.nodes, rules.rules);
const {rows, at} = treeRows(tree);
// Every item has a row; the leaves take whole rows and never share one.
const leaves = [...tree.leaves, ...tree.outbounds.filter(outbound => !tree.leaves.some(rule => parentOf(tree, rule) === outbound.id))];
const leaves = [...tree.leaves, ...tree.outbounds.filter(outbound => !tree.leaves.some(rule => treeIndex(tree).parents.get(rule.id) === outbound.id))];
expect(new Set(leaves.map(item => at.get(item.id)))).toHaveProperty('size', leaves.length);
expect(rows).toBe(leaves.length + tree.nodes.filter(node => !tree.outbounds.some(outbound => parentOf(tree, outbound) === node.id)).length);
expect(rows).toBe(leaves.length + tree.nodes.filter(node => !tree.outbounds.some(outbound => treeIndex(tree).parents.get(outbound.id) === node.id)).length);
for (const outbound of tree.outbounds) {
const under = tree.leaves.filter(rule => parentOf(tree, rule) === outbound.id).map(rule => at.get(rule.id)!);
const under = tree.leaves.filter(rule => treeIndex(tree).parents.get(rule.id) === outbound.id).map(rule => at.get(rule.id)!);
if (!under.length) continue;
expect(at.get(outbound.id)).toBe((Math.min(...under) + Math.max(...under)) / 2);
// Siblings sit on consecutive rows, so their connectors never cross another branch.
expect(Math.max(...under) - Math.min(...under)).toBe(under.length - 1);
}
for (const node of tree.nodes) {
const under = tree.outbounds.filter(outbound => parentOf(tree, outbound) === node.id).map(outbound => at.get(outbound.id)!);
const under = tree.outbounds.filter(outbound => treeIndex(tree).parents.get(outbound.id) === node.id).map(outbound => at.get(outbound.id)!);
if (under.length) expect(at.get(node.id)).toBe((Math.min(...under) + Math.max(...under)) / 2);
}
});
@@ -109,7 +109,7 @@ it('keeps a retained flow from an earlier generation apart from the rule that no
expect(historical).toMatchObject({label: 'domain(suffix: old.example)', count: 1, outbound: null});
expect(tree.leaves.find(leaf => leaf.id === 'rule:' + matched.rule_id)?.label).toBe(matched.rule_expression);
const names = nodeNames(nodes.nodes);
expect(flowsThrough([...flows.flows, stale], historical.id, names, rules.rules)).toEqual([stale]);
expect(flowsThrough([...flows.flows, stale], historical.id, rules.rules)).toEqual([stale]);
expect(pinnedLabel(historical.id, rules.rules, names, String)).toBe('domain(suffix: old.example)');
});
@@ -122,7 +122,7 @@ it('seen by device, the leaves are client addresses joined to outbounds by flows
expect(tree.leaves.reduce((sum, leaf) => sum + leaf.count, 0)).toBe(flows.flows.length);
const device = tree.leaves.find(leaf => leaf.label === '10.0.0.12')!;
expect(tree.links.some(link => link.source === device.id && link.target.startsWith('outbound:') && link.count > 0)).toBe(true);
expect(flowsThrough(flows.flows, device.id, nodeNames(nodes.nodes), rules.rules)).toHaveLength(device.count);
expect(flowsThrough(flows.flows, device.id, rules.rules)).toHaveLength(device.count);
// Groups and their selected nodes still come from the config.
expect(tree.outbounds.some(outbound => outbound.label === 'skylink' && outbound.count === 0)).toBe(true);
const {rows, at} = treeRows(tree);
@@ -144,8 +144,8 @@ it('keeps missing stages distinct from backend values literally named unknown',
expect(absent.id).not.toBe(present.id);
expect(absent.count).toBe(1);
expect(present.count).toBe(1);
expect(flowsThrough(flows, absent.id, names, [])).toEqual([missing]);
expect(flowsThrough(flows, present.id, names, [])).toEqual([known]);
expect(flowsThrough(flows, absent.id, [])).toEqual([missing]);
expect(flowsThrough(flows, present.id, [])).toEqual([known]);
expect(pinnedLabel(absent.id, [], names, name => name ?? 'Missing')).toBe('Missing');
}
expect(pinnedLabel(tree.nodes.find(item => !item.unknown)!.id, [], names, String)).toBe('Known node');
+4 -6
View File
@@ -50,12 +50,14 @@ function stagePart(
// Empty identities distinguish missing values from identifiers literally named "unknown".
const stageId = (stage: Stage, part: {label: string; key?: string; unknown?: boolean}) => stage + ':' + (part.unknown ? '' : (part.key ?? part.label));
export function flowsThrough(flows: FlowSummary[], id: string, names: NodeNames, rules: RoutingRule[]): FlowSummary[] {
// Identities are keyed by node ID, not name, so matching needs no name catalogue.
const noNames: NodeNames = new Map();
export function flowsThrough(flows: FlowSummary[], id: string, rules: RoutingRule[]): FlowSummary[] {
const stage = id.slice(0, id.indexOf(':')) as Stage;
if (!stages.includes(stage)) return [];
const rulesById = new Map(rules.map(rule => [rule.rule_id, rule]));
return flows.filter(flow => {
const part = stagePart(flow, stage, names, rulesById);
const part = stagePart(flow, stage, noNames, rulesById);
return part !== null && stageId(stage, part) === id;
});
}
@@ -195,10 +197,6 @@ export function treeIndex(tree: RoutingTree): TreeIndex {
return index;
}
export function parentOf(tree: RoutingTree, item: TreeLeaf | TreeOutbound): string | null {
return treeIndex(tree).parents.get(item.id) ?? null;
}
// Parents sit midway between their children, whose rows retain configuration order.
export function treeRows(tree: RoutingTree): {rows: number; at: Map<string, number>} {
const at = new Map<string, number>();
+6
View File
@@ -16,6 +16,8 @@ export const messages = defineMessages({
'flow.mapEmpty': '尚無可供繪製的規則、策略群組或保留流程',
'flow.stageClient': '裝置',
'flow.treeFlows': '{n} 筆流程',
'flow.treeTo': '→ {names}',
'flow.treeFrom': '← {names}',
'flow.byRule': '依規則',
'flow.byClient': '依裝置',
'flow.addRule': '為此目標新增規則',
@@ -126,6 +128,8 @@ export const messages = defineMessages({
'flow.mapEmpty': '尚无可供绘制的规则、策略组或保留流程',
'flow.stageClient': '设备',
'flow.treeFlows': '{n} 条流程',
'flow.treeTo': '→ {names}',
'flow.treeFrom': '← {names}',
'flow.byRule': '按规则',
'flow.byClient': '按设备',
'flow.addRule': '为此目标新增规则',
@@ -236,6 +240,8 @@ export const messages = defineMessages({
'flow.mapEmpty': 'No rules, policy groups or retained flows are available to display',
'flow.stageClient': 'Device',
'flow.treeFlows': {one: '{n} flow', other: '{n} flows'},
'flow.treeTo': '→ {names}',
'flow.treeFrom': '← {names}',
'flow.byRule': 'By rule',
'flow.byClient': 'By device',
'flow.addRule': 'Add a rule for this target',
+13 -9
View File
@@ -1,6 +1,6 @@
import {useMemo, useState} from 'react';
import {useMemo} from 'react';
import {useCapabilities, useFlow, useFlows, useOutboundNames, useRules, type FlowFilter} from '../../store';
import {outboundLabel} from '../../api/selectors';
import {connectionStates, outboundLabel} from '../../api/selectors';
import {useLang, useT} from '../../i18n';
import {within} from '../../shell/route';
import {panelQuery, useMediaQuery} from '../../ui/ui';
@@ -11,10 +11,13 @@ import {flowRecordsView} from './view';
export function useFlowRecords({go, query}: PageProps) {
const t = useT();
const lang = useLang();
const [network, setNetwork] = useState<NonNullable<FlowFilter['network']>>('all');
const [state, setState] = useState<NonNullable<FlowFilter['state']>>('all');
const wide = useMediaQuery(panelQuery);
const params = useMemo(() => new URLSearchParams(query), [query]);
// Filters live in the address, so they survive a tab switch like the other pages' filters.
const requestedNetwork = params.get('network');
const network: NonNullable<FlowFilter['network']> = requestedNetwork === 'tcp' || requestedNetwork === 'udp' ? requestedNetwork : 'all';
const requestedState = params.get('state') ?? '';
const state = (Object.hasOwn(connectionStates, requestedState) ? requestedState : 'all') as NonNullable<FlowFilter['state']>;
const connectionId = params.get('connection_id') ?? undefined;
const resource = useFlows({connection_id: connectionId, network, state});
const resources = useCapabilities().data?.resources;
@@ -27,8 +30,8 @@ export function useFlowRecords({go, query}: PageProps) {
const pinned = params.get('path');
const shown = useMemo(() => {
const all = resource.data?.flows ?? [];
return pinned ? flowsThrough(all, pinned, names, rules.data?.rules ?? []) : all;
}, [resource.data, pinned, names, rules.data]);
return pinned ? flowsThrough(all, pinned, rules.data?.rules ?? []) : all;
}, [resource.data, pinned, rules.data]);
const view = useMemo(
() => flowRecordsView(shown, detail.data ?? undefined, resource.data, names, canAdd, t, lang),
[shown, detail.data, resource.data, names, canAdd, t, lang]
@@ -36,9 +39,9 @@ export function useFlowRecords({go, query}: PageProps) {
return {
...view,
network,
setNetwork: (value: string) => setNetwork(value as NonNullable<FlowFilter['network']>),
setNetwork: (value: string) => go('rules', within(query, {network: value === 'all' ? null : value})),
state,
setState: (value: string) => setState(value as NonNullable<FlowFilter['state']>),
setState: (value: string) => go('rules', within(query, {state: value === 'all' ? null : value})),
wide,
id,
rulesListed,
@@ -49,7 +52,8 @@ export function useFlowRecords({go, query}: PageProps) {
detailError: detail.error,
detailRetry: detail.refetch,
detailLoading: !detail.data && detail.loading,
select: (value: string | null) => go('rules', within(query, {id: value})),
// Opening a record adds a history entry; moving between records or closing rewrites it, so Back is not one step per row.
select: (value: string | null) => go('rules', within(query, {id: value}), {replace: id !== null}),
pinLabel: pinned
? t('flow.mapFilter', {
label: pinnedLabel(pinned, rules.data?.rules ?? [], names, name => (name === null ? t('flow.mapUnknown') : outboundLabel(name, t)))
+5 -2
View File
@@ -3,7 +3,7 @@ import {useCapabilities, useFlows, useGroups, useNodes, useRules} from '../../st
import {useT} from '../../i18n';
import {within} from '../../shell/route';
import type {PageProps} from '../types';
import {flowsThrough, nodeNames, routingTree, type TreeBy} from './map';
import {flowsThrough, routingTree, type TreeBy} from './map';
import {routingMapView} from './view';
export function useRoutingMap({go, query}: PageProps) {
@@ -26,7 +26,10 @@ export function useRoutingMap({go, query}: PageProps) {
latest.current = query;
}, [query]);
const pin = useCallback((path: string | null) => go('rules', within(latest.current, {path})), [go]);
const count = pinned ? flowsThrough(resource.data?.flows ?? [], pinned, nodeNames(nodes.data ?? []), rules.data?.rules ?? []).length : 0;
const count = useMemo(
() => (pinned ? flowsThrough(resource.data?.flows ?? [], pinned, rules.data?.rules ?? []).length : 0),
[resource.data, pinned, rules.data]
);
return {
...routingMapView(tree, !!(resource.data || rules.data || groups.data), !!resource.error, pinned, count, t),
by,
+15 -6
View File
@@ -1,19 +1,23 @@
import {useCallback, useEffect, useMemo, useState} from 'react';
import {useT} from '../../i18n';
import {useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState} from 'react';
import {useLang, useT} from '../../i18n';
import {useContentWidth} from '../../ui/ui';
import {treeIndex, treeReach, type RoutingTree} from './map';
import {TREE_STEP, treeGeometry, treeWindow} from './view';
export function useTree(tree: RoutingTree, pinned: string | null, onPin: (id: string | null) => void) {
const t = useT();
const lang = useLang();
const [limit, setLimit] = useState(TREE_STEP);
const [hovered, setHovered] = useState<string | null>(null);
const [ref, measured] = useContentWidth<HTMLDivElement>();
const focus = hovered ?? pinned;
const index = useMemo(() => treeIndex(tree), [tree]);
const active = useMemo(() => (focus ? treeReach(index, focus) : null), [index, focus]);
const shown = useMemo(() => treeWindow(tree, limit), [tree, limit]);
const geometry = useMemo(() => treeGeometry(shown, measured, t), [shown, measured, t]);
const geometry = useMemo(() => treeGeometry(shown, measured, t, lang), [shown, measured, t, lang]);
// A tile that leaves under the pointer never reports the hover's end, so only a tile still drawn counts as hovered.
const drawn = useMemo(() => new Set(geometry.placed.map(tile => tile.view.id)), [geometry.placed]);
const known = useMemo(() => new Set([...tree.leaves, ...tree.outbounds, ...tree.nodes].map(item => item.id)), [tree]);
const focus = hovered && drawn.has(hovered) ? hovered : pinned && known.has(pinned) ? pinned : null;
const active = useMemo(() => (focus ? treeReach(index, focus) : null), [index, focus]);
useEffect(() => {
if (!pinned) return;
const clear = (event: KeyboardEvent) => {
@@ -22,7 +26,12 @@ export function useTree(tree: RoutingTree, pinned: string | null, onPin: (id: st
document.addEventListener('keydown', clear);
return () => document.removeEventListener('keydown', clear);
}, [pinned, onPin]);
const pin = useCallback((id: string) => onPin(pinned === id ? null : id), [pinned, onPin]);
// Read at press time, so one `pin` serves every tile across pin changes.
const current = useRef(pinned);
useLayoutEffect(() => {
current.current = pinned;
}, [pinned]);
const pin = useCallback((id: string) => onPin(current.current === id ? null : id), [onPin]);
return {
...geometry,
ref,
+18 -5
View File
@@ -11,7 +11,7 @@ it('suppresses full coverage and keeps exact dropped counts and partial scopes',
const coverage = Object.fromEntries(Object.keys(list.coverage).map(scope => [scope, 'full'])) as typeof list.coverage;
expect(coverageView({coverage, dropped_records: null}, t, 'en')).toBeNull();
const view = coverageView({coverage: {...coverage, userspace_tcp: 'partial', kernel_direct: 'none'}, dropped_records: '18446744073709551615'}, t, 'en')!;
expect(view.dropped).toContain('18446744073709551615');
expect(view.dropped).toContain('18,446,744,073,709,551,615');
expect(view.summary).toBe(t('flow.coverageSummary', {n: 2}));
expect(view.detail).toContain(t('flow.userspaceTcp'));
expect(view.detail).toContain(t('flow.partialVisibility'));
@@ -47,7 +47,7 @@ it('prepares tile labels with configured destinations, nested policies and unkno
const api = createMockApi();
const [rules, groups, nodes] = await Promise.all([api.rules(), api.groups(), api.nodes({limit: 1000})]);
const tree = routingTree([], groups, nodes.nodes, rules.rules);
const tiles = tileViews(tree, t);
const tiles = tileViews(tree, t, 'en');
const rule = rules.rules.find(rule => rule.outbound === 'block')!;
const tile = tiles.find(tile => tile.id === 'rule:' + rule.rule_id)!;
expect(tile.label).toContain('→ ' + t('ui.block'));
@@ -76,7 +76,7 @@ it('keeps native policy names distinct and falls back only when the native name
const api = createMockApi();
const groups = await api.groups();
const group = {...groups[0], policy: {...groups[0].policy, kind: 'urltest' as const, native: 'min_avg10'}};
const notes = (native: string) => tileViews(routingTree([], [{...group, policy: {...group.policy, native}}], [], []), t)[0].notes;
const notes = (native: string) => tileViews(routingTree([], [{...group, policy: {...group.policy, native}}], [], []), t, 'en')[0].notes;
expect(notes('min_avg10')).toContainEqual({text: 'min_avg10'});
expect(notes('min_last_delay')).toContainEqual({text: 'min_last_delay'});
expect(notes('')).toContainEqual({text: 'urltest'});
@@ -91,7 +91,7 @@ it('bounds each tree reveal while keeping layout, connector endpoints and branch
Array.from({length: 4096}, (_, i) => ({...rule, rule_id: String(i), outbound: 'direct'}))
);
const shown = treeWindow(tree, 30);
const view = treeGeometry(shown, 720, t);
const view = treeGeometry(shown, 720, t, 'en');
expect(view.placed.filter(tile => tile.view.stage === 'rule')).toHaveLength(30);
expect(treeWindow(tree, 60).leaves.at(-1)?.id).toBe('rule:59');
expect(view.placed.find(tile => tile.view.id === 'rule:0')?.style.top).toBe(0);
@@ -101,8 +101,21 @@ it('bounds each tree reveal while keeping layout, connector endpoints and branch
expect(view.geometry).toHaveLength(30);
const edge = view.geometry[0];
expect(edge.path).toBe('M253.33333333333331,16 C281.3333333333333,16 281.3333333333333,596 309.3333333333333,596');
expect(treeGeometry(shown, 390, t).width).toBe(720);
expect(treeGeometry(shown, 390, t, 'en').width).toBe(720);
const reached = treeReach(treeIndex(tree), 'rule:0');
expect([...reached.items]).toEqual(['rule:0', 'outbound:direct']);
expect([...reached.edges]).toEqual([tree.links[0]]);
});
it('names the groups leading to a node tile and leaves an unmeasured step without a unit', async () => {
const api = createMockApi();
const [rules, groups, nodes, list] = await Promise.all([api.rules(), api.groups(), api.nodes({limit: 1000}), api.flows()]);
const tree = routingTree(list.flows, groups, nodes.nodes, rules.rules);
const tiles = tileViews(tree, t, 'en');
const link = tree.links.find(link => link.target.startsWith('node:'))!;
const source = tiles.find(tile => tile.id === link.source)!;
expect(tiles.find(tile => tile.id === link.target)!.label).toContain('← ' + source.name);
const detail = await api.flow(list.flows[0].id);
detail.trace.steps = detail.trace.steps.map(step => ({...step, elapsed_us: null}));
expect(flowRecordsView([], detail, list, new Map(), false, t, 'en').detail!.steps.every(step => step.elapsed === '—')).toBe(true);
});
+14 -9
View File
@@ -1,8 +1,8 @@
import type {FlowDetail, FlowList, FlowStep, FlowSummary} from '../../api/model';
import type {Key} from '../../i18n/messages';
import {formatList, LOCALE, type Lang, type Translator} from '../../i18n';
import {formatList, formatNumber, LOCALE, type Lang, type Translator} from '../../i18n';
import {chainLabel, connectionStates, localTime, outboundLabel, relativeStart, sourceIp, type MessageRef, type OutboundNames} from '../../api/selectors';
import {millis} from '../../api/u64';
import {millis, parseU64} from '../../api/u64';
import {latencyTone} from '../../ui/ui';
import {policyKindLabels} from '../policies/view';
import type {RoutingTree, TreeBy, TreeItem} from './map';
@@ -148,7 +148,7 @@ function flowStepFields(step: FlowStep): Array<[Key | MessageRef, string | Messa
type TileNote = {text: string; tone?: 'ok' | 'warn' | 'err'};
export type TileView = {id: string; stage: TreeBy | 'outbound' | 'node'; name: string; badge?: string; notes: TileNote[]; count: number; label: string};
export function tileViews(tree: RoutingTree, t: Translator): TileView[] {
export function tileViews(tree: RoutingTree, t: Translator, lang: Lang): TileView[] {
const unknown = (item: TreeItem, name: string) => (item.unknown ? t('flow.mapUnknown') : name);
type Bare = Omit<TileView, 'label'>;
const tiles: Bare[] = [
@@ -185,10 +185,14 @@ export function tileViews(tree: RoutingTree, t: Translator): TileView[] {
}))
];
const names = new Map(tiles.map(tile => [tile.id, tile.name]));
const {outgoing, incoming} = treeIndex(tree);
return tiles.map(tile => {
const to = (treeIndex(tree).outgoing.get(tile.id) ?? []).map(link => names.get(link.target)!);
const to = (outgoing.get(tile.id) ?? []).map(link => names.get(link.target)!);
// A node's groups are drawn only as connectors, so its name carries them for assistive technology.
const from = tile.stage === 'node' ? (incoming.get(tile.id) ?? []).map(link => names.get(link.source)!) : [];
const parts = [tile.name, ...(tile.badge ? [tile.badge] : []), ...tile.notes.map(note => note.text), t('flow.treeFlows', {n: tile.count})];
if (to.length) parts.push('→ ' + to.join(', '));
if (from.length) parts.push(t('flow.treeFrom', {names: formatList(lang, from)}));
if (to.length) parts.push(t('flow.treeTo', {names: formatList(lang, to)}));
return {...tile, label: parts.join(' · ')};
});
}
@@ -205,7 +209,8 @@ const visibility: Record<string, Key> = {full: 'flow.full', partial: 'flow.parti
export type CoverageView = {summary: string | null; detail: string; dropped: string | null};
export function coverageView(data: Pick<FlowList, 'coverage' | 'dropped_records'>, t: Translator, lang: Lang): CoverageView | null {
const partial = Object.entries(data.coverage).filter(([, value]) => value !== 'full');
const dropped = data.dropped_records !== null && BigInt(data.dropped_records) > 0n ? t('flow.dropped', {n: data.dropped_records}) : null;
const count = parseU64(data.dropped_records);
const dropped = count ? t('flow.dropped', {n: formatNumber(count, LOCALE[lang])}) : null;
if (!partial.length && !dropped) return null;
return {
summary: partial.length ? t('flow.coverageSummary', {n: partial.length}) : null,
@@ -316,7 +321,7 @@ export function flowRecordsView(
id: step.seq,
stage: stages[step.stage] ? t(stages[step.stage]) : step.stage,
observed: localTime(step.observed_at, locale),
elapsed: t('ui.microseconds', {n: step.elapsed_us ?? '—'}),
elapsed: step.elapsed_us == null ? '—' : t('ui.microseconds', {n: step.elapsed_us}),
fields:
fields?.map(([key, value]) => [
typeof key === 'string' ? t(key) : t(key.key, key.params),
@@ -345,7 +350,7 @@ export function treeWindow(tree: RoutingTree, limit: number): RoutingTree {
return tree.leaves.length <= limit ? tree : {...tree, leaves: tree.leaves.slice(0, limit)};
}
export function treeGeometry(tree: RoutingTree, measured: number | null, t: Translator) {
export function treeGeometry(tree: RoutingTree, measured: number | null, t: Translator, lang: Lang) {
const width = measured === null ? undefined : Math.max(measured, MIN_WIDTH);
const unit = ((width ?? 0) - 2 * GAP) / shares.reduce((sum, share) => sum + share);
const column = (stage: TreeStage) => {
@@ -353,7 +358,7 @@ export function treeGeometry(tree: RoutingTree, measured: number | null, t: Tran
return {left: shares.slice(0, index).reduce((sum, share) => sum + share * unit + GAP, 0), width: shares[index] * unit};
};
const layout = treeRows(tree);
const placed = tileViews(tree, t).map(view => ({view, style: {top: layout.at.get(view.id)! * PITCH, ...column(view.stage)}}));
const placed = tileViews(tree, t, lang).map(view => ({view, style: {top: layout.at.get(view.id)! * PITCH, ...column(view.stage)}}));
const outbounds = new Map(tree.outbounds.map(outbound => [outbound.id, outbound]));
const geometry = tree.links.flatMap(link => {
if (!layout.at.has(link.source) || !layout.at.has(link.target)) return [];
+33 -32
View File
@@ -1,11 +1,42 @@
import {useMemo} from 'react';
import {useT} from '../../i18n';
import {Button, DataTable, ErrorMessage, LabeledSelect, Light, Switch, TextField, TextTooltip, Empty} from '../../ui/ui';
import {Button, DataTable, ErrorMessage, LabeledSelect, Light, Switch, TextField, TextTooltip, Empty, type TableColumn} from '../../ui/ui';
import {useLogs} from './useLogs';
import Download from '../../ui/icons/Download';
type LogRow = ReturnType<typeof useLogs>['rows'][number];
export function Logs() {
const t = useT();
const vm = useLogs();
// Stable column definitions: a new array on every stream tick would re-render every visible row.
const columns = useMemo(
(): TableColumn<LogRow>[] => [
{id: 'ts', label: t('ui.time'), minWidth: 180, grow: 0, drop: 2, render: record => <span className="rp-code">{record.timestamp}</span>},
{
id: 'level',
label: t('log.level'),
minWidth: 90,
grow: 0,
drop: 3,
render: record => (
<Light small tone={record.tone}>
{record.levelText}
</Light>
)
},
{id: 'target', label: t('log.target'), minWidth: 160, grow: 0, drop: 1, render: record => <span className="rp-code">{record.target}</span>},
{
id: 'message',
label: t('log.message'),
minWidth: 280,
grow: 3,
isRowHeader: true,
render: record => <TextTooltip>{record.message}</TextTooltip>
}
],
[t]
);
if (vm.unavailable)
return (
<div className="rp-page">
@@ -33,37 +64,7 @@ export function Logs() {
</Button>
</div>
<ErrorMessage error={vm.error} onRetry={vm.retry} />
<DataTable
label={t('nav.logs')}
rows={vm.rows}
height={640}
loading={vm.loading}
empty={t('log.empty')}
cols={[
{id: 'ts', label: t('ui.time'), minWidth: 180, grow: 0, drop: 2, render: record => <span className="rp-code">{record.timestamp}</span>},
{
id: 'level',
label: t('log.level'),
minWidth: 90,
grow: 0,
drop: 3,
render: record => (
<Light small tone={record.tone}>
{record.levelText}
</Light>
)
},
{id: 'target', label: t('log.target'), minWidth: 160, grow: 0, drop: 1, render: record => <span className="rp-code">{record.target}</span>},
{
id: 'message',
label: t('log.message'),
minWidth: 280,
grow: 3,
isRowHeader: true,
render: record => <TextTooltip>{record.message}</TextTooltip>
}
]}
/>
<DataTable label={t('nav.logs')} stream rows={vm.rows} height={640} loading={vm.loading} empty={t('log.empty')} cols={columns} />
</div>
);
}
+18 -15
View File
@@ -4,16 +4,17 @@ export const messages = defineMessages({
'zh-TW': {
'log.unavailable': '此後端不提供日誌串流。',
'log.level': '等級',
'log.level.trace': 'trace',
'log.level.debug': 'debug',
'log.level.info': 'info',
'log.level.warn': 'warn',
'log.level.error': 'error',
'log.level.trace': '追蹤',
'log.level.debug': '除錯',
'log.level.info': '資訊',
'log.level.warn': '警告',
'log.level.error': '錯誤',
'log.target': '模組',
'log.targetPlaceholder': '模組前綴',
'log.pause': '暫停',
'log.connected': '串流中',
'log.reconnecting': '連線中',
'log.disconnected': '已中斷連線',
'log.clear': '清空',
'log.export': '匯出',
'log.message': '訊息',
@@ -22,16 +23,17 @@ export const messages = defineMessages({
'zh-CN': {
'log.unavailable': '此后端不提供日志流。',
'log.level': '级别',
'log.level.trace': 'trace',
'log.level.debug': 'debug',
'log.level.info': 'info',
'log.level.warn': 'warn',
'log.level.error': 'error',
'log.level.trace': '跟踪',
'log.level.debug': '调试',
'log.level.info': '信息',
'log.level.warn': '警告',
'log.level.error': '错误',
'log.target': '模块',
'log.targetPlaceholder': '模块前缀',
'log.pause': '暂停',
'log.connected': '流式接收中',
'log.reconnecting': '连接中',
'log.disconnected': '已断开连接',
'log.clear': '清空',
'log.export': '导出',
'log.message': '消息',
@@ -40,16 +42,17 @@ export const messages = defineMessages({
en: {
'log.unavailable': 'This backend does not stream logs.',
'log.level': 'Level',
'log.level.trace': 'trace',
'log.level.debug': 'debug',
'log.level.info': 'info',
'log.level.warn': 'warn',
'log.level.error': 'error',
'log.level.trace': 'Trace',
'log.level.debug': 'Debug',
'log.level.info': 'Info',
'log.level.warn': 'Warning',
'log.level.error': 'Error',
'log.target': 'Module',
'log.targetPlaceholder': 'Module prefix',
'log.pause': 'Pause',
'log.connected': 'Streaming',
'log.reconnecting': 'Connecting',
'log.disconnected': 'Disconnected',
'log.clear': 'Clear',
'log.export': 'Export',
'log.message': 'Message',
+2 -2
View File
@@ -18,8 +18,8 @@ export function useLogs() {
const level = logLevel(requestedLevel, resource?.levels);
const feed = useLogFeed({level, target: targetFilter, paused});
const view = useMemo(
() => logView(feed.records, resource?.levels ?? [], feed.connected, version.data?.engine.name, locale, t),
[feed.records, feed.connected, resource, version.data, locale, t]
() => logView(feed.records, resource?.levels ?? [], feed.connected, version.data?.engine.name, locale, t, !!feed.error),
[feed.records, feed.connected, feed.error, resource, version.data, locale, t]
);
return {
...view,
+1
View File
@@ -22,6 +22,7 @@ it('keeps structured fields readable in rows and lossless in chronological expor
expect(logsExport(records)).toContain(JSON.stringify(records[0].fields));
expect(view.levels.map(level => level.id)).toEqual(['error']);
expect(view.status.tone).toBe('warn');
expect(logView(records, ['error'], false, undefined, 'en-US', t, true).status).toEqual({tone: 'err', text: t('log.disconnected')});
});
it('resolves selected log levels against advertised choices', () => {
+9 -5
View File
@@ -4,7 +4,7 @@ import type {Translator as LabelFn} from '../../i18n';
import type {Key} from '../../i18n/messages';
const tones = {trace: 'muted', debug: 'neutral', info: 'info', warn: 'warn', error: 'err'} as const;
const labels: Record<LogLevel, Key> = {
export const logLevelLabels: Record<LogLevel, Key> = {
trace: 'log.level.trace',
debug: 'log.level.debug',
info: 'log.level.info',
@@ -20,7 +20,7 @@ function logRow(record: LogRecord & {id: string}, locale: string, t: LabelFn): L
const row: LogRow = {
id: record.id,
timestamp: localTime(record.ts, locale),
levelText: t(labels[record.level]),
levelText: t(logLevelLabels[record.level]),
tone: tones[record.level],
target: record.target,
message:
@@ -41,12 +41,16 @@ export function logView(
connected: boolean,
engine: string | undefined,
locale: string,
t: LabelFn
t: LabelFn,
failed = false
) {
return {
rows: records.map(record => logRow(record, locale, t)),
levels: levels.map(id => ({id, label: t(labels[id])})),
status: {tone: connected ? ('ok' as const) : ('warn' as const), text: t(connected ? 'log.connected' : 'log.reconnecting')},
levels: levels.map(id => ({id, label: t(logLevelLabels[id])})),
// A failed stream is not retried until asked, so it is not "connecting".
status: failed
? {tone: 'err' as const, text: t('log.disconnected')}
: {tone: connected ? ('ok' as const) : ('warn' as const), text: t(connected ? 'log.connected' : 'log.reconnecting')},
exportBase: `${engine || 'engine'}-log`
};
}
+1 -1
View File
@@ -63,7 +63,7 @@ export function NodeTable({model: m}: {model: NodeTableView}) {
</MenuButton>
)}
{row.removable && (
<Button small quiet isDisabled={busy} label={row.removeLabel} onPress={row.remove}>
<Button small quiet icon isDisabled={busy} label={row.removeLabel} onPress={row.remove}>
<Close />
</Button>
)}
+1 -1
View File
@@ -94,7 +94,7 @@ export function ProviderTable({model: m}: {model: ProviderTableView}) {
</Button>
)}
{row.removable && (
<Button small quiet isDisabled={m.busy} label={row.removeLabel} onPress={row.remove}>
<Button small quiet icon isDisabled={m.busy} label={row.removeLabel} onPress={row.remove}>
<Close />
</Button>
)}
+8 -1
View File
@@ -63,7 +63,7 @@ describe('writeInterval', () => {
it('turns a scalar entry into a block and keeps its agent', () => {
const next = writeInterval(text, 'compatible', 3600);
expect(next).toContain(
` compatible: {\n url: 'https://example.net/sub'\n ua: 'honk/1.0 like'\n interval: '3600s'\n }\n 'https://example.org/no_tag_link'`
` compatible: {\n url: 'https://example.net/sub'\n ua: 'honk/1.0 like'\n interval: '3600s'\n } # keep the agent\n 'https://example.org/no_tag_link'`
);
expect(readSubscriptions(next).find(e => e.tag === 'compatible')?.interval).toBe(3600);
});
@@ -132,3 +132,10 @@ it('does not turn unreadable or unspecified intervals into manual-only or a pres
);
expect(entries.map(entry => entry.interval)).toEqual([null, null]);
});
it('keeps a same-line comment when a one-line subscription becomes a block', () => {
const text = "subscription {\n paid: 'https://example.org/sub' # work account\n}\n";
const out = writeInterval(text, 'paid', 3600);
expect(out).toContain('# work account');
expect(out).toContain("interval: '3600s'");
});
+8 -4
View File
@@ -2,7 +2,7 @@ import {blockFields, quote, scanConfig, uncomment, unquote, type TextBlock, type
export type SubscriptionEntry = {tag: string; host: string | null; interval: number | null; from: number; to: number};
type ScalarSubscription = {tag: string; url: string; ua: string | null};
type SubscriptionRange = SubscriptionEntry & {block?: TextBlock; fields: TextField[]; parts: ScalarSubscription | null};
type SubscriptionRange = SubscriptionEntry & {block?: TextBlock; fields: TextField[]; parts: ScalarSubscription | null; comment?: string};
export function parseInterval(text: string): number | null {
const found = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(text.trim());
@@ -86,9 +86,13 @@ function subscriptionRanges(text: string) {
while (tokens[i + 1] && !(text[tokens[i].from] === ')' && tokens[i].parens === 1)) i++;
}
let to = tokens[i].to;
if (tokens[i + 1]?.kind === 'comment' && tokens[i + 1].line === tokens[i].line) to = tokens[++i].to;
let comment: string | undefined;
if (tokens[i + 1]?.kind === 'comment' && tokens[i + 1].line === tokens[i].line) {
comment = text.slice(tokens[i + 1].from, tokens[i + 1].to);
to = tokens[++i].to;
}
const parts = scalarParts(text.slice(from, to));
if (parts) entries.push({from, to, tag: parts.tag, host: host(parts.url), interval: null, fields: [], parts});
if (parts) entries.push({from, to, tag: parts.tag, host: host(parts.url), interval: null, fields: [], parts, comment});
}
}
return entries;
@@ -113,7 +117,7 @@ export function writeInterval(text: string, tag: string, seconds: number): strin
if (entry.parts) {
const body = [`${indent}${/^[\w.-]+$/.test(tag) ? tag : quote(tag)}: {`, `${inner}url: ${quote(entry.parts.url)}`];
if (entry.parts.ua !== null) body.push(`${inner}ua: ${quote(entry.parts.ua)}`);
body.push(`${inner}interval: '${seconds}s'`, `${indent}}`);
body.push(`${inner}interval: '${seconds}s'`, `${indent}}${entry.comment ? ' ' + entry.comment : ''}`);
return text.slice(0, entry.from) + body.join('\n') + text.slice(entry.to);
}
const field = entry.fields.find(field => field.name === 'interval');
+11 -3
View File
@@ -1,4 +1,5 @@
import {useMemo, useState} from 'react';
import {useFilter} from 'react-aria-components';
import {useT, useLang, LOCALE, formatNumber} from '../../i18n';
import type {Node, Provider} from '../../api/model';
import {useNodeProbe} from '../../store';
@@ -51,7 +52,14 @@ export function useNodeTable(input: NodeTableInput) {
.map(id => ({id, label: id})),
[nodes]
);
const members = useMemo(() => nodeRows(nodes, search, group, protocol, sort), [nodes, search, group, protocol, sort]);
// A filter chosen for another source applies only if this source offers that value.
const activeGroup = groups.some(item => item.id === group) ? group : '';
const activeProtocol = protocols.some(item => item.id === protocol) ? protocol : '';
const {contains} = useFilter({sensitivity: 'base'});
const members = useMemo(
() => nodeRows(nodes, search, activeGroup, activeProtocol, sort, contains),
[nodes, search, activeGroup, activeProtocol, sort, contains]
);
const entries = useMemo(
() => readGroupEntries(source.main?.content ?? '').map(entry => ({...entry, names: new Set(namedIn(entry))})),
[source.main?.content]
@@ -95,9 +103,9 @@ export function useNodeTable(input: NodeTableInput) {
rows,
search,
setSearch,
group,
group: activeGroup,
setGroup,
protocol,
protocol: activeProtocol,
setProtocol,
sort,
setSort,
+5 -2
View File
@@ -51,7 +51,8 @@ export function useNodesPage({go, query}: PageProps) {
const entries = useMemo(() => readSubscriptions(source.main?.content ?? ''), [source.main?.content]);
const {list} = useMemo(() => providerRows(providers.data?.providers ?? [], nodes.data ?? [], entries, t), [providers.data, nodes.data, entries, t]);
const params = useMemo(() => new URLSearchParams(query), [query]);
const selectedId = params.get('provider') ?? list[0]?.id ?? null;
// Default to the first real source: the built-in and unattributed rows only lead when nothing else exists.
const selectedId = params.get('provider') ?? (list.find(item => item.kind !== 'builtin' && item.kind !== 'unattributed') ?? list[0])?.id ?? null;
const provider = list.find(item => item.id === selectedId) ?? null;
const owned = useMemo(() => {
const owner = list.find(item => item.id === selectedId);
@@ -155,7 +156,8 @@ export function useNodesPage({go, query}: PageProps) {
if (!id) return;
const next = new URLSearchParams(query);
next.set('provider', id);
go('nodes', next.toString());
// A source is always selected, so switching it rewrites the entry rather than stacking one per row.
go('nodes', next.toString(), {replace: true});
},
canManage: !!resources?.providers.can_manage,
canRefresh: !!resources?.providers.can_refresh,
@@ -163,6 +165,7 @@ export function useNodesPage({go, query}: PageProps) {
source,
entries,
reload,
refresh: refreshing,
onAdd: () => open({kind: 'provider'}),
onRemove: item => open({kind: 'removeProvider', item})
});
+2 -1
View File
@@ -17,13 +17,14 @@ type ProviderTableInput = {
source: MainSourceEdit;
entries: SubscriptionEntry[];
reload: () => void;
refresh: ReturnType<typeof useProviderRefresh>;
onAdd: () => void;
onRemove: (item: Provider) => void;
};
export function useProviderTable(input: ProviderTableInput) {
const t = useT();
const locale = LOCALE[useLang()];
const refresh = useProviderRefresh(input.reload);
const {refresh} = input;
const intervals = new Map(input.entries.map(entry => [entry.tag, entry.interval]));
const fail = (error: unknown) => toast('negative', errorText(error));
const rows = input.rows.map(item => ({
+11 -4
View File
@@ -5,6 +5,7 @@ import {nodeRows, ownedNodes, providerRows, nodeRowView, providerRowView, interv
import {translate, type Translator} from '../../i18n';
import {nodeFixtures} from '../../api/mock/fixtures';
import {formatBytes} from '../../api/u64';
const contains = (value: string, query: string) => value.toLowerCase().includes(query.toLowerCase());
const t: Translator = (key, params) => translate('en', key, params);
const provider = (id: string, overrides: Partial<Provider> = {}): Provider => ({
@@ -96,9 +97,15 @@ describe('node rows', () => {
node('hk-3', {group_ids: ['gaming'], protocol: 'trojan'}),
node('sg-1', {group_ids: ['gaming']})
];
expect(nodeRows(nodes, ' HK- ', 'gaming', 'vless', {column: 'name', direction: 'ascending'}).map(item => item.id)).toEqual(['hk-2', 'HK-10']);
expect(nodeRows(nodes, ' HK- ', 'gaming', 'vless', {column: 'name', direction: 'ascending'}, contains).map(item => item.id)).toEqual(['hk-2', 'HK-10']);
expect(nodes.map(item => item.id)).toEqual(['HK-10', 'hk-2', 'hk-1', 'hk-3', 'sg-1']);
expect(nodeRows(nodes, '', '', '', {column: 'protocol', direction: 'ascending'}).map(item => item.id)).toEqual(['hk-3', 'HK-10', 'hk-2', 'hk-1', 'sg-1']);
expect(nodeRows(nodes, '', '', '', {column: 'protocol', direction: 'ascending'}, contains).map(item => item.id)).toEqual([
'hk-3',
'HK-10',
'hk-2',
'hk-1',
'sg-1'
]);
});
it('sorts measured latency before missing health and breaks ties by name in either direction', () => {
@@ -124,8 +131,8 @@ describe('node rows', () => {
node('unavailable', {health: [{...sample, state: 'unavailable', latency_ms: 1}]})
];
const ascending = ['zero', 'slow-2', 'slow-10', 'missing', 'unavailable'];
expect(nodeRows(nodes, '', '', '', {column: 'latency', direction: 'ascending'}).map(item => item.id)).toEqual(ascending);
expect(nodeRows(nodes, '', '', '', {column: 'latency', direction: 'descending'}).map(item => item.id)).toEqual([...ascending].reverse());
expect(nodeRows(nodes, '', '', '', {column: 'latency', direction: 'ascending'}, contains).map(item => item.id)).toEqual(ascending);
expect(nodeRows(nodes, '', '', '', {column: 'latency', direction: 'descending'}, contains).map(item => item.id)).toEqual([...ascending].reverse());
});
});
+5 -4
View File
@@ -17,7 +17,7 @@ export function nodeRowView(node: Node, names: OutboundNames, lang: Lang, t: Tra
name: node.name,
protocol: node.protocol ?? '—',
latency: measured ? t('ui.latency', {n: millis(health.latency_ms!)}) : health?.state === 'unavailable' ? t('ui.unavailable') : '—',
latencyClass: measured ? `ms ${latencyTone(health.latency_ms!)}` : 'ms err',
latencyClass: measured ? `ms ${latencyTone(health.latency_ms!)}` : health?.state === 'unavailable' ? 'ms err' : 'ms',
groups: node.group_ids.length
? formatList(
lang,
@@ -122,10 +122,11 @@ export function ownedNodes(nodes: Node[], ownerId: string | null | undefined, ki
);
}
export function nodeRows(owned: Node[], search: string, group: string, protocol: string, sort: TableSort) {
const needle = search.trim().toLowerCase();
// `contains` is the locale-aware matcher the policy grid also uses, so both pages find the same names.
export function nodeRows(owned: Node[], search: string, group: string, protocol: string, sort: TableSort, contains: (value: string, query: string) => boolean) {
const needle = search.trim();
const kept = owned.filter(
node => (!needle || node.name.toLowerCase().includes(needle)) && (!group || node.group_ids.includes(group)) && (!protocol || node.protocol === protocol)
node => (!needle || contains(node.name, needle)) && (!group || node.group_ids.includes(group)) && (!protocol || node.protocol === protocol)
);
const sign = sort.direction === 'ascending' ? 1 : -1;
const latency = sort.column === 'latency' ? new Map(kept.map(node => [node.id, latencyOf(node)])) : new Map();
+10 -10
View File
@@ -8,7 +8,7 @@ export function Overview() {
const vm = useOverview();
return (
<div className="rp-page">
{vm.errors.capabilities && <ErrorMessage error={vm.errors.capabilities} />}
<ErrorMessage error={vm.errors.capabilities} onRetry={vm.retry.capabilities} />
<div className="rp-between">
<div className="rp-cluster">
<Light tone={vm.status.tone}>{vm.status.text}</Light>
@@ -29,13 +29,12 @@ export function Overview() {
<LifecycleActions actions={vm.actions} />
</div>
</div>
{vm.errors.runtime && <ErrorMessage error={vm.errors.runtime} onRetry={vm.retry} />}
<div className="rp-g3">
<section className="rp-card" aria-labelledby="overview-engine">
<h3 className="rp-h3" id="overview-engine">
{t('ov.engine')}
</h3>
{vm.errors.version && <ErrorMessage error={vm.errors.version} />}
<ErrorMessage error={vm.errors.version} onRetry={vm.retry.version} />
{vm.engine.state === 'ready' ? (
<>
<Kv items={vm.engine.fields} />
@@ -49,7 +48,7 @@ export function Overview() {
</>
) : vm.engine.state === 'loading' ? (
<Loading />
) : (
) : vm.errors.version ? null : (
<Empty>{t('ov.unavailable')}</Empty>
)}
</section>
@@ -57,6 +56,7 @@ export function Overview() {
<h3 className="rp-h3" id="overview-counters">
{t('ov.counters')}
</h3>
<ErrorMessage error={vm.errors.runtime} onRetry={vm.retry.runtime} />
{vm.counters.state === 'ready' ? (
<>
<Kv items={vm.counters.fields} />
@@ -64,7 +64,7 @@ export function Overview() {
</>
) : vm.counters.state === 'loading' ? (
<Loading />
) : (
) : vm.errors.runtime ? null : (
<Empty>{t('ov.unavailable')}</Empty>
)}
</section>
@@ -72,7 +72,7 @@ export function Overview() {
<h3 className="rp-h3" id="overview-memory">
{t('ov.memory')}
</h3>
{vm.errors.memory && <ErrorMessage error={vm.errors.memory} />}
<ErrorMessage error={vm.errors.memory} onRetry={vm.retry.memory} />
{vm.memory.state === 'ready' ? (
<>
{vm.memory.bar && <Bar label={vm.memory.bar.label} value={vm.memory.bar.value} pct={vm.memory.bar.pct} color={vm.memory.bar.color} />}
@@ -80,7 +80,7 @@ export function Overview() {
</>
) : vm.memory.state === 'loading' ? (
<Loading />
) : (
) : vm.errors.memory ? null : (
<Empty>{t('ov.unavailable')}</Empty>
)}
</section>
@@ -90,7 +90,7 @@ export function Overview() {
<h3 className="rp-h3" id="overview-datapath">
{t('ov.datapath')}
</h3>
{vm.errors.datapath && <ErrorMessage error={vm.errors.datapath} />}
<ErrorMessage error={vm.errors.datapath} onRetry={vm.retry.datapath} />
{vm.datapath.state === 'ready' ? (
<>
<Kv items={vm.datapath.fields} />
@@ -127,7 +127,7 @@ export function Overview() {
</>
) : vm.datapath.state === 'loading' ? (
<Loading />
) : (
) : vm.errors.datapath ? null : (
<Empty>{t('ov.unavailable')}</Empty>
)}
</section>
@@ -148,7 +148,7 @@ export function Overview() {
</div>
) : vm.resources.state === 'loading' ? (
<Loading />
) : (
) : vm.errors.capabilities ? null : (
<Empty>{t('ov.unavailable')}</Empty>
)}
</section>
+7 -1
View File
@@ -44,7 +44,13 @@ export function useOverview() {
...view,
memory: memoryView,
errors: {capabilities: capabilities.error, runtime: runtime.error, version: version.error, memory: memory.error, datapath: datapath.error},
retry: runtime.refetch,
retry: {
capabilities: capabilities.refetch,
runtime: runtime.refetch,
version: version.refetch,
memory: memory.refetch,
datapath: datapath.refetch
},
actions: lifecycleActions(operations.canRun, operations.busy, kind => void run(kind), t),
export: () => downloadFile(exportName('doona-state', 'json'), overviewExport(data, new Date().toISOString()), 'application/json')
};
+14 -3
View File
@@ -9,13 +9,13 @@ const loading = {capabilities: false, runtime: false, version: false, memory: fa
it('keeps unknown datapath vocabulary and does not invent unknown map occupancy', () => {
expect(datapathValue('future_backend', t)).toBe('future_backend');
const value = {...datapath, ebpf: {...datapath.ebpf!, maps: {state: 'ready' as const, conn_state: {occupancy: 0, capacity: 100, occupancy_known: false}}}};
expect(datapathFields(value, 'unknown', t).find(([label]) => label === t('ov.f.connState'))?.[1]).toBe('unknown');
expect(datapathFields(value, 'unknown', t, 'en-US').find(([label]) => label === t('ov.f.connState'))?.[1]).toBe('unknown');
});
it('marks shared memory as shared and omits selected fields without losing zero counters', () => {
const fields = memoryFields({...runtimeMemory, cgroup: {...runtimeMemory.cgroup!, scope: 'shared'}}, t, ['ov.f.cgroupPercent']);
const fields = memoryFields({...runtimeMemory, cgroup: {...runtimeMemory.cgroup!, scope: 'shared'}}, t, 'en-US', ['ov.f.cgroupLimit']);
expect(fields.find(([label]) => label === t('ov.f.cgroupScope'))?.[1]).toBe(t('ov.v.cgroupShared'));
expect(fields.find(([label]) => label === t('ov.f.cgroupPercent'))).toBeUndefined();
expect(fields.find(([label]) => label === t('ov.f.cgroupLimit'))).toBeUndefined();
expect(fields.find(([label]) => label === t('ov.f.oomKill'))?.[1]).toBe('0');
});
@@ -30,6 +30,17 @@ it('distinguishes loading and unavailable sections and deduplicates datapath err
expect(absent.canExport).toBe(false);
});
it('shows the version without the runtime and formats counts for the locale', () => {
const engine = overviewView({version}, loading, 'en-US', t).engine;
expect(engine.state).toBe('ready');
expect(engine.fields).toContainEqual([t('ov.f.instance'), '—']);
const events = {...runtimeMemory.cgroup!.events!, oom: '12345'};
const fields = memoryFields({...runtimeMemory, cgroup: {...runtimeMemory.cgroup!, events}}, t, 'en-US');
expect(fields).toContainEqual([t('ov.f.oom'), '12,345']);
const maps = {state: 'ready' as const, conn_state: {occupancy: 1234, capacity: 65536, occupancy_known: true}};
expect(datapathFields({...datapath, ebpf: {...datapath.ebpf!, maps}}, 'unknown', t, 'en-US')).toContainEqual([t('ov.f.connState'), '1,234 / 65,536']);
});
it('retains a pending operation even when lifecycle state stops offering it', () => {
const run = vi.fn();
const actions = lifecycleActions(kind => kind === 'resume', 'suspend', run, t);
+30 -25
View File
@@ -1,7 +1,7 @@
import type {Capabilities, Datapath, Runtime, RuntimeMemory, Version} from '../../api/model';
import type {Key} from '../../i18n/messages';
import {formatDuration, lifecycleStates, lifecycleTone, localTime, shortId} from '../../api/selectors';
import {formatBytes, pctU64} from '../../api/u64';
import {formatBytes, parseU64, pctU64} from '../../api/u64';
import {formatNumber, type Translator as LabelFn} from '../../i18n';
const datapathValues: Record<string, Key> = {
ebpf: 'ov.v.ebpf',
@@ -32,7 +32,7 @@ const datapathValues: Record<string, Key> = {
export function datapathValue(value: string, label: LabelFn): string {
return datapathValues[value] ? label(datapathValues[value]) : value;
}
export function datapathFields(datapath: Datapath, unknown: string, label: LabelFn): Array<[string, string]> {
export function datapathFields(datapath: Datapath, unknown: string, label: LabelFn, locale: string): Array<[string, string]> {
const ebpf = datapath.ebpf;
const occupancy = ebpf?.maps?.conn_state;
const v = (value: string) => datapathValue(value, label);
@@ -48,24 +48,31 @@ export function datapathFields(datapath: Datapath, unknown: string, label: Label
[label('ov.f.routing'), v(ebpf.routing.state)],
[label('ov.f.health'), v(ebpf.health)],
[label('ov.f.maps'), v(ebpf.maps?.state ?? 'unknown')],
[label('ov.f.connState'), occupancy?.occupancy_known && occupancy.occupancy !== null ? occupancy.occupancy + ' / ' + occupancy.capacity : unknown]
[
label('ov.f.connState'),
occupancy?.occupancy_known && occupancy.occupancy !== null
? formatNumber(occupancy.occupancy, locale) + ' / ' + formatNumber(occupancy.capacity, locale)
: unknown
]
] as Array<[string, string]>)
: [])
];
}
const cgroupScopes: Record<'service' | 'shared' | 'unknown', Key> = {service: 'ov.v.cgroupService', shared: 'ov.v.cgroupShared', unknown: 'ui.unknown'};
export function memoryFields(memory: RuntimeMemory, label: LabelFn, omit: Key[] = []): Array<[string, string]> {
const percent = pctU64(memory.cgroup?.current_bytes ?? null, memory.cgroup?.limit_bytes ?? null);
export function memoryFields(memory: RuntimeMemory, label: LabelFn, locale: string, omit: Key[] = []): Array<[string, string]> {
const count = (value: string | null | undefined) => {
const parsed = parseU64(value ?? null);
return parsed === null ? '—' : formatNumber(parsed, locale);
};
const rows: Array<[Key, string]> = [
['ov.f.rss', formatBytes(memory.process?.rss_bytes ?? null)],
['ov.f.cgroupCurrent', formatBytes(memory.cgroup?.current_bytes ?? null)],
['ov.f.cgroupLimit', formatBytes(memory.cgroup?.limit_bytes ?? null)],
['ov.f.cgroupPercent', percent === null ? '—' : Math.round(percent) + '%'],
// Distinguish service, shared, and unknown cgroups so shared usage is not attributed solely to the engine.
['ov.f.cgroupScope', memory.cgroup ? label(cgroupScopes[memory.cgroup.scope]) : '—'],
['ov.f.oomHigh', memory.cgroup?.events?.high ?? '—'],
['ov.f.oom', memory.cgroup?.events?.oom ?? '—'],
['ov.f.oomKill', memory.cgroup?.events?.oom_kill ?? '—'],
['ov.f.oomHigh', count(memory.cgroup?.events?.high)],
['ov.f.oom', count(memory.cgroup?.events?.oom)],
['ov.f.oomKill', count(memory.cgroup?.events?.oom_kill)],
['ov.f.ebpfBytes', formatBytes(memory.kernel?.ebpf_bytes ?? null)]
];
return rows.filter(([key]) => !omit.includes(key)).map(([key, value]) => [label(key), value]);
@@ -133,18 +140,18 @@ export function overviewView(
}
: null,
engine: {
state: section(!!version && !!runtime, loading.capabilities || loading.version || loading.runtime),
fields:
version && runtime
? ([
[t('ov.f.engine'), version.engine.name + ' ' + version.engine.version],
[t('ov.f.api'), `${version.api.name} v${version.api.major} · ${version.api.status}`],
[t('ov.f.build'), [version.build?.revision, version.build?.target].filter(Boolean).join(' · ') || '—'],
[t('ov.f.instance'), runtime.instance_id],
[t('ov.f.started'), localTime(runtime.lifecycle.started_at, locale)],
[t('ov.f.activated'), runtime.generation.activated_at ? localTime(runtime.generation.activated_at, locale) : '—']
] as Array<[string, string]>)
: [],
// The version stands on its own: a failing runtime leaves its rows at a dash rather than hiding the build.
state: section(!!version, loading.version),
fields: version
? ([
[t('ov.f.engine'), version.engine.name + ' ' + version.engine.version],
[t('ov.f.api'), `${version.api.name} v${version.api.major} · ${version.api.status}`],
[t('ov.f.build'), [version.build?.revision, version.build?.target].filter(Boolean).join(' · ') || '—'],
[t('ov.f.instance'), runtime?.instance_id ?? '—'],
[t('ov.f.started'), localTime(runtime?.lifecycle.started_at ?? null, locale)],
[t('ov.f.activated'), localTime(runtime?.generation.activated_at ?? null, locale)]
] as Array<[string, string]>)
: [],
profiles: capabilities?.profiles.map(id => ({id, text: t(id === 'base' ? 'ov.profileBase' : 'ov.profileFull')})) ?? []
},
counters: {
@@ -168,9 +175,7 @@ export function overviewView(
},
memory: {
state: section(!!memory, loading.capabilities || loading.memory),
fields: memory
? memoryFields(memory, t, percent === null ? ['ov.f.cgroupPercent'] : ['ov.f.cgroupPercent', 'ov.f.cgroupCurrent', 'ov.f.cgroupLimit'])
: [],
fields: memory ? memoryFields(memory, t, locale, percent === null ? [] : ['ov.f.cgroupCurrent', 'ov.f.cgroupLimit']) : [],
bar:
percent === null
? null
@@ -183,7 +188,7 @@ export function overviewView(
},
datapath: {
state: section(!!datapath, loading.capabilities || loading.datapath),
fields: datapath ? datapathFields(datapath, t('ov.unknown'), t) : [],
fields: datapath ? datapathFields(datapath, t('ov.unknown'), t, locale) : [],
showAttachments: !!datapath?.ebpf,
attachments: (datapath?.ebpf?.attachments ?? []).map((a, i) => ({
id: String(i),
+36 -8
View File
@@ -1,4 +1,4 @@
import {memo} from 'react';
import {memo, type ReactNode} from 'react';
import {useT} from '../../i18n';
import Refresh from '../../ui/icons/Refresh';
import {Badge, Button, Disclosure, DisclosureGroup, ErrorMessage, Light, Loading, Kv, Segmented, Switch, Empty} from '../../ui/ui';
@@ -8,6 +8,29 @@ import type {PageProps} from '../types';
import {usePolicies, usePolicyVisibility} from './usePolicies';
import {usePolicyGroup, type PolicyGroupInput} from './usePolicyGroup';
// Holds roughly the loaded card's height, so cards below do not move when the details arrive.
function PolicyWait({heading, members, label}: {heading: ReactNode; members: number; label?: string}) {
return (
<>
<div className="rp-row">{heading}</div>
<div className="rp-wait-line" />
<div className="rp-form" role={label ? 'status' : undefined} aria-label={label}>
{members > 12 ? (
<>
<div className="rp-wait-line" />
<div className="rp-nodegrid" />
</>
) : (
<div className="rp-nodes">
{Array.from({length: Math.max(members, 1)}, (_, i) => (
<span key={i} className="rp-node" />
))}
</div>
)}
</div>
</>
);
}
function PolicyDetail(props: PolicyGroupInput) {
const t = useT();
const m = usePolicyGroup(props);
@@ -15,7 +38,7 @@ function PolicyDetail(props: PolicyGroupInput) {
return (
<>
<ErrorMessage error={m.error} />
{m.loading && <Loading>{m.loadingText}</Loading>}
{m.loading && <PolicyWait heading={<h3 className="rp-h3">{props.name}</h3>} members={props.members} label={m.loadingText} />}
{g && (
<>
<div className="rp-row">
@@ -82,16 +105,21 @@ function PolicyDetail(props: PolicyGroupInput) {
</>
);
}
const PolicyCard = memo(function PolicyCard({focused, domId, ...props}: PolicyGroupInput & {focused: boolean; domId: string}) {
const {ref, active, expand} = usePolicyVisibility(focused);
const PolicyCard = memo(function PolicyCard({focused, domId, ...props}: Omit<PolicyGroupInput, 'paused'> & {focused: boolean; domId: string}) {
const {ref, active, visible, expand} = usePolicyVisibility(focused);
return (
<section ref={ref} className="rp-card" id={domId} aria-label={props.name}>
{active ? (
<PolicyDetail {...props} />
<PolicyDetail {...props} paused={!visible} />
) : (
<Button quiet onPress={expand}>
{props.name}
</Button>
<PolicyWait
heading={
<Button quiet onPress={expand}>
{props.name}
</Button>
}
members={props.members}
/>
)}
</section>
);
+10
View File
@@ -0,0 +1,10 @@
import {expect, it} from 'vitest';
import {regionOf} from './geo';
it('guesses regions from whole Latin tokens and spaced phrases', () => {
expect(regionOf('HK-01')).toBe('HK');
expect(regionOf('FRA 02')).toBe('DE');
expect(regionOf('Paris CDG')).toBe('FR');
expect(regionOf('San Jose premium')).toBe('US');
expect(regionOf('shkhk')).toBeNull();
});
Loaded 100 of 168 files, more files were not shown because too many files have changed in this diff. Show more