A full-featured download manager.
feat(engine): add dns resolution mode with auto fallback (#1870)
Dr_rOot98fc3730ad85
diff --git a/.claude/rules/commit-and-quality.md b/.claude/rules/commit-and-quality.mdindex ffbdb392..2e869fc9 100644--- a/.claude/rules/commit-and-quality.md+++ b/.claude/rules/commit-and-quality.md@@ -10,10 +10,14 @@ Run all three commands and fix failures before committing:```bashpnpm run check:boundaries-pnpm exec biome check src/+pnpm run lintpnpm exec tsc --noEmit```+`pnpm run lint` (`biome check .`, scoped by biome.json) is the same command+CI runs — do not substitute a narrower path list, and never pipe it in a way+that discards its exit code.+`check:boundaries` is an automated baseline, not a complete architectureproof. Review changed imports against `architecture.md` as well.@@ -45,5 +49,5 @@ Run every check that matches the change:the relevant verifier. Follow workflow-supplied arguments for checks such as`check:update-artifacts`.-Use `pnpm exec biome check --write src/` only for reviewed, auto-fixable+Use `pnpm exec biome check --write .` only for reviewed, auto-fixableissues; re-run the required gate afterward.diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ab616c81..ae00805b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -108,14 +108,19 @@ jobs:- name: File naming conventionsrun: pnpm run check:file-names+ # Fingerprint the resolved Biome first: lint verdicts have disagreed+ # between runs with identical inputs before, and the version line is+ # the fastest way to tell a toolchain drift from a real finding.+ - name: Biome toolchain fingerprint+ run: |+ pnpm exec biome --version+ pnpm ls @biomejs/biome++ # Single source of truth for lint scope: package.json's `lint` script+ # (`biome check .`), bounded by biome.json. Keep this in lockstep with+ # the local commit gate in .claude/rules/commit-and-quality.md.- name: Lint- run: >-- pnpm exec biome check- src/ scripts/- packages/native-host/build.mjs- packages/native-host/build.test.mjs- packages/native-host/package-flatpak-companion.mjs- packages/native-host/package-flatpak-companion.test.mjs+ run: pnpm run lint- name: Native host JavaScript tooling testsrun: >-diff --git a/scripts/check-schema-parity.mjs b/scripts/check-schema-parity.mjsindex 868e3117..8b4e15a9 100644--- a/scripts/check-schema-parity.mjs+++ b/scripts/check-schema-parity.mjs@@ -41,7 +41,7 @@ for (const path of FACADES) {`drift: ${path} contains unexpected content beyond the re-export.`)const display =- stripped.length > 200 ? stripped.slice(0, 200) + '...' : stripped+ stripped.length > 200 ? `${stripped.slice(0, 200)}...` : strippedconsole.error(` residue: ${display}`)failed = true}diff --git a/src/core/engine/aria2/aria2-config-builder.test.ts b/src/core/engine/aria2/aria2-config-builder.test.tsindex 6faee4a0..1f9da08a 100644--- a/src/core/engine/aria2/aria2-config-builder.test.ts+++ b/src/core/engine/aria2/aria2-config-builder.test.ts@@ -609,4 +609,21 @@ describe('Aria2ConfigBuilder', () => {expect(idxBtSaveMetadata).toBeGreaterThan(idxSplit)})})++ describe('dns resolution mode', () => {+ it.each([+ ['auto', '--async-dns=true'],+ ['engine', '--async-dns=true'],+ ['system', '--async-dns=false'],+ ] as const)('emits %s as %s', (dnsMode, flag) => {+ const args = builder.buildArgs(+ makeEngineSettings({ dnsMode }),+ true,+ null,+ { download: 0, upload: 0 }+ )++ expect(args).toContain(flag)+ })+ })})diff --git a/src/core/engine/aria2/aria2-config-builder.ts b/src/core/engine/aria2/aria2-config-builder.tsindex 7c5b3838..016e900c 100644--- a/src/core/engine/aria2/aria2-config-builder.ts+++ b/src/core/engine/aria2/aria2-config-builder.ts@@ -2,6 +2,7 @@ import { access, copyFile, mkdir } from 'node:fs/promises'import path from 'node:path'import { proxyToAria2Options } from '@core/proxy/serializers'import type { EngineSettings, ProxySettings } from '@shared/types/settings'+import { dnsModeToAsyncDns } from './dns-fallback'export class Aria2ConfigBuilder {private readonly userConfPath: string@@ -105,6 +106,9 @@ export class Aria2ConfigBuilder {`--max-tries=${settings.maxTries}`,`--retry-wait=${settings.retryWait}`,`--lowest-speed-limit=${settings.lowestSpeedLimit}`,+ // 'auto' starts optimistic (async resolver); the runtime fallback+ // consumer flips it to false via changeGlobalOption when needed.+ `--async-dns=${dnsModeToAsyncDns(settings.dnsMode)}`,`--bt-max-peers=${settings.btMaxPeers}`,`--bt-enable-lpd=${settings.btEnableLpd}`,`--seed-ratio=${settings.seedRatio}`,diff --git a/src/core/engine/aria2/dns-fallback-consumer.test.ts b/src/core/engine/aria2/dns-fallback-consumer.test.tsnew file mode 100644index 00000000..94e69b43--- /dev/null+++ b/src/core/engine/aria2/dns-fallback-consumer.test.ts@@ -0,0 +1,187 @@+import { DownloadErrorCode } from '@shared/errors'+import type { DnsResolutionMode } from '@shared/types/settings'+import { TaskStatus } from '@shared/types/task'+import type { TaskTerminalOccurrence } from '@shared/types/task-occurrence'+import { describe, expect, it, vi } from 'vitest'+import { createDnsFallbackConsumer } from './dns-fallback'++const DNS_MESSAGE =+ 'CUID#11 - Name resolution for mikanani.me failed:Could not contact DNS servers'++function makeOccurrence(+ overrides?: Partial<TaskTerminalOccurrence>+): TaskTerminalOccurrence {+ return {+ occurrenceId: 'task-1:error:1000',+ type: 'terminal',+ taskId: 'task-1',+ fromStatus: TaskStatus.Downloading,+ toStatus: TaskStatus.Error,+ cause: 'engine',+ errorGroup: {+ errorCode: DownloadErrorCode.NetworkError,+ errorMessage: DNS_MESSAGE,+ errorDetailKey: null,+ errorDetailParams: null,+ },+ createdAt: 2000,+ ...overrides,+ }+}++function makeHarness(overrides?: {+ dnsMode?: DnsResolutionMode+ taskStatus?: TaskStatus | null+ startedAt?: number+}) {+ const applyAsyncDns = vi.fn().mockResolvedValue(undefined)+ const reAddTask = vi.fn().mockResolvedValue(undefined)+ const notify = vi.fn()+ const log = { info: vi.fn(), warn: vi.fn() }+ const consumer = createDnsFallbackConsumer({+ getDnsMode: () => overrides?.dnsMode ?? 'auto',+ getTaskStatus: () =>+ overrides?.taskStatus === undefined+ ? TaskStatus.Error+ : overrides.taskStatus,+ getTaskName: () => 'My Download',+ applyAsyncDns,+ reAddTask,+ notify,+ log,+ now: () => overrides?.startedAt ?? 1000,+ })+ return { consumer, applyAsyncDns, reAddTask, notify, log }+}++describe('createDnsFallbackConsumer', () => {+ it('falls back to the system resolver and retries the task once', async () => {+ const { consumer, applyAsyncDns, reAddTask, notify } = makeHarness()++ await consumer.consume(makeOccurrence())++ expect(applyAsyncDns).toHaveBeenCalledExactlyOnceWith(false)+ expect(reAddTask).toHaveBeenCalledExactlyOnceWith('task-1')+ expect(notify).toHaveBeenCalledOnce()+ expect(notify.mock.calls[0][0]).toMatchObject({+ sourceKey: 'dns-fallback:task-1:error:1000',+ kind: 'dns-fallback',+ taskId: 'task-1',+ titleParams: { name: 'My Download' },+ })+ })++ it('flips async-dns only once across different failing tasks', async () => {+ const { consumer, applyAsyncDns, reAddTask } = makeHarness()++ await consumer.consume(makeOccurrence())+ await consumer.consume(+ makeOccurrence({ occurrenceId: 'task-2:error:1001', taskId: 'task-2' })+ )++ expect(applyAsyncDns).toHaveBeenCalledTimes(1)+ expect(reAddTask).toHaveBeenCalledTimes(2)+ })++ it('never retries the same task twice', async () => {+ const { consumer, reAddTask } = makeHarness()++ await consumer.consume(makeOccurrence())+ await consumer.consume(+ makeOccurrence({ occurrenceId: 'task-1:error:3000', createdAt: 3000 })+ )++ expect(reAddTask).toHaveBeenCalledTimes(1)+ })++ it.each([+ ['system', 'system'],+ ['engine', 'engine'],+ ] as const)('does nothing when dnsMode is %s', async (_label, dnsMode) => {+ const { consumer, applyAsyncDns, reAddTask } = makeHarness({ dnsMode })++ await consumer.consume(makeOccurrence())++ expect(applyAsyncDns).not.toHaveBeenCalled()+ expect(reAddTask).not.toHaveBeenCalled()+ })++ it('ignores non-DNS network errors', async () => {+ const { consumer, reAddTask } = makeHarness()++ await consumer.consume(+ makeOccurrence({+ errorGroup: {+ errorCode: DownloadErrorCode.NetworkError,+ errorMessage: 'Connection reset by peer',+ errorDetailKey: null,+ errorDetailParams: null,+ },+ })+ )++ expect(reAddTask).not.toHaveBeenCalled()+ })++ it('ignores occurrences created before the consumer started', async () => {+ const { consumer, reAddTask } = makeHarness({ startedAt: 5000 })++ await consumer.consume(makeOccurrence({ createdAt: 2000 }))++ expect(reAddTask).not.toHaveBeenCalled()+ })++ it('ignores user cancellations, completions, and diagnosis occurrences', async () => {+ const { consumer, reAddTask } = makeHarness()++ await consumer.consume(makeOccurrence({ cause: 'user-cancel' }))+ await consumer.consume(+ makeOccurrence({ toStatus: TaskStatus.Completed, errorGroup: null })+ )+ await consumer.consume({+ occurrenceId: 'task-1:diag:1',+ type: 'diagnosis',+ taskId: 'task-1',+ terminalOccurrenceId: 'task-1:error:1000',+ revision: 1,+ diagnosis: {+ errorCode: DownloadErrorCode.NetworkError,+ errorMessage: DNS_MESSAGE,+ errorDetailKey: null,+ errorDetailParams: null,+ },+ createdAt: 2000,+ })++ expect(reAddTask).not.toHaveBeenCalled()+ })++ it('skips a task that is no longer in Error (already re-added or removed)', async () => {+ const { consumer, reAddTask } = makeHarness({ taskStatus: null })++ await consumer.consume(makeOccurrence())++ expect(reAddTask).not.toHaveBeenCalled()+ })++ it('swallows retry failures without throwing back to the dispatcher', async () => {+ const { consumer, reAddTask, log } = makeHarness()+ reAddTask.mockRejectedValueOnce(new Error('engine gone'))++ await expect(consumer.consume(makeOccurrence())).resolves.toBeUndefined()+ expect(log.warn).toHaveBeenCalled()+ })++ it('reset() re-arms the latch and per-task guard', async () => {+ const { consumer, applyAsyncDns, reAddTask } = makeHarness()++ await consumer.consume(makeOccurrence())+ consumer.reset()+ await consumer.consume(+ makeOccurrence({ occurrenceId: 'task-1:error:4000', createdAt: 4000 })+ )++ expect(applyAsyncDns).toHaveBeenCalledTimes(2)+ expect(reAddTask).toHaveBeenCalledTimes(2)+ })+})diff --git a/src/core/engine/aria2/dns-fallback.test.ts b/src/core/engine/aria2/dns-fallback.test.tsnew file mode 100644index 00000000..626d03a3--- /dev/null+++ b/src/core/engine/aria2/dns-fallback.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from 'vitest'+import { dnsModeToAsyncDns, isDnsContactFailure } from './dns-fallback'++// Messages reproduce aria2's MSG_NAME_RESOLUTION_FAILED format wrapping the+// exact ares_strerror() texts. Only c-ares *transport* failures qualify for+// a system-resolver fallback; deterministic answers (NXDOMAIN, no data) must+// never retrigger a retry.+describe('isDnsContactFailure', () => {+ it.each([+ 'CUID#11 - Name resolution for mikanani.me failed:Could not contact DNS servers',+ 'CUID#7 - Name resolution for example.com failed:Timeout while contacting DNS servers',+ 'CUID#3 - Name resolution for tracker.example failed:No DNS servers were configured',+ ])('matches transport failure %s', (message) => {+ expect(isDnsContactFailure(message)).toBe(true)+ })++ it.each([+ 'CUID#11 - Name resolution for nxdomain.example failed:Domain name not found',+ 'CUID#11 - Name resolution for a.example failed:DNS server returned answer with no data',+ 'CUID#11 - Name resolution for b.example failed:DNS server returned general failure',+ 'Connection refused by remote host',+ '',+ ])('does not match %s', (message) => {+ expect(isDnsContactFailure(message)).toBe(false)+ })++ it('does not match null', () => {+ expect(isDnsContactFailure(null)).toBe(false)+ })+})++describe('dnsModeToAsyncDns', () => {+ it.each([+ ['auto', true],+ ['engine', true],+ ['system', false],+ ] as const)('%s -> async-dns=%s', (mode, asyncDns) => {+ expect(dnsModeToAsyncDns(mode)).toBe(asyncDns)+ })+})diff --git a/src/core/engine/aria2/dns-fallback.ts b/src/core/engine/aria2/dns-fallback.tsnew file mode 100644index 00000000..538b1902--- /dev/null+++ b/src/core/engine/aria2/dns-fallback.ts@@ -0,0 +1,134 @@+import { NotificationKinds } from '@shared/types/notification'+import type { DnsResolutionMode } from '@shared/types/settings'+import { TaskStatus } from '@shared/types/task'+import type { TaskOccurrence } from '@shared/types/task-occurrence'++// Exact ares_strerror() texts for the c-ares failures that mean "the+// resolver could not reach any DNS server" — the only outcomes where the+// OS resolver may still succeed. Deterministic answers (NXDOMAIN, empty+// answer, SERVFAIL) are excluded: retrying them with another resolver+// cannot change the result.+const DNS_TRANSPORT_FAILURE_TEXTS = [+ 'Could not contact DNS servers',+ 'Timeout while contacting DNS servers',+ 'No DNS servers were configured',+] as const++export function isDnsContactFailure(+ errorMessage: string | null | undefined+): boolean {+ if (!errorMessage) return false+ return DNS_TRANSPORT_FAILURE_TEXTS.some((text) => errorMessage.includes(text))+}++export function dnsModeToAsyncDns(mode: DnsResolutionMode): boolean {+ return mode !== 'system'+}++export interface DnsFallbackDeps {+ getDnsMode(): DnsResolutionMode+ /** `null` when the task no longer exists. */+ getTaskStatus(taskId: string): TaskStatus | null+ getTaskName(taskId: string): string | null+ /** EngineSupervisor.applyAsyncDns — hot-flips aria2's `async-dns`. */+ applyAsyncDns(asyncDns: boolean): Promise<void>+ /** Re-adds an errored task as a fresh engine download. */+ reAddTask(taskId: string): Promise<unknown>+ /** NotificationCenter.notify — sourceKey dedups across redelivery. */+ notify(input: {+ sourceKey: string+ kind: string+ severity: 'info'+ titleKey: string+ titleParams?: Record<string, string>+ bodyKey?: string+ taskId?: string+ }): unknown+ log: {+ info(ctx: Record<string, unknown>, msg: string): void+ warn(ctx: Record<string, unknown>, msg: string): void+ }+ now?: () => number+}++export interface DnsFallbackConsumer {+ name: 'dns-fallback'+ consume(occ: TaskOccurrence): Promise<void>+ /** Re-arms the session latch — call when the user changes `dnsMode`. */+ reset(): void+}++/**+ * Occurrence consumer implementing the `auto` DNS mode: the first task+ * that errors with a c-ares transport failure flips the engine to the+ * system resolver for the rest of the session and is re-added once.+ *+ * Guards, in match order:+ * - only fresh terminal Error occurrences (startup redelivery of old+ * failures must not trigger surprise retries);+ * - only while `dnsMode` is `auto`;+ * - only c-ares transport failures (see `isDnsContactFailure`);+ * - once per task, and only while the task still sits in Error;+ * - all failures are logged, never rethrown — throwing would make the+ * dispatcher hold the occurrence for redelivery and loop.+ */+export function createDnsFallbackConsumer(+ deps: DnsFallbackDeps+): DnsFallbackConsumer {+ const startedAt = (deps.now ?? Date.now)()+ let fellBack = false+ const retriedTaskIds = new Set<string>()++ async function consume(occ: TaskOccurrence): Promise<void> {+ if (occ.type !== 'terminal') return+ if (occ.toStatus !== TaskStatus.Error) return+ if (occ.cause === 'user-cancel') return+ if (occ.createdAt < startedAt) return+ if (deps.getDnsMode() !== 'auto') return+ if (!isDnsContactFailure(occ.errorGroup?.errorMessage)) return+ if (retriedTaskIds.has(occ.taskId)) return+ if (deps.getTaskStatus(occ.taskId) !== TaskStatus.Error) return++ // Marked before any awaits: a failure below must not leave the task+ // eligible for another automatic retry.+ retriedTaskIds.add(occ.taskId)++ try {+ if (!fellBack) {+ await deps.applyAsyncDns(false)+ fellBack = true+ deps.log.info(+ { taskId: occ.taskId },+ 'dns fallback: switched engine to system resolver'+ )+ }+ await deps.reAddTask(occ.taskId)+ deps.notify({+ sourceKey: `dns-fallback:${occ.occurrenceId}`,+ kind: NotificationKinds.DnsFallback,+ severity: 'info',+ titleKey: 'notification.dnsFallback.title',+ titleParams: { name: deps.getTaskName(occ.taskId) ?? occ.taskId },+ bodyKey: 'notification.dnsFallback.body',+ taskId: occ.taskId,+ })+ } catch (err) {+ deps.log.warn(+ {+ taskId: occ.taskId,+ err: err instanceof Error ? err.message : String(err),+ },+ 'dns fallback attempt failed'+ )+ }+ }++ return {+ name: 'dns-fallback',+ consume,+ reset() {+ fellBack = false+ retriedTaskIds.clear()+ },+ }+}diff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.tsindex 3053cc3b..7c3703d7 100644--- a/src/core/engine/engine-supervisor.test.ts+++ b/src/core/engine/engine-supervisor.test.ts@@ -734,6 +734,28 @@ describe('EngineSupervisor', () => {})})+ describe('applyAsyncDns', () => {+ it('is a no-op unless Ready', async () => {+ await supervisor.applyAsyncDns(false)+ expect(rpcClient.changeGlobalOption).not.toHaveBeenCalled()+ })++ it.each([+ [false, 'false'],+ [true, 'true'],+ ] as const)(+ 'calls changeGlobalOption with async-dns=%s when Ready',+ async (asyncDns, wire) => {+ await supervisor.start('/usr/bin/aria2c')+ vi.mocked(rpcClient.changeGlobalOption).mockClear()+ await supervisor.applyAsyncDns(asyncDns)+ expect(rpcClient.changeGlobalOption).toHaveBeenCalledWith({+ 'async-dns': wire,+ })+ }+ )+ })+describe('applySpeedLimits', () => {it('is a no-op unless Ready', async () => {await supervisor.applySpeedLimits({ download: 100, upload: 50 })diff --git a/src/core/engine/engine-supervisor.ts b/src/core/engine/engine-supervisor.tsindex 3f6ff954..e05ea1f6 100644--- a/src/core/engine/engine-supervisor.ts+++ b/src/core/engine/engine-supervisor.ts@@ -145,6 +145,19 @@ export class EngineSupervisor {})}+ /**+ * HOT-update the aria2 DNS resolver via `aria2.changeGlobalOption`.+ * No-op when the engine is not Ready (cold start picks up the value via+ * `buildArgs`). Applies to new and waiting downloads only — active+ * downloads keep the resolver they started with.+ */+ async applyAsyncDns(asyncDns: boolean): Promise<void> {+ if (this.state !== EngineState.Ready) return+ await this.rpcClient.changeGlobalOption({+ 'async-dns': String(asyncDns),+ })+ }+/*** HOT-update the aria2 proxy via `aria2.changeGlobalOption`. No-op when* the engine is not Ready (cold start picks up proxy via `buildArgs`).diff --git a/src/main/index.ts b/src/main/index.tsindex 283ae43d..c4072111 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -5,6 +5,8 @@ import { Aria2Adapter } from '@core/engine/aria2/aria2-adapter'import { Aria2ConfigBuilder } from '@core/engine/aria2/aria2-config-builder'import { Aria2ProcessManager } from '@core/engine/aria2/aria2-process-manager'import { Aria2RpcClient } from '@core/engine/aria2/aria2-rpc-client'+import type { DnsFallbackConsumer } from '@core/engine/aria2/dns-fallback'+import { createDnsFallbackConsumer } from '@core/engine/aria2/dns-fallback'import { JsonRpcProtocol } from '@core/engine/aria2/json-rpc-protocol'import {PollingScheduler,@@ -365,6 +367,10 @@ let aria2Adapter: Aria2Adapter// Constructed in Phase 2 below (F4); see that construction site's comment// for the full must-reach registration/drain ordering rationale.let notificationCenter: NotificationCenter+// Constructed and registered in startEngineAndRestore; its task retry is+// late-bound by buildCommandHandlers to the ReAddTasks deps bundle.+let dnsFallbackConsumer: DnsFallbackConsumer | undefined+let dnsFallbackRetry: ((taskId: string) => Promise<unknown>) | undefinedlet trayHandle: ReturnType<typeof setupTray> | null = nulllet natManager: NatManager | null = nulllet trackerManager: TrackerManager | null = null@@ -998,6 +1004,22 @@ async function startEngineAndRestore(notificationConsumer.name,notificationConsumer.consume)+ dnsFallbackConsumer = createDnsFallbackConsumer({+ getDnsMode: () => settingsManager.get().engine.dnsMode,+ getTaskStatus: (id) => taskManager.getById(id)?.status ?? null,+ getTaskName: (id) => taskManager.getById(id)?.name ?? null,+ applyAsyncDns: (asyncDns) => supervisor.applyAsyncDns(asyncDns),+ reAddTask: (id) =>+ dnsFallbackRetry+ ? dnsFallbackRetry(id)+ : Promise.reject(new Error('dns fallback task retry not bound')),+ notify: (input) => notificationCenter.notify(input),+ log: getLogger('dns-fallback'),+ })+ occurrenceDispatcher.register(+ dnsFallbackConsumer.name,+ dnsFallbackConsumer.consume+ )try {await supervisor.start(platform.aria2BinaryPath)@@ -2105,6 +2127,10 @@ async function initializeMainProcess(): Promise<void> {const disposeCommandHandlers = registerCommandHandlers({cliToolService,supervisor,+ dnsFallback: { reset: () => dnsFallbackConsumer?.reset() },+ bindTaskRetry: (fn) => {+ dnsFallbackRetry = fn+ },sessionManager,settingsManager,protocolManager,diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex de320c50..5b691b51 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -3,6 +3,8 @@ import { access, rm } from 'node:fs/promises'import path from 'node:path'import { promisify } from 'node:util'import type { AdaptedMux } from '@core/bridge-receiver/submit-download-adapter'+import type { DnsFallbackConsumer } from '@core/engine/aria2/dns-fallback'+import { dnsModeToAsyncDns } from '@core/engine/aria2/dns-fallback'import type { EngineAdapter } from '@core/engine/engine-adapter'import type { EngineSupervisor } from '@core/engine/engine-supervisor'import { ENGINE_READY_TIMEOUT_MS } from '@core/engine/engine-supervisor'@@ -148,6 +150,14 @@ async function setLinuxDefaultTorrentHandler(): Promise<void> {export interface CommandContext {cliToolService: Pick<CliToolService, 'install'>supervisor: EngineSupervisor+ /** Session latch of the auto DNS fallback — reset when dnsMode changes. */+ dnsFallback?: Pick<DnsFallbackConsumer, 'reset'>+ /**+ * Late-binds the DNS fallback consumer's task retry to the same+ * `reAddTask` deps bundle the ReAddTasks command uses, so the two+ * paths cannot drift. Called synchronously during handler construction.+ */+ bindTaskRetry?: (fn: (taskId: string) => Promise<unknown>) => voidsessionManager: SessionManagersettingsManager: SettingsManagerprotocolManager: ReturnType<typeof createProtocolManager>@@ -240,6 +250,8 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {const {cliToolService,supervisor,+ dnsFallback,+ bindTaskRetry,sessionManager,settingsManager,protocolManager,@@ -408,6 +420,9 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {publishTaskUpdate,publishTaskUpdateNow,}+ // The DNS fallback consumer retries through the same deps bundle as+ // Commands.ReAddTasks so the automatic and user-initiated paths match.+ bindTaskRetry?.((id) => reAddTask(id, reAddDeps))const removeDeps = {taskManager,adapter,@@ -907,6 +922,15 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {trackerManager.applySyncScheduleChange()}+ if (oldFull.engine.dnsMode !== newFull.engine.dnsMode) {+ await supervisor.applyAsyncDns(+ dnsModeToAsyncDns(newFull.engine.dnsMode)+ )+ // Mode changes re-arm the auto fallback so a later switch back to+ // 'auto' starts optimistic again.+ dnsFallback?.reset()+ }+if (result.requiresRestart) {await supervisor.restart()}diff --git a/src/renderer/routes/settings/cards/network-dialog.test.tsx b/src/renderer/routes/settings/cards/network-dialog.test.tsxindex 5c2857c9..b044f2a1 100644--- a/src/renderer/routes/settings/cards/network-dialog.test.tsx+++ b/src/renderer/routes/settings/cards/network-dialog.test.tsx@@ -50,6 +50,9 @@ const FIXTURE = {autoDiagnostic: false,diagnosticIntervalSec: 3600,},+ engine: {+ dnsMode: 'auto',+ },}describe('<NetworkDialog>', () => {@@ -94,6 +97,33 @@ describe('<NetworkDialog>', () => {expect(onClose).toHaveBeenCalled()})+ it('changing dns resolution submits an engine dnsMode patch', async () => {+ const onClose = vi.fn()+ render(+ <NetworkDialog+ open+ onClose={onClose}+ labelKey="settings.cards.network.title"+ descKey="settings.cards.network.desc"+ />+ )+ await waitFor(() =>+ expect(+ screen.getByRole('heading', { name: /^dns$/i })+ ).toBeInTheDocument()+ )+ const user = userEvent.setup()+ await user.click(screen.getByRole('combobox', { name: /dns lookup/i }))+ await user.click(await screen.findByRole('option', { name: /system dns/i }))+ await user.click(screen.getByRole('button', { name: /apply/i }))+ await waitFor(() => {+ expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {+ engine: { dnsMode: 'system' },+ })+ })+ expect(onClose).toHaveBeenCalled()+ })+it('Import from system populates host/port/protocol', async () => {render(<NetworkDialogdiff --git a/src/renderer/routes/settings/cards/network-dialog.tsx b/src/renderer/routes/settings/cards/network-dialog.tsxindex c3d94c2c..96f5640e 100644--- a/src/renderer/routes/settings/cards/network-dialog.tsx+++ b/src/renderer/routes/settings/cards/network-dialog.tsx@@ -31,9 +31,14 @@ import { pickDirty } from '@renderer/lib/form-utils'import { transport } from '@renderer/lib/transport'import { Commands } from '@shared/protocol/commands'import { Queries } from '@shared/protocol/queries'-import { DEFAULT_NAT_SETTINGS, DEFAULT_PROXY_SETTINGS } from '@shared/schemas'+import {+ DEFAULT_ENGINE_SETTINGS,+ DEFAULT_NAT_SETTINGS,+ DEFAULT_PROXY_SETTINGS,+} from '@shared/schemas'import type {AppSettings,+ DnsResolutionMode,NatSettings,ProxySettings,} from '@shared/types/settings'@@ -47,13 +52,17 @@ import { ProxySection } from './proxy-section'export interface NetworkFields {proxy: ProxySettingsnat: NatSettings+ // Only the DNS slice of EngineSettings is edited here; the rest of the+ // engine namespace stays with the Downloads dialog.+ engine: { dnsMode: DnsResolutionMode }}-// Source of truth: src/shared/schemas/{proxy,nat}-settings.ts.-// Keep in sync with DEFAULT_PROXY_SETTINGS / DEFAULT_NAT_SETTINGS.+// Source of truth: src/shared/schemas/{proxy,nat,engine}-settings.ts.+// Keep in sync with the corresponding DEFAULT_* exports.const DEFAULTS: NetworkFields = {proxy: { ...DEFAULT_PROXY_SETTINGS },nat: { ...DEFAULT_NAT_SETTINGS },+ engine: { dnsMode: DEFAULT_ENGINE_SETTINGS.dnsMode },}const NAT_PROTOCOL_OPTIONS = [@@ -85,6 +94,12 @@ export function NetworkDialog({const { t } = useTranslation()const form = useForm<NetworkFields>({ defaultValues: DEFAULTS })+ const dnsModeOptions = [+ { value: 'auto', label: t('settings.network.dns.modeAuto') },+ { value: 'system', label: t('settings.network.dns.modeSystem') },+ { value: 'engine', label: t('settings.network.dns.modeEngine') },+ ] as const+// biome-ignore lint/correctness/useExhaustiveDependencies: form is stableuseEffect(() => {let cancelled = false@@ -94,7 +109,13 @@ export function NetworkDialog({if (cancelled) returnconst all = data as AppSettings | undefinedif (all?.proxy && all?.nat) {- form.reset({ proxy: all.proxy, nat: all.nat })+ form.reset({+ proxy: all.proxy,+ nat: all.nat,+ engine: {+ dnsMode: all.engine?.dnsMode ?? DEFAULT_ENGINE_SETTINGS.dnsMode,+ },+ })}}).catch(() => {@@ -134,6 +155,49 @@ export function NetworkDialog({<Separator className="my-4" />+ {/* DNS resolution */}+ <h3 className="text-sm font-semibold text-foreground">+ {t('settings.network.dns.title')}+ </h3>+ <FormField+ control={form.control}+ name="engine.dnsMode"+ render={({ field }) => (+ <FormItem className="flex items-start justify-between gap-4">+ <div className="space-y-1">+ <FormLabel>{t('settings.network.dns.mode')}</FormLabel>+ <FormDescription className="text-xs">+ {t('settings.network.dns.modeDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Select+ items={dnsModeOptions}+ value={field.value}+ onValueChange={(value) => {+ if (value !== null) field.onChange(value)+ }}+ >+ <SelectTrigger className="w-35" size="sm">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {dnsModeOptions.map(({ label, value }) => (+ <SelectItem key={value} value={value}>+ {label}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ </FormItem>+ )}+ />++ <Separator className="my-4" />+{/* NAT mapping */}<h3 className="text-sm font-semibold text-foreground">{t('settings.network.nat.title')}@@ -176,7 +240,7 @@ export function NetworkDialog({if (value !== null) field.onChange(value)}}>- <SelectTrigger className="w-32" size="sm">+ <SelectTrigger className="w-35" size="sm"><SelectValue /></SelectTrigger><SelectContent>diff --git a/src/server/index.ts b/src/server/index.tsindex 50189040..5f26967a 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -7,6 +7,7 @@ import { Aria2Adapter } from '@core/engine/aria2/aria2-adapter'import { Aria2ConfigBuilder } from '@core/engine/aria2/aria2-config-builder'import { Aria2ProcessManager } from '@core/engine/aria2/aria2-process-manager'import { Aria2RpcClient } from '@core/engine/aria2/aria2-rpc-client'+import { createDnsFallbackConsumer } from '@core/engine/aria2/dns-fallback'import { JsonRpcProtocol } from '@core/engine/aria2/json-rpc-protocol'import {PollingScheduler,@@ -827,10 +828,32 @@ async function main() {log,})+ // Auto DNS fallback: constructed here so the command context can reset+ // its latch; registered on the occurrence dispatcher further down with+ // the other consumers. The retry fn is late-bound by+ // buildServerCommandHandlers to the ReAddTasks deps bundle.+ let dnsFallbackRetry: ((taskId: string) => Promise<unknown>) | undefined+ const dnsFallbackConsumer = createDnsFallbackConsumer({+ getDnsMode: () => settingsManager.get().engine.dnsMode,+ getTaskStatus: (id) => taskManager.getById(id)?.status ?? null,+ getTaskName: (id) => taskManager.getById(id)?.name ?? null,+ applyAsyncDns: (asyncDns) => supervisor.applyAsyncDns(asyncDns),+ reAddTask: (id) =>+ dnsFallbackRetry+ ? dnsFallbackRetry(id)+ : Promise.reject(new Error('dns fallback task retry not bound')),+ notify: (input) => notificationCenter.notify(input),+ log: getLogger('dns-fallback'),+ })+// ─── HTTP App ─────────────────────────────────────────────────const commandHandlers = buildServerCommandHandlers({supervisor,settingsManager,+ dnsFallback: dnsFallbackConsumer,+ bindTaskRetry: (fn) => {+ dnsFallbackRetry = fn+ },rpcClient,adapter,trackerManager,@@ -1164,6 +1187,10 @@ async function main() {notificationConsumer.name,notificationConsumer.consume)+ occurrenceDispatcher.register(+ dnsFallbackConsumer.name,+ dnsFallbackConsumer.consume+ )await sessionManager.restore()if (!shellAsyncWork.isAccepting()) returndiff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.tsindex d2e024d4..c3f424d3 100644--- a/src/server/ipc/commands.test.ts+++ b/src/server/ipc/commands.test.ts@@ -44,7 +44,9 @@ function makeFakeCtx() {supervisor: {stop: vi.fn().mockResolvedValue(undefined),start: vi.fn().mockResolvedValue(undefined),+ applyAsyncDns: vi.fn().mockResolvedValue(undefined),} as unknown as EngineSupervisor,+ dnsFallback: { reset: vi.fn() },settingsManager: {get: vi.fn(),update: vi.fn(),@@ -142,7 +144,8 @@ function makeFakeCtx() {function makeSettings(proxy: typeof PROXY_OFF,- tracker: { sourcesEnabled?: boolean; blacklistEnabled?: boolean } = {}+ tracker: { sourcesEnabled?: boolean; blacklistEnabled?: boolean } = {},+ engine: { dnsMode?: 'auto' | 'system' | 'engine' } = {}) {return {proxy,@@ -151,6 +154,10 @@ function makeSettings(blacklistEnabled: true,...tracker,},+ engine: {+ dnsMode: 'auto',+ ...engine,+ },}}@@ -187,6 +194,39 @@ describe('server Commands.UpdateSettings', () => {expect(ctx.proxyApplier.apply).toHaveBeenCalledWith(PROXY_OFF, PROXY_ON)})+ it('hot-applies async-dns and resets the fallback latch when dnsMode changes', async () => {+ const ctx = makeFakeCtx()+ ;(ctx.settingsManager.get as ReturnType<typeof vi.fn>)+ .mockReturnValueOnce(makeSettings(PROXY_OFF, {}, { dnsMode: 'auto' }))+ .mockReturnValueOnce(makeSettings(PROXY_OFF, {}, { dnsMode: 'system' }))+ ;(ctx.settingsManager.update as ReturnType<typeof vi.fn>).mockResolvedValue(+ { ok: true, requiresRestart: false, changedRestartKeys: [] }+ )+ const handlers = buildServerCommandHandlers(+ ctx as Parameters<typeof buildServerCommandHandlers>[0]+ )+ await handlers[Commands.UpdateSettings]?.({ engine: { dnsMode: 'system' } })+ expect(ctx.supervisor.applyAsyncDns).toHaveBeenCalledExactlyOnceWith(false)+ expect(ctx.dnsFallback.reset).toHaveBeenCalledOnce()+ expect(ctx.supervisor.stop).not.toHaveBeenCalled()+ })++ it('leaves async-dns alone when dnsMode is unchanged', async () => {+ const ctx = makeFakeCtx()+ ;(ctx.settingsManager.get as ReturnType<typeof vi.fn>).mockReturnValue(+ makeSettings(PROXY_OFF)+ )+ ;(ctx.settingsManager.update as ReturnType<typeof vi.fn>).mockResolvedValue(+ { ok: true, requiresRestart: false, changedRestartKeys: [] }+ )+ const handlers = buildServerCommandHandlers(+ ctx as Parameters<typeof buildServerCommandHandlers>[0]+ )+ await handlers[Commands.UpdateSettings]?.({})+ expect(ctx.supervisor.applyAsyncDns).not.toHaveBeenCalled()+ expect(ctx.dnsFallback.reset).not.toHaveBeenCalled()+ })+it('restarts engine via stop+start when requiresRestart is true', async () => {const ctx = makeFakeCtx();(ctx.settingsManager.get as ReturnType<typeof vi.fn>).mockReturnValue(diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex 57fb05a5..8916939b 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -1,5 +1,7 @@import path from 'node:path'import type { Aria2RpcClient } from '@core/engine/aria2/aria2-rpc-client'+import type { DnsFallbackConsumer } from '@core/engine/aria2/dns-fallback'+import { dnsModeToAsyncDns } from '@core/engine/aria2/dns-fallback'import type { EngineAdapter } from '@core/engine/engine-adapter'import type { EngineSupervisor } from '@core/engine/engine-supervisor'import { ENGINE_READY_TIMEOUT_MS } from '@core/engine/engine-supervisor'@@ -64,6 +66,14 @@ import type { createServerProxyApplier } from '../proxy/wiring'export interface ServerCommandContext {supervisor: EngineSupervisorsettingsManager: SettingsManager+ /** Session latch of the auto DNS fallback — reset when dnsMode changes. */+ dnsFallback?: Pick<DnsFallbackConsumer, 'reset'>+ /**+ * Late-binds the DNS fallback consumer's task retry to the same+ * `reAddTask` deps bundle the ReAddTasks command uses, so the two+ * paths cannot drift. Called synchronously during handler construction.+ */+ bindTaskRetry?: (fn: (taskId: string) => Promise<unknown>) => voidrpcClient: Aria2RpcClientadapter: EngineAdaptertrackerManager: TrackerManager@@ -121,6 +131,8 @@ export function buildServerCommandHandlers(const {supervisor,settingsManager,+ dnsFallback,+ bindTaskRetry,adapter,trackerManager,aria2BinaryPath,@@ -258,6 +270,9 @@ export function buildServerCommandHandlers(publishTaskUpdate,publishTaskUpdateNow,}+ // The DNS fallback consumer retries through the same deps bundle as+ // Commands.ReAddTasks so the automatic and user-initiated paths match.+ bindTaskRetry?.((id) => reAddTask(id, reAddDeps))const removeDeps = {taskManager,adapter,@@ -521,6 +536,15 @@ export function buildServerCommandHandlers()}+ if (oldFull.engine.dnsMode !== newFull.engine.dnsMode) {+ await supervisor.applyAsyncDns(+ dnsModeToAsyncDns(newFull.engine.dnsMode)+ )+ // Mode changes re-arm the auto fallback so a later switch back to+ // 'auto' starts optimistic again.+ dnsFallback?.reset()+ }+// Server uses explicit stop+start (mirrors Commands.RestartEngine// handler in this file); main runtime uses supervisor.restart().if (result.requiresRestart) {diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex 35e0eb41..441b02f5 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -919,7 +919,7 @@},"network": {"title": "Network",- "desc": "Proxy and NAT/UPnP"+ "desc": "Proxy, DNS, and NAT/UPnP"},"integration": {"title": "Integration",@@ -1251,6 +1251,14 @@}},"network": {+ "dns": {+ "title": "DNS",+ "mode": "DNS lookup",+ "modeDesc": "How downloads look up server addresses.",+ "modeAuto": "Auto",+ "modeSystem": "System DNS",+ "modeEngine": "Built-in DNS"+ },"proxy": {"title": "Proxy","enable": "Enable proxy",@@ -2068,6 +2076,10 @@"engineFailure": {"title": "Download engine failed"},+ "dnsFallback": {+ "title": "{{name}} retried with system DNS",+ "body": "Motrix couldn't reach a DNS server, so it switched to system DNS for this session."+ },"center": {"title": "Notifications","markAllRead": "Mark all read",diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex c1cabc8c..00b8fefa 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -906,7 +906,7 @@},"network": {"title": "网络",- "desc": "代理与 NAT/UPnP"+ "desc": "代理、DNS 与 NAT/UPnP"},"integration": {"title": "集成",@@ -1238,6 +1238,14 @@}},"network": {+ "dns": {+ "title": "DNS",+ "mode": "DNS 解析方式",+ "modeDesc": "下载引擎解析域名的方式。",+ "modeAuto": "自动",+ "modeSystem": "系统解析器",+ "modeEngine": "引擎内置解析器"+ },"proxy": {"title": "代理","enable": "启用代理",@@ -2048,6 +2056,10 @@"engineFailure": {"title": "下载引擎故障"},+ "dnsFallback": {+ "title": "{{name}} 已改用系统 DNS 重试",+ "body": "引擎无法联系任何 DNS 服务器,本次会话已切换到系统解析器。"+ },"center": {"title": "通知","markAllRead": "全部标为已读",diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 709cc6df..f9c12586 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -906,7 +906,7 @@},"network": {"title": "網路",- "desc": "Proxy 和 NAT/UPnP"+ "desc": "Proxy、DNS 和 NAT/UPnP"},"integration": {"title": "整合",@@ -1238,6 +1238,14 @@}},"network": {+ "dns": {+ "title": "DNS",+ "mode": "DNS 解析方式",+ "modeDesc": "下載引擎解析網域名稱的方式。",+ "modeAuto": "自動",+ "modeSystem": "系統解析器",+ "modeEngine": "引擎內建解析器"+ },"proxy": {"title": "Proxy","enable": "啟用 Proxy",@@ -1669,6 +1677,10 @@"engineFailure": {"title": "下載引擎失敗"},+ "dnsFallback": {+ "title": "{{name}} 已改用系統 DNS 重試",+ "body": "引擎無法聯繫任何 DNS 伺服器,本次工作階段已切換至系統解析器。"+ },"center": {"title": "通知","markAllRead": "全部標示為已讀",diff --git a/src/shared/schemas/engine-settings.test.ts b/src/shared/schemas/engine-settings.test.tsnew file mode 100644index 00000000..db23e1a6--- /dev/null+++ b/src/shared/schemas/engine-settings.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest'+import {+ DEFAULT_ENGINE_SETTINGS,+ engineSettingsSchema,+} from './engine-settings'++describe('engineSettingsSchema dnsMode', () => {+ it('defaults to auto', () => {+ expect(DEFAULT_ENGINE_SETTINGS.dnsMode).toBe('auto')+ })++ it.each(['auto', 'system', 'engine'] as const)('accepts %s', (mode) => {+ expect(engineSettingsSchema.parse({ dnsMode: mode }).dnsMode).toBe(mode)+ })++ it.each(['c-ares', 'true', 42, null])(+ 'recovers invalid persisted value %s to auto',+ (bad) => {+ expect(engineSettingsSchema.parse({ dnsMode: bad }).dnsMode).toBe('auto')+ }+ )+})diff --git a/src/shared/schemas/engine-settings.ts b/src/shared/schemas/engine-settings.tsindex 419f60d3..49a7437b 100644--- a/src/shared/schemas/engine-settings.ts+++ b/src/shared/schemas/engine-settings.ts@@ -22,6 +22,7 @@ export const engineSettingsSchema = z.object({maxTries: z.number().int().min(0).max(100).catch(5),retryWait: z.number().int().min(0).max(300).catch(10),lowestSpeedLimit: z.number().int().min(0).catch(0),+ dnsMode: z.enum(['auto', 'system', 'engine']).catch('auto'),// BitTorrent (HOT)btMaxPeers: z.number().int().min(1).max(1000).catch(128),diff --git a/src/shared/types/notification.ts b/src/shared/types/notification.tsindex 458fdb5f..7266a515 100644--- a/src/shared/types/notification.ts+++ b/src/shared/types/notification.ts@@ -5,6 +5,7 @@ export const NotificationKinds = {TaskError: 'task-error',TaskComplete: 'task-complete',EngineFailure: 'engine-failure',+ DnsFallback: 'dns-fallback',} as constexport type NotificationKind = stringdiff --git a/src/shared/types/settings.ts b/src/shared/types/settings.tsindex c327c07e..60b474c8 100644--- a/src/shared/types/settings.ts+++ b/src/shared/types/settings.ts@@ -150,6 +150,15 @@ export interface OnboardingState {disclaimerAccepted: boolean}+/**+ * DNS resolution strategy for the download engine.+ * - `auto`: engine resolver first; on a DNS transport failure the session+ * falls back to the system resolver and retries the failed task once.+ * - `system`: always the OS resolver (`async-dns=false`).+ * - `engine`: always the engine's built-in async resolver, no fallback.+ */+export type DnsResolutionMode = 'auto' | 'system' | 'engine'+export interface EngineSettings {// Startup params (change requires engine restart)rpcPort: number@@ -171,6 +180,7 @@ export interface EngineSettings {maxTries: numberretryWait: numberlowestSpeedLimit: number+ dnsMode: DnsResolutionMode// BitTorrent (HOT, flat)btMaxPeers: numberdiff --git a/tests/scripts/workflow-release-matrix.test.ts b/tests/scripts/workflow-release-matrix.test.tsindex 738b78ca..dd90a87e 100644--- a/tests/scripts/workflow-release-matrix.test.ts+++ b/tests/scripts/workflow-release-matrix.test.ts@@ -506,15 +506,25 @@ describe('general CI native-host split contract', () => {(step) => step.name === 'Release and packaging contracts')+ // Lint runs through the package script so the workflow, the local+ // commit gate, and biome.json cannot drift apart. The repo-wide+ // `biome check .` keeps the native-host tooling scripts covered —+ // the guarantee the previous explicit path list existed for.expect(lint).toBeDefined()const lintCommand = stringField(lint as LooseRecord, 'run')- expect(lintCommand).toContain(- 'packages/native-host/package-flatpak-companion.mjs'+ expect(lintCommand.trim()).toBe('pnpm run lint')+ const packageJson = JSON.parse(+ readFileSync(path.join(ROOT, 'package.json'), 'utf8')+ ) as { scripts?: Record<string, string> }+ expect(packageJson.scripts?.lint).toBe('biome check .')++ const fingerprint = steps.find(+ (step) => step.name === 'Biome toolchain fingerprint')- expect(lintCommand).toContain(- 'packages/native-host/package-flatpak-companion.test.mjs'+ expect(fingerprint).toBeDefined()+ expect(stringField(fingerprint as LooseRecord, 'run')).toContain(+ 'biome --version')- expect(lintCommand).toContain('src/')expect(tooling).toBeDefined()const toolingCommand = stringField(tooling as LooseRecord, 'run')