A full-featured download manager.
feat(trackers): make selection and task updates recoverable (#2269)
Dr_rOotf578dbfbb051
diff --git a/e2e/task-trackers.spec.ts b/e2e/task-trackers.spec.tsnew file mode 100644index 00000000..c86a5f4b--- /dev/null+++ b/e2e/task-trackers.spec.ts@@ -0,0 +1,217 @@+import { createHash } from 'node:crypto'+import { writeFile } from 'node:fs/promises'+import path from 'node:path'+import { CURRENT_SETTINGS_VERSION } from '../src/core/settings/migrations'+import { Commands } from '../src/shared/protocol/commands'+import { Queries } from '../src/shared/protocol/queries'+import type { DownloadTask } from '../src/shared/types/task'+import {+ expect,+ launchMotrix,+ test,+ waitForEngineReady,+} from './fixtures/electron-app'+import { getFreePort } from './helpers/free-port'++const old = 'http://127.0.0.1:9/old'+const fresh = 'http://127.0.0.1:10/new'+const manual = 'http://127.0.0.1:11/manual'+const native = 'http://127.0.0.1:12/native'+const sources = [+ {+ id: 'first',+ label: 'First',+ url: 'http://127.0.0.1:9/first.txt',+ enabled: true,+ builtin: false,+ },+ {+ id: 'second',+ label: 'Second',+ url: 'http://127.0.0.1:9/second.txt',+ enabled: false,+ builtin: false,+ },+]++for (const active of [false, true]) {+ test(`task Tracker preview preserves ownership with active=${active}`, async ({+ userDataDir,+ rpcPort,+ }, testInfo) => {+ test.setTimeout(90000)+ const now = Date.now()+ await writeFile(+ path.join(userDataDir, 'settings.json'),+ JSON.stringify({+ version: CURRENT_SETTINGS_VERSION,+ app: { language: 'en-US', warnBeforeQuit: false },+ engine: {+ dhtEnabled: false,+ listenPort: await getFreePort(),+ btEnableLpd: false,+ },+ tracker: {+ autoSync: false,+ probeEnabled: false,+ blacklistEnabled: false,+ sources,+ },+ onboarding: { disclaimerAccepted: true },+ })+ )+ await writeFile(+ path.join(userDataDir, 'tracker.json'),+ JSON.stringify({+ version: 2,+ effective: [old],+ snapshots: Object.fromEntries(+ sources.map((source, index) => [+ `tracker:${source.id}`,+ {+ ...source,+ kind: 'tracker',+ urls: [index ? fresh : old],+ lastAttemptAt: now,+ lastSuccessAt: now,+ contentChangedAt: now,+ error: null,+ failures: 0,+ nextRetryAt: null,+ },+ ])+ ),+ })+ )+ const app = await launchMotrix({ userDataDir, rpcPort })+ try {+ const page = await app.firstWindow()+ await waitForEngineReady(page)+ const invoke = (+ channel:+ | (typeof Commands)[keyof typeof Commands]+ | (typeof Queries)[keyof typeof Queries],+ value?: unknown+ ) =>+ page.evaluate(+ ({ channel, value }) => window.motrix.invoke(channel, value),+ { channel, value }+ )+ await expect+ .poll(+ async () =>+ ((await invoke(Queries.GetTrackerList)) as { effective: string[] })+ .effective+ )+ .toEqual([old])+ const payload = Buffer.from('0123456789')+ const torrent = Buffer.concat([+ Buffer.from(+ `d8:announce${native.length}:${native}4:infod6:lengthi10e4:name8:test.bin12:piece lengthi16384e6:pieces20:`+ ),+ createHash('sha1').update(payload).digest(),+ Buffer.from('ee'),+ ]).toString('base64')+ await invoke(Commands.CreateTask, {+ type: 'bt',+ payload: { kind: 'torrent-base64', base64: torrent },+ selectedFiles: [0],+ saveDir: path.join(userDataDir, 'downloads'),+ })+ const readTask = async () =>+ ((await invoke(Queries.ListTasks)) as DownloadTask[])[0]!+ await expect+ .poll(async () => (await readTask())?.engineTaskId)+ .toBeTruthy()+ const task = await readTask()+ await invoke(Commands.PauseTask, task.id)+ await invoke(Commands.SetTaskBtTracker, {+ taskId: task.id,+ engineGid: task.engineTaskId,+ trackers: [old, manual],+ })+ if (active) {+ await invoke(Commands.ResumeTask, task.id)+ await expect+ .poll(async () => (await readTask()).status)+ .toBe('downloading')+ }+ await invoke(Commands.UpdateSettings, {+ tracker: {+ sources: sources.map((source) => ({+ ...source,+ enabled: !source.enabled,+ })),+ },+ })+ await expect+ .poll(+ async () =>+ ((await invoke(Queries.GetTrackerList)) as { effective: string[] })+ .effective+ )+ .toEqual([fresh])+ await page.getByRole('link', { name: 'Downloads', exact: true }).click()+ await page.locator(`[data-task-id="${task.id}"]`).dblclick()+ const inspector = page.getByTestId('task-inspector-drawer-content')+ await inspector+ .getByRole('tab', { name: 'Trackers', exact: true })+ .click()+ await inspector.getByRole('button', { name: 'Sync', exact: true }).click()+ const dialog = page.getByRole('dialog').filter({+ has: page.getByRole('heading', { name: 'Update task trackers' }),+ })+ await expect(dialog).toBeVisible()+ const overlay = page.locator('[data-slot="dialog-overlay"]')+ await expect(overlay).toBeVisible()+ await expect(overlay).toHaveCSS('opacity', '1')+ const viewport = await page.evaluate(() => ({+ width: window.innerWidth,+ height: window.innerHeight,+ }))+ expect(await overlay.boundingBox()).toEqual({ x: 0, y: 0, ...viewport })+ await expect(dialog.getByText(old, { exact: true })).toBeVisible()+ await expect(dialog.getByText(fresh, { exact: true })).toBeVisible()+ await expect(dialog.getByText(/briefly pause/)).toHaveCount(+ active ? 1 : 0+ )+ await expect(dialog).toHaveCSS('opacity', '1')+ await page.screenshot({+ path: testInfo.outputPath('tracker-task-diff.png'),+ animations: 'disabled',+ })+ await dialog.getByRole('button', { name: 'Apply update' }).click()+ await expect(dialog).toHaveCount(0)+ await expect(overlay).toHaveCount(0)+ await expect+ .poll(async () => (await readTask()).status)+ .toBe(active ? 'downloading' : 'paused')+ expect(+ await invoke(Queries.GetTaskBtTracker, { engineGid: task.engineTaskId })+ ).toEqual([manual, fresh])+ await expect(inspector.getByText(manual, { exact: true })).toBeVisible()+ const freshRow = inspector.getByText(fresh, { exact: true }).locator('..')+ await freshRow.hover()+ await freshRow.getByRole('button', { name: 'Delete tracker' }).click()+ await expect+ .poll(+ async () =>+ await invoke(Queries.GetTaskBtTracker, {+ engineGid: task.engineTaskId,+ })+ )+ .toEqual([manual])+ await inspector.getByRole('button', { name: 'Sync', exact: true }).click()+ await expect(+ dialog.getByRole('button', { name: 'Apply update' })+ ).toBeDisabled()+ await expect(dialog.getByText(/you removed/)).toBeVisible()+ await page.screenshot({+ path: testInfo.outputPath('tracker-task-exclusion.png'),+ animations: 'disabled',+ })+ } finally {+ await app.close()+ }+ })+}diff --git a/scripts/smoke-server-image.mjs b/scripts/smoke-server-image.mjsindex 5fb94b9f..5c8d36f9 100644--- a/scripts/smoke-server-image.mjs+++ b/scripts/smoke-server-image.mjs@@ -1143,6 +1143,7 @@ export async function smokeServerImage(options) {throw new Error('BT output retained the duplicated torrent root')}await rpc(url, operatorToken, 'command', 'command:setTaskBtTracker', {+ taskId: finalBtTask.id,engineGid: finalBtTask.engineTaskId,trackers: [trackerUrl],})diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.tsindex 5eb27f73..afa80415 100644--- a/src/core/engine/aria2/aria2-adapter.test.ts+++ b/src/core/engine/aria2/aria2-adapter.test.ts@@ -2566,12 +2566,19 @@ describe('Aria2Adapter', () => {metadata: new Uint8Array([1, 2, 3]),saveDir: '/tmp',isPrivate: true,+ extraEngineOptions: {+ 'bt-tracker': 'udp://public:80',+ 'bt-exclude-tracker': '*',+ 'enable-peer-exchange': 'true',+ },})const opts = (rpc.addTorrent as Mock).mock.calls[0][2] as Record<string,string>expect(opts['bt-tracker']).toBe('')+ expect(opts['bt-exclude-tracker']).toBe('')+ expect(opts['enable-peer-exchange']).toBe('false')})it('omits bt-tracker override when isPrivate=false', async () => {diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.tsindex e9a64fe1..d815a6c3 100644--- a/src/core/engine/aria2/aria2-adapter.ts+++ b/src/core/engine/aria2/aria2-adapter.ts@@ -28,6 +28,7 @@ import type { TuningContext } from '@shared/types/tuning'import { probeQuick } from '../../probe/disk-probe'import type {AddTorrentParams,+ BtTrackerPolicy,CreateDownloadParams,DirectResourceMetadataProfile,DownloadCookie,@@ -130,6 +131,41 @@ import {} from './translate'export class Aria2Adapter implements EngineAdapter {+ private btTrackerPolicy?: BtTrackerPolicy+ configureBtTrackerPolicy(policy: BtTrackerPolicy): void {+ this.btTrackerPolicy = policy+ }+ async setTaskBtTracker(+ engineTaskId: string,+ trackers: string[]+ ): Promise<void> {+ await this.rpc.changeOption(engineTaskId, {+ 'bt-tracker': trackers.join(','),+ })+ }+ private async applyBtTrackerPolicy(+ options: Record<string, string | string[]>,+ gid?: string,+ metadata?: Uint8Array,+ isPrivate?: boolean+ ): Promise<void> {+ if (!this.btTrackerPolicy) return+ const raw = options['bt-tracker']+ const manual = (Array.isArray(raw) ? raw : (raw ?? '').split(',')).filter(+ Boolean+ )+ const policy = await this.btTrackerPolicy({+ engineGid: gid,+ metadata,+ isPrivate,+ manual,+ })+ options['bt-tracker'] = policy.trackers.join(',')+ // Subscription exclusions select supplements; never exclude native trackers.+ options['bt-exclude-tracker'] = ''+ if (policy.isPrivate) options['enable-peer-exchange'] = 'false'+ }+private readonly log = getLogger('aria2-adapter')private capability: EngineCapability = {http: true,@@ -550,6 +586,7 @@ export class Aria2Adapter implements EngineAdapter {// not halt the entire torrent before a healthy source sends any data.if (params.uris.some((uri) => /^magnet:/i.test(uri))) {options['max-file-not-found'] = '0'+ await this.applyBtTrackerPolicy(options, requestedGid)}const actualGid = await this.addUriWithConnectionFallback(@@ -772,11 +809,6 @@ export class Aria2Adapter implements EngineAdapter {if (params.checkIntegrity) {opts['check-integrity'] = 'true'}- if (params.isPrivate) {- // Private torrents must not announce to global trackers (BEP-27).- // Override aria2's engine-wide bt-tracker default with empty string.- opts['bt-tracker'] = ''- }if (params.prioritizePreviewPieces) {opts['bt-prioritize-piece'] = 'head=10M,tail=10M'}@@ -794,6 +826,20 @@ export class Aria2Adapter implements EngineAdapter {opts[k] = v}}+ await this.applyBtTrackerPolicy(+ opts,+ requestedGid,+ params.metadata,+ params.isPrivate+ )+ if (params.isPrivate) {+ // Apply after extra options: private torrents keep their own trackers.+ // A configured policy can restore explicitly owned private-task edits.+ // Without that provenance, no supplemental option is trusted.+ if (!this.btTrackerPolicy) opts['bt-tracker'] = ''+ opts['bt-exclude-tracker'] = ''+ opts['enable-peer-exchange'] = 'false'+ }if (requestedGid !== undefined) {opts.gid = requestedGid}diff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.tsindex af8bf0a8..a8ce0a88 100644--- a/src/core/engine/engine-adapter.ts+++ b/src/core/engine/engine-adapter.ts@@ -142,7 +142,17 @@ export interface CreateDownloadParams {minSplitSize?: number}+/** Host-owned policy, invoked after a durable GID owner exists and before dispatch. */+export type BtTrackerPolicy = (input: {+ engineGid?: string+ metadata?: Uint8Array+ manual: string[]+ isPrivate?: boolean+}) => Promise<{ trackers: string[]; isPrivate: boolean }>+export interface EngineAdapter {+ configureBtTrackerPolicy?(policy: BtTrackerPolicy): void+ setTaskBtTracker(engineTaskId: string, trackers: string[]): Promise<void>connect(): Promise<void>disconnect(): Promise<void>getCapabilities(): EngineCapabilitydiff --git a/src/core/session/migrations/index.ts b/src/core/session/migrations/index.tsindex 7e9bc772..b8b26b54 100644--- a/src/core/session/migrations/index.ts+++ b/src/core/session/migrations/index.ts@@ -10,6 +10,7 @@ import { V3_SCHEMA_OBJECTS, v3 } from './v3'import { V4_SCHEMA_OBJECTS, v4 } from './v4'import { V5_TASK_SCHEMA_OBJECTS, v5 } from './v5'import { V6_SCHEMA_OBJECTS, v6 } from './v6'+import { V7_SCHEMA_OBJECTS, v7 } from './v7'interface Migration {version: number@@ -26,7 +27,7 @@ interface Migration {// persists the user-selected save directory independently of engine paths and// repairs stale instance statuses beneath terminal tasks. v6 adds independent// seeding-time counters without inventing pre-upgrade history.-const MIGRATIONS: Migration[] = [v1, v2, v3, v4, v5, v6]+const MIGRATIONS: Migration[] = [v1, v2, v3, v4, v5, v6, v7]const HIGHEST_KNOWN_VERSION = MIGRATIONS.reduce((max, m) => (m.version > max ? m.version : max),@@ -66,6 +67,7 @@ export class StaleSchemaError extends Error {| 'activity_schema_missing'| 'inspector_activity_schema_missing'| 'plugin_hook_schema_missing'+ | 'task_tracker_schema_missing'| 'foreign_key_violation',public readonly dbPath: string) {@@ -93,7 +95,9 @@ export class StaleSchemaError extends Error {'indexes) are invalid': reason === 'plugin_hook_schema_missing'? 'expected plugin finalize, post-delivery, or quota tables, constraints, and indexes are invalid'- : 'the canonical schema contains foreign-key violations'+ : reason === 'task_tracker_schema_missing'+ ? 'expected task Tracker ownership journal schema is invalid'+ : 'the canonical schema contains foreign-key violations'super(`The versioned database schema is incompatible with this build: ` +`${detail}. ` +@@ -281,6 +285,12 @@ function validateCanonicalTaskAndActivitySchema(db: Database.Database): void {}function validateCanonicalSchema(db: Database.Database): void {+ if (+ !hasExactSchemaObjects(db, V7_SCHEMA_OBJECTS) ||+ !hasNoExplicitIndexesOrTriggers(db, ['task_tracker_state'])+ ) {+ throw new StaleSchemaError('task_tracker_schema_missing', db.name)+ }if (!hasExactSchemaObjects(db, V6_SCHEMA_OBJECTS) ||!hasNoExplicitIndexesOrTriggers(db, ['task_seeding_activity'])diff --git a/src/core/session/migrations/v1.test.ts b/src/core/session/migrations/v1.test.tsindex 29c9e875..b0abf3dd 100644--- a/src/core/session/migrations/v1.test.ts+++ b/src/core/session/migrations/v1.test.ts@@ -468,7 +468,7 @@ describe('migrate() schema guard (Codex finding #7)', () => {version INTEGER PRIMARY KEY,applied_at INTEGER NOT NULL);- INSERT INTO schema_version (version, applied_at) VALUES (7, 0);+ INSERT INTO schema_version (version, applied_at) VALUES (8, 0);CREATE TABLE task_metadata (motrix_id TEXT PRIMARY KEY);`)@@ -524,7 +524,7 @@ describe('migrate() schema guard (Codex finding #7)', () => {const rows = db.prepare('SELECT version FROM schema_version ORDER BY version').all() as Array<{ version: number }>- expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5, 6])+ expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5, 6, 7])db.close()})@@ -543,7 +543,7 @@ describe('migrate() schema guard (Codex finding #7)', () => {// Inspector Activity persistence, and v4 adds durable Hook delivery and// finalize journals. V5 repairs terminal instances and v6 tracks seeding time.// All apply on a fresh DB.- expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5, 6])+ expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5, 6, 7])const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table'")diff --git a/src/core/session/migrations/v3.test.ts b/src/core/session/migrations/v3.test.tsindex 0c1e557c..8dd90278 100644--- a/src/core/session/migrations/v3.test.ts+++ b/src/core/session/migrations/v3.test.ts@@ -110,7 +110,7 @@ describe('migration v3 compatibility', () => {const db = openMemory()migrate(db)- expect(readVersion(db)).toBe(6)+ expect(readVersion(db)).toBe(7)const names = db.prepare(`SELECT name FROM sqlite_master@@ -166,7 +166,7 @@ describe('migration v3 compatibility', () => {const reopened = new Database(dbPath)reopened.pragma('foreign_keys = ON')- expect(readVersion(reopened)).toBe(6)+ expect(readVersion(reopened)).toBe(7)expect(reopened.prepare("SELECT motrix_id FROM tasks WHERE motrix_id = 'survivor'")@@ -207,7 +207,7 @@ describe('migration v3 compatibility', () => {})()expect(() => migrate(db)).not.toThrow()- expect(readVersion(db)).toBe(6)+ expect(readVersion(db)).toBe(7)db.close()})diff --git a/src/core/session/migrations/v4.test.ts b/src/core/session/migrations/v4.test.tsindex 68eaf7df..1e6036bb 100644--- a/src/core/session/migrations/v4.test.ts+++ b/src/core/session/migrations/v4.test.ts@@ -40,7 +40,7 @@ describe('migration v4', () => {const db = openMemory()migrate(db)- expect(readVersion(db)).toBe(6)+ expect(readVersion(db)).toBe(7)const rows = db.prepare(`SELECT name FROM sqlite_master@@ -68,7 +68,7 @@ describe('migration v4', () => {migrate(db)- expect(readVersion(db)).toBe(6)+ expect(readVersion(db)).toBe(7)expect(db.prepare("SELECT name FROM tasks WHERE motrix_id = 'survivor'").get()).toEqual({ name: 'fixture' })diff --git a/src/core/session/migrations/v5.test.ts b/src/core/session/migrations/v5.test.tsindex 714bca52..4971c22a 100644--- a/src/core/session/migrations/v5.test.ts+++ b/src/core/session/migrations/v5.test.ts@@ -111,7 +111,7 @@ describe('task recovery migration v5', () => {expect(db.prepare('SELECT total_changes() AS count').get()).toEqual(changes)expect(db.prepare('SELECT version FROM schema_version ORDER BY version').all()- ).toEqual([1, 2, 3, 4, 5, 6].map((version) => ({ version })))+ ).toEqual([1, 2, 3, 4, 5, 6, 7].map((version) => ({ version })))db.close()})})diff --git a/src/core/session/migrations/v7.ts b/src/core/session/migrations/v7.tsnew file mode 100644index 00000000..0cf85102--- /dev/null+++ b/src/core/session/migrations/v7.ts@@ -0,0 +1,20 @@+import type Database from 'better-sqlite3'+import type { SchemaObjectDefinition } from './v1'++export const V7_SCHEMA_OBJECTS: readonly SchemaObjectDefinition[] = [+ {+ name: 'task_tracker_state',+ sql: `CREATE TABLE task_tracker_state (+ motrix_id TEXT NOT NULL PRIMARY KEY+ CHECK (typeof(motrix_id) = 'text' AND length(motrix_id) > 0),+ state TEXT NOT NULL CHECK (typeof(state) = 'text' AND json_valid(state)),+ FOREIGN KEY (motrix_id) REFERENCES tasks(motrix_id) ON DELETE CASCADE+ ) WITHOUT ROWID`,+ },+]+export const v7 = {+ version: 7,+ up(db: Database.Database): void {+ for (const object of V7_SCHEMA_OBJECTS) db.exec(object.sql)+ },+}diff --git a/src/core/task/actions/pause-task.ts b/src/core/task/actions/pause-task.tsindex f6db5866..8da8f54f 100644--- a/src/core/task/actions/pause-task.ts+++ b/src/core/task/actions/pause-task.ts@@ -22,6 +22,7 @@ export async function pauseTask(): Promise<void> {const task = getTaskOrWarn(deps, taskId, 'pauseTask')if (!task) return+ deps.onPauseRequested?.(taskId)const optimistic = {...task,status: TaskStatus.Paused,diff --git a/src/core/task/actions/resume-task.ts b/src/core/task/actions/resume-task.tsindex cb7c88bd..d7a2d13c 100644--- a/src/core/task/actions/resume-task.ts+++ b/src/core/task/actions/resume-task.ts@@ -24,6 +24,7 @@ export async function resumeTask(): Promise<void> {const task = getTaskOrWarn(deps, taskId, 'resumeTask')if (!task) return+ deps.onResumeRequested?.(taskId)const optimistic = {...task,status: TaskStatus.Downloading,diff --git a/src/core/task/actions/shared.ts b/src/core/task/actions/shared.tsindex f0b6b545..7dfdbae1 100644--- a/src/core/task/actions/shared.ts+++ b/src/core/task/actions/shared.ts@@ -20,6 +20,10 @@ import type { TaskManager } from '../task-manager'* siblings don't import from an unrelated peer just to reach the common type.*/export interface TaskActionDeps {+ /** Explicit controls supersede a temporary Tracker pause/recovery lease. */+ onPauseRequested?: (taskId: string) => void+ onResumeRequested?: (taskId: string) => void+taskManager: TaskManageradapter: EngineAdaptereventBus: EventBusdiff --git a/src/core/tracker/task-tracker-repository.test.ts b/src/core/tracker/task-tracker-repository.test.tsnew file mode 100644index 00000000..2a5d32e0--- /dev/null+++ b/src/core/tracker/task-tracker-repository.test.ts@@ -0,0 +1,76 @@+import { migrate } from '@core/session/migrations'+import { v1 } from '@core/session/migrations/v1'+import { v2 } from '@core/session/migrations/v2'+import { v3 } from '@core/session/migrations/v3'+import { v4 } from '@core/session/migrations/v4'+import { v5 } from '@core/session/migrations/v5'+import { v6 } from '@core/session/migrations/v6'+import {+ type TaskTrackerState,+ taskTrackerStateSchema,+} from '@shared/schemas/task-tracker'+import Database from 'better-sqlite3'+import { describe, expect, it } from 'vitest'+import { TaskTrackerRepository } from './task-tracker-repository'++const state: TaskTrackerState = {+ engineGid: 'gid',+ revision: 1,+ original: ['https://native/announce'],+ manual: [],+ managed: ['udp://public:80'],+ excluded: [],+ isPrivate: false,+ pending: null,+}++describe('task Tracker persistence', () => {+ it('migrates v6 without inventing ownership; roundtrips pending state and cascades deletion', () => {+ const db = new Database(':memory:')+ db.pragma('foreign_keys = ON')+ db.exec(`CREATE TABLE schema_version (+ version INTEGER PRIMARY KEY,+ applied_at INTEGER NOT NULL+ )`)+ for (const migration of [v1, v2, v3, v4, v5, v6]) {+ migration.up(db)+ db.prepare('INSERT INTO schema_version VALUES (?, 1)').run(+ migration.version+ )+ }+ db.exec(+ "INSERT INTO tasks (motrix_id,name,task_type,created_at,updated_at) VALUES ('task','file','bt',1,1)"+ )+ migrate(db)+ const store = new TaskTrackerRepository(db)+ expect(store.get('task')).toBeNull()+ const pending = {+ ...state,+ pending: {+ before: [],+ after: state.managed,+ next: state,+ resumeRequired: true,+ },+ }+ store.save('task', pending)+ expect(new TaskTrackerRepository(db).get('task')).toEqual(+ taskTrackerStateSchema.parse(pending)+ )+ expect(store.pendingTaskIds()).toEqual(['task'])+ store.save('task', state)+ expect(store.pendingTaskIds()).toEqual([])+ expect(() => store.save('missing', state)).toThrow()+ db.exec("DELETE FROM tasks WHERE motrix_id = 'task'")+ expect(store.get('task')).toBeNull()+ expect(() => migrate(db)).not.toThrow()+ db.close()+ })+ it('rejects a damaged journal schema instead of silently losing ownership', () => {+ const db = new Database(':memory:')+ migrate(db)+ db.exec('DROP TABLE task_tracker_state')+ expect(() => migrate(db)).toThrow('Tracker ownership journal')+ db.close()+ })+})diff --git a/src/core/tracker/task-tracker-repository.ts b/src/core/tracker/task-tracker-repository.tsnew file mode 100644index 00000000..6c3dad8c--- /dev/null+++ b/src/core/tracker/task-tracker-repository.ts@@ -0,0 +1,34 @@+import {+ type TaskTrackerState,+ taskTrackerStateSchema,+} from '@shared/schemas/task-tracker'+import type Database from 'better-sqlite3'++/** Task-owned journal; task deletion cascades in the same SQLite transaction. */+export class TaskTrackerRepository {+ constructor(private readonly db: Database.Database) {}+ get(taskId: string): TaskTrackerState | null {+ const row = this.db+ .prepare('SELECT state FROM task_tracker_state WHERE motrix_id = ?')+ .get(taskId) as { state: string } | undefined+ return row ? taskTrackerStateSchema.parse(JSON.parse(row.state)) : null+ }+ save(taskId: string, state: TaskTrackerState): void {+ const value = JSON.stringify(taskTrackerStateSchema.parse(state))+ this.db.transaction(() => {+ this.db+ .prepare(`INSERT INTO task_tracker_state (motrix_id, state) VALUES (?, ?)+ ON CONFLICT(motrix_id) DO UPDATE SET state = excluded.state`)+ .run(taskId, value)+ })()+ }+ pendingTaskIds(): string[] {+ return (+ this.db+ .prepare(+ "SELECT motrix_id FROM task_tracker_state WHERE json_type(state, '$.pending') = 'object'"+ )+ .all() as { motrix_id: string }[]+ ).map((row) => row.motrix_id)+ }+}diff --git a/src/core/tracker/task-tracker-service.test.ts b/src/core/tracker/task-tracker-service.test.tsnew file mode 100644index 00000000..941cac0e--- /dev/null+++ b/src/core/tracker/task-tracker-service.test.ts@@ -0,0 +1,371 @@+import type { EngineAdapter } from '@core/engine/engine-adapter'+import { TaskManager } from '@core/task/task-manager'+import type { TaskTrackerState } from '@shared/schemas/task-tracker'+import { makeDefaultBtExtension, TaskStatus } from '@shared/types/task'+import { makeDownloadTask } from '@test-utils/task'+import parseTorrent from 'parse-torrent'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { TaskTrackerService } from './task-tracker-service'++vi.mock('parse-torrent', () => ({ default: vi.fn() }))+const a = 'udp://a.example:80/announce'+const b = 'https://b.example/announce?passkey=Secret'+const c = 'https://c.example/announce'+const native = 'https://native.example/announce'++function fixture(initial: string[] = [a, b]) {+ let selected = [c]+ let effective = [...initial]+ let state: TaskTrackerState | null = {+ engineGid: '1234567890abcdef',+ revision: 1,+ original: [native],+ manual: [b],+ managed: [a],+ excluded: [],+ isPrivate: false,+ pending: null,+ }+ const tasks = new TaskManager()+ const task = makeDownloadTask({+ id: 'task',+ engineTaskId: '1234567890abcdef',+ status: TaskStatus.Downloading,+ })+ tasks.add(task)+ const repository = {+ get: vi.fn(() => state && structuredClone(state)),+ save: vi.fn((_id: string, value: TaskTrackerState) => {+ state = structuredClone(value)+ }),+ pendingTaskIds: () => (state?.pending ? ['task'] : []),+ }+ const adapter = {+ getTaskBtTracker: vi.fn(async () => [...effective]),+ getTaskStatus: vi.fn(async () => task),+ setTaskBtTracker: vi.fn(async (_gid: string, urls: string[]) => {+ effective = [...urls]+ }),+ }+ const actions = {+ pauseTask: vi.fn(async () => {+ task.status = TaskStatus.Paused+ }),+ resumeTask: vi.fn(async () => {+ task.status = TaskStatus.Downloading+ }),+ }+ const deps = {+ adapter: adapter as unknown as EngineAdapter,+ tasks,+ repository,+ selected: () => selected,+ actions,+ }+ const service = new TaskTrackerService(deps)+ const plan = () => service.plan(task.id, task.engineTaskId)+ const apply = async () =>+ service.apply(task.id, task.engineTaskId, (await plan()).fingerprint)+ return {+ service,+ deps,+ task,+ tasks,+ repository,+ adapter,+ actions,+ plan,+ apply,+ state: () => state,+ setState: (value: TaskTrackerState | null) => {+ state = value+ },+ effective: () => effective,+ setEffective: (value: string[]) => {+ effective = value+ },+ select: (value: string[]) => {+ selected = value+ },+ }+}++beforeEach(() => {+ vi.mocked(parseTorrent).mockReset()+})++describe('task tracker ownership and journal', () => {+ it('previews only managed removal, preserves manual and native overlap, then resumes', async () => {+ const f = fixture([a, b, native])+ const plan = await f.plan()+ expect(plan).toMatchObject({+ added: [c],+ removed: [a],+ retained: [b, native],+ requiresPause: true,+ })+ expect(f.adapter.setTaskBtTracker).not.toHaveBeenCalled()+ await f.service.apply('task', f.task.engineTaskId, plan.fingerprint)+ expect(f.effective()).toEqual([b, native, c])+ expect(f.state()).toMatchObject({ managed: [c], pending: null })+ expect(f.actions.pauseTask).toHaveBeenCalledOnce()+ expect(f.actions.resumeTask).toHaveBeenCalledOnce()+ })+ it('does not misclassify supplemental URLs in aria2 announceList as native metadata', async () => {+ const f = fixture([a, b])+ f.task.bt = makeDefaultBtExtension({ announceList: [[native, a, b]] })+ expect(await f.plan()).toMatchObject({+ original: [native],+ removed: [a],+ added: [c],+ })+ await f.service.edit('task', f.task.engineTaskId, [b])+ expect(f.effective()).toEqual([b])+ })++ it('never guesses legacy ownership from global membership', async () => {+ const f = fixture()+ f.setState(null)+ f.task.torrentMetaPath = '/seed.torrent'+ const plan = await f.plan()+ expect(plan.removed).toEqual([])+ expect(plan.retained).toEqual([a, b])+ })+ it('keeps managed/manual overlap when that URL leaves selection', async () => {+ const f = fixture()+ f.setState({ ...f.state()!, manual: [a, b] })+ expect((await f.plan()).removed).toEqual([])+ })+ it('persists manual deletion as an exclusion through later sync and re-add', async () => {+ const f = fixture()+ f.select([a, c])+ await f.service.edit('task', f.task.engineTaskId, [b])+ expect(f.state()?.excluded).toEqual([a])+ await f.apply()+ expect(f.effective()).toEqual([b, c])+ vi.mocked(parseTorrent).mockResolvedValue({+ private: false,+ announce: [native],+ } as never)+ const prepared = await f.service.prepareCreation({+ engineGid: f.task.engineTaskId,+ metadata: new Uint8Array([1]),+ manual: [],+ })+ expect(prepared.trackers).toEqual([b, c])+ })+ it('an explicit re-add of an excluded URL makes it manual', async () => {+ const f = fixture()+ f.setState({ ...f.state()!, managed: [], excluded: [a] })+ f.setEffective([b])+ await f.service.edit('task', f.task.engineTaskId, [a, b])+ expect(f.state()).toMatchObject({ excluded: [], manual: [a, b] })+ expect((await f.plan()).removed).toEqual([])+ })+ it('rejects stale selection, engine options, or active-state previews before pausing', async () => {+ for (const change of [+ (f: ReturnType<typeof fixture>) => f.select([a]),+ (f: ReturnType<typeof fixture>) => f.setEffective([a]),+ (f: ReturnType<typeof fixture>) => {+ f.task.status = TaskStatus.Paused+ },+ ]) {+ const f = fixture()+ const plan = await f.plan()+ change(f)+ await expect(+ f.service.apply('task', f.task.engineTaskId, plan.fingerprint)+ ).rejects.toThrow('stale')+ expect(f.actions.pauseTask).not.toHaveBeenCalled()+ expect(f.adapter.setTaskBtTracker).not.toHaveBeenCalled()+ }+ })+ it('does not pause an already-paused task or resume it after applying', async () => {+ const f = fixture()+ f.task.status = TaskStatus.Paused+ await f.apply()+ expect(f.actions.pauseTask).not.toHaveBeenCalled()+ expect(f.actions.resumeTask).not.toHaveBeenCalled()+ })+ it('does not pause or write for an unchanged plan', async () => {+ const f = fixture()+ f.select([a])+ await f.apply()+ expect(f.adapter.setTaskBtTracker).not.toHaveBeenCalled()+ expect(f.actions.pauseTask).not.toHaveBeenCalled()+ })+ it('records intent before pausing and compensates even if pause rejects after taking effect', async () => {+ const f = fixture()+ f.actions.pauseTask.mockImplementationOnce(async () => {+ expect(f.state()?.pending).toMatchObject({+ before: [a, b],+ after: [b, c],+ resumeRequired: true,+ })+ f.task.status = TaskStatus.Paused+ throw new Error('pause acknowledgement lost')+ })+ await expect(f.apply()).rejects.toThrow('pause acknowledgement lost')+ expect(f.actions.resumeTask).toHaveBeenCalledOnce()+ expect(f.adapter.setTaskBtTracker).not.toHaveBeenCalled()+ expect(f.state()).toMatchObject({ managed: [a], pending: null })+ })+ it('verifies applied options after a lost write response', async () => {+ const f = fixture()+ f.adapter.setTaskBtTracker.mockImplementationOnce(async (_gid, urls) => {+ f.setEffective(urls)+ throw new Error('lost response')+ })+ await expect(f.apply()).rejects.toThrow('lost response')+ expect(f.state()?.lastError?.phase).toBe('write')+ expect(f.state()).toMatchObject({ managed: [c], pending: null })+ expect(f.actions.resumeTask).toHaveBeenCalledOnce()+ })+ it('retains a journal across resume failure and recovers idempotently in a new service', async () => {+ const f = fixture()+ f.actions.resumeTask.mockRejectedValueOnce(new Error('offline'))+ await expect(f.apply()).rejects.toThrow('offline')+ expect(f.state()?.pending).not.toBeNull()+ const restarted = new TaskTrackerService(f.deps)+ await restarted.recover()+ await restarted.recover()+ expect(f.state()).toMatchObject({ managed: [c], pending: null })+ expect(f.adapter.setTaskBtTracker).toHaveBeenCalledOnce()+ expect(f.actions.resumeTask).toHaveBeenCalledTimes(2)+ })+ it('surrenders ambiguous ownership after an external engine edit during recovery', async () => {+ const f = fixture()+ f.adapter.setTaskBtTracker.mockImplementationOnce(async () => {+ f.setEffective([b, native])+ throw new Error('external change')+ })+ await expect(f.apply()).rejects.toThrow()+ expect(f.state()).toMatchObject({+ managed: [],+ manual: [b, native],+ pending: null,+ })+ })+ it('never resumes a replacement generation or overwrites its options', async () => {+ const f = fixture()+ f.actions.pauseTask.mockImplementationOnce(async () => {+ f.task.engineTaskId = 'fedcba0987654321'+ })+ await expect(f.apply()).rejects.toThrow('changed')+ expect(f.adapter.setTaskBtTracker).not.toHaveBeenCalled()+ expect(f.actions.resumeTask).not.toHaveBeenCalled()+ })+ it('retains pending state while engine is missing instead of treating [] as success', async () => {+ const f = fixture()+ f.adapter.getTaskStatus+ .mockResolvedValueOnce(f.task)+ .mockResolvedValueOnce(null as never)+ await expect(f.apply()).rejects.toThrow('unavailable')+ expect(f.state()?.pending).not.toBeNull()+ await f.service.recover()+ expect(f.state()?.pending).toBeNull()+ })+ it('private and unknown tasks receive no selection, including private metadata overriding false flags', async () => {+ for (const privacy of [true, null]) {+ const f = fixture()+ f.setState({ ...f.state()!, isPrivate: privacy })+ expect((await f.plan()).added).toEqual([])+ }+ const f = fixture()+ vi.mocked(parseTorrent).mockResolvedValue({+ private: true,+ announce: [native],+ } as never)+ expect(+ await f.service.prepareCreation({+ engineGid: f.task.engineTaskId,+ metadata: new Uint8Array([1]),+ manual: [c],+ isPrivate: false,+ })+ ).toEqual({ trackers: [], isPrivate: true })+ expect(f.state()).toMatchObject({+ managed: [],+ manual: [],+ original: [native],+ isPrivate: true,+ })+ })+ it('restores explicit manual edits made to an already-confirmed private task', async () => {+ const f = fixture()+ f.setState({ ...f.state()!, isPrivate: true, managed: [] })+ vi.mocked(parseTorrent).mockResolvedValue({+ private: true,+ announce: [native],+ } as never)+ const restored = await f.service.prepareCreation({+ engineGid: f.task.engineTaskId,+ metadata: new Uint8Array([1]),+ manual: [c],+ isPrivate: true,+ })+ expect(restored).toEqual({ trackers: [b], isPrivate: true })+ expect(f.state()?.managed).toEqual([])+ })++ it('unknown magnets and malformed metadata never inherit public supplements', async () => {+ const f = fixture([])+ f.setState(null)+ expect(+ await f.service.prepareCreation({+ engineGid: f.task.engineTaskId,+ manual: [],+ })+ ).toEqual({ trackers: [], isPrivate: false })+ vi.mocked(parseTorrent).mockRejectedValueOnce(new Error('invalid'))+ expect(+ (+ await f.service.prepareCreation({+ engineGid: f.task.engineTaskId,+ metadata: new Uint8Array(),+ manual: [],+ })+ ).trackers+ ).toEqual([])+ })+ it('keeps native metadata addresses outside the supplemental cap and preserves manual credentials', async () => {+ const f = fixture()+ f.select([native, c])+ vi.mocked(parseTorrent).mockResolvedValue({+ private: false,+ announce: [native],+ } as never)+ expect(+ (+ await f.service.prepareCreation({+ engineGid: f.task.engineTaskId,+ metadata: new Uint8Array([1]),+ manual: [],+ })+ ).trackers+ ).toEqual([b, c])+ expect(f.state()?.pending?.next.original).toEqual([native])+ })+ it('honors an explicit user pause while applying instead of auto-resuming over it', async () => {+ const f = fixture()+ f.adapter.setTaskBtTracker.mockImplementationOnce(async (_gid, urls) => {+ f.service.noteTaskControl('task', true)+ f.setEffective(urls)+ })+ await f.apply()+ expect(f.actions.resumeTask).not.toHaveBeenCalled()+ expect(f.task.status).toBe(TaskStatus.Paused)+ expect(f.state()).toMatchObject({ managed: [c], pending: null })+ })++ it('serializes edits with sync and drains accepted work at shutdown', async () => {+ const f = fixture()+ const first = f.service.edit('task', f.task.engineTaskId, [b])+ const second = f.service.edit('task', f.task.engineTaskId, [b, c])+ await f.service.stopAndDrain()+ await first+ await second+ expect(f.effective()).toEqual([b, c])+ await expect(f.plan()).rejects.toThrow('stopped')+ })+})diff --git a/src/core/tracker/task-tracker-service.ts b/src/core/tracker/task-tracker-service.tsnew file mode 100644index 00000000..c7726eef--- /dev/null+++ b/src/core/tracker/task-tracker-service.ts@@ -0,0 +1,467 @@+import { createHash } from 'node:crypto'+import { readFile } from 'node:fs/promises'+import type {+ BtTrackerPolicy,+ EngineAdapter,+} from '@core/engine/engine-adapter'+import type { TaskManager } from '@core/task/task-manager'+import type {+ TaskTrackerOwnership,+ TaskTrackerPlan,+ TaskTrackerState,+} from '@shared/schemas/task-tracker'+import { type DownloadTask, TaskStatus } from '@shared/types/task'+import parseTorrent from 'parse-torrent'+import type { TaskTrackerRepository } from './task-tracker-repository'+import type { TrackerTaskActions } from './tracker-manager'++const unique = (urls: readonly string[]) => [...new Set(urls)]+const same = (a: string[], b: string[]) =>+ a.length === b.length && a.every((url) => b.includes(url))+const active = (task: DownloadTask) =>+ [+ TaskStatus.Downloading,+ TaskStatus.Seeding,+ TaskStatus.FetchingMetadata,+ ].includes(task.status)+const terminal = (task: DownloadTask) =>+ [+ TaskStatus.Completed,+ TaskStatus.Error,+ TaskStatus.Removed,+ TaskStatus.Finalizing,+ TaskStatus.MetadataReady,+ ].includes(task.status)++export interface TaskTrackerDependencies {+ adapter: EngineAdapter+ tasks: Pick<TaskManager, 'getById' | 'getByEngineTaskId' | 'getAll'>+ repository: Pick<TaskTrackerRepository, 'get' | 'save' | 'pendingTaskIds'>+ selected: () => string[]+ actions: TrackerTaskActions+}++/** Owns only supplemental options. Native announce tiers never pass through a write. */+export class TaskTrackerService {+ private operations = new Map<string, Promise<unknown>>()+ private stopped = false+ private controlIntents = new Map<string, boolean>()+ constructor(private readonly deps: TaskTrackerDependencies) {}++ private current(taskId: string, gid: string): DownloadTask {+ const task = this.deps.tasks.getById(taskId)+ if (!task || task.engineTaskId !== gid || terminal(task))+ throw new Error('Tracker task changed; refresh and try again')+ return task+ }++ private run<T>(taskId: string, operation: () => Promise<T>): Promise<T> {+ if (this.stopped)+ return Promise.reject(new Error('Tracker service stopped'))+ const prior = this.operations.get(taskId) ?? Promise.resolve()+ const next = prior+ .catch(() => undefined)+ .then(() =>+ this.deps.actions.runTaskMutation+ ? this.deps.actions.runTaskMutation([taskId], operation)+ : operation()+ )+ this.operations.set(taskId, next)+ void next+ .finally(() => {+ if (this.operations.get(taskId) === next) {+ this.operations.delete(taskId)+ this.controlIntents.delete(taskId)+ }+ })+ .catch(() => undefined)+ return next+ }++ noteTaskControl(taskId: string, paused: boolean): void {+ if (this.operations.has(taskId)) this.controlIntents.set(taskId, paused)+ const state = this.deps.repository.get(taskId)+ if (state?.pending)+ this.deps.repository.save(taskId, {+ ...state,+ pending: { ...state.pending, resumeRequired: !paused },+ })+ }++ /** Called after a durable reserved owner exists, before every engine add/re-add.+ * Unknown magnets get no global supplements until metadata confirms public BT. */+ readonly prepareCreation: BtTrackerPolicy = async ({+ engineGid,+ metadata,+ manual,+ isPrivate,+ }) => {+ if (this.stopped) throw new Error('Tracker service stopped')+ let privacy: boolean | null = isPrivate === true ? true : null+ let original: string[] = []+ if (metadata) {+ try {+ const parsed = await parseTorrent(metadata)+ privacy = isPrivate === true || parsed.private === true+ original = unique(parsed.announce ?? [])+ } catch {+ /* Invalid metadata is rejected by the engine; never expand it. */+ }+ }+ const task = engineGid+ ? this.deps.tasks.getByEngineTaskId(engineGid)+ : undefined+ if (!task || task.engineTaskId !== engineGid)+ return { trackers: manual, isPrivate: privacy === true }+ const saved = this.deps.repository.get(task.id)+ const retainedManual =+ privacy === true+ ? saved?.isPrivate === true+ ? saved.manual+ : []+ : unique([...(saved?.manual ?? []), ...manual])+ const excluded = saved?.excluded ?? []+ const managed =+ privacy === false+ ? this.deps+ .selected()+ .filter((url) => !excluded.includes(url) && !original.includes(url))+ : []+ const trackers = unique([...retainedManual, ...managed])+ const next: TaskTrackerOwnership = {+ engineGid,+ revision: (saved?.revision ?? 0) + 1,+ original,+ manual: retainedManual,+ managed,+ excluded,+ isPrivate: privacy,+ }+ // The intent is durable before dispatch. Recovery verifies actual options;+ // never infer successful engine application from a desired snapshot alone.+ this.deps.repository.save(task.id, {+ ...next,+ pending: { before: [], after: trackers, next, resumeRequired: false },+ })+ return { trackers, isPrivate: privacy === true }+ }++ private async read(taskId: string, gid: string) {+ this.current(taskId, gid)+ const effective = unique(await this.deps.adapter.getTaskBtTracker(gid))+ const task = this.current(taskId, gid)+ const saved = this.deps.repository.get(taskId)+ const matching = saved?.engineGid === gid ? saved : null+ // Existing upgrades are deliberately unowned. Observed URLs become manual,+ // never managed merely because they also occur in the global selection.+ // aria2 tellStatus announceList includes supplemental options. Only the+ // original metainfo (or a creation-time snapshot of it) proves nativeness.+ let original = matching?.original ?? []+ let privacy = matching?.isPrivate ?? null+ if (!matching) {+ if (task.torrentMetaPath) {+ try {+ const parsed = await parseTorrent(+ await readFile(task.torrentMetaPath)+ )+ original = unique(parsed.announce ?? [])+ privacy = parsed.private === true+ } catch {+ // Missing metadata cannot establish a removable native baseline.+ original = unique(task.bt?.announceList.flat() ?? [])+ }+ } else {+ original = unique(+ task.uris+ .filter((uri) => uri.startsWith('magnet:'))+ .flatMap((uri) => new URL(uri).searchParams.getAll('tr'))+ )+ }+ this.current(taskId, gid)+ }+ const state: TaskTrackerState = matching ?? {+ engineGid: gid,+ revision: saved?.revision ?? 0,+ original,+ manual: effective,+ managed: [],+ excluded: saved?.excluded ?? [],+ isPrivate: privacy,+ pending: null,+ }+ const isPrivate = task.bt?.isPrivate === true ? true : state.isPrivate+ const manual = unique([+ ...state.manual.filter((url) => effective.includes(url)),+ ...effective.filter((url) => !state.managed.includes(url)),+ ])+ return { task, effective, state: { ...state, original, manual, isPrivate } }+ }++ private async build(taskId: string, gid: string) {+ const { task, effective, state } = await this.read(taskId, gid)+ if (state.pending)+ throw new Error('Tracker update awaits recovery; retry shortly')+ const selected =+ state.isPrivate === false+ ? unique(this.deps.selected()).filter(+ (url) =>+ !state.excluded.includes(url) && !state.original.includes(url)+ )+ : []+ // A private/unknown task may retire previously managed public supplements,+ // but must never gain new ones. Original/manual overlap remains protected.+ const after = unique([+ ...state.manual,+ ...effective.filter((url) => state.original.includes(url)),+ ...selected,+ ])+ const next = { ...state, managed: selected, revision: state.revision + 1 }+ const added = after.filter((url) => !effective.includes(url))+ const removed = effective.filter((url) => !after.includes(url))+ const fingerprint = createHash('sha256')+ .update(+ JSON.stringify({+ taskId,+ gid,+ effective: [...effective].sort(),+ state,+ after,+ active: active(task),+ })+ )+ .digest('hex')+ const plan: TaskTrackerPlan = {+ taskId,+ engineGid: gid,+ fingerprint,+ added,+ removed,+ retained: effective.filter((url) => after.includes(url)),+ original: state.original,+ excluded: state.excluded,+ requiresPause: active(task) && added.length + removed.length > 0,+ protected: state.isPrivate !== false,+ }+ return { plan, state, next, effective, after }+ }++ plan(taskId: string, gid: string): Promise<TaskTrackerPlan> {+ return this.run(taskId, async () => {+ await this.recoverTask(taskId)+ return (await this.build(taskId, gid)).plan+ })+ }++ apply(taskId: string, gid: string, fingerprint: string): Promise<void> {+ return this.run(taskId, async () => {+ await this.recoverTask(taskId)+ const { plan, state, next, effective, after } = await this.build(+ taskId,+ gid+ )+ if (plan.fingerprint !== fingerprint)+ throw new Error('Tracker preview is stale; refresh and try again')+ await this.write(taskId, gid, state, next, effective, after)+ })+ }++ edit(taskId: string, gid: string, urls: string[]): Promise<void> {+ return this.run(taskId, async () => {+ await this.recoverTask(taskId)+ const { effective, state } = await this.read(taskId, gid)+ const requested = unique(urls)+ if (requested.some((url) => !/^(https?|udp):\/\/[^\s,]+$/i.test(url)))+ throw new Error('Invalid tracker URL')+ const removed = state.managed.filter((url) => !requested.includes(url))+ const excluded = unique([...state.excluded, ...removed]).filter(+ (url) => !requested.includes(url)+ )+ const managed = state.managed.filter((url) => requested.includes(url))+ // Unchanged managed rows stay managed; explicitly re-added excluded rows+ // become manual. Editing is never allowed to alter native announce tiers.+ const manual = requested.filter(+ (url) => !managed.includes(url) || state.manual.includes(url)+ )+ const after = unique([+ ...requested,+ ...effective.filter((url) => state.original.includes(url)),+ ])+ const next = {+ ...state,+ revision: state.revision + 1,+ manual,+ managed,+ excluded,+ }+ await this.write(taskId, gid, state, next, effective, after)+ })+ }++ private async write(+ taskId: string,+ gid: string,+ state: TaskTrackerState,+ next: TaskTrackerOwnership,+ before: string[],+ after: string[]+ ): Promise<void> {+ this.current(taskId, gid)+ const task = await this.deps.adapter.getTaskStatus(gid)+ this.current(taskId, gid)+ if (!task || terminal(task))+ throw new Error('Tracker engine task unavailable')+ if (same(before, after)) {+ this.deps.repository.save(taskId, { ...next, pending: null })+ return+ }+ const journal: TaskTrackerState = {+ ...state,+ lastError: undefined,+ pending: {+ before,+ after,+ next,+ resumeRequired:+ this.controlIntents.get(taskId) !== true && active(task),+ },+ }+ this.deps.repository.save(taskId, journal)+ let phase: 'pause' | 'write' = 'pause'+ try {+ if (active(task)) await this.deps.actions.pauseTask(taskId)+ this.current(taskId, gid)+ if (+ this.current(taskId, gid).bt?.isPrivate === true &&+ next.isPrivate === false+ )+ throw new Error('Torrent privacy changed')+ phase = 'write'+ await this.deps.adapter.setTaskBtTracker(gid, after)+ this.current(taskId, gid)+ } catch (error) {+ this.recordFailure(taskId, phase)+ throw error+ } finally {+ // RPC may apply then reject/lose its response. Re-read actual options,+ // commit only what is proven, and retain the journal if recovery fails.+ await this.recoverTask(taskId)+ }+ }++ private recordFailure(+ taskId: string,+ phase: 'pause' | 'write' | 'resume' | 'recovery'+ ): void {+ const state = this.deps.repository.get(taskId)+ if (state?.pending)+ this.deps.repository.save(taskId, {+ ...state,+ lastError: { phase, at: Date.now() },+ })+ }++ private async recoverTask(taskId: string): Promise<void> {+ try {+ await this.reconcilePending(taskId)+ } catch (error) {+ this.recordFailure(taskId, 'recovery')+ throw error+ }+ }++ private async reconcilePending(taskId: string): Promise<void> {+ const state = this.deps.repository.get(taskId)+ const pending = state?.pending+ if (!state || !pending) return+ const task = this.deps.tasks.getById(taskId)+ if (!task || task.engineTaskId !== state.engineGid || terminal(task)) return+ const engineTask = await this.deps.adapter.getTaskStatus(state.engineGid)+ if (!engineTask)+ throw new Error('Tracker engine task unavailable; recovery pending')+ const actual = unique(+ await this.deps.adapter.getTaskBtTracker(state.engineGid)+ )+ this.current(taskId, state.engineGid)+ let recovered: TaskTrackerOwnership = state+ if (same(actual, pending.after)) recovered = pending.next+ else if (!same(actual, pending.before)) {+ // An external client or an interrupted generation changed the options.+ // Preserve every observed URL and surrender ambiguous ownership.+ recovered = {+ ...state,+ manual: actual,+ managed: [],+ revision: state.revision + 1,+ }+ }+ const latest = this.deps.repository.get(taskId)+ if (+ latest?.pending?.resumeRequired &&+ this.controlIntents.get(taskId) !== true+ ) {+ const current = this.current(taskId, state.engineGid)+ if (+ current.status === TaskStatus.Paused ||+ engineTask.status === TaskStatus.Paused+ )+ try {+ await this.deps.actions.resumeTask(taskId)+ } catch (error) {+ this.recordFailure(taskId, 'resume')+ throw error+ }+ this.current(taskId, state.engineGid)+ }+ this.deps.repository.save(taskId, {+ ...recovered,+ lastError: latest?.lastError,+ pending: null,+ })+ }++ private recovery: Promise<void> | null = null+ recover(): Promise<void> {+ if (this.stopped) return Promise.resolve()+ if (this.recovery) return this.recovery+ const ids = unique([+ ...this.deps.repository.pendingTaskIds(),+ ...this.deps.tasks+ .getAll()+ .filter(+ (task) =>+ task.bt && !terminal(task) && !this.deps.repository.get(task.id)+ )+ .map((task) => task.id),+ ])+ // Bound background RPC work; never pause an active task to adopt a legacy+ // baseline. Existing addresses are retained as manual, not guessed managed.+ this.recovery = (async () => {+ let index = 0+ await Promise.allSettled(+ Array.from({ length: Math.min(4, ids.length) }, async () => {+ while (index < ids.length && !this.stopped) {+ const id = ids[index++]+ if (!id) break+ await this.run(id, async () => {+ await this.recoverTask(id)+ if (this.deps.repository.get(id)) return+ const task = this.deps.tasks.getById(id)+ if (!task || terminal(task)) return+ if (!(await this.deps.adapter.getTaskStatus(task.engineTaskId)))+ return+ const { state } = await this.read(id, task.engineTaskId)+ this.deps.repository.save(id, state)+ }).catch(() => undefined)+ }+ })+ )+ })().finally(() => {+ this.recovery = null+ })+ return this.recovery+ }+ async stopAndDrain(): Promise<void> {+ this.stopped = true+ await Promise.allSettled([...this.operations.values()])+ }+}diff --git a/src/core/tracker/task-tracker.integration.test.ts b/src/core/tracker/task-tracker.integration.test.tsnew file mode 100644index 00000000..214df001--- /dev/null+++ b/src/core/tracker/task-tracker.integration.test.ts@@ -0,0 +1,231 @@+// @vitest-environment node+import { createHash } from 'node:crypto'+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { migrate } from '@core/session/migrations'+import { TaskManager } from '@core/task/task-manager'+import {+ makeDefaultBtExtension,+ TaskStatus,+ TaskType,+} from '@shared/types/task'+import {+ bundledAria2Exists,+ canBindLoopbackTcp,+ connectAdapter,+ spawnAria2ForTest,+} from '@test-utils/aria2'+import { makeDownloadTask } from '@test-utils/task'+import Database from 'better-sqlite3'+import { describe, expect, it, vi } from 'vitest'+import { TaskTrackerRepository } from './task-tracker-repository'+import { TaskTrackerService } from './task-tracker-service'++type Value = string | number | Buffer | Value[] | { [key: string]: Value }+function encode(value: Value): Buffer {+ if (typeof value === 'number') return Buffer.from(`i${value}e`)+ if (Array.isArray(value))+ return Buffer.concat([+ Buffer.from('l'),+ ...value.map(encode),+ Buffer.from('e'),+ ])+ if (typeof value === 'string' || Buffer.isBuffer(value)) {+ const bytes = Buffer.from(value)+ return Buffer.concat([Buffer.from(`${bytes.length}:`), bytes])+ }+ return Buffer.concat([+ Buffer.from('d'),+ ...Object.keys(value)+ .sort()+ .flatMap((key) => [encode(key), encode(value[key]!)]),+ Buffer.from('e'),+ ])+}+const native = 'http://127.0.0.1:9/native?passkey=kept'+const old = 'udp://127.0.0.1:10/announce'+const fresh = 'http://127.0.0.1:11/announce'+const manual = 'http://127.0.0.1:12/manual?passkey=keep'+const metadata = (isPrivate: boolean) =>+ encode({+ announce: native,+ 'announce-list': [[native]],+ info: {+ name: isPrivate ? 'private.bin' : 'public.bin',+ length: 10,+ 'piece length': 16384,+ pieces: createHash('sha1').update('0123456789').digest(),+ private: isPrivate ? 1 : 0,+ },+ })++describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(+ 'task Tracker lifecycle with real aria2 and SQLite',+ () => {+ it('replaces only owned supplements, preserves exclusions over re-add, protects private and unknown tasks', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-trackers-'))+ const handle = await spawnAria2ForTest({+ baseDir: root,+ extraArgs: [+ '--enable-dht=false',+ '--enable-dht6=false',+ '--bt-enable-lpd=false',+ ],+ })+ const wired = await connectAdapter(handle)+ const db = new Database(':memory:')+ db.pragma('foreign_keys = ON')+ migrate(db)+ const repository = new TaskTrackerRepository(db)+ const tasks = new TaskManager()+ let selected = [old]+ const actions = {+ pauseTask: vi.fn(async () => {+ throw new Error('All test tasks must remain paused')+ }),+ resumeTask: vi.fn(async () => {+ throw new Error('All test tasks must remain paused')+ }),+ }+ const service = new TaskTrackerService({+ adapter: wired.adapter,+ tasks,+ repository,+ selected: () => selected,+ actions,+ })+ wired.adapter.configureBtTrackerPolicy(service.prepareCreation)+ const make = (id: string, gid: string) => {+ db.prepare(+ 'INSERT INTO tasks (motrix_id,name,task_type,created_at,updated_at) VALUES (?, ?, ?, 1, 1)'+ ).run(id, id, 'bt')+ const task = makeDownloadTask({+ id,+ engineTaskId: gid,+ status: TaskStatus.Paused,+ type: TaskType.Bt,+ torrentMetaPath: '/fixture.torrent',+ bt: makeDefaultBtExtension(),+ })+ tasks.add(task)+ return task+ }+ try {+ const task = make('public', '1234567890abcdef')+ await wired.adapter.addTorrent({+ gid: task.engineTaskId,+ metadata: metadata(false),+ saveDir: root,+ pause: true,+ extraEngineOptions: { 'bt-tracker': manual },+ })+ expect(await wired.adapter.getTaskBtTracker(task.engineTaskId)).toEqual(+ [manual, old]+ )+ const initial = await service.plan(task.id, task.engineTaskId)+ expect(initial.added).toEqual([])+ selected = [fresh]+ const plan = await service.plan(task.id, task.engineTaskId)+ expect(plan).toMatchObject({+ added: [fresh],+ removed: [old],+ requiresPause: false,+ })+ await service.apply(task.id, task.engineTaskId, plan.fingerprint)+ expect(await wired.adapter.getTaskBtTracker(task.engineTaskId)).toEqual(+ [manual, fresh]+ )+ expect(+ (+ await wired.adapter.getTaskStatus(task.engineTaskId)+ )?.bt?.announceList.flat()+ ).toContain(native)+ await service.edit(task.id, task.engineTaskId, [manual])+ expect(repository.get(task.id)?.excluded).toContain(fresh)+ expect((await service.plan(task.id, task.engineTaskId)).added).toEqual(+ []+ )+ await wired.adapter.forceRemoveTask(task.engineTaskId)+ task.engineTaskId = '2234567890abcdef'+ tasks.set(task.id, task)+ await wired.adapter.addTorrent({+ gid: task.engineTaskId,+ metadata: metadata(false),+ saveDir: root,+ pause: true,+ })+ expect(await wired.adapter.getTaskBtTracker(task.engineTaskId)).toEqual(+ [manual]+ )+ const privateTask = make('private', '3234567890abcdef')+ await wired.adapter.addTorrent({+ gid: privateTask.engineTaskId,+ metadata: metadata(true),+ saveDir: root,+ pause: true,+ isPrivate: false,+ extraEngineOptions: {+ 'bt-tracker': fresh,+ 'bt-exclude-tracker': native,+ 'enable-peer-exchange': 'true',+ },+ })+ expect(+ await wired.adapter.getTaskBtTracker(privateTask.engineTaskId)+ ).toEqual([])+ expect(repository.get('private')?.isPrivate).toBe(true)+ expect(+ (await service.plan('private', privateTask.engineTaskId)).added+ ).toEqual([])+ await service.edit('private', privateTask.engineTaskId, [manual])+ await wired.adapter.forceRemoveTask(privateTask.engineTaskId)+ privateTask.engineTaskId = '5234567890abcdef'+ tasks.set(privateTask.id, privateTask)+ await wired.adapter.addTorrent({+ gid: privateTask.engineTaskId,+ metadata: metadata(true),+ saveDir: root,+ pause: true,+ isPrivate: true,+ })+ expect(+ await wired.adapter.getTaskBtTracker(privateTask.engineTaskId)+ ).toEqual([manual])+ expect(repository.get('private')?.managed).toEqual([])+ expect(+ (await wired.rpc.getOption(privateTask.engineTaskId))[+ 'bt-exclude-tracker'+ ]+ ).toBe('')+ expect(+ (await wired.rpc.getOption(privateTask.engineTaskId))[+ 'enable-peer-exchange'+ ]+ ).toBe('false')+ const magnet = make('magnet', '4234567890abcdef')+ await wired.adapter.createDownload({+ gid: magnet.engineTaskId,+ uris: [+ 'magnet:?xt=urn:btih:abcdef0123456789abcdef0123456789abcdef01',+ ],+ saveDir: root,+ pause: true,+ })+ expect(+ await wired.adapter.getTaskBtTracker(magnet.engineTaskId)+ ).toEqual([])+ expect(+ (await service.plan('magnet', magnet.engineTaskId)).protected+ ).toBe(true)+ expect(actions.pauseTask).not.toHaveBeenCalled()+ } finally {+ await service.stopAndDrain()+ wired.disconnect()+ await handle.kill()+ db.close()+ await rm(root, { recursive: true, force: true })+ }+ }, 30000)+ }+)diff --git a/src/core/tracker/tracker-http-client.ts b/src/core/tracker/tracker-http-client.tsindex a06c8215..451ef275 100644--- a/src/core/tracker/tracker-http-client.ts+++ b/src/core/tracker/tracker-http-client.ts@@ -3,9 +3,18 @@ import type { ProxyConfig } from '@shared/types/tracker'interface TrackerRequestInit {method?: stringsignal?: AbortSignal+ headers?: Record<string, string>}-interface TrackerResponse {+export interface TrackerResponse {+ status?: number+ headers?: { get(name: string): string | null }+ body?: {+ getReader(): {+ read(): Promise<{ done: boolean; value?: Uint8Array }>+ cancel(): Promise<void>+ }+ } | nulltext(): Promise<string>}diff --git a/src/core/tracker/tracker-manager.test.ts b/src/core/tracker/tracker-manager.test.tsindex b4afee19..07bb40dd 100644--- a/src/core/tracker/tracker-manager.test.ts+++ b/src/core/tracker/tracker-manager.test.ts@@ -4,6 +4,7 @@ import type { CuratedTrackerList } from '@shared/types/tracker'import type { Mock } from 'vitest'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { TrackerManager } from './tracker-manager'+import { TrackerStore } from './tracker-store'function createMockRpcClient() {return {@@ -44,7 +45,16 @@ function createMockSettingsManager() {tracker: {autoSync: false,syncIntervalHours: 12,- sources: [],+ sources: [+ {+ id: 's1',+ label: 'S1',+ url: 'http://example/list',+ enabled: true,+ builtin: false,+ cdn: false,+ },+ ],sourcesEnabled: true,probeEnabled: true,probeTimeoutMs: 5000,@@ -72,7 +82,14 @@ function createMockSyncer() {return {fetch: vi.fn().mockResolvedValue({trackers: ['udp://a.com:1337', 'http://b.com/ann', 'udp://c.com:80'],- sourceStatus: { s1: { ok: true, count: 3, elapsedMs: 100 } },+ sourceStatus: {+ s1: {+ ok: true,+ count: 3,+ elapsedMs: 100,+ urls: ['udp://a.com:1337', 'http://b.com/ann', 'udp://c.com:80'],+ },+ },}),}}@@ -85,7 +102,7 @@ function createMockProber() {protocol: 'udp',status: 'healthy',lastProbeMs: 20,- lastProbeAt: 1000,+ lastProbeAt: Date.now(),successCount: 1,failCount: 0,successRate: 1.0,@@ -95,7 +112,7 @@ function createMockProber() {protocol: 'http',status: 'unreachable',lastProbeMs: null,- lastProbeAt: 1000,+ lastProbeAt: Date.now(),successCount: 0,failCount: 1,successRate: 0,@@ -105,7 +122,7 @@ function createMockProber() {protocol: 'udp',status: 'healthy',lastProbeMs: 50,- lastProbeAt: 1000,+ lastProbeAt: Date.now(),successCount: 1,failCount: 0,successRate: 1.0,@@ -126,11 +143,9 @@ function createMockStore() {return {load: vi.fn().mockResolvedValue(data),save: vi.fn().mockResolvedValue(undefined),- mergeHealth: vi.fn().mockImplementation((_existing, fresh) => {- const map: Record<string, unknown> = {}- for (const h of fresh) map[h.url] = h- return map- }),+ mergeHealth: vi.fn((existing, fresh) =>+ new TrackerStore('/unused').mergeHealth(existing, fresh)+ ),}}@@ -152,6 +167,7 @@ describe('TrackerManager', () => {let manager: TrackerManagerbeforeEach(() => {+ vi.spyOn(Math, 'random').mockReturnValue(0)vi.useFakeTimers()rpc = createMockRpcClient()eventBus = createMockEventBus()@@ -167,6 +183,7 @@ describe('TrackerManager', () => {prober as never,store as never)+ eventBus.emit(Events.EngineRecovered)})afterEach(() => {@@ -179,17 +196,17 @@ describe('TrackerManager', () => {expect(syncer.fetch).toHaveBeenCalledOnce()expect(prober.probe).toHaveBeenCalledOnce()- expect(store.save).toHaveBeenCalledOnce()+ expect(store.save).toHaveBeenCalled()expect(rpc.changeGlobalOption).toHaveBeenCalledOnce()const opts = rpc.changeGlobalOption.mock.calls[0][0]expect(opts['bt-tracker']).toContain('udp://a.com:1337')expect(opts['bt-tracker']).toContain('udp://c.com:80')- expect(opts['bt-tracker']).not.toContain('http://b.com/ann')+ expect(opts['bt-tracker']).toContain('http://b.com/ann') // A single timeout only lowers rank.expect(result.totalFetched).toBe(3)- expect(result.totalHealthy).toBe(2)- expect(result.totalCurated).toBe(2)+ expect(result.totalHealthy).toBe(3)+ expect(result.totalCurated).toBe(3)})it('publishes queryable sync stages for automatic and manual callers', async () => {@@ -210,7 +227,7 @@ describe('TrackerManager', () => {expect(manager.getSyncStatus()).toBe('idle')})- it.each(['fetch', 'probe', 'save', 'apply'] as const)(+ it.each(['fetch', 'probe', 'save'] as const)('publishes failure when %s rejects and clears it on retry',async (stage) => {const operation = {@@ -311,30 +328,33 @@ describe('TrackerManager', () => {expect(syncer.fetch).toHaveBeenCalledOnce()})- it('waits for the engine and then fills the empty cache after three seconds', async () => {+ it('maintains sources while the engine is offline and applies on recovery', async () => {eventBus.emit(Events.EngineDisconnected)+ rpc.changeGlobalOption.mockClear()withTracker({ autoSync: true })manager.applySyncScheduleChange()- await vi.advanceTimersByTimeAsync(60_000)- expect(syncer.fetch).not.toHaveBeenCalled()- eventBus.emit(Events.EngineRecovered)- await vi.advanceTimersByTimeAsync(2_999)- expect(syncer.fetch).not.toHaveBeenCalled()- await vi.advanceTimersByTimeAsync(1)+ await vi.advanceTimersByTimeAsync(3_000)expect(syncer.fetch).toHaveBeenCalledOnce()+ expect(rpc.changeGlobalOption).not.toHaveBeenCalled()+ expect(manager.getCuratedList().pendingEngineApply).toBe(true)+ eventBus.emit(Events.EngineRecovered)+ await vi.advanceTimersByTimeAsync(0)+ expect(rpc.changeGlobalOption).toHaveBeenCalledOnce()+ expect(manager.getCuratedList().pendingEngineApply).toBe(false)})- it('honors the remaining cache lifetime across startup', async () => {+ it('deduplicates recent successful startup checks', async () => {const cached = await store.load()store.load.mockResolvedValue({...cached,effective: ['udp://cached:80'],- lastSyncAt: Date.now() - 40 * 60_000,+ sourceMap: { 'udp://cached:80': ['s1'] },+ lastSyncAt: Date.now() - 20 * 60_000,})withTracker({ autoSync: true, syncIntervalHours: 1 })await manager.init()expect(manager.getCuratedList().effective).toEqual(['udp://cached:80'])- await vi.advanceTimersByTimeAsync(20 * 60_000 - 1)+ await vi.advanceTimersByTimeAsync(40 * 60_000 - 1)expect(syncer.fetch).not.toHaveBeenCalled()await vi.advanceTimersByTimeAsync(1)expect(syncer.fetch).toHaveBeenCalledOnce()@@ -347,6 +367,7 @@ describe('TrackerManager', () => {store.load.mockResolvedValue({...cached,effective: ['udp://cached:80'],+ sourceMap: { 'udp://cached:80': ['s1'] },lastSyncAt: Date.now() - 13 * 3600_000,})withTracker({ autoSync: true })@@ -364,7 +385,10 @@ describe('TrackerManager', () => {const manual = manager.syncAndCurate()await vi.advanceTimersByTimeAsync(2 * 3600_000)expect(syncer.fetch).toHaveBeenCalledOnce()- fetched.resolve({ trackers: [], sourceStatus: {} })+ fetched.resolve({+ trackers: [],+ sourceStatus: { s1: { ok: true, urls: [], count: 0, elapsedMs: 0 } },+ })await manualawait vi.advanceTimersByTimeAsync(3_000)expect(syncer.fetch).toHaveBeenCalledOnce()@@ -372,7 +396,7 @@ describe('TrackerManager', () => {expect(syncer.fetch).toHaveBeenCalledTimes(2)})- it('waits for the regular interval after failure instead of retrying every three seconds', async () => {+ it('backs off for five minutes after an unexpected failure', async () => {withTracker({ autoSync: true, syncIntervalHours: 1 })syncer.fetch.mockRejectedValueOnce(new Error('offline'))manager.applySyncScheduleChange()@@ -380,7 +404,7 @@ describe('TrackerManager', () => {expect(syncer.fetch).toHaveBeenCalledOnce()await vi.advanceTimersByTimeAsync(3_000)expect(syncer.fetch).toHaveBeenCalledOnce()- await vi.advanceTimersByTimeAsync(3600_000 - 3_000)+ await vi.advanceTimersByTimeAsync(5 * 60_000 - 3_000)expect(syncer.fetch).toHaveBeenCalledTimes(2)})@@ -408,6 +432,7 @@ describe('TrackerManager', () => {await Promise.resolve()manager.dispose()+ const appliedBeforeShutdown = rpc.changeGlobalOption.mock.calls.lengthloaded.resolve({effective: ['udp://cached-tracker'],blacklist: [],@@ -419,16 +444,137 @@ describe('TrackerManager', () => {await initializingawait vi.advanceTimersByTimeAsync(3_600_000)- expect(rpc.changeGlobalOption).not.toHaveBeenCalled()+ expect(rpc.changeGlobalOption).toHaveBeenCalledTimes(+ appliedBeforeShutdown+ )expect(syncer.fetch).not.toHaveBeenCalled()})})+ it('preserves the last global success and retries only failed sources', async () => {+ settings.get().tracker.sources.push({+ ...settings.get().tracker.sources[0],+ id: 's2',+ url: 'http://example/second',+ })+ syncer.fetch.mockResolvedValueOnce({+ trackers: ['udp://a:80', 'udp://b:80'],+ sourceStatus: {+ s1: { ok: true, count: 1, urls: ['udp://a:80'] },+ s2: { ok: true, count: 1, urls: ['udp://b:80'] },+ },+ })+ await manager.syncAndCurate()+ const successAt = manager.getCuratedList().lastSyncAt+ await vi.advanceTimersByTimeAsync(1000)+ syncer.fetch.mockResolvedValueOnce({+ trackers: [],+ sourceStatus: {+ s1: { ok: true, count: 0, urls: [] },+ s2: { ok: false, count: 0, failure: 'network' },+ },+ })+ await manager.syncAndCurate()+ expect(manager.getCuratedList()).toMatchObject({+ effective: ['udp://b:80'],+ lastSyncAt: successAt,+ history: [+ expect.objectContaining({ outcome: 'partial' }),+ expect.anything(),+ ],+ })+ syncer.fetch.mockResolvedValueOnce({+ trackers: ['udp://c:80'],+ sourceStatus: { s2: { ok: true, count: 1, urls: ['udp://c:80'] } },+ })+ await manager.syncAndCurate('retry')+ expect(+ syncer.fetch.mock.lastCall?.[0].map((s: { id: string }) => s.id)+ ).toEqual(['s2'])+ expect(manager.getCuratedList().effective).toEqual(['udp://c:80'])+ })++ it('cannot restore a source disabled while its request is in flight', async () => {+ const pending = deferred<Awaited<ReturnType<typeof syncer.fetch>>>()+ syncer.fetch.mockReturnValueOnce(pending.promise)+ const run = manager.syncAndCurate()+ await vi.advanceTimersByTimeAsync(0)+ settings.get().tracker.sources[0].enabled = false+ await manager.applySelectionChange()+ pending.resolve({+ trackers: ['udp://late:80'],+ sourceStatus: {+ s1: { ok: true, urls: ['udp://late:80'], count: 1, elapsedMs: 0 },+ },+ })+ await run+ expect(manager.getCuratedList().effective).toEqual([])+ expect(rpc.changeGlobalOption).toHaveBeenLastCalledWith({+ 'bt-tracker': '',+ 'bt-exclude-tracker': '',+ })+ })++ it('records a pending apply when the engine rejects updated defaults', async () => {+ rpc.changeGlobalOption.mockRejectedValueOnce(new Error('offline'))+ await manager.syncAndCurate()+ expect(manager.getCuratedList().pendingEngineApply).toBe(true)+ expect(manager.getSyncStatus()).toBe('idle')+ await manager.init()+ await vi.advanceTimersByTimeAsync(0)+ eventBus.emit(Events.EngineRecovered)+ await vi.advanceTimersByTimeAsync(0)+ expect(manager.getCuratedList().pendingEngineApply).toBe(false)+ })++ it('filters blacklisted additions before sending them to the engine without pausing tasks', async () => {+ settings.get().tracker.blacklistEnabled = true+ settings.get().tracker.blacklistSources.push({+ ...settings.get().tracker.sources[0],+ id: 'b1',+ url: 'http://example/blacklist',+ })+ syncer.fetch+ .mockResolvedValueOnce({+ trackers: ['udp://a:80', 'udp://b:80'],+ sourceStatus: {+ s1: { ok: true, count: 2, urls: ['udp://a:80', 'udp://b:80'] },+ },+ })+ .mockResolvedValueOnce({+ trackers: ['udp://b:80'],+ sourceStatus: { b1: { ok: true, count: 1, urls: ['udp://b:80'] } },+ })+ await manager.syncAndCurate()+ expect(rpc.changeGlobalOption.mock.lastCall?.[0]['bt-tracker']).toBe(+ 'udp://a:80'+ )+ expect(rpc.pause).not.toHaveBeenCalled()+ expect(rpc.changeOption).not.toHaveBeenCalled()+ })++ it('keeps the sync single-flight through final persistence and suppresses shutdown publication', async () => {+ const finalSave = deferred<void>()+ let saves = 0+ store.save.mockImplementation(() =>+ ++saves === 3 ? finalSave.promise : Promise.resolve()+ )+ const run = manager.syncAndCurate()+ await vi.advanceTimersByTimeAsync(0)+ expect(saves).toBe(3)+ expect(manager.syncAndCurate()).toBe(run)+ const drain = manager.stopAndDrain()+ eventBus.emit.mockClear()+ finalSave.resolve()+ await drain+ expect(eventBus.emit).not.toHaveBeenCalled()+ })+it('emits TrackerListUpdated after sync', async () => {await manager.syncAndCurate()expect(eventBus.emit).toHaveBeenCalledWith('event:trackerListUpdated',- expect.objectContaining({ count: 2 })+ expect.objectContaining({ count: 3 }))})@@ -444,14 +590,22 @@ describe('TrackerManager', () => {scopes: { download: false, updateApp: false, updateTrackers: true },})await manager.syncAndCurate()- expect(syncer.fetch).toHaveBeenCalledWith(expect.anything(), {- server: 'http://p.example.com:8080',- })+ expect(syncer.fetch).toHaveBeenCalledWith(+ expect.anything(),+ { server: 'http://p.example.com:8080' },+ expect.any(Object),+ expect.any(AbortSignal)+ )})it('passes undefined proxy when updateTrackers scope is off', async () => {await manager.syncAndCurate()- expect(syncer.fetch).toHaveBeenCalledWith(expect.anything(), undefined)+ expect(syncer.fetch).toHaveBeenCalledWith(+ expect.anything(),+ undefined,+ expect.any(Object),+ expect.any(AbortSignal)+ )})it('uses the resolved HTTP bridge for SOCKS5 tracker fetches', async () => {@@ -481,9 +635,12 @@ describe('TrackerManager', () => {bridgedManager.dispose()expect(resolveProxyUrl).toHaveBeenCalledWith(settings.getProxy())- expect(syncer.fetch).toHaveBeenCalledWith(expect.anything(), {- server: 'http://127.0.0.1:43123',- })+ expect(syncer.fetch).toHaveBeenCalledWith(+ expect.anything(),+ { server: 'http://127.0.0.1:43123' },+ expect.any(Object),+ expect.any(AbortSignal)+ )})it('invalidateProxyCache is callable without throwing', () => {@@ -527,33 +684,33 @@ describe('TrackerManager', () => {it('builds sourceMap from per-source urls in SourceFetchStatus', async () => {syncer.fetch.mockResolvedValue({- trackers: ['udp://a', 'udp://b'],+ trackers: ['udp://a:80', 'udp://b:80'],sourceStatus: {- 'src-1': {+ s1: {ok: true,count: 2,elapsedMs: 5,- urls: ['udp://a', 'udp://b'],+ urls: ['udp://a:80', 'udp://b:80'],},},})prober.probe.mockResolvedValue([{- url: 'udp://a',+ url: 'udp://a:80',protocol: 'udp',status: 'healthy',lastProbeMs: 10,- lastProbeAt: 1000,+ lastProbeAt: Date.now(),successCount: 1,failCount: 0,successRate: 1.0,},{- url: 'udp://b',+ url: 'udp://b:80',protocol: 'udp',status: 'healthy',lastProbeMs: 20,- lastProbeAt: 1000,+ lastProbeAt: Date.now(),successCount: 1,failCount: 0,successRate: 1.0,@@ -564,7 +721,7 @@ describe('TrackerManager', () => {expect(store.save).toHaveBeenCalledWith(expect.objectContaining({- sourceMap: { 'udp://a': ['src-1'], 'udp://b': ['src-1'] },+ sourceMap: { 'udp://a:80': ['s1'], 'udp://b:80': ['s1'] },}))})@@ -614,8 +771,10 @@ function makeManager(effective: effectiveTrackers,blacklist: [],healthMap: {},- sourceMap: {},- lastSyncAt: null,+ sourceMap: Object.fromEntries(+ effectiveTrackers.map((url) => [url, ['s1']])+ ),+ lastSyncAt: Date.now(),lastProbeAt: null,}),save: vi.fn().mockResolvedValue(undefined),@@ -641,6 +800,7 @@ function makeManager(store as never,taskActions)+ eventBus.emit(Events.EngineRecovered)// Eagerly initialise so curated.effective is populated from the store mockreturn { manager: mgr, initPromise: mgr.init(), taskActions }}@@ -788,17 +948,17 @@ describe('TrackerManager.syncBtTracker', () => {it('additively merges global into effective and writes back', async () => {const rpc = makeRpcMock({status: 'paused',- getOption: { 'bt-tracker': 'http://a.example,http://b.example' },+ getOption: { 'bt-tracker': 'http://a.example/,http://b.example/' },})const { manager, initPromise } = makeManager(rpc, {- curatedEffective: ['http://b.example', 'http://c.example'],+ curatedEffective: ['http://b.example/', 'http://c.example/'],})await initPromiseawait manager.syncBtTracker('task-1', 'gid-1', false)const optsArg = (rpc.changeOption as Mock).mock.calls[0][1]const trackers = (optsArg['bt-tracker'] as string).split(',')expect(new Set(trackers)).toEqual(- new Set(['http://a.example', 'http://b.example', 'http://c.example'])+ new Set(['http://a.example/', 'http://b.example/', 'http://c.example/']))})@@ -819,7 +979,10 @@ describe('TrackerManager.applySourcesChange', () => {const { manager, initPromise } = makeManager(rpc)await initPromiseawait manager.applySourcesChange(false)- expect(rpc.changeGlobalOption).toHaveBeenCalledWith({ 'bt-tracker': '' })+ expect(rpc.changeGlobalOption).toHaveBeenCalledWith({+ 'bt-tracker': '',+ 'bt-exclude-tracker': '',+ })})it('triggers syncAndCurate when enabled', async () => {@@ -844,6 +1007,7 @@ describe('TrackerManager.applyBlacklistChange', () => {await initPromiseawait manager.applyBlacklistChange(false)expect(rpc.changeGlobalOption).toHaveBeenCalledWith({+ 'bt-tracker': '','bt-exclude-tracker': '',})})@@ -887,7 +1051,16 @@ describe('TrackerManager engine-ready cache push', () => {tracker: {autoSync: false,syncIntervalHours: 12,- sources: [],+ sources: [+ {+ id: 's1',+ label: 'S1',+ url: 'http://example/list',+ enabled: true,+ builtin: false,+ cdn: false,+ },+ ],sourcesEnabled: opts.sourcesEnabled,probeEnabled: true,probeTimeoutMs: 5000,@@ -895,7 +1068,16 @@ describe('TrackerManager engine-ready cache push', () => {minSuccessRate: 0.5,maxTrackerCount: 50,blacklistEnabled: opts.blacklistEnabled,- blacklistSources: [],+ blacklistSources: [+ {+ id: 'b1',+ label: 'B1',+ url: 'http://example/blocked',+ enabled: true,+ builtin: false,+ cdn: false,+ },+ ],},})return base@@ -909,8 +1091,11 @@ describe('TrackerManager engine-ready cache push', () => {effective,blacklist,healthMap: {},- sourceMap: {},- lastSyncAt: 1,+ sourceMap: Object.fromEntries([+ ...effective.map((url) => [url, ['s1']]),+ ...blacklist.map((url) => [url, ['b1']]),+ ]),+ lastSyncAt: Date.now(),lastProbeAt: 1,}}@@ -935,47 +1120,52 @@ describe('TrackerManager engine-ready cache push', () => {it('waits for engine ready before pushing cached effective and blacklist', async () => {const { mgr, rpc, eventBus } = makeHarness(- makeCached(['udp://cached-tracker'], ['udp://cached-bad']),+ makeCached(['udp://cached-tracker:80'], ['udp://cached-bad:80']),{ sourcesEnabled: true, blacklistEnabled: true })await mgr.init()expect(rpc.changeGlobalOption).not.toHaveBeenCalled()eventBus.emit(Events.EngineRecovered)+ await new Promise((resolve) => setTimeout(resolve, 0))expect(rpc.changeGlobalOption).toHaveBeenCalledWith({- 'bt-tracker': 'udp://cached-tracker',- 'bt-exclude-tracker': 'udp://cached-bad',+ 'bt-tracker': 'udp://cached-tracker:80',+ 'bt-exclude-tracker': '',})mgr.dispose()})it('pushes after init when engine ready arrives while cache is loading', async () => {- const cached = makeCached(['udp://cached-tracker'])+ const cached = makeCached(['udp://cached-tracker:80'])const loaded = deferred<CuratedTrackerList>()const { mgr, rpc, eventBus, store } = makeHarness(cached)store.load.mockReturnValueOnce(loaded.promise)const initializing = mgr.init()eventBus.emit(Events.EngineRecovered)+ await new Promise((resolve) => setTimeout(resolve, 0))expect(rpc.changeGlobalOption).not.toHaveBeenCalled()loaded.resolve(cached)await initializingexpect(rpc.changeGlobalOption).toHaveBeenCalledWith({- 'bt-tracker': 'udp://cached-tracker',+ 'bt-tracker': 'udp://cached-tracker:80',+ 'bt-exclude-tracker': '',})mgr.dispose()})it('reapplies cached state after an engine reconnect', async () => {const { mgr, rpc, eventBus } = makeHarness(- makeCached(['udp://cached-tracker'])+ makeCached(['udp://cached-tracker:80']))await mgr.init()eventBus.emit(Events.EngineRecovered)+ await new Promise((resolve) => setTimeout(resolve, 0))eventBus.emit(Events.EngineDisconnected)eventBus.emit(Events.EngineRecovered)+ await new Promise((resolve) => setTimeout(resolve, 0))expect(rpc.changeGlobalOption).toHaveBeenCalledTimes(2)mgr.dispose()@@ -983,12 +1173,13 @@ describe('TrackerManager engine-ready cache push', () => {it('does not push after disposal', async () => {const { mgr, rpc, eventBus } = makeHarness(- makeCached(['udp://cached-tracker'])+ makeCached(['udp://cached-tracker:80']))await mgr.init()mgr.dispose()eventBus.emit(Events.EngineRecovered)+ await new Promise((resolve) => setTimeout(resolve, 0))expect(rpc.changeGlobalOption).not.toHaveBeenCalled()expect(eventBus.off).toHaveBeenCalledWith(@@ -1001,7 +1192,7 @@ describe('TrackerManager engine-ready cache push', () => {const pushStarted = deferred<void>()const allowPush = deferred<void>()const { mgr, rpc, eventBus } = makeHarness(- makeCached(['udp://cached-tracker'])+ makeCached(['udp://cached-tracker:80']))rpc.changeGlobalOption.mockImplementation(async () => {pushStarted.resolve()@@ -1010,6 +1201,7 @@ describe('TrackerManager engine-ready cache push', () => {})await mgr.init()eventBus.emit(Events.EngineRecovered)+ await new Promise((resolve) => setTimeout(resolve, 0))await pushStarted.promiseconst draining = mgr.stopAndDrain()@@ -1025,14 +1217,18 @@ describe('TrackerManager engine-ready cache push', () => {expect(drained).toBe(true)})- it('does not push when both subsystems are disabled', async () => {+ it('clears stale defaults when both subsystems are disabled', async () => {const { mgr, rpc, eventBus } = makeHarness(makeCached(['udp://x'], ['udp://y']),{ sourcesEnabled: false, blacklistEnabled: false })await mgr.init()eventBus.emit(Events.EngineRecovered)- expect(rpc.changeGlobalOption).not.toHaveBeenCalled()+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(rpc.changeGlobalOption).toHaveBeenCalledWith({+ 'bt-tracker': '',+ 'bt-exclude-tracker': '',+ })mgr.dispose()})})diff --git a/src/core/tracker/tracker-manager.ts b/src/core/tracker/tracker-manager.tsindex 340bea0b..c4c21309 100644--- a/src/core/tracker/tracker-manager.ts+++ b/src/core/tracker/tracker-manager.ts@@ -1,39 +1,37 @@+import { createHash, randomUUID } from 'node:crypto'+import { networkInterfaces } from 'node:os'+import type { EngineAdapter } from '@core/engine/engine-adapter'import { proxyToFetchUrl } from '@core/proxy/serializers'+import type { TaskManager } from '@core/task/task-manager'import { type EventChannel, Events } from '@shared/protocol/events'+import type { TaskTrackerPlan } from '@shared/schemas/task-tracker'+import {+ TRACKER_HISTORY_MAX_AGE_MS,+ TRACKER_PROBE_FRESH_MS,+ type TrackerState,+ trackerStateSchema,+} from '@shared/schemas/tracker-state'import type { TrackerSyncStatus } from '@shared/schemas/tracker-sync'-import type { ProxySettings } from '@shared/types/settings'+import type { ProxySettings, TrackerSettings } from '@shared/types/settings'import type {CuratedTrackerList,ProxyConfig,- SourceFetchStatus,SyncAndCurateResult,SyncResult,- TrackerHealth,} from '@shared/types/tracker'import { trackerLogger } from './logger'+import type { TaskTrackerRepository } from './task-tracker-repository'+import { TaskTrackerService } from './task-tracker-service'import type { TrackerProber } from './tracker-prober'+import { selectTrackers, sourceKey } from './tracker-selector'+import { mergeSourceSnapshots } from './tracker-snapshots'import type { TrackerStore } from './tracker-store'+import { pruneTrackerHealth } from './tracker-store'import type { TrackerSyncer } from './tracker-syncer'const log = trackerLogger('manager')const STARTUP_SYNC_DELAY_MS = 3_000-function buildSourceMap(- statuses: Array<Record<string, SourceFetchStatus>>-): Record<string, string[]> {- const result: Record<string, string[]> = {}- for (const status of statuses) {- for (const [sourceId, s] of Object.entries(status)) {- if (!s.urls) continue- for (const url of s.urls) {- if (!result[url]) result[url] = []- if (!result[url].includes(sourceId)) result[url].push(sourceId)- }- }- }- return result-}-interface RpcClient {changeGlobalOption(opts: Record<string, string>): Promise<'OK'>changeOption(gid: string, opts: Record<string, string>): Promise<'OK'>@@ -50,6 +48,10 @@ interface EventBus {}export interface TrackerTaskActions {+ runTaskMutation?<T>(+ taskIds: readonly string[],+ operation: () => Promise<T>+ ): Promise<T>pauseTask(taskId: string): Promise<void>resumeTask(taskId: string): Promise<void>}@@ -57,33 +59,7 @@ export interface TrackerTaskActions {interface SettingsManager {get(): {onboarding: { disclaimerAccepted: boolean }- tracker: {- autoSync: boolean- syncIntervalHours: number- sources: {- id: string- label: string- url: string- builtin: boolean- enabled: boolean- cdn: boolean- }[]- sourcesEnabled: boolean- probeEnabled: boolean- probeTimeoutMs: number- healthyThresholdMs: number- minSuccessRate: number- maxTrackerCount: number- blacklistEnabled: boolean- blacklistSources: {- id: string- label: string- url: string- builtin: boolean- enabled: boolean- cdn: boolean- }[]- }+ tracker: TrackerSettings}getProxy(): ProxySettings}@@ -101,16 +77,16 @@ async function resolveProxyUrlWithoutBridge(}export class TrackerManager {- private curated: CuratedTrackerList = {- effective: [],- blacklist: [],- healthMap: {},- sourceMap: {},- lastSyncAt: null,- lastProbeAt: null,- }+ private curated: TrackerState = trackerStateSchema.parse({})+ private readonly abort = new AbortController()+ private engineApplyQueue: Promise<void> = Promise.resolve()+ private routeKey: string | undefined+ private failureRetryAt = 0+ private startupCheck = false+ private clockWatch: ReturnType<typeof setInterval> | null = nullprivate timer: ReturnType<typeof setTimeout> | null = nullprivate syncInFlight: Promise<SyncAndCurateResult> | null = null+ private finishingSync = falseprivate syncStatus: TrackerSyncStatus = 'idle'private disposed = falseprivate initialized = false@@ -118,16 +94,20 @@ export class TrackerManager {private lifecycleGeneration = 0private readonly inFlightTrackerChanges = new Set<Promise<void>>()private readonly inFlightCachedStatePushes = new Set<Promise<void>>()+ private taskTrackers?: TaskTrackerService+ private readonly periodicJitterMs = Math.floor(Math.random() * 30_000)private stopPromise: Promise<void> | null = nullprivate readonly handleEngineRecovered = (): void => {this.engineReady = trueif (!this.initialized || this.disposed) return- void this.queueCachedStatePush()+ void this.queueCachedStatePush().catch(() => {+ if (!this.disposed) log.warn('failed to persist tracker defaults')+ })this.applySyncScheduleChange()+ void this.taskTrackers?.recover()}private readonly handleEngineDisconnected = (): void => {this.engineReady = false- this.clearSyncTimer()}constructor(@@ -144,12 +124,49 @@ export class TrackerManager {this.eventBus.on(Events.EngineDisconnected, this.handleEngineDisconnected)}+ configureTaskTracking(+ adapter: EngineAdapter,+ tasks: TaskManager,+ repository: TaskTrackerRepository+ ): void {+ if (!this.taskActions) throw new Error('Tracker task actions missing')+ this.taskTrackers = new TaskTrackerService({+ adapter,+ tasks,+ repository,+ actions: this.taskActions,+ selected: () => this.getCuratedList().effective,+ })+ adapter.configureBtTrackerPolicy?.(this.taskTrackers.prepareCreation)+ }++ noteTaskControl(taskId: string, paused: boolean): void {+ this.taskTrackers?.noteTaskControl(taskId, paused)+ }++ getTaskTrackerPlan(+ taskId: string,+ engineGid: string+ ): Promise<TaskTrackerPlan> {+ if (!this.taskTrackers) throw new Error('Task trackers not configured')+ return this.taskTrackers.plan(taskId, engineGid)+ }++ applyTaskTrackerPlan(+ taskId: string,+ engineGid: string,+ fingerprint: string+ ): Promise<void> {+ if (!this.taskTrackers) throw new Error('Task trackers not configured')+ return this.taskTrackers.apply(taskId, engineGid, fingerprint)+ }+async init(): Promise<void> {if (this.disposed) returnconst generation = this.lifecycleGenerationconst curated = await this.store.load()if (!this.isCurrent(generation)) return- this.curated = curated+ this.curated = trackerStateSchema.parse(curated)const cfg = this.settings.get().trackerlog.info({@@ -160,15 +177,61 @@ export class TrackerManager {},'init: loaded curated list')+ if (curated.version !== 2) {+ for (const kind of ['tracker', 'blacklist'] as const) {+ const sources = kind === 'tracker' ? cfg.sources : cfg.blacklistSources+ for (const source of sources) {+ const urls = Object.entries(curated.sourceMap)+ .filter(([, ids]) => ids.includes(source.id))+ .map(([url]) => url)+ if (!urls.length || curated.lastSyncAt === null) continue+ this.curated.snapshots[sourceKey(kind, source.id)] = {+ id: source.id,+ url: source.url,+ kind,+ urls,+ lastAttemptAt: curated.lastSyncAt,+ lastSuccessAt: curated.lastSyncAt,+ contentChangedAt: curated.lastSyncAt,+ error: null,+ failures: 0,+ nextRetryAt: null,+ }+ }+ }+ }+ this.reselect()this.initialized = true- this.applySyncScheduleChange()+ if (this.engineReady) void this.taskTrackers?.recover()+ this.startupCheck = true+ this.applySyncScheduleChange(true)+ if (this.clockWatch) clearInterval(this.clockWatch)+ let observedAt = Date.now()+ let network = this.networkSignature()+ this.clockWatch = setInterval(() => {+ if (this.engineReady) void this.taskTrackers?.recover()+ const now = Date.now()+ const currentNetwork = this.networkSignature()+ if (+ now < observedAt ||+ now - observedAt > 120_000 ||+ network !== currentNetwork+ )+ this.notifyWake()+ network = currentNetwork+ observedAt = now+ }, 60_000)+ this.clockWatch.unref?.()if (this.engineReady) {await this.queueCachedStatePush()}}private queueCachedStatePush(): Promise<void> {- const operation = this.pushCachedState()+ const operation = this.engineApplyQueue+ .catch(() => undefined)+ .then(() => this.pushCachedState())+ this.engineApplyQueue = operationthis.inFlightCachedStatePushes.add(operation)void operation.then(() => this.inFlightCachedStatePushes.delete(operation),@@ -178,213 +241,342 @@ export class TrackerManager {}private async pushCachedState(): Promise<void> {+ if (this.disposed || !this.engineReady) returnconst generation = this.captureGeneration()- const cfg = this.settings.get().tracker- const opts: Record<string, string> = {}- if (cfg.sourcesEnabled && this.curated.effective.length > 0) {- opts['bt-tracker'] = this.curated.effective.join(',')- }- if (cfg.blacklistEnabled && this.curated.blacklist.length > 0) {- opts['bt-exclude-tracker'] = this.curated.blacklist.join(',')- }- if (Object.keys(opts).length > 0) {- try {- await this.rpc.changeGlobalOption(opts)- if (!this.isCurrent(generation)) return- log.info(- { opts: Object.keys(opts) },- 'pushed cached state to aria2 after engine became ready'- )- } catch (err) {- if (!this.isCurrent(generation)) return- log.warn(- { err },- 'failed to push cached state after engine became ready'- )- }+ this.reselect()+ const revision = this.curated.revision+ try {+ await this.rpc.changeGlobalOption({+ 'bt-tracker': this.curated.effective.join(','),+ 'bt-exclude-tracker': '',+ })+ if (!this.isCurrent(generation)) return+ if (revision === this.curated.revision)+ this.curated.pendingEngineApply = false+ } catch {+ if (!this.isCurrent(generation)) return+ this.curated.pendingEngineApply = true+ log.warn(+ 'failed to apply cached tracker defaults; waiting for engine recovery'+ )}+ await this.store.save(this.curated)}- syncAndCurate(): Promise<SyncAndCurateResult> {+ syncAndCurate(+ trigger: 'manual' | 'scheduled' | 'retry' = 'manual'+ ): Promise<SyncAndCurateResult> {if (this.syncInFlight) return this.syncInFlightthis.clearSyncTimer()- const operation = this.performSyncAndCurate()+ const operation = this.performSyncAndCurate(trigger).catch((error) => {- if (!this.disposed) this.setSyncStatus('failed')+ if (!this.disposed) {+ this.failureRetryAt = Date.now() + 5 * 60_000+ this.setSyncStatus('failed')+ }throw error})- .finally(() => {- this.syncInFlight = null- // A failed/empty sync waits for the regular interval, rather than- // retrying every three seconds. Manual sync also resets the interval.- this.scheduleSync(- this.settings.get().tracker.syncIntervalHours * 3600_000- )+ .finally(async () => {+ this.finishingSync = true+ try {+ if (this.disposed) return+ this.applySyncScheduleChange()+ await this.store.save(this.curated)+ if (!this.disposed)+ this.eventBus.emit(Events.TrackerListUpdated, {+ count: this.curated.effective.length,+ })+ } catch (error) {+ if (!this.disposed) this.setSyncStatus('failed')+ throw error+ } finally {+ this.finishingSync = false+ this.syncInFlight = null+ }})this.syncInFlight = operationreturn operation}- private async performSyncAndCurate(): Promise<SyncAndCurateResult> {+ private async performSyncAndCurate(+ trigger: 'manual' | 'scheduled' | 'retry'+ ): Promise<SyncAndCurateResult> {const generation = this.captureGeneration()+ const startedAt = Date.now()this.setSyncStatus('fetching')- const cfg = this.settings.get().tracker- const totalStart = Date.now()- log.info(- {- sourcesEnabled: cfg.sourcesEnabled,- enabledSources: cfg.sources.filter((s) => s.enabled).length,- totalSources: cfg.sources.length,- blacklistEnabled: cfg.blacklistEnabled,- probeEnabled: cfg.probeEnabled,- maxTrackerCount: cfg.maxTrackerCount,- },- 'syncAndCurate start'- )-- const proxySettings = this.settings.getProxy()- const proxyUrl = await this.proxyUrlResolver(proxySettings)+ const cfg = structuredClone(this.settings.get().tracker)+ const proxyUrl = await this.proxyUrlResolver(this.settings.getProxy())this.assertCurrent(generation)const proxy: ProxyConfig | undefined = proxyUrl? { server: proxyUrl }: undefined-- let syncResult: SyncResult = { trackers: [], sourceStatus: {} }- let healthy: string[] = []- let healthMap = this.curated.healthMap-- if (cfg.sourcesEnabled) {- syncResult = await this.syncer.fetch(cfg.sources, proxy)+ this.routeKey = createHash('sha256')+ .update(proxyUrl ?? 'direct')+ .digest('hex')+ .slice(0, 16)+ this.pruneSnapshots()+ let snapshots = { ...this.curated.snapshots }+ const fetchKind = async (kind: 'tracker' | 'blacklist') => {+ const enabled =+ kind === 'tracker' ? cfg.sourcesEnabled : cfg.blacklistEnabled+ const sources = (+ kind === 'tracker' ? cfg.sources : cfg.blacklistSources+ ).filter(+ (source) =>+ enabled &&+ source.enabled &&+ (trigger !== 'retry' ||+ snapshots[sourceKey(kind, source.id)]?.error != null) &&+ (trigger !== 'scheduled' ||+ (this.startupCheck &&+ !snapshots[sourceKey(kind, source.id)]?.error &&+ Date.now() -+ (snapshots[sourceKey(kind, source.id)]?.lastSuccessAt ?? 0) >=+ 30 * 60_000) ||+ this.sourceDueAt(kind, source.id, source.url) <= Date.now())+ )+ if (!sources.length)+ return { trackers: [], sourceStatus: {} } as SyncResult+ const cache = Object.fromEntries(+ sources+ .map((source) => [source.id, snapshots[sourceKey(kind, source.id)]])+ .filter(([, snapshot]) => snapshot)+ )+ const result = await this.syncer.fetch(+ sources,+ proxy,+ cache,+ this.abort.signal+ )this.assertCurrent(generation)-- let healthResults: TrackerHealth[] = []- if (cfg.probeEnabled && syncResult.trackers.length > 0) {- this.setSyncStatus('probing')- healthResults = await this.prober.probe(syncResult.trackers, {- timeoutMs: cfg.probeTimeoutMs,- proxy,- healthyThresholdMs: cfg.healthyThresholdMs,- })- this.assertCurrent(generation)- } else if (cfg.probeEnabled) {- log.warn('probe skipped: no trackers fetched')- }-- healthMap = this.store.mergeHealth(this.curated.healthMap, healthResults)-- healthy = cfg.probeEnabled- ? Object.values(healthMap)- .filter(- (h) =>- h.status !== 'unreachable' &&- h.successRate >= cfg.minSuccessRate- )- .sort(- (a, b) =>- (a.lastProbeMs ?? Infinity) - (b.lastProbeMs ?? Infinity)- )- .slice(0, cfg.maxTrackerCount)- .map((h) => h.url)- : syncResult.trackers.slice(0, cfg.maxTrackerCount)-- if (healthy.length === 0) {- log.warn(- {- totalFetched: syncResult.trackers.length,- probeEnabled: cfg.probeEnabled,- minSuccessRate: cfg.minSuccessRate,- },- 'curated list is empty — check sources, network, or probe threshold'- )+ snapshots = mergeSourceSnapshots(+ snapshots,+ sources,+ result.sourceStatus,+ kind,+ Date.now(),+ kind === 'tracker' ? cfg.sources : cfg.blacklistSources+ )+ for (const source of sources) {+ const snapshot = snapshots[sourceKey(kind, source.id)]+ if (snapshot?.error && result.sourceStatus[source.id]?.ok) {+ result.sourceStatus[source.id] = {+ ok: false,+ count: 0,+ elapsedMs: 0,+ failure: snapshot.error,+ }+ }}- } else {- log.info('source fetch skipped: sourcesEnabled is false')+ return result}-- let blacklist: string[] = []- let blacklistSyncResult: SyncResult = { trackers: [], sourceStatus: {} }- if (cfg.blacklistEnabled && cfg.blacklistSources.length > 0) {- this.setSyncStatus('fetching')- blacklistSyncResult = await this.syncer.fetch(cfg.blacklistSources, proxy)+ const syncResult = await fetchKind('tracker')+ const blacklistResult = await fetchKind('blacklist')+ this.failureRetryAt = 0+ this.startupCheck = false+ const now = Date.now()+ let selection = selectTrackers({+ settings: this.settings.get().tracker,+ snapshots,+ health: this.curated.healthMap,+ previous: this.curated.effective,+ firstSeen: this.curated.firstSeen,+ now,+ routeKey: this.routeKey,+ })+ let healthMap = this.curated.healthMap+ const current = this.settings.get().tracker+ const probeUrls = current.probeEnabled+ ? selection.candidates+ .filter(+ (c) => c.reason !== 'blacklisted' && c.reason !== 'unsupported'+ )+ .sort(+ (a, b) =>+ (healthMap[a.url]?.lastProbeAt ?? 0) -+ (healthMap[b.url]?.lastProbeAt ?? 0) ||+ a.url.localeCompare(b.url)+ )+ .filter(+ (c) =>+ healthMap[c.url]?.routeKey !== this.routeKey ||+ healthMap[c.url]?.lastProbeAt == null ||+ now - (healthMap[c.url].lastProbeAt ?? 0) >=+ TRACKER_PROBE_FRESH_MS+ )+ .slice(0, 100)+ .map((c) => c.url)+ : []+ if (probeUrls.length) {+ this.setSyncStatus('probing')+ const results = await this.prober.probe(probeUrls, {+ timeoutMs: current.probeTimeoutMs,+ proxy,+ healthyThresholdMs: current.healthyThresholdMs,+ signal: this.abort.signal,+ routeKey: this.routeKey,+ })this.assertCurrent(generation)- blacklist = blacklistSyncResult.trackers- log.info({ blacklistCount: blacklist.length }, 'blacklist fetched')+ healthMap = this.store.mergeHealth(healthMap, results)+ }+ // Re-read settings after IO; late results cannot restore disabled sources.+ selection = selectTrackers({+ settings: this.settings.get().tracker,+ snapshots,+ health: healthMap,+ previous: this.curated.effective,+ firstSeen: selection.firstSeen,+ now: Date.now(),+ routeKey: this.routeKey,+ })+ const statuses = [+ ...Object.values(syncResult.sourceStatus),+ ...Object.values(blacklistResult.sourceStatus),+ ]+ const failed = statuses.filter((status) => !status.ok).length+ const successful = statuses.length - failed+ const enabledSnapshots = (['tracker', 'blacklist'] as const).flatMap(+ (kind) => {+ const settings = this.settings.get().tracker+ if (+ !(kind === 'tracker'+ ? settings.sourcesEnabled+ : settings.blacklistEnabled)+ )+ return []+ return (+ kind === 'tracker' ? settings.sources : settings.blacklistSources+ )+ .filter((source) => source.enabled)+ .map((source) => {+ const snapshot = snapshots[sourceKey(kind, source.id)]+ return snapshot?.url === source.url ? snapshot : undefined+ })+ }+ )+ const allSourcesSucceeded =+ enabledSnapshots.length > 0 &&+ enabledSnapshots.every(+ (snapshot) =>+ snapshot && !snapshot.error && snapshot.lastSuccessAt !== null+ )+ const previous = new Set(this.curated.effective)+ const next = new Set(selection.effective)+ const run = {+ id: randomUUID(),+ trigger,+ startedAt,+ finishedAt: Date.now(),+ outcome:+ failed === 0+ ? ('success' as const)+ : successful+ ? ('partial' as const)+ : ('failed' as const),+ successfulSources: successful,+ failedSources: failed,+ added: [...next].filter((url) => !previous.has(url)).length,+ removed: [...previous].filter((url) => !next.has(url)).length,+ selected: next.size,}-- const sourceMap = buildSourceMap([- syncResult.sourceStatus,- blacklistSyncResult.sourceStatus,- ])-this.setSyncStatus('applying')this.curated = {- effective: healthy,- blacklist,- healthMap,- sourceMap,- lastSyncAt: Date.now(),- lastProbeAt:- cfg.probeEnabled && cfg.sourcesEnabled- ? Date.now()- : this.curated.lastProbeAt,+ ...this.curated,+ version: 2,+ ...selection,+ snapshots,+ healthMap: pruneTrackerHealth(+ healthMap,+ new Set(selection.candidates.map((c) => c.url)),+ Date.now()+ ),+ revision: this.curated.revision + 1,+ history: [run, ...this.curated.history]+ .filter((r) => Date.now() - r.finishedAt <= TRACKER_HISTORY_MAX_AGE_MS)+ .slice(0, 100),+ lastAttemptAt: Date.now(),+ lastSyncAt:+ allSourcesSucceeded && statuses.length+ ? Math.min(+ ...enabledSnapshots.map(+ (snapshot) => snapshot?.lastSuccessAt ?? 0+ )+ )+ : this.curated.lastSyncAt,+ lastProbeAt: probeUrls.length ? Date.now() : this.curated.lastProbeAt,+ pendingEngineApply: true,}-- this.assertCurrent(generation)+ this.pruneSnapshots()await this.store.save(this.curated)this.assertCurrent(generation)-- const globalOpt: Record<string, string> = {- 'bt-tracker': healthy.join(','),- 'bt-exclude-tracker': blacklist.join(','),- }-- try {- await this.rpc.changeGlobalOption(globalOpt)- this.assertCurrent(generation)- log.info(- { btTrackerCount: healthy.length, btExcludeCount: blacklist.length },- 'applied to aria2 via changeGlobalOption'- )- } catch (err) {- this.assertCurrent(generation)- log.warn(- { err },- 'failed to apply to aria2 — is the engine running? (curated list was still saved)'- )- throw err- }-+ await this.queueCachedStatePush()+ this.assertCurrent(generation)this.eventBus.emit(Events.TrackerListUpdated, {- count: healthy.length,- lastSyncAt: this.curated.lastSyncAt,+ count: this.curated.effective.length,})-- // Source fetches can fail individually without rejecting the whole sync.- const sourceFailed = [- ...Object.values(syncResult.sourceStatus),- ...Object.values(blacklistSyncResult.sourceStatus),- ].some((source) => !source.ok)- this.setSyncStatus(sourceFailed ? 'failed' : 'idle')-- log.info(- {- totalFetched: syncResult.trackers.length,- totalHealthy: healthy.length,- totalCurated: healthy.length,- elapsedMs: Date.now() - totalStart,- },- 'syncAndCurate done'- )-+ this.setSyncStatus(failed ? 'failed' : 'idle')return {totalFetched: syncResult.trackers.length,- totalHealthy: healthy.length,- totalCurated: healthy.length,+ totalHealthy: selection.effective.length,+ totalCurated: selection.effective.length,syncResult,}}+ private reselect(): void {+ Object.assign(+ this.curated,+ selectTrackers({+ settings: this.settings.get().tracker,+ snapshots: this.curated.snapshots,+ health: this.curated.healthMap,+ previous: this.curated.effective,+ firstSeen: this.curated.firstSeen,+ now: Date.now(),+ routeKey: this.routeKey,+ })+ )+ }++ private pruneSnapshots(): void {+ const cfg = this.settings.get().tracker+ const keys = new Set([+ ...cfg.sources.map((source) => sourceKey('tracker', source.id)),+ ...cfg.blacklistSources.map((source) =>+ sourceKey('blacklist', source.id)+ ),+ ])+ this.curated.snapshots = Object.fromEntries(+ Object.entries(this.curated.snapshots).filter(([key]) => keys.has(key))+ )+ const referenced = new Set([+ ...Object.keys(this.curated.healthMap),+ ...this.curated.candidates.map((c) => c.url),+ ])+ this.curated.firstSeen = Object.fromEntries(+ Object.entries(this.curated.firstSeen).filter(([url]) =>+ referenced.has(url)+ )+ )+ }++ async applySelectionChange(): Promise<void> {+ const generation = this.captureGeneration()+ this.reselect()+ this.curated.revision+++ this.curated.pendingEngineApply = true+ await this.store.save(this.curated)+ this.assertCurrent(generation)+ await this.queueCachedStatePush()+ this.assertCurrent(generation)+ this.eventBus.emit(Events.TrackerListUpdated, {+ count: this.curated.effective.length,+ })+ this.applySyncScheduleChange()+ }+getCuratedList(): CuratedTrackerList {+ this.reselect()return this.curated}@@ -403,7 +595,9 @@ export class TrackerManager {engineGid: string,trackers: string[]): Promise<void> {- const operation = this.setBtTrackerOwned(taskId, engineGid, trackers)+ const operation = this.taskTrackers+ ? this.taskTrackers.edit(taskId, engineGid, trackers)+ : this.setBtTrackerOwned(taskId, engineGid, trackers)this.inFlightTrackerChanges.add(operation)void operation.then(() => this.inFlightTrackerChanges.delete(operation),@@ -455,7 +649,12 @@ export class TrackerManager {engineGid: string,isPrivate: boolean): Promise<void> {- if (isPrivate) return // never merge global into private torrents+ if (isPrivate !== false) return // never merge global into private torrents+ if (this.taskTrackers) {+ const plan = await this.taskTrackers.plan(taskId, engineGid)+ await this.taskTrackers.apply(taskId, engineGid, plan.fingerprint)+ return+ }const generation = this.captureGeneration()const opts = await this.rpc.getOption(engineGid)@@ -465,58 +664,95 @@ export class TrackerManager {.map((s) => s.trim()).filter((s) => s.length > 0)- const merged = [...new Set([...effective, ...this.curated.effective])]+ const merged = [+ ...new Set([...effective, ...this.getCuratedList().effective]),+ ]await this.setBtTracker(taskId, engineGid, merged)}async applySourcesChange(enabled: boolean): Promise<void> {- const generation = this.captureGeneration()- if (!enabled) {- await this.rpc.changeGlobalOption({ 'bt-tracker': '' })- this.assertCurrent(generation)- log.info('sources disabled — cleared bt-tracker')- return- }- log.info('sources enabled — running syncAndCurate')- await this.syncAndCurate()+ await this.applySelectionChange()+ if (enabled) await this.syncAndCurate()}async applyBlacklistChange(enabled: boolean): Promise<void> {- const generation = this.captureGeneration()- if (!enabled) {- await this.rpc.changeGlobalOption({ 'bt-exclude-tracker': '' })- this.assertCurrent(generation)- log.info('blacklist disabled — cleared bt-exclude-tracker')- return- }- log.info('blacklist enabled — running syncAndCurate')- await this.syncAndCurate()+ await this.applySelectionChange()+ if (enabled) await this.syncAndCurate()}invalidateProxyCache(): void {- // Phase 1: TrackerManager re-reads settings on each operation, so- // there is no cache to invalidate. The hook exists so that the- // proxyApplier can call it; future caching can be wired here.+ this.routeKey = undefined+ this.reselect()+ this.applySyncScheduleChange(true)+ }++ /** Wake/interface changes share the normal single-flight, debounced schedule. */+ notifyWake(): void {+ if (this.disposed) return+ this.startupCheck = true+ this.applySyncScheduleChange(true)+ }++ private networkSignature(): string {+ return Object.entries(networkInterfaces())+ .flatMap(([name, addresses]) =>+ (addresses ?? [])+ .filter((address) => !address.internal)+ .map((address) => `${name}:${address.family}:${address.address}`)+ )+ .sort()+ .join('|')+ }++ private sourceDueAt(+ kind: 'tracker' | 'blacklist',+ id: string,+ url: string+ ): number {+ const snapshot = this.curated.snapshots[sourceKey(kind, id)]+ if (!snapshot || snapshot.url !== url) return 0+ if ((snapshot.lastAttemptAt ?? 0) > Date.now()) return 0+ return (+ snapshot.nextRetryAt ??+ (snapshot.lastSuccessAt ?? 0) ++ this.settings.get().tracker.syncIntervalHours * 3600_000 ++ this.periodicJitterMs+ )}/** Recompute the next automatic sync from the persisted cache age. */- applySyncScheduleChange(): void {+ applySyncScheduleChange(startup = false): void {const cfg = this.settings.get().tracker- const intervalMs = cfg.syncIntervalHours * 3600_000- const lastSyncAt = this.curated.lastSyncAt- const empty = cfg.sourcesEnabled && this.curated.effective.length === 0- const elapsed =- lastSyncAt == null ? intervalMs : Math.max(0, Date.now() - lastSyncAt)- this.scheduleSync(- empty- ? STARTUP_SYNC_DELAY_MS- : Math.max(STARTUP_SYNC_DELAY_MS, intervalMs - elapsed)- )+ const now = Date.now()+ const due = (['tracker', 'blacklist'] as const).flatMap((kind) => {+ if (!(kind === 'tracker' ? cfg.sourcesEnabled : cfg.blacklistEnabled))+ return []+ return (kind === 'tracker' ? cfg.sources : cfg.blacklistSources)+ .filter((source) => source.enabled)+ .map((source) => {+ const snapshot = this.curated.snapshots[sourceKey(kind, source.id)]+ const at = this.sourceDueAt(kind, source.id, source.url)+ if (+ startup &&+ !snapshot?.error &&+ now - (snapshot?.lastSuccessAt ?? 0) >= 30 * 60_000+ )+ return now+ return at+ })+ })+ if (!due.length) {+ this.clearSyncTimer()+ return+ }+ const deadline = Math.max(this.failureRetryAt, Math.min(...due))+ this.scheduleSync(Math.max(STARTUP_SYNC_DELAY_MS, deadline - now))}private clearSyncTimer(): void {if (this.timer) clearTimeout(this.timer)this.timer = null+ this.curated.nextCheckAt = null}private scheduleSync(delayMs: number): void {@@ -525,12 +761,12 @@ export class TrackerManager {if (this.disposed ||!this.initialized ||- !this.engineReady ||- this.syncInFlight ||+ (this.syncInFlight && !this.finishingSync) ||!settings.tracker.autoSync ||!settings.onboarding.disclaimerAccepted)return+ this.curated.nextCheckAt = Date.now() + delayMsconst generation = this.lifecycleGenerationthis.timer = setTimeout(() => {this.timer = null@@ -539,9 +775,15 @@ export class TrackerManager {!this.settings.get().onboarding.disclaimerAccepted)return- void this.syncAndCurate().catch((err) => {+ if (this.syncInFlight) {+ void this.syncInFlight+ .finally(() => this.applySyncScheduleChange())+ .catch(() => undefined)+ return+ }+ void this.syncAndCurate('scheduled').catch(() => {if (this.isCurrent(generation))- log.warn({ err }, 'scheduled tracker sync failed')+ log.warn('scheduled tracker sync failed')})}, delayMs)this.timer.unref?.()@@ -550,6 +792,9 @@ export class TrackerManager {dispose(): void {if (this.disposed) returnthis.disposed = true+ this.abort.abort()+ if (this.clockWatch) clearInterval(this.clockWatch)+ this.clockWatch = nullthis.lifecycleGeneration += 1this.eventBus.off(Events.EngineRecovered, this.handleEngineRecovered)this.eventBus.off(Events.EngineDisconnected, this.handleEngineDisconnected)@@ -563,8 +808,11 @@ export class TrackerManager {// compensation before the captured promise settles.this.dispose()const accepted = [+ this.store.flush?.(),+ this.taskTrackers?.stopAndDrain(),...this.inFlightTrackerChanges,...this.inFlightCachedStatePushes,+ ...(this.syncInFlight ? [this.syncInFlight] : []),]this.stopPromise = Promise.allSettled(accepted).then(() => undefined)return this.stopPromisediff --git a/src/core/tracker/tracker-prober-udp.test.ts b/src/core/tracker/tracker-prober-udp.test.tsindex d665fa01..2f6f1421 100644--- a/src/core/tracker/tracker-prober-udp.test.ts+++ b/src/core/tracker/tracker-prober-udp.test.ts@@ -10,18 +10,19 @@ import { TrackerProber } from './tracker-prober'class FakeSocket extends EventEmitter {closed = falsesendCallback: ((error: Error | null) => void) | undefined- send = vi.fn(- (- _buffer: Buffer,- _offset: number,- _length: number,- _port: number,- _host: string,- callback: (error: Error | null) => void- ) => {- this.sendCallback = callback- }+ request: Buffer = Buffer.alloc(16)+ connect = vi.fn((_port: number, _host: string, callback: () => void) =>+ callback())+ send = vi.fn((buffer: Buffer, callback: (error: Error | null) => void) => {+ this.request = buffer+ this.sendCallback = callback+ })+ reply() {+ const reply = Buffer.alloc(16)+ reply.writeUInt32BE(this.request.readUInt32BE(12), 4)+ return reply+ }close = vi.fn(() => {if (this.closed) {throw Object.assign(new Error('Not running'), {@@ -72,7 +73,7 @@ describe('TrackerProber UDP lifecycle', () => {await vi.advanceTimersByTimeAsync(100)socket.sendCallback?.(null)- expect(() => socket.emit('message', Buffer.alloc(16))).not.toThrow()+ expect(() => socket.emit('message', socket.reply())).not.toThrow()expect((await result)[0].status).toBe('unreachable')expect(socket.close).toHaveBeenCalledOnce()expect(socket.listenerCount('message')).toBe(0)@@ -81,7 +82,7 @@ describe('TrackerProber UDP lifecycle', () => {it('closes a successful probe once and clears its deadline', async () => {const { result } = await startProbe()socket.sendCallback?.(null)- socket.emit('message', Buffer.alloc(16))+ socket.emit('message', socket.reply())expect((await result)[0].status).toBe('healthy')await vi.advanceTimersByTimeAsync(100)@@ -91,7 +92,7 @@ describe('TrackerProber UDP lifecycle', () => {it('handles a reply before the send callback completes', async () => {const { result } = await startProbe()- socket.emit('message', Buffer.alloc(16))+ socket.emit('message', socket.reply())expect((await result)[0].status).toBe('healthy')expect(() =>socket.sendCallback?.(new Error('late send error'))@@ -160,9 +161,42 @@ describe('TrackerProber UDP lifecycle', () => {socket.close.mockImplementationOnce(() => {throw new Error('unexpected close failure')})- expect(() => socket.emit('message', Buffer.alloc(16))).not.toThrow()+ expect(() => socket.emit('message', socket.reply())).not.toThrow()expect((await result)[0].status).toBe('unreachable')await vi.advanceTimersByTimeAsync(100)expect(socket.close).toHaveBeenCalledOnce()})+ it('ignores incorrect transaction IDs, actions, and truncated responses', async () => {+ const { result } = await startProbe()+ const wrongId = socket.reply()+ wrongId.writeUInt32BE((wrongId.readUInt32BE(4) + 1) >>> 0, 4)+ socket.emit('message', wrongId)+ const wrongAction = socket.reply()+ wrongAction.writeUInt32BE(1, 0)+ socket.emit('message', wrongAction)+ socket.emit('message', socket.reply().subarray(0, 8))+ expect(socket.close).not.toHaveBeenCalled()+ socket.emit('message', socket.reply())+ expect((await result)[0]).toMatchObject({+ status: 'healthy',+ evidence: 'udp',+ })+ })++ it('treats a matching protocol error as failure', async () => {+ const { result } = await startProbe()+ const error = socket.reply()+ error.writeUInt32BE(3, 0)+ socket.emit('message', error)+ expect((await result)[0].status).toBe('unreachable')+ })++ it('does not bypass a configured proxy for UDP', async () => {+ const result = await prober.probe(['udp://tracker.example:80'], {+ timeoutMs: 100,+ proxy: { server: 'http://localhost:1234' },+ })+ expect(result[0].status).toBe('unknown')+ expect(createSocket).not.toHaveBeenCalled()+ })})diff --git a/src/core/tracker/tracker-prober.ts b/src/core/tracker/tracker-prober.tsindex 53d48e21..50f8e39a 100644--- a/src/core/tracker/tracker-prober.ts+++ b/src/core/tracker/tracker-prober.ts@@ -1,129 +1,141 @@+import { randomBytes } from 'node:crypto'+import { createSocket } from 'node:dgram'+import { isIP } from 'node:net'import type {ProxyConfig,TrackerHealth,TrackerProtocol,} from '@shared/types/tracker'-import { trackerLogger } from './logger'import {createTrackerHttpClient,type TrackerHttpClient,} from './tracker-http-client'-const log = trackerLogger('prober')-interface ProbeOptions {timeoutMs: numberproxy?: ProxyConfighealthyThresholdMs?: number+ signal?: AbortSignal+ routeKey?: string}export class TrackerProber {async probe(urls: string[], opts: ProbeOptions): Promise<TrackerHealth[]> {- if (urls.length === 0) return []-- const threshold = opts.healthyThresholdMs ?? 3000- const start = Date.now()- log.info(- {- urls: urls.length,- timeoutMs: opts.timeoutMs,- healthyThresholdMs: threshold,- proxy: Boolean(opts.proxy),- },- 'probe start'- )- const httpClient = await createTrackerHttpClient(opts.proxy)- let results: PromiseSettledResult<number>[]+ if (!urls.length) return []+ const client = await createTrackerHttpClient(opts.proxy)+ const groups = new Map<string, { url: string; index: number }[]>()+ urls.forEach((url, index) => {+ let host: string+ try {+ host = new URL(url).hostname+ } catch {+ host = url+ }+ const group = groups.get(host) ?? []+ group.push({ url, index })+ groups.set(host, group)+ })+ const queue = [...groups.values()]+ const results: TrackerHealth[] = new Array(urls.length)try {- results = await Promise.allSettled(- urls.map((url) => this.probeOne(url, opts, httpClient))+ await Promise.all(+ Array.from({ length: Math.min(8, queue.length) }, async () => {+ while (queue.length) {+ const group = queue.shift()+ if (!group) return+ for (const { url, index } of group) {+ if (opts.signal?.aborted) throw opts.signal.reason+ const protocol = url.split(':', 1)[0] as TrackerProtocol+ const record: TrackerHealth = {+ url,+ protocol,+ status: 'unknown',+ lastProbeMs: null,+ lastProbeAt: Date.now(),+ successCount: 0,+ failCount: 0,+ successRate: 0,+ routeKey: opts.routeKey,+ evidence: 'none',+ }+ // HTTP proxies cannot carry UDP announces; never silently bypass them.+ if (+ protocol !== 'ws' &&+ protocol !== 'wss' &&+ !(protocol === 'udp' && opts.proxy)+ ) {+ try {+ const ms = await this.probeOne(url, opts, client)+ record.status =+ ms <= (opts.healthyThresholdMs ?? 3000) ? 'healthy' : 'slow'+ record.lastProbeMs = ms+ record.successCount = 1+ record.successRate = 1+ record.evidence = protocol === 'udp' ? 'udp' : 'http'+ } catch {+ if (opts.signal?.aborted) throw opts.signal.reason+ record.status = 'unreachable'+ record.failCount = 1+ }+ }+ results[index] = record+ }+ }+ }))} finally {- await httpClient.close()- }-- const mapped = results.map((r, i) => {- const url = urls[i]- const protocol = this.detectProtocol(url)- const now = Date.now()-- if (r.status === 'fulfilled') {- const ms = r.value- const status = ms <= threshold ? 'healthy' : 'slow'- return {- url,- protocol,- status: status as 'healthy' | 'slow',- lastProbeMs: ms,- lastProbeAt: now,- successCount: 1,- failCount: 0,- successRate: 1.0,- }- }- return {- url,- protocol,- status: 'unreachable' as const,- lastProbeMs: null,- lastProbeAt: now,- successCount: 0,- failCount: 1,- successRate: 0,- }- })-- const counts = { healthy: 0, slow: 0, unreachable: 0 }- for (const h of mapped) {- if (h.status === 'healthy') counts.healthy++- else if (h.status === 'slow') counts.slow++- else counts.unreachable+++ await client.close()}- log.info(- { total: mapped.length, ...counts, elapsedMs: Date.now() - start },- 'probe done'- )- return mapped+ return results}private async probeOne(url: string,opts: ProbeOptions,- httpClient: TrackerHttpClient+ client: TrackerHttpClient): Promise<number> {- const protocol = this.detectProtocol(url)- const start = Date.now()-- if (protocol === 'udp') {- return this.probeUdp(url, opts.timeoutMs)- }-- await httpClient.fetch(url, {+ if (url.startsWith('udp:'))+ return this.probeUdp(url, opts.timeoutMs, opts.signal)+ const start = performance.now()+ const response = await client.fetch(url, {method: 'HEAD',- signal: AbortSignal.timeout(opts.timeoutMs),+ signal: opts.signal+ ? AbortSignal.any([opts.signal, AbortSignal.timeout(opts.timeoutMs)])+ : AbortSignal.timeout(opts.timeoutMs),})- return Date.now() - start+ await response.body+ ?.getReader()+ .cancel()+ .catch(() => undefined)+ if ((response.status ?? 200) >= 500)+ throw new Error('HTTP tracker unavailable')+ // A 401/403/405 is still HTTP connectivity evidence, not announce success.+ return Math.round(performance.now() - start)}- private async probeUdp(url: string, timeoutMs: number): Promise<number> {- const { createSocket } = await import('node:dgram')+ private async probeUdp(+ url: string,+ timeoutMs: number,+ signal?: AbortSignal+ ): Promise<number> {const parsed = new URL(url)+ const hostname = parsed.hostname.replace(/^\[|\]$/g, '')+ const port = Number(parsed.port)+ if (!port || port > 65535) throw new Error('Invalid tracker port')return new Promise((resolve, reject) => {- const start = Date.now()- const socket = createSocket('udp4')+ const start = performance.now()+ const socket = createSocket(isIP(hostname) === 6 ? 'udp6' : 'udp4')+ const transaction = randomBytes(4).readUInt32BE()let settled = false-const finish = (error?: Error) => {- // DNS/send callbacks can arrive after the deadline closed the socket.- // Every completion path must claim cleanup before calling close().if (settled) returnsettled = trueclearTimeout(timer)+ signal?.removeEventListener('abort', onAbort)socket.off('message', onMessage)try {socket.close()} catch (closeError) {- // A native socket may already be closed after a network failure.if ((closeError as NodeJS.ErrnoException).code !=='ERR_SOCKET_DGRAM_NOT_RUNNING'@@ -133,41 +145,48 @@ export class TrackerProber {}}if (error) reject(error)- else resolve(Date.now() - start)+ else resolve(Math.round(performance.now() - start))}- const onMessage = () => finish()+ const onMessage = (message: Buffer) => {+ if (message.length < 8 || message.readUInt32BE(4) !== transaction)+ return+ const action = message.readUInt32BE(0)+ if (action === 3) finish(new Error('UDP tracker error'))+ else if (action === 0 && message.length === 16) finish()+ }+ const onAbort = () => finish(new Error('Tracker probe cancelled'))const onError = (error: Error) => finish(error)const timer = setTimeout(() => finish(new Error('UDP probe timeout')),timeoutMs)-- // Keep the error handler through close so in-flight network errors are- // contained by this probe instead of reaching uncaughtException.socket.on('error', onError)socket.once('close', () => socket.off('error', onError))- socket.once('message', onMessage)-+ socket.on('message', onMessage)+ signal?.addEventListener('abort', onAbort, { once: true })+ if (signal?.aborted) {+ onAbort()+ return+ }try {- // Minimal BT UDP tracker connection request- const buf = Buffer.alloc(16)- buf.writeBigInt64BE(0x41727101980n, 0) // protocol_id- buf.writeInt32BE(0, 8) // action: connect- buf.writeInt32BE((Math.random() * 0x7fffffff) | 0, 12) // transaction_id- socket.send(buf, 0, 16, Number(parsed.port), parsed.hostname, (err) => {- if (err) finish(err)+ // A connected UDP socket only accepts datagrams from this endpoint.+ socket.connect(port, hostname, () => {+ if (settled) return+ const request = Buffer.alloc(16)+ request.writeBigUInt64BE(0x41727101980n, 0)+ request.writeUInt32BE(0, 8)+ request.writeUInt32BE(transaction, 12)+ try {+ socket.send(request, (error) => {+ if (error) finish(error)+ })+ } catch (error) {+ finish(error as Error)+ }})} catch (error) {finish(error as Error)}})}-- private detectProtocol(url: string): TrackerProtocol {- if (url.startsWith('udp://')) return 'udp'- if (url.startsWith('wss://')) return 'wss'- if (url.startsWith('ws://')) return 'ws'- if (url.startsWith('https://')) return 'https'- return 'http'- }}diff --git a/src/core/tracker/tracker-selector.test.ts b/src/core/tracker/tracker-selector.test.tsnew file mode 100644index 00000000..afafb133--- /dev/null+++ b/src/core/tracker/tracker-selector.test.ts@@ -0,0 +1,250 @@+import { DEFAULT_TRACKER_SETTINGS } from '@shared/schemas/tracker-settings'+import {+ TRACKER_SOURCE_MAX_AGE_MS,+ type TrackerSourceSnapshot,+} from '@shared/schemas/tracker-state'+import type { TrackerHealth, TrackerSource } from '@shared/types/tracker'+import { describe, expect, it } from 'vitest'+import { normalizeTrackerUrl, selectTrackers } from './tracker-selector'+import { mergeSourceSnapshots } from './tracker-snapshots'+import { TrackerStore } from './tracker-store'++const now = 1_790_000_000_000+const source = (id: string): TrackerSource => ({+ id,+ label: id,+ url: `https://${id}.example/list`,+ enabled: true,+ builtin: false,+ cdn: false,+})+const snapshot = (+ id: string,+ urls: string[],+ kind: 'tracker' | 'blacklist' = 'tracker'+): TrackerSourceSnapshot => ({+ id,+ url: source(id).url,+ kind,+ urls,+ lastAttemptAt: now,+ lastSuccessAt: now,+ contentChangedAt: now,+ error: null,+ failures: 0,+ nextRetryAt: null,+})+const healthy = (url: string): TrackerHealth => ({+ url,+ protocol: 'udp',+ status: 'healthy',+ lastProbeMs: 20,+ lastProbeAt: now,+ successCount: 1,+ failCount: 0,+ successRate: 1,+ routeKey: 'direct',+ samples: [{ at: now, ok: true }],+})+const base = () => ({+ settings: {+ ...DEFAULT_TRACKER_SETTINGS,+ sources: [source('s1')],+ blacklistSources: [source('b1')],+ blacklistEnabled: true,+ maxTrackerCount: 5,+ },+ snapshots: {} as Record<string, TrackerSourceSnapshot>,+ health: {} as Record<string, TrackerHealth>,+ previous: [] as string[],+ firstSeen: {},+ now,+ routeKey: 'direct',+})++describe('source-qualified tracker selection', () => {+ it('removes deleted source URLs even though real health merging retains them (#2249)', () => {+ const input = base()+ input.snapshots['tracker:s1'] = snapshot('s1', ['udp://old.test:80'])+ input.health = new TrackerStore('/unused').mergeHealth({}, [+ healthy('udp://old.test:80'),+ ])+ const first = selectTrackers(input)+ input.snapshots = mergeSourceSnapshots(+ input.snapshots,+ input.settings.sources,+ { s1: { ok: true, urls: ['udp://new.test:80'], count: 1, elapsedMs: 0 } },+ 'tracker',+ now + 1+ )+ input.health = new TrackerStore('/unused').mergeHealth(input.health, [+ healthy('udp://new.test:80'),+ ])+ expect(input.health['udp://old.test:80']).toBeDefined()+ const second = selectTrackers({ ...input, previous: first.effective })+ expect(second.effective).toEqual(['udp://new.test:80'])+ expect(second.sourceMap['udp://old.test:80']).toBeUndefined()+ })++ it('keeps an address until all contributing sources remove it', () => {+ const input = base()+ input.settings.sources.push(source('s2'))+ input.snapshots = {+ 'tracker:s1': snapshot('s1', []),+ 'tracker:s2': snapshot('s2', ['udp://shared.test:80']),+ }+ const result = selectTrackers(input)+ expect(result.effective).toEqual(['udp://shared.test:80'])+ expect(result.sourceMap['udp://shared.test:80']).toEqual(['s2'])+ input.settings.sources[1].enabled = false+ expect(selectTrackers(input).effective).toEqual([])+ })++ it('rejects caches from a changed source URL and expired fallback caches', () => {+ const input = base()+ input.snapshots['tracker:s1'] = {+ ...snapshot('s1', ['udp://a:80']),+ lastSuccessAt: now - TRACKER_SOURCE_MAX_AGE_MS - 1,+ }+ expect(selectTrackers(input).effective).toEqual([])+ input.snapshots['tracker:s1'] = snapshot('s1', ['udp://a:80'])+ input.settings.sources[0].url += '?new'+ expect(selectTrackers(input).effective).toEqual([])+ })++ it('filters blacklist and unsupported protocols before allocating capacity', () => {+ const input = base()+ input.snapshots = {+ 'tracker:s1': snapshot('s1', [+ 'udp://a:80',+ 'udp://b:80',+ 'wss://ws.test/',+ ]),+ 'blacklist:b1': snapshot('b1', ['udp://a:80'], 'blacklist'),+ }+ const result = selectTrackers(input)+ expect(result.effective).toEqual(['udp://b:80'])+ expect(result.candidates.map((c) => c.reason)).toEqual([+ 'blacklisted',+ 'selected',+ 'unsupported',+ ])+ expect(result.sourceMap['udp://a:80']).toEqual(['s1', 'b1'])+ })++ it('uses recent repeated failures for cooldown, not lifetime failure counts', () => {+ const input = base()+ const url = 'udp://a:80'+ input.snapshots['tracker:s1'] = snapshot('s1', [url])+ input.health[url] = {+ ...healthy(url),+ status: 'unreachable',+ successCount: 0,+ failCount: 999,+ successRate: 0,+ samples: [{ at: now, ok: false }],+ }+ expect(selectTrackers(input).effective).toEqual([url])+ input.health[url].samples = Array.from({ length: 3 }, () => ({+ at: now,+ ok: false,+ }))+ expect(selectTrackers(input).candidates[0].reason).toBe('cooldown')+ expect(+ selectTrackers({ ...input, routeKey: 'new-network' }).effective+ ).toEqual([url])+ expect(+ selectTrackers({ ...input, now: now + 13 * 3600_000 }).effective+ ).toEqual([url])+ })++ it('reserves bounded space for new addresses and prefers distinct hosts', () => {+ const input = base()+ const known = Array.from(+ { length: 8 },+ (_, i) => `udp://known${i % 4}.test:${8000 + i}`+ )+ input.snapshots['tracker:s1'] = snapshot('s1', [+ ...known,+ 'udp://new.test:80',+ ])+ input.health = Object.fromEntries(known.map((url) => [url, healthy(url)]))+ const result = selectTrackers(input)+ expect(result.effective).toHaveLength(5)+ expect(result.effective).toContain('udp://new.test:80')+ expect(+ new Set(result.effective.map((url) => new URL(url).hostname)).size+ ).toBe(5)+ expect(+ selectTrackers({ ...input, previous: result.effective }).effective+ ).toEqual(result.effective)+ })++ it('preserves firstSeen and the query/path spelling used for authentication', () => {+ expect(+ normalizeTrackerUrl(+ 'HTTP://EXAMPLE.COM:80/Announce?passkey=A%2FB&x=1#fragment'+ )+ ).toBe('http://example.com/Announce?passkey=A%2FB&x=1')+ const input = base()+ input.snapshots['tracker:s1'] = snapshot('s1', ['udp://a:80'])+ const first = selectTrackers(input)+ expect(+ selectTrackers({ ...input, firstSeen: first.firstSeen, now: now + 1000 })+ .candidates[0].firstSeenAt+ ).toBe(now)+ })+})++describe('per-source snapshot commits', () => {+ it('retains failed source cache, accepts an empty successful list, and records backoff independently', () => {+ const old = {+ 'tracker:s1': snapshot('s1', ['udp://a:80']),+ 'tracker:s2': snapshot('s2', ['udp://b:80']),+ }+ const result = mergeSourceSnapshots(+ old,+ [source('s1'), source('s2')],+ {+ s1: { ok: false, count: 0, elapsedMs: 0, failure: 'network' },+ s2: { ok: true, count: 0, elapsedMs: 0, urls: [] },+ },+ 'tracker',+ now + 100+ )+ expect(result['tracker:s1']).toMatchObject({+ urls: ['udp://a:80'],+ lastSuccessAt: now,+ failures: 1,+ nextRetryAt: now + 100 + 300_000,+ })+ expect(result['tracker:s2']).toMatchObject({+ urls: [],+ lastSuccessAt: now + 100,+ contentChangedAt: now + 100,+ })+ })++ it('304 renews freshness without pretending the content changed', () => {+ const old = { 'tracker:s1': snapshot('s1', ['udp://a:80']) }+ const result = mergeSourceSnapshots(+ old,+ [source('s1')],+ {+ s1: {+ ok: true,+ count: 1,+ elapsedMs: 0,+ urls: ['udp://a:80'],+ notModified: true,+ },+ },+ 'tracker',+ now + 100+ )+ expect(result['tracker:s1']).toMatchObject({+ lastSuccessAt: now + 100,+ contentChangedAt: now,+ })+ })+})diff --git a/src/core/tracker/tracker-selector.ts b/src/core/tracker/tracker-selector.tsnew file mode 100644index 00000000..76a50924--- /dev/null+++ b/src/core/tracker/tracker-selector.ts@@ -0,0 +1,178 @@+import {+ TRACKER_MAX_CANDIDATES,+ TRACKER_PROBE_FRESH_MS,+ TRACKER_SOURCE_MAX_AGE_MS,+ type TrackerCandidate,+ type TrackerSourceSnapshot,+} from '@shared/schemas/tracker-state'+import type { TrackerSettings } from '@shared/types/settings'+import type { TrackerHealth, TrackerSource } from '@shared/types/tracker'++export function sourceKey(kind: 'tracker' | 'blacklist', id: string): string {+ return `${kind}:${id}`+}++export function normalizeTrackerUrl(value: string): string | null {+ try {+ const url = new URL(value)+ if (!['http:', 'https:', 'udp:', 'ws:', 'wss:'].includes(url.protocol))+ return null+ if (!url.hostname || (url.protocol === 'udp:' && !url.port)) return null+ // Query/path spelling and authentication parameters are preserved.+ url.hash = ''+ return url.href+ } catch {+ return null+ }+}++export function collectSourceUrls(+ sources: TrackerSource[],+ snapshots: Record<string, TrackerSourceSnapshot>,+ kind: 'tracker' | 'blacklist',+ now: number+): Record<string, string[]> {+ const urls: Record<string, string[]> = {}+ for (const source of sources) {+ if (!source.enabled) continue+ const snapshot = snapshots[sourceKey(kind, source.id)]+ if (+ !snapshot ||+ snapshot.url !== source.url ||+ snapshot.lastSuccessAt === null ||+ now - snapshot.lastSuccessAt > TRACKER_SOURCE_MAX_AGE_MS+ )+ continue+ for (const raw of snapshot.urls) {+ const url = normalizeTrackerUrl(raw)+ if (!url) continue+ if (!urls[url]) urls[url] = []+ if (!urls[url].includes(source.id)) urls[url].push(source.id)+ }+ }+ return urls+}++export function selectTrackers(input: {+ settings: TrackerSettings+ snapshots: Record<string, TrackerSourceSnapshot>+ health: Record<string, TrackerHealth>+ previous: string[]+ firstSeen: Record<string, number>+ now: number+ routeKey?: string+}): {+ effective: string[]+ blacklist: string[]+ sourceMap: Record<string, string[]>+ candidates: TrackerCandidate[]+ firstSeen: Record<string, number>+} {+ const { settings, snapshots, health, now } = input+ const sourceMap = settings.sourcesEnabled+ ? collectSourceUrls(settings.sources, snapshots, 'tracker', now)+ : {}+ const blockedMap = settings.blacklistEnabled+ ? collectSourceUrls(settings.blacklistSources, snapshots, 'blacklist', now)+ : {}+ const blocked = new Set(Object.keys(blockedMap))+ const previous = new Set(input.previous)+ const firstSeen = { ...input.firstSeen }+ const candidates = Object.entries(sourceMap)+ .slice(0, TRACKER_MAX_CANDIDATES)+ .map(([url, sourceIds]): TrackerCandidate => {+ firstSeen[url] ??= now+ const sample = health[url]+ const matchingRoute = sample?.routeKey === input.routeKey+ const recent =+ matchingRoute &&+ sample?.lastProbeAt != null &&+ now >= sample.lastProbeAt &&+ now - sample.lastProbeAt < TRACKER_PROBE_FRESH_MS+ const consecutiveFailures =+ sample?.samples?.slice(-3).filter((s) => !s.ok).length ??+ (sample?.status === 'unreachable' ? 1 : 0)+ return {+ url,+ sourceIds,+ firstSeenAt: firstSeen[url],+ reason: blocked.has(url)+ ? 'blacklisted'+ : /^wss?:/.test(url)+ ? 'unsupported'+ : settings.probeEnabled &&+ recent &&+ consecutiveFailures >= 3 &&+ sample.successRate < settings.minSuccessRate+ ? 'cooldown'+ : 'capacity',+ }+ })+ const eligible = candidates.filter((c) => c.reason === 'capacity')+ const known = (url: string) => {+ const h = health[url]+ return (+ h &&+ h.status !== 'unknown' &&+ h.routeKey === input.routeKey &&+ h.lastProbeAt != null &&+ now >= h.lastProbeAt &&+ now - h.lastProbeAt < TRACKER_PROBE_FRESH_MS+ )+ }+ const score = (url: string) => {+ const h = health[url]+ if (!settings.probeEnabled || !known(url))+ return previous.has(url) ? 0.05 : 0+ // Coarse latency buckets avoid replacing trackers for millisecond jitter.+ return (+ h.successRate * 10 ++ (h.status === 'unreachable' ? -4 : 1) ++ (previous.has(url) ? 0.25 : 0) -+ Math.min(5, Math.floor((h.lastProbeMs ?? 5000) / 1000)) * 0.1+ )+ }+ eligible.sort(+ (a, b) => score(b.url) - score(a.url) || a.url.localeCompare(b.url)+ )+ const effective: string[] = []+ const hosts = new Set<string>()+ const add = (candidate: TrackerCandidate) => {+ effective.push(candidate.url)+ hosts.add(new URL(candidate.url).hostname)+ candidate.reason = 'selected'+ }+ // A small bounded exploration allocation gives unmeasured endpoints a way in.+ const explorers = settings.probeEnabled+ ? eligible+ .filter((c) => !known(c.url))+ .slice(0, Math.max(1, Math.floor(settings.maxTrackerCount / 10)))+ : []+ const target = Math.min(settings.maxTrackerCount, eligible.length)+ const ranked = eligible.filter((c) => !explorers.includes(c))+ for (const c of ranked) {+ if (effective.length >= target - explorers.length) break+ if (!hosts.has(new URL(c.url).hostname)) add(c)+ }+ for (const c of explorers) {+ if (effective.length < target) add(c)+ }+ for (const c of eligible) {+ if (effective.length >= target) break+ if (c.reason !== 'selected') add(c)+ }+ return {+ effective,+ blacklist: [...blocked],+ sourceMap: Object.fromEntries(+ [...new Set([...Object.keys(blockedMap), ...Object.keys(sourceMap)])].map(+ (url) => [+ url,+ [...new Set([...(sourceMap[url] ?? []), ...(blockedMap[url] ?? [])])],+ ]+ )+ ),+ candidates,+ firstSeen,+ }+}diff --git a/src/core/tracker/tracker-snapshots.ts b/src/core/tracker/tracker-snapshots.tsnew file mode 100644index 00000000..494b3a0f--- /dev/null+++ b/src/core/tracker/tracker-snapshots.ts@@ -0,0 +1,65 @@+import {+ TRACKER_MAX_CANDIDATES,+ type TrackerSourceSnapshot,+} from '@shared/schemas/tracker-state'+import type { SourceFetchStatus, TrackerSource } from '@shared/types/tracker'+import { sourceKey } from './tracker-selector'++export function mergeSourceSnapshots(+ snapshots: Record<string, TrackerSourceSnapshot>,+ sources: TrackerSource[],+ statuses: Record<string, SourceFetchStatus>,+ kind: 'tracker' | 'blacklist',+ now: number,+ eligibleSources: TrackerSource[] = sources+): Record<string, TrackerSourceSnapshot> {+ const result = { ...snapshots }+ for (const source of sources) {+ const status = statuses[source.id]+ if (!status) continue+ const key = sourceKey(kind, source.id)+ const old = result[key]?.url === source.url ? result[key] : undefined+ const urls = status.urls ?? []+ const otherUrls = new Set(+ Object.entries(result)+ .filter(+ ([id, s]) =>+ id !== key &&+ s.kind === kind &&+ eligibleSources.some(+ (source) =>+ source.enabled && source.id === s.id && source.url === s.url+ )+ )+ .flatMap(([, s]) => s.urls)+ )+ for (const url of urls) otherUrls.add(url)+ const ok = status.ok && otherUrls.size <= TRACKER_MAX_CANDIDATES+ const failures = ok ? 0 : (old?.failures ?? 0) + 1+ const delays = [5 * 60_000, 30 * 60_000, 2 * 3_600_000, 12 * 3_600_000]+ result[key] = {+ id: source.id,+ url: source.url,+ kind,+ urls: ok ? urls : (old?.urls ?? []),+ lastAttemptAt: now,+ lastSuccessAt: ok ? now : (old?.lastSuccessAt ?? null),+ contentChangedAt:+ ok && (!old || old.urls.join('\n') !== urls.join('\n'))+ ? now+ : (old?.contentChangedAt ?? null),+ etag: ok ? status.etag : old?.etag,+ lastModified: ok ? status.lastModified : old?.lastModified,+ error: ok ? null : status.ok ? 'limit' : (status.failure ?? 'network'),+ failures,+ nextRetryAt: ok+ ? null+ : now ++ Math.max(+ delays[Math.min(failures - 1, delays.length - 1)],+ status.retryAfterMs ?? 0+ ),+ }+ }+ return result+}diff --git a/src/core/tracker/tracker-store.test.ts b/src/core/tracker/tracker-store.test.tsindex d143f986..afb4f560 100644--- a/src/core/tracker/tracker-store.test.ts+++ b/src/core/tracker/tracker-store.test.ts@@ -50,7 +50,7 @@ describe('TrackerStore', () => {}await store.save(data)const loaded = await store.load()- expect(loaded).toEqual(data)+ expect(loaded).toMatchObject({ ...data, version: 2 })})it('persists sourceMap', async () => {@@ -75,6 +75,11 @@ describe('TrackerStore', () => {lastProbeMs: 50,lastProbeAt: 900,successCount: 3,+ samples: [+ { at: 700, ok: true },+ { at: 800, ok: true },+ { at: 900, ok: true },+ ],failCount: 0,successRate: 1.0,},@@ -106,4 +111,76 @@ describe('TrackerStore', () => {expect(merged['udp://a.com'].lastProbeMs).toBe(4000)expect(merged['http://b.com'].successCount).toBe(1)})+ it('backs up v1 state before the first atomic migration', async () => {+ const legacy = JSON.stringify({+ effective: ['udp://a:80'],+ healthMap: {},+ sourceMap: {},+ blacklist: [],+ lastSyncAt: 100,+ lastProbeAt: null,+ })+ await fs.writeFile(filePath, legacy)+ const loaded = await store.load()+ await store.save(loaded)+ expect(await fs.readFile(`${filePath}.v1.bak`, 'utf8')).toBe(legacy)+ expect((await store.load()).version).toBe(2)+ })++ it('preserves an invalid original before recovery', async () => {+ await fs.writeFile(filePath, '{broken')+ const loaded = await store.load()+ await store.save(loaded)+ expect(await fs.readFile(`${filePath}.invalid.bak`, 'utf8')).toBe('{broken')+ })++ it('does not treat lifetime aggregates as recent timed samples', () => {+ const old = {+ url: 'udp://a:80',+ protocol: 'udp' as const,+ status: 'healthy' as const,+ lastProbeMs: 1,+ lastProbeAt: 1000,+ successCount: 9999,+ failCount: 0,+ successRate: 1,+ }+ const merged = store.mergeHealth({ [old.url]: old }, [+ { ...old, status: 'unreachable', lastProbeAt: 2000 },+ ])+ expect(merged[old.url]).toMatchObject({+ successCount: 0,+ failCount: 1,+ successRate: 0,+ })+ })++ it('drops old samples and separates network routes', () => {+ const now = Date.now()+ const old = {+ url: 'udp://a:80',+ protocol: 'udp' as const,+ status: 'healthy' as const,+ lastProbeMs: 1,+ lastProbeAt: now,+ successCount: 1,+ failCount: 1,+ successRate: 0.5,+ routeKey: 'a',+ samples: [+ { at: now - 8 * 86_400_000, ok: false },+ { at: now, ok: true },+ ],+ }+ expect(+ store.mergeHealth({ [old.url]: old }, [{ ...old, lastProbeAt: now + 1 }])[+ old.url+ ].successRate+ ).toBe(1)+ expect(+ store.mergeHealth({ [old.url]: old }, [+ { ...old, routeKey: 'b', status: 'unreachable', lastProbeAt: now + 1 },+ ])[old.url].samples+ ).toEqual([{ at: now + 1, ok: false }])+ })})diff --git a/src/core/tracker/tracker-store.ts b/src/core/tracker/tracker-store.tsindex 0318ff35..1de10fad 100644--- a/src/core/tracker/tracker-store.ts+++ b/src/core/tracker/tracker-store.ts@@ -1,43 +1,67 @@+import { randomUUID } from 'node:crypto'+import { constants } from 'node:fs'import fs from 'node:fs/promises'+import path from 'node:path'+import {+ TRACKER_HEALTH_MAX_AGE_MS,+ TRACKER_HISTORY_MAX_AGE_MS,+ trackerStateSchema,+} from '@shared/schemas/tracker-state'import type { CuratedTrackerList, TrackerHealth } from '@shared/types/tracker'import writeFileAtomic from 'write-file-atomic'-const EMPTY_LIST: CuratedTrackerList = {- effective: [],- blacklist: [],- healthMap: {},- sourceMap: {},- lastSyncAt: null,- lastProbeAt: null,-}-export class TrackerStore {+ private backupSuffix: string | null = null+ private writes: Promise<void> = Promise.resolve()constructor(private filePath: string) {}async load(): Promise<CuratedTrackerList> {try {- const raw = await fs.readFile(this.filePath, 'utf-8')- const parsed = JSON.parse(raw) as Partial<CuratedTrackerList>- return {- effective: parsed.effective ?? [],- blacklist: parsed.blacklist ?? [],- healthMap: parsed.healthMap ?? {},- sourceMap: parsed.sourceMap ?? {},- lastSyncAt: parsed.lastSyncAt ?? null,- lastProbeAt: parsed.lastProbeAt ?? null,- }- } catch {- return { ...EMPTY_LIST, healthMap: {}, sourceMap: {} }+ const parsed = trackerStateSchema.parse(+ JSON.parse(await fs.readFile(this.filePath, 'utf-8'))+ )+ this.backupSuffix = parsed.version !== 2 ? 'v1.bak' : null+ return parsed+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT')+ this.backupSuffix = 'invalid.bak'+ return trackerStateSchema.parse({})}}- async save(list: CuratedTrackerList): Promise<void> {- const dir = this.filePath.replace(/[/\\][^/\\]+$/, '')- await fs.mkdir(dir, { recursive: true })- // Atomic: tracker.json accumulates health stats over time.- // A half-written file on crash would silently reset the- // cumulative successCount / failCount / sourceMap.- await writeFileAtomic(this.filePath, JSON.stringify(list, null, 2))+ save(list: CuratedTrackerList): Promise<void> {+ const snapshot = JSON.stringify({ ...list, version: 2 }, null, 2)+ const write = this.writes+ .catch(() => undefined)+ .then(async () => {+ await fs.mkdir(path.dirname(this.filePath), { recursive: true })+ if (this.backupSuffix) {+ try {+ await fs.copyFile(+ this.filePath,+ `${this.filePath}.${this.backupSuffix}`,+ constants.COPYFILE_EXCL+ )+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error+ if (this.backupSuffix === 'invalid.bak') {+ await fs.copyFile(+ this.filePath,+ `${this.filePath}.${randomUUID()}.invalid.bak`,+ constants.COPYFILE_EXCL+ )+ }+ }+ this.backupSuffix = null+ }+ await writeFileAtomic(this.filePath, snapshot)+ })+ this.writes = write+ return write+ }++ flush(): Promise<void> {+ return this.writes}mergeHealth(@@ -47,20 +71,44 @@ export class TrackerStore {const result = { ...existing }for (const item of fresh) {const prev = result[item.url]- if (prev) {- const successCount = prev.successCount + item.successCount- const failCount = prev.failCount + item.failCount- const total = successCount + failCount- result[item.url] = {- ...item,- successCount,- failCount,- successRate: total > 0 ? successCount / total : 0,- }- } else {- result[item.url] = item+ const now = item.lastProbeAt ?? Date.now()+ const compatible = prev?.routeKey === item.routeKey+ const samples = (compatible ? (prev?.samples ?? []) : []).filter(+ (sample) => now - sample.at <= TRACKER_HEALTH_MAX_AGE_MS+ )+ if (item.status !== 'unknown')+ samples.push({ at: now, ok: item.status !== 'unreachable' })+ const recent = samples.slice(-20)+ const successCount = recent.filter((sample) => sample.ok).length+ const failCount = recent.length - successCount+ result[item.url] = {+ ...item,+ samples: recent,+ successCount,+ failCount,+ successRate: recent.length ? successCount / recent.length : 0,}}return result}}++export function pruneTrackerHealth(+ health: Record<string, TrackerHealth>,+ referenced: Set<string>,+ now: number+): Record<string, TrackerHealth> {+ const archived = Object.entries(health)+ .filter(+ ([url, record]) =>+ !referenced.has(url) &&+ record.lastProbeAt != null &&+ now - record.lastProbeAt <= TRACKER_HISTORY_MAX_AGE_MS+ )+ .sort((a, b) => (b[1].lastProbeAt ?? 0) - (a[1].lastProbeAt ?? 0))+ .slice(0, 5000)+ return Object.fromEntries([+ ...archived,+ ...Object.entries(health).filter(([url]) => referenced.has(url)),+ ])+}diff --git a/src/core/tracker/tracker-syncer.test.ts b/src/core/tracker/tracker-syncer.test.tsindex 9c9603e0..935f4af8 100644--- a/src/core/tracker/tracker-syncer.test.ts+++ b/src/core/tracker/tracker-syncer.test.ts@@ -89,7 +89,7 @@ describe('TrackerSyncer', () => {expect(result.trackers).toEqual(['udp://ok.com:80'])expect(result.sourceStatus.good.ok).toBe(true)expect(result.sourceStatus.bad.ok).toBe(false)- expect(result.sourceStatus.bad.error).toBe('network error')+ expect(result.sourceStatus.bad.error).toBe('network')})it('uses undici fetch with an HTTP ProxyAgent and closes the agent', async () => {@@ -127,12 +127,12 @@ describe('TrackerSyncer', () => {it('populates SourceFetchStatus.urls with per-source URLs on success', async () => {vi.spyOn(globalThis, 'fetch').mockResolvedValue(- new Response('udp://a/announce\nudp://b/announce\n')+ new Response('udp://a:80/announce\nudp://b:80/announce\n'))const result = await syncer.fetch([source('src-1', 'http://x')])expect(result.sourceStatus['src-1'].urls).toEqual([- 'udp://a/announce',- 'udp://b/announce',+ 'udp://a:80/announce',+ 'udp://b:80/announce',])})@@ -158,13 +158,12 @@ describe('TrackerSyncer', () => {new Response(['udp://ok.com:80',- 'http://ok.com:80/announce',+ 'http://ok.com/announce','https://ok.com/announce',- 'ws://ok.com',- 'wss://ok.com',+ 'ws://ok.com/',+ 'wss://ok.com/','ftp://disallowed.com','random text',- '<!DOCTYPE html>','javascript:alert(1)',].join('\n'))@@ -172,10 +171,73 @@ describe('TrackerSyncer', () => {const result = await syncer.fetch([source('s1', 'http://list.com')])expect(result.trackers).toEqual(['udp://ok.com:80',- 'http://ok.com:80/announce',+ 'http://ok.com/announce','https://ok.com/announce',- 'ws://ok.com',- 'wss://ok.com',+ 'ws://ok.com/',+ 'wss://ok.com/',])})+ it('uses conditional requests without altering signed source queries', async () => {+ const url = 'https://list.test/file?token=secret&format=text'+ const fetch = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue(new Response(null, { status: 304 }))+ const cached = {+ id: 's1',+ url,+ kind: 'tracker' as const,+ urls: ['udp://a:80'],+ lastAttemptAt: 0,+ lastSuccessAt: 0,+ contentChangedAt: 0,+ error: null,+ failures: 0,+ nextRetryAt: null,+ etag: 'v1',+ }+ const result = await syncer.fetch([source('s1', url)], undefined, {+ s1: cached,+ })+ expect(fetch).toHaveBeenCalledWith(+ url,+ expect.objectContaining({ headers: { 'If-None-Match': 'v1' } })+ )+ expect(result.sourceStatus.s1).toMatchObject({+ ok: true,+ urls: cached.urls,+ notModified: true,+ })+ })++ it.each([+ [new Response('<html>Failure</html>'), 'invalid'],+ [new Response('not a tracker list'), 'invalid'],+ [new Response(null, { status: 304 }), 'missing-cache'],+ [+ new Response('udp://a:80', { headers: { 'content-length': '3000000' } }),+ 'limit',+ ],+ ])('rejects malformed or oversized responses', async (response, failure) => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(response as Response)+ const result = await syncer.fetch([source('s1', 'https://list.test/')])+ expect(result.sourceStatus.s1).toMatchObject({ ok: false, failure })+ })++ it('accepts a legitimate empty list and respects bounded Retry-After', async () => {+ vi.spyOn(globalThis, 'fetch')+ .mockResolvedValueOnce(new Response('# Empty list'))+ .mockResolvedValueOnce(+ new Response('', { status: 429, headers: { 'retry-after': '600' } })+ )+ const result = await syncer.fetch([+ source('empty', 'https://empty.test/'),+ source('busy', 'https://busy.test/'),+ ])+ expect(result.sourceStatus.empty).toMatchObject({ ok: true, urls: [] })+ expect(result.sourceStatus.busy).toMatchObject({+ ok: false,+ failure: 'http',+ retryAfterMs: 600_000,+ })+ })})diff --git a/src/core/tracker/tracker-syncer.ts b/src/core/tracker/tracker-syncer.tsindex 1b6cfac9..4f3e3dae 100644--- a/src/core/tracker/tracker-syncer.ts+++ b/src/core/tracker/tracker-syncer.ts@@ -1,3 +1,8 @@+import {+ TRACKER_MAX_SOURCE_BYTES,+ TRACKER_MAX_SOURCE_URLS,+ type TrackerSourceSnapshot,+} from '@shared/schemas/tracker-state'import type {ProxyConfig,SourceFetchStatus,@@ -5,127 +10,171 @@ import type {TrackerSource,} from '@shared/types/tracker'import { trackerLogger } from './logger'-import { createTrackerHttpClient } from './tracker-http-client'+import {+ createTrackerHttpClient,+ type TrackerResponse,+} from './tracker-http-client'+import { normalizeTrackerUrl } from './tracker-selector'const log = trackerLogger('syncer')--const ALLOWED_TRACKER_PROTOCOLS = [- 'udp://',- 'http://',- 'https://',- 'ws://',- 'wss://',-] as const--function isValidTrackerLine(line: string): boolean {- if (line.length === 0) return false- if (line.startsWith('#')) return false- return ALLOWED_TRACKER_PROTOCOLS.some((scheme) => line.startsWith(scheme))+class SourceError extends Error {+ constructor(+ readonly code: NonNullable<SourceFetchStatus['failure']>,+ readonly retryAfterMs?: number+ ) {+ super(code)+ }+}+async function readLimited(response: TrackerResponse): Promise<string> {+ if (+ Number(response.headers?.get('content-length') ?? 0) >+ TRACKER_MAX_SOURCE_BYTES+ ) {+ await response.body+ ?.getReader()+ .cancel()+ .catch(() => undefined)+ throw new SourceError('limit')+ }+ if (!response.body) {+ const text = await response.text()+ if (Buffer.byteLength(text) > TRACKER_MAX_SOURCE_BYTES)+ throw new SourceError('limit')+ return text+ }+ const reader = response.body.getReader()+ const chunks: Uint8Array[] = []+ let length = 0+ try {+ while (true) {+ const { done, value } = await reader.read()+ if (done) break+ if (!value) continue+ length += value.length+ if (length > TRACKER_MAX_SOURCE_BYTES) throw new SourceError('limit')+ chunks.push(value)+ }+ } finally {+ await reader.cancel().catch(() => undefined)+ }+ return Buffer.concat(chunks).toString('utf8')+}+export function parseTrackerSource(text: string): string[] {+ const lines = text+ .replace(/^\uFEFF/, '')+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter((line) => line && !line.startsWith('#'))+ if (lines.some((line) => /[<>]/.test(line))) throw new SourceError('invalid')+ const urls = [+ ...new Set(+ lines+ .map(normalizeTrackerUrl)+ .filter((url): url is string => url !== null)+ ),+ ]+ if (lines.length && !urls.length) throw new SourceError('invalid')+ if (urls.length > TRACKER_MAX_SOURCE_URLS) throw new SourceError('limit')+ return urls}export class TrackerSyncer {async fetch(sources: TrackerSource[],- proxy?: ProxyConfig+ proxy?: ProxyConfig,+ cache: Record<string, TrackerSourceSnapshot> = {},+ signal?: AbortSignal): Promise<SyncResult> {- const enabled = sources.filter((s) => s.enabled)- if (enabled.length === 0) {- log.warn(- { totalSources: sources.length },- 'fetch skipped: no enabled sources'- )- return { trackers: [], sourceStatus: {} }- }-- log.info(- { enabledSources: enabled.length, proxy: Boolean(proxy) },- 'fetch start'- )- const httpClient = await createTrackerHttpClient(proxy)- const now = Date.now()-- let entries: PromiseSettledResult<{- id: string- urls: string[]- elapsedMs: number- }>[]+ const enabled = sources.filter((source) => source.enabled)+ if (!enabled.length) return { trackers: [], sourceStatus: {} }+ const client = await createTrackerHttpClient(proxy)+ const sourceStatus: Record<string, SourceFetchStatus> = {}+ let index = 0try {- entries = await Promise.allSettled(- enabled.map(async (src) => {- const start = Date.now()- const res = await httpClient.fetch(`${src.url}?t=${now}`, {- signal: AbortSignal.timeout(30_000),- })- const text = await res.text()- const urls = [- ...new Set(- text- .split(/\r?\n/)- .map((line) => line.trim())- .filter(isValidTrackerLine)- ),- ]- return {- id: src.id,- urls,- elapsedMs: Date.now() - start,+ await Promise.all(+ Array.from({ length: Math.min(4, enabled.length) }, async () => {+ while (index < enabled.length) {+ const src = enabled[index++]+ const start = Date.now()+ const old =+ cache[src.id]?.url === src.url ? cache[src.id] : undefined+ try {+ const headers: Record<string, string> = {}+ if (old?.etag) headers['If-None-Match'] = old.etag+ if (old?.lastModified)+ headers['If-Modified-Since'] = old.lastModified+ const response = await client.fetch(src.url, {+ headers,+ signal: signal+ ? AbortSignal.any([signal, AbortSignal.timeout(30_000)])+ : AbortSignal.timeout(30_000),+ })+ const status = response.status ?? 200+ if (status === 304 && old?.lastSuccessAt == null)+ throw new SourceError('missing-cache')+ if (status !== 304 && (status < 200 || status >= 300)) {+ const retry = response.headers?.get('retry-after')+ const delay = retry+ ? /^\d+$/.test(retry)+ ? Number(retry) * 1000+ : Date.parse(retry) - Date.now()+ : undefined+ await response.body+ ?.getReader()+ .cancel()+ .catch(() => undefined)+ throw new SourceError(+ 'http',+ delay && Number.isFinite(delay)+ ? Math.max(0, Math.min(delay, 12 * 3_600_000))+ : undefined+ )+ }+ const urls =+ status === 304 && old+ ? old.urls+ : parseTrackerSource(await readLimited(response))+ sourceStatus[src.id] = {+ ok: true,+ count: urls.length,+ elapsedMs: Date.now() - start,+ urls,+ notModified: status === 304,+ etag:+ response.headers?.get('etag') ??+ (status === 304 ? old?.etag : undefined),+ lastModified:+ response.headers?.get('last-modified') ??+ (status === 304 ? old?.lastModified : undefined),+ }+ } catch (error) {+ const failure =+ error instanceof SourceError ? error.code : 'network'+ sourceStatus[src.id] = {+ ok: false,+ count: 0,+ elapsedMs: Date.now() - start,+ failure,+ error: failure,+ retryAfterMs:+ error instanceof SourceError ? error.retryAfterMs : undefined,+ }+ // Do not log source URLs or raw fetch errors containing credentials.+ log.warn({ id: src.id, failure }, 'source fetch failed')+ }}}))} finally {- await httpClient.close()+ await client.close()}-- const seen = new Set<string>()- const sourceStatus: Record<string, SourceFetchStatus> = {}-- for (let i = 0; i < entries.length; i++) {- const entry = entries[i]- const src = enabled[i]- if (entry.status === 'fulfilled') {- for (const url of entry.value.urls) {- seen.add(url)- }- sourceStatus[src.id] = {- ok: true,- count: entry.value.urls.length,- elapsedMs: entry.value.elapsedMs,- urls: entry.value.urls,- }- log.debug(- {- id: src.id,- count: entry.value.urls.length,- elapsedMs: entry.value.elapsedMs,- },- 'source fetched'- )- } else {- const error = entry.reason?.message ?? 'Unknown error'- sourceStatus[src.id] = {- ok: false,- count: 0,- elapsedMs: 0,- error,- }- log.warn(- { id: src.id, url: src.url, error, err: entry.reason },- 'source fetch failed'- )- }+ return {+ trackers: [+ ...new Set(+ Object.values(sourceStatus).flatMap((status) => status.urls ?? [])+ ),+ ],+ sourceStatus,}-- const okCount = Object.values(sourceStatus).filter((s) => s.ok).length- const failCount = Object.values(sourceStatus).length - okCount- log.info(- {- uniqueTrackers: seen.size,- okSources: okCount,- failedSources: failCount,- },- 'fetch done'- )-- return { trackers: [...seen], sourceStatus }}}diff --git a/src/main/index.ts b/src/main/index.tsindex a4eafbf8..547379a6 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -119,6 +119,7 @@ import {TrackerStore,TrackerSyncer,} from '@core/tracker'+import { TaskTrackerRepository } from '@core/tracker/task-tracker-repository'import type { NatManager } from '@motrix/nat'import { APP_ID } from '@shared/constants'import { DEFAULT_LOCALE, type SupportedLocale } from '@shared/constants/locales'@@ -1713,6 +1714,7 @@ async function initializeMainProcess(): Promise<void> {// OS logout/shutdown: skip the quit dialog so session end is never blocked.powerMonitor.on('shutdown', prepareForSessionEnd)+ powerMonitor.on('resume', () => trackerManager?.notifyWake())if (gate.isAccepted()) {const runMode = settingsManager.getApp().runMode@@ -2221,6 +2223,8 @@ async function initializeMainProcess(): Promise<void> {trackerProber,trackerStore,{+ runTaskMutation: (taskIds, operation) =>+ activeTaskInspectorActivityRuntime.runTaskMutation(taskIds, operation),pauseTask: (taskId) =>pauseTaskAction(taskId, {taskManager,@@ -2262,6 +2266,11 @@ async function initializeMainProcess(): Promise<void> {},(settings) => proxyBridge.resolveForFetch(settings))+ trackerManager.configureTaskTracking(+ adapter,+ taskManager,+ new TaskTrackerRepository(motrixDb.database)+ )const proxyApplier = createMainProxyApplier(supervisor,@@ -2462,6 +2471,10 @@ async function initializeMainProcess(): Promise<void> {// control-plane. getMediaSegmentGids is lazy over bridgeManager.current// (same as the IPC command path in commands.ts).const mediaActionDeps = {+ onPauseRequested: (taskId: string) =>+ trackerManager?.noteTaskControl(taskId, true),+ onResumeRequested: (taskId: string) =>+ trackerManager?.noteTaskControl(taskId, false),taskManager,adapter,eventBus,diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.tsindex 2f7912e9..b30d6a0e 100644--- a/src/main/ipc/commands.test.ts+++ b/src/main/ipc/commands.test.ts@@ -201,6 +201,7 @@ function fakeCtx() {setChannel: vi.fn(),},trackerManager: {+ applySelectionChange: vi.fn().mockResolvedValue(undefined),applySourcesChange: vi.fn().mockResolvedValue(undefined),applyBlacklistChange: vi.fn().mockResolvedValue(undefined),applySyncScheduleChange: vi.fn(),@@ -1340,6 +1341,7 @@ describe('SetTaskBtTracker handler', () => {taskManager,} as unknown as CommandContext)await handlers[Commands.SetTaskBtTracker]?.({+ taskId: 'task-1',engineGid: 'gid-1',trackers: ['http://a'],})@@ -1350,7 +1352,7 @@ describe('SetTaskBtTracker handler', () => {)})- it('no-ops when task not found', async () => {+ it('rejects a missing task without mutating trackers', async () => {const trackerManager = { setBtTracker: vi.fn() }const taskManager = {...fakeCtx().taskManager,@@ -1361,10 +1363,13 @@ describe('SetTaskBtTracker handler', () => {trackerManager,taskManager,} as unknown as CommandContext)- await handlers[Commands.SetTaskBtTracker]?.({- engineGid: 'gid-x',- trackers: [],- })+ await expect(+ handlers[Commands.SetTaskBtTracker]?.({+ taskId: 'task-1',+ engineGid: 'gid-x',+ trackers: [],+ })+ ).rejects.toThrow('Tracker task changed')expect(trackerManager.setBtTracker).not.toHaveBeenCalled()})})@@ -2134,6 +2139,36 @@ describe('Commands.UpdateSettings', () => {expect(ctx.notificationCenter.notify).not.toHaveBeenCalled()})+ it('reselects when the configured cap changes without fetching sources', async () => {+ const ctx = fakeCtx()+ const before = makeSettingsLike(PROXY_OFF, {+ tracker: { maxTrackerCount: 50 },+ })+ const after = makeSettingsLike(PROXY_OFF, {+ tracker: { maxTrackerCount: 10 },+ })+ const settingsManager = {+ ...ctx.settingsManager,+ get: vi.fn().mockReturnValueOnce(before).mockReturnValueOnce(after),+ update: vi.fn().mockResolvedValue({+ ok: true,+ requiresRestart: false,+ changedRestartKeys: [],+ }),+ }+ const handlers = buildCommandHandlers({+ ...ctx,+ settingsManager,+ } as unknown as CommandContext)+ await handlers[Commands.UpdateSettings]?.({+ tracker: { maxTrackerCount: 10 },+ })+ expect(ctx.trackerManager.applySelectionChange).toHaveBeenCalledOnce()+ expect(ctx.trackerManager.syncAndCurate).not.toHaveBeenCalled()+ await handlers[Commands.RetryTrackerSources]?.()+ expect(ctx.trackerManager.syncAndCurate).toHaveBeenCalledWith('retry')+ })+it('calls trackerManager.applySourcesChange when sourcesEnabled changes', async () => {const ctx = fakeCtx()const before = makeSettingsLike(PROXY_OFF, {@@ -2375,7 +2410,7 @@ describe('SyncTaskBtTracker handler', () => {)})- it('defaults isPrivate to false when metadata not found', async () => {+ it('blocks public supplementation when private metadata is unknown', async () => {const trackerManager = {syncBtTracker: vi.fn().mockResolvedValue(undefined),}@@ -2396,7 +2431,7 @@ describe('SyncTaskBtTracker handler', () => {expect(trackerManager.syncBtTracker).toHaveBeenCalledWith('task-1','gid-1',- false+ true)})})diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex 31128596..67cc490a 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -114,6 +114,10 @@ import { checkPluginUpdatesPayloadSchema } from '@shared/schemas/plugin-update'import { REGISTRY_PLUGIN_ID_RE } from '@shared/schemas/registry'import { removeTaskPayloadSchema } from '@shared/schemas/remove-task'import { showAddTaskWindowSchema } from '@shared/schemas/show-add-task-window'+import {+ taskTrackerApplySchema,+ taskTrackerEditSchema,+} from '@shared/schemas/task-tracker'import {CLI_INSTALL_PACKAGE_MANAGERS,type CliInstallRequest,@@ -404,6 +408,10 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {// Shared by the singular AND plural task command handlers below — one// deps bundle per action family so the two arities cannot drift.const pauseResumeDeps = {+ onPauseRequested: (taskId: string) =>+ trackerManager.noteTaskControl?.(taskId, true),+ onResumeRequested: (taskId: string) =>+ trackerManager.noteTaskControl?.(taskId, false),taskManager,adapter,eventBus,@@ -1152,6 +1160,21 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {)}+ if (+ JSON.stringify(oldFull.tracker.sources) !==+ JSON.stringify(newFull.tracker.sources) ||+ JSON.stringify(oldFull.tracker.blacklistSources) !==+ JSON.stringify(newFull.tracker.blacklistSources) ||+ oldFull.tracker.maxTrackerCount !==+ newFull.tracker.maxTrackerCount ||+ oldFull.tracker.probeEnabled !== newFull.tracker.probeEnabled ||+ oldFull.tracker.minSuccessRate !== newFull.tracker.minSuccessRate ||+ oldFull.tracker.healthyThresholdMs !==+ newFull.tracker.healthyThresholdMs+ ) {+ await trackerManager.applySelectionChange()+ }+if (oldFull.tracker.autoSync !== newFull.tracker.autoSync ||oldFull.tracker.syncIntervalHours !==@@ -1477,6 +1500,9 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {return { ok: true }},+ [Commands.RetryTrackerSources]: async () =>+ trackerManager.syncAndCurate('retry'),+[Commands.SyncTrackers]: async () => {log.info('syncTrackers: invoked')try {@@ -1496,24 +1522,24 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {}},- [Commands.SetTaskBtTracker]: async (params: {- engineGid: string- trackers: string[]- }) => {- const task = taskManager.getByEngineTaskId(params.engineGid)- if (!task) return- await trackerManager.setBtTracker(- task.id,- params.engineGid,- params.trackers- )+ [Commands.ApplyTaskTrackerPlan]: async (raw: unknown) => {+ const { taskId, engineGid, fingerprint } =+ taskTrackerApplySchema.parse(raw)+ await trackerManager.applyTaskTrackerPlan(taskId, engineGid, fingerprint)+ },++ [Commands.SetTaskBtTracker]: async (raw: unknown) => {+ const { taskId, engineGid, trackers } = taskTrackerEditSchema.parse(raw)+ const task = taskManager.getByEngineTaskId(engineGid)+ if (!task || task.id !== taskId) throw new Error('Tracker task changed')+ await trackerManager.setBtTracker(taskId, engineGid, trackers)},[Commands.SyncTaskBtTracker]: async (params: { engineGid: string }) => {const task = taskManager.getByEngineTaskId(params.engineGid)if (!task) returnconst pair = motrixDatabase.getTask(task.id)- const isPrivate = pair?.task.isPrivate ?? false+ const isPrivate = pair?.task.isPrivate ?? task.bt?.isPrivate ?? trueawait trackerManager.syncBtTracker(task.id, params.engineGid, isPrivate)},diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.tsindex 6ead7707..1c0b7eef 100644--- a/src/main/ipc/queries.ts+++ b/src/main/ipc/queries.ts@@ -45,6 +45,7 @@ import {import type { QueryHandlerMap } from '@shared/protocol/handler-types'import { Queries } from '@shared/protocol/queries'import { parseTaskInspectorActivitySnapshot } from '@shared/schemas/task-inspector-activity'+import { taskTrackerRequestSchema } from '@shared/schemas/task-tracker'import type { GetTransferStatsParams } from '@shared/types/stats'import type { GetTaskActivityParams } from '@shared/types/task-activity'import { ipcMain, session } from 'electron'@@ -250,6 +251,11 @@ export function buildQueryHandlers(ctx: QueryContext): QueryHandlerMap {[Queries.GetTuningRecommendation]: getTuningRecommendation,+ [Queries.GetTaskTrackerPlan]: async (raw: unknown) => {+ const { taskId, engineGid } = taskTrackerRequestSchema.parse(raw)+ return trackerManager.getTaskTrackerPlan(taskId, engineGid)+ },+[Queries.GetTrackerList]: async () => {return trackerManager.getCuratedList()},diff --git a/src/renderer/components/ui/dialog.tsx b/src/renderer/components/ui/dialog.tsxindex 24f8c93d..d84c4e17 100644--- a/src/renderer/components/ui/dialog.tsx+++ b/src/renderer/components/ui/dialog.tsx@@ -41,16 +41,21 @@ function DialogContent({className,children,overlayClassName,+ forceRenderOverlay = false,showCloseButton = true,...props}: DialogPrimitive.Popup.Props & {overlayClassName?: string+ forceRenderOverlay?: booleanshowCloseButton?: boolean}) {const { t } = useTranslation()return (<DialogPortal>- <DialogOverlay className={overlayClassName} />+ <DialogOverlay+ className={overlayClassName}+ forceRender={forceRenderOverlay}+ /><DialogPrimitive.Popupdata-slot="dialog-content"className={cn(diff --git a/src/renderer/routes/downloads/inspector/task-tracker-dialog.tsx b/src/renderer/routes/downloads/inspector/task-tracker-dialog.tsxnew file mode 100644index 00000000..db3e9679--- /dev/null+++ b/src/renderer/routes/downloads/inspector/task-tracker-dialog.tsx@@ -0,0 +1,96 @@+import { Button } from '@renderer/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/components/ui/dialog'+import type { TaskTrackerPlan } from '@shared/schemas/task-tracker'+import { useTranslation } from 'react-i18next'++export function TaskTrackerDialog({+ plan,+ open,+ onOpenChange,+ onApply,+ busy,+}: {+ plan: TaskTrackerPlan | null+ open: boolean+ onOpenChange: (open: boolean) => void+ onApply: () => void+ busy: boolean+}) {+ const { t } = useTranslation()+ const key = 'panel.downloads.inspector.trackers.preview'+ return (+ <Dialog+ open={open}+ onOpenChange={(value) => {+ if (!busy) onOpenChange(value)+ }}+ >+ {/* The inspector drawer is non-modal, so this nested dialog needs its own backdrop. */}+ <DialogContent forceRenderOverlay>+ <DialogHeader>+ <DialogTitle>{t(`${key}.title`)}</DialogTitle>+ <DialogDescription>{t(`${key}.description`)}</DialogDescription>+ </DialogHeader>+ {plan && (+ <div className="space-y-3 text-xs">+ {plan.requiresPause && (+ <p className="text-muted-foreground">{t(`${key}.reconnect`)}</p>+ )}+ <div className="max-h-64 overflow-auto rounded-lg border border-border divide-y divide-border">+ {(['added', 'removed'] as const).map((kind) => (+ <section key={kind} className="p-3 space-y-2">+ <h3 className="font-medium">+ {t(`${key}.${kind}`, { count: plan[kind].length })}+ </h3>+ {plan[kind].length > 0 && (+ <ul className="space-y-1 text-muted-foreground">+ {plan[kind].map((url) => (+ <li className="break-all select-text" key={url}>+ {url}+ </li>+ ))}+ </ul>+ )}+ </section>+ ))}+ </div>+ <p className="text-muted-foreground">+ {t(`${key}.retained`, { count: plan.retained.length })}+ </p>+ {plan.excluded.length > 0 && (+ <p className="text-muted-foreground">+ {t(`${key}.excluded`, { count: plan.excluded.length })}+ </p>+ )}+ </div>+ )}+ <DialogFooter>+ <Button+ variant="outline"+ size="sm"+ disabled={busy}+ onClick={() => onOpenChange(false)}+ >+ {t('common.cancel')}+ </Button>+ <Button+ size="sm"+ disabled={+ busy || !plan || plan.added.length + plan.removed.length === 0+ }+ onClick={onApply}+ >+ {t(`${key}.apply`)}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/src/renderer/routes/downloads/inspector/trackers-tab.test.tsx b/src/renderer/routes/downloads/inspector/trackers-tab.test.tsxindex c0600b4b..c93ab4ae 100644--- a/src/renderer/routes/downloads/inspector/trackers-tab.test.tsx+++ b/src/renderer/routes/downloads/inspector/trackers-tab.test.tsx@@ -93,6 +93,19 @@ describe('TrackersTab — read mode', () => {if (channel === Queries.GetTaskDetail) {return makeBtTask()}+ if (channel === Queries.GetTaskTrackerPlan)+ return {+ taskId: 'task-1',+ engineGid: 'gid-1',+ fingerprint: 'a'.repeat(64),+ added: ['http://global2'],+ removed: [],+ retained: [],+ original: ['http://announce1', 'http://announce2'],+ excluded: [],+ requiresPause: true,+ protected: false,+ }return undefined})@@ -123,7 +136,7 @@ describe('TrackersTab — read mode', () => {render(<TrackersTab task={makeBtTask()} />)// 4 rows, 1 global URL not in effective (global2)expect(await screen.findByText(/4 trackers/)).toBeInTheDocument()- expect(screen.getByText(/1 not in global/)).toBeInTheDocument()+ expect(screen.getByText(/Pending changes: 1/)).toBeInTheDocument()})it('shows private banner when isPrivate', async () => {@@ -302,6 +315,7 @@ describe('TrackersTab — read mode', () => {) as HTMLButtonElementawait userEvent.click(trash)expect(transport.invoke).toHaveBeenCalledWith(Commands.SetTaskBtTracker, {+ taskId: 'task-1',engineGid: 'gid-1',trackers: ['http://global1', 'http://announce1'], // effective minus 'http://effective-only'})@@ -357,6 +371,7 @@ describe('TrackersTab — edit mode', () => {await userEvent.type(textarea, 'http://a\nhttps://b\nudp://c:80')await userEvent.click(screen.getByRole('button', { name: /save/i }))expect(transport.invoke).toHaveBeenCalledWith(Commands.SetTaskBtTracker, {+ taskId: 'task-1',engineGid: 'gid-1',trackers: ['http://a', 'https://b', 'udp://c:80'],})@@ -373,6 +388,7 @@ describe('TrackersTab — edit mode', () => {expect.objectContaining({ type: 'warning' }))expect(transport.invoke).toHaveBeenCalledWith(Commands.SetTaskBtTracker, {+ taskId: 'task-1',engineGid: 'gid-1',trackers: ['http://ok'],})@@ -480,25 +496,84 @@ describe('TrackersTab — Sync', () => {vi.clearAllMocks()})- it('Sync click invokes SyncTaskBtTracker', async () => {- ;(transport.invoke as ReturnType<typeof vi.fn>).mockImplementation(- async (channel) => {- if (channel === Queries.GetTaskBtTracker) return []- return undefined- }- )+ it('previews additions and removals without writing, then applies the reviewed fingerprint', async () => {+ const plan = {+ taskId: 'task-1',+ engineGid: 'gid-1',+ fingerprint: 'a'.repeat(64),+ added: ['https://new.example/announce'],+ removed: ['udp://old.example:80'],+ retained: ['https://manual.example/announce'],+ original: ['https://native.example/announce'],+ excluded: ['udp://excluded.example:80'],+ requiresPause: true,+ protected: false,+ }+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.GetTaskBtTracker) return []+ if (channel === Queries.GetTaskDetail) return makeBtTask()+ if (channel === Queries.GetTaskTrackerPlan) return plan+ return undefined+ })render(<TrackersTab task={makeBtTask()} />)await userEvent.click(await screen.findByRole('button', { name: /sync/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.SyncTaskBtTracker, {- engineGid: 'gid-1',+ expect(await screen.findByRole('dialog')).toBeInTheDocument()+ expect(screen.getByText(plan.added[0]!)).toBeInTheDocument()+ expect(screen.getByText(plan.removed[0]!)).toBeInTheDocument()+ expect(screen.getByText(/briefly pause and reconnect/)).toBeInTheDocument()+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.ApplyTaskTrackerPlan,+ expect.anything()+ )+ await userEvent.click(screen.getByRole('button', { name: 'Apply update' }))+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.ApplyTaskTrackerPlan,+ {+ taskId: plan.taskId,+ engineGid: plan.engineGid,+ fingerprint: plan.fingerprint,+ }+ )+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())+ })++ it('dismisses the preview on task switch without applying it', async () => {+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.GetTaskBtTracker) return []+ if (channel === Queries.GetTaskDetail) return makeBtTask()+ if (channel === Queries.GetTaskTrackerPlan)+ return {+ taskId: 'task-1',+ engineGid: 'gid-1',+ fingerprint: 'a'.repeat(64),+ added: [],+ removed: [],+ retained: [],+ original: [],+ excluded: [],+ requiresPause: false,+ protected: false,+ }})+ const { rerender } = render(<TrackersTab task={makeBtTask()} />)+ await userEvent.click(await screen.findByRole('button', { name: /sync/i }))+ expect(await screen.findByRole('dialog')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Apply update' })).toBeDisabled()+ rerender(+ <TrackersTab task={makeBtTask({ id: 'task-2', engineTaskId: 'gid-2' })} />+ )+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.ApplyTaskTrackerPlan,+ expect.anything()+ )})it('Sync error toasts', async () => {;(transport.invoke as ReturnType<typeof vi.fn>).mockImplementation(async (channel) => {if (channel === Queries.GetTaskBtTracker) return []- if (channel === Commands.SyncTaskBtTracker) throw new Error('rpc fail')+ if (channel === Queries.GetTaskTrackerPlan) throw new Error('rpc fail')})render(<TrackersTab task={makeBtTask()} />)diff --git a/src/renderer/routes/downloads/inspector/trackers-tab.tsx b/src/renderer/routes/downloads/inspector/trackers-tab.tsxindex 71dca0df..52e8744a 100644--- a/src/renderer/routes/downloads/inspector/trackers-tab.tsx+++ b/src/renderer/routes/downloads/inspector/trackers-tab.tsx@@ -12,10 +12,16 @@ import { parseTrackerInput } from '@renderer/lib/trackers'import { transport } from '@renderer/lib/transport'import { cn } from '@renderer/lib/utils'import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import {+ type TaskTrackerPlan,+ taskTrackerPlanSchema,+} from '@shared/schemas/task-tracker'import type { DownloadTask } from '@shared/types/task'import { TaskStatus } from '@shared/types/task'import { type KeyboardEvent, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'+import { TaskTrackerDialog } from './task-tracker-dialog'interface TrackerRowData {url: string@@ -38,6 +44,7 @@ export function TrackersTab({ task }: TrackersTabProps) {task.engineTaskId)const { list } = useTrackerList()+ const [nativeUrls, setNativeUrls] = useState<string[] | null>(null)// announceList is projected out of the broadcast (option E); read the// static seed list on demand from the full per-task detail. Keyed on@@ -46,9 +53,11 @@ export function TrackersTab({ task }: TrackersTabProps) {const detail = useTaskBtDetail(task.id, task.engineTaskId)const { announceList } = detailconst detailReady = !detail.isLoading && detail.error === null- const announceFlat = useMemo(() => announceList.flat(), [announceList])+ const announceFlat = useMemo(+ () => nativeUrls ?? announceList.flat(),+ [nativeUrls, announceList]+ )const announceSet = useMemo(() => new Set(announceFlat), [announceFlat])- const effectiveSet = useMemo(() => new Set(effective), [effective])const isPrivate = task.bt?.isPrivate === true// Tasks that aria2 no longer holds (Completed-and-evicted, Error,// Removed) cannot accept SetTaskBtTracker / SyncTaskBtTracker —@@ -78,12 +87,39 @@ export function TrackersTab({ task }: TrackersTabProps) {return out}, [announceFlat, announceSet, effective, detailReady])- const driftCount = useMemo(() => {- if (isPrivate) return 0- if (!isEditable) return 0- return list.effective.filter((u) => !effectiveSet.has(u)).length- }, [list.effective, effectiveSet, isPrivate, isEditable])+ const planRequest = JSON.stringify({+ taskId: task.id,+ engineGid: task.engineTaskId,+ effective,+ selected: list.effective,+ })+ const [driftCount, setDriftCount] = useState(0)+ useEffect(() => {+ let disposed = false+ setDriftCount(0)+ if (!isEditable) return+ const { taskId, engineGid } = JSON.parse(planRequest)+ void transport+ .invoke(Queries.GetTaskTrackerPlan, { taskId, engineGid })+ .then((raw) => {+ const result = taskTrackerPlanSchema.safeParse(raw)+ if (!disposed && result.success) {+ setNativeUrls(result.data.original)+ setDriftCount(+ isPrivate+ ? 0+ : result.data.added.length + result.data.removed.length+ )+ }+ })+ .catch(() => undefined)+ return () => {+ disposed = true+ }+ }, [planRequest, isEditable, isPrivate])+ const [syncPlan, setSyncPlan] = useState<TaskTrackerPlan | null>(null)+ const [planOpen, setPlanOpen] = useState(false)const [mode, setMode] = useState<'read' | 'edit'>('read')const [draft, setDraft] = useState('')const [isSaving, setIsSaving] = useState(false)@@ -105,6 +141,9 @@ export function TrackersTab({ task }: TrackersTabProps) {setMode('read')setIsSaving(false)setIsSyncing(false)+ setSyncPlan(null)+ setNativeUrls(null)+ setPlanOpen(false)}, [task.id, task.engineTaskId])// If a task transitions out of editable state mid-edit (e.g. polling@@ -197,6 +236,7 @@ export function TrackersTab({ task }: TrackersTabProps) {setIsSaving(true)try {await transport.invoke(Commands.SetTaskBtTracker, {+ taskId: task.id,engineGid: task.engineTaskId,trackers: valid,})@@ -222,10 +262,15 @@ export function TrackersTab({ task }: TrackersTabProps) {const taskKey = taskKeyRef.currentsetIsSyncing(true)try {- await transport.invoke(Commands.SyncTaskBtTracker, {- engineGid: task.engineTaskId,- })- await refresh()+ const plan = taskTrackerPlanSchema.parse(+ await transport.invoke(Queries.GetTaskTrackerPlan, {+ taskId: task.id,+ engineGid: task.engineTaskId,+ })+ )+ if (taskKeyRef.current !== taskKey) return+ setSyncPlan(plan)+ setPlanOpen(true)} catch (e) {if (taskKeyRef.current !== taskKey) returntoast.add({@@ -239,6 +284,34 @@ export function TrackersTab({ task }: TrackersTabProps) {}}+ const applyPlan = async () => {+ if (!syncPlan || isSyncing) return+ const taskKey = taskKeyRef.current+ setIsSyncing(true)+ try {+ await transport.invoke(Commands.ApplyTaskTrackerPlan, {+ taskId: syncPlan.taskId,+ engineGid: syncPlan.engineGid,+ fingerprint: syncPlan.fingerprint,+ })+ await refresh()+ if (taskKeyRef.current === taskKey) setPlanOpen(false)+ } catch (error) {+ if (taskKeyRef.current !== taskKey) return+ toast.add({+ title: t('panel.downloads.inspector.trackers.syncFailed', {+ reason: error instanceof Error ? error.message : String(error),+ }),+ type: 'error',+ })+ // Refresh the diff after a stale preview or partial failure. Applying the+ // newly computed plan still requires an explicit click.+ await sync()+ } finally {+ if (taskKeyRef.current === taskKey) setIsSyncing(false)+ }+ }+const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {e.preventDefault()@@ -254,6 +327,7 @@ export function TrackersTab({ task }: TrackersTabProps) {const next = effective.filter((u) => u !== url)try {await transport.invoke(Commands.SetTaskBtTracker, {+ taskId: task.id,engineGid: task.engineTaskId,trackers: next,})@@ -273,6 +347,13 @@ export function TrackersTab({ task }: TrackersTabProps) {return (<div className="flex min-h-0 flex-1 flex-col gap-2">+ <TaskTrackerDialog+ plan={syncPlan}+ open={planOpen}+ onOpenChange={setPlanOpen}+ onApply={applyPlan}+ busy={isSyncing}+ />{isPrivate && (<Alert className="shrink-0 flex items-center gap-2"><LockedIcon className="size-3.5 shrink-0" />@@ -291,9 +372,12 @@ export function TrackersTab({ task }: TrackersTabProps) {<>{' · '}<span className="text-foreground">- {t('panel.downloads.inspector.trackers.driftSuffix', {- count: driftCount,- })}+ {t(+ 'panel.downloads.inspector.trackers.preview.changesPending',+ {+ count: driftCount,+ }+ )}</span></>)}@@ -302,7 +386,12 @@ export function TrackersTab({ task }: TrackersTabProps) {{mode === 'read' ? (isEditable ? (<>- <Button size="xs" variant="outline" onClick={startEdit}>+ <Button+ size="xs"+ variant="outline"+ onClick={startEdit}+ disabled={isSyncing}+ >{t('panel.downloads.inspector.trackers.action.edit')}</Button><Buttondiff --git a/src/renderer/routes/trackers/components/tracker-sync-details.tsx b/src/renderer/routes/trackers/components/tracker-sync-details.tsxnew file mode 100644index 00000000..13986fe6--- /dev/null+++ b/src/renderer/routes/trackers/components/tracker-sync-details.tsx@@ -0,0 +1,352 @@+import { InfoIcon } from '@renderer/components/icons'+import { Button } from '@renderer/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from '@renderer/components/ui/dialog'+import { Input } from '@renderer/components/ui/input'+import {+ ScrollArea,+ ScrollAreaContent,+ ScrollAreaViewport,+ ScrollBar,+} from '@renderer/components/ui/scroll-area'+import {+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+} from '@renderer/components/ui/tabs'+import { useTrackerList } from '@renderer/hooks/use-tracker-list'+import { useTransportMirror } from '@renderer/hooks/use-transport-mirror'+import { transport } from '@renderer/lib/transport'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import { TRACKER_SOURCE_MAX_AGE_MS } from '@shared/schemas/tracker-state'+import type { AppSettings, TrackerSettings } from '@shared/types/settings'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'++export function TrackerSyncDetails({+ kind,+ message,+ busy,+}: {+ kind: 'effective' | 'blacklist'+ message?: string+ busy: boolean+}) {+ const { t, i18n } = useTranslation()+ const { list, error } = useTrackerList()+ const [settings, setSettings] = useState<TrackerSettings | null>(null)+ const [open, setOpen] = useState(false)+ const [retrying, setRetrying] = useState(false)+ const [retryFailed, setRetryFailed] = useState(false)+ const [search, setSearch] = useState('')+ const [limit, setLimit] = useState(50)+ useTransportMirror({+ events: [],+ refreshOnSettingsSave: true,+ load: async (stale, read) => {+ const next = (await read(Queries.GetSettings)) as AppSettings+ if (!stale()) setSettings(next.tracker)+ },+ })+ const date = (value: number | null | undefined) =>+ value == null ? '—' : new Date(value).toLocaleString(i18n.language)+ const blacklist = kind === 'blacklist'+ const sources =+ (blacklist ? settings?.blacklistSources : settings?.sources)?.filter(+ (s) => s.enabled+ ) ?? []+ const enabled = blacklist+ ? settings?.blacklistEnabled+ : settings?.sourcesEnabled+ const rows = sources.map((source) => {+ const stored =+ list.snapshots?.[`${blacklist ? 'blacklist' : 'tracker'}:${source.id}`]+ const snapshot = stored?.url === source.url ? stored : undefined+ const state =+ snapshot?.lastSuccessAt == null+ ? snapshot?.error+ ? 'failed'+ : 'pending'+ : Date.now() - snapshot.lastSuccessAt > TRACKER_SOURCE_MAX_AGE_MS+ ? 'expired'+ : snapshot.error+ ? 'cached'+ : 'fresh'+ return { source, snapshot, state }+ })+ const failed = rows.filter(+ (row) => row.snapshot?.error || row.state === 'expired'+ )+ const count = blacklist ? list.blacklist.length : list.effective.length+ const summary =+ message ??+ (error+ ? t('trackers.sync.unavailable')+ : !settings+ ? '—'+ : !enabled+ ? t('trackers.sync.details.disabled')+ : !sources.length+ ? t('trackers.sync.details.noSources')+ : failed.length+ ? t('trackers.sync.details.attention', {+ count,+ failed: failed.length,+ })+ : t('trackers.sync.details.summary', {+ count,+ time: date(list.lastSyncAt),+ }))+ const candidates = (list.candidates ?? []).filter((row) =>+ row.url.toLowerCase().includes(search.toLowerCase())+ )+ async function retry() {+ setRetrying(true)+ setRetryFailed(false)+ try {+ await transport.invoke(Commands.RetryTrackerSources)+ } catch {+ setRetryFailed(true)+ } finally {+ setRetrying(false)+ }+ }+ return (+ <div className="flex min-w-0 items-center gap-1.5">+ <span className="truncate" title={summary}>+ {summary}+ </span>+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger+ render={+ <Button+ size="icon-xs"+ variant="ghost"+ aria-label={t('trackers.sync.details.title')}+ />+ }+ >+ <InfoIcon />+ </DialogTrigger>+ <DialogContent+ className="flex max-h-[85vh] flex-col gap-0 p-0 sm:max-w-[700px]"+ initialFocus={false}+ >+ <DialogHeader className="shrink-0 px-6 pt-6 pb-4">+ <DialogTitle>{t('trackers.sync.details.title')}</DialogTitle>+ <DialogDescription>+ {t('trackers.sync.details.scope')}+ </DialogDescription>+ </DialogHeader>+ <Tabs+ key={kind}+ defaultValue="sources"+ className="flex min-h-0 flex-1 flex-col px-6"+ >+ <TabsList className="shrink-0 bg-tab-background">+ <TabsTrigger value="sources">+ {t('trackers.sync.details.sources')}+ </TabsTrigger>+ {!blacklist && (+ <TabsTrigger value="candidates">+ {t('trackers.sync.details.candidates')}+ </TabsTrigger>+ )}+ <TabsTrigger value="history">+ {t('trackers.sync.details.history')}+ </TabsTrigger>+ </TabsList>+ <ScrollArea className="mt-4 min-h-0 flex-1">+ <ScrollAreaViewport className="max-h-[55vh] overscroll-contain">+ <ScrollAreaContent>+ <TabsContent value="sources" className="m-0 space-y-4 pb-4">+ <dl className="grid grid-cols-2 gap-x-6 gap-y-3 text-xs">+ <div>+ <dt className="text-muted-foreground">+ {t('trackers.sync.details.lastAttempt')}+ </dt>+ <dd className="mt-1">{date(list.lastAttemptAt)}</dd>+ </div>+ <div>+ <dt className="text-muted-foreground">+ {t('trackers.sync.details.nextCheck')}+ </dt>+ <dd className="mt-1">+ {settings?.autoSync+ ? date(list.nextCheckAt)+ : t('trackers.sync.details.autoOff')}+ </dd>+ </div>+ </dl>+ {list.pendingEngineApply && (+ <p className="text-xs text-muted-foreground">+ {t('trackers.sync.details.enginePending')}+ </p>+ )}+ <div className="divide-y rounded-lg border border-border">+ {rows.map(({ source, snapshot, state }) => (+ <div+ key={source.id}+ className="space-y-1.5 px-3 py-3 text-xs"+ >+ <div className="flex items-start justify-between gap-4">+ <span className="min-w-0 truncate font-medium">+ {source.label}+ </span>+ <span className="shrink-0 text-muted-foreground">+ {t(`trackers.sync.details.state.${state}`)}+ </span>+ </div>+ <p className="text-muted-foreground">+ {t('trackers.sync.details.sourceResult', {+ count: snapshot?.urls.length ?? 0,+ time: date(snapshot?.lastSuccessAt),+ })}+ </p>+ {snapshot?.error && (+ <p className="text-muted-foreground">+ {t(+ `trackers.sync.details.failure.${snapshot.error}`+ )}+ </p>+ )}+ {snapshot?.nextRetryAt && settings?.autoSync && (+ <p className="text-muted-foreground">+ {t('trackers.sync.details.retryAt', {+ time: date(snapshot.nextRetryAt),+ })}+ </p>+ )}+ </div>+ ))}+ {!rows.length && (+ <p className="p-4 text-xs text-muted-foreground">+ {t('trackers.sync.details.noSources')}+ </p>+ )}+ </div>+ </TabsContent>+ <TabsContent+ value="candidates"+ className="m-0 space-y-3 pb-4"+ >+ <p className="text-xs text-muted-foreground">+ {t('trackers.sync.details.evidence')}+ </p>+ <Input+ aria-label={t('panel.trackers.searchPlaceholder')}+ placeholder={t('panel.trackers.searchPlaceholder')}+ value={search}+ onChange={(e) => {+ setSearch(e.target.value)+ setLimit(50)+ }}+ />+ <div className="divide-y rounded-lg border border-border">+ {candidates.slice(0, limit).map((row) => (+ <div+ key={row.url}+ className="space-y-1 px-3 py-2 text-xs"+ >+ <div className="flex items-start justify-between gap-3">+ <span className="min-w-0 break-all">{row.url}</span>+ <span className="shrink-0 text-muted-foreground">+ {t(`trackers.sync.details.reason.${row.reason}`)}+ </span>+ </div>+ <p className="text-muted-foreground">+ {t('trackers.sync.details.firstSeen', {+ time: date(row.firstSeenAt),+ })}+ </p>+ </div>+ ))}+ {!candidates.length && (+ <p className="p-4 text-xs text-muted-foreground">+ {t('trackers.sync.details.noCandidates')}+ </p>+ )}+ </div>+ {limit < candidates.length && (+ <Button+ size="sm"+ variant="ghost"+ onClick={() => setLimit((n) => n + 50)}+ >+ {t('trackers.sync.details.showMore')}+ </Button>+ )}+ </TabsContent>+ <TabsContent value="history" className="m-0 pb-4">+ <div className="divide-y rounded-lg border border-border">+ {(list.history ?? []).map((run) => (+ <div+ key={run.id}+ className="space-y-1.5 px-3 py-3 text-xs"+ >+ <div className="flex justify-between gap-3">+ <span>+ {t(+ `trackers.sync.details.outcome.${run.outcome}`+ )}+ </span>+ <span className="text-muted-foreground">+ {date(run.finishedAt)}+ </span>+ </div>+ <p className="text-muted-foreground">+ {t('trackers.sync.details.run', {+ success: run.successfulSources,+ failed: run.failedSources,+ added: run.added,+ removed: run.removed,+ })}+ </p>+ </div>+ ))}+ {!list.history?.length && (+ <p className="p-4 text-xs text-muted-foreground">+ {t('trackers.sync.details.noHistory')}+ </p>+ )}+ </div>+ </TabsContent>+ </ScrollAreaContent>+ </ScrollAreaViewport>+ <ScrollBar />+ </ScrollArea>+ </Tabs>+ <DialogFooter className="shrink-0 border-t border-border px-6 py-4">+ {retryFailed && (+ <p role="alert" className="text-xs text-destructive">+ {t('trackers.sync.failed')}+ </p>+ )}+ {rows.some((row) => row.snapshot?.error) && (+ <Button+ variant="outline"+ size="sm"+ disabled={busy || retrying || !enabled}+ onClick={retry}+ >+ {t('trackers.sync.details.retry')}+ </Button>+ )}+ <Button size="sm" onClick={() => setOpen(false)}>+ {t('common.close')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ )+}diff --git a/src/renderer/routes/trackers/trackers-page.test.tsx b/src/renderer/routes/trackers/trackers-page.test.tsxindex 0478997a..cecba437 100644--- a/src/renderer/routes/trackers/trackers-page.test.tsx+++ b/src/renderer/routes/trackers/trackers-page.test.tsx@@ -63,6 +63,73 @@ describe('TrackersPage', () => {expect(screen.getByRole('button', { name: 'Filter by URL…' })).toHaveFocus()})+ it('opens real update details and retries failed sources without moving the original controls', async () => {+ const source = {+ id: 's1',+ label: 'Example source',+ url: 'https://list.test',+ enabled: true,+ builtin: false,+ cdn: false,+ }+ const now = Date.now()+ vi.mocked(transport.invoke).mockImplementation(async (cmd) => {+ if (cmd === Queries.GetSettings)+ return {+ tracker: {+ ...SETTINGS_RESPONSE.tracker,+ sources: [source],+ autoSync: true,+ },+ }+ if (cmd === Queries.GetTrackerSyncStatus) return 'idle'+ if (cmd === Queries.GetTrackerList)+ return {+ ...TRACKER_LIST_RESPONSE,+ effective: ['udp://a:80'],+ candidates: [+ {+ url: 'udp://a:80',+ sourceIds: ['s1'],+ firstSeenAt: now,+ reason: 'selected',+ },+ ],+ snapshots: {+ 'tracker:s1': {+ id: 's1',+ url: source.url,+ urls: ['udp://a:80'],+ lastSuccessAt: now,+ error: 'network',+ nextRetryAt: now + 300_000,+ },+ },+ }+ return undefined+ })+ const user = userEvent.setup({ pointerEventsCheck: 0 })+ render(<TrackersPage />)+ await waitFor(() => expect(screen.getByRole('switch')).toBeInTheDocument())+ await user.click(screen.getByRole('button', { name: 'Update details' }))+ const dialog = screen.getByRole('dialog')+ expect(+ within(dialog).getByText('Using last successful cache')+ ).toBeInTheDocument()+ await user.click(+ within(dialog).getByRole('button', { name: 'Retry failed sources' })+ )+ expect(transport.invoke).toHaveBeenCalledWith(Commands.RetryTrackerSources)+ await user.click(within(dialog).getByRole('tab', { name: 'Candidates' }))+ expect(within(dialog).getByText('Selected')).toBeInTheDocument()+ expect(within(dialog).getByText(/First seen:/)).toBeInTheDocument()+ await user.keyboard('{Escape}')+ await waitFor(() =>+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ )+ expect(screen.getByRole('button', { name: 'Update details' })).toHaveFocus()+ })+it('renders panel title and the two tabs', () => {render(<TrackersPage />)expect(screen.getByText('Trackers')).toBeInTheDocument()diff --git a/src/renderer/routes/trackers/trackers-page.tsx b/src/renderer/routes/trackers/trackers-page.tsxindex c6eeec8c..beba4a5b 100644--- a/src/renderer/routes/trackers/trackers-page.tsx+++ b/src/renderer/routes/trackers/trackers-page.tsx@@ -15,6 +15,7 @@ import { useState } from 'react'import { useTranslation } from 'react-i18next'import { BlacklistTrackerPanel } from './components/blacklist-tracker-panel'import { EffectiveTrackerPanel } from './components/effective-tracker-panel'+import { TrackerSyncDetails } from './components/tracker-sync-details'export function TrackersPage() {const { t } = useTranslation()@@ -53,12 +54,18 @@ export function TrackersPage() {error && 'text-destructive')}>- {syncMessage ??- (error === 'failed'- ? t('trackers.sync.failed')- : error === 'unavailable'- ? t('trackers.sync.unavailable')- : null)}+ <TrackerSyncDetails+ kind={tab}+ busy={isSyncing}+ message={+ syncMessage ??+ (error === 'failed'+ ? t('trackers.sync.failed')+ : error === 'unavailable'+ ? t('trackers.sync.unavailable')+ : undefined)+ }+ /></div><Buttontype="button"diff --git a/src/server/index.ts b/src/server/index.tsindex bedfd6bf..5769fc92 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -122,6 +122,7 @@ import {TrackerStore,TrackerSyncer,} from '@core/tracker'+import { TaskTrackerRepository } from '@core/tracker/task-tracker-repository'import { resolveSupportedLocale } from '@shared/constants/locales'import { Commands } from '@shared/protocol/commands'import { Events } from '@shared/protocol/events'@@ -838,6 +839,8 @@ async function main() {trackerProber,trackerStore,{+ runTaskMutation: (taskIds, operation) =>+ taskInspectorActivityRuntime.runTaskMutation(taskIds, operation),pauseTask: (taskId) =>pauseTaskAction(taskId, {taskManager,@@ -873,6 +876,12 @@ async function main() {},(settings) => proxyBridge.resolveForFetch(settings))+ trackerManager.configureTaskTracking(+ adapter,+ taskManager,+ new TaskTrackerRepository(db.database)+ )+shutdownActions.disposeTracker = () => trackerManager.stopAndDrain()// ─── Proxy Applier ────────────────────────────────────────────@@ -1853,6 +1862,10 @@ async function main() {}),}const taskActionDeps = {+ onPauseRequested: (taskId: string) =>+ trackerManager.noteTaskControl(taskId, true),+ onResumeRequested: (taskId: string) =>+ trackerManager.noteTaskControl(taskId, false),taskManager,adapter,eventBus,diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.tsindex 8d81e2b3..855fcd73 100644--- a/src/server/ipc/commands.test.ts+++ b/src/server/ipc/commands.test.ts@@ -91,6 +91,8 @@ function makeFakeCtx() {rpcClient: {} as Aria2RpcClient,adapter: {} as EngineAdapter,trackerManager: {+ applySelectionChange: vi.fn().mockResolvedValue(undefined),+ syncAndCurate: vi.fn().mockResolvedValue(undefined),applySourcesChange: vi.fn().mockResolvedValue(undefined),applyBlacklistChange: vi.fn().mockResolvedValue(undefined),applySyncScheduleChange: vi.fn(),@@ -206,6 +208,7 @@ function makeSettings(blacklistEnabled?: booleanautoSync?: booleansyncIntervalHours?: number+ maxTrackerCount?: number} = {},engine: { dnsMode?: 'auto' | 'system' | 'engine'; split?: number } = {},app: { defaultSaveDir?: string; browserBridgeEnabled?: boolean } = {},@@ -957,6 +960,32 @@ describe('server Commands.UpdateSettings', () => {expect(ctx.notificationCenter.notify).not.toHaveBeenCalled()})+ it('reselects when the configured cap changes without fetching sources', async () => {+ const ctx = makeFakeCtx()+ const before = makeSettings(PROXY_OFF, { maxTrackerCount: 50 })+ const after = makeSettings(PROXY_OFF, { maxTrackerCount: 10 })+ const settingsManager = {+ ...ctx.settingsManager,+ get: vi.fn().mockReturnValueOnce(before).mockReturnValueOnce(after),+ update: vi.fn().mockResolvedValue({+ ok: true,+ requiresRestart: false,+ changedRestartKeys: [],+ }),+ }+ const handlers = buildServerCommandHandlers({+ ...ctx,+ settingsManager,+ } as unknown as ServerCommandContext)+ await handlers[Commands.UpdateSettings]?.({+ tracker: { maxTrackerCount: 10 },+ })+ expect(ctx.trackerManager.applySelectionChange).toHaveBeenCalledOnce()+ expect(ctx.trackerManager.syncAndCurate).not.toHaveBeenCalled()+ await handlers[Commands.RetryTrackerSources]?.()+ expect(ctx.trackerManager.syncAndCurate).toHaveBeenCalledWith('retry')+ })+it('calls trackerManager.applySourcesChange when sourcesEnabled changes', async () => {const ctx = makeFakeCtx();(ctx.settingsManager.get as ReturnType<typeof vi.fn>)diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex 8616cb80..c6fa6655 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -89,6 +89,10 @@ import { languagePreferenceSchema } from '@shared/schemas/locale'import { moveTasksPayloadSchema } from '@shared/schemas/move-tasks'import { checkPluginUpdatesPayloadSchema } from '@shared/schemas/plugin-update'import { removeTaskPayloadSchema } from '@shared/schemas/remove-task'+import {+ taskTrackerApplySchema,+ taskTrackerEditSchema,+} from '@shared/schemas/task-tracker'import { EngineRecoveryAction } from '@shared/types/engine'import type { ProxySettings } from '@shared/types/settings'import type { DownloadTask } from '@shared/types/task'@@ -285,6 +289,10 @@ export function buildServerCommandHandlers(// Shared by the singular AND plural task command handlers below — one// deps bundle per action family so the two arities cannot drift.const pauseResumeDeps = {+ onPauseRequested: (taskId: string) =>+ trackerManager.noteTaskControl?.(taskId, true),+ onResumeRequested: (taskId: string) =>+ trackerManager.noteTaskControl?.(taskId, false),taskManager,adapter,eventBus,@@ -847,6 +855,21 @@ export function buildServerCommandHandlers()}+ if (+ JSON.stringify(oldFull.tracker.sources) !==+ JSON.stringify(newFull.tracker.sources) ||+ JSON.stringify(oldFull.tracker.blacklistSources) !==+ JSON.stringify(newFull.tracker.blacklistSources) ||+ oldFull.tracker.maxTrackerCount !==+ newFull.tracker.maxTrackerCount ||+ oldFull.tracker.probeEnabled !== newFull.tracker.probeEnabled ||+ oldFull.tracker.minSuccessRate !== newFull.tracker.minSuccessRate ||+ oldFull.tracker.healthyThresholdMs !==+ newFull.tracker.healthyThresholdMs+ ) {+ await trackerManager.applySelectionChange()+ }+if (oldFull.tracker.autoSync !== newFull.tracker.autoSync ||oldFull.tracker.syncIntervalHours !==@@ -886,28 +909,28 @@ export function buildServerCommandHandlers([Commands.RequestDefaultTorrentHandler]: async () => ({ ok: false }),+ [Commands.RetryTrackerSources]: async () =>+ trackerManager.syncAndCurate('retry'),+[Commands.SyncTrackers]: async () => trackerManager.syncAndCurate(),- [Commands.SetTaskBtTracker]: async (params: {- engineGid: string- trackers: string[]- }) => {- const task = taskManager.getByEngineTaskId(params.engineGid)- if (!task) return- await trackerManager.setBtTracker(- task.id,- params.engineGid,- params.trackers- )+ [Commands.ApplyTaskTrackerPlan]: async (raw: unknown) => {+ const { taskId, engineGid, fingerprint } =+ taskTrackerApplySchema.parse(raw)+ await trackerManager.applyTaskTrackerPlan(taskId, engineGid, fingerprint)+ },++ [Commands.SetTaskBtTracker]: async (raw: unknown) => {+ const { taskId, engineGid, trackers } = taskTrackerEditSchema.parse(raw)+ const task = taskManager.getByEngineTaskId(engineGid)+ if (!task || task.id !== taskId) throw new Error('Tracker task changed')+ await trackerManager.setBtTracker(taskId, engineGid, trackers)},[Commands.SyncTaskBtTracker]: async (params: { engineGid: string }) => {const task = taskManager.getByEngineTaskId(params.engineGid)if (!task) return- // Server mode lacks db-backed isPrivate persistence; rely on the- // in-memory DownloadTask.bt.isPrivate (false in current server impl- // until proper persistence lands).- const isPrivate = task.bt?.isPrivate ?? false+ const isPrivate = task.bt?.isPrivate ?? trueawait trackerManager.syncBtTracker(task.id, params.engineGid, isPrivate)},diff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.tsindex a86596b7..db077b07 100644--- a/src/server/ipc/queries.ts+++ b/src/server/ipc/queries.ts@@ -42,6 +42,7 @@ import type { SupportedLocale } from '@shared/constants/locales'import type { QueryHandlerMap } from '@shared/protocol/handler-types'import { Queries } from '@shared/protocol/queries'import { ListServerDirectoryLocationsRequestSchema } from '@shared/schemas/server-directory'+import { taskTrackerRequestSchema } from '@shared/schemas/task-tracker'import type { AppUpdateState } from '@shared/types/app-update'import type { AppImageIntegrationView } from '@shared/types/appimage-integration'import {@@ -297,6 +298,11 @@ export function buildServerQueryHandlers(magnet: false,}),+ [Queries.GetTaskTrackerPlan]: async (raw: unknown) => {+ const { taskId, engineGid } = taskTrackerRequestSchema.parse(raw)+ return trackerManager.getTaskTrackerPlan(taskId, engineGid)+ },+[Queries.GetTrackerList]: async () => trackerManager.getCuratedList(),[Queries.GetTrackerSyncStatus]: async () => trackerManager.getSyncStatus(),diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.jsonindex 14ed419e..474ccb39 100644--- a/src/shared/locales/ar.json+++ b/src/shared/locales/ar.json@@ -1126,7 +1126,18 @@"summary_two": "المتعقّبات: {{count}}","summary_zero": "المتعقّبات: {{count}}","syncFailed": "تعذّرت مزامنة المتعقّبات: {{reason}}",- "syncPrivateDisabled": "المزامنة غير متاحة للتورنت الخاص."+ "syncPrivateDisabled": "المزامنة غير متاحة للتورنت الخاص.",+ "preview": {+ "title": "تحديث متتبعات المهمة",+ "description": "راجع تغييرات المتتبعات الإضافية. تُحفظ عناوين التورنت والعناوين المضافة يدويًا.",+ "reconnect": "ستتوقف المهمة مؤقتًا لفترة قصيرة وتعيد الاتصال ثم تستأنف تلقائيًا.",+ "added": "إضافة: {{count}}",+ "removed": "إزالة: {{count}}",+ "retained": "الاحتفاظ بالمتتبعات الإضافية الحالية: {{count}}. تبقى مجموعات announce الأصلية دون تغيير.",+ "excluded": "لن تُضاف المتتبعات التي أزلتها ({{count}}) مجددًا أثناء التحديثات التلقائية.",+ "apply": "تطبيق التحديث",+ "changesPending": "تغييرات معلقة: {{count}}"+ }}},"media": {@@ -2857,7 +2868,7 @@"disabled": "معطّل — فعّله لعرض قائمة المتعقّبات الفعّالة.","empty": "لا توجد متعقّبات فعّالة بعد. شغّل المزامنة لملء القائمة.","enabled": "إضافة المتعقّبات المنتقاة",- "enabledDesc": "إلحاق قائمة المتعقّبات المنتقاة بكل مهام BitTorrent."+ "enabledDesc": "إضافة المتتبعات المختارة إلى مهام BitTorrent العامة الجديدة."},"sync": {"applying": "جارٍ تطبيق قوائم المتعقّبات…",@@ -2865,7 +2876,57 @@"fetching": "جارٍ جلب قوائم المتعقّبات…","probing": "جارٍ التحقق من توفر المتعقّبات…","syncing": "جارٍ المزامنة…",- "unavailable": "تعذّرت قراءة حالة المزامنة. تحقق من الاتصال وحاول مجددًا."+ "unavailable": "تعذّرت قراءة حالة المزامنة. تحقق من الاتصال وحاول مجددًا.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"tray": {diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.jsonindex 864b5993..ef30c8d5 100644--- a/src/shared/locales/bg.json+++ b/src/shared/locales/bg.json@@ -1078,7 +1078,18 @@"summary_one": "{{count}} тракер","summary_other": "{{count}} тракера","syncFailed": "Списъкът с тракери не можа да бъде синхронизиран: {{reason}}",- "syncPrivateDisabled": "Синхронизирането е недостъпно за частни торенти."+ "syncPrivateDisabled": "Синхронизирането е недостъпно за частни торенти.",+ "preview": {+ "title": "Обновяване на тракерите на задачата",+ "description": "Прегледайте промените в допълнителните тракери. Адресите от торента и добавените ръчно се запазват.",+ "reconnect": "Задачата ще бъде спряна за кратко, ще се свърже отново и ще продължи автоматично.",+ "added": "Добавяне: {{count}}",+ "removed": "Премахване: {{count}}",+ "retained": "Запазване на {{count}} съществуващи допълнителни тракера. Оригиналните announce групи остават непроменени.",+ "excluded": "Премахнатите от вас тракери ({{count}}) няма да се добавят отново при автоматично обновяване.",+ "apply": "Прилагане на обновяването",+ "changesPending": "Чакащи промени: {{count}}"+ }}},"media": {@@ -2769,7 +2780,7 @@"disabled": "Изключено — включете, за да видите действащия списък с тракери.","empty": "Все още няма действащи тракери. Синхронизирайте, за да попълните списъка.","enabled": "Добавяне на подбрани тракери",- "enabledDesc": "Добавя списъка с подбрани тракери към всички BitTorrent задачи."+ "enabledDesc": "Добавяне на избраните тракери към нови публични BitTorrent задачи."},"sync": {"applying": "Прилагане на списъците с тракери…",@@ -2777,7 +2788,57 @@"fetching": "Изтегляне на списъците с тракери…","probing": "Проверка на достъпността на тракерите…","syncing": "Синхронизиране…",- "unavailable": "Състоянието на синхронизирането не може да се прочете. Проверете връзката и опитайте отново."+ "unavailable": "Състоянието на синхронизирането не може да се прочете. Проверете връзката и опитайте отново.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"tray": {diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.jsonindex 2ba51d49..159cf810 100644--- a/src/shared/locales/ca.json+++ b/src/shared/locales/ca.json@@ -1090,7 +1090,18 @@"summary_one": "{{count}} rastrejador","summary_other": "{{count}} rastrejadors","syncFailed": "No s'han pogut sincronitzar els rastrejadors: {{reason}}",- "syncPrivateDisabled": "La sincronització no està disponible per als torrents privats."+ "syncPrivateDisabled": "La sincronització no està disponible per als torrents privats.",+ "preview": {+ "title": "Actualitza els trackers de la tasca",+ "description": "Revisa els canvis dels trackers addicionals. Es conserven les adreces del torrent i les afegides manualment.",+ "reconnect": "La tasca es posarà en pausa breument, es reconnectarà i es reprendrà automàticament.",+ "added": "Afegeix: {{count}}",+ "removed": "Elimina: {{count}}",+ "retained": "Es conserven {{count}} trackers addicionals existents. Els grups announce originals no canvien.",+ "excluded": "Els {{count}} trackers que has eliminat no es tornaran a afegir en les actualitzacions automàtiques.",+ "apply": "Aplica l’actualització",+ "changesPending": "Canvis pendents: {{count}}"+ }}},"media": {@@ -2791,7 +2802,7 @@"disabled": "Desactivat; activeu-ho per veure la llista de rastrejadors efectius.","empty": "Encara no hi ha rastrejadors efectius. Sincronitzeu per emplenar la llista.","enabled": "Afegir rastrejadors seleccionats",- "enabledDesc": "Afegeix la llista de rastrejadors seleccionats a totes les tasques de BitTorrent."+ "enabledDesc": "Afegeix els trackers seleccionats a les noves tasques públiques de BitTorrent."},"sync": {"applying": "S'estan aplicant les llistes de rastrejadors…",@@ -2799,7 +2810,57 @@"fetching": "S'estan obtenint les llistes de rastrejadors…","probing": "S'està comprovant la disponibilitat dels rastrejadors…","syncing": "S'està sincronitzant…",- "unavailable": "No es pot llegir l'estat de sincronització. Comproveu la connexió i torneu-ho a provar."+ "unavailable": "No es pot llegir l'estat de sincronització. Comproveu la connexió i torneu-ho a provar.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"tray": {diff --git a/src/shared/locales/de.json b/src/shared/locales/de.jsonindex bf328fdf..abd7ead1 100644--- a/src/shared/locales/de.json+++ b/src/shared/locales/de.json@@ -818,7 +818,18 @@"invalidLines_one": "{{count}} ungültige Zeile übersprungen","invalidLines_other": "{{count}} ungültige Zeilen übersprungen","editPlaceholder": "Eine Tracker-URL pro Zeile. Nur http(s)/udp/ws(s).",- "editHint": "Diese Tracker ersetzen die wirksame bt-tracker-Liste der Aufgabe. Einträge der announce-list aus der .torrent-Datei bleiben unverändert."+ "editHint": "Diese Tracker ersetzen die wirksame bt-tracker-Liste der Aufgabe. Einträge der announce-list aus der .torrent-Datei bleiben unverändert.",+ "preview": {+ "title": "Task-Tracker aktualisieren",+ "description": "Änderungen an zusätzlichen Trackern prüfen. Torrent-eigene und manuell hinzugefügte Adressen bleiben erhalten.",+ "reconnect": "Dieser Task wird kurz pausiert, neu verbunden und automatisch fortgesetzt.",+ "added": "Hinzufügen: {{count}}",+ "removed": "Entfernen: {{count}}",+ "retained": "{{count}} vorhandene zusätzliche Tracker bleiben erhalten. Die ursprünglichen Announce-Gruppen bleiben unverändert.",+ "excluded": "{{count}} von dir entfernte Tracker werden bei automatischen Updates nicht erneut hinzugefügt.",+ "apply": "Update anwenden",+ "changesPending": "Ausstehende Änderungen: {{count}}"+ }},"multi": {"totals": "Gesamtwerte",@@ -2155,7 +2166,7 @@"trackers": {"effective": {"enabled": "Kuratierte Tracker hinzufügen",- "enabledDesc": "Die kuratierte Tracker-Liste an alle BitTorrent-Aufgaben anhängen.",+ "enabledDesc": "Ausgewählte Tracker zu neuen öffentlichen BitTorrent-Tasks hinzufügen.","disabled": "Deaktiviert – aktivieren Sie die Funktion, um die wirksame Tracker-Liste anzuzeigen.","empty": "Noch keine wirksamen Tracker. Starten Sie die Synchronisierung, um die Liste zu füllen.","column": {@@ -2193,7 +2204,57 @@"probing": "Tracker-Verfügbarkeit wird geprüft…","applying": "Tracker-Listen werden angewendet…","failed": "Synchronisierung unvollständig. Prüfen Sie Ihr Netzwerk oder Ihre Quellen und versuchen Sie es erneut.",- "unavailable": "Der Synchronisierungsstatus konnte nicht gelesen werden. Prüfen Sie Ihre Verbindung und versuchen Sie es erneut."+ "unavailable": "Der Synchronisierungsstatus konnte nicht gelesen werden. Prüfen Sie Ihre Verbindung und versuchen Sie es erneut.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"plugins": {diff --git a/src/shared/locales/el.json b/src/shared/locales/el.jsonindex 70f1868c..010d33cd 100644--- a/src/shared/locales/el.json+++ b/src/shared/locales/el.json@@ -1078,7 +1078,18 @@"summary_one": "{{count}} tracker","summary_other": "{{count}} trackers","syncFailed": "Δεν ήταν δυνατός ο συγχρονισμός των trackers: {{reason}}",- "syncPrivateDisabled": "Ο συγχρονισμός δεν είναι διαθέσιμος για ιδιωτικά torrents."+ "syncPrivateDisabled": "Ο συγχρονισμός δεν είναι διαθέσιμος για ιδιωτικά torrents.",+ "preview": {+ "title": "Ενημέρωση trackers εργασίας",+ "description": "Ελέγξτε τις αλλαγές στους πρόσθετους trackers. Οι διευθύνσεις του torrent και όσες προστέθηκαν χειροκίνητα διατηρούνται.",+ "reconnect": "Η εργασία θα διακοπεί στιγμιαία, θα επανασυνδεθεί και θα συνεχιστεί αυτόματα.",+ "added": "Προσθήκη: {{count}}",+ "removed": "Αφαίρεση: {{count}}",+ "retained": "Διατήρηση {{count}} υπαρχόντων πρόσθετων trackers. Οι αρχικές ομάδες announce παραμένουν αμετάβλητες.",+ "excluded": "Οι {{count}} trackers που αφαιρέσατε δεν θα προστεθούν ξανά στις αυτόματες ενημερώσεις.",+ "apply": "Εφαρμογή ενημέρωσης",+ "changesPending": "Εκκρεμείς αλλαγές: {{count}}"+ }}},"media": {@@ -2769,7 +2780,7 @@"disabled": "Απενεργοποιημένο — ενεργοποιήστε το για να δείτε τη λίστα trackers που εφαρμόζεται.","empty": "Δεν υπάρχουν ακόμη trackers προς εφαρμογή. Εκτελέστε συγχρονισμό για να συμπληρωθεί η λίστα.","enabled": "Προσθήκη επιλεγμένων trackers",- "enabledDesc": "Προσθήκη της επιλεγμένης λίστας trackers σε όλες τις εργασίες BitTorrent."+ "enabledDesc": "Προσθήκη επιλεγμένων trackers σε νέες δημόσιες εργασίες BitTorrent."},"sync": {"applying": "Εφαρμογή λιστών trackers…",@@ -2777,7 +2788,57 @@"fetching": "Λήψη λιστών trackers…","probing": "Έλεγχος διαθεσιμότητας trackers…","syncing": "Συγχρονισμός…",- "unavailable": "Δεν είναι δυνατή η ανάγνωση της κατάστασης συγχρονισμού. Ελέγξτε τη σύνδεσή σας και δοκιμάστε ξανά."+ "unavailable": "Δεν είναι δυνατή η ανάγνωση της κατάστασης συγχρονισμού. Ελέγξτε τη σύνδεσή σας και δοκιμάστε ξανά.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"tray": {diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex a91be694..c68e32b3 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -818,7 +818,18 @@"invalidLines_one": "Skipped {{count}} invalid line","invalidLines_other": "Skipped {{count}} invalid lines","editPlaceholder": "One tracker URL per line. http(s)/udp/ws(s) only.",- "editHint": "These trackers replace the task’s effective bt-tracker list. Announce-list entries from the .torrent are unaffected."+ "editHint": "These trackers replace the task’s effective bt-tracker list. Announce-list entries from the .torrent are unaffected.",+ "preview": {+ "title": "Update task trackers",+ "description": "Review changes to supplemental trackers. Torrent trackers and manually added addresses are preserved.",+ "reconnect": "This task will briefly pause and reconnect, then resume automatically.",+ "added": "Add: {{count}}",+ "removed": "Remove: {{count}}",+ "retained": "Keep {{count}} existing supplemental trackers. Native announce tiers stay unchanged.",+ "excluded": "{{count}} trackers you removed are excluded from automatic updates.",+ "apply": "Apply update",+ "changesPending": "Pending changes: {{count}}"+ }},"multi": {"totals": "Totals",@@ -2155,7 +2166,7 @@"trackers": {"effective": {"enabled": "Inject curated trackers",- "enabledDesc": "Append the curated tracker list to all BitTorrent tasks.",+ "enabledDesc": "Add curated trackers to new public BitTorrent tasks.","disabled": "Disabled — turn on to view the effective tracker list.","empty": "No effective trackers yet. Run sync to populate.","column": {@@ -2193,7 +2204,57 @@"probing": "Checking tracker availability…","applying": "Applying tracker lists…","failed": "Sync incomplete. Check your network or sources and try again.",- "unavailable": "Can’t read sync status. Check your connection and try again."+ "unavailable": "Can’t read sync status. Check your connection and try again.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"plugins": {diff --git a/src/shared/locales/es.json b/src/shared/locales/es.jsonindex 3307dda0..88461441 100644--- a/src/shared/locales/es.json+++ b/src/shared/locales/es.json@@ -830,7 +830,18 @@"editHint": "Estos trackers sustituyen la lista bt-tracker efectiva de la tarea. No se modifican las entradas de announce-list del archivo .torrent.","summary_many": "{{count}} trackers","driftSuffix_many": "Fuera de la lista global: {{count}}",- "invalidLines_many": "Se omitieron {{count}} líneas no válidas"+ "invalidLines_many": "Se omitieron {{count}} líneas no válidas",+ "preview": {+ "title": "Actualizar trackers de la tarea",+ "description": "Revisa los cambios de los trackers adicionales. Se conservan las direcciones del torrent y las añadidas manualmente.",+ "reconnect": "La tarea se pausará brevemente, se reconectará y se reanudará automáticamente.",+ "added": "Añadir: {{count}}",+ "removed": "Eliminar: {{count}}",+ "retained": "Se conservan {{count}} trackers adicionales existentes. Los grupos announce del torrent no cambian.",+ "excluded": "Los {{count}} trackers que eliminaste no se añadirán de nuevo en las actualizaciones automáticas.",+ "apply": "Aplicar actualización",+ "changesPending": "Cambios pendientes: {{count}}"+ }},"multi": {"totals": "Totales",@@ -2170,7 +2181,7 @@"trackers": {"effective": {"enabled": "Añadir trackers seleccionados",- "enabledDesc": "Añade la lista de trackers seleccionados a todas las tareas de BitTorrent.",+ "enabledDesc": "Añadir los trackers seleccionados a las nuevas tareas públicas de BitTorrent.","disabled": "Desactivado. Actívalo para ver la lista efectiva de trackers.","empty": "Todavía no hay trackers efectivos. Sincroniza para completar la lista.","column": {@@ -2208,7 +2219,57 @@"probing": "Comprobando disponibilidad de trackers…","applying": "Aplicando listas de trackers…","failed": "Sincronización incompleta. Comprueba la red o las fuentes y vuelve a intentarlo.",- "unavailable": "No se puede leer el estado de sincronización. Comprueba la conexión y vuelve a intentarlo."+ "unavailable": "No se puede leer el estado de sincronización. Comprueba la conexión y vuelve a intentarlo.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"plugins": {diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.jsonindex f3338816..12f90698 100644--- a/src/shared/locales/fa.json+++ b/src/shared/locales/fa.json@@ -1078,7 +1078,18 @@"summary_one": "{{count}} ردیاب","summary_other": "{{count}} ردیاب","syncFailed": "همگامسازی ردیابها ناموفق بود: {{reason}}",- "syncPrivateDisabled": "همگامسازی برای تورنتهای خصوصی در دسترس نیست."+ "syncPrivateDisabled": "همگامسازی برای تورنتهای خصوصی در دسترس نیست.",+ "preview": {+ "title": "بهروزرسانی ردیابهای کار",+ "description": "تغییرات ردیابهای تکمیلی را بررسی کنید. نشانیهای خود تورنت و نشانیهای دستی حفظ میشوند.",+ "reconnect": "این کار برای مدت کوتاهی مکث میکند، دوباره متصل میشود و خودکار ادامه مییابد.",+ "added": "افزودن: {{count}}",+ "removed": "حذف: {{count}}",+ "retained": "حفظ {{count}} ردیاب تکمیلی موجود. گروههای announce اصلی تغییر نمیکنند.",+ "excluded": "{{count}} ردیابی که حذف کردهاید در بهروزرسانی خودکار دوباره اضافه نمیشوند.",+ "apply": "اعمال بهروزرسانی",+ "changesPending": "تغییرات در انتظار: {{count}}"+ }}},"media": {@@ -2769,7 +2780,7 @@"disabled": "غیرفعال است؛ برای دیدن فهرست ردیابهای مؤثر، فعال کنید.","empty": "هنوز ردیاب مؤثری وجود ندارد. برای پر کردن فهرست، همگامسازی را اجرا کنید.","enabled": "افزودن ردیابهای گزینششده",- "enabledDesc": "فهرست ردیابهای گزینششده به همهٔ کارهای BitTorrent افزوده شود."+ "enabledDesc": "ردیابهای منتخب را به کارهای عمومی جدید BitTorrent اضافه کنید."},"sync": {"applying": "در حال اعمال فهرست ردیابها…",@@ -2777,7 +2788,57 @@"fetching": "در حال دریافت فهرست ردیابها…","probing": "در حال بررسی دسترسی به ردیابها…","syncing": "در حال همگامسازی…",- "unavailable": "خواندن وضعیت همگامسازی ممکن نیست. اتصال را بررسی کنید و دوباره تلاش کنید."+ "unavailable": "خواندن وضعیت همگامسازی ممکن نیست. اتصال را بررسی کنید و دوباره تلاش کنید.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"tray": {diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.jsonindex 4fc0982a..2dcd4354 100644--- a/src/shared/locales/fr.json+++ b/src/shared/locales/fr.json@@ -1084,7 +1084,18 @@"summary_one": "{{count}} tracker","summary_other": "{{count}} trackers","syncFailed": "Échec de la synchronisation des trackers : {{reason}}",- "syncPrivateDisabled": "La synchronisation est indisponible pour les torrents privés."+ "syncPrivateDisabled": "La synchronisation est indisponible pour les torrents privés.",+ "preview": {+ "title": "Mettre à jour les trackers de la tâche",+ "description": "Vérifiez les changements des trackers supplémentaires. Les adresses du torrent et celles ajoutées manuellement sont conservées.",+ "reconnect": "La tâche sera brièvement mise en pause, reconnectée, puis reprise automatiquement.",+ "added": "Ajouts : {{count}}",+ "removed": "Suppressions : {{count}}",+ "retained": "{{count}} trackers supplémentaires existants conservés. Les groupes announce du torrent restent inchangés.",+ "excluded": "Les {{count}} trackers que vous avez supprimés sont exclus des mises à jour automatiques.",+ "apply": "Appliquer la mise à jour",+ "changesPending": "Changements en attente : {{count}}"+ }}},"media": {@@ -2791,7 +2802,7 @@"disabled": "Désactivé. Activez cette option pour afficher la liste des trackers effectifs.","empty": "Aucun tracker effectif pour le moment. Lancez une synchronisation pour remplir la liste.","enabled": "Ajouter les trackers sélectionnés",- "enabledDesc": "Ajouter la liste de trackers sélectionnés à toutes les tâches BitTorrent."+ "enabledDesc": "Ajouter les trackers sélectionnés aux nouvelles tâches BitTorrent publiques."},"sync": {"applying": "Application des listes de trackers…",@@ -2799,7 +2810,57 @@"fetching": "Récupération des listes de trackers…","probing": "Vérification de la disponibilité des trackers…","syncing": "Synchronisation…",- "unavailable": "Impossible de lire l’état de la synchronisation. Vérifiez votre connexion et réessayez."+ "unavailable": "Impossible de lire l’état de la synchronisation. Vérifiez votre connexion et réessayez.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"tray": {diff --git a/src/shared/locales/id.json b/src/shared/locales/id.jsonindex 004bf163..6444354f 100644--- a/src/shared/locales/id.json+++ b/src/shared/locales/id.json@@ -806,7 +806,18 @@"deleteFailed": "Gagal menghapus pelacak: {{reason}}","invalidLines_other": "{{count}} baris tidak valid dilewati","editPlaceholder": "Satu URL pelacak per baris. Hanya http(s)/udp/ws(s).",- "editHint": "Pelacak ini menggantikan daftar bt-tracker yang digunakan oleh tugas. Entri announce-list dari .torrent tidak terpengaruh."+ "editHint": "Pelacak ini menggantikan daftar bt-tracker yang digunakan oleh tugas. Entri announce-list dari .torrent tidak terpengaruh.",+ "preview": {+ "title": "Perbarui tracker tugas",+ "description": "Tinjau perubahan tracker tambahan. Alamat bawaan torrent dan yang ditambahkan manual tetap dipertahankan.",+ "reconnect": "Tugas ini akan dijeda sebentar, disambungkan kembali, lalu dilanjutkan otomatis.",+ "added": "Tambah: {{count}}",+ "removed": "Hapus: {{count}}",+ "retained": "Pertahankan {{count}} tracker tambahan yang ada. Grup announce bawaan torrent tidak berubah.",+ "excluded": "{{count}} tracker yang Anda hapus tidak akan ditambahkan kembali dalam pembaruan otomatis.",+ "apply": "Terapkan pembaruan",+ "changesPending": "Perubahan tertunda: {{count}}"+ }},"multi": {"totals": "Total",@@ -2140,7 +2151,7 @@"trackers": {"effective": {"enabled": "Tambahkan pelacak terpilih",- "enabledDesc": "Tambahkan daftar pelacak terpilih ke semua tugas BitTorrent.",+ "enabledDesc": "Tambahkan tracker pilihan ke tugas BitTorrent publik yang baru.","disabled": "Nonaktif — aktifkan untuk melihat daftar pelacak yang digunakan.","empty": "Belum ada pelacak yang digunakan. Sinkronkan untuk mengisi daftar.","column": {@@ -2178,7 +2189,57 @@"probing": "Memeriksa ketersediaan pelacak…","applying": "Menerapkan daftar pelacak…","failed": "Sinkronisasi belum selesai. Periksa jaringan atau sumber, lalu coba lagi.",- "unavailable": "Status sinkronisasi tidak dapat dibaca. Periksa koneksi dan coba lagi."+ "unavailable": "Status sinkronisasi tidak dapat dibaca. Periksa koneksi dan coba lagi.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"plugins": {diff --git a/src/shared/locales/it.json b/src/shared/locales/it.jsonindex bb792dec..38c096ec 100644--- a/src/shared/locales/it.json+++ b/src/shared/locales/it.json@@ -830,7 +830,18 @@"invalidLines_other": "Ignorate {{count}} righe non valide","invalidLines_many": "Ignorate {{count}} righe non valide","editPlaceholder": "Un URL tracker per riga. Solo http(s)/udp/ws(s).",- "editHint": "Questi tracker sostituiscono l’elenco bt-tracker usato dall’attività. Le voci announce-list del file .torrent rimangono invariate."+ "editHint": "Questi tracker sostituiscono l’elenco bt-tracker usato dall’attività. Le voci announce-list del file .torrent rimangono invariate.",+ "preview": {+ "title": "Aggiorna i tracker dell’attività",+ "description": "Controlla le modifiche ai tracker aggiuntivi. Gli indirizzi del torrent e quelli aggiunti manualmente vengono mantenuti.",+ "reconnect": "L’attività verrà sospesa brevemente, riconnessa e ripresa automaticamente.",+ "added": "Aggiunte: {{count}}",+ "removed": "Rimozioni: {{count}}",+ "retained": "Mantieni {{count}} tracker aggiuntivi esistenti. I gruppi announce originali restano invariati.",+ "excluded": "I {{count}} tracker rimossi non verranno aggiunti nuovamente dagli aggiornamenti automatici.",+ "apply": "Applica aggiornamento",+ "changesPending": "Modifiche in sospeso: {{count}}"+ }},"multi": {"totals": "Totali",@@ -2170,7 +2181,7 @@"trackers": {"effective": {"enabled": "Aggiungi tracker selezionati",- "enabledDesc": "Aggiungi l’elenco dei tracker selezionati a tutte le attività BitTorrent.",+ "enabledDesc": "Aggiungi i tracker selezionati alle nuove attività BitTorrent pubbliche.","disabled": "Disattivato: attiva per visualizzare l’elenco dei tracker effettivamente usati.","empty": "Nessun tracker effettivamente in uso. Esegui la sincronizzazione per compilare l’elenco.","column": {@@ -2208,7 +2219,57 @@"probing": "Verifica della disponibilità dei tracker…","applying": "Applicazione degli elenchi tracker…","failed": "Sincronizzazione incompleta. Controlla la rete o le fonti e riprova.",- "unavailable": "Impossibile leggere lo stato della sincronizzazione. Controlla la connessione e riprova."+ "unavailable": "Impossibile leggere lo stato della sincronizzazione. Controlla la connessione e riprova.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"plugins": {diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.jsonindex 16664c93..40c35d65 100644--- a/src/shared/locales/ja.json+++ b/src/shared/locales/ja.json@@ -806,7 +806,18 @@"deleteFailed": "トラッカーを削除できませんでした:{{reason}}","invalidLines_other": "無効な行を {{count}} 行スキップしました","editPlaceholder": "トラッカーの URL を 1 行に 1 件入力してください。http(s)/udp/ws(s) のみ対応しています。",- "editHint": "このトラッカー一覧でタスクに適用中の bt-tracker リストを置き換えます。.torrent の Announce-list エントリーは変更しません。"+ "editHint": "このトラッカー一覧でタスクに適用中の bt-tracker リストを置き換えます。.torrent の Announce-list エントリーは変更しません。",+ "preview": {+ "title": "タスクのトラッカーを更新",+ "description": "補助トラッカーの変更を確認してください。Torrent 固有のアドレスと手動追加したアドレスは保持されます。",+ "reconnect": "このタスクは一時停止して再接続し、その後自動的に再開します。",+ "added": "追加: {{count}}",+ "removed": "削除: {{count}}",+ "retained": "既存の補助トラッカー {{count}} 件を保持します。Torrent 固有の announce グループは変更されません。",+ "excluded": "削除した {{count}} 件のトラッカーは自動更新で再追加されません。",+ "apply": "更新を適用",+ "changesPending": "保留中の変更: {{count}}"+ }},"multi": {"totals": "合計",@@ -2140,7 +2151,7 @@"trackers": {"effective": {"enabled": "選定済みトラッカーを追加",- "enabledDesc": "選定済みのトラッカー一覧をすべての BitTorrent タスクに追加します。",+ "enabledDesc": "新しい公開 BitTorrent タスクに選定したトラッカーを追加します。","disabled": "無効です。有効にすると、適用中のトラッカー一覧を表示します。","empty": "適用中のトラッカーはまだありません。同期して取得してください。","column": {@@ -2178,7 +2189,57 @@"probing": "トラッカーの接続を確認中…","applying": "トラッカー一覧を適用中…","failed": "同期が完了しませんでした。ネットワークまたはソースを確認して、もう一度お試しください。",- "unavailable": "同期状態を読み取れません。接続を確認して、もう一度お試しください。"+ "unavailable": "同期状態を読み取れません。接続を確認して、もう一度お試しください。",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"plugins": {diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.jsonindex c20e0229..d4f1bebf 100644--- a/src/shared/locales/ko.json+++ b/src/shared/locales/ko.json@@ -806,7 +806,18 @@"deleteFailed": "트래커를 제거하지 못했습니다: {{reason}}","invalidLines_other": "올바르지 않은 줄 {{count}}개를 건너뛰었습니다","editPlaceholder": "한 줄에 트래커 URL 하나를 입력하세요. http(s)/udp/ws(s)만 지원합니다.",- "editHint": "이 트래커 목록은 작업에 적용되는 bt-tracker 목록을 대체합니다. .torrent의 announce-list 항목에는 영향을 주지 않습니다."+ "editHint": "이 트래커 목록은 작업에 적용되는 bt-tracker 목록을 대체합니다. .torrent의 announce-list 항목에는 영향을 주지 않습니다.",+ "preview": {+ "title": "작업 트래커 업데이트",+ "description": "보조 트래커 변경 사항을 확인하세요. 토렌트에 포함된 주소와 수동으로 추가한 주소는 유지됩니다.",+ "reconnect": "이 작업은 잠시 일시 중지되어 다시 연결된 후 자동으로 재개됩니다.",+ "added": "추가: {{count}}",+ "removed": "제거: {{count}}",+ "retained": "기존 보조 트래커 {{count}}개를 유지합니다. 토렌트의 announce 그룹은 변경되지 않습니다.",+ "excluded": "삭제한 트래커 {{count}}개는 자동 업데이트 시 다시 추가되지 않습니다.",+ "apply": "업데이트 적용",+ "changesPending": "대기 중인 변경: {{count}}"+ }},"multi": {"totals": "합계",@@ -2140,7 +2151,7 @@"trackers": {"effective": {"enabled": "선별된 트래커 추가",- "enabledDesc": "모든 BitTorrent 작업에 선별된 트래커 목록을 추가합니다.",+ "enabledDesc": "새 공개 BitTorrent 작업에 선정된 트래커를 추가합니다.","disabled": "비활성화됨. 유효한 트래커 목록을 보려면 켜세요.","empty": "아직 유효한 트래커가 없습니다. 동기화하여 목록을 채우세요.","column": {@@ -2178,7 +2189,57 @@"probing": "트래커 사용 가능 여부를 확인하는 중…","applying": "트래커 목록을 적용하는 중…","failed": "동기화가 완료되지 않았습니다. 네트워크 또는 소스를 확인하고 다시 시도하세요.",- "unavailable": "동기화 상태를 읽지 못했습니다. 연결을 확인하고 다시 시도하세요."+ "unavailable": "동기화 상태를 읽지 못했습니다. 연결을 확인하고 다시 시도하세요.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"plugins": {diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.jsonindex a980f24c..7db801bb 100644--- a/src/shared/locales/nb.json+++ b/src/shared/locales/nb.json@@ -1078,7 +1078,18 @@"summary_one": "{{count}} tracker","summary_other": "{{count}} trackere","syncFailed": "Kunne ikke synkronisere trackere: {{reason}}",- "syncPrivateDisabled": "Synkronisering er utilgjengelig for private torrenter."+ "syncPrivateDisabled": "Synkronisering er utilgjengelig for private torrenter.",+ "preview": {+ "title": "Oppdater oppgavens trackere",+ "description": "Se gjennom endringene i ekstra trackere. Torrentens adresser og manuelt lagte adresser beholdes.",+ "reconnect": "Oppgaven settes kort på pause, kobles til på nytt og fortsetter automatisk.",+ "added": "Legg til: {{count}}",+ "removed": "Fjern: {{count}}",+ "retained": "Behold {{count}} eksisterende ekstra trackere. Torrentens announce-grupper forblir uendret.",+ "excluded": "De {{count}} trackerne du fjernet, legges ikke til igjen ved automatiske oppdateringer.",+ "apply": "Bruk oppdatering",+ "changesPending": "Ventende endringer: {{count}}"+ }}},"media": {@@ -2769,7 +2780,7 @@"disabled": "Deaktivert — slå på for å se trackerlisten som brukes.","empty": "Ingen trackere i bruk ennå. Kjør synkronisering for å fylle listen.","enabled": "Legg til utvalgte trackere",- "enabledDesc": "Legg den utvalgte trackerlisten til i alle BitTorrent-oppgaver."+ "enabledDesc": "Legg til utvalgte trackere i nye offentlige BitTorrent-oppgaver."},"sync": {"applying": "Tar i bruk trackerlister…",@@ -2777,7 +2788,57 @@"fetching": "Henter trackerlister…","probing": "Kontrollerer trackertilgjengelighet…","syncing": "Synkroniserer…",- "unavailable": "Kan ikke lese synkroniseringsstatus. Kontroller tilkoblingen og prøv igjen."+ "unavailable": "Kan ikke lese synkroniseringsstatus. Kontroller tilkoblingen og prøv igjen.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"tray": {diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.jsonindex 606bb45d..67bdef4f 100644--- a/src/shared/locales/nl.json+++ b/src/shared/locales/nl.json@@ -1078,7 +1078,18 @@"summary_one": "{{count}} tracker","summary_other": "{{count}} trackers","syncFailed": "Trackers konden niet worden gesynchroniseerd: {{reason}}",- "syncPrivateDisabled": "Synchronisatie is niet beschikbaar voor privétorrents."+ "syncPrivateDisabled": "Synchronisatie is niet beschikbaar voor privétorrents.",+ "preview": {+ "title": "Taaktrackers bijwerken",+ "description": "Controleer de wijzigingen in aanvullende trackers. Adressen uit de torrent en handmatig toegevoegde adressen blijven behouden.",+ "reconnect": "De taak wordt kort gepauzeerd, opnieuw verbonden en automatisch hervat.",+ "added": "Toevoegen: {{count}}",+ "removed": "Verwijderen: {{count}}",+ "retained": "{{count}} bestaande aanvullende trackers behouden. De oorspronkelijke announce-groepen blijven ongewijzigd.",+ "excluded": "De {{count}} door jou verwijderde trackers worden bij automatische updates niet opnieuw toegevoegd.",+ "apply": "Update toepassen",+ "changesPending": "Openstaande wijzigingen: {{count}}"+ }}},"media": {@@ -2769,7 +2780,7 @@"disabled": "Uitgeschakeld — schakel in om de gebruikte trackerlijst te bekijken.","empty": "Nog geen trackers in gebruik. Synchroniseer om de lijst te vullen.","enabled": "Geselecteerde trackers toevoegen",- "enabledDesc": "De samengestelde trackerlijst aan alle BitTorrent-taken toevoegen."+ "enabledDesc": "Geselecteerde trackers toevoegen aan nieuwe openbare BitTorrent-taken."},"sync": {"applying": "Trackerlijsten toepassen…",@@ -2777,7 +2788,57 @@"fetching": "Trackerlijsten ophalen…","probing": "Beschikbaarheid van trackers controleren…","syncing": "Synchroniseren…",- "unavailable": "De synchronisatiestatus kan niet worden gelezen. Controleer je verbinding en probeer het opnieuw."+ "unavailable": "De synchronisatiestatus kan niet worden gelezen. Controleer je verbinding en probeer het opnieuw.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"tray": {diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.jsonindex 899f63eb..d90bd757 100644--- a/src/shared/locales/pl.json+++ b/src/shared/locales/pl.json@@ -842,7 +842,18 @@"invalidLines_few": "Pominięto {{count}} nieprawidłowe wiersze","invalidLines_many": "Pominięto {{count}} nieprawidłowych wierszy","editPlaceholder": "Jeden adres URL trackera w wierszu. Tylko http(s)/udp/ws(s).",- "editHint": "Te trackery zastępują używaną przez zadanie listę bt-tracker. Wpisy announce-list z pliku .torrent pozostają bez zmian."+ "editHint": "Te trackery zastępują używaną przez zadanie listę bt-tracker. Wpisy announce-list z pliku .torrent pozostają bez zmian.",+ "preview": {+ "title": "Aktualizuj trackery zadania",+ "description": "Sprawdź zmiany dodatkowych trackerów. Adresy z torrenta i dodane ręcznie zostaną zachowane.",+ "reconnect": "Zadanie zostanie na chwilę wstrzymane, połączone ponownie i automatycznie wznowione.",+ "added": "Dodaj: {{count}}",+ "removed": "Usuń: {{count}}",+ "retained": "Zachowaj istniejące dodatkowe trackery: {{count}}. Oryginalne grupy announce pozostaną bez zmian.",+ "excluded": "Usunięte przez Ciebie trackery ({{count}}) nie zostaną ponownie dodane podczas automatycznej aktualizacji.",+ "apply": "Zastosuj aktualizację",+ "changesPending": "Oczekujące zmiany: {{count}}"+ }},"multi": {"totals": "Wartości łączne",@@ -2185,7 +2196,7 @@"trackers": {"effective": {"enabled": "Dodawaj trackery z wybranych list",- "enabledDesc": "Dołączaj listę wybranych trackerów do wszystkich zadań BitTorrent.",+ "enabledDesc": "Dodawaj wybrane trackery do nowych publicznych zadań BitTorrent.","disabled": "Wyłączone. Włącz, aby zobaczyć listę używanych trackerów.","empty": "Nie ma jeszcze używanych trackerów. Uruchom synchronizację, aby uzupełnić listę.","column": {@@ -2223,7 +2234,57 @@"probing": "Sprawdzanie dostępności trackerów…","applying": "Stosowanie list trackerów…","failed": "Synchronizacja jest niepełna. Sprawdź sieć lub źródła i spróbuj ponownie.",- "unavailable": "Nie można odczytać stanu synchronizacji. Sprawdź połączenie i spróbuj ponownie."+ "unavailable": "Nie można odczytać stanu synchronizacji. Sprawdź połączenie i spróbuj ponownie.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"plugins": {diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.jsonindex 84a8ed08..63deaa0e 100644--- a/src/shared/locales/pt-BR.json+++ b/src/shared/locales/pt-BR.json@@ -830,7 +830,18 @@"invalidLines_other": "{{count}} linhas inválidas ignoradas","invalidLines_many": "{{count}} linhas inválidas ignoradas","editPlaceholder": "Um URL de rastreador por linha. Apenas http(s)/udp/ws(s).",- "editHint": "Estes rastreadores substituem a lista bt-tracker em uso pela tarefa. As entradas announce-list do arquivo .torrent não são alteradas."+ "editHint": "Estes rastreadores substituem a lista bt-tracker em uso pela tarefa. As entradas announce-list do arquivo .torrent não são alteradas.",+ "preview": {+ "title": "Atualizar trackers da tarefa",+ "description": "Revise as alterações dos trackers adicionais. Os endereços do torrent e os adicionados manualmente serão mantidos.",+ "reconnect": "A tarefa será pausada brevemente, reconectada e retomada automaticamente.",+ "added": "Adicionar: {{count}}",+ "removed": "Remover: {{count}}",+ "retained": "Manter {{count}} trackers adicionais existentes. Os grupos announce do torrent não serão alterados.",+ "excluded": "Os {{count}} trackers removidos por você não serão adicionados novamente nas atualizações automáticas.",+ "apply": "Aplicar atualização",+ "changesPending": "Alterações pendentes: {{count}}"+ }},"multi": {"totals": "Totais",@@ -2170,7 +2181,7 @@"trackers": {"effective": {"enabled": "Adicionar rastreadores selecionados",- "enabledDesc": "Acrescenta a lista de rastreadores selecionados a todas as tarefas BitTorrent.",+ "enabledDesc": "Adicionar os trackers selecionados às novas tarefas públicas de BitTorrent.","disabled": "Desativado — ative para ver a lista de rastreadores em uso.","empty": "Ainda não há rastreadores em uso. Sincronize para preencher a lista.","column": {@@ -2208,7 +2219,57 @@"probing": "Verificando disponibilidade dos rastreadores…","applying": "Aplicando listas de rastreadores…","failed": "Sincronização incompleta. Verifique a rede ou as fontes e tente novamente.",- "unavailable": "Não foi possível ler o estado da sincronização. Verifique a conexão e tente novamente."+ "unavailable": "Não foi possível ler o estado da sincronização. Verifique a conexão e tente novamente.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"plugins": {diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.jsonindex af38aaec..c16c7f34 100644--- a/src/shared/locales/ro.json+++ b/src/shared/locales/ro.json@@ -1090,7 +1090,18 @@"summary_one": "{{count}} tracker","summary_other": "{{count}} de trackere","syncFailed": "Trackerele nu au putut fi sincronizate: {{reason}}",- "syncPrivateDisabled": "Sincronizarea nu este disponibilă pentru torrente private."+ "syncPrivateDisabled": "Sincronizarea nu este disponibilă pentru torrente private.",+ "preview": {+ "title": "Actualizează trackerele sarcinii",+ "description": "Verifică modificările trackerelor suplimentare. Adresele torrentului și cele adăugate manual sunt păstrate.",+ "reconnect": "Sarcina va fi întreruptă pentru scurt timp, reconectată și reluată automat.",+ "added": "Adaugă: {{count}}",+ "removed": "Elimină: {{count}}",+ "retained": "Păstrează {{count}} trackere suplimentare existente. Grupurile announce originale rămân neschimbate.",+ "excluded": "Cele {{count}} trackere eliminate nu vor fi adăugate din nou prin actualizări automate.",+ "apply": "Aplică actualizarea",+ "changesPending": "Modificări în așteptare: {{count}}"+ }}},"media": {@@ -2791,7 +2802,7 @@"disabled": "Dezactivat — activează pentru a vedea lista de trackere folosită.","empty": "Încă nu există trackere în uz. Sincronizează pentru a popula lista.","enabled": "Adaugă trackerele selectate",- "enabledDesc": "Adaugă lista de trackere selectate la toate sarcinile BitTorrent."+ "enabledDesc": "Adaugă trackerele selectate la sarcinile BitTorrent publice noi."},"sync": {"applying": "Se aplică listele de trackere…",@@ -2799,7 +2810,57 @@"fetching": "Se preiau listele de trackere…","probing": "Se verifică disponibilitatea trackerelor…","syncing": "Se sincronizează…",- "unavailable": "Starea sincronizării nu poate fi citită. Verifică conexiunea și încearcă din nou."+ "unavailable": "Starea sincronizării nu poate fi citită. Verifică conexiunea și încearcă din nou.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"tray": {diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.jsonindex 9cc93d5b..a9d3462f 100644--- a/src/shared/locales/ru.json+++ b/src/shared/locales/ru.json@@ -842,7 +842,18 @@"invalidLines_few": "Пропущены {{count}} некорректные строки","invalidLines_many": "Пропущено {{count}} некорректных строк","editPlaceholder": "Один URL трекера на строку. Только http(s)/udp/ws(s).",- "editHint": "Эти трекеры заменяют действующий список bt-tracker задачи. Записи announce-list из файла .torrent остаются без изменений."+ "editHint": "Эти трекеры заменяют действующий список bt-tracker задачи. Записи announce-list из файла .torrent остаются без изменений.",+ "preview": {+ "title": "Обновить трекеры задачи",+ "description": "Проверьте изменения дополнительных трекеров. Адреса из торрента и добавленные вручную сохраняются.",+ "reconnect": "Задача ненадолго приостановится, подключится заново и автоматически продолжится.",+ "added": "Добавить: {{count}}",+ "removed": "Удалить: {{count}}",+ "retained": "Сохраняются дополнительные трекеры: {{count}}. Исходные группы announce не изменяются.",+ "excluded": "Удалённые вами трекеры ({{count}}) не будут добавлены при автоматическом обновлении.",+ "apply": "Применить обновление",+ "changesPending": "Ожидающие изменения: {{count}}"+ }},"multi": {"totals": "Итоги",@@ -2185,7 +2196,7 @@"trackers": {"effective": {"enabled": "Добавлять отобранные трекеры",- "enabledDesc": "Добавлять отобранный список трекеров ко всем задачам BitTorrent.",+ "enabledDesc": "Добавлять выбранные трекеры в новые публичные задачи BitTorrent.","disabled": "Отключено — включите, чтобы просмотреть действующий список трекеров.","empty": "Действующих трекеров пока нет. Запустите синхронизацию для заполнения списка.","column": {@@ -2223,7 +2234,57 @@"probing": "Проверка доступности трекеров…","applying": "Применение списков трекеров…","failed": "Синхронизация не завершена. Проверьте сеть или источники и повторите попытку.",- "unavailable": "Не удалось получить статус синхронизации. Проверьте подключение и повторите попытку."+ "unavailable": "Не удалось получить статус синхронизации. Проверьте подключение и повторите попытку.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"plugins": {diff --git a/src/shared/locales/th.json b/src/shared/locales/th.jsonindex 7778f1db..22b19c00 100644--- a/src/shared/locales/th.json+++ b/src/shared/locales/th.json@@ -1066,7 +1066,18 @@"saveFailed": "อัปเดตแทร็กเกอร์ไม่ได้: {{reason}}","summary_other": "{{count}} แทร็กเกอร์","syncFailed": "ซิงค์แทร็กเกอร์ไม่ได้: {{reason}}",- "syncPrivateDisabled": "ซิงค์ทอร์เรนต์ส่วนตัวไม่ได้"+ "syncPrivateDisabled": "ซิงค์ทอร์เรนต์ส่วนตัวไม่ได้",+ "preview": {+ "title": "อัปเดตแทร็กเกอร์ของงาน",+ "description": "ตรวจสอบการเปลี่ยนแปลงแทร็กเกอร์เสริม โดยจะเก็บที่อยู่เดิมของทอร์เรนต์และที่อยู่ที่เพิ่มเองไว้",+ "reconnect": "งานนี้จะหยุดชั่วคราวสั้น ๆ เชื่อมต่อใหม่ แล้วทำงานต่อโดยอัตโนมัติ",+ "added": "เพิ่ม: {{count}}",+ "removed": "ลบ: {{count}}",+ "retained": "เก็บแทร็กเกอร์เสริมเดิม {{count}} รายการ โดยไม่เปลี่ยนกลุ่ม announce ของทอร์เรนต์",+ "excluded": "แทร็กเกอร์ {{count}} รายการที่คุณลบจะไม่ถูกเพิ่มกลับในการอัปเดตอัตโนมัติ",+ "apply": "ใช้อัปเดต",+ "changesPending": "การเปลี่ยนแปลงที่รออยู่: {{count}}"+ }}},"media": {@@ -2747,7 +2758,7 @@"disabled": "ปิดอยู่ — เปิดเพื่อดูรายการแทร็กเกอร์ที่ใช้งาน","empty": "ยังไม่มีแทร็กเกอร์ที่ใช้งาน ซิงค์เพื่อเติมรายการ","enabled": "เพิ่มแทร็กเกอร์ที่คัดเลือกแล้ว",- "enabledDesc": "เพิ่มรายการแทร็กเกอร์ที่คัดเลือกแล้วให้ทุกงาน BitTorrent"+ "enabledDesc": "เพิ่มแทร็กเกอร์ที่คัดเลือกให้งาน BitTorrent สาธารณะที่สร้างใหม่"},"sync": {"applying": "กำลังใช้รายการแทร็กเกอร์…",@@ -2755,7 +2766,57 @@"fetching": "กำลังดึงรายการแทร็กเกอร์…","probing": "กำลังตรวจสอบความพร้อมของแทร็กเกอร์…","syncing": "กำลังซิงค์…",- "unavailable": "อ่านสถานะการซิงค์ไม่ได้ ตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง"+ "unavailable": "อ่านสถานะการซิงค์ไม่ได้ ตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"tray": {diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.jsonindex 89f7a26d..0adf53e0 100644--- a/src/shared/locales/tr.json+++ b/src/shared/locales/tr.json@@ -818,7 +818,18 @@"invalidLines_one": "{{count}} geçersiz satır atlandı","invalidLines_other": "{{count}} geçersiz satır atlandı","editPlaceholder": "Her satıra bir izleyici URL’si girin. Yalnızca http(s)/udp/ws(s).",- "editHint": "Bu izleyiciler, görevin kullanılan bt-tracker listesinin yerini alır. .torrent dosyasındaki announce-list kayıtları etkilenmez."+ "editHint": "Bu izleyiciler, görevin kullanılan bt-tracker listesinin yerini alır. .torrent dosyasındaki announce-list kayıtları etkilenmez.",+ "preview": {+ "title": "Görev izleyicilerini güncelle",+ "description": "Ek izleyici değişikliklerini inceleyin. Torrent adresleri ve elle eklenen adresler korunur.",+ "reconnect": "Bu görev kısa süreliğine duraklatılacak, yeniden bağlanacak ve otomatik sürdürülecektir.",+ "added": "Ekle: {{count}}",+ "removed": "Kaldır: {{count}}",+ "retained": "Mevcut {{count}} ek izleyici korunur. Torrentin announce grupları değişmez.",+ "excluded": "Kaldırdığınız {{count}} izleyici otomatik güncellemelerle yeniden eklenmez.",+ "apply": "Güncellemeyi uygula",+ "changesPending": "Bekleyen değişiklikler: {{count}}"+ }},"multi": {"totals": "Toplamlar",@@ -2155,7 +2166,7 @@"trackers": {"effective": {"enabled": "Seçilmiş izleyicileri ekle",- "enabledDesc": "Seçilmiş izleyici listesini tüm BitTorrent görevlerine ekleyin.",+ "enabledDesc": "Seçilen izleyicileri yeni herkese açık BitTorrent görevlerine ekle.","disabled": "Devre dışı. Kullanılan izleyici listesini görmek için açın.","empty": "Henüz kullanılan izleyici yok. Listeyi doldurmak için eşzamanlayın.","column": {@@ -2193,7 +2204,57 @@"probing": "İzleyicilerin kullanılabilirliği kontrol ediliyor…","applying": "İzleyici listeleri uygulanıyor…","failed": "Eşzamanlama tamamlanmadı. Ağınızı veya kaynakları kontrol edip tekrar deneyin.",- "unavailable": "Eşzamanlama durumu okunamıyor. Bağlantınızı kontrol edip tekrar deneyin."+ "unavailable": "Eşzamanlama durumu okunamıyor. Bağlantınızı kontrol edip tekrar deneyin.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"plugins": {diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.jsonindex c831ab95..0747a268 100644--- a/src/shared/locales/uk.json+++ b/src/shared/locales/uk.json@@ -1102,7 +1102,18 @@"summary_one": "{{count}} трекер","summary_other": "{{count}} трекера","syncFailed": "Не вдалося синхронізувати трекери: {{reason}}",- "syncPrivateDisabled": "Синхронізація недоступна для приватних торрентів."+ "syncPrivateDisabled": "Синхронізація недоступна для приватних торрентів.",+ "preview": {+ "title": "Оновити трекери завдання",+ "description": "Перевірте зміни додаткових трекерів. Адреси торента та додані вручну зберігаються.",+ "reconnect": "Завдання ненадовго призупиниться, підключиться знову й автоматично продовжиться.",+ "added": "Додати: {{count}}",+ "removed": "Видалити: {{count}}",+ "retained": "Зберігаються додаткові трекери: {{count}}. Початкові групи announce не змінюються.",+ "excluded": "Видалені вами трекери ({{count}}) не додаватимуться під час автоматичного оновлення.",+ "apply": "Застосувати оновлення",+ "changesPending": "Очікувані зміни: {{count}}"+ }}},"media": {@@ -2813,7 +2824,7 @@"disabled": "Вимкнено — увімкніть, щоб переглянути діючий список трекерів.","empty": "Діючих трекерів ще немає. Запустіть синхронізацію, щоб заповнити список.","enabled": "Додавати відібрані трекери",- "enabledDesc": "Додавати відібраний список трекерів до всіх завдань BitTorrent."+ "enabledDesc": "Додавати вибрані трекери до нових публічних завдань BitTorrent."},"sync": {"applying": "Застосування списків трекерів…",@@ -2821,7 +2832,57 @@"fetching": "Отримання списків трекерів…","probing": "Перевірка доступності трекерів…","syncing": "Синхронізація…",- "unavailable": "Не вдалося прочитати стан синхронізації. Перевірте з'єднання та спробуйте ще раз."+ "unavailable": "Не вдалося прочитати стан синхронізації. Перевірте з'єднання та спробуйте ще раз.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"tray": {diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.jsonindex bd014db2..67420307 100644--- a/src/shared/locales/vi.json+++ b/src/shared/locales/vi.json@@ -806,7 +806,18 @@"deleteFailed": "Không thể xóa máy chủ theo dõi: {{reason}}","invalidLines_other": "Đã bỏ qua {{count}} dòng không hợp lệ","editPlaceholder": "Mỗi dòng một URL máy chủ theo dõi. Chỉ hỗ trợ http(s)/udp/ws(s).",- "editHint": "Các máy chủ này thay thế danh sách bt-tracker đang áp dụng cho tác vụ. Các mục announce-list trong tệp .torrent không bị ảnh hưởng."+ "editHint": "Các máy chủ này thay thế danh sách bt-tracker đang áp dụng cho tác vụ. Các mục announce-list trong tệp .torrent không bị ảnh hưởng.",+ "preview": {+ "title": "Cập nhật tracker của tác vụ",+ "description": "Xem lại thay đổi của tracker bổ sung. Địa chỉ có sẵn trong torrent và địa chỉ thêm thủ công được giữ lại.",+ "reconnect": "Tác vụ sẽ tạm dừng trong giây lát, kết nối lại rồi tự động tiếp tục.",+ "added": "Thêm: {{count}}",+ "removed": "Xóa: {{count}}",+ "retained": "Giữ {{count}} tracker bổ sung hiện có. Các nhóm announce gốc không thay đổi.",+ "excluded": "{{count}} tracker bạn đã xóa sẽ không được thêm lại khi cập nhật tự động.",+ "apply": "Áp dụng cập nhật",+ "changesPending": "Thay đổi đang chờ: {{count}}"+ }},"multi": {"totals": "Tổng cộng",@@ -2140,7 +2151,7 @@"trackers": {"effective": {"enabled": "Bổ sung máy chủ theo dõi được tuyển chọn",- "enabledDesc": "Thêm danh sách máy chủ theo dõi được tuyển chọn vào tất cả tác vụ BitTorrent.",+ "enabledDesc": "Thêm tracker được chọn vào tác vụ BitTorrent công khai mới.","disabled": "Đã tắt — bật để xem danh sách máy chủ theo dõi đang áp dụng.","empty": "Chưa có máy chủ theo dõi đang áp dụng. Hãy đồng bộ để tạo danh sách.","column": {@@ -2178,7 +2189,57 @@"probing": "Đang kiểm tra khả năng kết nối máy chủ theo dõi…","applying": "Đang áp dụng danh sách máy chủ theo dõi…","failed": "Đồng bộ chưa hoàn tất. Hãy kiểm tra mạng hoặc các nguồn rồi thử lại.",- "unavailable": "Không thể đọc trạng thái đồng bộ. Hãy kiểm tra kết nối rồi thử lại."+ "unavailable": "Không thể đọc trạng thái đồng bộ. Hãy kiểm tra kết nối rồi thử lại.",+ "details": {+ "title": "Update details",+ "scope": "These defaults supplement new public BitTorrent tasks. Existing downloads keep their current trackers.",+ "sources": "Source status",+ "candidates": "Candidates",+ "history": "Update history",+ "disabled": "Disabled",+ "noSources": "No enabled sources",+ "attention": "{{count}} trackers · {{failed}} sources need attention",+ "summary": "{{count}} trackers · Last successful update: {{time}}",+ "lastAttempt": "Last check",+ "nextCheck": "Next check",+ "autoOff": "Automatic updates off",+ "enginePending": "Saved; waiting to apply defaults to the download engine.",+ "sourceResult": "{{count}} addresses · Last success: {{time}}",+ "retryAt": "Next retry: {{time}}",+ "evidence": "Connection checks are evidence of reachability, not a guarantee of peers or download speed.",+ "firstSeen": "First seen: {{time}}",+ "noCandidates": "No matching candidates",+ "showMore": "Show more",+ "run": "{{success}} sources succeeded · {{failed}} failed · +{{added}} / −{{removed}} selected",+ "noHistory": "No update history",+ "retry": "Retry failed sources",+ "state": {+ "fresh": "Up to date",+ "cached": "Using last successful cache",+ "expired": "Cache expired",+ "pending": "Not checked yet",+ "failed": "No usable cache"+ },+ "failure": {+ "network": "Connection failed. The previous cache is retained for up to 7 days.",+ "http": "The source returned an HTTP error.",+ "invalid": "The response is not a valid tracker list.",+ "limit": "The source exceeded the size or address limit.",+ "missing-cache": "The source returned 304 without a usable cache."+ },+ "reason": {+ "selected": "Selected",+ "capacity": "Reserve",+ "blacklisted": "Blacklisted",+ "unsupported": "Unsupported protocol",+ "cooldown": "Repeated connection failures"+ },+ "outcome": {+ "success": "Completed",+ "partial": "Partially completed",+ "failed": "Failed"+ }+ }}},"plugins": {diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex d7a22a91..6b7504ab 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -830,7 +830,18 @@"deleteFailed": "删除 tracker 失败:{{reason}}","invalidLines_other": "已跳过 {{count}} 行非法输入","editPlaceholder": "一行一个 URL。仅支持 http(s)/udp/ws(s)。",- "editHint": "保存后将整体覆盖任务的 effective bt-tracker;torrent 自带的 announce-list 不受影响。"+ "editHint": "保存后将整体覆盖任务的 effective bt-tracker;torrent 自带的 announce-list 不受影响。",+ "preview": {+ "title": "更新任务 Trackers",+ "description": "确认补充 Tracker 的变更。种子自带和手动添加的地址会保留。",+ "reconnect": "此任务将短暂暂停并重新连接,随后自动恢复。",+ "added": "新增 {{count}} 个",+ "removed": "移除 {{count}} 个",+ "retained": "保留 {{count}} 个现有补充 Tracker,种子自带的 announce 分组保持不变。",+ "excluded": "你已移除的 {{count}} 个 Tracker 不会被自动重新加入。",+ "apply": "应用更新",+ "changesPending": "待更新 {{count}} 项"+ }}},"action": {@@ -2140,7 +2151,7 @@"trackers": {"effective": {"enabled": "注入精选 Tracker",- "enabledDesc": "将精选 Tracker 列表追加到所有 BT 任务。",+ "enabledDesc": "为新建的公共 BT 任务补充精选 Tracker。","disabled": "已禁用 — 开启后可查看生效的 Tracker 列表。","empty": "暂无生效的 Tracker,运行同步以填充。","column": {@@ -2178,7 +2189,57 @@"probing": "正在检测 Tracker 可用性…","applying": "正在应用 Tracker 列表…","failed": "同步未完成,请检查网络或来源后重试。",- "unavailable": "无法获取同步状态,请检查连接后重试。"+ "unavailable": "无法获取同步状态,请检查连接后重试。",+ "details": {+ "title": "更新详情",+ "scope": "此列表用于补充新建的公共 BT 任务,已有下载保持当前 Tracker。",+ "sources": "来源状态",+ "candidates": "候选列表",+ "history": "更新记录",+ "disabled": "已关闭",+ "noSources": "没有启用的来源",+ "attention": "{{count}} 个 Tracker · {{failed}} 个来源需关注",+ "summary": "{{count}} 个 Tracker · 最近成功:{{time}}",+ "lastAttempt": "最近检查",+ "nextCheck": "下次检查",+ "autoOff": "自动更新已关闭",+ "enginePending": "已保存,等待应用到下载引擎。",+ "sourceResult": "{{count}} 个地址 · 最近成功:{{time}}",+ "retryAt": "下次重试:{{time}}",+ "evidence": "连接检查仅提供可达性参考,不代表一定能找到节点或获得下载速度。",+ "firstSeen": "首次发现:{{time}}",+ "noCandidates": "没有匹配的候选地址",+ "showMore": "显示更多",+ "run": "{{success}} 个来源成功 · {{failed}} 个失败 · 入选 +{{added}} / −{{removed}}",+ "noHistory": "暂无更新记录",+ "retry": "重试失败来源",+ "state": {+ "fresh": "已更新",+ "cached": "使用上次成功缓存",+ "expired": "缓存已过期",+ "pending": "尚未检查",+ "failed": "无可用缓存"+ },+ "failure": {+ "network": "连接失败,保留上次成功缓存,最长 7 天。",+ "http": "来源返回 HTTP 错误。",+ "invalid": "响应不是有效的 Tracker 列表。",+ "limit": "来源超过大小或地址数量限制。",+ "missing-cache": "来源返回 304,但没有可用缓存。"+ },+ "reason": {+ "selected": "已入选",+ "capacity": "候补",+ "blacklisted": "黑名单排除",+ "unsupported": "不支持的协议",+ "cooldown": "连续连接失败"+ },+ "outcome": {+ "success": "已完成",+ "partial": "部分完成",+ "failed": "失败"+ }+ }}},"plugins": {diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex aad8b16e..03a1de93 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -806,7 +806,18 @@"deleteFailed": "無法移除 Tracker: {{reason}}","invalidLines_other": "已略過 {{count}} 行無效內容","editPlaceholder": "每行一個 Tracker URL,只支援 http(s)/udp/ws(s)。",- "editHint": "這些 Tracker 會取代任務有效的 bt-tracker 清單,不影響 .torrent 中 announce-list 的項目。"+ "editHint": "這些 Tracker 會取代任務有效的 bt-tracker 清單,不影響 .torrent 中 announce-list 的項目。",+ "preview": {+ "title": "更新任務 Trackers",+ "description": "確認補充 Tracker 的變更。種子自帶和手動新增的位址會保留。",+ "reconnect": "此任務將短暫暫停並重新連線,隨後自動恢復。",+ "added": "新增 {{count}} 個",+ "removed": "移除 {{count}} 個",+ "retained": "保留 {{count}} 個現有補充 Tracker,種子自帶的 announce 分組保持不變。",+ "excluded": "你已移除的 {{count}} 個 Tracker 不會被自動重新加入。",+ "apply": "套用更新",+ "changesPending": "待更新 {{count}} 項"+ }},"multi": {"totals": "總計",@@ -2140,7 +2151,7 @@"trackers": {"effective": {"enabled": "插入精選 Tracker",- "enabledDesc": "將精選 Tracker 清單附加到所有 BitTorrent 任務。",+ "enabledDesc": "為新建的公開 BT 任務補充精選 Tracker。","disabled": "已停用,請開啟以檢視有效的 Tracker 清單。","empty": "尚無有效的 Tracker。請執行同步來填入。","column": {@@ -2178,7 +2189,57 @@"probing": "正在檢測 Tracker 可用性…","applying": "正在套用 Tracker 清單…","failed": "同步未完成,請檢查網路或來源後重試。",- "unavailable": "無法取得同步狀態,請檢查連線後重試。"+ "unavailable": "無法取得同步狀態,請檢查連線後重試。",+ "details": {+ "title": "更新詳細資訊",+ "scope": "此清單用於補充新建的公開 BT 任務,現有下載保留目前的 Tracker。",+ "sources": "來源狀態",+ "candidates": "候選清單",+ "history": "更新記錄",+ "disabled": "已關閉",+ "noSources": "沒有啟用的來源",+ "attention": "{{count}} 個 Tracker · {{failed}} 個來源需要注意",+ "summary": "{{count}} 個 Tracker · 最近成功:{{time}}",+ "lastAttempt": "最近檢查",+ "nextCheck": "下次檢查",+ "autoOff": "自動更新已關閉",+ "enginePending": "已儲存,等待套用至下載引擎。",+ "sourceResult": "{{count}} 個位址 · 最近成功:{{time}}",+ "retryAt": "下次重試:{{time}}",+ "evidence": "連線檢查僅提供可達性參考,不代表一定能找到節點或取得下載速度。",+ "firstSeen": "首次發現:{{time}}",+ "noCandidates": "沒有符合的候選位址",+ "showMore": "顯示更多",+ "run": "{{success}} 個來源成功 · {{failed}} 個失敗 · 入選 +{{added}} / −{{removed}}",+ "noHistory": "尚無更新記錄",+ "retry": "重試失敗來源",+ "state": {+ "fresh": "已更新",+ "cached": "使用上次成功快取",+ "expired": "快取已過期",+ "pending": "尚未檢查",+ "failed": "無可用快取"+ },+ "failure": {+ "network": "連線失敗,保留上次成功快取,最長 7 天。",+ "http": "來源傳回 HTTP 錯誤。",+ "invalid": "回應不是有效的 Tracker 清單。",+ "limit": "來源超過大小或位址數量限制。",+ "missing-cache": "來源傳回 304,但沒有可用快取。"+ },+ "reason": {+ "selected": "已入選",+ "capacity": "候補",+ "blacklisted": "黑名單排除",+ "unsupported": "不支援的協定",+ "cooldown": "連續連線失敗"+ },+ "outcome": {+ "success": "已完成",+ "partial": "部分完成",+ "failed": "失敗"+ }+ }}},"plugin": {diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.tsindex 0130b83e..d2342e48 100644--- a/src/shared/protocol/commands.ts+++ b/src/shared/protocol/commands.ts@@ -80,8 +80,10 @@ export const Commands = {CheckForUpdates: 'command:checkForUpdates',DownloadUpdate: 'command:downloadUpdate',InstallUpdate: 'command:installUpdate',+ ApplyTaskTrackerPlan: 'command:applyTaskTrackerPlan',// TrackerSyncTrackers: 'command:syncTrackers',+ RetryTrackerSources: 'command:retryTrackerSources',SyncTaskBtTracker: 'command:syncTaskBtTracker',SetTaskBtTracker: 'command:setTaskBtTracker',// Windowdiff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.tsindex cb3625fc..2007cd70 100644--- a/src/shared/protocol/queries.ts+++ b/src/shared/protocol/queries.ts@@ -53,6 +53,7 @@ export const Queries = {GetNatDiagnostic: 'query:getNatDiagnostic',// TuningGetTuningRecommendation: 'query:getTuningRecommendation',+ GetTaskTrackerPlan: 'query:getTaskTrackerPlan',// TrackerGetTrackerList: 'query:getTrackerList',GetTrackerSyncStatus: 'query:getTrackerSyncStatus',diff --git a/src/shared/schemas/task-tracker.ts b/src/shared/schemas/task-tracker.tsnew file mode 100644index 00000000..5e8c62c0--- /dev/null+++ b/src/shared/schemas/task-tracker.ts@@ -0,0 +1,52 @@+import { z } from 'zod'++const urls = z.array(z.string().min(1).max(8192)).max(10000)+export const taskTrackerOwnershipSchema = z.object({+ engineGid: z.string().min(1),+ revision: z.number().int().nonnegative(),+ original: urls,+ manual: urls,+ managed: urls,+ excluded: urls,+ isPrivate: z.boolean().nullable(),+})+export const taskTrackerStateSchema = taskTrackerOwnershipSchema.extend({+ lastError: z+ .object({+ phase: z.enum(['pause', 'write', 'resume', 'recovery']),+ at: z.number().finite().nonnegative(),+ })+ .optional(),+ pending: z+ .object({+ before: urls,+ after: urls,+ next: taskTrackerOwnershipSchema,+ resumeRequired: z.boolean(),+ })+ .nullable()+ .default(null),+})+export const taskTrackerRequestSchema = z.object({+ taskId: z.string().min(1),+ engineGid: z.string().min(1),+})+export const taskTrackerApplySchema = taskTrackerRequestSchema.extend({+ fingerprint: z.string().regex(/^[a-f0-9]{64}$/),+})+export const taskTrackerEditSchema = taskTrackerRequestSchema.extend({+ trackers: urls,+})+export const taskTrackerPlanSchema = taskTrackerRequestSchema.extend({+ fingerprint: z.string(),+ added: urls,+ removed: urls,+ retained: urls,+ original: urls,+ excluded: urls,+ requiresPause: z.boolean(),+ protected: z.boolean(),+})+export type TaskTrackerOwnership = z.infer<typeof taskTrackerOwnershipSchema>+export type TaskTrackerState = z.infer<typeof taskTrackerStateSchema>+export type TaskTrackerPlan = z.infer<typeof taskTrackerPlanSchema>diff --git a/src/shared/schemas/tracker-state.ts b/src/shared/schemas/tracker-state.tsnew file mode 100644index 00000000..6867df11--- /dev/null+++ b/src/shared/schemas/tracker-state.ts@@ -0,0 +1,91 @@+import { z } from 'zod'++export const TRACKER_SOURCE_MAX_AGE_MS = 7 * 86_400_000+export const TRACKER_HEALTH_MAX_AGE_MS = 7 * 86_400_000+export const TRACKER_PROBE_FRESH_MS = 12 * 3_600_000+export const TRACKER_HISTORY_MAX_AGE_MS = 30 * 86_400_000+export const TRACKER_MAX_CANDIDATES = 10_000+export const TRACKER_MAX_SOURCE_URLS = 5_000+export const TRACKER_MAX_SOURCE_BYTES = 2 * 1024 * 1024++const time = z.number().finite().nonnegative()+export const trackerSampleSchema = z.object({+ at: time,+ ok: z.boolean(),+})+export const trackerHealthSchema = z.object({+ url: z.string(),+ protocol: z.enum(['http', 'https', 'udp', 'ws', 'wss']),+ status: z.enum(['healthy', 'slow', 'unreachable', 'unknown']),+ lastProbeMs: z.number().nonnegative().nullable(),+ lastProbeAt: time.nullable(),+ successCount: z.number().nonnegative(),+ failCount: z.number().nonnegative(),+ successRate: z.number().min(0).max(1),+ samples: z.array(trackerSampleSchema).max(20).optional(),+ routeKey: z.string().optional(),+ evidence: z.enum(['http', 'udp', 'none']).optional(),+})+export const trackerSourceSnapshotSchema = z.object({+ id: z.string(),+ url: z.string(),+ kind: z.enum(['tracker', 'blacklist']),+ urls: z.array(z.string()).max(TRACKER_MAX_SOURCE_URLS),+ lastAttemptAt: time.nullable(),+ lastSuccessAt: time.nullable(),+ contentChangedAt: time.nullable(),+ etag: z.string().optional(),+ lastModified: z.string().optional(),+ error: z+ .enum(['network', 'http', 'invalid', 'limit', 'missing-cache'])+ .nullable(),+ failures: z.number().int().nonnegative(),+ nextRetryAt: time.nullable(),+})+export const trackerCandidateSchema = z.object({+ url: z.string(),+ sourceIds: z.array(z.string()),+ firstSeenAt: time,+ reason: z.enum([+ 'selected',+ 'capacity',+ 'blacklisted',+ 'unsupported',+ 'cooldown',+ ]),+})+export const trackerSyncRunSchema = z.object({+ id: z.string(),+ trigger: z.enum(['manual', 'scheduled', 'retry']),+ startedAt: time,+ finishedAt: time,+ outcome: z.enum(['success', 'partial', 'failed']),+ successfulSources: z.number().int().nonnegative(),+ failedSources: z.number().int().nonnegative(),+ added: z.number().int().nonnegative(),+ removed: z.number().int().nonnegative(),+ selected: z.number().int().nonnegative(),+})+export const trackerStateSchema = z.object({+ version: z.literal(2).optional(),+ effective: z.array(z.string()).default([]),+ blacklist: z.array(z.string()).default([]),+ healthMap: z.record(z.string(), trackerHealthSchema).default({}),+ sourceMap: z.record(z.string(), z.array(z.string())).default({}),+ lastSyncAt: time.nullable().default(null),+ lastProbeAt: time.nullable().default(null),+ snapshots: z.record(z.string(), trackerSourceSnapshotSchema).default({}),+ candidates: z.array(trackerCandidateSchema).default([]),+ firstSeen: z.record(z.string(), time).default({}),+ history: z.array(trackerSyncRunSchema).max(100).default([]),+ lastAttemptAt: time.nullable().default(null),+ nextCheckAt: time.nullable().default(null),+ revision: z.number().int().nonnegative().default(0),+ pendingEngineApply: z.boolean().default(false),+})+export type TrackerSourceSnapshot = z.infer<typeof trackerSourceSnapshotSchema>+export type TrackerCandidate = z.infer<typeof trackerCandidateSchema>+export type TrackerSyncRun = z.infer<typeof trackerSyncRunSchema>+export type TrackerState = z.infer<typeof trackerStateSchema>++export type TrackerHealth = z.infer<typeof trackerHealthSchema>diff --git a/src/shared/types/tracker.ts b/src/shared/types/tracker.tsindex 566bc7fa..80e0e066 100644--- a/src/shared/types/tracker.ts+++ b/src/shared/types/tracker.ts@@ -1,15 +1,11 @@+import type {+ TrackerHealth as StoredTrackerHealth,+ TrackerState,+} from '../schemas/tracker-state'+export type TrackerProtocol = 'http' | 'https' | 'udp' | 'ws' | 'wss'-export interface TrackerHealth {- url: string- protocol: TrackerProtocol- status: 'healthy' | 'slow' | 'unreachable' | 'unknown'- lastProbeMs: number | null- lastProbeAt: number | null- successCount: number- failCount: number- successRate: number-}+export type TrackerHealth = StoredTrackerHealthexport interface TrackerSource {id: string@@ -20,14 +16,15 @@ export interface TrackerSource {cdn: boolean}-export interface CuratedTrackerList {- effective: string[]- blacklist: string[]- healthMap: Record<string, TrackerHealth>- sourceMap: Record<string, string[]>- lastSyncAt: number | null- lastProbeAt: number | null-}+type LegacyTrackerKeys =+ | 'effective'+ | 'blacklist'+ | 'healthMap'+ | 'sourceMap'+ | 'lastSyncAt'+ | 'lastProbeAt'+export type CuratedTrackerList = Pick<TrackerState, LegacyTrackerKeys> &+ Partial<Omit<TrackerState, LegacyTrackerKeys>>export interface SyncResult {trackers: string[]@@ -40,6 +37,11 @@ export interface SourceFetchStatus {elapsedMs: numbererror?: stringurls?: string[]+ notModified?: boolean+ etag?: string+ lastModified?: string+ retryAfterMs?: number+ failure?: 'network' | 'http' | 'invalid' | 'limit' | 'missing-cache'}export interface ProxyConfig {