feat(nodes): set refresh interval, User-Agent and cache when adding a subscription

The add dialog shows each option the backend lists in create_options: the interval as the table's presets with the default preselected, the User-Agent with the default as placeholder, and the cache switch with a line of help. Only a value that differs from the default is sent, so an untouched entry stays one line. The e2e mock backend now serves provider create and refresh.
This commit is contained in:
Zakk committed 2026-09-25 23:09:34 +10:00
1 parent df9d024e0c
commit ca2b5be0fe
12 files changed
+192 -17

No files matched your search

+2
View File
@@ -157,6 +157,8 @@ export async function mockBackend(page: Page) {
else if (method === 'DELETE' && parts[0] === 'groups' && parts[2] === 'selection')
result = await api.clearGroupOverride(parts[1], url.searchParams.get('network') as 'tcp' | 'udp' | 'both');
else if (method === 'POST' && path === 'probes') result = await api.startProbe(request.postDataJSON());
else if (method === 'POST' && path === 'providers') result = await api.createProvider(request.postDataJSON());
else if (method === 'POST' && parts[0] === 'providers' && parts[2] === 'refresh') result = await api.refreshProvider(parts[1]);
else if (method === 'POST' && path === 'operations/reload') result = await api.startReload();
else if (method === 'PATCH' && path === 'runtime/settings') result = await api.patchRuntimeSettings(request.postDataJSON());
else if (method === 'POST' && path === 'operations/suspend') result = await api.startSuspend();
+40
View File
@@ -70,6 +70,46 @@ test('a subscription is added, refreshed at once, and removed with its nodes', a
await expect(sources.first()).toContainText('config.dae');
});
test('a subscription is added with its refresh interval, User-Agent and cache setting', async ({page}) => {
await page.goto('/#/nodes?tab=list');
await page.getByRole('button', {name: 'Add subscription', exact: true}).click();
const dialog = page.getByRole('dialog');
await dialog.getByLabel('Name').fill('sub-o');
await dialog.getByLabel('Subscription URL').fill('https://example.org/sub?token=abc');
await expect(dialog.getByRole('button', {name: 'Auto-refresh'})).toContainText('Every 24 hours');
await expect(dialog.getByLabel('User-Agent')).toHaveAttribute('placeholder', 'honk/0.0.1-alpha');
await expect(dialog.getByRole('switch', {name: 'Cache the subscription'})).toBeChecked();
await dialog.getByRole('button', {name: 'Auto-refresh'}).click();
await page.getByRole('option', {name: 'Every 6 hours', exact: true}).click();
await dialog.getByLabel('User-Agent').fill('agent\u00e9');
await expect(dialog.getByText('Up to 256 printable ASCII characters')).toBeVisible();
await expect(dialog.getByRole('button', {name: 'Add', exact: true})).toBeDisabled();
await dialog.getByLabel('User-Agent').fill('clash.meta');
await dialog.getByText('Cache the subscription').click();
await dialog.getByRole('button', {name: 'Add', exact: true}).click();
await expect(page.locator('.rp-toast.positive', {hasText: 'sub-o added and refreshed'})).toBeVisible();
await page.goto('/#/config?tab=source');
await expect(page.locator('.cm-content')).toContainText(
"sub-o: {\n url: 'https://example.org/sub?token=abc'\n ua: 'clash.meta'\n interval: '21600s'\n cache: false\n }"
);
});
test('an untouched option is left to the backend and an unadvertised one is not shown', async ({page}) => {
const {api, capabilities} = await mockBackend(page);
capabilities.resources.providers.create_options = {user_agent: 'honk/0.0.1-alpha'};
await page.goto('/#/nodes?tab=list');
await page.getByRole('button', {name: 'Add subscription', exact: true}).click();
const dialog = page.getByRole('dialog');
await expect(dialog.getByLabel('User-Agent')).toBeVisible();
await expect(dialog.getByRole('button', {name: 'Auto-refresh'})).toHaveCount(0);
await expect(dialog.getByRole('switch')).toHaveCount(0);
await dialog.getByLabel('Name').fill('sub-p');
await dialog.getByLabel('Subscription URL').fill('https://example.org/plain');
await dialog.getByRole('button', {name: 'Add', exact: true}).click();
await expect(page.locator('.rp-toast.positive', {hasText: 'sub-p added and refreshed'})).toBeVisible();
expect((await api.config()).sources.find(source => source.kind === 'main')!.content).toContain(" sub-p: 'https://example.org/plain'\n");
});
test('a node can be tested on its own', async ({page}) => {
await page.goto('/#/nodes?provider=inline');
await page.getByRole('button', {name: 'Test hk-01', exact: true}).click();
+3 -1
View File
@@ -123,7 +123,9 @@ it('writes subscription options as a block, checks them against create_options a
expect(await main()).toBe(before);
const created = await api.createProvider({name: 'optioned', ...base, update_interval: 3600, user_agent: 'clash.meta', cache: false});
expect(created).toMatchObject({name: 'optioned', url_redacted: 'https://example.net/sub?[redacted]'});
expect(await main()).toContain(" optioned: {\n url: 'https://example.net/sub?token=x'\n ua: 'clash.meta'\n interval: '3600s'\n cache: false\n }\n");
expect(await main()).toContain(
" optioned: {\n url: 'https://example.net/sub?token=x'\n ua: 'clash.meta'\n interval: '3600s'\n cache: false\n }\n"
);
await api.deleteProvider(created.id);
expect(await main()).toBe(before);
});
+5 -1
View File
@@ -250,7 +250,11 @@ export function createInventory(
)
throw new ApiError(422, 'unsupported_value', 'The subscription options are not supported');
// Like honk, an entry with options becomes a block; one without stays a scalar line.
const fields = [agent !== undefined && `ua: ${quote(agent)}`, interval !== undefined && `interval: '${interval}s'`, cache !== undefined && `cache: ${cache}`];
const fields = [
agent !== undefined && `ua: ${quote(agent)}`,
interval !== undefined && `interval: '${interval}s'`,
cache !== undefined && `cache: ${cache}`
];
const options = fields.filter(Boolean).map(field => ` ${field}\n`);
const line = configLine(() =>
options.length
+31 -1
View File
@@ -1,5 +1,5 @@
import {useT} from '../../i18n';
import {Button, ConfirmDialog, ErrorMessage, InlineAlert, ModalDialog, Tabs, TextField} from '../../ui/ui';
import {Button, ConfirmDialog, ErrorMessage, InlineAlert, LabeledSelect, ModalDialog, Switch, Tabs, TextField} from '../../ui/ui';
import {NodeLatency} from './Latency';
import type {PageProps} from '../../shell/routes';
import {ProviderTable} from './ProviderTable';
@@ -30,6 +30,8 @@ export function Nodes(props: PageProps) {
submitLabel,
groupHelp,
groupNameError,
agentError,
options,
policy,
setPolicy
} = useNodesPage(props);
@@ -90,6 +92,34 @@ export function Nodes(props: PageProps) {
placeholder="https://example.org/sub?token=…"
onChange={value => setForm({...form, value})}
/>
{options?.intervals && (
<LabeledSelect
label={t('nodes.interval')}
items={options.intervals}
value={options.interval}
isDisabled={pending}
onChange={interval => setForm({...form, interval})}
/>
)}
{options?.agent !== undefined && (
<TextField
isDisabled={pending}
label={t('nodes.agent')}
value={form.agent}
placeholder={options.agent}
error={agentError ?? undefined}
spellCheck={false}
onChange={agent => setForm({...form, agent})}
/>
)}
{options?.cache != null && (
<>
<Switch isSelected={options.cache} isDisabled={pending} onChange={cache => setForm({...form, cache})}>
{t('nodes.cache')}
</Switch>
<span className="rp-label">{t('nodes.cacheHelp')}</span>
</>
)}
</div>
)}
{dialog?.kind === 'group' && (
+12
View File
@@ -29,6 +29,10 @@ export const messages = defineMessages({
'nodes.add': '新增',
'nodes.name': '名稱',
'nodes.url': '訂閱網址',
'nodes.agent': 'User-Agent',
'nodes.agentInvalid': '最多 256 個可列印的 ASCII 字元',
'nodes.cache': '快取訂閱內容',
'nodes.cacheHelp': '保留最近一次取得的內容,啟動時無需連網即可載入。',
'nodes.added': '{name} 已新增',
'nodes.addedRefreshed': '{name} 已新增並重新整理,{n} 個節點',
'nodes.addedRefreshFailed': '{name} 已寫入組態,但無法重新整理:{error}',
@@ -116,6 +120,10 @@ export const messages = defineMessages({
'nodes.add': '添加',
'nodes.name': '名称',
'nodes.url': '订阅网址',
'nodes.agent': 'User-Agent',
'nodes.agentInvalid': '最多 256 个可打印的 ASCII 字符',
'nodes.cache': '缓存订阅内容',
'nodes.cacheHelp': '保留最近一次获取的内容,启动时无需联网即可加载。',
'nodes.added': '{name} 已添加',
'nodes.addedRefreshed': '{name} 已添加并刷新,{n} 个节点',
'nodes.addedRefreshFailed': '{name} 已写入配置,但无法刷新:{error}',
@@ -204,6 +212,10 @@ export const messages = defineMessages({
'nodes.add': 'Add',
'nodes.name': 'Name',
'nodes.url': 'Subscription URL',
'nodes.agent': 'User-Agent',
'nodes.agentInvalid': 'Up to 256 printable ASCII characters',
'nodes.cache': 'Cache the subscription',
'nodes.cacheHelp': 'Keeps the last fetched copy so it loads at startup without the network.',
'nodes.added': '{name} added',
'nodes.addedRefreshed': {one: '{name} added and refreshed, {n} node', other: '{name} added and refreshed, {n} nodes'},
'nodes.addedRefreshFailed': '{name} was written to the configuration, but could not be refreshed: {error}',
+18 -5
View File
@@ -9,7 +9,7 @@ import {isBareName} from '../../dae/text';
import {groupNameError, newGroupPolicies} from '../policies/policyText';
import type {PageProps} from '../../shell/routes';
import {readSubscriptions} from './subscriptions';
import {ownedNodes, providerRows, selectedProvider} from './view';
import {intervalItems, ownedNodes, providerCreate, providerRows, selectedProvider, type ProviderForm} from './view';
import {useProviderTable} from './useProviderTable';
import {useNodeTable} from './useNodeTable';
import {useDraftGuard} from '../../shell/draft';
@@ -18,13 +18,15 @@ import {errorText} from '../../api/error';
import {pickTab, tabQuery} from '../../shell/route';
import {offered} from '../../api/capabilities';
const blank: ProviderForm = {name: '', value: '', interval: '', agent: '', cache: null};
type NodeDialog =
{kind: 'provider'} | {kind: 'node'} | {kind: 'group'; item: Node} | {kind: 'removeProvider'; item: Provider} | {kind: 'removeNode'; item: Node};
export function useNodesPage({go, query}: PageProps) {
const t = useT();
const [dialog, setDialog] = useState<NodeDialog | null>(null);
const [form, setForm] = useState({name: '', value: ''});
const [form, setForm] = useState<ProviderForm>(blank);
const [policy, setPolicy] = useState(newGroupPolicies[0].id);
const session = useRef(0);
const submitting = useRef<NodeDialog | null>(null);
@@ -37,7 +39,7 @@ export function useNodesPage({go, query}: PageProps) {
});
const open = useCallback((next: NodeDialog) => {
session.current++;
setForm({name: '', value: ''});
setForm(blank);
setPolicy(newGroupPolicies[0].id);
setProblem(null);
setDialog(next);
@@ -93,7 +95,7 @@ export function useNodesPage({go, query}: PageProps) {
try {
if (dialog.kind === 'provider') {
// The backend's label for a subscription may be opaque; the toast names it as the user did.
const created = await manage.addProvider({name: form.name.trim(), kind: 'subscription', url: form.value.trim()});
const created = await manage.addProvider(providerCreate(form, createOptions));
if (!created) return;
const name = form.name.trim();
// The contract creates the provider unfetched; a refresh is what turns it into nodes.
@@ -160,9 +162,12 @@ export function useNodesPage({go, query}: PageProps) {
? t('nodes.newGroup')
: t(dialog.kind === 'removeProvider' ? 'nodes.removeProviderTitle' : 'nodes.removeNodeTitle', {name: dialog.item.name});
const nameError = dialog?.kind === 'group' ? groupNameError(form.name.trim(), groupNames, t) : null;
const createOptions = resources?.providers.create_options;
// The contract's User-Agent bound: up to 256 printable ASCII characters.
const agentError = /^[\x20-\x7E]{0,256}$/.test(form.agent.trim()) ? null : t('nodes.agentInvalid');
const formValid =
dialog?.kind === 'provider'
? isBareName(form.name.trim()) && isSubscriptionUrl(form.value)
? isBareName(form.name.trim()) && isSubscriptionUrl(form.value) && !agentError
: dialog?.kind === 'node'
? form.name.trim() !== '' && /^[a-z][a-z0-9+.-]*:\/\/\S+$/i.test(form.value.trim())
: dialog?.kind === 'group'
@@ -237,6 +242,14 @@ export function useNodesPage({go, query}: PageProps) {
groupHelp: dialog?.kind === 'group' ? t('nodes.newGroupHelp', {name: dialog.item.name}) : '',
// Only a name already typed is judged; an empty field is simply not ready.
groupNameError: form.name.trim() ? nameError : null,
agentError,
// Each option shows only when the backend lists it, with its default preselected or as the placeholder.
options: createOptions && {
intervals: createOptions.update_interval === undefined ? null : intervalItems(createOptions.update_interval, locale, t),
interval: form.interval || String(createOptions.update_interval),
agent: createOptions.user_agent,
cache: createOptions.cache === undefined ? null : (form.cache ?? createOptions.cache)
},
policy,
setPolicy: (next: string) => {
if (submitting.current !== dialog) setPolicy(next);
+46 -1
View File
@@ -1,7 +1,18 @@
import {describe, expect, it} from 'vitest';
import type {Node, ProbeResult, Provider} from '../../api/model';
import {readSubscriptions} from './subscriptions';
import {nodeRows, ownedNodes, providerRows, nodeRowView, probeToast, providerRowView, intervalText, selectedProvider} from './view';
import {
nodeRows,
ownedNodes,
providerRows,
nodeRowView,
probeToast,
providerRowView,
intervalText,
intervalItems,
providerCreate,
selectedProvider
} from './view';
import {translate, type Translator} from '../../i18n';
import {nodeFixtures} from '../../api/mock/fixtures';
import {formatBytes} from '../../i18n/format';
@@ -204,6 +215,40 @@ it('does not authorize writes from shared-host guesses or conflicting node tags'
expect(unspecified.intervals.map(item => item.id)).toEqual(['0', '3600', '21600', '43200', '86400']);
});
describe('providerCreate', () => {
const form = {name: ' sub-a ', value: ' https://example.org/sub ', interval: '', agent: '', cache: null};
const options = {update_interval: 86400, user_agent: 'honk/1.0', cache: true};
it('sends only the options that differ from the backend default', () => {
const base = {name: 'sub-a', kind: 'subscription', url: 'https://example.org/sub'};
expect(providerCreate(form, options)).toEqual(base);
expect(providerCreate({...form, interval: '86400', agent: ' honk/1.0 ', cache: true}, options)).toEqual(base);
expect(providerCreate({...form, interval: '0', agent: ' clash.meta ', cache: false}, options)).toEqual({
...base,
update_interval: 0,
user_agent: 'clash.meta',
cache: false
});
});
it('never sends an option the backend does not list', () => {
const chosen = {...form, interval: '3600', agent: 'clash.meta', cache: false};
expect(providerCreate(chosen, undefined)).toEqual({name: 'sub-a', kind: 'subscription', url: 'https://example.org/sub'});
expect(providerCreate(chosen, {user_agent: 'honk/1.0'})).toEqual({
name: 'sub-a',
kind: 'subscription',
url: 'https://example.org/sub',
user_agent: 'clash.meta'
});
});
it('offers the table presets and keeps a default outside them', () => {
expect(intervalItems(86400, 'en-US', t).map(item => item.id)).toEqual(['0', '3600', '21600', '43200', '86400']);
expect(intervalItems(7200, 'en-US', t).map(item => item.id)).toEqual(['0', '3600', '21600', '43200', '86400', '7200']);
expect(intervalItems(null, 'en-US', t).map(item => item.id)).toEqual(['0', '3600', '21600', '43200', '86400']);
});
});
it('falls back to the first real source when the linked provider is no longer listed', () => {
const {list} = providerRows([provider('a'), provider('b')], [], [], t);
expect(selectedProvider(list, 'b')).toBe('b');
+23 -8
View File
@@ -1,4 +1,4 @@
import type {Node, ProbeResult, Provider} from '../../api/model';
import type {Capabilities, Node, ProbeResult, Provider, ProviderCreate} from '../../api/model';
import {millis} from '../../api/u64';
import {compareLatency, healthMillis, preferredHealth} from '../../api/selectors';
import type {TableSort} from '../../ui/ui';
@@ -144,6 +144,27 @@ export function intervalText(seconds: number, locale: string, t: Translator) {
? t('nodes.everyHours', {n: formatNumber(seconds / 3600, locale)})
: formatDuration(String(seconds), locale);
}
// The presets, with a value outside them kept so a select can show it.
export function intervalItems(current: number | null, locale: string, t: Translator) {
return [0, ...intervals, ...(current === null || current === 0 || intervals.includes(current) ? [] : [current])].map(value => ({
id: String(value),
label: intervalText(value, locale, t)
}));
}
export type ProviderForm = {name: string; value: string; interval: string; agent: string; cache: boolean | null};
type CreateOptions = Capabilities['resources']['providers']['create_options'];
// An option left at the backend's default is not sent, so the entry stays a one-line scalar.
export function providerCreate(form: ProviderForm, options: CreateOptions): ProviderCreate {
const request: ProviderCreate = {name: form.name.trim(), kind: 'subscription', url: form.value.trim()};
const seconds = Number(form.interval);
if (options?.update_interval !== undefined && form.interval && seconds !== options.update_interval) request.update_interval = seconds;
const agent = form.agent.trim();
if (options?.user_agent !== undefined && agent && agent !== options.user_agent) request.user_agent = agent;
if (options?.cache !== undefined && form.cache !== null && form.cache !== options.cache) request.cache = form.cache;
return request;
}
export function providerRowView(item: ProviderRow, seconds: number | null | undefined, locale: string, t: Translator) {
const kinds: Record<ProviderRow['kind'], Key> = {
subscription: 'nodes.kind.subscription',
@@ -177,13 +198,7 @@ export function providerRowView(item: ProviderRow, seconds: number | null | unde
intervalValue: interval == null ? '' : String(interval),
hasInterval: interval !== undefined,
intervalLabel: t('nodes.intervalOf', {name}),
intervals:
interval === undefined
? []
: [0, ...intervals, ...(interval === null || intervals.includes(interval) || interval === 0 ? [] : [interval])].map(value => ({
id: String(value),
label: intervalText(value, locale, t)
})),
intervals: interval === undefined ? [] : intervalItems(interval, locale, t),
status: pseudo ? null : t(statuses[item.status]),
tone: tones[item.status],
error: item.last_error ? backendMessage(item.last_error.code, item.last_error.message, t) : undefined,
+4
View File
@@ -424,6 +424,10 @@ export const messages = {
'nodes.add': 'Add',
'nodes.name': 'Name',
'nodes.url': 'Subscription URL',
'nodes.agent': 'User-Agent',
'nodes.agentInvalid': 'Up to 256 printable ASCII characters',
'nodes.cache': 'Cache the subscription',
'nodes.cacheHelp': 'Keeps the last fetched copy so it loads at startup without the network.',
'nodes.added': '{name} added',
'nodes.addedRefreshed': {one: '{name} added and refreshed, {n} node', other: '{name} added and refreshed, {n} nodes'},
'nodes.addedRefreshFailed': '{name} was written to the configuration, but could not be refreshed: {error}',
+4
View File
@@ -408,6 +408,10 @@ export const messages = {
'nodes.add': '添加',
'nodes.name': '名称',
'nodes.url': '订阅网址',
'nodes.agent': 'User-Agent',
'nodes.agentInvalid': '最多 256 个可打印的 ASCII 字符',
'nodes.cache': '缓存订阅内容',
'nodes.cacheHelp': '保留最近一次获取的内容,启动时无需联网即可加载。',
'nodes.added': '{name} 已添加',
'nodes.addedRefreshed': '{name} 已添加并刷新,{n} 个节点',
'nodes.addedRefreshFailed': '{name} 已写入配置,但无法刷新:{error}',
+4
View File
@@ -407,6 +407,10 @@ export const messages = {
'nodes.add': '新增',
'nodes.name': '名稱',
'nodes.url': '訂閱網址',
'nodes.agent': 'User-Agent',
'nodes.agentInvalid': '最多 256 個可列印的 ASCII 字元',
'nodes.cache': '快取訂閱內容',
'nodes.cacheHelp': '保留最近一次取得的內容,啟動時無需連網即可載入。',
'nodes.added': '{name} 已新增',
'nodes.addedRefreshed': '{name} 已新增並重新整理,{n} 個節點',
'nodes.addedRefreshFailed': '{name} 已寫入組態,但無法重新整理:{error}',