mirror of
https://github.com/Zakkaus/doona.git
synced 2026-12-05 08:00:59 +00:00
feat(engines): work with dae through its native API (#722)
## Problem / 问题 The README already lists dae as a backend, but doona treated every backend as honk. Against dae's native API every probe failed with 422 (dae accepts only cold probes, `component/nativeapi/handlers_probes.go:85-89`), mode switching, rule templates and new groups were always off because dae keeps the entry file read-only and the sections in `config.d` modules, group edits wrote honk's policies and filters that dae rejects, and messages said honk. ## How I fixed it / 解决方法 A dae engine profile (`src/api/engines/dae.ts`) holds what differs, and the pages ask the engine instead of assuming honk. Probes send cold and offer the kinds dae declares. Writes go to the module that owns the section, falling back to `config.d/group.dae` as dae does (`cmd/config_groups.go:103-115`). The group dialog follows dae's grammar: its policies, no nested groups or `subtag(keyword: …)`, names dae can parse and does not rewrite (`must_`), `&&` continuation lines and latency annotations kept, `fixed`/`select` index within the members. Node delete is offered only for `config.d/node.dae`, the one file dae's DELETE edits. Messages name the running backend. honk keeps its behaviour and wording. Not fixed here, dae side: rules report `source: null` (so the rules page stays read-only), groups advertise empty `probe_transports` (so group-wide tests stay off), and `read_only_reason` values `entry_source`/`layout_unmanaged` are not in the contract enum. dae publishes `operation.updated` for every probe job, which fills the notices; honk publishes the same event, so it is left as it is. ## Verified / 验证 `pnpm check` passes (254 files, 4,470 tests). The full e2e suite ran once at the last code state but two: 10 failures, all from expected text (fixed in this commit) and from a notice change that is reverted here; the rerun was stopped by host memory pressure, so CI's e2e is the final check. Group text written for dae was parsed with dae's own Go parser (`config_parser.Parse` + `config.New`). Live against dae `0d85246` on a test VM: nodes, single and all-node probes (cold, healthy nodes 8–14 ms, a dead node unavailable), new group written to `group.dae` and reloaded, global and rule mode written to `routing.dae` and reloaded, configuration page, DNS, logs and connections. That live run predates the last two fixes (policy labels, `must_` and index checks), which are covered by unit tests only. No honk screen changes. | Nodes after test all | Global mode written | Entry file read-only | |---|---|---| |  |  |  | --- - [x] I understand this change and answer for every line - [x] This branch is based on the current main - [x] I ran the repository's gates and recorded the results in Verified - [x] Each commit is one coherent change - [x] If behaviour changed, I updated the documentation - [x] If interface text changed, I updated `en.json` and every complete language's catalogue - [ ] If interface appearance changed, I attached light and dark screenshots - [ ] If the API contract changed, I ran `pnpm gen:api` and `pnpm check:gen` - [ ] I checked the boxes above without reading them - [ ] I am an AI agent, and this content was submitted without human review
This commit is contained in:
72 files changed
+1316
-313
No files matched your search
+1
-1
@@ -142,7 +142,7 @@ For lite’s separate dependency install and build commands, see [Development](h
|
||||
|
||||
## Support
|
||||
|
||||
Report interface problems and ask questions in [doona issues](https://github.com/Zakkaus/doona/issues). Report proxy, routing, DNS and other engine problems in [honk issues](https://github.com/daeuniverse/honk/issues). See [SECURITY.md](.github/SECURITY.md) for reporting a vulnerability.
|
||||
Report interface problems and ask questions in [doona issues](https://github.com/Zakkaus/doona/issues). Report proxy, routing, DNS and other engine problems to the engine in use: [honk issues](https://github.com/daeuniverse/honk/issues) or [dae issues](https://github.com/daeuniverse/dae/issues). See [SECURITY.md](.github/SECURITY.md) for reporting a vulnerability.
|
||||
|
||||
## License and credits
|
||||
|
||||
|
||||
@@ -142,7 +142,7 @@ lite 的獨立相依套件安裝與建置指令見[開發](https://daeuniverse.o
|
||||
|
||||
## 支援
|
||||
|
||||
介面問題與提問請到 [doona issues](https://github.com/Zakkaus/doona/issues)。代理、分流、DNS 等引擎問題請提交至 [honk issues](https://github.com/daeuniverse/honk/issues)。通報安全漏洞的方式見 [SECURITY.md](.github/SECURITY.md)。
|
||||
介面問題與提問請到 [doona issues](https://github.com/Zakkaus/doona/issues)。代理、分流、DNS 等引擎問題請提交至所用引擎的 [honk issues](https://github.com/daeuniverse/honk/issues) 或 [dae issues](https://github.com/daeuniverse/dae/issues)。通報安全漏洞的方式見 [SECURITY.md](.github/SECURITY.md)。
|
||||
|
||||
## 授權與致謝
|
||||
|
||||
|
||||
+1
-1
@@ -142,7 +142,7 @@ lite 的独立依赖安装与构建命令见[开发](https://daeuniverse.org/zh-
|
||||
|
||||
## 支持
|
||||
|
||||
界面问题与提问请到 [doona issues](https://github.com/Zakkaus/doona/issues)。代理、分流、DNS 等引擎问题请提交到 [honk issues](https://github.com/daeuniverse/honk/issues)。报告安全漏洞的方式见 [SECURITY.md](.github/SECURITY.md)。
|
||||
界面问题与提问请到 [doona issues](https://github.com/Zakkaus/doona/issues)。代理、分流、DNS 等引擎问题请提交到所用引擎的 [honk issues](https://github.com/daeuniverse/honk/issues) 或 [dae issues](https://github.com/daeuniverse/dae/issues)。报告安全漏洞的方式见 [SECURITY.md](.github/SECURITY.md)。
|
||||
|
||||
## 许可与致谢
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
Fixed
|
||||
|
||||
- On dae, node and group probes send cold probes, which dae accepts, instead of failing with 422, and offer the probe kinds dae declares.
|
||||
- On dae, the outbound mode, rule templates and new groups write to the module that owns the section, in dae's syntax and with dae's policies.
|
||||
- On dae, node delete is offered only where dae deletes, filters continued on a `&&` line stay one filter, and `random` groups are no longer shown as manual selectors.
|
||||
- Reload, suspend and other messages name the running backend instead of always saying honk.
|
||||
+1
-1
@@ -6,7 +6,7 @@ import {translate} from '../src/i18n';
|
||||
import type {RuntimeSettings} from '../src/api/model';
|
||||
|
||||
test.beforeAll(loadCatalogues);
|
||||
const t = (key: Parameters<typeof translate>[1], params?: Parameters<typeof translate>[2]) => translate('en', key, params);
|
||||
const t = (key: Parameters<typeof translate>[1], params?: Parameters<typeof translate>[2]) => translate('en', key, params, undefined, undefined, 'honk');
|
||||
const full = geodataPreset('metacubex');
|
||||
const loyal = geodataPreset('loyalsoldier');
|
||||
// Serves the mock over the network and records every settings PATCH and geodata update the page sends, in order.
|
||||
|
||||
+1
-1
@@ -258,7 +258,7 @@ test('a Clash API with a saved secret explains that the native API is missing',
|
||||
);
|
||||
await page.goto('/#/activity');
|
||||
const login = page.locator('.rp-login-page');
|
||||
await expect(login.getByRole('heading', {level: 1})).toHaveText('This honk build has no native API');
|
||||
await expect(login.getByRole('heading', {level: 1})).toHaveText('This backend does not provide the native API');
|
||||
await expect(login.locator('.rp-alert')).toHaveCount(0);
|
||||
await expect(login.getByLabel('Token', {exact: true})).toHaveCount(0);
|
||||
});
|
||||
|
||||
+1
-1
@@ -321,7 +321,7 @@ for (const [code, refused] of [
|
||||
for (const lang of ['zh-CN', 'zh-TW'] as const)
|
||||
test.describe(`edited link rejection in ${lang}`, () => {
|
||||
test.use({storage: {'doona-lang': lang}});
|
||||
const t: Translator = (key, params) => translate(lang, key, params);
|
||||
const t: Translator = (key, params) => translate(lang, key, params, undefined, undefined, 'honk');
|
||||
for (const message of ['', 'XHTTP padding must stay within 1-8192'])
|
||||
test(`a known diagnostic ${message ? 'retains backend detail' : 'with an empty message still rejects'} without writing`, async ({page}) => {
|
||||
const {api, handlers, requests} = await mockBackend(page);
|
||||
|
||||
@@ -56,7 +56,7 @@ test('a released honk without the native API shows the requirement instead of a
|
||||
backend.handlers['GET version'] = missing;
|
||||
await page.goto('/#/activity');
|
||||
const form = page.locator('.rp-login-page');
|
||||
await expect(form.getByRole('heading')).toHaveText('This honk build has no native API');
|
||||
await expect(form.getByRole('heading')).toHaveText('This backend does not provide the native API');
|
||||
await expect(form.getByLabel('Token', {exact: true})).toHaveCount(0);
|
||||
await expect(form.getByRole('link', {name: 'Native API requirements'})).toHaveAttribute(
|
||||
'href',
|
||||
|
||||
@@ -10,7 +10,7 @@ for (const {name, lang, viewport} of [
|
||||
test.describe(name, () => {
|
||||
test.use({viewport, storage: {'doona-lang': lang, 'doona-scheme': 'light'}});
|
||||
test.beforeAll(loadCatalogues);
|
||||
const t: Translator = (key, params) => translate(lang, key, params);
|
||||
const t: Translator = (key, params) => translate(lang, key, params, undefined, undefined, 'honk');
|
||||
|
||||
test('the demo listener source reports its secret reason and remains read-only', async ({page}) => {
|
||||
await mockBackend(page);
|
||||
@@ -61,7 +61,7 @@ for (const {name, lang, viewport} of [
|
||||
const toast = page.locator('.rp-toast.negative');
|
||||
await expect(toast).toHaveCount(1);
|
||||
expect(patches).toBe(1);
|
||||
const message = reason === 'listener_secret_in_content' ? t('ui.refusal.listenerSecretInContent') : 'A specific configuration refusal';
|
||||
const message = reason === 'listener_secret_in_content' ? t('ui.refusal.listenerSecretInContentHonk') : 'A specific configuration refusal';
|
||||
await expect(toast.locator('.msg')).toHaveText(t('policy.actionFailed', {name: 'auto', error: message}));
|
||||
await expect(url).toHaveValue('https://cp.cloudflare.com/generate_204');
|
||||
if (shots && reason === 'listener_secret_in_content') await page.screenshot({path: `shots/toast-${name}.png`});
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import {writeMode} from '../../dae/outboundMode';
|
||||
import {scanConfig} from '../../dae/text';
|
||||
import type {Key} from '../../i18n';
|
||||
import type {ConfigSource} from '../model';
|
||||
import {settingsSnippet} from './snippet';
|
||||
import type {Engine, EngineReason} from './types';
|
||||
|
||||
// cmd/config_editor.go:123-147,163-170. A read-only configuration alone does not identify which gate failed.
|
||||
function readOnlyNote(reason: string | undefined | null): Key | undefined {
|
||||
switch (reason) {
|
||||
case 'writes_disabled':
|
||||
return 'config.daeWritesDisabled';
|
||||
case 'layout_unmanaged':
|
||||
return 'config.daeLayout';
|
||||
case 'entry_source':
|
||||
return 'config.daeEntry';
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// The lexer in go.mod:9 also skips /* ... */. doona's structural scanner only skips # comments and treats backslashes in pairs.
|
||||
const readable = (text: string) => !text.includes('*/') && !/\\\\['"]/.test(text);
|
||||
|
||||
// cmd/config_layout.go:90-104 permits each section in one module, regardless of the basename.
|
||||
export function daeSectionTarget(sources: ConfigSource[], section: 'group' | 'routing'): ConfigSource | null {
|
||||
let owner: ConfigSource | null = null;
|
||||
let fallback: ConfigSource | null = null;
|
||||
for (const source of sources) {
|
||||
if (source.kind !== 'main' && source.kind !== 'include') continue;
|
||||
if (!readable(source.content)) return null;
|
||||
const writable = source.kind === 'include' && source.writable;
|
||||
// cmd/config_groups.go:24,103-115 uses group.dae when no module declares the group.
|
||||
if (section === 'group' && writable && source.path === 'config.d/group.dae') fallback = source;
|
||||
for (const block of scanConfig(source.content).blocks) {
|
||||
if (block.name !== section) continue;
|
||||
if (owner || !writable) return null;
|
||||
owner = source;
|
||||
}
|
||||
}
|
||||
return owner ?? fallback;
|
||||
}
|
||||
|
||||
export const dae: Engine = {
|
||||
id: 'dae',
|
||||
// component/nativeapi/handlers_probes.go:78-89: dae opens a fresh connection for each probe.
|
||||
warmProbes: false,
|
||||
// cmd/config_nodes.go:27,37-46,768-772: DELETE only edits node.dae.
|
||||
nodeModule: 'config.d/node.dae',
|
||||
reason(subject, {resources, unreported}): EngineReason | undefined {
|
||||
const config = resources.config as typeof resources.config & {'x-dae'?: {layout?: {reason?: string}}};
|
||||
switch (subject) {
|
||||
case 'config':
|
||||
case 'mode':
|
||||
case 'rule_edit':
|
||||
case 'group_edit': {
|
||||
if (!config.available || config.writable !== false) return undefined;
|
||||
const reason = config['x-dae']?.layout?.reason;
|
||||
const message = readOnlyNote(reason);
|
||||
return message
|
||||
? {code: 'source-read-only', message, settings: reason === 'writes_disabled' ? [{key: 'api.config_write', value: 'true'}] : []}
|
||||
: undefined;
|
||||
}
|
||||
// component/nativeapi/handlers.go:117-126,243-248,330-333. Prefer a newer server's positive capability.
|
||||
case 'create':
|
||||
return config.available && config.create === false ? {code: 'no-switch'} : undefined;
|
||||
case 'geodata':
|
||||
case 'geodata_settings':
|
||||
return resources.geodata.available && resources.geodata.can_update === false ? {code: 'no-switch'} : undefined;
|
||||
case 'trace_live':
|
||||
return resources.routing_trace.resolve_modes?.includes('live') === false ? {code: 'no-switch'} : undefined;
|
||||
case 'runtime_settings':
|
||||
return unreported?.includes(subject) ? {code: 'build-lacks'} : undefined;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
sourceReadOnlyNote: source => readOnlyNote(source.read_only_reason),
|
||||
// cmd/config_editor.go:743-749,776-788: even an api block without a secret belongs to the hidden listener file.
|
||||
holdsCredentials: source => scanConfig(source.content).blocks.some(block => block.name === 'api'),
|
||||
snippet: settingsSnippet,
|
||||
redactedSections: blocks => blocks.filter(block => block.name === 'api').map(block => ({block, name: 'api'})),
|
||||
daeText: false,
|
||||
groupSource: sources => daeSectionTarget(sources, 'group'),
|
||||
routing: {
|
||||
readable,
|
||||
templates: 'routing-only',
|
||||
readOnlyNote: 'config.daeRoutingReadOnly',
|
||||
modeSource: sources => daeSectionTarget(sources, 'routing') ?? undefined,
|
||||
// config/patch.go:71-95 reserves must_ for mandatory routing.
|
||||
acceptsTarget: name => !name.startsWith('must_'),
|
||||
writeMode: (text, next) => writeMode(text, next, true)
|
||||
},
|
||||
// cmd/config_nodes.go:69-102 constructs the dialer; component/outbound/outbound.go:9-32 imports the registrations
|
||||
// from the outbound revision pinned in go.mod:136. socks4/4a are commented out and naive+quic refuses construction.
|
||||
nodeLinkSchemes: [
|
||||
'http',
|
||||
'https',
|
||||
'socks',
|
||||
'socks5',
|
||||
'ss',
|
||||
'shadowsocks',
|
||||
'ssr',
|
||||
'vmess',
|
||||
'vless',
|
||||
'trojan',
|
||||
'trojan-go',
|
||||
'tuic',
|
||||
'juicity',
|
||||
'hysteria2',
|
||||
'hy2',
|
||||
'anytls',
|
||||
'naive+https',
|
||||
'shadowtls',
|
||||
'shadow-tls',
|
||||
'simpleobfs',
|
||||
'tls',
|
||||
'utls',
|
||||
'ws',
|
||||
'wss'
|
||||
],
|
||||
// example.dae:76,87 uses quoted aggregate lists; common/utils.go:133 uses time.ParseDuration. The form supports neither grammar.
|
||||
globalSettings: null,
|
||||
restartOnly: [],
|
||||
restartCommand: 'systemctl restart dae.service',
|
||||
flowDemandGraceSeconds: null,
|
||||
uncheckedHooks: []
|
||||
};
|
||||
+8
-22
@@ -1,8 +1,11 @@
|
||||
import {writeMode} from '../../dae/outboundMode';
|
||||
import {honkProbes} from '../../dae/probes';
|
||||
import {settingsSnippet} from './snippet';
|
||||
import {honkGlobal, honkRestartOnly} from './honkSettings';
|
||||
import {blockFields, scanConfig} from '../../dae/text';
|
||||
import {honkConfig} from './honkConfig';
|
||||
import type {Capabilities, RuntimeSettings} from '../model';
|
||||
import type {Engine, EngineReason, EngineSetting, EngineSubject} from './types';
|
||||
import type {Engine, EngineReason, EngineSubject} from './types';
|
||||
|
||||
// honk's recorders, each available unless its record_* setting is false; every one defaults to true
|
||||
// (honk experimental.rs NativeApiConfig::default).
|
||||
@@ -136,25 +139,12 @@ function holdsListenerSecret(text: string): boolean {
|
||||
)
|
||||
);
|
||||
}
|
||||
// Writes dotted setting names as nested sections; consecutive settings in one section share it.
|
||||
function nest(settings: Array<{path: string[]; value: string}>, indent: string): string[] {
|
||||
const lines: string[] = [];
|
||||
for (let i = 0; i < settings.length;) {
|
||||
const [head, ...rest] = settings[i].path;
|
||||
if (!rest.length) {
|
||||
lines.push(`${indent}${head}: ${settings[i++].value}`);
|
||||
continue;
|
||||
}
|
||||
const inner: typeof settings = [];
|
||||
for (; i < settings.length && settings[i].path.length > 1 && settings[i].path[0] === head; i++)
|
||||
inner.push({...settings[i], path: settings[i].path.slice(1)});
|
||||
lines.push(`${indent}${head} {`, ...nest(inner, `${indent} `), `${indent}}`);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
export const honk: Engine = {
|
||||
id: 'honk',
|
||||
...honkProbes,
|
||||
nodeModule: null,
|
||||
routing: {modeSource: sources => sources.find(source => source.kind === 'main'), writeMode, templates: 'whole-file'},
|
||||
nodeLinkSchemes: ['socks5', 'socks4', 'socks4a', 'ss', 'trojan', 'anytls', 'vmess', 'vless', 'hysteria2', 'hysteria', 'hy2', 'tuic', 'juicity'],
|
||||
flowDemandGraceSeconds: 60,
|
||||
globalSettings: honkGlobal,
|
||||
@@ -165,11 +155,7 @@ export const honk: Engine = {
|
||||
// Reading these back takes a BPF_PROG_QUERY per hook, or a switch into the daens namespace for dae0peer.
|
||||
uncheckedHooks: ['cgroup', 'sk_lookup', 'dae0peer'],
|
||||
holdsCredentials: source => holdsListenerSecret(source.content),
|
||||
snippet: (settings: EngineSetting[]) =>
|
||||
nest(
|
||||
settings.map(({key, value}) => ({path: key.split('.'), value})),
|
||||
''
|
||||
).join('\n'),
|
||||
snippet: settingsSnippet,
|
||||
// honk redacts the native API token when it returns a source, so `experimental { native_api { } }` is not the file's text.
|
||||
redactedSections: blocks =>
|
||||
blocks
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import {daeSectionTarget} from './dae';
|
||||
|
||||
import {describe, expect, it} from 'vitest';
|
||||
import {normalizeCapabilities} from '../capabilities';
|
||||
import {capabilities, version} from '../../../mock/fixtures';
|
||||
import type {Capabilities, ReportedCapabilities} from '../model';
|
||||
import type {Capabilities, ConfigSource, ReportedCapabilities} from '../model';
|
||||
import {scanConfig} from '../../dae/text';
|
||||
import {configManagement, configOf, engineOf, type EngineSubject} from '.';
|
||||
|
||||
@@ -43,6 +45,77 @@ describe('engineOf', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('dae', () => {
|
||||
const engine = engineOf({engine: {name: 'dae', version: 'test'}});
|
||||
const source = (kind: 'include' | 'main', content: string): ConfigSource => ({
|
||||
kind,
|
||||
id: kind,
|
||||
path: kind === 'main' ? 'config.dae' : 'config.d/policy.dae',
|
||||
writable: kind === 'include',
|
||||
content,
|
||||
content_sha256: '',
|
||||
bytes: content.length,
|
||||
line_count: content.split('\n').length,
|
||||
loaded_at: ''
|
||||
});
|
||||
|
||||
it('uses the default group module only in the absence of a section owner', () => {
|
||||
const fallback = {...source('include', ''), path: 'config.d/group.dae'};
|
||||
const owner = source('include', 'group {}');
|
||||
expect(daeSectionTarget([], 'group')).toBeNull();
|
||||
expect(daeSectionTarget([fallback], 'group')).toBe(fallback);
|
||||
expect(daeSectionTarget([{...fallback, writable: false}], 'group')).toBeNull();
|
||||
expect(daeSectionTarget([fallback, owner], 'group')).toBe(owner);
|
||||
expect(daeSectionTarget([fallback, {...owner, writable: false}], 'group')).toBeNull();
|
||||
expect(daeSectionTarget([fallback, owner, owner], 'group')).toBeNull();
|
||||
expect(daeSectionTarget([fallback, source('include', '/* group {} */')], 'group')).toBeNull();
|
||||
});
|
||||
|
||||
it('uses the top-level api section rather than honk listener settings', () => {
|
||||
expect(engine.id).toBe('dae');
|
||||
const content = "api { listen: '127.0.0.1:9527'\n secret: '<redacted>' }";
|
||||
expect(engine.holdsCredentials({content})).toBe(true);
|
||||
expect(engine.redactedSections(scanConfig(content).blocks).map(section => section.name)).toEqual(['api']);
|
||||
expect(engine.holdsCredentials({content: "# api {\nnode { example: 'socks5://localhost:1080' }"})).toBe(false);
|
||||
expect(engine.snippet([{key: 'api.config_write', value: 'true'}])).toBe('api {\n config_write: true\n}');
|
||||
expect(engine.globalSettings).toBeNull(); // example.dae:76,87: the form cannot round-trip quoted comma lists.
|
||||
expect(engine.nodeLinkSchemes).toEqual(expect.arrayContaining(['http', 'ssr', 'shadowtls', 'socks5', 'naive+https']));
|
||||
expect(engine.nodeLinkSchemes).not.toContain('socks4');
|
||||
});
|
||||
|
||||
it('distinguishes the reported layout and write switch without guessing from writable alone', () => {
|
||||
const readOnly = (reason?: string) => {
|
||||
const config = {writable: false, 'x-dae': {layout: {reason}}};
|
||||
return patched({config});
|
||||
};
|
||||
expect(engine.reason('config', readOnly('writes_disabled'))).toMatchObject({settings: [{key: 'api.config_write', value: 'true'}]});
|
||||
expect(engine.reason('mode', readOnly('layout_unmanaged'))).toMatchObject({message: 'config.daeLayout', settings: []});
|
||||
expect(engine.reason('config', readOnly())).toBeUndefined();
|
||||
expect(engine.reason('create', patched({config: {create: false}}))).toEqual({code: 'no-switch'});
|
||||
expect(engine.reason('create', patched({config: {create: true}}))).toBeUndefined();
|
||||
expect(engine.reason('flows', capabilities)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('edits only the routing owner and preserves dae mandatory outbounds and other modules', () => {
|
||||
const entry = source('main', 'include { config.d/*.dae api.dae }');
|
||||
const dns = source('include', 'dns { routing { request { fallback: asis } } }');
|
||||
const content =
|
||||
'routing {\n pname(mosdns) -> must_rules\n pname(naiveproxy) -> must_direct\n dip(geoip:private) -> direct(mark: 0x800, must)\n fallback: my_group\n}';
|
||||
const route = source('include', content);
|
||||
const routing = engine.routing!;
|
||||
expect(routing.modeSource([entry, dns, route])).toBe(route);
|
||||
expect(routing.modeSource([entry, dns])).toBeUndefined();
|
||||
expect(routing.modeSource([{...route, writable: false}])).toBeUndefined();
|
||||
expect(routing.modeSource([{...route, kind: 'main'}])).toBeUndefined();
|
||||
expect(routing.modeSource([entry, route, source('include', 'routing { fallback: direct }')])).toBeUndefined();
|
||||
expect(routing.modeSource([source('include', '/* routing { fallback: direct } */\n' + content)])).toBeUndefined();
|
||||
const global = routing.writeMode(content, {mode: 'global', target: 'my_group'});
|
||||
expect(global).toContain('direct(mark: 0x800, must)\n l4proto(tcp, udp) -> my_group # doona: outbound mode\n fallback: my_group');
|
||||
expect(routing.writeMode(global, {mode: 'rule'})).toBe(content);
|
||||
expect(() => routing.writeMode('routing {\n dport(80) -> direct\n pname(mosdns) -> must_rules\n}', {mode: 'direct'})).toThrow('act.modeInterleaved');
|
||||
});
|
||||
});
|
||||
|
||||
describe('honk', () => {
|
||||
it('names the recorder setting for each recorder that is off', () => {
|
||||
const off = patched({traffic_history: {available: false}, memory_history: {available: false}, logs: {available: false}, dns_log: {available: false}});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {Version} from '../model';
|
||||
import {dae} from './dae';
|
||||
import {honk} from './honk';
|
||||
import type {Engine} from './types';
|
||||
|
||||
@@ -7,6 +8,9 @@ export type {Engine, EngineAction, EngineConfig, EngineReason, EngineSubject} fr
|
||||
// An engine doona has no knowledge of: the contract's own facts are all the page can give.
|
||||
const unknown: Engine = {
|
||||
id: 'unknown',
|
||||
warmProbes: true,
|
||||
nodeModule: null,
|
||||
routing: null,
|
||||
reason: () => undefined,
|
||||
holdsCredentials: () => false,
|
||||
snippet: settings => settings.map(({key, value}) => `${key}: ${value}`).join('\n'),
|
||||
@@ -23,6 +27,8 @@ const unknown: Engine = {
|
||||
// The engine behind the native API, by the engine name its version reports; unknown until the version has loaded.
|
||||
export function engineOf(version: Pick<Version, 'engine'> | undefined): Engine {
|
||||
switch (version?.engine.name) {
|
||||
case 'dae':
|
||||
return dae;
|
||||
case 'honk':
|
||||
return honk;
|
||||
default:
|
||||
@@ -31,3 +37,4 @@ export function engineOf(version: Pick<Version, 'engine'> | undefined): Engine {
|
||||
}
|
||||
|
||||
export {configManagement, configOf} from './config';
|
||||
export {engineWords} from './wording';
|
||||
@@ -0,0 +1,24 @@
|
||||
import type {EngineSetting} from './types';
|
||||
|
||||
// Writes dotted setting names as nested sections; consecutive settings in one section share it.
|
||||
function nest(settings: Array<{path: string[]; value: string}>, indent: string): string[] {
|
||||
const lines: string[] = [];
|
||||
for (let i = 0; i < settings.length;) {
|
||||
const [head, ...rest] = settings[i].path;
|
||||
if (!rest.length) {
|
||||
lines.push(`${indent}${head}: ${settings[i++].value}`);
|
||||
continue;
|
||||
}
|
||||
const inner: typeof settings = [];
|
||||
for (; i < settings.length && settings[i].path.length > 1 && settings[i].path[0] === head; i++)
|
||||
inner.push({...settings[i], path: settings[i].path.slice(1)});
|
||||
lines.push(`${indent}${head} {`, ...nest(inner, `${indent} `), `${indent}}`);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
export const settingsSnippet = (settings: EngineSetting[]) =>
|
||||
nest(
|
||||
settings.map(({key, value}) => ({path: key.split('.'), value})),
|
||||
''
|
||||
).join('\n');
|
||||
@@ -1,3 +1,6 @@
|
||||
import type {writeMode} from '../../dae/outboundMode';
|
||||
import type {ProbePolicy} from '../../dae/probes';
|
||||
import type {Key} from '../../i18n';
|
||||
import type {SettingsSection} from '../../dae/settings';
|
||||
import type {TextBlock} from '../../dae/text';
|
||||
import type {Capabilities, ConfigRevisionList, ConfigSource, EffectiveConfig, OperationAccepted, RuntimeSettings} from '../model';
|
||||
@@ -62,6 +65,7 @@ export type EngineReason =
|
||||
| {code: 'state-db-closed'; writeSwitch: string}
|
||||
// No setting turns the feature on.
|
||||
| {code: 'no-switch'}
|
||||
| {code: 'source-read-only'; message: Key; settings: EngineSetting[]}
|
||||
// The running build does not have the feature.
|
||||
| {code: 'build-lacks'};
|
||||
|
||||
@@ -102,8 +106,18 @@ export type EngineConfig = {
|
||||
|
||||
// An engine's explanations for what the native API contract states without a reason. An engine that does not know a
|
||||
// reason says nothing, so the page falls back to what the contract says.
|
||||
export type Engine = {
|
||||
id: 'honk' | 'unknown';
|
||||
export type Engine = ProbePolicy & {
|
||||
id: 'dae' | 'honk' | 'unknown';
|
||||
groupSource?(sources: ConfigSource[]): ConfigSource | null;
|
||||
routing: {
|
||||
modeSource(sources: ConfigSource[]): ConfigSource | undefined;
|
||||
acceptsTarget?(name: string): boolean;
|
||||
writeMode: typeof writeMode;
|
||||
templates: 'whole-file' | 'routing-only';
|
||||
readable?(text: string): boolean;
|
||||
readOnlyNote?: Key;
|
||||
} | null;
|
||||
sourceReadOnlyNote?(source: ConfigSource): Key | undefined;
|
||||
// Seconds the engine keeps recording flow demand after the last client read or stream; null when it does not say.
|
||||
flowDemandGraceSeconds: number | null;
|
||||
// Why `subject` is off, given that the capabilities show it is; undefined when the engine does not say.
|
||||
@@ -117,6 +131,8 @@ export type Engine = {
|
||||
// Whether the configuration text is dae's, which doona reads and writes; a page that infers settings from the text
|
||||
// or edits it by hand checks this first.
|
||||
daeText: boolean;
|
||||
// The module addressed by node DELETE, or null for main-source deletion.
|
||||
nodeModule: string | null;
|
||||
nodeLinkSchemes: readonly string[] | null;
|
||||
globalSettings: SettingsSection | null;
|
||||
// The global settings the engine applies only when it restarts, so a write that changes them is refused.
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import type {Rewording} from '../../i18n';
|
||||
|
||||
// These recovery steps are specific to honk even when another engine sends the same refusal code.
|
||||
const honkWords: Rewording = {
|
||||
'config.readOnlyHelp': 'config.readOnlyHelpHonk',
|
||||
'ui.refusal.listenerSecretInContent': 'ui.refusal.listenerSecretInContentHonk',
|
||||
'ui.refusal.writesDisabled': 'ui.refusal.writesDisabledHonk'
|
||||
};
|
||||
|
||||
export function engineWords(backendName: string | undefined): Rewording | undefined {
|
||||
return backendName === 'honk' ? honkWords : undefined;
|
||||
}
|
||||
@@ -150,7 +150,9 @@ it('carries reason and other details from an HTTP error into the recovery text',
|
||||
)
|
||||
);
|
||||
expect(error.details).toEqual({reason: 'credential_sources_changed', stage: 'write'});
|
||||
expect(errorText(error, (key, params) => translate('en', key, params), false)).toBe('The sources declaring API secrets have changed. Reload honk and retry.');
|
||||
expect(errorText(error, (key, params) => translate('en', key, params, undefined, undefined, 'honk'), false)).toBe(
|
||||
'The sources declaring API secrets have changed. Reload honk and retry.'
|
||||
);
|
||||
});
|
||||
|
||||
it('finds the request id on a failure or on the failure that stopped a partial one', () => {
|
||||
@@ -164,7 +166,7 @@ it('finds the request id on a failure or on the failure that stopped a partial o
|
||||
it('shows refusal recovery directly for a failed operation', () => {
|
||||
const t = (key: Parameters<typeof translate>[1], params?: Parameters<typeof translate>[2]) => translate('en', key, params);
|
||||
const error = new LocalError('ui.operationFailed', 'Refused', 'permission_denied', {reason: 'credential_sources_changed'});
|
||||
expect(errorText(error, t)).toBe('The sources declaring API secrets have changed. Reload honk and retry.');
|
||||
expect(errorText(error, t)).toBe('The sources declaring API secrets have changed. Reload the backend and retry.');
|
||||
});
|
||||
|
||||
it('reads Retry-After as a positive number of seconds and as null otherwise', () => {
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
ruleCondition,
|
||||
dnsConditionKinds,
|
||||
writeGroupEntry,
|
||||
writeDaeGroupEntry,
|
||||
nameText,
|
||||
nestedIn
|
||||
} from './groups';
|
||||
@@ -421,3 +422,41 @@ it.each([
|
||||
const renamed = removeSubtagsFromGroup(addSubtagsToGroup(source, 'g', ['new']), 'g', ['old']);
|
||||
expect(readGroupEntries(renamed)[0].filters).toEqual(expected);
|
||||
});
|
||||
|
||||
it('changes dae membership and policy without rewriting checks or adding honk settings', () => {
|
||||
const checks =
|
||||
" tcp_check_url: 'https://example.org,1.1.1.1'\n tcp_check_http_method: HEAD\n udp_check_dns: 'dns.google:53,8.8.8.8'\n check_interval: 2m\n check_tolerance: 55ms";
|
||||
const source = `group {\n work {\n filter: name(one) [add_latency: -5ms]\n policy: random\n${checks}\n }\n}`;
|
||||
const update = {
|
||||
policy: 'select(2)',
|
||||
filters: ['name(one) [add_latency: -5ms]', "subtag(regex: '(?=hk)hk')"],
|
||||
default: 'one',
|
||||
final: 'direct',
|
||||
exit: 'two',
|
||||
interrupt: 'true'
|
||||
};
|
||||
expect(writeDaeGroupEntry(source, 'work', update)).toBe(source.replace(' policy: random', ` filter: ${update.filters[1]}\n policy: select(2)`));
|
||||
});
|
||||
|
||||
it('inserts a dae filter after the complete conjunction', () => {
|
||||
const source = 'group {\n g {\n filter: name(edge)\n && subtag(work)\n policy: random\n }\n}';
|
||||
const {filters} = readGroupEntries(source)[0];
|
||||
expect(filters).toEqual(['name(edge) && subtag(work)']);
|
||||
expect(writeDaeGroupEntry(source, 'g', {filters: [...filters, 'name(backup)'], policy: 'random'})).toBe(
|
||||
source.replace(' policy:', ' filter: name(backup)\n policy:')
|
||||
);
|
||||
});
|
||||
|
||||
it('edits a dae latency annotation without changing its condition', () => {
|
||||
const source = 'group {\n g {\n filter: name(edge) [add_latency: -5ms]\n policy: random\n }\n}';
|
||||
const edit = (param: string) => writeDaeGroupEntry(source, 'g', {policy: 'random', filters: [`name(edge) [${param}]`]});
|
||||
expect(edit('add_latency: -10ms')).toBe(source.replace('-5ms', '-10ms'));
|
||||
for (const param of ['other: -10ms', 'add_latency: -10']) expect(() => edit(param)).toThrow('policy.editUnsafe');
|
||||
});
|
||||
|
||||
it.each(['group(child)', 'subtag(keyword: HK)'])('refuses unsupported dae filter %s', filter => {
|
||||
expect(() => writeDaeGroupEntry('group {}', 'work', {policy: 'random', filters: [filter]})).toThrow('policy.editUnsafe');
|
||||
});
|
||||
it.each(['score', 'fixed', 'fixed()', 'fixed(abc)', 'select(1, 2)'])('refuses invalid dae policy %s', policy => {
|
||||
expect(() => writeDaeGroupEntry('group {}', 'work', {policy, filters: []})).toThrow('policy.editUnsafe');
|
||||
});
|
||||
+45
-2
@@ -1,4 +1,7 @@
|
||||
import {blockFields, isBareName, isFragment, isQuotable, quote, scanConfig, unquote, type TextBlock, type TextField, type TextToken} from './text';
|
||||
import {LocalError} from '../api/error';
|
||||
import {daeConditionKind, daePolicyValid} from './vocab';
|
||||
import {parseGroupConditions} from './groupConditions';
|
||||
|
||||
export type GroupEntry = {
|
||||
name: string;
|
||||
@@ -15,13 +18,28 @@ export type GroupEntry = {
|
||||
to: number;
|
||||
};
|
||||
|
||||
// In dae a filter owns its bracketed latency annotation (example.dae:348-351). Its colon is not another group field.
|
||||
function groupFields(text: string, block: TextBlock, tokens: TextToken[]) {
|
||||
const fields = blockFields(text, block, tokens);
|
||||
for (let i = fields.length - 1; i > 0; i--) {
|
||||
const filter = fields[i - 1];
|
||||
const annotation = fields[i];
|
||||
if (filter.name !== 'filter' || !(annotation.name.startsWith('[') || filter.value.endsWith('['))) continue;
|
||||
filter.valueTo = filter.to = annotation.to;
|
||||
filter.value = text.slice(filter.valueFrom, filter.valueTo).trim();
|
||||
fields.splice(i, 1);
|
||||
}
|
||||
for (const field of fields) if (field.name === 'filter') field.value = field.value.replace(/[ \t]*\r?\n\s*(?=&&)/g, ' ');
|
||||
return fields;
|
||||
}
|
||||
|
||||
export function readGroupEntries(text: string): GroupEntry[] {
|
||||
const {blocks, tokens} = scanConfig(text);
|
||||
return blocks
|
||||
.filter(block => block.name === 'group')
|
||||
.flatMap(block =>
|
||||
block.children.map(entry => {
|
||||
const fields = blockFields(text, entry, tokens);
|
||||
const fields = groupFields(text, entry, tokens);
|
||||
const head = tokens.find(token => token.from === entry.from);
|
||||
const last = (name: string) => fields.filter(field => field.name === name).at(-1)?.value ?? null;
|
||||
return {
|
||||
@@ -57,6 +75,31 @@ export type GroupEntryUpdate = {
|
||||
exit?: string | null;
|
||||
interrupt?: string | null;
|
||||
};
|
||||
// component/outbound/dialer/annotation.go:23-37 accepts only add_latency with a Go time.Duration.
|
||||
const duration = /^[+-]?(?:0|(?:(?:\d+(?:\.\d*)?|\.\d+)(?:ns|us|µs|μs|ms|s|m|h))+)$/;
|
||||
const validLatency = (param: string) => {
|
||||
const match = /^\s*add_latency\s*:\s*(?:'([^']*)'|"([^"]*)"|([\w.+-]+))\s*$/.exec(param);
|
||||
return !!match && duration.test(match[1] ?? match[2] ?? match[3]);
|
||||
};
|
||||
|
||||
// dae config/config.go:108-120: leave check settings and annotations in place. Only policy and filters are editable.
|
||||
export function writeDaeGroupEntry(text: string, name: string, {filters, policy}: GroupEntryUpdate): string {
|
||||
const current = readGroupEntries(text).find(entry => entry.name === name);
|
||||
if ((!current || policy !== current.policy) && !daePolicyValid(policy)) throw new LocalError('policy.editUnsafe');
|
||||
for (const filter of filters) {
|
||||
if (current?.filters.includes(filter)) continue;
|
||||
const end = filter.lastIndexOf(')') + 1;
|
||||
const annotation = filter.slice(end).trim();
|
||||
if (annotation && !(annotation.startsWith('[') && annotation.endsWith(']') && annotation.slice(1, -1).split(',').every(validLatency)))
|
||||
throw new LocalError('policy.editUnsafe');
|
||||
const rows = parseGroupConditions(filter.slice(0, end));
|
||||
if (!rows?.every(row => [row, ...(row.alternatives ?? [])].every(term => daeConditionKind(term.kind)))) {
|
||||
throw new LocalError('policy.editUnsafe');
|
||||
}
|
||||
}
|
||||
return writeGroupEntry(text, name, {filters, policy});
|
||||
}
|
||||
|
||||
export function writeGroupEntry(text: string, name: string, next: GroupEntryUpdate): string {
|
||||
const {blocks, tokens} = scanConfig(text);
|
||||
const sections = blocks.filter(block => block.name === 'group');
|
||||
@@ -78,7 +121,7 @@ export function writeGroupEntry(text: string, name: string, next: GroupEntryUpda
|
||||
const lineStart = text.lastIndexOf('\n', entry.from - 1) + 1;
|
||||
const prefix = text.slice(lineStart, entry.from);
|
||||
const indent = /^\s*$/.test(prefix) ? prefix : ' ';
|
||||
const fields = blockFields(text, entry, tokens);
|
||||
const fields = groupFields(text, entry, tokens);
|
||||
const bodyStart = entry.open + 1;
|
||||
const old = text.slice(bodyStart, entry.close);
|
||||
const inner = old.match(/\n([ \t]+)\S/)?.[1] ?? indent + (indent || ' ');
|
||||
|
||||
+24
-19
@@ -1,5 +1,5 @@
|
||||
import {LocalError} from '../api/error';
|
||||
import {scanConfig, type TextBlock, type TextToken} from './text';
|
||||
import {scanConfig, unquote, type TextBlock, type TextToken} from './text';
|
||||
|
||||
// The marker lets mode changes remove their catch-all without touching authored rules.
|
||||
export type OutboundMode = {mode: 'rule'} | {mode: 'direct'} | {mode: 'global'; target: string};
|
||||
@@ -31,11 +31,12 @@ export function readMode(text: string): OutboundMode {
|
||||
return found ? (found.target === 'direct' ? {mode: 'direct'} : {mode: 'global', target: found.target}) : {mode: 'rule'};
|
||||
}
|
||||
|
||||
export function writeMode(text: string, next: OutboundMode): string {
|
||||
export function writeMode(text: string, next: OutboundMode, extendedMust = false): string {
|
||||
const scanned = scanConfig(text);
|
||||
for (const range of modeRanges(text, scanned.blocks, scanned.tokens).reverse()) text = text.slice(0, range.from) + text.slice(range.to);
|
||||
if (next.mode === 'rule') return text;
|
||||
const {blocks, tokens} = scanConfig(text);
|
||||
const ruleTokens = extendedMust ? tokens.filter(token => token.kind !== 'comment') : tokens;
|
||||
const block = blocks.find(block => block.name === 'routing');
|
||||
if (!block) throw new LocalError('act.modeNoRouting');
|
||||
const body = text.slice(block.open + 1, block.close);
|
||||
@@ -49,29 +50,33 @@ export function writeMode(text: string, next: OutboundMode): string {
|
||||
return text.slice(text.lastIndexOf('\n', at - 1) + 1, end === -1 ? undefined : end).trim();
|
||||
};
|
||||
// Mandatory rules must form a prefix or the catch-all cannot preserve their precedence.
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
const arrow = tokens[i];
|
||||
for (let i = 0; i < ruleTokens.length; i++) {
|
||||
const arrow = ruleTokens[i];
|
||||
if (arrow.from <= block.open || arrow.to > block.close || arrow.depth !== 1 || arrow.parens !== 0 || text.slice(arrow.from, arrow.to) !== '->') continue;
|
||||
const target = tokens[i + 1],
|
||||
open = tokens[i + 2],
|
||||
modifier = tokens[i + 3],
|
||||
close = tokens[i + 4];
|
||||
const mandatory =
|
||||
target &&
|
||||
open &&
|
||||
modifier &&
|
||||
close &&
|
||||
text.slice(open.from, open.to) === '(' &&
|
||||
text.slice(modifier.from, modifier.to) === 'must' &&
|
||||
text.slice(close.from, close.to) === ')';
|
||||
const raw = (index: number) => (ruleTokens[index] ? text.slice(ruleTokens[index].from, ruleTokens[index].to) : '');
|
||||
let tail = i + 1;
|
||||
let mandatory = extendedMust && raw(tail).startsWith('must_');
|
||||
if (raw(i + 2) === '(') {
|
||||
if (extendedMust) {
|
||||
// dae accepts must as a bare argument alongside a mark, and must_<outbound> as a shorthand.
|
||||
for (tail = i + 3; tail < ruleTokens.length && ruleTokens[tail].parens > 0; tail++) {
|
||||
if (['(', ','].includes(raw(tail - 1)) && unquote(raw(tail)) === 'must' && [',', ')'].includes(raw(tail + 1))) mandatory = true;
|
||||
if (raw(tail) === ')') break;
|
||||
}
|
||||
} else if (raw(i + 3) === 'must' && raw(i + 4) === ')') {
|
||||
mandatory = true;
|
||||
tail = i + 4;
|
||||
}
|
||||
}
|
||||
if (!mandatory) {
|
||||
ordinary ??= lineOf(arrow.from);
|
||||
continue;
|
||||
}
|
||||
if (ordinary !== null) throw new LocalError('act.modeInterleaved', ordinary);
|
||||
const end = text.indexOf('\n', close.to);
|
||||
at = end !== -1 && end < block.close ? end + 1 : close.to;
|
||||
const following = tokens[i + 5];
|
||||
const endOfTarget = ruleTokens[tail].to;
|
||||
const end = text.indexOf('\n', endOfTarget);
|
||||
at = end !== -1 && end < block.close ? end + 1 : endOfTarget;
|
||||
const following = ruleTokens[tail + 1];
|
||||
if (following && following.from < at && following.kind !== 'comment') throw new LocalError('act.modeInterleaved', lineOf(following.from));
|
||||
}
|
||||
const outbound = next.mode === 'direct' ? 'direct' : next.target;
|
||||
|
||||
@@ -29,3 +29,6 @@ export function supportsNodeProbe(protocol: string | null, kind: ProbeRequest['k
|
||||
? support.connect && transports.every(transport => transport === 'tcp')
|
||||
: support.stream && transports.every(transport => transport === 'tcp' || (kind === 'dns' && support.udp !== false));
|
||||
}
|
||||
|
||||
export type ProbePolicy = {warmProbes: boolean; supportsNodeProbe?: typeof supportsNodeProbe};
|
||||
export const honkProbes: ProbePolicy = {warmProbes: true, supportsNodeProbe};
|
||||
+3
-1
@@ -134,7 +134,9 @@ 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.parens === 0 && (token.kind === 'comment' || (field && text.slice(field.valueTo, token.from).includes('\n')))) field = undefined;
|
||||
// A line that opens with && continues the filter above it (dae pkg/config_parser/walker.go:173-180).
|
||||
const continues = field?.name === 'filter' && raw.startsWith('&&');
|
||||
if (token.parens === 0 && (token.kind === 'comment' || (field && !continues && 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];
|
||||
// Adjacent tokens and comma-separated items belong to the value, including address and URL colons.
|
||||
|
||||
+27
-7
@@ -1,4 +1,5 @@
|
||||
import type {Group} from '../api/model';
|
||||
import type {Engine} from '../api/engines';
|
||||
import type {Key} from '../i18n';
|
||||
|
||||
// The dae configuration vocabulary the engine accepts, as honk's parser spells it (crates/honk-config/src/parser):
|
||||
@@ -43,7 +44,7 @@ export const globalKeys = [
|
||||
// Which contract kind a native policy expression behaves as, read as honk reads it: the name before `(`, trimmed, in
|
||||
// ASCII lower case. Legacy min/random use its selector fallback; other unknown names stay undefined.
|
||||
// honk rejects `honk` as the old name of `score`.
|
||||
const policyKinds: Record<string, Group['policy']['kind']> = {
|
||||
const honkPolicyKinds: Record<string, Group['policy']['kind']> = {
|
||||
select: 'selector',
|
||||
selector: 'selector',
|
||||
fixed: 'selector',
|
||||
@@ -60,12 +61,15 @@ const policyKinds: Record<string, Group['policy']['kind']> = {
|
||||
fallback: 'fallback',
|
||||
score: 'score'
|
||||
};
|
||||
export function policyKind(native: string): Group['policy']['kind'] | undefined {
|
||||
const base = native
|
||||
.split('(', 1)[0]
|
||||
.trim()
|
||||
.replace(/[A-Z]/g, letter => letter.toLowerCase());
|
||||
return Object.hasOwn(policyKinds, base) ? policyKinds[base] : undefined;
|
||||
|
||||
// dae cmd/nativeapi_groups.go:125-136 classifies all other policies as urltest.
|
||||
const daePolicyKinds: typeof honkPolicyKinds = {select: 'selector', fixed: 'fixed', random: 'random'};
|
||||
export function policyKind(native: string, engine: Engine['id'] = 'honk'): Group['policy']['kind'] | undefined {
|
||||
const {dialect, policyKinds, fallbackKind} = groupGrammar[engine];
|
||||
const args = native.indexOf('(');
|
||||
const name = (args === -1 ? native : native.slice(0, args)).trim();
|
||||
const base = dialect === 'dae' ? name : name.replace(/[A-Z]/g, letter => letter.toLowerCase());
|
||||
return Object.hasOwn(policyKinds, base) ? policyKinds[base] : fallbackKind;
|
||||
}
|
||||
// Written out rather than read from policyKinds, so completion keeps to the spellings dae shares. dae's `random` is
|
||||
// left out: honk reads it as an unknown policy and falls back to a selector.
|
||||
@@ -78,6 +82,22 @@ export const newGroupPolicies: Array<{id: string; label: Key; description: Key}>
|
||||
{id: 'roundrobin', label: 'policy.kind.loadbalance', description: 'group.policy.spreadHint'},
|
||||
{id: 'select', label: 'policy.kind.selector', description: 'group.policy.manualHint'}
|
||||
];
|
||||
// dae common/consts/dialer.go:25-38 and component/outbound/dialer_selection_policy.go:31-82.
|
||||
const daePolicies = ['min_moving_avg', 'min_avg10', 'min', 'random', 'fixed', 'select'];
|
||||
const honkGroupGrammar = {dialect: 'honk', policies: newGroupPolicies.map(item => item.id), policyKinds: honkPolicyKinds, fallbackKind: undefined} as const;
|
||||
export const groupGrammar = {
|
||||
dae: {dialect: 'dae', policies: daePolicies, policyKinds: daePolicyKinds, fallbackKind: 'urltest'},
|
||||
honk: honkGroupGrammar,
|
||||
unknown: honkGroupGrammar
|
||||
} as const;
|
||||
// dae component/outbound/filter.go:245-319: name accepts exact, keyword and regexp2; subtag accepts exact and regexp2.
|
||||
export const daeConditionKind = (kind: string) => kind !== 'group' && kind !== 'subtagKeyword';
|
||||
export const indexedPolicy = (policy: string | null) => /^(fixed|select)\s*\(\s*([^()]*)\s*\)$/.exec(policy ?? '');
|
||||
export function daePolicyValid(policy: string | null): boolean {
|
||||
const indexed = indexedPolicy(policy);
|
||||
if (indexed) return /^\d+$/.test(indexed[2].trim()) && Number.isSafeInteger(Number(indexed[2]));
|
||||
return policy !== null && policy !== 'fixed' && daePolicies.includes(policy);
|
||||
}
|
||||
// Built-in outbounds, as nodes, groups and rules name them; a rule may add `(must)`, which keeps DNS traffic from
|
||||
// being hijacked for that rule.
|
||||
export const builtinOutboundNames = ['direct', 'block'] as const;
|
||||
|
||||
@@ -150,6 +150,14 @@ it('stages global targets without changing the current mode and detects an uncha
|
||||
expect(staged.incomplete).toBe(false);
|
||||
});
|
||||
|
||||
it('excludes must_ groups from dae targets and its default choice only', () => {
|
||||
const groups = [{name: 'must_work'}, {name: 'work'}];
|
||||
const view = (name: string) =>
|
||||
modeView({mode: 'rule'}, null, groups, true, true, t, true, undefined, engineOf({engine: {...version.engine, name}}).routing?.acceptsTarget);
|
||||
expect(view('dae')).toMatchObject({target: 'work', targets: [{id: 'work', label: 'work'}]});
|
||||
expect(view('honk')).toMatchObject({target: 'must_work', targets: groups.map(({name}) => ({id: name, label: name}))});
|
||||
});
|
||||
|
||||
it('explains a read-only mode with the overview text when configuration writes are off', () => {
|
||||
const off = {...capabilities, resources: {...capabilities.resources, config: {...capabilities.resources.config, writable: false}}};
|
||||
const hint = limitHint('mode', off, version, t, 'en');
|
||||
|
||||
@@ -31,7 +31,7 @@ export function RestartNotice({settings, sources, command}: {settings: RestartSe
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
<span>{t('config.restart.next')}</span>
|
||||
<span>{t(command ? 'config.restart.nextWithCommand' : 'config.restart.next')}</span>
|
||||
{command && (
|
||||
<span className="rp-cluster">
|
||||
<code className="rp-code rp-limit-snippet">{command}</code>
|
||||
|
||||
@@ -95,7 +95,10 @@ export function useConfigPage({go, query}: PageProps) {
|
||||
const engine = useMemo(() => engineOf(version), [version]);
|
||||
const tabs = configTabs(!!engine.globalSettings, configOf(version), capabilities.data);
|
||||
const hint = capabilities.data && limitHint('config', capabilities.data, version, t, lang);
|
||||
const readOnly = source ? readOnlyBadge(source, configWritable, isComplete(source), engine, t, hint) : null;
|
||||
const sourceNote = source && !source.writable && engine.sourceReadOnlyNote?.(source);
|
||||
const readOnly = sourceNote
|
||||
? {reason: 'refused' as const, label: t('config.readOnly'), note: t(sourceNote)}
|
||||
: source && readOnlyBadge(source, configWritable, isComplete(source), engine, t, hint);
|
||||
const canWrite = !!source && !readOnly;
|
||||
// Each source keeps the person's last open or collapse of its diagnostics, and the card reports the errors it shows
|
||||
// for the tab, a draft's included; away from the card the tab counts the accepted configuration's.
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import {useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState} from 'react';
|
||||
import {useLang, useT} from '../../i18n';
|
||||
import {engineOf} from '../../api/engines';
|
||||
import {useVersion} from '../../store';
|
||||
import {useContentWidth} from '../../ui/ui';
|
||||
import {treeIndex, treeReach, type RoutingTree} from './map';
|
||||
import {TREE_STEP, treeGeometry, treeWindow} from './view';
|
||||
@@ -7,12 +9,13 @@ 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 engine = engineOf(useVersion().data).id;
|
||||
const [limit, setLimit] = useState(TREE_STEP);
|
||||
const [hovered, setHovered] = useState<string | null>(null);
|
||||
const [ref, measured] = useContentWidth<HTMLDivElement>();
|
||||
const index = useMemo(() => treeIndex(tree), [tree]);
|
||||
const shown = useMemo(() => treeWindow(tree, limit), [tree, limit]);
|
||||
const geometry = useMemo(() => treeGeometry(shown, measured, t, lang), [shown, measured, t, lang]);
|
||||
const geometry = useMemo(() => treeGeometry(shown, measured, t, lang, engine), [shown, measured, t, lang, engine]);
|
||||
// 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]);
|
||||
|
||||
@@ -92,6 +92,13 @@ it('names a policy by what it does, whatever the native spelling', async () => {
|
||||
expect(notes('')).toContainEqual({text: t('policy.kind.urltest')});
|
||||
});
|
||||
|
||||
it('labels a dae random group on the routing map without changing the honk spelling', async () => {
|
||||
const [group] = await createMockApi().groups();
|
||||
const tree = routingTree([], [{...group, policy: {kind: 'random', native: 'random'}}], [], undefined);
|
||||
expect(treeGeometry(tree, 720, t, 'en', 'dae').placed[0].view.notes).toContainEqual({text: t('policy.kind.random')});
|
||||
expect(treeGeometry(tree, 720, t, 'en', 'honk').placed[0].view.notes).toContainEqual({text: t('policy.kind.selector')});
|
||||
});
|
||||
|
||||
it('bounds each tree reveal while keeping layout, connector endpoints and branch reachability', async () => {
|
||||
const rules = await createMockApi().rules();
|
||||
const tree = routingTree([], [], [], {...rules, rules: Array.from({length: 4096}, (_, i) => ({...rules.rules[0], rule_id: String(i), outbound: 'direct'}))});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {isBuiltinOutbound} from '../../dae/vocab';
|
||||
import type {Capabilities, FlowDetail, FlowList, FlowStep, FlowSummary} from '../../api/model';
|
||||
import type {Engine} from '../../api/engines';
|
||||
import {enumLabel} from '../../i18n/enum';
|
||||
import type {Key} from '../../i18n';
|
||||
import {formatList, formatNumber, LOCALE, type Lang, type Translator} from '../../i18n';
|
||||
@@ -125,7 +126,7 @@ export type TileView = {
|
||||
countText: string;
|
||||
label: string;
|
||||
};
|
||||
export function tileViews(tree: RoutingTree, t: Translator, lang: Lang): TileView[] {
|
||||
export function tileViews(tree: RoutingTree, t: Translator, lang: Lang, engine: Engine['id'] = 'honk'): TileView[] {
|
||||
const unknown = (item: TreeItem, name: string) => (item.unknown ? t('ui.unknown') : name);
|
||||
type Bare = Omit<TileView, 'label' | 'countText'>;
|
||||
const tiles: Bare[] = [
|
||||
@@ -143,7 +144,7 @@ export function tileViews(tree: RoutingTree, t: Translator, lang: Lang): TileVie
|
||||
name: unknown(outbound, outboundLabel(outbound.label, t)),
|
||||
notes: [
|
||||
...outbound.groups.slice(1).map(group => ({text: '› ' + group.name})),
|
||||
...outbound.groups.slice(-1).map(group => ({text: groupPolicyText({kind: group.kind, native: group.policy}, t).label})),
|
||||
...outbound.groups.slice(-1).map(group => ({text: groupPolicyText({kind: group.kind, native: group.policy}, t, engine).label})),
|
||||
...(outbound.kind === 'group' && !outbound.node ? [{text: t('flow.treeNoNode')}] : [])
|
||||
],
|
||||
count: outbound.count
|
||||
@@ -320,7 +321,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, lang: Lang) {
|
||||
export function treeGeometry(tree: RoutingTree, measured: number | null, t: Translator, lang: Lang, engine: Engine['id'] = 'honk') {
|
||||
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) => {
|
||||
@@ -328,7 +329,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, lang).map(view => ({view, style: {top: layout.at.get(view.id)! * PITCH, ...column(view.stage)}}));
|
||||
const placed = tileViews(tree, t, lang, engine).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 [];
|
||||
|
||||
@@ -218,3 +218,10 @@ it.each(['group', 'protocol', 'nodeIds'] as const)('clears selection when the %s
|
||||
else overrides = {nodeIds: [nodes[1].id]};
|
||||
expect(read().selection.keys.size).toBe(0);
|
||||
});
|
||||
|
||||
it('offers new group when the group module is writable even with no writable main', () => {
|
||||
overrides = {source: {...input.source, writable: true, groupTarget: {id: 'module'} as NonNullable<typeof input.source.main>}};
|
||||
expect(read().canCreate).toBe(true);
|
||||
read().rows[0].join('/new');
|
||||
expect(input.onNewGroup).toHaveBeenCalledWith(nodes[0]);
|
||||
});
|
||||
@@ -103,8 +103,7 @@ export function useNodeTable(input: NodeTableInput) {
|
||||
[nodes, search, activeGroup, activeProtocol, sort, contains, locale]
|
||||
);
|
||||
const entries = useMemo(() => input.joinable.map(entry => ({...entry, names: new Set(namedIn(entry))})), [input.joinable]);
|
||||
// A new group is written to the main source.
|
||||
const canCreate = source.writable && !source.busy && !!source.main;
|
||||
const canCreate = source.writable && !source.busy && !!source.groupTarget;
|
||||
const inlineProviders = useMemo(() => new Set(providers.filter(provider => provider.kind === 'inline').map(provider => provider.id)), [providers]);
|
||||
const {probe: runProbe, choices, busy: probeBusy} = probe;
|
||||
// A row per node object, rebuilt only when the node or what every row reads changes. The running probe is not part
|
||||
|
||||
@@ -9,6 +9,8 @@ import {runSubscriptionAction, useNodesPage} from './useNodesPage';
|
||||
|
||||
const {capabilities, version} = await vi.hoisted(() => import('../../../mock/fixtures'));
|
||||
const store = vi.hoisted(() => ({
|
||||
capabilities,
|
||||
version,
|
||||
addNode: null as unknown as (input: unknown) => Promise<Node | null>,
|
||||
removeNode: vi.fn<(id: string) => Promise<unknown>>(),
|
||||
nodes: [] as Node[],
|
||||
@@ -30,7 +32,7 @@ vi.mock('react', async original => ({
|
||||
useLayoutEffect: () => undefined
|
||||
}));
|
||||
vi.mock('../../store', async () => ({
|
||||
useCapabilities: () => ({data: capabilities}),
|
||||
useCapabilities: () => ({data: store.capabilities}),
|
||||
useNodeManage: (reload: () => void) => ({
|
||||
addNode: (input: unknown) => store.addNode(input),
|
||||
removeNode: (id: string) =>
|
||||
@@ -45,7 +47,7 @@ vi.mock('../../store', async () => ({
|
||||
useProviders: () => ({data: {providers: store.providers}, refetch: store.refetchProviders, loading: false, error: null}),
|
||||
useOutboundNames: () => [],
|
||||
useProviderRefresh: () => ({refresh: vi.fn()}),
|
||||
useVersion: () => ({data: version}),
|
||||
useVersion: () => ({data: store.version}),
|
||||
readConfigFresh: () => Promise.resolve({sources: store.fresh})
|
||||
}));
|
||||
vi.mock('../../api/index', async original => ({...(await original<typeof import('../../api/index')>()), getApi: () => ({})}));
|
||||
@@ -103,6 +105,8 @@ it.each([true, false])('waits for source validation before consuming a subscript
|
||||
const read = () => hookHarness.render(() => useNodesPage({go: vi.fn(), query: ''}));
|
||||
beforeEach(() => {
|
||||
hookHarness.reset();
|
||||
store.capabilities = capabilities;
|
||||
store.version = version;
|
||||
store.nodes = [];
|
||||
store.providers = [];
|
||||
store.sources = [];
|
||||
@@ -113,6 +117,29 @@ beforeEach(() => {
|
||||
});
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
it.each([
|
||||
['inline', true, ['node'], true],
|
||||
['inline', true, ['other'], false],
|
||||
['inline', true, ['node', 'other'], false],
|
||||
['inline', true, [], false],
|
||||
['subscription', true, ['node'], false],
|
||||
['inline', false, ['node'], false]
|
||||
] as const)('gates dae deletion by provider %s, can_manage %s and modules %j', async (kind, canManage, modules, allowed) => {
|
||||
store.version = {...version, engine: {...version.engine, name: 'dae'}};
|
||||
store.capabilities = {...capabilities, resources: {...capabilities.resources, nodes: {...capabilities.resources.nodes, can_manage: canManage}}};
|
||||
const node = {id: 'n', name: 'included', provider_id: 'p', protocol: 'http', group_ids: []} as unknown as Node;
|
||||
store.nodes = [node];
|
||||
store.providers = [{id: 'p', kind, name: 'provider'}] as Provider[];
|
||||
store.sources = modules.map(name => ({kind: 'include', path: `config.d/${name}.dae`, content: "node { included: 'http://proxy:80' }"}) as ConfigSource);
|
||||
store.removeNode.mockResolvedValue(true);
|
||||
read().setDialog({kind: 'removeNodes', items: [node], onRemoved: vi.fn()});
|
||||
expect(read().removeNodes).toEqual(allowed ? [node] : []);
|
||||
read().setDialog({kind: 'removeNode', item: node});
|
||||
expect(read().formValid).toBe(allowed);
|
||||
await read().submit(vi.fn());
|
||||
expect(store.removeNode.mock.calls).toEqual(allowed ? [['n']] : []);
|
||||
});
|
||||
|
||||
// A request sent from one opening of the dialog settles after the person closed it or opened another: its success
|
||||
// must not close the new dialog, and its refusal goes to a toast rather than into the new dialog's alert.
|
||||
it.each([
|
||||
|
||||
@@ -187,7 +187,7 @@ export function useNodesPage({go, query}: PageProps) {
|
||||
const source = useMainSourceEdit();
|
||||
// A subscription is edited in whichever source declares it, and only in dae text this page knows how to write.
|
||||
const version = useVersion().data;
|
||||
const daeText = engineOf(version).daeText;
|
||||
const {daeText, nodeModule} = engineOf(version);
|
||||
const parsed =
|
||||
dialog?.kind === 'node' &&
|
||||
!byChain &&
|
||||
@@ -273,18 +273,31 @@ export function useNodesPage({go, query}: PageProps) {
|
||||
const joinChoices = useMemo(() => joinable.filter(customGroup).map(entry => ({id: entry.name, label: entry.name})), [joinable]);
|
||||
const joinPicked = joinPick.filter(name => joinChoices.some(choice => choice.id === name));
|
||||
const nodeInInclude = useCallback(
|
||||
(node: Node) => declaredInInclude([...authored, ...authoredChains].filter(item => item.entry.name === node.name)),
|
||||
[authored, authoredChains]
|
||||
(node: Node) => !nodeModule && declaredInInclude([...authored, ...authoredChains].filter(item => item.entry.name === node.name)),
|
||||
[nodeModule, authored, authoredChains]
|
||||
);
|
||||
const providerInInclude = useCallback((item: ProviderRow) => declaredInInclude(item.sourceTag ? (declared.get(item.sourceTag) ?? []) : []), [declared]);
|
||||
const removableNodes = useMemo(() => {
|
||||
const inline = new Set((providers.data?.providers ?? []).filter(item => item.kind === 'inline').map(item => item.id));
|
||||
const managed = new Set<string>();
|
||||
if (nodeModule) {
|
||||
const elsewhere = new Set<string>();
|
||||
for (const places of [authored, authoredChains]) {
|
||||
for (const {source, entry} of places) (source.path === nodeModule ? managed : elsewhere).add(entry.name);
|
||||
}
|
||||
for (const name of elsewhere) managed.delete(name);
|
||||
}
|
||||
return new Map(
|
||||
(resources?.nodes.can_manage ? (nodeList ?? []) : [])
|
||||
.filter(node => node.protocol !== 'chain' && typeof node.provider_id === 'string' && inline.has(node.provider_id) && !nodeInInclude(node))
|
||||
.filter(
|
||||
node =>
|
||||
typeof node.provider_id === 'string' &&
|
||||
inline.has(node.provider_id) &&
|
||||
(nodeModule ? managed.has(node.name) : node.protocol !== 'chain' && !nodeInInclude(node))
|
||||
)
|
||||
.map(node => [node.id, node])
|
||||
);
|
||||
}, [providers.data, resources?.nodes.can_manage, nodeList, nodeInInclude]);
|
||||
}, [providers.data, resources?.nodes.can_manage, nodeList, nodeInInclude, nodeModule, authored, authoredChains]);
|
||||
// honk's DELETE refuses a proxy chain, so a chain declared once in an editable main source is deleted as text.
|
||||
const removableChains = useMemo(
|
||||
() =>
|
||||
@@ -308,12 +321,13 @@ export function useNodesPage({go, query}: PageProps) {
|
||||
// A node or chain that a group, chain or DNS upstream still names would leave that reference dangling.
|
||||
const referrersOf = useCallback(
|
||||
(name: string) => {
|
||||
if (nodeModule) return null;
|
||||
const labels = sources
|
||||
.flatMap(item => nodeReferrers(item.content, name))
|
||||
.map(by => (by.kind === 'dns' ? t('nodes.referrerDns', {name: by.name}) : by.name));
|
||||
return labels.length ? formatList(lang, [...new Set(labels)]) : null;
|
||||
},
|
||||
[sources, t, lang]
|
||||
[nodeModule, sources, t, lang]
|
||||
);
|
||||
const removeBatch = useMemo(() => {
|
||||
const nodes: Node[] = [];
|
||||
@@ -625,7 +639,7 @@ export function useNodesPage({go, query}: PageProps) {
|
||||
toast('positive', t('nodes.removed', {name: dialog.item.name}));
|
||||
} else {
|
||||
if (referrers) return;
|
||||
if (dialog.item.protocol === 'chain') {
|
||||
if (!nodeModule && dialog.item.protocol === 'chain') {
|
||||
const chain = removableChains.get(dialog.item.id);
|
||||
if (!chain) {
|
||||
refuse(t(nodeInInclude(dialog.item) ? 'nodes.removeInclude' : 'nodes.editNodeMissing'));
|
||||
@@ -709,7 +723,7 @@ export function useNodesPage({go, query}: PageProps) {
|
||||
? newName !== '' && !!nodeValue.trim() && nodeFormReason('node', newName, nodeValue, t) === null && !nodeNameError && !linkError && !headerError
|
||||
: dialog?.kind === 'removeNodes'
|
||||
? removeNodes.length > 0
|
||||
: true;
|
||||
: dialog?.kind !== 'removeNode' || !nodeModule || removableNodes.has(dialog.item.id);
|
||||
const formValid = chainState ? chainState.valid : nodeFormValid;
|
||||
const subscription: SubscriptionDraft = {name: form.name, url: form.value, interval: form.interval, agent: form.agent, cache: form.cache, route: form.route};
|
||||
// A new subscription shows each option the backend lists, with its default preselected or as the placeholder; an
|
||||
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
import {LabeledSelect} from '../../../ui/Picker';
|
||||
import {SearchSelect} from '../../../ui/SearchSelect';
|
||||
import type {GroupDialogView} from './useGroupDialog';
|
||||
import {policyChoices} from '../../shared/policyText';
|
||||
import {BackendText} from '../../shared/BackendText';
|
||||
import {FilterSummary} from './FilterSummary';
|
||||
type PolicyDetails = {
|
||||
@@ -50,7 +49,7 @@ function Details({details: d}: {details: PolicyDetails}) {
|
||||
export function GroupDialog({model: m, details}: {model: GroupDialogView; details: PolicyDetails | null}) {
|
||||
const t = useT();
|
||||
const form = useId();
|
||||
const policy = policyChoices(m.policy, t);
|
||||
const policy = m.picker;
|
||||
return (
|
||||
<>
|
||||
<ModalDialog
|
||||
@@ -112,6 +111,7 @@ export function GroupDialog({model: m, details}: {model: GroupDialogView; detail
|
||||
</ProblemAlert>
|
||||
)}
|
||||
<LabeledSelect label={t('group.policy')} value={policy.selected} onChange={m.setPolicy} items={policy.items} isDisabled={m.busy} />
|
||||
{m.index && <TextField label={t('group.memberIndex')} value={m.index.value} onChange={m.index.change} isDisabled={m.busy} />}
|
||||
<IncludesEditor model={m} />
|
||||
{m.routes.map(field => (
|
||||
<SearchSelect
|
||||
|
||||
@@ -55,15 +55,17 @@ export function IncludesEditor({model: m}: {model: GroupDialogView}) {
|
||||
isDisabled={m.busy}
|
||||
/>
|
||||
)}
|
||||
<SearchMultiSelect
|
||||
label={t('group.nestedGroups')}
|
||||
searchLabel={t('group.searchGroups')}
|
||||
summary={m.includes.groupSummary}
|
||||
items={m.includes.choices.group}
|
||||
value={m.includes.selected.group}
|
||||
onChange={value => m.includes.change('group', value)}
|
||||
isDisabled={m.busy}
|
||||
/>
|
||||
{m.nestedGroups && (
|
||||
<SearchMultiSelect
|
||||
label={t('group.nestedGroups')}
|
||||
searchLabel={t('group.searchGroups')}
|
||||
summary={m.includes.groupSummary}
|
||||
items={m.includes.choices.group}
|
||||
value={m.includes.selected.group}
|
||||
onChange={value => m.includes.change('group', value)}
|
||||
isDisabled={m.busy}
|
||||
/>
|
||||
)}
|
||||
<SearchMultiSelect
|
||||
label={t('nav.nodes')}
|
||||
searchLabel={t('nodes.search')}
|
||||
|
||||
@@ -155,13 +155,14 @@ export function selectedIncludeLabels(filters: string[], nodes: Node[], provider
|
||||
subscriptions: new Map(selectedIncludes(filters, 'subscription').map(tag => [tag, subscriptionLabel(tag, nodes, providers)]))
|
||||
};
|
||||
}
|
||||
export function includeChoices(filters: string[], nodes: Node[], providers: Provider[], locale: string, declaredTags: string[] = []) {
|
||||
const matches = includeMatches(filters, nodes);
|
||||
export function includeChoices(filters: string[], nodes: Node[], providers: Provider[], locale: string, declaredTags: string[] = [], preview = true) {
|
||||
// dae uses regexp2, not honk's Rust regex dialect. Only offer region presets and local match counts with honk's matcher.
|
||||
const matches = preview ? includeMatches(filters, nodes) : null;
|
||||
const names = new Map(flagChoices(locale).map(region => [region.id, region.label]));
|
||||
// Only regions with nodes, and those already selected so that one with no nodes can still be unticked.
|
||||
const selectedRegions = new Set(selectedIncludes(filters, 'region'));
|
||||
const regions = regionFilters
|
||||
.map(region => ({id: region.id, label: names.get(region.id) ?? region.id, count: matches.regions.get(region.id)!.length}))
|
||||
const regions = (matches ? regionFilters : [])
|
||||
.map(region => ({id: region.id, label: names.get(region.id) ?? region.id, count: matches!.regions.get(region.id)!.length}))
|
||||
.filter(region => region.count > 0 || selectedRegions.has(region.id));
|
||||
const subscriptionIds = new Set(providers.filter(provider => provider.kind === 'subscription').map(provider => provider.id));
|
||||
const tags = new Set([
|
||||
@@ -184,7 +185,7 @@ export function includeChoices(filters: string[], nodes: Node[], providers: Prov
|
||||
count: nodeCounts.get(name) ?? 0,
|
||||
disabled: !isWritableName(name)
|
||||
}));
|
||||
return {region: regions, subscription: subscriptions, node: individual, matchedNodes: matches.selected};
|
||||
return {region: regions, subscription: subscriptions, node: individual, matchedNodes: matches?.selected ?? []};
|
||||
}
|
||||
|
||||
export function retainedIncludes(before: string[], after: string[], nodes: Node[]): string[] {
|
||||
|
||||
@@ -15,13 +15,15 @@ import {
|
||||
type GroupConditionRow,
|
||||
type GroupConditionKind
|
||||
} from '../../../dae/groupConditions';
|
||||
import {describeFilters, isWritableName} from '../../../dae/groups';
|
||||
import {describeFilters, isWritableName, writeDaeGroupEntry} from '../../../dae/groups';
|
||||
import {
|
||||
includeChoices,
|
||||
includesEveryNode,
|
||||
setEveryNode,
|
||||
retainedIncludes,
|
||||
advancedFilter,
|
||||
recogniseInclude,
|
||||
noNodes as noMembers,
|
||||
editMembership,
|
||||
selectedIncludes,
|
||||
setIncludes,
|
||||
@@ -37,8 +39,8 @@ import type {ConfigSource, Group, Node} from '../../../api/model';
|
||||
import {toast, type Problem} from '../../../ui/ui';
|
||||
import {useDialogSession, useDraftGuard} from '../../../shell/draft';
|
||||
import {LocalError, noticeText} from '../../../api/error';
|
||||
import {groupEditSafe, groupNameError, manualPolicy} from '../../shared/policyText';
|
||||
import {newGroupPolicies} from '../../../dae/vocab';
|
||||
import {groupEditSafe, groupNameError, manualPolicy, policyChoices, policyLabel} from '../../shared/policyText';
|
||||
import {daeConditionKind, daePolicyValid, groupGrammar, indexedPolicy} from '../../../dae/vocab';
|
||||
import type {SearchSection} from '../../../ui/SearchSelect';
|
||||
import type {CheckboxChoice} from '../../../ui/CheckboxSet';
|
||||
import {
|
||||
@@ -88,7 +90,9 @@ export type GroupDialogView = {
|
||||
problem: Problem | null;
|
||||
// Set once the group being edited is gone from the list, removed or renamed elsewhere: the edits stay to copy, unsaved.
|
||||
removed: string | null;
|
||||
policy: string | null;
|
||||
picker: {selected: string; items: Array<{id: string; label: string; desc?: string}>};
|
||||
index: {value: string; change: (value: string) => void} | null;
|
||||
nestedGroups: boolean;
|
||||
membershipFilters: string[] | null;
|
||||
invalid: boolean;
|
||||
filters: Array<{
|
||||
@@ -210,8 +214,13 @@ export function useGroupDialog(input: Input): GroupDialogView {
|
||||
const [viewing, setViewing] = useState(false);
|
||||
const busy = source.busy;
|
||||
const resources = useCapabilities().data?.resources;
|
||||
// `exit` is honk syntax, so only honk's text gets the field.
|
||||
const exitShown = engineOf(useVersion().data).daeText;
|
||||
const engine = engineOf(useVersion().data);
|
||||
const {dialect, policies} = groupGrammar[engine.id];
|
||||
const dae = dialect === 'dae';
|
||||
const nestedGroups = !dae && (context.g?.capabilities.supports_nested_groups ?? true);
|
||||
const indexed = dae ? indexedPolicy(draft?.policy ?? null) : null;
|
||||
const selectedPolicy = indexed?.[1] ?? draft?.policy ?? policies[0];
|
||||
const exitShown = engine.daeText;
|
||||
const allNodes = useNodes(!!draft && offered(resources, 'nodes', {whileLoading: false}));
|
||||
const providers = useProviders(!!draft && offered(resources, 'providers', {whileLoading: false}));
|
||||
const config = useConfig(!!draft && offered(resources, 'config', {whileLoading: false}));
|
||||
@@ -221,7 +230,6 @@ export function useGroupDialog(input: Input): GroupDialogView {
|
||||
);
|
||||
const nodes = draft ? (allNodes.data ?? (creating ? input.nodes : noNodes)) : noNodes;
|
||||
const filters = useMemo(() => (draft ? groupFilterTexts(draft.filters) : noFilters), [draft]);
|
||||
const invalid = !!draft?.filters.some(filter => groupFilterText(filter) === null);
|
||||
const quickFilters = draft ? groupFilterTexts(draft.filters.filter(filter => !advancedFilter(filter))) : noFilters;
|
||||
const selected = {
|
||||
region: selectedIncludes(quickFilters, 'region'),
|
||||
@@ -229,23 +237,38 @@ export function useGroupDialog(input: Input): GroupDialogView {
|
||||
node: selectedIncludes(quickFilters, 'node'),
|
||||
group: selectedIncludes(quickFilters, 'group')
|
||||
};
|
||||
let memberCount: number | undefined;
|
||||
if (indexed) {
|
||||
if (!creating) memberCount = context.g?.members.length;
|
||||
else if (!filters.length) memberCount = allNodes.data?.length;
|
||||
else if (filters.length === 1 && filters[0] === noMembers) memberCount = 0;
|
||||
// An expression or subscription may add members beyond the explicit node choices.
|
||||
else if (filters.every(filter => recogniseInclude(filter)?.kind === 'node')) memberCount = selectedIncludes(filters, 'node').length;
|
||||
}
|
||||
const invalid =
|
||||
!!draft &&
|
||||
(draft.filters.some(filter => groupFilterText(filter) === null) ||
|
||||
(dae && draft.policy !== entry?.policy && !daePolicyValid(draft.policy)) ||
|
||||
(!!indexed && memberCount !== undefined && Number(indexed[2]) >= memberCount));
|
||||
const choices = useMemo(
|
||||
() => includeChoices(filters, nodes, providers.data?.providers ?? [], lang, declaredTags),
|
||||
[filters, nodes, providers.data, lang, declaredTags]
|
||||
() => includeChoices(filters, nodes, providers.data?.providers ?? [], lang, declaredTags, !dae),
|
||||
[filters, nodes, providers.data, lang, declaredTags, dae]
|
||||
);
|
||||
const routes: RouteField[] = creating
|
||||
? manualPolicy(draft?.policy ?? null)
|
||||
? ['default_member_id', 'final_outbound']
|
||||
: ['final_outbound']
|
||||
: routeFields(context.g, draft?.policy ?? null);
|
||||
const routes: RouteField[] = dae
|
||||
? []
|
||||
: creating
|
||||
? manualPolicy(draft?.policy ?? null)
|
||||
? ['default_member_id', 'final_outbound']
|
||||
: ['final_outbound']
|
||||
: routeFields(context.g, draft?.policy ?? null);
|
||||
// The entry's keys the save writes as names.
|
||||
const nameKeys = [...routes.map(id => routeKeys[id]), ...(exitShown ? (['exit'] as const) : [])];
|
||||
const members = draft && manualPolicy(draft.policy) ? draftMembers(filters, nodes, t) : creating ? [] : context.members;
|
||||
const members = !dae && draft && manualPolicy(draft.policy) ? draftMembers(filters, nodes, t) : creating ? [] : context.members;
|
||||
const groupName = creating ? (draft?.name.trim() ?? '') : (draft?.name ?? '');
|
||||
const excluded = finalExcluded(groupName, context.outbounds.links);
|
||||
const [tried, setTried] = useState(false);
|
||||
const saving = useRef(false);
|
||||
const nameProblem = creating && draft ? groupNameError(draft.name.trim(), input.taken, t) : null;
|
||||
const nameProblem = creating && draft ? groupNameError(draft.name.trim(), input.taken, t, dae) : null;
|
||||
const session = useDialogSession();
|
||||
const [problem, setProblem] = useState<GroupDialogView['problem']>(null);
|
||||
const refuse = (text: string, kind?: Problem['kind'], refused?: Pick<Problem, 'lines' | 'backend'>) =>
|
||||
@@ -254,7 +277,7 @@ export function useGroupDialog(input: Input): GroupDialogView {
|
||||
!!draft &&
|
||||
((creating && !!draft.name) ||
|
||||
(!creating && draft.interrupt !== entry?.interrupt) ||
|
||||
draft.policy !== (creating ? newGroupPolicies[0].id : entry?.policy) ||
|
||||
draft.policy !== (creating ? policies[0] : entry?.policy) ||
|
||||
invalid ||
|
||||
JSON.stringify(filters) !== JSON.stringify(creating ? [] : entry?.filters) ||
|
||||
nameKeys.some(key => draft[key] !== routeValue(entry?.[key] ?? null)));
|
||||
@@ -299,20 +322,24 @@ export function useGroupDialog(input: Input): GroupDialogView {
|
||||
return;
|
||||
}
|
||||
const group = creating ? draft.name.trim() : draft.name;
|
||||
const update: GroupEntryUpdate = {filters, policy: draft.policy, ...(!creating ? {interrupt: draft.interrupt} : {})};
|
||||
const update: GroupEntryUpdate = {filters, policy: draft.policy, ...(!creating && !dae ? {interrupt: draft.interrupt} : {})};
|
||||
for (const key of nameKeys) Object.assign(update, {[key]: nameText(draft[key], written[key])});
|
||||
if (retry?.kind === 'conflict') {
|
||||
refuse(t('policy.editReopen'));
|
||||
return;
|
||||
}
|
||||
if (retry?.kind === 'merge') Object.assign(update, retry.keep);
|
||||
saving.current = true;
|
||||
const current = session.start();
|
||||
const origin = draft.refused ? (creating ? source.main : declared?.origin) : draft.origin;
|
||||
if (dae && (!origin || !engine.routing?.readable?.(origin.content))) {
|
||||
refuse(t('policy.editUnsafe'));
|
||||
return;
|
||||
}
|
||||
saving.current = true;
|
||||
void source
|
||||
.apply(text => {
|
||||
if (creating && readGroupEntries(text).some(entry => entry.name === group)) throw new LocalError('group.takenName');
|
||||
return writeGroupEntry(text, group, update);
|
||||
return dae ? writeDaeGroupEntry(text, group, update) : writeGroupEntry(text, group, update);
|
||||
}, origin ?? undefined)
|
||||
.then(result => {
|
||||
const open = current();
|
||||
@@ -361,7 +388,19 @@ export function useGroupDialog(input: Input): GroupDialogView {
|
||||
busy,
|
||||
problem,
|
||||
removed,
|
||||
policy: draft?.policy ?? null,
|
||||
picker: dae
|
||||
? {selected: selectedPolicy, items: policies.map(id => ({id, label: t('ui.aside', {text: policyLabel(id, t, engine.id), note: id})}))}
|
||||
: policyChoices(draft?.policy ?? null, t),
|
||||
index:
|
||||
dae && (selectedPolicy === 'fixed' || manualPolicy(selectedPolicy, engine.id))
|
||||
? {
|
||||
value: indexed?.[2].trim() ?? '',
|
||||
change: value => {
|
||||
if (/^\d*$/.test(value)) edit(prev => ({...prev, policy: selectedPolicy === 'select' && !value ? 'select' : `${selectedPolicy}(${value})`}));
|
||||
}
|
||||
}
|
||||
: null,
|
||||
nestedGroups,
|
||||
membershipFilters: draft ? filters : (entry?.filters ?? null),
|
||||
invalid,
|
||||
filters: (draft?.filters ?? []).filter(advancedFilter).map((filter, index, fields) => {
|
||||
@@ -382,7 +421,9 @@ export function useGroupDialog(input: Input): GroupDialogView {
|
||||
terms: conditionTerms(row).map((term, index) => ({
|
||||
...term,
|
||||
first: index === 0,
|
||||
kinds: kindChoices(row).map(kind => ({id: kind, label: t(conditionLabels[kind as keyof typeof conditionLabels])})),
|
||||
kinds: kindChoices(row)
|
||||
.filter(kind => !dae || daeConditionKind(kind))
|
||||
.map(kind => ({id: kind, label: t(conditionLabels[kind as keyof typeof conditionLabels])})),
|
||||
setKind: (kind: GroupConditionKind) => changeRow(changeTerm(row, term.id, {kind})),
|
||||
setValue: (value: string) => changeRow(changeTerm(row, term.id, {value})),
|
||||
remove: index === 0 ? null : () => changeRow(removeAlternative(row, term.id))
|
||||
@@ -405,7 +446,7 @@ export function useGroupDialog(input: Input): GroupDialogView {
|
||||
isDisabled: item.disabled
|
||||
})),
|
||||
node: choices.node.map(item => ({id: item.id, label: item.label, nodeName: true, isDisabled: item.disabled})),
|
||||
group: [...new Set([...context.outbounds.groups, ...selected.group])].map(name => ({
|
||||
group: (nestedGroups ? [...new Set([...context.outbounds.groups, ...selected.group])] : []).map(name => ({
|
||||
id: name,
|
||||
label: name,
|
||||
isDisabled: excluded.has(name) || !isWritableName(name) || /[|,]/.test(name)
|
||||
@@ -414,8 +455,11 @@ export function useGroupDialog(input: Input): GroupDialogView {
|
||||
groupSummary: selected.group.length ? t('group.selected', {n: selected.group.length}) : t('ui.none'),
|
||||
nodeSummary: selected.node.length ? t('group.selected', {n: selected.node.length}) : t('ui.none'),
|
||||
selected,
|
||||
change: (kind, value) => edit(prev => ({...prev, filters: editMembership(prev.filters, filters => setIncludes(filters, kind, value))})),
|
||||
count: t('group.memberCount', {n: choices.matchedNodes.length}),
|
||||
change: (kind, value) => {
|
||||
if ((kind !== 'group' || nestedGroups) && (kind !== 'region' || !dae))
|
||||
edit(prev => ({...prev, filters: editMembership(prev.filters, filters => setIncludes(filters, kind, value))}));
|
||||
},
|
||||
count: dae ? '' : t('group.memberCount', {n: choices.matchedNodes.length}),
|
||||
names: [...new Set(choices.matchedNodes.map(node => node.name))],
|
||||
everyNode:
|
||||
includesEveryNode(filters) &&
|
||||
@@ -447,7 +491,7 @@ export function useGroupDialog(input: Input): GroupDialogView {
|
||||
),
|
||||
stillIn: (() => {
|
||||
const prior = history.at(-1)?.filters;
|
||||
if (!prior) return '';
|
||||
if (dae || !prior) return '';
|
||||
const retained = retainedIncludes(groupFilterTexts(prior), filters, nodes);
|
||||
return retained.length ? t('group.stillIn', {n: retained.length}) : '';
|
||||
})()
|
||||
@@ -497,7 +541,7 @@ export function useGroupDialog(input: Input): GroupDialogView {
|
||||
origin: source.main,
|
||||
opened: null,
|
||||
refused: false,
|
||||
policy: newGroupPolicies[0].id,
|
||||
policy: policies[0],
|
||||
filters: filters.map(filter => groupFilterDraft(filter)),
|
||||
default: null,
|
||||
final: null,
|
||||
@@ -529,10 +573,10 @@ export function useGroupDialog(input: Input): GroupDialogView {
|
||||
close,
|
||||
dismiss: () => (dirty ? setDiscarding(true) : close()),
|
||||
discard: {isOpen: discarding, onCancel: () => setDiscarding(false), onConfirm: close},
|
||||
setPolicy: policy => edit(prev => ({...prev, policy})),
|
||||
setPolicy: policy => edit(prev => ({...prev, policy: dae && policy === 'fixed' ? 'fixed(0)' : policy})),
|
||||
add: () => edit(prev => ({...prev, filters: [...prev.filters, newGroupFilter()]})),
|
||||
save,
|
||||
interrupt: draft ? (draft.interrupt === null ? null : unquote(draft.interrupt) === 'true') : undefined,
|
||||
interrupt: draft && !dae ? (draft.interrupt === null ? null : unquote(draft.interrupt) === 'true') : undefined,
|
||||
setInterrupt: value => edit(prev => ({...prev, interrupt: value ? 'true' : prev.interrupt === null ? null : 'false'}))
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import {beforeEach, expect, it, vi} from 'vitest';
|
||||
import {hookHarness} from '../../store/testHelpers';
|
||||
import {usePolicies} from './usePolicies';
|
||||
import {readGroupEntries} from '../../dae/groups';
|
||||
import type {ConfigSource} from '../../api/model';
|
||||
import {useGroupDialog} from './group/useGroupDialog';
|
||||
import {nodeFixtures} from '../../../mock/fixtures';
|
||||
|
||||
const state = vi.hoisted(() => ({engine: 'dae', sources: [] as ConfigSource[], apply: vi.fn()}));
|
||||
const runtime = vi.hoisted(() => ({
|
||||
useCapabilities: () => ({
|
||||
data: {resources: {config: {available: true, writable: true}, groups: {available: false}, nodes: {available: false}, providers: {available: false}}}
|
||||
}),
|
||||
useVersion: () => ({data: {engine: {name: state.engine}}})
|
||||
}));
|
||||
vi.mock('../../store/runtime', () => runtime);
|
||||
vi.mock('../../store', () => ({
|
||||
...runtime,
|
||||
poll: {live: 1},
|
||||
useGroups: () => ({}),
|
||||
useNodes: () => ({}),
|
||||
useProviders: () => ({}),
|
||||
useSteadyNodes: () => undefined
|
||||
}));
|
||||
vi.mock('../../store/config', () => ({
|
||||
useConfig: () => ({data: {sources: state.sources}}),
|
||||
useConfigEditor: () => ({busy: null, apply: state.apply}),
|
||||
useSourceComplete: () => true,
|
||||
useCompleteness: () => () => true
|
||||
}));
|
||||
vi.mock('react', async original => ({
|
||||
...(await original<typeof import('react')>()),
|
||||
...hookHarness.hooks,
|
||||
useEffectEvent: (callback: unknown) => callback
|
||||
}));
|
||||
vi.mock('../../ui/landing', () => ({useLanding: () => undefined}));
|
||||
vi.mock('../../shell/draft', () => ({useDraftGuard: () => ({clear: vi.fn()}), useDialogSession: () => ({next: vi.fn(), start: () => () => true})}));
|
||||
vi.mock('../../i18n', async original => {
|
||||
const i18n = await original<typeof import('../../i18n')>();
|
||||
return {
|
||||
...i18n,
|
||||
useLang: () => 'en',
|
||||
useT: () => (key: string, params?: Record<string, string>) => (key === 'ui.aside' ? i18n.translate('en', key, params) : key)
|
||||
};
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
hookHarness.reset();
|
||||
state.apply.mockReset();
|
||||
});
|
||||
it.each(['dae', 'honk'].flatMap(engine => ['', 'new=1&node=Tokyo'].map(query => ({engine, query}))))(
|
||||
'creates from $query on $engine in its writable source',
|
||||
({engine, query}) => {
|
||||
state.engine = engine;
|
||||
const main = {id: 'entry', kind: 'main', writable: engine === 'honk', content: ''} as ConfigSource;
|
||||
const module = {
|
||||
id: 'module',
|
||||
path: query ? 'config.d/group.dae' : 'config.d/renamed.dae',
|
||||
kind: 'include',
|
||||
writable: true,
|
||||
content: query ? '' : 'group {\n}\n'
|
||||
} as ConfigSource;
|
||||
state.sources = [main, module];
|
||||
const read = () => hookHarness.render(() => usePolicies({query, go: vi.fn()}));
|
||||
const page = read();
|
||||
expect(page.createDisabled).toBe(false);
|
||||
if (query) hookHarness.runEffects();
|
||||
else page.create.show();
|
||||
read().create.name!.change('travel');
|
||||
if (engine === 'dae') {
|
||||
for (const name of ['1travel', '.travel', '-travel', 'must_travel']) {
|
||||
read().create.name!.change(name);
|
||||
expect(read().create.name!.error).toBe('group.daeNameStart');
|
||||
read().create.save(vi.fn());
|
||||
expect(state.apply).not.toHaveBeenCalled();
|
||||
}
|
||||
read().create.name!.change('travel');
|
||||
const editor = read().create;
|
||||
expect(editor.picker.items.map(item => item.id)).toEqual(['min_moving_avg', 'min_avg10', 'min', 'random', 'fixed', 'select']);
|
||||
expect(editor.picker.items.find(item => item.id === 'random')?.label).toBe('policy.kind.random (random)');
|
||||
editor.setPolicy('random');
|
||||
expect(read().create.index).toBeNull();
|
||||
expect(editor.nestedGroups).toBe(false);
|
||||
editor.includes.change('group', ['child']);
|
||||
for (const policy of ['fixed', 'select']) {
|
||||
read().create.setPolicy(policy);
|
||||
read().create.index!.change('1');
|
||||
if (query) {
|
||||
expect(read().create.invalid).toBe(true);
|
||||
read().create.save(vi.fn());
|
||||
expect(state.apply).not.toHaveBeenCalled();
|
||||
}
|
||||
}
|
||||
read().create.index!.change('0');
|
||||
expect(read().create.routes).toEqual([]);
|
||||
}
|
||||
read().create.save(vi.fn());
|
||||
const [[origin, transform]] = state.apply.mock.calls;
|
||||
expect(origin).toBe(engine === 'dae' ? module : main);
|
||||
expect(readGroupEntries(transform(origin.content))[0]).toMatchObject({
|
||||
name: 'travel',
|
||||
policy: engine === 'dae' ? 'select(0)' : 'score',
|
||||
filters: query ? ['name(Tokyo)'] : []
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['fixed', 'select'])('checks %s against the current group members when editing', policy => {
|
||||
state.engine = 'dae';
|
||||
const g = nodeFixtures(0).groups[0];
|
||||
const content = 'group { g { policy: random } }';
|
||||
const origin = {content, writable: true, kind: 'include'} as ConfigSource;
|
||||
const read = () =>
|
||||
hookHarness.render(() =>
|
||||
useGroupDialog({
|
||||
mode: 'edit',
|
||||
name: 'g',
|
||||
source: {main: null, writable: true, busy: false, apply: state.apply, error: null, retry: vi.fn()},
|
||||
declaration: {owner: {entry: readGroupEntries(content)[0], origin}, complete: true, loaded: true, error: null},
|
||||
context: {g, members: [], outbounds: {groups: [], nodes: [], links: new Map()}}
|
||||
})
|
||||
);
|
||||
read().show();
|
||||
read().setPolicy(policy);
|
||||
read().index!.change(String(g.members.length));
|
||||
expect(read().invalid).toBe(true);
|
||||
read().save(vi.fn());
|
||||
expect(state.apply).not.toHaveBeenCalled();
|
||||
read().index!.change(String(g.members.length - 1));
|
||||
expect(read().invalid).toBe(false);
|
||||
});
|
||||
@@ -45,7 +45,7 @@ export function usePolicies({go, query}: PageProps) {
|
||||
setHealth({from: nodes.data, groups: groups.data, map: sameHealth(health.map, map) ? health.map : map});
|
||||
}
|
||||
const sourceState = useMainSourceEdit();
|
||||
const {main, writable, busy, apply, error, retry} = sourceState;
|
||||
const {main, groupTarget, writable, busy, apply, error, retry} = sourceState;
|
||||
const source = useMemo(() => ({main, writable, busy, apply, error, retry}), [main, writable, busy, apply, error, retry]);
|
||||
// A group is edited in the source that declares it, which need not be the main one.
|
||||
const config = useConfig(offered(resources, 'config', {whileLoading: false}));
|
||||
@@ -134,7 +134,7 @@ export function usePolicies({go, query}: PageProps) {
|
||||
}, [runtimeGroups, refreshGroups, refreshNodes, retry]);
|
||||
const create = useGroupDialog({
|
||||
mode: 'create',
|
||||
source,
|
||||
source: {...source, main: groupTarget ?? null},
|
||||
taken: new Set([...outbounds.groups, ...owners.keys()]),
|
||||
outbounds,
|
||||
nodes: roster ?? [],
|
||||
@@ -147,8 +147,8 @@ export function usePolicies({go, query}: PageProps) {
|
||||
const editorOpened = useCallback(() => go('policies', within(query, {edit: null, node: null}), {replace: true}), [go, query]);
|
||||
const newRequested = params.get('new') === '1';
|
||||
useEffect(() => {
|
||||
if (newRequested && source.main && source.writable) openCreate();
|
||||
}, [newRequested, source.main, source.writable]);
|
||||
if (newRequested && groupTarget && writable) openCreate();
|
||||
}, [newRequested, groupTarget, writable]);
|
||||
return {
|
||||
declarations,
|
||||
cards: edited.gone ? [...kinds.shown, {...edited.gone, gone: true}] : kinds.shown,
|
||||
@@ -157,7 +157,7 @@ export function usePolicies({go, query}: PageProps) {
|
||||
providers: providers.data?.providers ?? [],
|
||||
memberSources,
|
||||
create,
|
||||
createDisabled: !source.writable || !source.main || source.busy,
|
||||
createDisabled: !writable || !groupTarget || busy,
|
||||
editRequested: params.get('edit') === '1',
|
||||
seedNode: params.get('node') ?? undefined,
|
||||
editorOpened,
|
||||
|
||||
@@ -76,7 +76,7 @@ export function usePolicyGroup(input: PolicyGroupInput) {
|
||||
}, [behind, selection, refetch]);
|
||||
const {memberSources} = input;
|
||||
const members = useMemo(() => memberViews(memberHealth(g, health), t, memberSources), [g, health, t, memberSources]);
|
||||
const card = g ? policyCardView(g, members, control.network, t, outbounds) : null;
|
||||
const card = g ? policyCardView(g, members, control.network, t, outbounds, control.engineId) : null;
|
||||
// The fold the reader left the group in. Pinning opens members once and each new visit from a link opens them again,
|
||||
// neither of which is remembered.
|
||||
const automatic = input.kind === 'auto';
|
||||
@@ -211,14 +211,15 @@ export function usePolicyGroup(input: PolicyGroupInput) {
|
||||
fields: exit ? [...card.fields, {label: t('groups.exit.label'), value: exit, nodeName: true}] : card.fields,
|
||||
heading: edit.editing ? t('policy.liveConfig') : null,
|
||||
reason: edit.editing ? null : (edit.tip ?? null),
|
||||
interrupt: card.interruptable
|
||||
? {
|
||||
selected: edit.editing ? edit.interrupt === true : card.interrupt,
|
||||
unset: edit.editing ? edit.interrupt === null : card.interruptUnset,
|
||||
isDisabled: !!control.busy || edit.busy,
|
||||
change: interrupt
|
||||
}
|
||||
: null
|
||||
interrupt:
|
||||
card.interruptable && (!edit.editing || edit.interrupt !== undefined)
|
||||
? {
|
||||
selected: edit.editing ? edit.interrupt === true : card.interrupt,
|
||||
unset: edit.editing ? edit.interrupt === null : card.interruptUnset,
|
||||
isDisabled: !!control.busy || edit.busy,
|
||||
change: interrupt
|
||||
}
|
||||
: null
|
||||
}
|
||||
: null,
|
||||
// Why the group's actions are locked, which the card gives as the lock beside its name.
|
||||
|
||||
@@ -123,6 +123,18 @@ it('names the policy as the picker does and keeps the engine spelling for the to
|
||||
expect(card('')).toEqual({label: t('policy.kind.urltest'), id: 'urltest'});
|
||||
});
|
||||
|
||||
it('labels a dae random group as automatic and keeps its supported override distinct from manual selection', () => {
|
||||
const group = nodeFixtures(0).groups[0];
|
||||
const g: Group = {...group, policy: {kind: 'random', native: 'random'}, capabilities: {...group.capabilities, can_select: false, can_override: true}};
|
||||
const zh: Translator = (key, params) => translate('zh-TW', key, params);
|
||||
expect(policyCardView(g, [], 'both', zh, undefined, 'dae')).toMatchObject({
|
||||
policy: {label: zh('policy.kind.random'), id: 'random'},
|
||||
selectable: false,
|
||||
overridable: true,
|
||||
automatic: true
|
||||
});
|
||||
});
|
||||
|
||||
it('filters large grids by region and observed health without mutating member order', () => {
|
||||
const nodes = Array.from({length: 13}, (_, index) => ({
|
||||
id: String(index),
|
||||
|
||||
@@ -2,6 +2,7 @@ import {groupConfigLabels, healthStatus, type OutboundCatalogue} from '../shared
|
||||
import {compareNames} from '../../i18n/format';
|
||||
import {enumLabel} from '../../i18n/enum';
|
||||
import type {Group, HealthObservation, JsonPatch, Node, ProbeResult, Provider} from '../../api/model';
|
||||
import type {Engine} from '../../api/engines';
|
||||
import type {Key} from '../../i18n';
|
||||
import {compareLatency, foldFamilies, healthMillis, measured, safeHttpUrl, type MessageRef} from '../../api/selectors';
|
||||
import {groupPolicyText} from '../shared/policyText';
|
||||
@@ -231,7 +232,14 @@ export function selectionSummary(g: Pick<Group, 'runtime'>, members: MemberView[
|
||||
const id = tcp ?? udp;
|
||||
return {text: t('policy.summary', {member: id ? name(id) : t('policy.noneSelected')})};
|
||||
}
|
||||
export function policyCardView(g: Group, members: MemberView[], network: 'both' | 'tcp' | 'udp', t: Translator, outbounds?: OutboundCatalogue) {
|
||||
export function policyCardView(
|
||||
g: Group,
|
||||
members: MemberView[],
|
||||
network: 'both' | 'tcp' | 'udp',
|
||||
t: Translator,
|
||||
outbounds?: OutboundCatalogue,
|
||||
engine: Engine['id'] = 'honk'
|
||||
) {
|
||||
const tcp = g.runtime.selection.tcp?.member_id;
|
||||
const udp = g.runtime.selection.udp?.member_id;
|
||||
const selectable = g.policy.kind === 'selector' && g.capabilities.can_select;
|
||||
@@ -244,7 +252,7 @@ export function policyCardView(g: Group, members: MemberView[], network: 'both'
|
||||
return {
|
||||
id: g.id,
|
||||
name: g.name,
|
||||
policy: groupPolicyText(g.policy, t),
|
||||
policy: groupPolicyText(g.policy, t, engine),
|
||||
selected: network === 'tcp' ? tcp : network === 'udp' ? udp : tcp === udp ? tcp : undefined,
|
||||
// Both networks on different members: neither is the selection, so each is marked with the network it carries.
|
||||
marks: network === 'both' && tcp && udp && tcp !== udp ? {[tcp]: t('ui.tcp'), [udp]: t('ui.udp')} : undefined,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import {expect, it, vi} from 'vitest';
|
||||
import {hookHarness} from '../../store/testHelpers';
|
||||
import type {ConfigSource} from '../../api/model';
|
||||
import {useRuleTemplates} from './useRuleTemplates';
|
||||
|
||||
const apply = vi.hoisted(() => vi.fn());
|
||||
const module = (id: string, content: string): ConfigSource => ({
|
||||
id,
|
||||
content,
|
||||
path: `config.d/${id}.dae`,
|
||||
kind: 'include',
|
||||
writable: true,
|
||||
content_sha256: '',
|
||||
bytes: content.length,
|
||||
line_count: 1,
|
||||
loaded_at: ''
|
||||
});
|
||||
const routing = module('routing', 'routing { fallback: direct }');
|
||||
const sources = [
|
||||
{...module('entry', 'include { config.d/*.dae api.dae }'), kind: 'main' as const, writable: false},
|
||||
module('group', 'group { my_group { policy: min_moving_avg } }'),
|
||||
routing
|
||||
];
|
||||
vi.mock('react', async original => ({...(await original<typeof import('react')>()), ...(await import('../../store/testHelpers')).hookHarness.hooks}));
|
||||
vi.mock('../../store', () => ({
|
||||
useCapabilities: () => ({data: {resources: {config: {available: true, writable: true}, nodes: {available: false}}}}),
|
||||
useConfig: () => ({data: {sources}}),
|
||||
useConfigEditor: () => ({apply}),
|
||||
useNodes: () => ({}),
|
||||
useGeodata: () => ({}),
|
||||
useVersion: () => ({data: {engine: {name: 'dae'}}})
|
||||
}));
|
||||
vi.mock('../../store/config', () => ({useCompleteness: () => () => true}));
|
||||
vi.mock('../../shell/draft', () => ({useDraftGuard: () => ({})}));
|
||||
vi.mock('../../i18n', async original => {
|
||||
const actual = await original<typeof import('../../i18n')>();
|
||||
return {...actual, useT: () => actual.translate.bind(null, 'en'), useLang: () => 'en'};
|
||||
});
|
||||
|
||||
it('writes dae routing to its module without introducing group or DNS sections', async () => {
|
||||
hookHarness.reset();
|
||||
const render = () => hookHarness.render(() => useRuleTemplates({query: '', go: vi.fn()}));
|
||||
render().select('single');
|
||||
expect(render().canApply).toBe(false);
|
||||
expect(render().refusal).toContain('proxy, auto');
|
||||
render().select('bypass');
|
||||
expect(render().canApply).toBe(true);
|
||||
render().open();
|
||||
const model = render();
|
||||
expect(model.dialog?.dns).toBeNull();
|
||||
expect(model.dialog?.after).toContain('domain(geosite:cn) -> direct');
|
||||
expect(model.dialog?.after).toContain('fallback: my_group');
|
||||
expect(model.dialog?.after).not.toMatch(/group \{|dns \{|policy: score/);
|
||||
await model.confirm();
|
||||
expect(apply).toHaveBeenCalledWith(routing, model.dialog!.after);
|
||||
});
|
||||
@@ -13,7 +13,8 @@ import type {LimitLink} from '../shared/limitHint';
|
||||
import {backendWords, explainDiagnostic} from '../shared/offlineDependency';
|
||||
import {geodataKinds} from '../shared/geodataUpdate';
|
||||
import {toast, toastFailure} from '../../ui/ui';
|
||||
import {fileName} from '../../dae/sources';
|
||||
import {allGroupNames, fileName} from '../../dae/sources';
|
||||
import {templateGroups} from '../../dae/setup';
|
||||
import type {RuleTemplate, TemplateOptions} from '../../dae/templates';
|
||||
import type {PageProps} from '../../shell/routes';
|
||||
import {useDraftGuard} from '../../shell/draft';
|
||||
@@ -93,6 +94,11 @@ export function useRuleTemplates({go, query}: PageProps): RuleTemplatesModel {
|
||||
const view = useMemo(() => templatesView(sources, t), [sources, t]);
|
||||
const version = useVersion().data;
|
||||
const engine = useMemo(() => engineOf(version), [version]);
|
||||
const routing = engine.routing;
|
||||
const routingOnly = routing?.templates === 'routing-only';
|
||||
const accepts = routing?.readable;
|
||||
const readableSyntax = useMemo(() => !accepts || sources.every(source => accepts(source.content)), [accepts, sources]);
|
||||
const defined = useMemo(() => (routingOnly ? allGroupNames(sources).map(group => group.written) : []), [routingOnly, sources]);
|
||||
const isComplete = useCompleteness(sources);
|
||||
// A new group named like a node takes that name over, so the impact names the nodes it would shadow.
|
||||
const nodes = useNodes(readable && offered(resources, 'nodes', {whileLoading: false}));
|
||||
@@ -127,13 +133,22 @@ export function useRuleTemplates({go, query}: PageProps): RuleTemplatesModel {
|
||||
const target = templateTarget({
|
||||
sources,
|
||||
configWritable: resources?.config.writable === true,
|
||||
daeText: engine.daeText,
|
||||
daeText: !!routing && readableSyntax,
|
||||
complete: isComplete,
|
||||
holdsCredentials: source => engine.holdsCredentials(source),
|
||||
denied
|
||||
});
|
||||
const setMode = (mode: string) => go('rules', within(query, {view: mode}));
|
||||
const selected = picked ?? view.current?.id ?? null;
|
||||
const missing = routingOnly && selected ? templateGroups(selected, defined) : [];
|
||||
const sourceNote = target.source && !target.source.writable && engine.sourceReadOnlyNote?.(target.source);
|
||||
const refusal = sourceNote
|
||||
? t(sourceNote)
|
||||
: target.refusal
|
||||
? refusalReason(target.refusal, target.source, t)
|
||||
: missing.length
|
||||
? t('rule.template.needsGroups', {groups: missing.join(t('ui.listSeparator'))})
|
||||
: null;
|
||||
const options: TemplateOptions = {blockAds: view.blockAds, blockQuic: view.blockQuic, networkManagerDirect: view.networkManagerDirect, ...pickedOptions};
|
||||
const applying = editor.busy === 'save';
|
||||
const dirty = !!selected && (selected !== view.current?.id || templateOptionKeys.some(key => options[key] !== view[key]));
|
||||
@@ -146,20 +161,20 @@ export function useRuleTemplates({go, query}: PageProps): RuleTemplatesModel {
|
||||
},
|
||||
'rule.templates'
|
||||
);
|
||||
const canApply = dirty && !target.refusal && !!target.source && isComplete(target.source) === true && !editor.busy;
|
||||
const canApply = dirty && !refusal && !!target.source && isComplete(target.source) === true && !editor.busy;
|
||||
return {
|
||||
...view,
|
||||
...options,
|
||||
setOption: (option, enabled) => setPickedOptions(current => ({...current, [option]: enabled})),
|
||||
available: readable && engine.daeText && !!config.data,
|
||||
pending: readable && engine.daeText && config.loading && !config.data,
|
||||
available: readable && !!routing && !!config.data,
|
||||
pending: readable && !!routing && config.loading && !config.data,
|
||||
mode: ruleViewMode(query),
|
||||
setMode,
|
||||
file: target.source && fileName(target.source),
|
||||
selected,
|
||||
select: setPicked,
|
||||
refusal: target.refusal && refusalReason(target.refusal, target.source, t),
|
||||
refusalLink: target.refusal ? refusalLink(target.refusal, t, lang) : undefined,
|
||||
refusal,
|
||||
refusalLink: target.refusal && !sourceNote ? refusalLink(target.refusal, t, lang) : undefined,
|
||||
canApply,
|
||||
open: () => {
|
||||
const source = target.source;
|
||||
@@ -179,7 +194,8 @@ export function useRuleTemplates({go, query}: PageProps): RuleTemplatesModel {
|
||||
(nodes.data ?? []).map(node => node.name),
|
||||
t
|
||||
),
|
||||
...templateWrites(selected, source, sources, t, options)
|
||||
...templateWrites(selected, source, sources, t, options),
|
||||
...(routingOnly && {withDns: null})
|
||||
});
|
||||
},
|
||||
dialog: dialog && {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import type {ReactNode} from 'react';
|
||||
import {renderToStaticMarkup} from 'react-dom/server';
|
||||
import {expect, it, vi} from 'vitest';
|
||||
import {capabilities} from '../../../mock/fixtures';
|
||||
import {engineOf} from '../../api/engines';
|
||||
import {LangContext} from '../../i18n';
|
||||
import {optionsProbe, probeChoices, readProbeOptions, type ProbeOptions} from '../../store/probeOptions';
|
||||
import {ProbeOptionsDialog} from '../shared/ProbeOptionsDialog';
|
||||
import {ProbeSettingsCard} from './ProbeSettings';
|
||||
|
||||
const state = vi.hoisted(() => ({name: 'dae', submit: (_: {preventDefault(): void}) => {}}));
|
||||
vi.mock('../../store/runtime', () => ({useVersion: () => ({data: {engine: {name: state.name}}}), useCapabilities: () => ({data: capabilities})}));
|
||||
vi.mock('../../store/probeOptions', async original => ({
|
||||
...(await original<typeof import('../../store/probeOptions')>()),
|
||||
useProbeOptions: () => readProbeOptions()
|
||||
}));
|
||||
// The dialog portal has no DOM on the server; render its controls and submit the form through its handler.
|
||||
vi.mock('../../ui/ui', async original => ({
|
||||
...(await original<typeof import('../../ui/ui')>()),
|
||||
ModalDialog: ({children}: {children: ReactNode}) => children,
|
||||
DialogForm: ({children, onSubmit}: {children: ReactNode; onSubmit: typeof state.submit}) => {
|
||||
state.submit = onSubmit;
|
||||
return children;
|
||||
}
|
||||
}));
|
||||
|
||||
it('shows and submits cold on dae without replacing the warmth preference used on honk', () => {
|
||||
const storage = {getItem: () => '{"cold":false}', setItem: vi.fn()};
|
||||
vi.stubGlobal('localStorage', storage);
|
||||
try {
|
||||
for (const name of ['dae', 'honk']) {
|
||||
state.name = name;
|
||||
const cold = name === 'dae';
|
||||
const engine = engineOf({engine: {name, version: '1'}});
|
||||
const target = {type: 'node', node_id: 'n'} as const;
|
||||
const request = (options: ProbeOptions) => optionsProbe(capabilities, target, options, undefined, ['ss'], engine);
|
||||
const settings = renderToStaticMarkup(
|
||||
<LangContext.Provider value="en">
|
||||
<ProbeSettingsCard />
|
||||
</LangContext.Provider>
|
||||
);
|
||||
const field = settings.split('data-setting="probeWarmth"')[1].split('data-setting="probeMembers"')[0];
|
||||
expect(field).toContain(cold ? 'Cold (new connection)' : 'Warm (reuse connection)');
|
||||
expect(field.includes('disabled=""')).toBe(cold);
|
||||
expect(request(readProbeOptions())?.warmth).toBe(cold ? 'cold' : 'warm');
|
||||
const submit = vi.fn(request);
|
||||
const dialog = renderToStaticMarkup(
|
||||
<LangContext.Provider value="en">
|
||||
<ProbeOptionsDialog model={{name: 'n', group: false, choices: probeChoices(capabilities, 'node'), busy: false, close: vi.fn(), submit}} />
|
||||
</LangContext.Provider>
|
||||
);
|
||||
const checkbox = dialog.match(/<input[^>]*type="checkbox"[^>]*>/)?.[0];
|
||||
expect(checkbox).toBeDefined();
|
||||
expect(checkbox!.includes('checked=""')).toBe(cold);
|
||||
expect(checkbox!.includes('disabled=""')).toBe(cold);
|
||||
state.submit({preventDefault() {}});
|
||||
expect(submit.mock.calls[0][0].cold).toBe(cold);
|
||||
expect(submit.mock.results[0].value?.warmth).toBe(cold ? 'cold' : 'warm');
|
||||
}
|
||||
expect(storage.setItem).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
@@ -9,18 +9,16 @@ import {settingsCard} from './nav';
|
||||
|
||||
const card = settingsCard('probes');
|
||||
|
||||
// What the Probe buttons and the options dialog send, saved in this browser. honk's background health checks are
|
||||
// configuration and keep their one editor on the configuration page.
|
||||
// On-demand probe options are saved in this browser; background health checks belong to the backend configuration.
|
||||
export function ProbeSettingsCard() {
|
||||
const t = useT();
|
||||
const caps = useCapabilities();
|
||||
const version = useVersion().data;
|
||||
const engine = engineOf(useVersion().data);
|
||||
const options = useProbeOptions();
|
||||
const resources = caps.data?.resources;
|
||||
const choices = probeChoices(caps.data, 'node');
|
||||
const choices = probeChoices(caps.data, 'node', undefined, undefined, engine);
|
||||
const versions = resources?.probes.ip_versions ?? [];
|
||||
const config =
|
||||
offered(resources, 'config', {whileLoading: false}) && engineOf(version).globalSettings ? href('config', {tab: 'global', field: 'tcp_check_url'}) : null;
|
||||
const config = offered(resources, 'config', {whileLoading: false}) && engine.globalSettings ? href('config', {tab: 'global', field: 'tcp_check_url'}) : null;
|
||||
return (
|
||||
<Card level={2} title={t(card.titleKey)} titleId={card.headingId}>
|
||||
{!resources ? (
|
||||
@@ -59,12 +57,10 @@ export function ProbeSettingsCard() {
|
||||
<LabeledSelect
|
||||
label={t('settings.probeWarmth')}
|
||||
description={t('settings.probeWarmthHelp')}
|
||||
value={options.cold ? 'cold' : 'warm'}
|
||||
value={options.cold || !engine.warmProbes ? 'cold' : 'warm'}
|
||||
isDisabled={!engine.warmProbes}
|
||||
onChange={warmth => saveProbeOptions({cold: warmth === 'cold'})}
|
||||
items={[
|
||||
{id: 'warm', label: t('settings.probeWarm')},
|
||||
{id: 'cold', label: t('settings.probeCold')}
|
||||
]}
|
||||
items={[...(engine.warmProbes ? [{id: 'warm', label: t('settings.probeWarm')}] : []), {id: 'cold', label: t('settings.probeCold')}]}
|
||||
/>
|
||||
</div>
|
||||
<div className="rp-contents" data-setting="probeMembers">
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import {useId, useState} from 'react';
|
||||
import {engineOf} from '../../api/engines';
|
||||
import {useVersion} from '../../store/runtime';
|
||||
import {useT} from '../../i18n';
|
||||
import {latencyProbeChoice, useProbeOptions, type ProbeChoice, type ProbeOptions} from '../../store/probeOptions';
|
||||
import {Button, DialogForm, LabeledSelect, ModalDialog, Switch} from '../../ui/ui';
|
||||
@@ -17,7 +19,9 @@ export function ProbeOptionsDialog({model: m}: {model: ProbeOptionsDialogModel})
|
||||
// Starts from the Latency probes settings; a change here applies to this probe only.
|
||||
const stored = useProbeOptions();
|
||||
const [choice, setChoice] = useState(latencyProbeChoice(m.choices, stored.choice)?.id ?? '');
|
||||
const [cold, setCold] = useState(stored.cold);
|
||||
const {warmProbes} = engineOf(useVersion().data);
|
||||
const [preferCold, setCold] = useState(stored.cold);
|
||||
const cold = !warmProbes || preferCold;
|
||||
const [leaves, setLeaves] = useState(stored.leaves);
|
||||
const disabled = m.busy || !m.choices.some(item => item.id === choice);
|
||||
return (
|
||||
@@ -44,7 +48,7 @@ export function ProbeOptionsDialog({model: m}: {model: ProbeOptionsDialogModel})
|
||||
}}
|
||||
>
|
||||
<LabeledSelect label={t('probe.kind')} value={choice} onChange={setChoice} items={m.choices.map(item => ({id: item.id, label: t(item.label)}))} />
|
||||
<Switch isSelected={cold} onChange={setCold}>
|
||||
<Switch isSelected={cold} isDisabled={!warmProbes} onChange={setCold}>
|
||||
{t('probe.cold')}
|
||||
</Switch>
|
||||
{m.group && (
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {useT} from '../../i18n';
|
||||
import {ConfirmDialog} from '../../ui/ui';
|
||||
|
||||
// Reloading honk rereads its files, so the top bar and the overview both ask first, in the same words.
|
||||
// The overview and top bar use the same confirmation because reload rereads the backend's files.
|
||||
export function ReloadConfirm({
|
||||
isOpen,
|
||||
onCancel,
|
||||
|
||||
@@ -12,8 +12,10 @@ export function modeView(
|
||||
configAvailable: boolean,
|
||||
t: LabelFn,
|
||||
known = true,
|
||||
reason?: EngineReason
|
||||
reason?: EngineReason,
|
||||
acceptsTarget?: (name: string) => boolean
|
||||
) {
|
||||
if (acceptsTarget) groups = groups.filter(group => acceptsTarget(group.name));
|
||||
const shown = writable ? (staged ?? current) : current;
|
||||
const target = shown.mode === 'global' ? shown.target : ((current.mode === 'global' ? current.target : groups[0]?.name) ?? '');
|
||||
return {
|
||||
|
||||
@@ -5,7 +5,7 @@ import {translate, type Translator} from '../../i18n';
|
||||
import type {ConfigSource} from '../../api/model';
|
||||
import type {PendingRule} from '../../store';
|
||||
import {byFile, editProblem, editToast, failureToast, insertRules, partialFailure, pendingView, refusalDetails, ruleFailure} from './pending';
|
||||
const t: Translator = (key, params, pluralParam, precision) => translate('en', key, params, pluralParam, precision);
|
||||
const t: Translator = (key, params, pluralParam, precision) => translate('en', key, params, pluralParam, precision, 'honk');
|
||||
|
||||
async function held() {
|
||||
const api = createMockApi();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {expect, it} from 'vitest';
|
||||
import {translate, type Translator} from '../../i18n';
|
||||
import {groupEditSafe, groupPolicyText, policyChoices, policyLabel} from './policyText';
|
||||
import {groupEditSafe, groupPolicyText, manualPolicy, policyChoices, policyLabel} from './policyText';
|
||||
const t: Translator = (key, params) => translate('en', key, params);
|
||||
|
||||
for (const lang of ['en', 'zh-TW', 'zh-CN'] as const) {
|
||||
@@ -52,6 +52,24 @@ it('names a live native policy with its engine spelling beside it', () => {
|
||||
expect(groupPolicyText({kind: 'fallback', native: ''}, t)).toEqual({label: t('policy.kind.fallback'), id: 'fallback'});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['select', 'selector', true],
|
||||
['select(2)', 'selector', true],
|
||||
['fixed(2)', 'fixed', false],
|
||||
['random', 'random', false],
|
||||
['min', 'urltest', false],
|
||||
['min_avg10', 'urltest', false],
|
||||
['min_moving_avg', 'urltest', false],
|
||||
['min_last_latency', 'urltest', false]
|
||||
] as const)('labels dae text %s as %s and only offers manual selection for select', (native, kind, manual) => {
|
||||
expect(policyLabel(native, t, 'dae')).toBe(t(`policy.kind.${kind}`));
|
||||
expect(manualPolicy(native, 'dae')).toBe(manual);
|
||||
});
|
||||
|
||||
it('uses the reported dae kind even for a native spelling the editor does not know', () => {
|
||||
expect(groupPolicyText({kind: 'random', native: 'future(1)'}, t, 'dae')).toEqual({label: t('policy.kind.random'), id: 'future(1)'});
|
||||
});
|
||||
|
||||
it('accepts an unchanged multi-line filter and checks only edited values', () => {
|
||||
const entry = {filters: ['name(a,\n b)'], policy: 'select'};
|
||||
expect(groupEditSafe(['name(a,\n b)'], 'select', entry)).toBe(true);
|
||||
|
||||
@@ -3,27 +3,28 @@ import {enumLabel} from '../../i18n/enum';
|
||||
import {isFragment} from '../../dae/text';
|
||||
import type {Translator} from '../../i18n';
|
||||
import {policyKindLabels} from '../../api/selectors';
|
||||
import {newGroupPolicies, policyKind} from '../../dae/vocab';
|
||||
import {groupGrammar, newGroupPolicies, policyKind} from '../../dae/vocab';
|
||||
import type {Group} from '../../api/model';
|
||||
import type {Engine} from '../../api/engines';
|
||||
|
||||
// A group without a policy line is a selector in honk, which is what `select` writes.
|
||||
const IMPLIED = 'select';
|
||||
|
||||
// Translate native names without changing expressions saved by the editor.
|
||||
export function policyLabel(value: string | null, t: Translator): string {
|
||||
const native = value ?? IMPLIED;
|
||||
const kind = policyKind(native);
|
||||
export function policyLabel(value: string | null, t: Translator, engine: Engine['id'] = 'honk'): string {
|
||||
const native = value ?? (engine === 'dae' ? groupGrammar.dae.policies[0] : IMPLIED);
|
||||
const kind = policyKind(native, engine);
|
||||
return kind ? enumLabel(policyKindLabels, kind, t) : native;
|
||||
}
|
||||
|
||||
export function groupPolicyText(policy: Pick<Group['policy'], 'kind' | 'native'>, t: Translator): {label: string; id?: string} {
|
||||
const label = policy.native ? policyLabel(policy.native, t) : enumLabel(policyKindLabels, policy.kind, t);
|
||||
export function groupPolicyText(policy: Pick<Group['policy'], 'kind' | 'native'>, t: Translator, engine: Engine['id'] = 'honk'): {label: string; id?: string} {
|
||||
const label = engine !== 'dae' && policy.native ? policyLabel(policy.native, t, engine) : enumLabel(policyKindLabels, policy.kind, t);
|
||||
const id = policy.native || policy.kind;
|
||||
return label === id ? {label} : {label, id};
|
||||
}
|
||||
|
||||
// Whether a policy as written picks by hand. honk reads a policy it does not recognise as a selector too.
|
||||
export const manualPolicy = (value: string | null): boolean => (policyKind(value ?? IMPLIED) ?? 'selector') === 'selector';
|
||||
export const manualPolicy = (value: string | null, engine: Engine['id'] = 'honk'): boolean => (policyKind(value ?? '', engine) ?? 'selector') === 'selector';
|
||||
|
||||
// The picker keeps a policy it does not offer as its own choice, so opening an editor never rewrites it.
|
||||
export function policyChoices(value: string | null, t: Translator) {
|
||||
@@ -36,8 +37,10 @@ export function policyChoices(value: string | null, t: Translator) {
|
||||
}
|
||||
|
||||
const nameProblems = {invalid: 'group.badName', taken: 'group.takenName'} as const;
|
||||
export function groupNameError(name: string, taken: ReadonlySet<string>, t: Translator): string | null {
|
||||
export function groupNameError(name: string, taken: ReadonlySet<string>, t: Translator, dae = false): string | null {
|
||||
if (!name.trim()) return t('nodes.nameMissing');
|
||||
// dae_config_lexer.go:81-82: ID starts with ASCII letter or underscore; config/patch.go:71-95 reserves must_.
|
||||
if (dae && (!/^[A-Za-z_]/.test(name) || name.startsWith('must_'))) return t('group.daeNameStart');
|
||||
const problem = groupNameProblem(name, taken);
|
||||
return problem ? t(nameProblems[problem]) : null;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import {useMemo} from 'react';
|
||||
import {useCapabilities, useGroups, useVersion} from '../../store';
|
||||
import {useConfig} from '../../store/config';
|
||||
import {useConfig, useSourceComplete} from '../../store/config';
|
||||
import {useMainSourceEdit} from '../../store/mainSource';
|
||||
import {editProblem, editToast} from './pending';
|
||||
import {useT} from '../../i18n';
|
||||
import {toast} from '../../ui/ui';
|
||||
import {useAction} from '../../store/action';
|
||||
import {useModeDraft} from './useModeDraft';
|
||||
import {readMode, writeMode, sameMode, type OutboundMode} from '../../dae/outboundMode';
|
||||
import {readMode, sameMode, type OutboundMode} from '../../dae/outboundMode';
|
||||
import {modeLabels, modeReasons, modeView} from './modeView';
|
||||
import {offered} from '../../api/capabilities';
|
||||
import {LocalError} from '../../api/error';
|
||||
@@ -20,24 +20,28 @@ export function useMode() {
|
||||
const groups = useGroups(offered(resources, 'groups', {whileLoading: false}));
|
||||
const config = useConfig(offered(resources, 'config', {whileLoading: false}));
|
||||
const {main, checking, writable, busy, error, retry, apply: write} = useMainSourceEdit();
|
||||
// The mode is a rule doona writes into dae text, so another engine's configuration neither shows nor takes one.
|
||||
// Until the version names the engine the card waits as it does for the configuration.
|
||||
const version = useVersion().data;
|
||||
const daeText = engineOf(version).daeText;
|
||||
const content = daeText ? (main ?? config.data?.sources.find(source => source.kind === 'main'))?.content : undefined;
|
||||
const engine = engineOf(version);
|
||||
const routing = engine.routing;
|
||||
const source = useMemo(() => engineOf(version).routing?.modeSource(config.data?.sources ?? []), [version, config.data]);
|
||||
const module = source?.kind === 'include';
|
||||
const complete = useSourceComplete(module && source.writable ? source : null);
|
||||
const content = source?.content;
|
||||
const current = useMemo<OutboundMode>(() => (content == null ? {mode: 'rule'} : readMode(content)), [content]);
|
||||
const [staged, setStaged] = useModeDraft();
|
||||
const action = useAction<'apply'>({shared: 'mode-action'});
|
||||
const configAvailable = (daeText || !version) && !!resources?.config.available;
|
||||
const configAvailable = (!!routing || !version) && !!resources?.config.available;
|
||||
// Each write changes the source, which is then checked again. The card keeps its controls meanwhile instead of
|
||||
// flashing the read-only status, so the Apply button a screen reader was just told about stays in place.
|
||||
const reason = capabilities && engineOf(version).reason('mode', capabilities);
|
||||
const view = modeView(current, staged, groups.data ?? [], daeText && writable && (!!main || checking), configAvailable, t, content != null, reason);
|
||||
const reason = capabilities && engine.reason('mode', capabilities);
|
||||
const editable = !!source && writable && (module ? source.writable && complete !== false : !!main || checking);
|
||||
const view = modeView(current, staged, groups.data ?? [], editable, configAvailable, t, content != null, reason, routing?.acceptsTarget);
|
||||
const note = view.readOnly && (reason && 'message' in reason ? reason.message : ((source && engine.sourceReadOnlyNote?.(source)) ?? routing?.readOnlyNote));
|
||||
const apply = () =>
|
||||
action.run('apply', async () => {
|
||||
const submitted = staged;
|
||||
if (!submitted || (submitted.mode === 'global' && !submitted.target)) return;
|
||||
const result = await write(text => writeMode(text, submitted));
|
||||
if (!routing || !source || !editable || !submitted || (submitted.mode === 'global' && !submitted.target)) return;
|
||||
const result = await write(text => routing.writeMode(text, submitted), module ? source : undefined);
|
||||
if (result.kind === 'ok') {
|
||||
setStaged(current => (current === submitted ? null : current));
|
||||
toast('positive', t('act.modeApplied', {mode: t(modeLabels[submitted.mode])}));
|
||||
@@ -52,7 +56,8 @@ export function useMode() {
|
||||
});
|
||||
return {
|
||||
...view,
|
||||
reasons: modeReasons(view, busy || !!action.busy, t),
|
||||
...(note && {readOnly: false}),
|
||||
reasons: note ? {mode: t(note), global: t(note)} : modeReasons(view, busy || !!action.busy, t),
|
||||
error,
|
||||
retry,
|
||||
busy: busy || !!action.busy,
|
||||
|
||||
@@ -134,3 +134,10 @@ it('keeps the backend detail for removed configuration keys and no longer names
|
||||
});
|
||||
expect(backendMessage('destination_rejected', 'Old backend detail', t).summary).toContain('Old backend detail');
|
||||
});
|
||||
|
||||
it('spaces a Latin backend name in Chinese but not the Chinese fallback', () => {
|
||||
const text = translate('zh-TW', 'ui.refusal.writesDisabled');
|
||||
expect(text).toContain('後端');
|
||||
expect(text).not.toMatch(/ 後端|後端 /);
|
||||
expect(translate('zh-TW', 'ui.refusal.writesDisabled', undefined, undefined, undefined, 'dae')).toMatch(/ dae /);
|
||||
});
|
||||
+47
-2
@@ -1,9 +1,9 @@
|
||||
import {renderToStaticMarkup} from 'react-dom/server';
|
||||
import {expect, it} from 'vitest';
|
||||
import {LangContext, translate, useT, type Lang, type Params} from './index';
|
||||
import {BackendNameContext, LangContext, translate, useT, type Lang, type Params} from './index';
|
||||
import type {Key} from './index';
|
||||
|
||||
function Message({messageKey, params}: {messageKey: Key; params: Params}) {
|
||||
function Message({messageKey, params}: {messageKey: Key; params?: Params}) {
|
||||
return useT()(messageKey, params);
|
||||
}
|
||||
|
||||
@@ -20,6 +20,51 @@ it('substitutes placeholders once and selects plural forms in the active languag
|
||||
expect(render('zh-CN', 'dns.deleted', {n: 2})).toBe('已删除 2 条缓存项');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['en', 'Reload dae?', 'Suspend dae', 'This backend does not provide the native API'],
|
||||
['zh-TW', '重載 dae?', '暫停 dae', '此後端未提供原生 API'],
|
||||
['zh-CN', '重载 dae?', '暂停 dae', '此后端未提供原生 API']
|
||||
] as const)('names dae for operations, but not on the no-API page, in %s', (lang, reload, suspend, noApi) => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<LangContext.Provider value={lang}>
|
||||
<BackendNameContext.Provider value="dae">
|
||||
<h2>
|
||||
<Message messageKey="shell.reloadTitle" />
|
||||
</h2>
|
||||
<h2>
|
||||
<Message messageKey="ov.suspendTitle" />
|
||||
</h2>
|
||||
<p>
|
||||
<Message messageKey="ov.suspendHelp" />
|
||||
</p>
|
||||
<p>
|
||||
<Message messageKey="ui.trafficUncounted" />
|
||||
</p>
|
||||
</BackendNameContext.Provider>
|
||||
<h2>
|
||||
<Message messageKey="login.noApiTitle" />
|
||||
</h2>
|
||||
</LangContext.Provider>
|
||||
);
|
||||
expect(markup).toContain(`<h2>${reload}</h2><h2>${suspend}</h2>`);
|
||||
expect(markup.match(/<p>[^<]*dae[^<]*<\/p>/g)).toHaveLength(2);
|
||||
expect(markup).not.toMatch(/honk|\{backendName/);
|
||||
expect(markup).toContain(`<h2>${noApi}</h2>`);
|
||||
});
|
||||
|
||||
it('keeps the exact backend spelling and falls back to a sentence subject when no version has arrived', () => {
|
||||
const render = (name?: string) =>
|
||||
renderToStaticMarkup(
|
||||
<LangContext.Provider value="en">
|
||||
<BackendNameContext.Provider value={name}>
|
||||
<Message messageKey="nodes.linkRejected" params={{reason: 'unsupported scheme'}} />
|
||||
</BackendNameContext.Provider>
|
||||
</LangContext.Provider>
|
||||
);
|
||||
expect(render('dAe')).toBe('dAe cannot read this link: unsupported scheme');
|
||||
expect(render()).toBe('The backend cannot read this link: unsupported scheme');
|
||||
});
|
||||
|
||||
it.each<[Key, number | bigint, string]>([
|
||||
['conn.filtersActive', 1, 'Filters, 1 applied'],
|
||||
['dns.logLoaded', 2, '2 loaded; the export covers loaded records only'],
|
||||
|
||||
+22
-5
@@ -160,7 +160,7 @@ const pluralNumber = (value: string | number | bigint): number => {
|
||||
const integer = BigInt(value);
|
||||
return integer <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(integer) : Number(integer % 1_000_000n) + 1_000_000;
|
||||
};
|
||||
export function translate(lang: Lang, key: Key, params?: Params, pluralParam = 'n', precision?: Precision): string {
|
||||
export function translate(lang: Lang, key: Key, params?: Params, pluralParam = 'n', precision?: Precision, backendName?: string): string {
|
||||
const own = catalogues.get(lang)?.[key];
|
||||
const message = own ?? catalogues.get(REFERENCE_LANG)?.[key];
|
||||
const origin = own === undefined ? REFERENCE_LANG : lang;
|
||||
@@ -174,18 +174,35 @@ export function translate(lang: Lang, key: Key, params?: Params, pluralParam = '
|
||||
const category = rules.select(operand === undefined ? NaN : pluralNumber(operand));
|
||||
text = message[category] ?? message.other;
|
||||
}
|
||||
return params ? text.replace(/\{(\w+)\}/g, (_, name: string) => param(lang, params[name], name === pluralParam, precision?.[name])) : text;
|
||||
if (!params && !text.includes('{backendName')) return text;
|
||||
// Chinese spaces a Latin engine name from the words around it, but not the Chinese fallback.
|
||||
if (backendName === undefined && origin.startsWith('zh')) text = text.replace(/ ?(\{backendName\w*\}) ?/g, '$1');
|
||||
return text.replace(/\{(\w+)\}/g, (placeholder, name: string) => {
|
||||
switch (name) {
|
||||
case 'backendName':
|
||||
return backendName ?? translate(origin, 'ui.backendName');
|
||||
case 'backendNameModifier':
|
||||
return backendName ?? translate(origin, 'ui.backendNameModifier');
|
||||
case 'backendNameSubject':
|
||||
return backendName ?? translate(origin, 'ui.backendNameSubject');
|
||||
default:
|
||||
return params ? param(lang, params[name], name === pluralParam, precision?.[name]) : placeholder;
|
||||
}
|
||||
});
|
||||
}
|
||||
// Keys to read in place of others, such as the palette's own words for a few statuses (src/shell/palettes.ts).
|
||||
export type Rewording = Readonly<Partial<Record<Key, Key>>>;
|
||||
export const RewordingContext = createContext<Rewording | undefined>(undefined);
|
||||
// One translator per language and rewording, so effects and memos that list `t` do not re-run every render.
|
||||
// These placeholders use the reported spelling, or a localized fallback for their position in the sentence.
|
||||
export const BackendNameContext = createContext<string | undefined>(undefined);
|
||||
export function useT(): Translator {
|
||||
const lang = useLang();
|
||||
const rewording = useContext(RewordingContext);
|
||||
const backendName = useContext(BackendNameContext);
|
||||
return useMemo(
|
||||
() => (key: Key, params?: Params, pluralParam?: string, precision?: Precision) => translate(lang, rewording?.[key] ?? key, params, pluralParam, precision),
|
||||
[lang, rewording]
|
||||
() => (key: Key, params?: Params, pluralParam?: string, precision?: Precision) =>
|
||||
translate(lang, rewording?.[key] ?? key, params, pluralParam, precision, backendName),
|
||||
[lang, rewording, backendName]
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+38
-24
@@ -120,6 +120,10 @@
|
||||
"config.changedMeanwhile": "The configuration changed or another write was still in progress, so nothing was written. Refresh and try again",
|
||||
"config.changedOnDisk": "The file changed on disk while you were editing; applying would replace that change.",
|
||||
"config.clean": "No diagnostics",
|
||||
"config.daeEntry": "The entry file is read-only. Edit the corresponding file under config.d instead.",
|
||||
"config.daeLayout": "dae can only write to a managed configuration. Keep the entry file and api.dae separate from the modules under config.d.",
|
||||
"config.daeRoutingReadOnly": "To change modes, doona needs one writable routing section it can read in full. Edit the routing source directly otherwise.",
|
||||
"config.daeWritesDisabled": "Enable config_write in api.dae, set a non-empty secret and restart dae to allow configuration writes.",
|
||||
"config.diagnostic.bareCondition": "Condition has no function call; it will never match",
|
||||
"config.diagnostic.braceWithoutSection": "Closing brace without an open section",
|
||||
"config.diagnostic.downloadGeodata": "Download geodata",
|
||||
@@ -143,7 +147,7 @@
|
||||
"config.discard": "Discard changes",
|
||||
"config.discardHelp": "Leaving discards these unsaved changes: {drafts}.",
|
||||
"config.discardTitle": "Discard changes not applied?",
|
||||
"config.diskAhead": "The file on disk is not the running configuration, so nothing was written. Reload honk to apply the file, or restart honk if it changes a setting that needs a restart",
|
||||
"config.diskAhead": "The file on disk is not the running configuration, so nothing was written. Reload {backendName} to apply the file, or restart {backendName} if it changes a setting that needs a restart",
|
||||
"config.draftBackend": "Backend profile",
|
||||
"config.draftConfig": "Config file",
|
||||
"config.draftDiagnostics": "Current draft diagnostics",
|
||||
@@ -290,7 +294,8 @@
|
||||
"config.openSourceAt": "Open config file: {where}",
|
||||
"config.readOnly": "Read-only",
|
||||
"config.readOnlyAttempt": "This file is read-only",
|
||||
"config.readOnlyHelp": "The backend does not allow configuration writes. On honk, enable experimental.native_api.config_write and set a secret or password sign-in.",
|
||||
"config.readOnlyHelp": "Check the configuration for {backendName} to enable writes.",
|
||||
"config.readOnlyHelpHonk": "The backend does not allow configuration writes. On honk, enable experimental.native_api.config_write and set a secret or password sign-in.",
|
||||
"config.readOnlyNote": "The backend does not allow configuration writes, so this file can only be viewed. The help above explains how to turn writes on.",
|
||||
"config.redacted": "Listener secret values are redacted",
|
||||
"config.refusedNote": "The backend does not accept writes to this file, so it can only be viewed.",
|
||||
@@ -301,7 +306,8 @@
|
||||
"config.restart.copyFailed": "Could not copy the command; select its text and copy it.",
|
||||
"config.restart.docs": "Reload and restart",
|
||||
"config.restart.effect": "takes effect only after a restart",
|
||||
"config.restart.next": "To apply it, edit the config file on the host, then restart honk there. The command is for systemd; the install guide covers other init systems.",
|
||||
"config.restart.next": "To apply it, edit the config file on the host, then restart {backendName} there.",
|
||||
"config.restart.nextWithCommand": "To apply it, edit the config file on the host, then restart {backendName} there. The command is for systemd; the install guide covers other init systems.",
|
||||
"config.restart.planned": "Writing such a change directly, with a prompt to restart, is planned for the next version.",
|
||||
"config.restart.title": {
|
||||
"one": "{n} setting needs a restart",
|
||||
@@ -360,14 +366,14 @@
|
||||
"one": "{n} warning",
|
||||
"other": "{n} warnings"
|
||||
},
|
||||
"config.writeHelp": "If the file changed on disk since loading, honk refuses the write.",
|
||||
"config.writeHelp": "If the file changed on disk since loading, {backendName} refuses the write.",
|
||||
"config.writeRestart": {
|
||||
"one": "{n} setting takes effect only after a restart; nothing written",
|
||||
"other": "{n} settings take effect only after a restart; nothing written"
|
||||
},
|
||||
"config.writeRestartAbsent": {
|
||||
"one": "The setting honk refuses the write over is not in the configuration. State it there and restart honk once.",
|
||||
"other": "The {n} settings honk refuses the write over are not in the configuration. State them there and restart honk once."
|
||||
"one": "The setting {backendName} refuses the write over is not in the configuration. State it there and restart {backendName} once.",
|
||||
"other": "The {n} settings {backendName} refuses the write over are not in the configuration. State them there and restart {backendName} once."
|
||||
},
|
||||
"conn.activeCount": {
|
||||
"one": "{n} active",
|
||||
@@ -816,6 +822,7 @@
|
||||
"group.byRule": "Selected by rules",
|
||||
"group.create": "Create",
|
||||
"group.customExpression": "Custom expression",
|
||||
"group.daeNameStart": "Start the name with a letter or underscore. The prefix must_ is reserved.",
|
||||
"group.everyNode": "Includes every node",
|
||||
"group.filterAnd": "AND",
|
||||
"group.filterKind.nameExact": "Exact names",
|
||||
@@ -834,6 +841,7 @@
|
||||
"one": "{n} node",
|
||||
"other": "{n} nodes"
|
||||
},
|
||||
"group.memberIndex": "Member index (starting at 0)",
|
||||
"group.nestedGroups": "Groups",
|
||||
"group.newGroup": "New group",
|
||||
"group.policy": "Selection policy",
|
||||
@@ -939,8 +947,8 @@
|
||||
"login.invalidCredentials": "The username or password is incorrect.",
|
||||
"login.mismatch": "The passwords do not match.",
|
||||
"login.needsSetup": "The backend has no administrator yet; create one first.",
|
||||
"login.noApiNote": "Use a honk build that provides the native API.",
|
||||
"login.noApiTitle": "This honk build has no native API",
|
||||
"login.noApiNote": "Use a backend build that provides the native API.",
|
||||
"login.noApiTitle": "This backend does not provide the native API",
|
||||
"login.note": "{backend} requires a Bearer token; it is stored only in this browser and sent in the Authorization header of every request.",
|
||||
"login.password": "Password",
|
||||
"login.passwordLong": "The password is longer than 128 characters.",
|
||||
@@ -1084,7 +1092,7 @@
|
||||
"nodes.latency.unmeasuredList": "{n} not measured: {names}",
|
||||
"nodes.link": "Node link",
|
||||
"nodes.linkInvalid": "The node link must be a protocol://… link, such as ss://, vmess://, vless://, trojan:// or hysteria2://",
|
||||
"nodes.linkRejected": "honk cannot read this link: {reason}",
|
||||
"nodes.linkRejected": "{backendNameSubject} cannot read this link: {reason}",
|
||||
"nodes.linkTooLong": "Adding a node takes a link of at most {n} characters; put a longer one in the configuration editor",
|
||||
"nodes.manual.advanced": "Advanced",
|
||||
"nodes.manual.congestion": "Congestion control",
|
||||
@@ -1207,7 +1215,7 @@
|
||||
"nodes.xhttp.headerDuplicate": "Header names must be unique (case-insensitive).",
|
||||
"nodes.xhttp.headerName": "Header {n} name",
|
||||
"nodes.xhttp.headerValue": "Header {n} value",
|
||||
"nodes.xhttp.help": "Blank fields use the shown defaults. honk validates on save; changed options give the node a new ID.",
|
||||
"nodes.xhttp.help": "Blank fields use the shown defaults. {backendNameSubject} validates on save; changed options give the node a new ID.",
|
||||
"nodes.xhttp.host": "HTTP host",
|
||||
"nodes.xhttp.mode": "Mode",
|
||||
"nodes.xhttp.noGrpcHeader": "Omit the gRPC content type (noGRPCHeader)",
|
||||
@@ -1326,7 +1334,7 @@
|
||||
"ov.lim.mainReadOnly": "The main config file contains the native API secret or a listener secret, and honk does not write back a file with secrets. Move the secrets into their own include file.",
|
||||
"ov.lim.manage": "Nodes and node sources",
|
||||
"ov.lim.mode": "Outbound mode",
|
||||
"ov.lim.notRunningReason": "honk is starting or stopping.",
|
||||
"ov.lim.notRunningReason": "{backendNameSubject} is starting or stopping.",
|
||||
"ov.lim.noticeSetting": "Status card setting",
|
||||
"ov.lim.recordOff": "These recorders are on by default. Add the settings below to the configuration, then restart honk.",
|
||||
"ov.lim.restore": "Restoring a revision",
|
||||
@@ -1376,8 +1384,8 @@
|
||||
"ov.status.datapathFailed": "{status}, datapath failed",
|
||||
"ov.succeeded": "Completed",
|
||||
"ov.suspend": "Suspend",
|
||||
"ov.suspendHelp": "Proxying stops until honk is resumed.",
|
||||
"ov.suspendTitle": "Suspend honk",
|
||||
"ov.suspendHelp": "Proxying stops until {backendName} is resumed.",
|
||||
"ov.suspendTitle": "Suspend {backendName}",
|
||||
"ov.unavailable": "This backend does not provide this data",
|
||||
"ov.unknown": "Unknown",
|
||||
"ov.unknownHelp": "The backend has not confirmed this state.",
|
||||
@@ -1817,6 +1825,7 @@
|
||||
"rule.template.homeboundSummary": "Route mainland China traffic through a dedicated group.",
|
||||
"rule.template.mode": "Routing mode",
|
||||
"rule.template.more": "More templates",
|
||||
"rule.template.needsGroups": "This template needs the following groups. Create them in the group module before applying it: {groups}.",
|
||||
"rule.template.networkManagerDirect": "Keep NetworkManager direct",
|
||||
"rule.template.networkManagerDirectHelp": "Only needed on Linux desktops using NetworkManager; routers do not need it.",
|
||||
"rule.template.networkManagerOff": "NetworkManager traffic follows the routing rules.",
|
||||
@@ -1916,7 +1925,7 @@
|
||||
"settings.geodataCronCustom": "This cron expression comes from the config file or the API.",
|
||||
"settings.geodataCustom": "Custom",
|
||||
"settings.geodataCustomUrls": "Custom URLs",
|
||||
"settings.geodataDailyHelp": "Local time on the honk device. The update starts within the following hour.",
|
||||
"settings.geodataDailyHelp": "Local time on the {backendNameModifier} device. The update starts within the following hour.",
|
||||
"settings.geodataDailyHour": "Daily update time",
|
||||
"settings.geodataDetails": "Details",
|
||||
"settings.geodataEdit": "Edit",
|
||||
@@ -2016,7 +2025,7 @@
|
||||
"settings.probeWarmth": "Measurement",
|
||||
"settings.probeWarmthHelp": "A cold probe opens a new connection, so its result includes connection setup.",
|
||||
"settings.probes": "Latency probes",
|
||||
"settings.probesChecks": "Background health checks, including the check URLs and interval, are part of the honk configuration.",
|
||||
"settings.probesChecks": "Background health checks, including the check URLs and interval, are part of the {backendNameModifier} configuration.",
|
||||
"settings.probesConfig": "Edit health checks in Configuration",
|
||||
"settings.probesNote": "Saved in this browser. Probe buttons use these settings, and the probe options dialog starts from them.",
|
||||
"settings.probesUnavailable": "This backend does not provide latency probes",
|
||||
@@ -2121,9 +2130,9 @@
|
||||
"shell.macShortcut": "⌘K",
|
||||
"shell.notOffered": "This backend does not provide this page",
|
||||
"shell.rateLimited": "Rate limit reached: retrying in {n} s",
|
||||
"shell.reloadEngine": "Reload honk",
|
||||
"shell.reloadHelp": "honk reads its config files again and reloads. Held rules are not written.",
|
||||
"shell.reloadTitle": "Reload honk?",
|
||||
"shell.reloadEngine": "Reload {backendName}",
|
||||
"shell.reloadHelp": "{backendNameSubject} reads its config files again and reloads. Held rules are not written.",
|
||||
"shell.reloadTitle": "Reload {backendName}?",
|
||||
"shell.report": "Report a problem",
|
||||
"shell.search": "Search pages, connections, nodes, groups, node sources and config files",
|
||||
"shell.searchUnavailable": "Could not open search: it did not load.",
|
||||
@@ -2248,6 +2257,9 @@
|
||||
"ui.backend.unsupportedMediaType": "Unsupported media type",
|
||||
"ui.backend.unsupportedValue": "Unsupported value",
|
||||
"ui.backendMessage": "Backend message: {message}",
|
||||
"ui.backendName": "the backend",
|
||||
"ui.backendNameModifier": "backend",
|
||||
"ui.backendNameSubject": "The backend",
|
||||
"ui.backendUrl": "Backend URL",
|
||||
"ui.block": "block",
|
||||
"ui.cache": "Cache",
|
||||
@@ -2330,15 +2342,17 @@
|
||||
"ui.refresh": "Refresh",
|
||||
"ui.refreshFailed": "Could not refresh data",
|
||||
"ui.refreshed": "Data refreshed.",
|
||||
"ui.refusal.configurationUnavailable": "The configuration service is unavailable. Check honk’s configuration and service status, then retry.",
|
||||
"ui.refusal.credentialSourcesChanged": "The sources declaring API secrets have changed. Reload honk and retry.",
|
||||
"ui.refusal.configurationUnavailable": "The configuration service is unavailable. Check {backendName}’s configuration and service status, then retry.",
|
||||
"ui.refusal.credentialSourcesChanged": "The sources declaring API secrets have changed. Reload {backendName} and retry.",
|
||||
"ui.refusal.importEntryChanged": "The import entry differs from the active database entry. Start honk with -c pointing to the active entry, then retry the import.",
|
||||
"ui.refusal.listenerSecretInContent": "The file content or source path contains an API secret value. Use a random secret that appears nowhere else, restart honk and sign in again.",
|
||||
"ui.refusal.listenerSecretInContent": "The change was refused to protect the API secret. Check the file and {backendName}’s API settings.",
|
||||
"ui.refusal.listenerSecretInContentHonk": "The file content or source path contains an API secret value. Use a random secret that appears nowhere else, restart honk and sign in again.",
|
||||
"ui.refusal.listenerSecretSource": "This file declares a listener secret, or this write would add one. Edit the file on disk.",
|
||||
"ui.refusal.listenerSettingsChanged": "This change alters protected listener settings or the database directory. Keep experimental.native_api, clash_api.secret and global.data_dir unchanged when writing here.",
|
||||
"ui.refusal.storeBlocked": "A failed configuration revision blocks writes. Activate the head revision, then retry.",
|
||||
"ui.refusal.unsafePath": "The configuration store refused the target path. Use a regular file within an allowed configuration directory and retry.",
|
||||
"ui.refusal.writesDisabled": "Configuration writes are disabled. Enable config_write and configure an API secret or password authentication, then restart honk and sign in again.",
|
||||
"ui.refusal.writesDisabled": "Configuration writes are disabled. Check how to enable writes for {backendName}.",
|
||||
"ui.refusal.writesDisabledHonk": "Configuration writes are disabled. Enable config_write and configure an API secret or password authentication, then restart honk and sign in again.",
|
||||
"ui.reloadPage": "Reload",
|
||||
"ui.requestNote": " (request_id: {requestId})",
|
||||
"ui.required": " (required)",
|
||||
@@ -2359,7 +2373,7 @@
|
||||
"ui.tcp": "TCP",
|
||||
"ui.theme": "Theme",
|
||||
"ui.time": "Time",
|
||||
"ui.trafficUncounted": "Only traffic that passes through honk is counted. Direct connections that the kernel forwards on its own are not counted.",
|
||||
"ui.trafficUncounted": "Only traffic that passes through {backendName} is counted. Direct connections that the kernel forwards on its own are not counted.",
|
||||
"ui.type": "Type",
|
||||
"ui.udp": "UDP",
|
||||
"ui.unavailable": "Unavailable",
|
||||
@@ -2376,7 +2390,7 @@
|
||||
"one": "Validation found {n} error; nothing written",
|
||||
"other": "Validation found {n} errors; nothing written"
|
||||
},
|
||||
"ui.writtenNotApplied": "Written to the config file but not applied; the running configuration is unchanged. Fix the file, then reload or restart honk",
|
||||
"ui.writtenNotApplied": "Written to the config file but not applied; the running configuration is unchanged. Fix the file, then reload or restart {backendName}",
|
||||
"ui.writtenNotRead": "The change was saved, but the configuration could not be read back. Retry to show it",
|
||||
"ui.yes": "Yes",
|
||||
"unit.byte": "{n} B",
|
||||
|
||||
+37
-23
@@ -114,6 +114,10 @@
|
||||
"config.changedMeanwhile": "配置已被更改或另一次写入尚未完成,因此未写入。请刷新后重试",
|
||||
"config.changedOnDisk": "编辑期间磁盘上的文件已更改,应用会覆盖该更改。",
|
||||
"config.clean": "没有诊断",
|
||||
"config.daeEntry": "入口文件只读。请编辑 config.d 下对应的模块文件。",
|
||||
"config.daeLayout": "dae 只能写入托管配置。入口文件和 api.dae 须与 config.d 下的模块分开。",
|
||||
"config.daeRoutingReadOnly": "切换模式需要一个可写且可完整读取的 routing 段。否则请直接编辑分流配置文件。",
|
||||
"config.daeWritesDisabled": "请在 api.dae 中启用 config_write,设置非空的 secret,然后重启 dae 以允许写入配置。",
|
||||
"config.diagnostic.bareCondition": "条件中没有函数调用,因此永远不会匹配",
|
||||
"config.diagnostic.braceWithoutSection": "右大括号没有对应的区段开头",
|
||||
"config.diagnostic.downloadGeodata": "下载地理数据",
|
||||
@@ -137,7 +141,7 @@
|
||||
"config.discard": "放弃修改",
|
||||
"config.discardHelp": "离开后,以下项目的未保存修改将丢失:{drafts}。",
|
||||
"config.discardTitle": "放弃未应用的修改?",
|
||||
"config.diskAhead": "磁盘上的文件与运行中的配置不同,因此未写入。请重载 honk 以应用该文件;若文件更改了需重启的设置,请重启 honk",
|
||||
"config.diskAhead": "磁盘上的文件与运行中的配置不同,因此未写入。请重载 {backendName} 以应用该文件;若文件更改了需重启的设置,请重启 {backendName}",
|
||||
"config.draftBackend": "后端配置",
|
||||
"config.draftConfig": "配置文件",
|
||||
"config.draftDiagnostics": "当前草稿的诊断",
|
||||
@@ -254,7 +258,8 @@
|
||||
"config.openSourceAt": "打开配置文件:{where}",
|
||||
"config.readOnly": "只读",
|
||||
"config.readOnlyAttempt": "此文件只读",
|
||||
"config.readOnlyHelp": "后端未开放写入配置。honk 须启用 experimental.native_api.config_write,并设置密钥或密码登录。",
|
||||
"config.readOnlyHelp": "请检查 {backendName} 的配置,确认是否已允许写入。",
|
||||
"config.readOnlyHelpHonk": "后端未开放写入配置。honk 须启用 experimental.native_api.config_write,并设置密钥或密码登录。",
|
||||
"config.readOnlyNote": "后端未开放写入配置,只能在此查看。启用方法见上方说明。",
|
||||
"config.redacted": "后端已脱敏监听密钥的值",
|
||||
"config.refusedNote": "后端不接受写入此文件,只能在此查看。",
|
||||
@@ -265,7 +270,8 @@
|
||||
"config.restart.copyFailed": "无法复制命令,请选中文本后手动复制",
|
||||
"config.restart.docs": "重新加载与重启",
|
||||
"config.restart.effect": "需重启才会生效",
|
||||
"config.restart.next": "请在主机上修改配置文件,再在该主机上重启 honk。此命令适用于 systemd,其他 init 系统见安装指南。",
|
||||
"config.restart.next": "请在主机上修改配置文件,再重启 {backendName}。",
|
||||
"config.restart.nextWithCommand": "请在主机上修改配置文件,再在该主机上重启 {backendName}。此命令适用于 systemd,其他 init 系统见安装指南。",
|
||||
"config.restart.planned": "预计下个版本支持直接写入,并提示重启。",
|
||||
"config.restart.title": "{n} 项设置需重启",
|
||||
"config.revisionHelp": "当前生效的配置内容的版本标识,内容变更并生效后会改变。",
|
||||
@@ -315,9 +321,9 @@
|
||||
"config.validateNoMain": "后端未返回完整的主配置,因此无法校验",
|
||||
"config.validateOther": "校验只涵盖主配置及其引入文件,不含此文件",
|
||||
"config.warnings": "{n} 个警告",
|
||||
"config.writeHelp": "若加载后磁盘上的文件已更改,honk 会拒绝写入。",
|
||||
"config.writeHelp": "若加载后磁盘上的文件已更改,{backendName} 会拒绝写入。",
|
||||
"config.writeRestart": "{n} 项设置需重启才会生效,未写入",
|
||||
"config.writeRestartAbsent": "honk 拒绝写入所指的 {n} 项设置不在配置文件里。在配置文件明写这些值,并重新启动 honk 一次。",
|
||||
"config.writeRestartAbsent": "{backendName} 拒绝写入所指的 {n} 项设置不在配置文件里。在配置文件明写这些值,并重新启动 {backendName} 一次。",
|
||||
"conn.activeCount": "{n} 条进行中",
|
||||
"conn.addRuleFor": "为 {target} 添加路由规则",
|
||||
"conn.allDevices": "所有设备",
|
||||
@@ -705,6 +711,7 @@
|
||||
"group.byRule": "由规则选入",
|
||||
"group.create": "创建",
|
||||
"group.customExpression": "自定义表达式",
|
||||
"group.daeNameStart": "名称必须以英文字母或下划线开头,且不能使用保留前缀 must_。",
|
||||
"group.everyNode": "包含所有节点",
|
||||
"group.filterAnd": "AND",
|
||||
"group.filterKind.nameExact": "完整名称",
|
||||
@@ -720,6 +727,7 @@
|
||||
"group.groupNameHint": "只能使用英文字母、数字、下划线、句点和连字符。",
|
||||
"group.matchingNodes": "匹配的节点",
|
||||
"group.memberCount": "{n} 个节点",
|
||||
"group.memberIndex": "成员索引(从 0 开始)",
|
||||
"group.nestedGroups": "子组",
|
||||
"group.newGroup": "新建组",
|
||||
"group.policy": "选择方式",
|
||||
@@ -807,8 +815,8 @@
|
||||
"login.invalidCredentials": "用户名或密码错误。",
|
||||
"login.mismatch": "两次输入的密码不一致。",
|
||||
"login.needsSetup": "后端尚未设置管理员,请先创建账号。",
|
||||
"login.noApiNote": "请使用提供原生 API 的 honk 构建。",
|
||||
"login.noApiTitle": "此 honk 构建未提供原生 API",
|
||||
"login.noApiNote": "请使用提供原生 API 的后端构建。",
|
||||
"login.noApiTitle": "此后端未提供原生 API",
|
||||
"login.note": "{backend} 要求提供 Bearer Token;Token 仅保存在此浏览器中,并随每个请求的 Authorization 请求头发送。",
|
||||
"login.password": "密码",
|
||||
"login.passwordLong": "密码超过 128 个字符。",
|
||||
@@ -934,7 +942,7 @@
|
||||
"nodes.latency.unmeasuredList": "尚未测量({n} 个):{names}",
|
||||
"nodes.link": "节点链接",
|
||||
"nodes.linkInvalid": "节点链接须为 协议://… 格式,例如 ss://、vmess://、vless://、trojan://、hysteria2://",
|
||||
"nodes.linkRejected": "honk 无法读取此链接:{reason}",
|
||||
"nodes.linkRejected": "{backendNameSubject} 无法读取此链接:{reason}",
|
||||
"nodes.linkTooLong": "添加节点的链接最多 {n} 个字符;更长的链接请在配置编辑器中写入",
|
||||
"nodes.manual.advanced": "高级",
|
||||
"nodes.manual.congestion": "拥塞控制",
|
||||
@@ -1051,7 +1059,7 @@
|
||||
"nodes.xhttp.headerDuplicate": "Header 名称不能重复(不区分大小写)。",
|
||||
"nodes.xhttp.headerName": "Header {n} 名称",
|
||||
"nodes.xhttp.headerValue": "Header {n} 值",
|
||||
"nodes.xhttp.help": "留空使用所示默认值。honk 保存时校验,修改选项会改变节点 ID。",
|
||||
"nodes.xhttp.help": "留空使用所示默认值。{backendNameSubject} 保存时校验,修改选项会改变节点 ID。",
|
||||
"nodes.xhttp.host": "HTTP host",
|
||||
"nodes.xhttp.mode": "模式",
|
||||
"nodes.xhttp.noGrpcHeader": "省略 gRPC 内容类型(noGRPCHeader)",
|
||||
@@ -1155,7 +1163,7 @@
|
||||
"ov.lim.mainReadOnly": "主配置文件含有 native API 或监听器的密钥,honk 不会写回含密钥的文件。请将密钥移至单独的 include 文件。",
|
||||
"ov.lim.manage": "节点与节点来源",
|
||||
"ov.lim.mode": "出站模式",
|
||||
"ov.lim.notRunningReason": "honk 正在启动或停止。",
|
||||
"ov.lim.notRunningReason": "{backendNameSubject} 正在启动或停止。",
|
||||
"ov.lim.noticeSetting": "状态卡显示设置",
|
||||
"ov.lim.recordOff": "这些记录默认为开启。在配置中加入以下设置,然后重启 honk。",
|
||||
"ov.lim.restore": "修订恢复",
|
||||
@@ -1205,8 +1213,8 @@
|
||||
"ov.status.datapathFailed": "{status},数据路径故障",
|
||||
"ov.succeeded": "已完成",
|
||||
"ov.suspend": "暂停",
|
||||
"ov.suspendHelp": "代理会停止,直到恢复 honk。",
|
||||
"ov.suspendTitle": "暂停 honk",
|
||||
"ov.suspendHelp": "代理会停止,直到恢复 {backendName}。",
|
||||
"ov.suspendTitle": "暂停 {backendName}",
|
||||
"ov.unavailable": "此后端不提供该项数据",
|
||||
"ov.unknown": "未知",
|
||||
"ov.unknownHelp": "后端未确认此项状态。",
|
||||
@@ -1613,6 +1621,7 @@
|
||||
"rule.template.homeboundSummary": "通过专用组连接中国大陆。",
|
||||
"rule.template.mode": "分流方式",
|
||||
"rule.template.more": "更多模板",
|
||||
"rule.template.needsGroups": "应用模板前,请先在组模块中创建以下组:{groups}。",
|
||||
"rule.template.networkManagerDirect": "NetworkManager 直连",
|
||||
"rule.template.networkManagerDirectHelp": "仅使用 NetworkManager 的 Linux 桌面需要,路由器不需要。",
|
||||
"rule.template.networkManagerOff": "NetworkManager 流量将遵循分流规则。",
|
||||
@@ -1706,7 +1715,7 @@
|
||||
"settings.geodataCronCustom": "此 cron 表达式来自配置文件或 API。",
|
||||
"settings.geodataCustom": "自定义",
|
||||
"settings.geodataCustomUrls": "自定义网址",
|
||||
"settings.geodataDailyHelp": "honk 设备的本地时间,更新会在之后一小时内开始。",
|
||||
"settings.geodataDailyHelp": "{backendNameModifier} 设备的本地时间,更新会在之后一小时内开始。",
|
||||
"settings.geodataDailyHour": "每日更新时间",
|
||||
"settings.geodataDetails": "详细信息",
|
||||
"settings.geodataEdit": "编辑",
|
||||
@@ -1806,7 +1815,7 @@
|
||||
"settings.probeWarmth": "连接",
|
||||
"settings.probeWarmthHelp": "冷探测建立新连接,结果包含建立连接的时间。",
|
||||
"settings.probes": "延迟探测",
|
||||
"settings.probesChecks": "后台健康检查的检查 URL 与间隔属于 honk 配置。",
|
||||
"settings.probesChecks": "后台健康检查的检查 URL 与间隔属于 {backendNameModifier} 配置。",
|
||||
"settings.probesConfig": "在配置中编辑健康检查",
|
||||
"settings.probesNote": "保存在此浏览器。探测按钮使用这些设置,探测选项对话框也以此为初始值。",
|
||||
"settings.probesUnavailable": "此后端不提供延迟探测",
|
||||
@@ -1908,9 +1917,9 @@
|
||||
"shell.macShortcut": "⌘K",
|
||||
"shell.notOffered": "此后端不提供该页面",
|
||||
"shell.rateLimited": "已达请求次数上限:{n} 秒后重试",
|
||||
"shell.reloadEngine": "重载 honk",
|
||||
"shell.reloadHelp": "honk 会重新读取配置文件并重载。暂存的规则不会写入。",
|
||||
"shell.reloadTitle": "重载 honk?",
|
||||
"shell.reloadEngine": "重载 {backendName}",
|
||||
"shell.reloadHelp": "{backendNameSubject} 会重新读取配置文件并重载。暂存的规则不会写入。",
|
||||
"shell.reloadTitle": "重载 {backendName}?",
|
||||
"shell.report": "报告问题",
|
||||
"shell.search": "搜索页面、连接、节点、组、节点来源和配置文件",
|
||||
"shell.searchUnavailable": "无法打开搜索:搜索功能加载失败。",
|
||||
@@ -2032,6 +2041,9 @@
|
||||
"ui.backend.unsupportedMediaType": "不支持此媒体类型",
|
||||
"ui.backend.unsupportedValue": "不支持此设置值",
|
||||
"ui.backendMessage": "后端消息:{message}",
|
||||
"ui.backendName": "后端",
|
||||
"ui.backendNameModifier": "后端",
|
||||
"ui.backendNameSubject": "后端",
|
||||
"ui.backendUrl": "后端网址",
|
||||
"ui.block": "block",
|
||||
"ui.cache": "缓存",
|
||||
@@ -2114,15 +2126,17 @@
|
||||
"ui.refresh": "刷新",
|
||||
"ui.refreshFailed": "无法刷新数据",
|
||||
"ui.refreshed": "数据已刷新。",
|
||||
"ui.refusal.configurationUnavailable": "配置服务不可用。请检查 honk 的配置和服务状态,然后重试。",
|
||||
"ui.refusal.credentialSourcesChanged": "声明 API 密钥的配置源已更改。请重新加载 honk,然后重试。",
|
||||
"ui.refusal.configurationUnavailable": "配置服务不可用。请检查 {backendName} 的配置和服务状态,然后重试。",
|
||||
"ui.refusal.credentialSourcesChanged": "声明 API 密钥的配置源已更改。请重新加载 {backendName},然后重试。",
|
||||
"ui.refusal.importEntryChanged": "导入入口与当前数据库入口不同。请使用 -c 指定当前入口启动 honk,然后重试导入。",
|
||||
"ui.refusal.listenerSecretInContent": "文件内容或源路径包含 API 密钥值。请使用未在其他位置出现的随机密钥,然后重启 honk 并重新登录。",
|
||||
"ui.refusal.listenerSecretInContent": "为保护 API 密钥,后端拒绝此更改。请检查文件和 {backendName} 的 API 设置。",
|
||||
"ui.refusal.listenerSecretInContentHonk": "文件内容或源路径包含 API 密钥值。请使用未在其他位置出现的随机密钥,然后重启 honk 并重新登录。",
|
||||
"ui.refusal.listenerSecretSource": "此文件声明了监听器密钥,或此次写入会新增此类声明。请在磁盘上编辑此文件。",
|
||||
"ui.refusal.listenerSettingsChanged": "此更改会修改受保护的监听器设置或数据库目录。在此写入时,请保持 experimental.native_api、clash_api.secret 和 global.data_dir 不变。",
|
||||
"ui.refusal.storeBlocked": "失败的配置修订阻止写入。请激活最新修订后重试。",
|
||||
"ui.refusal.unsafePath": "配置存储拒绝了目标路径。请使用允许的配置目录中的常规文件,然后重试。",
|
||||
"ui.refusal.writesDisabled": "配置写入未启用。请启用 config_write,并配置 API 密钥或密码认证,然后重启 honk 并重新登录。",
|
||||
"ui.refusal.writesDisabled": "配置写入未启用。请检查 {backendName} 的写入设置。",
|
||||
"ui.refusal.writesDisabledHonk": "配置写入未启用。请启用 config_write,并配置 API 密钥或密码认证,然后重启 honk 并重新登录。",
|
||||
"ui.reloadPage": "重新加载",
|
||||
"ui.requestNote": "(request_id:{requestId})",
|
||||
"ui.required": "(必填)",
|
||||
@@ -2143,7 +2157,7 @@
|
||||
"ui.tcp": "TCP",
|
||||
"ui.theme": "主题",
|
||||
"ui.time": "时间",
|
||||
"ui.trafficUncounted": "只计入经过 honk 转发的流量;由内核直接转发的直连连接不计入。",
|
||||
"ui.trafficUncounted": "只计入经过 {backendName} 转发的流量;由内核直接转发的直连连接不计入。",
|
||||
"ui.type": "类型",
|
||||
"ui.udp": "UDP",
|
||||
"ui.unavailable": "不可用",
|
||||
@@ -2157,7 +2171,7 @@
|
||||
"ui.wordmark": "字标",
|
||||
"ui.writeFailed": "无法写入配置",
|
||||
"ui.writeInvalid": "校验发现 {n} 个错误,未写入",
|
||||
"ui.writtenNotApplied": "已写入配置文件,但未生效,运行中的配置未变更。请修正文件后重载,或重启 honk",
|
||||
"ui.writtenNotApplied": "已写入配置文件,但未生效,运行中的配置未变更。请修正文件后重载,或重启 {backendName}",
|
||||
"ui.writtenNotRead": "变更已保存,但无法重新读取配置。请重试以显示最新内容",
|
||||
"ui.yes": "是",
|
||||
"unit.byte": "{n} B",
|
||||
|
||||
+37
-23
@@ -114,6 +114,10 @@
|
||||
"config.changedMeanwhile": "組態已被變更或另一次寫入尚未完成,因此未寫入。請重新整理後重試",
|
||||
"config.changedOnDisk": "編輯期間磁碟上的檔案已變更,套用會覆蓋該變更。",
|
||||
"config.clean": "沒有診斷",
|
||||
"config.daeEntry": "入口檔案為唯讀。請編輯 config.d 下對應的模組檔案。",
|
||||
"config.daeLayout": "dae 只能寫入受管組態。入口檔案和 api.dae 須與 config.d 下的模組分開。",
|
||||
"config.daeRoutingReadOnly": "切換模式需要一個可寫入且能完整讀取的 routing 區段。否則請直接編輯分流組態檔案。",
|
||||
"config.daeWritesDisabled": "請在 api.dae 啟用 config_write,設定非空白的 secret,然後重新啟動 dae,才能寫入組態。",
|
||||
"config.diagnostic.bareCondition": "條件沒有函式呼叫,因此永遠不會相符",
|
||||
"config.diagnostic.braceWithoutSection": "右大括號沒有對應的區段開頭",
|
||||
"config.diagnostic.downloadGeodata": "下載地理資料",
|
||||
@@ -137,7 +141,7 @@
|
||||
"config.discard": "放棄修改",
|
||||
"config.discardHelp": "離開後,以下項目的未儲存修改將遺失:{drafts}。",
|
||||
"config.discardTitle": "放棄未套用的修改?",
|
||||
"config.diskAhead": "磁碟上的檔案與執行中的組態不同,因此未寫入。請重載 honk 以套用該檔案;若檔案變更了需重新啟動的設定,請重新啟動 honk",
|
||||
"config.diskAhead": "磁碟上的檔案與執行中的組態不同,因此未寫入。請重載 {backendName} 以套用該檔案;若檔案變更了需重新啟動的設定,請重新啟動 {backendName}",
|
||||
"config.draftBackend": "後端設定檔",
|
||||
"config.draftConfig": "設定檔",
|
||||
"config.draftDiagnostics": "目前草稿的診斷",
|
||||
@@ -254,7 +258,8 @@
|
||||
"config.openSourceAt": "開啟設定檔:{where}",
|
||||
"config.readOnly": "唯讀",
|
||||
"config.readOnlyAttempt": "此檔案唯讀",
|
||||
"config.readOnlyHelp": "後端未開放寫入組態。honk 須啟用 experimental.native_api.config_write,並設定密鑰或密碼登入。",
|
||||
"config.readOnlyHelp": "請檢查 {backendName} 的組態,確認是否已開放寫入。",
|
||||
"config.readOnlyHelpHonk": "後端未開放寫入組態。honk 須啟用 experimental.native_api.config_write,並設定密鑰或密碼登入。",
|
||||
"config.readOnlyNote": "後端未開放寫入組態,只能在此檢視。啟用方式見上方說明。",
|
||||
"config.redacted": "後端已遮蔽監聽密鑰的值",
|
||||
"config.refusedNote": "後端不接受寫入此檔案,只能在此檢視。",
|
||||
@@ -265,7 +270,8 @@
|
||||
"config.restart.copyFailed": "無法複製指令,請選取文字後自行複製",
|
||||
"config.restart.docs": "重新載入與重新啟動",
|
||||
"config.restart.effect": "需重新啟動才會生效",
|
||||
"config.restart.next": "請在主機上修改組態檔,再於該主機重新啟動 honk。此指令適用於 systemd,其他 init 系統見安裝指南。",
|
||||
"config.restart.next": "請在主機上修改組態檔,再於該主機重新啟動 {backendName}。",
|
||||
"config.restart.nextWithCommand": "請在主機上修改組態檔,再於該主機重新啟動 {backendName}。此指令適用於 systemd,其他 init 系統見安裝指南。",
|
||||
"config.restart.planned": "預計下個版本支援直接寫入,並提示重新啟動。",
|
||||
"config.restart.title": "{n} 項設定需重新啟動",
|
||||
"config.revisionHelp": "目前生效的組態內容的版本識別碼,內容變更並生效後會改變。",
|
||||
@@ -315,9 +321,9 @@
|
||||
"config.validateNoMain": "後端未回傳完整的主組態,因此無法驗證",
|
||||
"config.validateOther": "驗證只涵蓋主組態與其引入檔,不含此檔案",
|
||||
"config.warnings": "{n} 個警告",
|
||||
"config.writeHelp": "若載入後磁碟上的檔案已變更,honk 會拒絕寫入。",
|
||||
"config.writeHelp": "若載入後磁碟上的檔案已變更,{backendName} 會拒絕寫入。",
|
||||
"config.writeRestart": "{n} 項設定需重新啟動才會生效,未寫入",
|
||||
"config.writeRestartAbsent": "honk 拒絕寫入所指的 {n} 項設定不在設定檔裡。在設定檔明寫這些值,並重新啟動 honk 一次。",
|
||||
"config.writeRestartAbsent": "{backendName} 拒絕寫入所指的 {n} 項設定不在設定檔裡。在設定檔明寫這些值,並重新啟動 {backendName} 一次。",
|
||||
"conn.activeCount": "{n} 條進行中",
|
||||
"conn.addRuleFor": "為 {target} 新增路由規則",
|
||||
"conn.allDevices": "所有裝置",
|
||||
@@ -705,6 +711,7 @@
|
||||
"group.byRule": "由規則選入",
|
||||
"group.create": "建立",
|
||||
"group.customExpression": "自訂運算式",
|
||||
"group.daeNameStart": "名稱必須以英文字母或底線開頭,且不能使用保留前綴 must_。",
|
||||
"group.everyNode": "包含所有節點",
|
||||
"group.filterAnd": "AND",
|
||||
"group.filterKind.nameExact": "完整名稱",
|
||||
@@ -720,6 +727,7 @@
|
||||
"group.groupNameHint": "只能使用英文字母、數字、底線、句點與連字號。",
|
||||
"group.matchingNodes": "符合的節點",
|
||||
"group.memberCount": "{n} 個節點",
|
||||
"group.memberIndex": "成員索引(從 0 開始)",
|
||||
"group.nestedGroups": "子群組",
|
||||
"group.newGroup": "新增群組",
|
||||
"group.policy": "選擇方式",
|
||||
@@ -807,8 +815,8 @@
|
||||
"login.invalidCredentials": "使用者名稱或密碼錯誤。",
|
||||
"login.mismatch": "兩次輸入的密碼不一致。",
|
||||
"login.needsSetup": "後端尚未設定管理員,請先建立帳號。",
|
||||
"login.noApiNote": "請使用提供原生 API 的 honk 建置。",
|
||||
"login.noApiTitle": "此 honk 建置沒有提供原生 API",
|
||||
"login.noApiNote": "請使用提供原生 API 的後端建置。",
|
||||
"login.noApiTitle": "此後端未提供原生 API",
|
||||
"login.note": "{backend} 要求提供 Bearer Token;Token 僅儲存於此瀏覽器,並隨每個請求的 Authorization 標頭送出。",
|
||||
"login.password": "密碼",
|
||||
"login.passwordLong": "密碼超過 128 個字元。",
|
||||
@@ -934,7 +942,7 @@
|
||||
"nodes.latency.unmeasuredList": "尚未測量({n} 個):{names}",
|
||||
"nodes.link": "節點連結",
|
||||
"nodes.linkInvalid": "節點連結須為 協定://… 格式,例如 ss://、vmess://、vless://、trojan://、hysteria2://",
|
||||
"nodes.linkRejected": "honk 無法讀取此連結:{reason}",
|
||||
"nodes.linkRejected": "{backendNameSubject} 無法讀取此連結:{reason}",
|
||||
"nodes.linkTooLong": "新增節點的連結最多 {n} 個字元;更長的連結請在組態編輯器中寫入",
|
||||
"nodes.manual.advanced": "進階",
|
||||
"nodes.manual.congestion": "壅塞控制",
|
||||
@@ -1051,7 +1059,7 @@
|
||||
"nodes.xhttp.headerDuplicate": "Header 名稱不能重複(不區分大小寫)。",
|
||||
"nodes.xhttp.headerName": "Header {n} 名稱",
|
||||
"nodes.xhttp.headerValue": "Header {n} 值",
|
||||
"nodes.xhttp.help": "留空使用所示預設值。honk 儲存時驗證,變更選項會改變節點 ID。",
|
||||
"nodes.xhttp.help": "留空使用所示預設值。{backendNameSubject} 儲存時驗證,變更選項會改變節點 ID。",
|
||||
"nodes.xhttp.host": "HTTP host",
|
||||
"nodes.xhttp.mode": "模式",
|
||||
"nodes.xhttp.noGrpcHeader": "省略 gRPC 內容類型(noGRPCHeader)",
|
||||
@@ -1155,7 +1163,7 @@
|
||||
"ov.lim.mainReadOnly": "主設定檔含有 native API 或監聽器的密鑰,honk 不會寫回含密鑰的檔案。請將密鑰移至獨立的 include 檔案。",
|
||||
"ov.lim.manage": "節點與節點來源",
|
||||
"ov.lim.mode": "出站模式",
|
||||
"ov.lim.notRunningReason": "honk 正在啟動或停止。",
|
||||
"ov.lim.notRunningReason": "{backendNameSubject} 正在啟動或停止。",
|
||||
"ov.lim.noticeSetting": "狀態卡顯示設定",
|
||||
"ov.lim.recordOff": "這些記錄預設為開啟。在組態加入以下設定,然後重新啟動 honk。",
|
||||
"ov.lim.restore": "修訂還原",
|
||||
@@ -1205,8 +1213,8 @@
|
||||
"ov.status.datapathFailed": "{status},資料路徑故障",
|
||||
"ov.succeeded": "已完成",
|
||||
"ov.suspend": "暫停",
|
||||
"ov.suspendHelp": "代理會停止,直到恢復 honk。",
|
||||
"ov.suspendTitle": "暫停 honk",
|
||||
"ov.suspendHelp": "代理會停止,直到恢復 {backendName}。",
|
||||
"ov.suspendTitle": "暫停 {backendName}",
|
||||
"ov.unavailable": "此後端不提供該項資料",
|
||||
"ov.unknown": "未知",
|
||||
"ov.unknownHelp": "後端未確認此項狀態。",
|
||||
@@ -1613,6 +1621,7 @@
|
||||
"rule.template.homeboundSummary": "透過專用群組連線至中國大陸。",
|
||||
"rule.template.mode": "分流方式",
|
||||
"rule.template.more": "更多範本",
|
||||
"rule.template.needsGroups": "套用範本前,請先在群組模組建立以下群組:{groups}。",
|
||||
"rule.template.networkManagerDirect": "NetworkManager 直連",
|
||||
"rule.template.networkManagerDirectHelp": "僅使用 NetworkManager 的 Linux 桌面需要,路由器不需要。",
|
||||
"rule.template.networkManagerOff": "NetworkManager 流量將遵循分流規則。",
|
||||
@@ -1706,7 +1715,7 @@
|
||||
"settings.geodataCronCustom": "此 cron 表達式來自組態檔或 API。",
|
||||
"settings.geodataCustom": "自訂",
|
||||
"settings.geodataCustomUrls": "自訂網址",
|
||||
"settings.geodataDailyHelp": "honk 裝置的本地時間,更新會在其後一小時內開始。",
|
||||
"settings.geodataDailyHelp": "{backendNameModifier} 裝置的本地時間,更新會在其後一小時內開始。",
|
||||
"settings.geodataDailyHour": "每日更新時間",
|
||||
"settings.geodataDetails": "詳細資料",
|
||||
"settings.geodataEdit": "編輯",
|
||||
@@ -1806,7 +1815,7 @@
|
||||
"settings.probeWarmth": "連線",
|
||||
"settings.probeWarmthHelp": "冷探測建立新連線,結果包含建立連線的時間。",
|
||||
"settings.probes": "延遲探測",
|
||||
"settings.probesChecks": "背景健康檢查的檢查 URL 與間隔屬於 honk 組態。",
|
||||
"settings.probesChecks": "背景健康檢查的檢查 URL 與間隔屬於 {backendNameModifier} 組態。",
|
||||
"settings.probesConfig": "在組態中編輯健康檢查",
|
||||
"settings.probesNote": "儲存在此瀏覽器。探測按鈕使用這些設定,探測選項對話框也以此為初始值。",
|
||||
"settings.probesUnavailable": "此後端不提供延遲探測",
|
||||
@@ -1908,9 +1917,9 @@
|
||||
"shell.macShortcut": "⌘K",
|
||||
"shell.notOffered": "此後端不提供該頁面",
|
||||
"shell.rateLimited": "已達請求次數上限:{n} 秒後重試",
|
||||
"shell.reloadEngine": "重載 honk",
|
||||
"shell.reloadHelp": "honk 會重新讀取設定檔並重載。暫存的規則不會寫入。",
|
||||
"shell.reloadTitle": "重載 honk?",
|
||||
"shell.reloadEngine": "重載 {backendName}",
|
||||
"shell.reloadHelp": "{backendNameSubject} 會重新讀取設定檔並重載。暫存的規則不會寫入。",
|
||||
"shell.reloadTitle": "重載 {backendName}?",
|
||||
"shell.report": "回報問題",
|
||||
"shell.search": "搜尋頁面、連線、節點、群組、節點來源與設定檔",
|
||||
"shell.searchUnavailable": "無法開啟搜尋:搜尋功能載入失敗。",
|
||||
@@ -2032,6 +2041,9 @@
|
||||
"ui.backend.unsupportedMediaType": "不支援此媒體類型",
|
||||
"ui.backend.unsupportedValue": "不支援此設定值",
|
||||
"ui.backendMessage": "後端訊息:{message}",
|
||||
"ui.backendName": "後端",
|
||||
"ui.backendNameModifier": "後端",
|
||||
"ui.backendNameSubject": "後端",
|
||||
"ui.backendUrl": "後端網址",
|
||||
"ui.block": "block",
|
||||
"ui.cache": "快取",
|
||||
@@ -2114,15 +2126,17 @@
|
||||
"ui.refresh": "重新整理",
|
||||
"ui.refreshFailed": "無法重新整理資料",
|
||||
"ui.refreshed": "資料已重新整理。",
|
||||
"ui.refusal.configurationUnavailable": "設定服務無法使用。請檢查 honk 的設定和服務狀態,然後重試。",
|
||||
"ui.refusal.credentialSourcesChanged": "宣告 API 金鑰的設定來源已變更。請重新載入 honk,然後重試。",
|
||||
"ui.refusal.configurationUnavailable": "設定服務無法使用。請檢查 {backendName} 的設定和服務狀態,然後重試。",
|
||||
"ui.refusal.credentialSourcesChanged": "宣告 API 金鑰的設定來源已變更。請重新載入 {backendName},然後重試。",
|
||||
"ui.refusal.importEntryChanged": "匯入入口與目前資料庫入口不同。請使用 -c 指定目前入口啟動 honk,然後重試匯入。",
|
||||
"ui.refusal.listenerSecretInContent": "檔案內容或來源路徑包含 API 金鑰值。請使用未在其他位置出現的隨機金鑰,然後重新啟動 honk 並重新登入。",
|
||||
"ui.refusal.listenerSecretInContent": "為保護 API 金鑰,後端拒絕此變更。請檢查檔案及 {backendName} 的 API 設定。",
|
||||
"ui.refusal.listenerSecretInContentHonk": "檔案內容或來源路徑包含 API 金鑰值。請使用未在其他位置出現的隨機金鑰,然後重新啟動 honk 並重新登入。",
|
||||
"ui.refusal.listenerSecretSource": "此檔案宣告了監聽器金鑰,或此次寫入會新增此類宣告。請在磁碟上編輯此檔案。",
|
||||
"ui.refusal.listenerSettingsChanged": "此變更會修改受保護的監聽器設定或資料庫目錄。在此寫入時,請保持 experimental.native_api、clash_api.secret 和 global.data_dir 不變。",
|
||||
"ui.refusal.storeBlocked": "失敗的組態修訂阻止寫入。請啟用最新修訂後重試。",
|
||||
"ui.refusal.unsafePath": "設定儲存拒絕了目標路徑。請使用允許的設定目錄中的一般檔案,然後重試。",
|
||||
"ui.refusal.writesDisabled": "設定寫入未啟用。請啟用 config_write,並設定 API 金鑰或密碼驗證,然後重新啟動 honk 並重新登入。",
|
||||
"ui.refusal.writesDisabled": "設定寫入未啟用。請確認 {backendName} 的寫入設定。",
|
||||
"ui.refusal.writesDisabledHonk": "設定寫入未啟用。請啟用 config_write,並設定 API 金鑰或密碼驗證,然後重新啟動 honk 並重新登入。",
|
||||
"ui.reloadPage": "重新載入",
|
||||
"ui.requestNote": "(request_id:{requestId})",
|
||||
"ui.required": "(必填)",
|
||||
@@ -2143,7 +2157,7 @@
|
||||
"ui.tcp": "TCP",
|
||||
"ui.theme": "主題",
|
||||
"ui.time": "時間",
|
||||
"ui.trafficUncounted": "只計入經過 honk 轉發的流量;由核心直接轉發的直連連線不計入。",
|
||||
"ui.trafficUncounted": "只計入經過 {backendName} 轉發的流量;由核心直接轉發的直連連線不計入。",
|
||||
"ui.type": "類型",
|
||||
"ui.udp": "UDP",
|
||||
"ui.unavailable": "無法使用",
|
||||
@@ -2157,7 +2171,7 @@
|
||||
"ui.wordmark": "字標",
|
||||
"ui.writeFailed": "無法寫入組態",
|
||||
"ui.writeInvalid": "驗證發現 {n} 個錯誤,未寫入",
|
||||
"ui.writtenNotApplied": "已寫入設定檔,但未生效,執行中的組態未變更。請修正檔案後重載,或重新啟動 honk",
|
||||
"ui.writtenNotApplied": "已寫入設定檔,但未生效,執行中的組態未變更。請修正檔案後重載,或重新啟動 {backendName}",
|
||||
"ui.writtenNotRead": "變更已儲存,但無法重新讀取設定。請重試以顯示最新內容",
|
||||
"ui.yes": "是",
|
||||
"unit.byte": "{n} B",
|
||||
|
||||
+1
-2
@@ -45,8 +45,7 @@ export function Frame(props: FrameProps & {view: ShellModel}) {
|
||||
}
|
||||
|
||||
const rereadAll = () => void refetchAll();
|
||||
// Applying held rules and reloading honk are separate commands. The latest state is read through a ref so the memoised
|
||||
// top bar keeps one callback for each.
|
||||
// The latest command state is read through a ref so the memoised top bar keeps one callback for each action.
|
||||
function useCommands() {
|
||||
const t = useT();
|
||||
const capabilities = useCapabilities();
|
||||
|
||||
+21
-9
@@ -1,7 +1,7 @@
|
||||
import './install';
|
||||
import {lazy, Suspense, useCallback, useState, type ComponentProps, type ReactNode} from 'react';
|
||||
import {lazy, Suspense, useCallback, useMemo, useState, type ComponentProps, type ReactNode} from 'react';
|
||||
import {I18nProvider, RouterProvider} from 'react-aria-components';
|
||||
import {LangContext, LOCALE, RewordingContext, useT, withCatalogue, type Lang, type Key} from '../i18n';
|
||||
import {BackendNameContext, LangContext, LOCALE, RewordingContext, useT, withCatalogue, type Lang, type Key} from '../i18n';
|
||||
import {ConfirmDialog, Toasts, ErrorMessage, Loading, PageSkeleton, PageShapeContext, WaitScope} from '../ui/ui';
|
||||
import {DraftContext, draftLabels, useDraftGuard} from './draft';
|
||||
import {useModeDraft} from '../features/shared/useModeDraft';
|
||||
@@ -12,19 +12,20 @@ import {resolvedFlag} from '../features/shared/countryFlags';
|
||||
import {useCopyDiagnostics} from '../features/shared/useCopyDiagnostics';
|
||||
import {readSettings} from './preferences';
|
||||
import type {ToastPlacement} from './preferences';
|
||||
import {useShell, type ShellModel} from './useShell';
|
||||
import {useShell, type ShellModel, type ShellVersion} from './useShell';
|
||||
import {applyAppearance} from './useAppearance';
|
||||
import {paletteWords} from './palettes';
|
||||
import type {PaletteId} from './palettes';
|
||||
import {useShellController, useShellFrame, useStartupToasts} from './useShellController';
|
||||
import {LoadBoundary} from '../ui/LoadBoundary';
|
||||
import {preloadable} from '../ui/preloadable';
|
||||
import {expectsAccess} from '../api';
|
||||
import {features} from './registry';
|
||||
import {headingOf, navGroups} from './view';
|
||||
import {headingOf, navGroups, shellWords} from './view';
|
||||
import {PageHead} from './PageHead';
|
||||
import {useHeldScroll} from './heldScroll';
|
||||
import logo from '../logo.svg';
|
||||
import type {Frame, FrameProps} from './Frame';
|
||||
import {useVersion} from '../store';
|
||||
const FlagPicker = lazy(() => import('../ui/FlagPicker').then(module => ({default: module.FlagPicker})));
|
||||
|
||||
// Only a backend that refuses the request needs the sign-in forms, so they load on demand.
|
||||
@@ -40,6 +41,7 @@ export function stampAppearance() {
|
||||
export function Shell({lang: initial}: {lang: Lang}) {
|
||||
const {settings, lang, ap, route, query, go, confirming, discard, cancel, searchOpen, pickLang, openSearch, closeSearch, navigate, draft, mac} =
|
||||
useShellController(initial);
|
||||
const version = useVersion();
|
||||
const [flagTarget, setFlagTarget] = useState<{name: string} | null>(null);
|
||||
const editFlag = useCallback((name: string) => setFlagTarget({name}), []);
|
||||
const lookupFlag = useCallback((name: string) => resolvedFlag(name, ap.flagOverrides, ap.countryFlags), [ap.flagOverrides, ap.countryFlags]);
|
||||
@@ -47,7 +49,7 @@ export function Shell({lang: initial}: {lang: Lang}) {
|
||||
<LangContext.Provider value={lang}>
|
||||
<CountryFlagsContext.Provider value={lookupFlag}>
|
||||
<FlagEditingContext.Provider value={editFlag}>
|
||||
<RewordingContext.Provider value={paletteWords(ap.palette)}>
|
||||
<ShellText palette={ap.palette} backendName={version.data?.engine.name}>
|
||||
{/* The mirrored layout turns React Aria right to left too; the locale keeps its strings and formats. */}
|
||||
<I18nProvider locale={LOCALE[lang]} direction={ap.mirrored ? 'rtl' : undefined}>
|
||||
<RouterProvider navigate={navigate}>
|
||||
@@ -55,6 +57,7 @@ export function Shell({lang: initial}: {lang: Lang}) {
|
||||
<ModeDraftGuard />
|
||||
<ShellFrame
|
||||
settings={settings}
|
||||
version={version}
|
||||
lang={lang}
|
||||
pickLang={pickLang}
|
||||
ap={ap}
|
||||
@@ -89,13 +92,22 @@ export function Shell({lang: initial}: {lang: Lang}) {
|
||||
<ToastHost placement={ap.toastPlacement} route={route} />
|
||||
</RouterProvider>
|
||||
</I18nProvider>
|
||||
</RewordingContext.Provider>
|
||||
</ShellText>
|
||||
</FlagEditingContext.Provider>
|
||||
</CountryFlagsContext.Provider>
|
||||
</LangContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function ShellText({palette, backendName, children}: {palette: PaletteId; backendName: string | undefined; children: ReactNode}) {
|
||||
const words = useMemo(() => shellWords(palette, backendName), [palette, backendName]);
|
||||
return (
|
||||
<BackendNameContext.Provider value={backendName}>
|
||||
<RewordingContext.Provider value={words}>{children}</RewordingContext.Provider>
|
||||
</BackendNameContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
// The outbound mode staged in a widget or on Activity outlives the frame: a refused read that turns the tab to the
|
||||
// sign-in page still warns before the reload that signing in again starts.
|
||||
function ModeDraftGuard() {
|
||||
@@ -156,8 +168,8 @@ export function StartupFrame({route, children}: {route?: string; children: React
|
||||
);
|
||||
}
|
||||
|
||||
function ShellFrame(props: FrameProps) {
|
||||
const view = useShell(props.settings, props.route);
|
||||
function ShellFrame({version, ...props}: FrameProps & {version: ShellVersion}) {
|
||||
const view = useShell(props.settings, props.route, version);
|
||||
// Signing in takes the whole page: the shell around it would offer nothing that works yet.
|
||||
if (view.content.kind === 'login') return <SignIn {...props} view={view} content={view.content} />;
|
||||
// A failed read shows with its retry while the rest of startup still waits.
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
import {renderToStaticMarkup} from 'react-dom/server';
|
||||
import {expect, it} from 'vitest';
|
||||
import {LangContext, RewordingContext, translate, useT, type Key, type Lang} from '../i18n';
|
||||
import {DEFAULT_PALETTE, isPaletteId, paletteWords, palettes, type PaletteId} from './palettes';
|
||||
import {BackendNameContext, LangContext, RewordingContext, translate, useT, type Key, type Lang} from '../i18n';
|
||||
import {DEFAULT_PALETTE, isPaletteId, palettes, type PaletteId} from './palettes';
|
||||
import {shellWords} from './view';
|
||||
|
||||
function Message({messageKey}: {messageKey: Key}) {
|
||||
return useT()(messageKey);
|
||||
}
|
||||
const render = (lang: Lang, palette: PaletteId, key: Key) =>
|
||||
const render = (lang: Lang, palette: PaletteId, key: Key, backendName?: string) =>
|
||||
renderToStaticMarkup(
|
||||
<LangContext.Provider value={lang}>
|
||||
<RewordingContext.Provider value={paletteWords(palette)}>
|
||||
<Message messageKey={key} />
|
||||
</RewordingContext.Provider>
|
||||
<BackendNameContext.Provider value={backendName}>
|
||||
<RewordingContext.Provider value={shellWords(palette, backendName)}>
|
||||
<Message messageKey={key} />
|
||||
</RewordingContext.Provider>
|
||||
</BackendNameContext.Provider>
|
||||
</LangContext.Provider>
|
||||
);
|
||||
|
||||
@@ -36,6 +39,14 @@ it('reads the China and Halloween palette words for their statuses and the catal
|
||||
expect(render('zh-CN', DEFAULT_PALETTE, 'lifecycle.degraded')).toBe(translate('zh-CN', 'lifecycle.degraded'));
|
||||
});
|
||||
|
||||
it('reserves honk write recovery instructions for honk without replacing the palette words', () => {
|
||||
const palette = 'halloween/halloween';
|
||||
expect(render('en', palette, 'ui.refusal.writesDisabled', 'honk')).toContain('Enable config_write and configure an API secret or password authentication');
|
||||
expect(render('en', palette, 'ui.refusal.writesDisabled', 'dae')).toBe('Configuration writes are disabled. Check how to enable writes for dae.');
|
||||
expect(render('en', palette, 'ui.refusal.writesDisabled')).not.toMatch(/honk|config_write/);
|
||||
expect(render('en', palette, 'lifecycle.running', 'honk')).toBe('Haunting');
|
||||
});
|
||||
|
||||
it('offers the Glass materials in order, Clear included', () => {
|
||||
expect(palettes.filter(palette => palette.id.startsWith('glass/')).map(palette => palette.id)).toEqual([
|
||||
'glass/glass',
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {createContext, useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react';
|
||||
import {refetchAll, useCapabilities, useCredentialRefusal, useVersion} from '../store';
|
||||
import {refetchAll, useCapabilities, useCredentialRefusal} from '../store';
|
||||
import type {Settings} from './preferences';
|
||||
import type {Version} from '../api/model';
|
||||
import {useLang, useT} from '../i18n';
|
||||
import {toast, toastErrorDetail} from '../ui/ui';
|
||||
import {accessError, duckView, shellView, wordmark, type AboutView, type ShellView} from './view';
|
||||
@@ -14,10 +15,10 @@ export type ShellModel = ShellView & {
|
||||
wordmark: string;
|
||||
honk: () => void;
|
||||
};
|
||||
export function useShell(settings: Settings, route: string): ShellModel {
|
||||
export type ShellVersion = {data: Version | undefined; error: Error | null};
|
||||
export function useShell(settings: Settings, route: string, version: ShellVersion): ShellModel {
|
||||
const t = useT();
|
||||
const capabilities = useCapabilities();
|
||||
const version = useVersion();
|
||||
const refusal = useCredentialRefusal();
|
||||
const capabilityError = accessError(capabilities.error, refusal);
|
||||
const [spinning, setSpinning] = useState(false);
|
||||
|
||||
+13
-2
@@ -2,7 +2,7 @@ import {afterEach, beforeEach, expect, it, vi} from 'vitest';
|
||||
import {ApiError} from '../api/error';
|
||||
import {capabilitiesBase, version} from '../../mock/fixtures';
|
||||
import {readSettings} from './preferences';
|
||||
import {translate} from '../i18n';
|
||||
import {translate, type Translator} from '../i18n';
|
||||
import {accessError, shellView, topBarCommands} from './view';
|
||||
import {hubs, routePaths} from './routes';
|
||||
|
||||
@@ -105,7 +105,8 @@ it('puts every page in exactly one hub and shows the hubs as the navigation sect
|
||||
['Settings', ['config', 'settings']]
|
||||
]);
|
||||
});
|
||||
it('splits the top bar into apply for held rules and reload for honk', () => {
|
||||
it('keeps apply for held rules separate from reloading the backend', () => {
|
||||
const t: Translator = (key, params) => translate('en', key, params, undefined, undefined, version.engine.name);
|
||||
const none = {count: 0, label: '', busy: false};
|
||||
const two = {count: 2, label: t('rule.applyPending', {n: 2}), busy: false};
|
||||
expect(topBarCommands(none, true, false, t)).toEqual({apply: null, reload: {label: 'Reload honk', busy: false, blocked: false}});
|
||||
@@ -120,6 +121,16 @@ it('splits the top bar into apply for held rules and reload for honk', () => {
|
||||
expect(topBarCommands(two, true, true, t)).toMatchObject({apply: {blocked: true}, reload: {busy: true}});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['dae', 'Reload dae'],
|
||||
[undefined, 'Reload the backend']
|
||||
] as const)('labels reload for backend %s', (backendName, label) => {
|
||||
const commands = topBarCommands({count: 0, label: '', busy: false}, true, false, (key, params) =>
|
||||
translate('en', key, params, undefined, undefined, backendName)
|
||||
);
|
||||
expect(commands.reload?.label).toBe(label);
|
||||
});
|
||||
|
||||
it('routes a mock authentication refusal to sign-in after leaving offline Settings', async () => {
|
||||
const {createMockApi} = await import('../../mock');
|
||||
const api = createMockApi({signIn: true, session: 'rejected'});
|
||||
|
||||
+10
-5
@@ -5,11 +5,11 @@ import {ApiError} from '../api/error';
|
||||
import {expectsAccess} from '../api';
|
||||
import {isDemoApi} from '../api/profiles';
|
||||
import type {Scheme, Settings} from './preferences';
|
||||
import {palettes, type PaletteId} from './palettes';
|
||||
import {palettes, paletteWords, type PaletteId} from './palettes';
|
||||
import {defaultRoute, hubs, type PageProps} from './routes';
|
||||
import {LANGS, type Translator} from '../i18n';
|
||||
import {LANGS, type Rewording, type Translator} from '../i18n';
|
||||
import {features, navAvailable} from './registry';
|
||||
import {configOf} from '../api/engines';
|
||||
import {configOf, engineWords} from '../api/engines';
|
||||
import {href} from './route';
|
||||
|
||||
export type ShortcutView = {id: string; path: string; key: string; keys: string[]; label: string};
|
||||
@@ -218,8 +218,7 @@ function backendState(
|
||||
if (versionError) return ['warn', 'shell.backend.degraded'];
|
||||
return ['ok', 'shell.backend.connected'];
|
||||
}
|
||||
// The top bar's two commit commands. Apply writes the held rules and does nothing else; reload reloads honk and leaves
|
||||
// the held rules held. Each is null when it has nothing to do, and each waits while the other is running.
|
||||
// Apply writes held rules; reload leaves them held. Each waits while the other is running.
|
||||
export type TopBarCommands = {
|
||||
apply: {label: string; count: number; busy: boolean; blocked: boolean} | null;
|
||||
reload: {label: string; busy: boolean; blocked: boolean} | null;
|
||||
@@ -238,6 +237,12 @@ export function duckView(taps: number) {
|
||||
const painted = honked && (taps - 5) % 2 === 1;
|
||||
return {honked, painted, hop: taps > 0 && !painted, wordmark: wordmark(honked)};
|
||||
}
|
||||
export function shellWords(palette: PaletteId, backendName: string | undefined): Rewording | undefined {
|
||||
const words = paletteWords(palette);
|
||||
const backend = engineWords(backendName);
|
||||
return words && backend ? {...words, ...backend} : (words ?? backend);
|
||||
}
|
||||
|
||||
// The appearance menu: one section per run of palettes that share a group. Other only gathers its palettes, so their
|
||||
// names do not start with it.
|
||||
export function paletteMenu(t: Translator): PaletteSection[] {
|
||||
|
||||
@@ -16,7 +16,7 @@ vi.mock('react', () => ({
|
||||
}));
|
||||
vi.mock('../api/index', () => ({getApi: () => state.api}));
|
||||
vi.mock('./nodes', async importOriginal => ({...(await importOriginal<typeof import('./nodes')>()), useNodes: () => ({data: state.nodes})}));
|
||||
vi.mock('./runtime', () => ({useCapabilities: () => ({data: state.capabilities})}));
|
||||
vi.mock('./runtime', () => ({useCapabilities: () => ({data: state.capabilities}), useVersion: () => ({data: {engine: {name: 'honk'}}})}));
|
||||
vi.mock('./resource', () => ({
|
||||
useResource: <T>(resource: Resource<T>, {enabled = true} = {}) => {
|
||||
const name = normalizeResourceKey(resource.key);
|
||||
|
||||
+8
-5
@@ -9,7 +9,8 @@ import {activationError, etag, finished, settle, readBackUnconfirmed, useAction}
|
||||
import {useSharedControl} from './sharedControl';
|
||||
import {optionsProbe, probeChoices, probeFallback, useProbeOptions, type ProbeOptions} from './probeOptions';
|
||||
import {nodeIndex, useNodes} from './nodes';
|
||||
import {useCapabilities} from './runtime';
|
||||
import {engineOf} from '../api/engines';
|
||||
import {useCapabilities, useVersion} from './runtime';
|
||||
// A probe refused after some batches finished: the batches that did finish, and the error that stopped the rest.
|
||||
export type PartialProbeError = LocalError & {cause: unknown; partialResult: ProbeResult; completed: number; total: number};
|
||||
export async function probeGroup(
|
||||
@@ -107,6 +108,7 @@ export function useGroupControl(id: string, refetchGroups: () => unknown, refetc
|
||||
const stored = useProbeOptions();
|
||||
const api = getApi();
|
||||
const capabilities = useCapabilities().data;
|
||||
const engine = engineOf(useVersion().data);
|
||||
const own = useNodes(!shared).data;
|
||||
const nodes = shared ? shared.nodes : own;
|
||||
const resource = useResource({key: ['group', {id}], every: poll.inventory, fetch: signal => api.group(id, signal)}, {paused});
|
||||
@@ -144,7 +146,7 @@ export function useGroupControl(id: string, refetchGroups: () => unknown, refetc
|
||||
: [null],
|
||||
[resource.data, nodes, nested, leaves]
|
||||
);
|
||||
const request = optionsProbe(capabilities, {type: 'group', group_id: id}, stored, resource.data, protocols);
|
||||
const request = optionsProbe(capabilities, {type: 'group', group_id: id}, stored, resource.data, protocols, engine);
|
||||
const limits = capabilities?.resources.probes.limits;
|
||||
const canProbe =
|
||||
request !== null &&
|
||||
@@ -172,13 +174,14 @@ export function useGroupControl(id: string, refetchGroups: () => unknown, refetc
|
||||
return {
|
||||
...resource,
|
||||
data,
|
||||
engineId: engine.id,
|
||||
// The load error stays with the resource (shown inline); `actionError` is the last control that failed.
|
||||
actionError: action.error,
|
||||
network,
|
||||
setNetwork,
|
||||
busy: action.busy,
|
||||
canProbe,
|
||||
probeChoices: resource.data ? probeChoices(capabilities, 'group', resource.data, protocols) : [],
|
||||
probeChoices: resource.data ? probeChoices(capabilities, 'group', resource.data, protocols, engine) : [],
|
||||
select: useCallback(
|
||||
(member_id: string) => run('selection', signal => api.selectGroup(id, {member_id, network}, signal).catch(readBackUnconfirmed(refetchShown, signal))),
|
||||
[api, id, network, run, refetchShown]
|
||||
@@ -193,7 +196,7 @@ export function useGroupControl(id: string, refetchGroups: () => unknown, refetc
|
||||
if (!capabilities || !resource.data || (!options && !canProbe)) throw new LocalError('ui.probeUnsupported');
|
||||
try {
|
||||
const chosen = options ?? stored;
|
||||
const request = optionsProbe(capabilities, {type: 'group', group_id: id}, chosen, resource.data, protocols);
|
||||
const request = optionsProbe(capabilities, {type: 'group', group_id: id}, chosen, resource.data, protocols, engine);
|
||||
const result = await probeGroup(api, capabilities, resource.data, signal, request);
|
||||
return {...result, fallback: request ? probeFallback(chosen.choice, request) : undefined};
|
||||
} catch (error) {
|
||||
@@ -201,7 +204,7 @@ export function useGroupControl(id: string, refetchGroups: () => unknown, refetc
|
||||
throw error;
|
||||
}
|
||||
}),
|
||||
[api, id, capabilities, resource.data, protocols, stored, canProbe, run, refetchShown]
|
||||
[api, id, capabilities, engine, resource.data, protocols, stored, canProbe, run, refetchShown]
|
||||
),
|
||||
patchConfig: patch,
|
||||
// Turning off a value the group never set clears it again rather than writing false.
|
||||
|
||||
+12
-1
@@ -1,5 +1,6 @@
|
||||
import {useCallback, useMemo} from 'react';
|
||||
import {useCapabilities} from './runtime';
|
||||
import {useCapabilities, useVersion} from './runtime';
|
||||
import {engineOf, type Engine} from '../api/engines';
|
||||
import {useConfig, useConfigEditor, useSourceComplete, type ConfigTransform} from './config';
|
||||
import type {ConfigDiagnostic, ConfigSource} from '../api/model';
|
||||
import {LocalError} from '../api/error';
|
||||
@@ -8,6 +9,7 @@ import {offered} from '../api/capabilities';
|
||||
// Apply small main-source edits through shared preparation, optional full validation, If-Match write, and reload.
|
||||
export type MainSourceEdit = {
|
||||
main: ConfigSource | null;
|
||||
groupTarget?: ConfigSource | null;
|
||||
// Whether the backend lets this page write at all: configuration content and writes both offered.
|
||||
writable: boolean;
|
||||
busy: boolean;
|
||||
@@ -19,6 +21,11 @@ export type MainSourceEdit = {
|
||||
// `invalid` keeps the diagnostics of the preflight, so the edit can say which lines were refused, as a refused write does.
|
||||
export type EditResult = {kind: 'ok'} | {kind: 'invalid'; diagnostics: ConfigDiagnostic[]} | {kind: 'cancelled'} | {kind: 'failed'; error: unknown};
|
||||
|
||||
// dae cmd/config_layout.go:90-104: a section belongs to one module, not necessarily the file named after it.
|
||||
export function groupWriteTarget(engine: Engine, sources: ConfigSource[]): ConfigSource | null {
|
||||
return engine.groupSource ? engine.groupSource(sources) : (sources.find(source => source.kind === 'main' && source.writable) ?? null);
|
||||
}
|
||||
|
||||
// `checking`: the main source is there and its completeness is still being checked, as after each write.
|
||||
export function useMainSourceEdit(): MainSourceEdit & {checking: boolean} {
|
||||
const resources = useCapabilities().data?.resources;
|
||||
@@ -28,12 +35,16 @@ export function useMainSourceEdit(): MainSourceEdit & {checking: boolean} {
|
||||
const source = config.data?.sources.find(source => source.kind === 'main' && source.writable) ?? null;
|
||||
const complete = useSourceComplete(source);
|
||||
const main = complete ? source : null;
|
||||
const engine = engineOf(useVersion().data);
|
||||
const target = useMemo(() => groupWriteTarget(engine, config.data?.sources ?? []), [engine, config.data]);
|
||||
const moduleComplete = useSourceComplete(target === source ? null : target);
|
||||
// While the digest check is still running nothing is wrong yet; the notice waits for a verdict.
|
||||
const incomplete = complete === false;
|
||||
const error = useMemo(() => config.error ?? (incomplete ? new LocalError('config.incomplete') : null), [config.error, incomplete]);
|
||||
const {apply} = editor;
|
||||
return {
|
||||
main,
|
||||
groupTarget: target === source ? main : moduleComplete ? target : null,
|
||||
checking: !!source && complete === null,
|
||||
writable,
|
||||
busy: editor.busy !== null,
|
||||
|
||||
@@ -6,10 +6,10 @@ import {useNodeProbe} from './nodes';
|
||||
import {capabilities} from '../../mock/fixtures';
|
||||
import {deferred} from './testHelpers';
|
||||
|
||||
const state = vi.hoisted(() => ({api: null as unknown as Api, cell: null as unknown as ReturnType<typeof actionCell>}));
|
||||
const state = vi.hoisted(() => ({engine: 'honk', api: null as unknown as Api, cell: null as unknown as ReturnType<typeof actionCell>}));
|
||||
vi.mock('react', async original => ({...(await original<typeof import('react')>()), useCallback: (callback: unknown) => callback}));
|
||||
vi.mock('../api/index', () => ({getApi: () => state.api}));
|
||||
vi.mock('./runtime', () => ({useCapabilities: () => ({data: capabilities})}));
|
||||
vi.mock('./runtime', () => ({useCapabilities: () => ({data: capabilities}), useVersion: () => ({data: {engine: {name: state.engine}}})}));
|
||||
vi.mock('./probeOptions', async original => ({
|
||||
...(await original<typeof import('./probeOptions')>()),
|
||||
useProbeOptions: () => ({choice: 'dns_udp', family: 'ipv6', cold: true, leaves: true})
|
||||
@@ -24,6 +24,7 @@ vi.mock('./action', async original => ({
|
||||
}));
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
state.engine = 'honk';
|
||||
state.api = createMockApi();
|
||||
state.cell = actionCell(state.api);
|
||||
});
|
||||
@@ -80,3 +81,22 @@ it('cancels active requests and never starts another node or publishes stale pro
|
||||
expect(state.api.startProbe).toHaveBeenCalledTimes(4);
|
||||
expect(progress).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sends cold single and batch probes for dae HTTP and SSR nodes even when warm is requested', async () => {
|
||||
state.engine = 'dae';
|
||||
const {nodes} = await state.api.nodes({limit: 2});
|
||||
const targets = nodes.map((node, i) => ({...node, protocol: i ? 'ssr' : 'http'}));
|
||||
const start = vi.spyOn(state.api, 'startProbe');
|
||||
const probe = useNodeProbe(vi.fn());
|
||||
const single = probe.probe(targets[0], {choice: 'dns_udp', family: 'ipv6', cold: false, leaves: false});
|
||||
await vi.runAllTimersAsync();
|
||||
await single;
|
||||
const batch = probe.probeMany(targets, vi.fn());
|
||||
await vi.runAllTimersAsync();
|
||||
await batch;
|
||||
expect(start.mock.calls.map(([{kind, warmth, transport}]) => [kind, warmth, transport])).toEqual([
|
||||
['dns', 'cold', ['udp']],
|
||||
['http', 'cold', ['tcp']],
|
||||
['http', 'cold', ['tcp']]
|
||||
]);
|
||||
});
|
||||
+6
-4
@@ -7,7 +7,8 @@ import {gated, pageSize, useResource, walk} from './resource';
|
||||
import {activationError, finished, settle, useAction, type SucceededResult} from './action';
|
||||
import {optionsProbe, probeChoices, probeDefaults, probeFallback, useProbeOptions} from './probeOptions';
|
||||
import {foldFamilies} from '../api/selectors';
|
||||
import {useCapabilities} from './runtime';
|
||||
import {engineOf} from '../api/engines';
|
||||
import {useCapabilities, useVersion} from './runtime';
|
||||
export function useNodes(enabled = true) {
|
||||
const api = getApi();
|
||||
return useResource(
|
||||
@@ -166,18 +167,19 @@ export function useNodeProbe(refetch: () => void) {
|
||||
const stored = useProbeOptions();
|
||||
const api = getApi();
|
||||
const capabilities = useCapabilities();
|
||||
const engine = engineOf(useVersion().data);
|
||||
const {busy, run, cancel} = useAction<string>({rethrow: true});
|
||||
const choices = useCallback((node: Node) => probeChoices(capabilities.data, 'node', undefined, [node.protocol]), [capabilities.data]);
|
||||
const choices = useCallback((node: Node) => probeChoices(capabilities.data, 'node', undefined, [node.protocol], engine), [capabilities.data, engine]);
|
||||
const one = useCallback(
|
||||
async (node: Node, options: typeof stored, signal: AbortSignal) => {
|
||||
const request = optionsProbe(capabilities.data, {type: 'node', node_id: node.id}, options, undefined, [node.protocol]);
|
||||
const request = optionsProbe(capabilities.data, {type: 'node', node_id: node.id}, options, undefined, [node.protocol], engine);
|
||||
if (!request) return;
|
||||
const accepted = await api.startProbe(request, signal);
|
||||
const result = await settle(api, accepted, signal);
|
||||
refetch();
|
||||
return {...finished(result, 'probe'), fallback: probeFallback(options.choice, request)};
|
||||
},
|
||||
[api, capabilities.data, refetch]
|
||||
[api, capabilities.data, engine, refetch]
|
||||
);
|
||||
const probe = useCallback((node: Node, options = stored) => run(node.id, signal => one(node, options, signal)), [stored, run, one]);
|
||||
const probeMany = useCallback(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {expect, it, vi} from 'vitest';
|
||||
import type {Capabilities, Group, ProbeRequest} from '../api/model';
|
||||
import {engineOf} from '../api/engines';
|
||||
import {latencyProbeChoice, optionsProbe, probeChoices, probeDefaults, readProbeOptions, saveProbeOptions, type ProbeOptions} from './probeOptions';
|
||||
import {storageKeys} from '../api/storage';
|
||||
|
||||
@@ -167,3 +168,18 @@ it('offers unknown UDP paths for groups but excludes a proven unsupported member
|
||||
});
|
||||
expect(probeChoices(caps, 'group', group, [...protocols, 'vmess']).map(choice => choice.id)).not.toContain('dns_udp');
|
||||
});
|
||||
|
||||
it.each(['dae', 'other'])('uses the %s probe capabilities without filtering by honk protocols', name => {
|
||||
const engine = engineOf({engine: {name, version: '1'}});
|
||||
const udpOnly: Capabilities = {...caps, resources: {...caps.resources, probes: {...caps.resources.probes, transports: ['udp']}}};
|
||||
for (const protocol of ['http', 'ssr']) {
|
||||
expect(probeChoices(caps, 'node', undefined, [protocol], engine).map(choice => choice.id)).toEqual([
|
||||
'http',
|
||||
'tcp_connect',
|
||||
'dns_tcp',
|
||||
'dns_udp',
|
||||
'dns_both'
|
||||
]);
|
||||
expect(probeChoices(udpOnly, 'node', undefined, [protocol], engine).map(choice => choice.id)).toEqual(['dns_udp']);
|
||||
}
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import {useSyncExternalStore} from 'react';
|
||||
import type {Capabilities, Group, ProbeRequest} from '../api/model';
|
||||
import type {StoragePort} from '../api/profiles';
|
||||
import {storageKeys} from '../api/storage';
|
||||
import {supportsNodeProbe} from '../dae/probes';
|
||||
import {honkProbes} from '../dae/probes';
|
||||
import type {Key} from '../i18n';
|
||||
|
||||
const choices = [
|
||||
@@ -62,14 +62,16 @@ export function probeChoices(
|
||||
capabilities: Capabilities | undefined,
|
||||
type: ProbeRequest['target']['type'],
|
||||
group?: Group,
|
||||
protocols?: Array<string | null>
|
||||
protocols?: Array<string | null>,
|
||||
engine = honkProbes
|
||||
): ProbeChoice[] {
|
||||
const probes = capabilities?.resources.probes;
|
||||
const accepts = engine.supportsNodeProbe;
|
||||
if (!probes?.available || !probes.targets?.includes(type) || !probes.ip_versions?.length) return [];
|
||||
return choices.filter(
|
||||
choice =>
|
||||
probes.kinds?.includes(choice.kind) &&
|
||||
(!protocols || protocols.every(protocol => supportsNodeProbe(protocol, choice.kind, choice.transport))) &&
|
||||
(!accepts || !protocols || protocols.every(protocol => accepts(protocol, choice.kind, choice.transport))) &&
|
||||
choice.transport.every(transport => probes.transports?.includes(transport) && (!group || group.capabilities.probe_transports.includes(transport)))
|
||||
);
|
||||
}
|
||||
@@ -79,10 +81,11 @@ export function optionsProbe(
|
||||
target: ProbeRequest['target'],
|
||||
options: ProbeOptions = probeDefaults,
|
||||
group?: Group,
|
||||
protocols?: Array<string | null>
|
||||
protocols?: Array<string | null>,
|
||||
engine = honkProbes
|
||||
): ProbeRequest | null {
|
||||
// A choice the target cannot carry falls back to HTTP, then to the first it can; probeFallback reports the swap.
|
||||
const choice = latencyProbeChoice(probeChoices(capabilities, target.type, group, protocols), options.choice);
|
||||
const choice = latencyProbeChoice(probeChoices(capabilities, target.type, group, protocols, engine), options.choice);
|
||||
if (!choice) return null;
|
||||
const versions = capabilities!.resources.probes.ip_versions!;
|
||||
const auto = versions.includes('ipv4') ? (versions.includes('ipv6') ? 'any' : 'ipv4') : 'ipv6';
|
||||
@@ -91,7 +94,7 @@ export function optionsProbe(
|
||||
kind: choice.kind,
|
||||
transport: [...choice.transport],
|
||||
ip_version: options.family !== 'auto' && versions.includes(options.family) ? options.family : auto,
|
||||
warmth: options.cold ? 'cold' : 'warm',
|
||||
warmth: options.cold || !engine.warmProbes ? 'cold' : 'warm',
|
||||
...(target.type === 'group' ? {members: options.leaves ? 'leaves' : 'direct'} : {})
|
||||
};
|
||||
return request;
|
||||
|
||||
Reference in new issue
Block a user