From d2011676c0120d85d48aa897a062b96f4c3f5bb7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:29:35 +0000 Subject: [PATCH 01/37] fix(table): give the table view a single scrollport so virtualization works The virtualizer's scroll element had no height constraint, so it grew to content height, the WindowShell wrapper scrolled instead, TanStack Virtual saw a viewport equal to the full list and rendered every row (re-rendered each 1Hz tick), and the sticky header stuck to the wrong scrollport. Constrain TorrentTable's scroll container with h-full (mirroring CardList) and make the WindowShell wrapper overflow-hidden for the table view so exactly one scrollport exists. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- frontend/src/components/list/TorrentTable.tsx | 7 ++++++- frontend/src/components/shell/WindowShell.tsx | 10 +++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/frontend/src/components/list/TorrentTable.tsx b/frontend/src/components/list/TorrentTable.tsx index 3ed2870..d4febba 100644 --- a/frontend/src/components/list/TorrentTable.tsx +++ b/frontend/src/components/list/TorrentTable.tsx @@ -93,7 +93,12 @@ export function TorrentTable(props: Props) { }); return ( -
+ // h-full constrains this element to the pane so IT is the scrollport + // (mirroring CardList). Without the height cap the div grows to content + // height, the ancestor scrolls instead, the virtualizer sees a viewport + // equal to the full list and renders every row, and the sticky header + // sticks to the wrong scroll container. +
diff --git a/frontend/src/components/shell/WindowShell.tsx b/frontend/src/components/shell/WindowShell.tsx index 39ec694..4bb3475 100644 --- a/frontend/src/components/shell/WindowShell.tsx +++ b/frontend/src/components/shell/WindowShell.tsx @@ -180,7 +180,15 @@ export function WindowShell(props: Props) { onToggleAltSpeed={props.onToggleAltSpeed} /> -
+ {/* The table view owns its scrollport (TorrentTable's + h-full overflow-auto container, which its row + virtualizer and sticky header measure against), so + this wrapper must NOT scroll there — two nested + scrollports would defeat the virtualization. The + cards view (CardList) also scrolls itself; keep + overflow-auto here only as the fallback for the + non-virtualized empty state. */} +
{props.children}
From 15cc83c9125c8142639f196c6825259ddf52448a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:29:35 +0000 Subject: [PATCH 02/37] fix(inspector): stop re-fetching rate limits every tick, guard stale responses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Overview effect tracked props.detail, which is replaced wholesale every ~1Hz inspector tick — one getTorrentRateLimits request per second while the default tab was open. Key the effect on the torrent id via createEffect(on) and discard responses whose id no longer matches, so a slow reply for torrent A can't populate B's rate-limit inputs. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- .../src/components/inspector/OverviewTab.tsx | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/frontend/src/components/inspector/OverviewTab.tsx b/frontend/src/components/inspector/OverviewTab.tsx index cdbb3aa..ccf95f8 100644 --- a/frontend/src/components/inspector/OverviewTab.tsx +++ b/frontend/src/components/inspector/OverviewTab.tsx @@ -1,4 +1,4 @@ -import {createEffect, createSignal, Show} from 'solid-js'; +import {createEffect, createSignal, on, Show} from 'solid-js'; import {Copy} from 'lucide-solid'; import {toast} from 'solid-sonner'; import type {DetailDTO, SeedPolicyDTO} from '../../lib/bindings'; @@ -216,15 +216,19 @@ export function OverviewTab(props: Props) { const [downKbps, setDownKbps] = createSignal(0); const [upKbps, setUpKbps] = createSignal(0); - createEffect(() => { - const d = props.detail; - if (!d) return; - const id = d.id; + // Keyed on the torrent id only — props.detail is replaced wholesale every + // inspector tick (~1Hz), so tracking it directly re-fetched the rate + // limits once per second for as long as the tab was open. Responses that + // arrive after the user switched torrents are discarded so a slow reply + // for torrent A can't populate B's inputs. + createEffect(on(() => props.detail?.id, (id) => { + if (!id) return; api.getTorrentRateLimits(id).then((limits) => { + if (props.detail?.id !== id) return; // stale — torrent changed mid-flight setDownKbps(limits.down_kbps); setUpKbps(limits.up_kbps); }).catch(() => {}); - }); + })); const saveDown = async (kbps: number) => { const id = props.detail?.id; From c8050d7f44a6e47aeff2727c3ad1fdcf387924f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:29:35 +0000 Subject: [PATCH 03/37] fix(transport): add missing AddTracker/RemoveTracker HTTP routes The browser transport had no routes for AddTracker/RemoveTracker, so the trackers tab silently failed outside Wails even though the backend endpoints (POST/DELETE /api/torrents/{id}/trackers, JSON {url}) exist. Also surface remove-tracker failures with an error toast instead of swallowing them. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- frontend/src/components/inspector/TrackersTab.tsx | 7 ++++--- frontend/src/lib/http_transport.ts | 12 ++++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/frontend/src/components/inspector/TrackersTab.tsx b/frontend/src/components/inspector/TrackersTab.tsx index 3401dde..a8aeb16 100644 --- a/frontend/src/components/inspector/TrackersTab.tsx +++ b/frontend/src/components/inspector/TrackersTab.tsx @@ -1,8 +1,10 @@ import {createSignal, Index, Show} from 'solid-js'; import {Trash2} from 'lucide-solid'; +import {toast} from 'solid-sonner'; import type {DetailDTO} from '../../lib/bindings'; import {api} from '../../lib/bindings'; import {fmtTimestamp} from '../../lib/format'; +import {userErr} from '../../lib/errors'; type Props = {detail: DetailDTO | null}; @@ -36,9 +38,8 @@ export function TrackersTab(props: Props) { if (!props.detail?.id) return; try { await api.removeTracker(props.detail.id, url); - } catch { - // silently ignore — the tracker will reappear on the next tick if it - // wasn't actually removed + } catch (err) { + toast.error(`Couldn't remove tracker — ${userErr(err)}`); } } diff --git a/frontend/src/lib/http_transport.ts b/frontend/src/lib/http_transport.ts index 88ab743..93c78b6 100644 --- a/frontend/src/lib/http_transport.ts +++ b/frontend/src/lib/http_transport.ts @@ -125,6 +125,18 @@ const ROUTES: Record = { body: ([infohash, enabled]) => ({infohash, enabled}), unwrap: okEnvelope, }, + AddTracker: { + method: 'POST', + path: ([id]) => `/api/torrents/${encodeURIComponent(id)}/trackers`, + body: ([, url]) => ({url}), + unwrap: okEnvelope, + }, + RemoveTracker: { + method: 'DELETE', + path: ([id]) => `/api/torrents/${encodeURIComponent(id)}/trackers`, + body: ([, url]) => ({url}), + unwrap: okEnvelope, + }, // Stats / inspector GlobalStats: {method: 'GET', path: () => '/api/stats'}, From f083e0740484923c1a6892e2d0f985839694ce31 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:29:36 +0000 Subject: [PATCH 04/37] fix(rss): stop validating filter regexes with the JS engine MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Filters run on Go's RE2 engine, but the form validated with new RegExp — the app's own suggested syntax (?i)ubuntu.*amd64 throws in JS and permanently disabled Save. Only require a non-empty regex client-side; create/update errors from the backend already surface via the submit handlers' toast. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- frontend/src/components/settings/RSSPane.tsx | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/frontend/src/components/settings/RSSPane.tsx b/frontend/src/components/settings/RSSPane.tsx index 6a9c6fc..960824e 100644 --- a/frontend/src/components/settings/RSSPane.tsx +++ b/frontend/src/components/settings/RSSPane.tsx @@ -476,18 +476,18 @@ function FilterForm(props: { const [savePath, setSavePath] = createSignal(props.initial.save_path); const [enabled, setEnabled] = createSignal(props.initial.enabled); + // Only require a non-empty regex client-side. Filters run on Go's RE2 + // engine, whose syntax differs from JS RegExp — validating with + // `new RegExp` here rejected valid RE2 patterns like the suggested + // `(?i)ubuntu.*amd64` and permanently disabled Save. Syntax errors are + // the backend's call; create/update failures surface via the submit + // handlers' toast. const regexEmpty = () => regex().trim() === ''; - const regexValid = () => { - const r = regex().trim(); - if (!r) return false; - try { new RegExp(r); return true; } catch { return false; } - }; // Surfaces *why* Save is disabled. Plain "disabled button" gave no // signal — users (correctly) couldn't tell whether the regex, the // category dropdown, or something else was blocking submit. const disabledReason = () => { if (regexEmpty()) return 'Enter a regex to enable Save.'; - if (!regexValid()) return 'Regex is invalid — fix the syntax to enable Save.'; return null; }; @@ -496,7 +496,7 @@ function FilterForm(props: { class="flex flex-col gap-2 rounded-md border border-white/[.06] bg-white/[.02] p-2 my-1" onSubmit={async (e) => { e.preventDefault(); - if (!regexValid()) return; + if (regexEmpty()) return; await props.onSubmit({ id: props.initial.id, feed_id: props.initial.feed_id, @@ -513,7 +513,6 @@ function FilterForm(props: { setRegex(e.currentTarget.value)} autofocus @@ -563,7 +562,7 @@ function FilterForm(props: { Cancel - From 87e3394eef2e5118fc545e27ff6918de5af60ee9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:29:36 +0000 Subject: [PATCH 05/37] fix(selection): range-select over the visible list, confirm bulk keyboard delete MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit extendSelectTo ranged over the raw torrents array (unfiltered, insertion order), so with a filter or sort active a shift-click silently selected hidden torrents — which Delete/Backspace then removed without warning. Row click handlers now pass the filtered+sorted id list they actually render (the table passes its sorted row model, cards the filtered list), and the keyboard delete asks for confirmation before removing more than one torrent, reusing the confirm() pattern of the settings panes' destructive actions. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- frontend/src/App.tsx | 13 +++++++++---- frontend/src/components/list/TorrentList.tsx | 6 ++++-- frontend/src/components/list/TorrentTable.tsx | 6 ++++-- frontend/src/lib/store.ts | 15 +++++++++------ 4 files changed, 26 insertions(+), 14 deletions(-) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index a9d3507..e7f40ca 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -143,9 +143,9 @@ function AuthenticatedApp() { } }; - const handleSelect = (id: string, e: MouseEvent) => { + const handleSelect = (id: string, e: MouseEvent, visibleIds: string[]) => { if (e.metaKey || e.ctrlKey) store.toggleSelect(id); - else if (e.shiftKey) store.extendSelectTo(id); + else if (e.shiftKey) store.extendSelectTo(id, visibleIds); else { store.select(id); store.openInspector(id); @@ -196,10 +196,15 @@ function AuthenticatedApp() { } }); } else if (e.key === 'Delete' || e.key === 'Backspace') { - if (store.state.selection.size === 0) return; + const ids = [...store.state.selection]; + if (ids.length === 0) return; e.preventDefault(); + // Bulk removal is destructive and a stray keystroke away — confirm + // first, matching the confirm() pattern used by the settings panes' + // destructive actions. A single torrent stays one keystroke. + if (ids.length > 1 && !confirm(`Remove ${ids.length} torrents from the list? Downloaded files are kept.`)) return; const failures: string[] = []; - Promise.all([...store.state.selection].map(async (id) => { + Promise.all(ids.map(async (id) => { try { await store.remove(id, false); } catch (err) { failures.push(`${id.slice(0, 8)}: ${String(err)}`); } })).then(() => { diff --git a/frontend/src/components/list/TorrentList.tsx b/frontend/src/components/list/TorrentList.tsx index 0a69c9d..66d3070 100644 --- a/frontend/src/components/list/TorrentList.tsx +++ b/frontend/src/components/list/TorrentList.tsx @@ -14,7 +14,9 @@ type Props = { selection: Set; categories: CategoryDTO[]; tags: TagDTO[]; - onSelect: (id: string, e: MouseEvent) => void; + // visibleIds is the id list in the on-screen (filtered + sorted) order, so + // shift-click range select extends over exactly the rows the user sees. + onSelect: (id: string, e: MouseEvent, visibleIds: string[]) => void; onPause: (id: string) => void; onResume: (id: string) => void; onRecheck: (id: string) => void; @@ -89,7 +91,7 @@ function CardList(props: Props) { props.onSelect(t().id, e)} + onSelect={(e) => props.onSelect(t().id, e, props.torrents.map((x) => x.id))} onPause={() => props.onPause(t().id)} onResume={() => props.onResume(t().id)} onRemove={() => props.onRemove(t().id)} diff --git a/frontend/src/components/list/TorrentTable.tsx b/frontend/src/components/list/TorrentTable.tsx index d4febba..3106ba8 100644 --- a/frontend/src/components/list/TorrentTable.tsx +++ b/frontend/src/components/list/TorrentTable.tsx @@ -9,7 +9,9 @@ import {fmtBytes, fmtETA, fmtPercent, fmtRate} from '../../lib/format'; type Props = { torrents: Torrent[]; selection: Set; - onRowClick: (id: string, e: MouseEvent) => void; + // visibleIds is the id list in the on-screen (sorted) order, so shift-click + // range select can extend over exactly the rows the user sees. + onRowClick: (id: string, e: MouseEvent, visibleIds: string[]) => void; }; // Fixed table row height (px). Rows are single-line with truncation so the @@ -138,7 +140,7 @@ export function TorrentTable(props: Props) {
props.onRowClick(row().original.id, e)} + onClick={(e) => props.onRowClick(row().original.id, e, table.getRowModel().rows.map((r) => r.original.id))} > {(cell) => ( diff --git a/frontend/src/lib/store.ts b/frontend/src/lib/store.ts index 8e3bcee..5fd19aa 100644 --- a/frontend/src/lib/store.ts +++ b/frontend/src/lib/store.ts @@ -376,16 +376,19 @@ export function createTorrentsStore() { if (next.has(id)) next.delete(id); else next.add(id); s.selection = next; })), - extendSelectTo: (id: string) => setState(produce((s) => { - // Range select: from last-selected to id within the current visible list order. - const visible = s.torrents.map((t) => t.id); + // Range select: from last-selected to id. visibleIds is the id list in + // the order the user actually sees (filtered + sorted), passed in by the + // row click handler — ranging over raw s.torrents (unfiltered, insertion + // order) silently swept hidden torrents into the selection whenever a + // filter or sort was active. + extendSelectTo: (id: string, visibleIds: string[]) => setState(produce((s) => { const last = [...s.selection].pop(); if (!last) { s.selection = new Set([id]); return; } - const a = visible.indexOf(last); - const b = visible.indexOf(id); + const a = visibleIds.indexOf(last); + const b = visibleIds.indexOf(id); if (a < 0 || b < 0) { s.selection = new Set([id]); return; } const [lo, hi] = a < b ? [a, b] : [b, a]; - s.selection = new Set(visible.slice(lo, hi + 1)); + s.selection = new Set(visibleIds.slice(lo, hi + 1)); })), selectAll: () => setState(produce((s) => { s.selection = new Set(s.torrents.map((t) => t.id)); })), clearSelection: () => setState(produce((s) => { s.selection = new Set(); })), From d5264c4de5f47583a7057c7850ae807f507e561b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:29:36 +0000 Subject: [PATCH 06/37] fix: assorted minor frontend bugs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - App.tsx onRemove: await store.remove and toast errors instead of firing the success toast early and leaving the rejection unhandled - App.tsx onMoveQueue: only send setQueuePosition for rows whose position actually changed (the backend stores positions verbatim, no reshuffle) - format.ts: floor/carry the minor unit in fmtDuration (no more '1h 60m' / '1d 24h'), clamp fmtPercent below 100 for progress in [0.9995,1), and return an em-dash from fmtBytes/fmtETA on NaN/undefined inputs - store.ts rowToDetail: seed ratio with 0 — bytes_done/total_bytes is progress, not up/down ratio, and flashed wrong in the inspector - AddTorrentModal: key the reset effect on the open transition only, so a late-arriving defaultSavePath no longer wipes in-progress input - ShareTorrentModal: discard refresh() responses that land after the dialog switched to a different torrent https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- frontend/src/App.tsx | 13 +++++++++++-- .../src/components/shell/AddTorrentModal.tsx | 14 +++++++++----- .../src/components/shell/ShareTorrentModal.tsx | 1 + frontend/src/lib/format.test.ts | 8 ++++++++ frontend/src/lib/format.ts | 17 ++++++++++++----- frontend/src/lib/store.ts | 5 ++++- 6 files changed, 45 insertions(+), 13 deletions(-) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index e7f40ca..73289f6 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -129,7 +129,13 @@ function AuthenticatedApp() { const moved = sorted.splice(currentIdx, 1)[0]; sorted.splice(targetIdx, 0, moved); try { - await Promise.all(sorted.map((t, i) => store.setQueuePosition(t.id, i))); + // The backend stores each torrent's position verbatim (no server-side + // reshuffle), so every row whose index changed needs a write — but + // rows already at their position (the common case: all but two for a + // one-step move) don't need to be re-sent. + await Promise.all( + sorted.flatMap((t, i) => (t.queue_position === i ? [] : [store.setQueuePosition(t.id, i)])), + ); } catch (err) { toast.error(`Couldn't reorder — ${userErr(err)}`); } @@ -385,7 +391,10 @@ function AuthenticatedApp() { try { await api.recheck(id); toast.success('Recheck started'); } catch (err) { toast.error(`Recheck failed — ${userErr(err)}`); } }} - onRemove={(id) => { store.remove(id, false); toast.success('Torrent removed'); }} + onRemove={async (id) => { + try { await store.remove(id, false); toast.success('Torrent removed'); } + catch (err) { toast.error(`Couldn't remove — ${userErr(err)}`); } + }} onSetCategory={async (id, categoryID) => { try { await store.setTorrentCategory(id, categoryID); diff --git a/frontend/src/components/shell/AddTorrentModal.tsx b/frontend/src/components/shell/AddTorrentModal.tsx index 86d8325..9264ddc 100644 --- a/frontend/src/components/shell/AddTorrentModal.tsx +++ b/frontend/src/components/shell/AddTorrentModal.tsx @@ -1,7 +1,7 @@ import {Dialog} from '@kobalte/core/dialog'; import {RadioGroup} from '@kobalte/core/radio-group'; import {ChevronDown, FileDown, FolderOpen, Magnet, X} from 'lucide-solid'; -import {createEffect, createSignal, For, Show} from 'solid-js'; +import {createEffect, createSignal, For, on, Show} from 'solid-js'; import {Button} from '../ui/Button'; import type {CategoryDTO, TagDTO} from '../../lib/bindings'; import {isWailsRuntime} from '../../lib/runtime'; @@ -35,9 +35,13 @@ export function AddTorrentModal(props: Props) { const [pickedFile, setPickedFile] = createSignal(null); const isWails = isWailsRuntime(); - // Reset state whenever the modal opens — especially `source` if initialSource changes. - createEffect(() => { - if (props.open) { + // Reset state when the modal opens — especially `source` if initialSource + // changes. Keyed on `open` only via on(): a bare createEffect also tracked + // initialSource and defaultSavePath, so a late-arriving default save path + // (boot fetch resolving after the user opened the modal) wiped whatever + // they had already typed. + createEffect(on(() => props.open, (open) => { + if (open) { setSource(props.initialSource ?? 'magnet'); setMagnet(''); setSavePath(props.defaultSavePath); @@ -46,7 +50,7 @@ export function AddTorrentModal(props: Props) { setError(null); setPickedFile(null); } - }); + })); const toggleTag = (id: number) => { setSelectedTags((prev) => { diff --git a/frontend/src/components/shell/ShareTorrentModal.tsx b/frontend/src/components/shell/ShareTorrentModal.tsx index c32de8d..b73fcd1 100644 --- a/frontend/src/components/shell/ShareTorrentModal.tsx +++ b/frontend/src/components/shell/ShareTorrentModal.tsx @@ -30,6 +30,7 @@ export function ShareTorrentModal(props: Props) { if (!id) return; try { const [u, s] = await Promise.all([api.listUsers(), api.listTorrentShares(id)]); + if (props.torrentID !== id) return; // stale — dialog moved to another torrent mid-flight setUsers(u); setShares(s); } catch (err) { diff --git a/frontend/src/lib/format.test.ts b/frontend/src/lib/format.test.ts index 14b1651..3ae8d00 100644 --- a/frontend/src/lib/format.test.ts +++ b/frontend/src/lib/format.test.ts @@ -6,6 +6,8 @@ describe('fmtBytes', () => { test('kilobytes', () => expect(fmtBytes(1500)).toBe('1.5 KB')); test('megabytes', () => expect(fmtBytes(1_572_864)).toBe('1.5 MB')); test('gigabytes', () => expect(fmtBytes(1_610_612_736)).toBe('1.50 GB')); + test('NaN is em-dash', () => expect(fmtBytes(NaN)).toBe('—')); + test('undefined is em-dash', () => expect(fmtBytes(undefined as unknown as number)).toBe('—')); }); describe('fmtRate', () => { @@ -20,12 +22,15 @@ describe('fmtETA', () => { test('minutes', () => expect(fmtETA(60_000, 100)).toBe('10m')); test('hours', () => expect(fmtETA(3_600_000, 100)).toBe('10h')); test('days', () => expect(fmtETA(86_400_000, 100)).toBe('10d')); + test('NaN remaining is em-dash', () => expect(fmtETA(NaN, 100)).toBe('—')); + test('undefined rate is em-dash', () => expect(fmtETA(1000, undefined as unknown as number)).toBe('—')); }); describe('fmtPercent', () => { test('zero', () => expect(fmtPercent(0)).toBe('0.0%')); test('partial', () => expect(fmtPercent(0.7234)).toBe('72.3%')); test('complete', () => expect(fmtPercent(1)).toBe('100%')); + test('nearly complete never claims 100', () => expect(fmtPercent(0.9999)).toBe('99.9%')); }); describe('fmtDuration', () => { @@ -33,6 +38,9 @@ describe('fmtDuration', () => { test('minutes', () => expect(fmtDuration(125)).toBe('2m')); test('hours+minutes', () => expect(fmtDuration(3725)).toBe('1h 2m')); test('days+hours', () => expect(fmtDuration(90_061)).toBe('1d 1h')); + test('minor unit floors, never "1h 60m"', () => expect(fmtDuration(7199)).toBe('1h 59m')); + test('minor unit floors, never "23h 60m"', () => expect(fmtDuration(86_399)).toBe('23h 59m')); + test('minor unit floors, never "1d 24h"', () => expect(fmtDuration(172_799)).toBe('1d 23h')); }); describe('fmtTimestamp', () => { diff --git a/frontend/src/lib/format.ts b/frontend/src/lib/format.ts index 9968580..2f6c021 100644 --- a/frontend/src/lib/format.ts +++ b/frontend/src/lib/format.ts @@ -1,4 +1,5 @@ export function fmtBytes(n: number): string { + if (!Number.isFinite(n)) return '—'; if (n < 1024) return `${n} B`; if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`; if (n < 1024 * 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MB`; @@ -11,6 +12,7 @@ export function fmtRate(bytesPerSec: number): string { } export function fmtETA(remainingBytes: number, bytesPerSec: number): string { + if (!Number.isFinite(remainingBytes) || !Number.isFinite(bytesPerSec)) return '—'; if (bytesPerSec === 0) return '∞'; const seconds = remainingBytes / bytesPerSec; if (seconds < 60) return `${Math.round(seconds)}s`; @@ -21,19 +23,24 @@ export function fmtETA(remainingBytes: number, bytesPerSec: number): string { export function fmtPercent(progress: number): string { if (progress >= 1) return '100%'; - return `${(progress * 100).toFixed(1)}%`; + // toFixed rounds, so progress in [0.9995, 1) would still render "100.0%" + // despite the guard above — clamp so a not-quite-done torrent never + // claims completion. + return `${Math.min(progress * 100, 99.9).toFixed(1)}%`; } +// Floor (never round) the minor unit: rounding produced impossible +// renderings like "1h 60m" (3599s of remainder) and "1d 24h". export function fmtDuration(seconds: number): string { - if (seconds < 60) return `${Math.round(seconds)}s`; - if (seconds < 3600) return `${Math.round(seconds / 60)}m`; + if (seconds < 60) return `${Math.floor(seconds)}s`; + if (seconds < 3600) return `${Math.floor(seconds / 60)}m`; if (seconds < 86_400) { const h = Math.floor(seconds / 3600); - const m = Math.round((seconds - h * 3600) / 60); + const m = Math.floor((seconds - h * 3600) / 60); return `${h}h ${m}m`; } const d = Math.floor(seconds / 86_400); - const h = Math.round((seconds - d * 86_400) / 3600); + const h = Math.floor((seconds - d * 86_400) / 3600); return `${d}d ${h}h`; } diff --git a/frontend/src/lib/store.ts b/frontend/src/lib/store.ts index 5fd19aa..3cdca1c 100644 --- a/frontend/src/lib/store.ts +++ b/frontend/src/lib/store.ts @@ -107,7 +107,10 @@ function rowToDetail(t: import('./bindings').Torrent): import('./bindings').Deta total_bytes: t.total_bytes, bytes_done: t.bytes_done, progress: t.progress, - ratio: t.bytes_done > 0 ? t.bytes_done / Math.max(1, t.total_bytes) : 0, + // The row carries no up/down counters, so the real ratio is unknown — + // seed 0 and let the tick fill it in. (bytes_done/total_bytes is the + // progress, not the ratio, and flashed a wrong value in the inspector.) + ratio: 0, total_down: 0, // tick will fill in real cumulative counters total_up: 0, peers: t.peers, From 3d3730a59349489caa66b5bc0b7bf4990457d475 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:29:36 +0000 Subject: [PATCH 07/37] fix(transport): cancel ws reconnect timer, bail with no subscribers, back off The reconnect timer was never cancelled and ensureSocket didn't re-check handlers.size, so a timer scheduled before the last unsubscribe could resurrect a socket with zero subscribers and leak it; reconnects also hammered a down server at a fixed 1s forever. Bail out of ensureSocket when no handlers remain, clear the timer when the last handler unsubscribes, and reconnect with capped exponential backoff (1s doubling to 30s, reset on successful open). https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- frontend/src/lib/http_transport.ts | 33 +++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/frontend/src/lib/http_transport.ts b/frontend/src/lib/http_transport.ts index 93c78b6..9985b43 100644 --- a/frontend/src/lib/http_transport.ts +++ b/frontend/src/lib/http_transport.ts @@ -350,17 +350,33 @@ interface FetchOptions { wsCtor?: new (url: string) => WebSocket; } +// WebSocket reconnect backoff bounds: start at 1s, double per failed +// attempt, cap at 30s. +const RECONNECT_BASE_MS = 1000; +const RECONNECT_MAX_MS = 30_000; + export function makeHTTPTransport(origin: string, opts: FetchOptions = {}): Transport { const fetchImpl = opts.fetchImpl ?? (typeof fetch !== 'undefined' ? fetch.bind(globalThis) : undefined); const wsCtor = opts.wsCtor ?? (typeof WebSocket !== 'undefined' ? WebSocket : undefined); const handlers = new Map void>>(); let socket: WebSocket | null = null; + // Pending reconnect timer, cancelled when the last handler unsubscribes — + // otherwise a timer scheduled before the unsubscribe would resurrect a + // socket with zero subscribers and leak it. + let reconnectTimer: ReturnType | null = null; + // Capped exponential backoff so a down server isn't hammered at 1Hz + // forever; reset once a connection opens successfully. + let reconnectDelayMs = RECONNECT_BASE_MS; function ensureSocket() { if (socket || !wsCtor) return; + if (handlers.size === 0) return; // nobody listening — don't (re)connect const wsURL = origin.replace(/^http/, 'ws') + '/api/ws'; socket = new wsCtor(wsURL); + socket.onopen = () => { + reconnectDelayMs = RECONNECT_BASE_MS; + }; socket.onmessage = (ev) => { try { const env = JSON.parse(ev.data); @@ -373,9 +389,10 @@ export function makeHTTPTransport(origin: string, opts: FetchOptions = {}): Tran }; socket.onclose = () => { socket = null; - // Reconnect after a short delay if any handlers are still subscribed. + // Reconnect with backoff if any handlers are still subscribed. if (handlers.size > 0) { - setTimeout(ensureSocket, 1000); + reconnectTimer = setTimeout(ensureSocket, reconnectDelayMs); + reconnectDelayMs = Math.min(reconnectDelayMs * 2, RECONNECT_MAX_MS); } }; socket.onerror = (e) => console.error('ws error', e); @@ -425,9 +442,15 @@ export function makeHTTPTransport(origin: string, opts: FetchOptions = {}): Tran s.delete(handler); if (s.size === 0) handlers.delete(event); } - if (handlers.size === 0 && socket) { - socket.close(); - socket = null; + if (handlers.size === 0) { + if (reconnectTimer !== null) { + clearTimeout(reconnectTimer); + reconnectTimer = null; + } + if (socket) { + socket.close(); + socket = null; + } } }; }, From 164f94b59d602ee7c8c762a630105fd8ee02b40a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:34:18 +0000 Subject: [PATCH 08/37] watchfolder: fix Stop double-close panic and per-poll re-add storm MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Start closed the previous loop's stop channel but left w.stop/w.done pointing at the closed channels when it early-returned (empty path or stat failure), so a later Stop() — or a concurrent Stop() during the unlocked done-wait — closed an already-closed channel and panicked. Both Start and Stop now swap the fields to nil under the lock before closing, so no code path can observe a closed channel. poll() also re-added every .torrent file on every 5-second tick when delete_after_add is off, re-triggering a verify each time. The run loop now keeps a processed map keyed by path with a size+mtime fingerprint: unchanged files are skipped, changed files count as new, and entries for files that disappear are dropped. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/api/watchfolder.go | 54 ++++++++++++++---- backend/api/watchfolder_test.go | 97 +++++++++++++++++++++++++++++++++ 2 files changed, 141 insertions(+), 10 deletions(-) create mode 100644 backend/api/watchfolder_test.go diff --git a/backend/api/watchfolder.go b/backend/api/watchfolder.go index 55866f3..d7a21a2 100644 --- a/backend/api/watchfolder.go +++ b/backend/api/watchfolder.go @@ -2,6 +2,7 @@ package api import ( "context" + "fmt" "os" "path/filepath" "strings" @@ -37,11 +38,16 @@ func (w *WatchFolder) Start(path string, deleteAfterAdd bool) { w.mu.Lock() defer w.mu.Unlock() - // Stop any running loop. + // Stop any running loop. Swap stop/done to nil under the lock BEFORE + // closing, so neither a concurrent Stop() during the unlocked wait below + // nor a later Stop() after one of the early returns can ever observe — + // and re-close — an already-closed channel. if w.stop != nil { - close(w.stop) + stop, done := w.stop, w.done + w.stop, w.done = nil, nil + close(stop) w.mu.Unlock() - <-w.done + <-done w.mu.Lock() } @@ -68,11 +74,12 @@ func (w *WatchFolder) Stop() { w.mu.Unlock() return } - close(w.stop) - done := w.done - w.stop = nil - w.done = nil + // Same swap-before-close discipline as Start: once the fields are nil + // nobody else can reach the closed channel. + stop, done := w.stop, w.done + w.stop, w.done = nil, nil w.mu.Unlock() + close(stop) <-done } @@ -83,8 +90,16 @@ func (w *WatchFolder) run(dir string, deleteAfterAdd bool, stop <-chan struct{}, ctx := WithCaller(context.Background(), SystemCaller) + // processed remembers files already added this session, keyed by path + // with a size+mtime fingerprint as the value. Without it, every poll + // with delete_after_add=false re-adds every file in the folder (and + // re-triggers a verify each time). A changed fingerprint counts as a + // new file; entries for files that disappear are dropped so a later + // re-creation is picked up again. + processed := make(map[string]string) + // Poll immediately on start, then on each 5-second tick. - w.poll(ctx, dir, deleteAfterAdd) + w.poll(ctx, dir, deleteAfterAdd, processed) t := time.NewTicker(5 * time.Second) defer t.Stop() @@ -94,17 +109,18 @@ func (w *WatchFolder) run(dir string, deleteAfterAdd bool, stop <-chan struct{}, log.Info().Str("dir", dir).Msg("watch_folder: stopped") return case <-t.C: - w.poll(ctx, dir, deleteAfterAdd) + w.poll(ctx, dir, deleteAfterAdd, processed) } } } -func (w *WatchFolder) poll(ctx context.Context, dir string, deleteAfterAdd bool) { +func (w *WatchFolder) poll(ctx context.Context, dir string, deleteAfterAdd bool, processed map[string]string) { entries, err := os.ReadDir(dir) if err != nil { log.Warn().Err(err).Str("dir", dir).Msg("watch_folder: ReadDir failed") return } + present := make(map[string]struct{}, len(entries)) for _, e := range entries { if e.IsDir() { continue @@ -113,6 +129,16 @@ func (w *WatchFolder) poll(ctx context.Context, dir string, deleteAfterAdd bool) continue } path := filepath.Join(dir, e.Name()) + info, err := e.Info() + if err != nil { + // File vanished between ReadDir and stat; next poll catches it. + continue + } + present[path] = struct{}{} + fingerprint := fmt.Sprintf("%d|%d", info.Size(), info.ModTime().UnixNano()) + if processed[path] == fingerprint { + continue // already added this exact file + } blob, err := os.ReadFile(path) if err != nil { log.Warn().Err(err).Str("path", path).Msg("watch_folder: read file failed") @@ -123,6 +149,7 @@ func (w *WatchFolder) poll(ctx context.Context, dir string, deleteAfterAdd bool) log.Warn().Err(err).Str("path", path).Msg("watch_folder: AddTorrentBytes failed") continue } + processed[path] = fingerprint log.Info().Str("path", path).Str("id", string(id)).Msg("watch_folder: torrent added") if deleteAfterAdd { if err := os.Remove(path); err != nil { @@ -130,4 +157,11 @@ func (w *WatchFolder) poll(ctx context.Context, dir string, deleteAfterAdd bool) } } } + // Drop processed entries for files that no longer exist so the map can't + // grow unboundedly and a re-created file is treated as new. + for p := range processed { + if _, ok := present[p]; !ok { + delete(processed, p) + } + } } diff --git a/backend/api/watchfolder_test.go b/backend/api/watchfolder_test.go new file mode 100644 index 0000000..8bb9c0f --- /dev/null +++ b/backend/api/watchfolder_test.go @@ -0,0 +1,97 @@ +package api + +import ( + "context" + "os" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "mosaic/backend/engine" +) + +// recordingAdder counts AddTorrentBytes calls so poll-dedup tests can assert +// a file is only added once. Thread-safe; the zero value is ready to use. +type recordingAdder struct { + mu sync.Mutex + calls int +} + +func (r *recordingAdder) AddMagnet(context.Context, string, string) (engine.TorrentID, error) { + return "", nil +} + +func (r *recordingAdder) AddTorrentBytes(context.Context, []byte, string) (engine.TorrentID, error) { + r.mu.Lock() + r.calls++ + r.mu.Unlock() + return "id", nil +} + +func (r *recordingAdder) SetTorrentCategory(context.Context, string, *int) error { return nil } + +func (r *recordingAdder) count() int { + r.mu.Lock() + defer r.mu.Unlock() + return r.calls +} + +// TestWatchFolder_StopAfterEmptyPathRestart pins the double-close fix: a +// Start that stops a running loop and then early-returns (empty path) must +// nil out stop/done, otherwise the following Stop re-closes a closed channel +// and panics. +func TestWatchFolder_StopAfterEmptyPathRestart(t *testing.T) { + w := NewWatchFolder(&recordingAdder{}) + w.Start(t.TempDir(), false) + w.Start("", false) // disable — early return after stopping the loop + w.Stop() // must be a no-op, not a panic +} + +// TestWatchFolder_StopAfterStatFailureRestart is the same as above for the +// "path does not exist" early return. +func TestWatchFolder_StopAfterStatFailureRestart(t *testing.T) { + w := NewWatchFolder(&recordingAdder{}) + w.Start(t.TempDir(), false) + w.Start(filepath.Join(t.TempDir(), "missing"), false) + w.Stop() +} + +// TestWatchFolder_StopTwice ensures Stop stays idempotent. +func TestWatchFolder_StopTwice(t *testing.T) { + w := NewWatchFolder(&recordingAdder{}) + w.Start(t.TempDir(), false) + w.Stop() + w.Stop() +} + +// TestWatchFolder_PollSkipsAlreadyProcessed covers the processed-map dedup: +// with delete_after_add=false the same on-disk file must be added exactly +// once across polls, and a changed file (new size/mtime) must be re-added. +func TestWatchFolder_PollSkipsAlreadyProcessed(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "a.torrent") + require.NoError(t, os.WriteFile(path, []byte("blob"), 0o644)) + + adder := &recordingAdder{} + w := NewWatchFolder(adder) + processed := make(map[string]string) + ctx := context.Background() + + w.poll(ctx, dir, false, processed) + w.poll(ctx, dir, false, processed) + require.Equal(t, 1, adder.count(), "unchanged file must not be re-added") + + // Rewrite with different content + mtime → counts as a new file. + require.NoError(t, os.WriteFile(path, []byte("blob2"), 0o644)) + require.NoError(t, os.Chtimes(path, time.Now().Add(time.Hour), time.Now().Add(time.Hour))) + w.poll(ctx, dir, false, processed) + require.Equal(t, 2, adder.count(), "changed file should be re-added") + + // Delete the file → its processed entry is dropped. + require.NoError(t, os.Remove(path)) + w.poll(ctx, dir, false, processed) + require.Empty(t, processed) +} From 8b932a94e7c0f1edfd0e19355cb19198840a1883 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:34:30 +0000 Subject: [PATCH 09/37] persistence: stop duplicate Save from clobbering user state; add SetPaused/SetCompletedAt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Torrents.Save's ON CONFLICT clause reset added_at, paused, queue_position, force_start, category_id, rate limits, sequential and completed_at on every duplicate add — so an RSS re-match, watch-folder re-scan, or the user re-dropping the same file silently wiped queue order, category, pause state and limits. The upsert now refreshes identity/metadata only (name, magnet when non-empty, metainfo); save_path stays too since the engine keeps using the original storage location for an already-known infohash. The dead seedingStartedAt plumbing in Save is removed — dedicated methods own that column. New DAOs, styled after SetQueuePosition/SetForceStart/SetSequential: - SetPaused: lets the service persist user pause/resume so RestoreOnStartup's paused branch is no longer dead code. - SetCompletedAt: lets the service record first completion so missing-files detection can arm on restore. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/persistence/torrents.go | 49 +++++++++++------ backend/persistence/torrents_test.go | 82 ++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+), 18 deletions(-) diff --git a/backend/persistence/torrents.go b/backend/persistence/torrents.go index 8818bec..6592ece 100644 --- a/backend/persistence/torrents.go +++ b/backend/persistence/torrents.go @@ -64,30 +64,22 @@ func (t *Torrents) Save(ctx context.Context, r TorrentRecord) error { if r.Sequential { sequential = 1 } - var seedingStartedAt sql.NullInt64 - if r.SeedingStartedAt != nil { - seedingStartedAt = sql.NullInt64{Int64: r.SeedingStartedAt.Unix(), Valid: true} - } _, err := t.db.SQL().ExecContext(ctx, ` INSERT INTO torrents (infohash, name, magnet, save_path, category_id, added_at, completed_at, paused, queue_position, force_start, metainfo, down_rate_limit, up_rate_limit, sequential) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(infohash) DO UPDATE SET name = excluded.name, - magnet = excluded.magnet, - save_path = excluded.save_path, - category_id = excluded.category_id, - added_at = excluded.added_at, - completed_at = excluded.completed_at, - paused = excluded.paused, - queue_position = excluded.queue_position, - force_start = excluded.force_start, - metainfo = COALESCE(excluded.metainfo, torrents.metainfo), - down_rate_limit = excluded.down_rate_limit, - up_rate_limit = excluded.up_rate_limit, - sequential = excluded.sequential + magnet = COALESCE(NULLIF(excluded.magnet, ''), torrents.magnet), + metainfo = COALESCE(excluded.metainfo, torrents.metainfo) `, r.InfoHash, r.Name, r.Magnet, r.SavePath, catID, r.AddedAt.Unix(), completed, paused, r.QueuePosition, forceStart, nullableBytes(r.Metainfo), r.DownRateLimit, r.UpRateLimit, sequential) - // seed_policy and seeding_started_at are set by dedicated methods only. - _ = seedingStartedAt + // On duplicate adds (RSS re-match, watch-folder re-scan, user re-dropping + // the same file) only identity/metadata fields are refreshed. User state — + // added_at, paused, queue_position, force_start, category_id, rate limits, + // sequential, completed_at — is owned by the dedicated Set* methods and + // must not be reset by a re-add. save_path stays too: the engine keeps + // using the original storage location for an already-known infohash, so + // persisting a new path would desync DB from disk. seed_policy and + // seeding_started_at are likewise set by dedicated methods only. return err } @@ -174,6 +166,27 @@ func (t *Torrents) SetQueuePosition(ctx context.Context, infohash string, pos in return err } +// SetPaused persists whether a torrent is user-paused, so the state survives +// restarts (RestoreOnStartup re-pauses torrents with paused=1). +func (t *Torrents) SetPaused(ctx context.Context, infohash string, paused bool) error { + v := 0 + if paused { + v = 1 + } + _, err := t.db.SQL().ExecContext(ctx, + `UPDATE torrents SET paused = ? WHERE infohash = ?`, v, infohash) + return err +} + +// SetCompletedAt records when a torrent first finished downloading. Written +// once by the service when it observes the completed transition; never +// cleared. RestoreOnStartup uses it to arm missing-files detection. +func (t *Torrents) SetCompletedAt(ctx context.Context, infohash string, at time.Time) error { + _, err := t.db.SQL().ExecContext(ctx, + `UPDATE torrents SET completed_at = ? WHERE infohash = ?`, at.Unix(), infohash) + return err +} + // SetForceStart toggles whether a torrent bypasses the queue limit. func (t *Torrents) SetForceStart(ctx context.Context, infohash string, force bool) error { v := 0 diff --git a/backend/persistence/torrents_test.go b/backend/persistence/torrents_test.go index bdc106b..ad72b0b 100644 --- a/backend/persistence/torrents_test.go +++ b/backend/persistence/torrents_test.go @@ -83,6 +83,88 @@ func TestTorrents_QueueAndForceStart(t *testing.T) { require.True(t, got.ForceStart) } +func TestTorrents_SetPausedRoundtrip(t *testing.T) { + db := newTestDB(t) + tr := NewTorrents(db) + ctx := context.Background() + require.NoError(t, tr.Save(ctx, TorrentRecord{InfoHash: "p1", Name: "n", SavePath: "/p", AddedAt: time.Now()})) + + got, _ := tr.Get(ctx, "p1") + require.False(t, got.Paused) + + require.NoError(t, tr.SetPaused(ctx, "p1", true)) + got, _ = tr.Get(ctx, "p1") + require.True(t, got.Paused) + + require.NoError(t, tr.SetPaused(ctx, "p1", false)) + got, _ = tr.Get(ctx, "p1") + require.False(t, got.Paused) +} + +func TestTorrents_SetCompletedAt(t *testing.T) { + db := newTestDB(t) + tr := NewTorrents(db) + ctx := context.Background() + require.NoError(t, tr.Save(ctx, TorrentRecord{InfoHash: "c1", Name: "n", SavePath: "/p", AddedAt: time.Now()})) + + got, _ := tr.Get(ctx, "c1") + require.Nil(t, got.CompletedAt) + + at := time.Unix(1700000123, 0) + require.NoError(t, tr.SetCompletedAt(ctx, "c1", at)) + got, _ = tr.Get(ctx, "c1") + require.NotNil(t, got.CompletedAt) + require.Equal(t, at.Unix(), got.CompletedAt.Unix()) +} + +// TestTorrents_SaveDuplicateKeepsUserState pins the non-destructive upsert: +// re-adding an already-known torrent (RSS re-match, watch-folder re-scan) +// must refresh metadata only, never reset user state set via the dedicated +// Set* methods. +func TestTorrents_SaveDuplicateKeepsUserState(t *testing.T) { + db := newTestDB(t) + tr := NewTorrents(db) + cats := NewCategories(db) + ctx := context.Background() + + addedAt := time.Unix(1700000000, 0) + require.NoError(t, tr.Save(ctx, TorrentRecord{ + InfoHash: "d1", Name: "n", Magnet: "magnet:?xt=urn:btih:d1", SavePath: "/p", AddedAt: addedAt, + })) + + catID, _ := cats.Create(ctx, Category{Name: "Movies"}) + completedAt := time.Unix(1700001000, 0) + require.NoError(t, tr.SetPaused(ctx, "d1", true)) + require.NoError(t, tr.SetQueuePosition(ctx, "d1", 3)) + require.NoError(t, tr.SetForceStart(ctx, "d1", true)) + require.NoError(t, tr.SetSequential(ctx, "d1", true)) + require.NoError(t, tr.SetCategory(ctx, "d1", &catID)) + require.NoError(t, tr.SetRateLimits(ctx, "d1", 1000, 2000)) + require.NoError(t, tr.SetCompletedAt(ctx, "d1", completedAt)) + + // Duplicate add: fresh AddedAt, zeroed user state, empty magnet (file add). + require.NoError(t, tr.Save(ctx, TorrentRecord{ + InfoHash: "d1", Name: "renamed", SavePath: "/other", AddedAt: time.Now(), + })) + + got, err := tr.Get(ctx, "d1") + require.NoError(t, err) + require.Equal(t, "renamed", got.Name, "name is metadata and should refresh") + require.Equal(t, "magnet:?xt=urn:btih:d1", got.Magnet, "empty magnet must not wipe the stored one") + require.Equal(t, "/p", got.SavePath, "save_path must not change on re-add") + require.Equal(t, addedAt.Unix(), got.AddedAt.Unix()) + require.True(t, got.Paused) + require.Equal(t, 3, got.QueuePosition) + require.True(t, got.ForceStart) + require.True(t, got.Sequential) + require.NotNil(t, got.CategoryID) + require.Equal(t, catID, *got.CategoryID) + require.Equal(t, int64(1000), got.DownRateLimit) + require.Equal(t, int64(2000), got.UpRateLimit) + require.NotNil(t, got.CompletedAt) + require.Equal(t, completedAt.Unix(), got.CompletedAt.Unix()) +} + func TestTorrents_CategoryAssignment(t *testing.T) { db := newTestDB(t) tor := NewTorrents(db) From 0471009112c22783738e607a027906a768e4ac98 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:34:38 +0000 Subject: [PATCH 10/37] api: persist pause state and completed_at so they survive restarts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pause/Resume/PauseAll/ResumeAll only flipped engine state; the DB paused column was written once at add time (false), so the restore branch reading r.Paused never fired and user-paused torrents resumed silently on the next launch. The four methods now also call Torrents.SetPaused, log-don't-fail on DB errors (engine state is already applied). completed_at was likewise never written, so RestoreOnStartup never armed the engine's missing-files detection and the inspector's completed_at stayed empty. BuildTorrentTickSnapshot — the tick choke point both the desktop stream and mosaicd's streamTicks funnel through — now persists it the first time it observes a torrent complete, gated on the record's CompletedAt being nil so it's written exactly once. detailToDTO surfaces the value as DetailDTO.CompletedAt. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/api/service.go | 68 +++++++++++++++++++++++++++++++------ backend/api/service_test.go | 19 +++++++++++ 2 files changed, 77 insertions(+), 10 deletions(-) diff --git a/backend/api/service.go b/backend/api/service.go index 60aaf3f..201ca2a 100644 --- a/backend/api/service.go +++ b/backend/api/service.go @@ -991,14 +991,29 @@ func (s *Service) Pause(ctx context.Context, id engine.TorrentID) error { if err := s.requireTorrentAccess(ctx, string(id), persistence.AccessEditor); err != nil { return err } - return s.engine.Pause(id) + if err := s.engine.Pause(id); err != nil { + return err + } + // Persist so the pause survives a restart (RestoreOnStartup re-pauses + // from the paused column). Log-don't-fail: the engine state is already + // applied and a DB hiccup shouldn't surface as a failed pause. + if err := s.torrents.SetPaused(ctx, string(id), true); err != nil { + log.Warn().Err(err).Str("id", string(id)).Msg("Pause: persist paused state failed") + } + return nil } func (s *Service) Resume(ctx context.Context, id engine.TorrentID) error { if err := s.requireTorrentAccess(ctx, string(id), persistence.AccessEditor); err != nil { return err } - return s.engine.Resume(id) + if err := s.engine.Resume(id); err != nil { + return err + } + if err := s.torrents.SetPaused(ctx, string(id), false); err != nil { + log.Warn().Err(err).Str("id", string(id)).Msg("Resume: persist paused state failed") + } + return nil } func (s *Service) Recheck(ctx context.Context, id engine.TorrentID) error { @@ -1012,26 +1027,34 @@ func (s *Service) Recheck(ctx context.Context, id engine.TorrentID) error { // individual torrents are logged but don't abort the loop — best-effort // semantics so a single missing/dead torrent can't strand the rest. // Used by the system-tray "Pause all" item. -func (s *Service) PauseAll(_ context.Context) { +func (s *Service) PauseAll(ctx context.Context) { for _, snap := range s.engine.List() { if snap.Paused { continue } if err := s.engine.Pause(snap.ID); err != nil { log.Warn().Err(err).Str("id", string(snap.ID)).Msg("PauseAll: pause failed") + continue + } + if err := s.torrents.SetPaused(ctx, string(snap.ID), true); err != nil { + log.Warn().Err(err).Str("id", string(snap.ID)).Msg("PauseAll: persist paused state failed") } } } // ResumeAll is the mirror of PauseAll. Used by the system-tray "Resume all" // item when the engine is in the globally-paused state. -func (s *Service) ResumeAll(_ context.Context) { +func (s *Service) ResumeAll(ctx context.Context) { for _, snap := range s.engine.List() { if !snap.Paused { continue } if err := s.engine.Resume(snap.ID); err != nil { log.Warn().Err(err).Str("id", string(snap.ID)).Msg("ResumeAll: resume failed") + continue + } + if err := s.torrents.SetPaused(ctx, string(snap.ID), false); err != nil { + log.Warn().Err(err).Str("id", string(snap.ID)).Msg("ResumeAll: persist paused state failed") } } } @@ -1114,8 +1137,29 @@ func (s *Service) BuildTorrentTickSnapshot(ctx context.Context) (TorrentTickSnap if err != nil { return TorrentTickSnapshot{}, err } + snaps := s.engine.List() + // Persist completed_at the first time we observe a torrent complete. + // Every flavor's tick path funnels through here, so this is the one + // choke point where the service sees the completion transition. The + // record's nil check keeps the write to exactly once per torrent — + // RestoreOnStartup reads the column to arm missing-files detection, and + // the inspector surfaces it as DetailDTO.CompletedAt. + now := time.Now() + for _, snap := range snaps { + rec, ok := byHash[string(snap.ID)] + if !ok || !snap.Completed || rec.CompletedAt != nil { + continue + } + if err := s.torrents.SetCompletedAt(ctx, string(snap.ID), now); err != nil { + log.Warn().Err(err).Str("id", string(snap.ID)).Msg("tick: persist completed_at failed") + continue + } + t := now + rec.CompletedAt = &t + byHash[string(snap.ID)] = rec + } return TorrentTickSnapshot{ - snaps: s.engine.List(), + snaps: snaps, byHash: byHash, tagsByHash: tagsByHash, }, nil @@ -1357,7 +1401,8 @@ func (s *Service) DetailForFocus(ctx context.Context) (*DetailDTO, error) { if err != nil { return nil, err } - dto := detailToDTO(d, s.lookupAddedAt(ctx, f.id)) + addedAt, completedAt := s.lookupRecordTimes(ctx, f.id) + dto := detailToDTO(d, addedAt, completedAt) return &dto, nil } @@ -1376,15 +1421,15 @@ func scopeForTabs(tabs []string) engine.DetailScope { return scope } -func (s *Service) lookupAddedAt(ctx context.Context, id engine.TorrentID) time.Time { +func (s *Service) lookupRecordTimes(ctx context.Context, id engine.TorrentID) (time.Time, *time.Time) { rec, err := s.torrents.Get(ctx, string(id)) if err != nil { - return time.Time{} + return time.Time{}, nil } - return rec.AddedAt + return rec.AddedAt, rec.CompletedAt } -func detailToDTO(d engine.Detail, addedAt time.Time) DetailDTO { +func detailToDTO(d engine.Detail, addedAt time.Time, completedAt *time.Time) DetailDTO { snap := d.Snapshot prog := 0.0 if snap.TotalBytes > 0 { @@ -1408,6 +1453,9 @@ func detailToDTO(d engine.Detail, addedAt time.Time) DetailDTO { Completed: snap.Completed, FilesMissing: snap.FilesMissing, } + if completedAt != nil { + dto.CompletedAt = completedAt.Unix() + } for _, f := range d.Files { fp := 0.0 if f.Size > 0 { diff --git a/backend/api/service_test.go b/backend/api/service_test.go index d5db238..ab6bdb9 100644 --- a/backend/api/service_test.go +++ b/backend/api/service_test.go @@ -264,6 +264,25 @@ func TestService_QueuePosition(t *testing.T) { require.Equal(t, 7, rows[0].QueuePosition) } +// TestService_PauseResume_PersistsPausedColumn pins that Pause/Resume write +// the paused column — RestoreOnStartup reads it to re-pause torrents the user +// paused last session. +func TestService_PauseResume_PersistsPausedColumn(t *testing.T) { + svc, _ := newTestService(t) + ctx := sysCtx() + id, _ := svc.AddMagnet(ctx, "magnet:?xt=urn:btih:pp", "") + + require.NoError(t, svc.Pause(ctx, id)) + rec, err := svc.torrents.Get(ctx, string(id)) + require.NoError(t, err) + require.True(t, rec.Paused) + + require.NoError(t, svc.Resume(ctx, id)) + rec, err = svc.torrents.Get(ctx, string(id)) + require.NoError(t, err) + require.False(t, rec.Paused) +} + func TestService_GlobalStats(t *testing.T) { svc, _ := newTestService(t) ctx := sysCtx() From 90a5d71226907a75f3137ce80f21f43a4bf4f123 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:34:48 +0000 Subject: [PATCH 11/37] rss: persist seen items across restarts; poller hygiene MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The per-feed seen set was in-memory only, so every restart re-added every matching item still present in the feed, and markSeen wiped the whole set once it hit 1000 entries — re-adding up to a feed's worth of items on the next poll. Seen GUIDs now live in a new rss_seen table (feed_id FK ON DELETE CASCADE, unique(feed_id, guid)), hydrated into the in-memory cache at startup; Add prunes the oldest rows beyond rssSeenCap per feed instead of wiping. Hygiene in the same area: - filter regexes are compiled once per poll instead of once per item, and invalid patterns are logged instead of silently skipped - feed bodies are parsed through a 10 MB io.LimitReader, matching the existing torrent-fetch cap - gofeed.Parser is constructed per Parse call — the shared instance raced its lazy translator init between run() and PollNow / GetFeedItems request goroutines https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/api/rss_poller.go | 79 ++++++++++++++----- backend/api/rss_poller_test.go | 45 ++++++++++- backend/bootstrap/backend.go | 2 +- .../persistence/migrations/0015_rss_seen.sql | 15 ++++ backend/persistence/rss_seen.go | 53 +++++++++++++ backend/persistence/rss_seen_test.go | 68 ++++++++++++++++ 6 files changed, 238 insertions(+), 24 deletions(-) create mode 100644 backend/persistence/migrations/0015_rss_seen.sql create mode 100644 backend/persistence/rss_seen.go create mode 100644 backend/persistence/rss_seen_test.go diff --git a/backend/api/rss_poller.go b/backend/api/rss_poller.go index 47ccc27..3b82768 100644 --- a/backend/api/rss_poller.go +++ b/backend/api/rss_poller.go @@ -27,7 +27,7 @@ type RSSPoller struct { adder TorrentAdder feeds *persistence.Feeds filters *persistence.Filters - parser *gofeed.Parser + seen *persistence.RSSSeen httpC *http.Client mu sync.Mutex @@ -36,22 +36,42 @@ type RSSPoller struct { stop chan struct{} } +// rssSeenCap bounds the persisted seen-set per feed: Add prunes the oldest +// rows beyond it, so the table tracks the ~1000 most recent items per feed. const rssSeenCap = 1000 +// rssBodyCap bounds how much of a feed body we parse — same idea as the +// 10 MB torrent-fetch cap below (blocklists get 50 MB elsewhere). +const rssBodyCap = 10 << 20 + // NewRSSPoller starts a goroutine that ticks every 60 seconds and polls feeds // whose LastPolled + IntervalMin has elapsed. Call Close() to stop the poller. -func NewRSSPoller(adder TorrentAdder, feeds *persistence.Feeds, filters *persistence.Filters) *RSSPoller { +func NewRSSPoller(adder TorrentAdder, feeds *persistence.Feeds, filters *persistence.Filters, seen *persistence.RSSSeen) *RSSPoller { p := &RSSPoller{ - adder: adder, feeds: feeds, filters: filters, - parser: gofeed.NewParser(), + adder: adder, feeds: feeds, filters: filters, seen: seen, httpC: safeHTTPClient(30 * time.Second), seenByID: make(map[int]map[string]struct{}), stop: make(chan struct{}), } + // Hydrate the seen cache from the DB before polling starts, so a restart + // doesn't re-add every matching item still present in the feeds. + p.loadSeen(WithCaller(context.Background(), SystemCaller)) go p.run() return p } +// loadSeen replaces the in-memory seen cache with the persisted sets. +func (p *RSSPoller) loadSeen(ctx context.Context) { + loaded, err := p.seen.All(ctx) + if err != nil { + log.Warn().Err(err).Msg("rss: load persisted seen items failed; matching items may be re-added") + return + } + p.mu.Lock() + p.seenByID = loaded + p.mu.Unlock() +} + func (p *RSSPoller) Close() { close(p.stop) } // PollNow polls a single feed immediately, regardless of its @@ -138,7 +158,11 @@ func (p *RSSPoller) pollOne(ctx context.Context, f persistence.Feed) error { return fmt.Errorf("rss: HTTP %d", resp.StatusCode) } - feed, err := p.parser.Parse(resp.Body) + // Fresh parser per Parse: gofeed.Parser lazily initializes its + // translators without synchronization, so sharing one instance between + // the run() goroutine and PollNow/GetFeedItems request goroutines races. + // Body is capped — a feed shouldn't be anywhere near 10 MB. + feed, err := gofeed.NewParser().Parse(io.LimitReader(resp.Body, rssBodyCap)) if err != nil { if uerr := p.feeds.UpdatePollResult(ctx, f.ID, time.Now(), f.ETag); uerr != nil { log.Warn().Err(uerr).Int("feed", f.ID).Msg("rss: update poll result failed") @@ -150,7 +174,22 @@ func (p *RSSPoller) pollOne(ctx context.Context, f persistence.Feed) error { if err != nil { return err } - enabledFilters := filterEnabled(filters) + // Compile each filter's regex once per poll instead of once per item; + // invalid patterns are logged once here rather than silently skipped on + // every item. + type compiledFilter struct { + persistence.Filter + re *regexp.Regexp + } + var enabledFilters []compiledFilter + for _, fil := range filterEnabled(filters) { + re, err := regexp.Compile(fil.Regex) + if err != nil { + log.Warn().Err(err).Int("feed_id", f.ID).Str("regex", fil.Regex).Msg("rss: invalid filter regex; filter skipped") + continue + } + enabledFilters = append(enabledFilters, compiledFilter{Filter: fil, re: re}) + } matched := 0 for _, item := range feed.Items { @@ -166,11 +205,7 @@ func (p *RSSPoller) pollOne(ctx context.Context, f persistence.Feed) error { } for _, fil := range enabledFilters { - re, err := regexp.Compile(fil.Regex) - if err != nil { - continue - } - if !re.MatchString(item.Title) { + if !fil.re.MatchString(item.Title) { continue } @@ -196,7 +231,7 @@ func (p *RSSPoller) pollOne(ctx context.Context, f persistence.Feed) error { id = string(tid) } else { // No torrent source found — mark seen so we don't retry forever. - p.markSeen(f.ID, key) + p.markSeen(ctx, f.ID, key) break } @@ -206,7 +241,7 @@ func (p *RSSPoller) pollOne(ctx context.Context, f persistence.Feed) error { } } matched++ - p.markSeen(f.ID, key) + p.markSeen(ctx, f.ID, key) break // first matching filter wins } } @@ -232,16 +267,21 @@ func (p *RSSPoller) alreadySeen(feedID int, key string) bool { return ok } -func (p *RSSPoller) markSeen(feedID int, key string) { +func (p *RSSPoller) markSeen(ctx context.Context, feedID int, key string) { p.mu.Lock() - defer p.mu.Unlock() if p.seenByID[feedID] == nil { p.seenByID[feedID] = make(map[string]struct{}) } - if len(p.seenByID[feedID]) >= rssSeenCap { - p.seenByID[feedID] = make(map[string]struct{}) - } p.seenByID[feedID][key] = struct{}{} + p.mu.Unlock() + // Persist so dedup survives restarts; Add caps the table at the newest + // rssSeenCap rows per feed. The in-memory set is deliberately NOT capped + // or wiped — wiping it (the old behavior) re-added up to a full feed's + // worth of items on the next poll. Log-don't-fail: the in-memory set + // still dedups for the rest of this session. + if err := p.seen.Add(ctx, feedID, key, rssSeenCap); err != nil { + log.Warn().Err(err).Int("feed_id", feedID).Msg("rss: persist seen item failed") + } } func filterEnabled(all []persistence.Filter) []persistence.Filter { @@ -365,7 +405,8 @@ func (p *RSSPoller) GetFeedItems(ctx context.Context, feedID int) ([]FeedItemDTO if resp.StatusCode >= 400 { return nil, fmt.Errorf("rss: HTTP %d", resp.StatusCode) } - feed, err := p.parser.Parse(resp.Body) + // Fresh parser + capped body, same as pollOne (see comment there). + feed, err := gofeed.NewParser().Parse(io.LimitReader(resp.Body, rssBodyCap)) if err != nil { return nil, err } diff --git a/backend/api/rss_poller_test.go b/backend/api/rss_poller_test.go index aa8c5ba..7363811 100644 --- a/backend/api/rss_poller_test.go +++ b/backend/api/rss_poller_test.go @@ -42,12 +42,12 @@ func newPollerForTest(t *testing.T) (*RSSPoller, *Service, *persistence.Feeds, * // handle to it, so build a fresh DB for poller dependencies. The poller's // SetTorrentCategory / AddMagnet calls go through svc.* which uses svc's // own DB, but tests only assert on the engine list (not the categories). - feeds, filters := newRSSDAOs(t) + feeds, filters, seen := newRSSDAOs(t) p := &RSSPoller{ adder: svc, feeds: feeds, filters: filters, - parser: gofeed.NewParser(), + seen: seen, httpC: &http.Client{Timeout: 5 * time.Second}, seenByID: make(map[int]map[string]struct{}), stop: make(chan struct{}), @@ -55,12 +55,12 @@ func newPollerForTest(t *testing.T) (*RSSPoller, *Service, *persistence.Feeds, * return p, svc, feeds, filters } -func newRSSDAOs(t *testing.T) (*persistence.Feeds, *persistence.Filters) { +func newRSSDAOs(t *testing.T) (*persistence.Feeds, *persistence.Filters, *persistence.RSSSeen) { t.Helper() db, err := persistence.Open(sysCtx(), t.TempDir()+"/rss.db") require.NoError(t, err) t.Cleanup(func() { _ = db.Close() }) - return persistence.NewFeeds(db), persistence.NewFilters(db) + return persistence.NewFeeds(db), persistence.NewFilters(db), persistence.NewRSSSeen(db) } func TestRSSPoller_PollOne_MatchesAndAddsMagnet(t *testing.T) { @@ -151,6 +151,43 @@ func TestRSSPoller_PollOne_DedupViaSeenSet(t *testing.T) { require.Len(t, rows, 2) } +// TestRSSPoller_SeenSurvivesRestart pins the persisted dedup: a second poller +// hydrated from the same DB (simulating a process restart) must not re-add +// items the first poller already handled. +func TestRSSPoller_SeenSurvivesRestart(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(rssFeedXML)) + })) + defer srv.Close() + + p, _, feeds, filters := newPollerForTest(t) + ctx := sysCtx() + + feedID, _ := feeds.Create(ctx, persistence.Feed{URL: srv.URL, Name: "n", IntervalMin: 1, Enabled: true}) + _, _ = filters.Create(ctx, persistence.Filter{FeedID: feedID, Regex: `.*`, Enabled: true}) + + f, _ := feeds.Get(ctx, feedID) + require.NoError(t, p.pollOne(ctx, f)) + + // "Restart": new poller against the same seen DAO, fresh in-memory cache. + svc2, _ := newTestService(t) + p2 := &RSSPoller{ + adder: svc2, + feeds: feeds, + filters: filters, + seen: p.seen, + httpC: &http.Client{Timeout: 5 * time.Second}, + seenByID: make(map[int]map[string]struct{}), + stop: make(chan struct{}), + } + p2.loadSeen(ctx) + require.NoError(t, p2.pollOne(ctx, f)) + + rows, err := svc2.ListTorrents(ctx) + require.NoError(t, err) + require.Empty(t, rows, "items seen before the restart must not be re-added") +} + func TestRSSPoller_Tick_SkipsDisabledAndNotDue(t *testing.T) { hits := 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/backend/bootstrap/backend.go b/backend/bootstrap/backend.go index c28d071..fcd97b9 100644 --- a/backend/bootstrap/backend.go +++ b/backend/bootstrap/backend.go @@ -199,7 +199,7 @@ func Init(ctx context.Context, cfg Config) (*Backend, func(), error) { closers = append(closers, schedEng.Close) // ---- RSS poller ---- - rss := api.NewRSSPoller(svc, feeds, filters) + rss := api.NewRSSPoller(svc, feeds, filters, persistence.NewRSSSeen(db)) closers = append(closers, rss.Close) svc.AttachRSSPoller(rss) diff --git a/backend/persistence/migrations/0015_rss_seen.sql b/backend/persistence/migrations/0015_rss_seen.sql new file mode 100644 index 0000000..9ab1f7d --- /dev/null +++ b/backend/persistence/migrations/0015_rss_seen.sql @@ -0,0 +1,15 @@ +-- +goose Up +-- Per-feed GUIDs of RSS items the poller has already handled. Previously the +-- seen set was in-memory only, so every restart re-added every matching item +-- still present in the feed. Rows cascade-delete with their feed; the poller +-- caps each feed at ~1000 rows by pruning the oldest. +CREATE TABLE rss_seen ( + id INTEGER PRIMARY KEY, + feed_id INTEGER NOT NULL REFERENCES rss_feeds(id) ON DELETE CASCADE, + guid TEXT NOT NULL, + seen_at INTEGER NOT NULL, + UNIQUE (feed_id, guid) +); + +-- +goose Down +DROP TABLE rss_seen; diff --git a/backend/persistence/rss_seen.go b/backend/persistence/rss_seen.go new file mode 100644 index 0000000..e54e762 --- /dev/null +++ b/backend/persistence/rss_seen.go @@ -0,0 +1,53 @@ +package persistence + +import ( + "context" + "time" +) + +// RSSSeen is the DAO for the rss_seen table: per-feed GUIDs of feed items the +// poller has already handled, persisted so dedup survives restarts. Rows +// cascade-delete with their feed. +type RSSSeen struct{ db *DB } + +func NewRSSSeen(db *DB) *RSSSeen { return &RSSSeen{db: db} } + +// All returns every seen GUID grouped by feed id. The RSS poller loads this +// once at startup to seed its in-memory cache. +func (s *RSSSeen) All(ctx context.Context) (map[int]map[string]struct{}, error) { + rows, err := s.db.SQL().QueryContext(ctx, `SELECT feed_id, guid FROM rss_seen`) + if err != nil { + return nil, err + } + defer rows.Close() + out := make(map[int]map[string]struct{}) + for rows.Next() { + var feedID int + var guid string + if err := rows.Scan(&feedID, &guid); err != nil { + return nil, err + } + if out[feedID] == nil { + out[feedID] = make(map[string]struct{}) + } + out[feedID][guid] = struct{}{} + } + return out, rows.Err() +} + +// Add records a seen GUID, then prunes the oldest rows beyond keep so a +// high-churn feed can't grow the table without bound. Re-marking an +// already-seen GUID is a no-op. +func (s *RSSSeen) Add(ctx context.Context, feedID int, guid string, keep int) error { + if _, err := s.db.SQL().ExecContext(ctx, + `INSERT INTO rss_seen (feed_id, guid, seen_at) VALUES (?, ?, ?) + ON CONFLICT(feed_id, guid) DO NOTHING`, + feedID, guid, time.Now().Unix()); err != nil { + return err + } + _, err := s.db.SQL().ExecContext(ctx, ` +DELETE FROM rss_seen WHERE feed_id = ? AND id NOT IN ( + SELECT id FROM rss_seen WHERE feed_id = ? ORDER BY seen_at DESC, id DESC LIMIT ? +)`, feedID, feedID, keep) + return err +} diff --git a/backend/persistence/rss_seen_test.go b/backend/persistence/rss_seen_test.go new file mode 100644 index 0000000..d52bd3b --- /dev/null +++ b/backend/persistence/rss_seen_test.go @@ -0,0 +1,68 @@ +package persistence + +import ( + "context" + "fmt" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRSSSeen_AddAndAll(t *testing.T) { + db := newTestDB(t) + feeds := NewFeeds(db) + seen := NewRSSSeen(db) + ctx := context.Background() + + feedID, err := feeds.Create(ctx, Feed{URL: "https://example.test/f", Name: "f", Enabled: true}) + require.NoError(t, err) + + require.NoError(t, seen.Add(ctx, feedID, "guid-1", 1000)) + require.NoError(t, seen.Add(ctx, feedID, "guid-2", 1000)) + // Re-marking is a no-op, not an error. + require.NoError(t, seen.Add(ctx, feedID, "guid-1", 1000)) + + all, err := seen.All(ctx) + require.NoError(t, err) + require.Len(t, all[feedID], 2) + require.Contains(t, all[feedID], "guid-1") + require.Contains(t, all[feedID], "guid-2") +} + +func TestRSSSeen_AddPrunesOldestBeyondKeep(t *testing.T) { + db := newTestDB(t) + feeds := NewFeeds(db) + seen := NewRSSSeen(db) + ctx := context.Background() + + feedID, err := feeds.Create(ctx, Feed{URL: "https://example.test/f", Name: "f", Enabled: true}) + require.NoError(t, err) + + for i := 0; i < 5; i++ { + require.NoError(t, seen.Add(ctx, feedID, fmt.Sprintf("guid-%d", i), 3)) + } + + all, err := seen.All(ctx) + require.NoError(t, err) + require.Len(t, all[feedID], 3, "oldest rows beyond keep should be pruned") + // Rows share a seen_at second; the id DESC tie-break keeps the newest. + require.Contains(t, all[feedID], "guid-4") + require.Contains(t, all[feedID], "guid-3") + require.Contains(t, all[feedID], "guid-2") +} + +func TestRSSSeen_CascadesWithFeed(t *testing.T) { + db := newTestDB(t) + feeds := NewFeeds(db) + seen := NewRSSSeen(db) + ctx := context.Background() + + feedID, err := feeds.Create(ctx, Feed{URL: "https://example.test/f", Name: "f", Enabled: true}) + require.NoError(t, err) + require.NoError(t, seen.Add(ctx, feedID, "guid-1", 1000)) + require.NoError(t, feeds.Delete(ctx, feedID)) + + all, err := seen.All(ctx) + require.NoError(t, err) + require.Empty(t, all[feedID]) +} From 6a3b7cc410f6fb2d1ac117fd6c0fd9345fb33770 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:34:56 +0000 Subject: [PATCH 12/37] engine: don't revert sequential piece priorities after verify Both exits of verifyAndStart (fast-resume and full-hash) reset every file to PiecePriorityNormal, silently overwriting the sequential gradient if the user enabled sequential download while the verify was in flight. New applyPostVerifyPriorities checks a.sequential[id] under pausedMu and re-applies the gradient via applySequentialPriorities instead of resetting when the flag is set. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/engine/anacrolix.go | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/backend/engine/anacrolix.go b/backend/engine/anacrolix.go index 1c19d93..42f24ae 100644 --- a/backend/engine/anacrolix.go +++ b/backend/engine/anacrolix.go @@ -792,7 +792,7 @@ func (a *AnacrolixBackend) verifyAndStart(ctx context.Context, id TorrentID, t * log.Printf("verify: fast-resume %s — skipping hash (partial, restored=%d pieces)", id, restored) } if ctx.Err() == nil { - setAllFilesPriority(t, anacrolix_types.PiecePriorityNormal) + a.applyPostVerifyPriorities(id, t) } return } @@ -826,6 +826,21 @@ func (a *AnacrolixBackend) verifyAndStart(ctx context.Context, id TorrentID, t * // next startup can take the fast-resume path. a.saveSnapshotIfComplete(id, t) + a.applyPostVerifyPriorities(id, t) +} + +// applyPostVerifyPriorities restores piece priorities once verify finishes. +// SetSequential may have run while the verify was in flight; blindly resetting +// every file to Normal here would silently revert the sequential gradient, so +// re-apply it instead when the flag is set. +func (a *AnacrolixBackend) applyPostVerifyPriorities(id TorrentID, t *torrent.Torrent) { + a.pausedMu.RLock() + sequential := a.sequential[id] + a.pausedMu.RUnlock() + if sequential { + applySequentialPriorities(t, true) + return + } setAllFilesPriority(t, anacrolix_types.PiecePriorityNormal) } From 10e763dadb2eb8b1f6ff583767b73b6a050595fa Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:41:35 +0000 Subject: [PATCH 13/37] fix(remote): disconnect WS clients and revoke sessions when web interface stops MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit http.Server.Shutdown does not touch hijacked WebSocket connections, so disabling (or reconfiguring) the web interface left established clients registered in the hub — bootstrap.StreamTicks kept pushing live torrent frames to them via sendFrameToUser, which bypasses the cancelled bus. Session cookies also stayed valid in the in-memory SessionStore and worked again on re-enable. - Add Hub.DisconnectAll (RevokeUser pattern, StatusGoingAway) and call it from shutdownLocked so every stop/restart path hangs up live WebSockets. - Revoke all sessions on full disable (Apply with Enabled=false) and on Server.Stop. A port/bind reconfigure restart deliberately keeps sessions: the SPA reconnects to the new listener with its still-valid cookie instead of forcing a re-login; disabling the interface is the case where remote credentials must stop working immediately. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/remote/lifecycle.go | 16 +++++++++++++++- backend/remote/lifecycle_test.go | 32 ++++++++++++++++++++++++++++++++ backend/remote/ws.go | 22 ++++++++++++++++++++++ 3 files changed, 69 insertions(+), 1 deletion(-) diff --git a/backend/remote/lifecycle.go b/backend/remote/lifecycle.go index 0109b09..10fe1af 100644 --- a/backend/remote/lifecycle.go +++ b/backend/remote/lifecycle.go @@ -120,6 +120,13 @@ func (s *Server) Apply(cfg api.WebConfigDTO) error { s.current = cfg if !cfg.Enabled { + // Full disable: revoke every session so remote credentials stop + // working the moment the interface is turned off (and don't silently + // come back to life on a later re-enable). A reconfigure restart + // (Enabled stays true, port/bind changed) deliberately keeps sessions: + // the browser reconnects to the new listener with its still-valid + // cookie instead of forcing everyone through the login screen. + s.sessions.RevokeAll() return nil } @@ -132,11 +139,14 @@ func (s *Server) Apply(cfg api.WebConfigDTO) error { return nil } -// Stop tears down the running server (no-op if not running). +// Stop tears down the running server (no-op if not running) and revokes all +// sessions — it is a full stop, not a restart, so no remote credential should +// outlive it. func (s *Server) Stop() { s.mu.Lock() defer s.mu.Unlock() s.shutdownLocked() + s.sessions.RevokeAll() } // CurrentAddr returns the addr the server is bound to ("" if not running). @@ -221,6 +231,10 @@ func (s *Server) shutdownLocked() { if s.cancel != nil { s.cancel() } + // Shutdown does not close hijacked connections, so established WebSocket + // clients would otherwise survive the listener and keep receiving the + // per-user tick frames pushed directly via sendFrameToUser. + s.hub.DisconnectAll() s.srv = nil s.cancel = nil } diff --git a/backend/remote/lifecycle_test.go b/backend/remote/lifecycle_test.go index 52c1668..aca68cf 100644 --- a/backend/remote/lifecycle_test.go +++ b/backend/remote/lifecycle_test.go @@ -188,6 +188,38 @@ func TestService_OnWebConfigChange_FiresFromSetWebConfig(t *testing.T) { 2*time.Second, 20*time.Millisecond) } +// TestServer_SessionsAcrossApplyTransitions pins the session lifecycle rules: +// a reconfigure restart (Enabled stays true) keeps sessions so browsers can +// reconnect with their cookie, while a full disable revokes every session so +// remote credentials don't survive (and silently revive on a later re-enable). +func TestServer_SessionsAcrossApplyTransitions(t *testing.T) { + svc, _ := newServerFixture(t) + hub := NewHub() + t.Cleanup(hub.Close) + sessions := NewSessionStore() + srv := NewServer(svc, hub, sessions, nil, t.TempDir(), FlavorDaemon) + t.Cleanup(srv.Stop) + + p1 := freePort(t) + srv.Apply(api.WebConfigDTO{Enabled: true, Port: p1}) + waitListening(t, fmt.Sprintf("127.0.0.1:%d", p1)) + + _, err := sessions.Create(1) + require.NoError(t, err) + require.Equal(t, 1, sessions.Count()) + + // Port change restart: sessions survive. + p2 := freePort(t) + srv.Apply(api.WebConfigDTO{Enabled: true, Port: p2}) + waitListening(t, fmt.Sprintf("127.0.0.1:%d", p2)) + require.Equal(t, 1, sessions.Count()) + + // Disable: sessions revoked. + srv.Apply(api.WebConfigDTO{Enabled: false, Port: p2}) + require.Empty(t, srv.CurrentAddr()) + require.Equal(t, 0, sessions.Count()) +} + func TestServer_StaticFSServedAtRoot(t *testing.T) { svc, _ := newServerFixture(t) hub := NewHub() diff --git a/backend/remote/ws.go b/backend/remote/ws.go index f318f5b..a3c5194 100644 --- a/backend/remote/ws.go +++ b/backend/remote/ws.go @@ -260,6 +260,28 @@ func (h *Hub) RevokeUser(userID int) { } } +// DisconnectAll hangs up every live WebSocket client. Called when the web +// interface is stopped or reconfigured: http.Server.Shutdown does not touch +// hijacked connections, so without this an established client would keep +// receiving frames from the per-user tick fan-out (sendFrameToUser bypasses +// the bus) after the listener is gone. StatusGoingAway tells the SPA the +// server is shutting down rather than that its session was revoked. +func (h *Hub) DisconnectAll() { + h.mu.Lock() + victims := make([]*hubClient, 0, len(h.clients)) + for c := range h.clients { + victims = append(victims, c) + } + h.mu.Unlock() + // Close outside the hub lock so the loop in HandleUpgrade can call + // removeClient (which re-acquires it) without deadlocking us. + for _, c := range victims { + if c.conn != nil { + _ = c.conn.Close(websocket.StatusGoingAway, "server stopping") + } + } +} + // wsSessionRecheckInterval is the cadence at which a live WebSocket // re-validates its session token. Cheaper than checking on every frame and // still fast enough that a logged-out user's stream stops within ~30s of From e54c6599647fb40a71eb4c5d24e9eca583e2c5b6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:42:16 +0000 Subject: [PATCH 14/37] fix(events): add Bus.Unsubscribe and release Hub.Run's subscription on exit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bus.Subscribe had no counterpart, so every remote.Server (re)start — each of which runs go hub.Run(ctx) — left a dead channel in b.subs forever after the run's context was cancelled. Unsubscribe removes and closes the channel under the write lock (mutually exclusive with Publish's read lock, so no send-on-closed race) and is a no-op after Close, which already closed and dropped every subscriber. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/events/bus.go | 17 +++++++++++++++++ backend/events/bus_test.go | 20 ++++++++++++++++++++ backend/remote/ws.go | 5 ++++- 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/backend/events/bus.go b/backend/events/bus.go index f3e35e5..a757fc0 100644 --- a/backend/events/bus.go +++ b/backend/events/bus.go @@ -24,6 +24,23 @@ func (b *Bus[T]) Subscribe() <-chan T { return ch } +// Unsubscribe removes ch from the bus and closes it, so a subscriber that is +// done (e.g. a fan-out loop whose context was cancelled) doesn't leave a dead +// channel accumulating in b.subs forever. No-op if ch is not subscribed — +// including after Close, which has already closed and dropped every +// subscriber channel. +func (b *Bus[T]) Unsubscribe(ch <-chan T) { + b.mu.Lock() + defer b.mu.Unlock() + for i, c := range b.subs { + if c == ch { + b.subs = append(b.subs[:i], b.subs[i+1:]...) + close(c) + return + } + } +} + func (b *Bus[T]) Publish(v T) { b.mu.RLock() defer b.mu.RUnlock() diff --git a/backend/events/bus_test.go b/backend/events/bus_test.go index 94c1fd9..0f15e2d 100644 --- a/backend/events/bus_test.go +++ b/backend/events/bus_test.go @@ -49,6 +49,26 @@ func TestBus_FanOutsToAllSubscribers(t *testing.T) { require.Equal(t, []int{1, 2, 3}, bv) } +func TestBus_UnsubscribeRemovesAndCloses(t *testing.T) { + bus := NewBus[sample](2) + t.Cleanup(bus.Close) + + a := bus.Subscribe() + b := bus.Subscribe() + + bus.Unsubscribe(a) + _, ok := <-a + require.False(t, ok, "unsubscribed channel must be closed") + + // The remaining subscriber is unaffected. + bus.Publish(sample{N: 7}) + require.Equal(t, sample{N: 7}, <-b) + + // Unsubscribe after Close is a no-op (no double close, no panic). + bus.Close() + bus.Unsubscribe(b) +} + func TestBus_DropsWhenSubscriberSlow(t *testing.T) { bus := NewBus[sample](2) t.Cleanup(bus.Close) diff --git a/backend/remote/ws.go b/backend/remote/ws.go index a3c5194..580eaad 100644 --- a/backend/remote/ws.go +++ b/backend/remote/ws.go @@ -45,9 +45,12 @@ func NewHub() *Hub { } // Run consumes the internal bus and pushes pre-encoded frames to every -// connected client's send channel. Returns when ctx is done. +// connected client's send channel. Returns when ctx is done. The subscription +// is released on exit — each web-server (re)start spawns a fresh Run, so +// without the Unsubscribe every restart would leak a dead channel in the bus. func (h *Hub) Run(ctx context.Context) { sub := h.bus.Subscribe() + defer h.bus.Unsubscribe(sub) for { select { case <-ctx.Done(): From cf4b4a7b30f1d1801b32976c7ef99096957c85d1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:43:15 +0000 Subject: [PATCH 15/37] fix(remote): stop the WS session recheck from immortalizing idle sessions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SessionStore.Valid slides expiry forward 12h on every hit, and the WebSocket loop re-validates its session token every 30s — so any open tab renewed its session forever even when fully idle. Add a read-only Peek (validates without sliding) and use it in the recheck; real user activity still extends the window via Valid on each API request. Also fix the stale maxSessions comment claiming oldest-entry eviction; Create actually returns ErrTooManySessions when full. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/remote/auth.go | 23 ++++++++++++++++++++--- backend/remote/auth_test.go | 32 ++++++++++++++++++++++++++++++++ backend/remote/ws.go | 4 +++- 3 files changed, 55 insertions(+), 4 deletions(-) diff --git a/backend/remote/auth.go b/backend/remote/auth.go index b3c6ab9..e64b845 100644 --- a/backend/remote/auth.go +++ b/backend/remote/auth.go @@ -32,9 +32,9 @@ const ( sessionCookieName = "mosaic_session" sessionTTL = 12 * time.Hour // maxSessions caps the SessionStore so a flood of logins (or stale tokens - // piling up) can't grow memory without bound. When full, the oldest - // (earliest-expiring) entry is evicted. 100 is plenty for an interactive - // single-user web UI. + // piling up) can't grow memory without bound. When full (after reaping + // expired entries), Create returns ErrTooManySessions. 100 is plenty for + // an interactive single-user web UI. maxSessions = 100 ) @@ -118,6 +118,23 @@ func (s *SessionStore) Valid(token string) (int, bool) { return e.userID, true } +// Peek reports whether token is currently valid WITHOUT sliding its expiry +// forward. Used by the WebSocket session recheck: an open tab pings every 30s, +// so routing that through Valid would renew an otherwise-idle session forever. +// Real user activity still slides the window via Valid on each API request. +func (s *SessionStore) Peek(token string) (int, bool) { + if token == "" { + return 0, false + } + s.mu.RLock() + defer s.mu.RUnlock() + e, ok := s.sessions[token] + if !ok || time.Now().After(e.expires) { + return 0, false + } + return e.userID, true +} + func (s *SessionStore) Delete(token string) { s.mu.Lock() delete(s.sessions, token) diff --git a/backend/remote/auth_test.go b/backend/remote/auth_test.go index 0a65e55..c01c614 100644 --- a/backend/remote/auth_test.go +++ b/backend/remote/auth_test.go @@ -123,6 +123,38 @@ func TestSessionStore_ValidSlidesExpiry(t *testing.T) { require.True(t, newExp.After(originalExp), "Valid() must slide expiry forward") } +// TestSessionStore_PeekDoesNotSlideExpiry confirms the read-only validity +// check used by the WS 30s recheck loop: an idle tab's periodic pings must +// not renew the session forever. +func TestSessionStore_PeekDoesNotSlideExpiry(t *testing.T) { + s := NewSessionStore() + tok, err := s.Create(1) + require.NoError(t, err) + + s.mu.RLock() + originalExp := s.sessions[tok].expires + s.mu.RUnlock() + + time.Sleep(10 * time.Millisecond) + uid, ok := s.Peek(tok) + require.True(t, ok) + require.Equal(t, 1, uid) + + s.mu.RLock() + newExp := s.sessions[tok].expires + s.mu.RUnlock() + require.Equal(t, originalExp, newExp, "Peek() must not slide expiry") + + // Unknown and expired tokens are rejected. + _, ok = s.Peek("nope") + require.False(t, ok) + s.mu.Lock() + s.sessions[tok] = sessionEntry{userID: 1, expires: time.Now().Add(-time.Second)} + s.mu.Unlock() + _, ok = s.Peek(tok) + require.False(t, ok) +} + // TestSessionStore_CreateRejectsAtCapacity confirms that an in-memory full // store refuses new logins instead of silently evicting the oldest live // session — closing an availability-attack vector where a flood of logins diff --git a/backend/remote/ws.go b/backend/remote/ws.go index 580eaad..1704d7b 100644 --- a/backend/remote/ws.go +++ b/backend/remote/ws.go @@ -350,7 +350,9 @@ func (h *Hub) HandleUpgrade(sessions *SessionStore, res CallerResolver) http.Han return case <-recheck.C: if sessionToken != "" { - if _, ok := sessions.Valid(sessionToken); !ok { + // Peek, not Valid: the recheck must not slide the expiry + // forward, or any open tab would immortalize its session. + if _, ok := sessions.Peek(sessionToken); !ok { conn.Close(websocket.StatusPolicyViolation, "session revoked") return } From 42a2ef2ec2a46c6b59bce1100367cf3f01fa8b4a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:44:22 +0000 Subject: [PATCH 16/37] fix(persistence): detach torrents when deleting an in-use category torrents.category_id REFERENCES categories(id) with no ON DELETE action and foreign_keys on, so deleting a category still assigned to a torrent failed with an FK violation that surfaced as a generic 500 in the web UI. Categories.Delete now NULLs the torrents' category_id and deletes the category in a single transaction. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/persistence/categories.go | 19 +++++++++++++++++-- backend/persistence/categories_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/backend/persistence/categories.go b/backend/persistence/categories.go index e3b9423..45e18cd 100644 --- a/backend/persistence/categories.go +++ b/backend/persistence/categories.go @@ -68,7 +68,22 @@ func (c *Categories) Update(ctx context.Context, cat Category) error { return err } +// Delete removes a category, detaching any torrents still assigned to it. +// torrents.category_id REFERENCES categories(id) with no ON DELETE action and +// foreign_keys is on, so deleting an in-use category would otherwise fail +// with an FK violation. Both statements run in one transaction so a failed +// delete can't leave torrents detached from a category that still exists. func (c *Categories) Delete(ctx context.Context, id int) error { - _, err := c.db.SQL().ExecContext(ctx, `DELETE FROM categories WHERE id = ?`, id) - return err + tx, err := c.db.SQL().BeginTx(ctx, nil) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + if _, err := tx.ExecContext(ctx, `UPDATE torrents SET category_id = NULL WHERE category_id = ?`, id); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `DELETE FROM categories WHERE id = ?`, id); err != nil { + return err + } + return tx.Commit() } diff --git a/backend/persistence/categories_test.go b/backend/persistence/categories_test.go index 12cd11b..4e1fb6b 100644 --- a/backend/persistence/categories_test.go +++ b/backend/persistence/categories_test.go @@ -3,6 +3,7 @@ package persistence import ( "context" "testing" + "time" "github.com/stretchr/testify/require" ) @@ -60,6 +61,31 @@ func TestCategories_Delete(t *testing.T) { require.ErrorIs(t, err, ErrNotFound) } +// TestCategories_DeleteInUse covers deleting a category still assigned to a +// torrent: torrents.category_id has no ON DELETE action and foreign_keys is +// on, so Delete must detach the torrents (category_id → NULL) in the same +// transaction instead of failing with an FK violation. +func TestCategories_DeleteInUse(t *testing.T) { + db := newTestDB(t) + c := NewCategories(db) + tor := NewTorrents(db) + ctx := context.Background() + + id, err := c.Create(ctx, Category{Name: "Movies"}) + require.NoError(t, err) + require.NoError(t, tor.Save(ctx, TorrentRecord{ + InfoHash: "aaa", Name: "film", SavePath: "/tmp", CategoryID: &id, AddedAt: time.Now(), + })) + + require.NoError(t, c.Delete(ctx, id)) + _, err = c.Get(ctx, id) + require.ErrorIs(t, err, ErrNotFound) + + got, err := tor.Get(ctx, "aaa") + require.NoError(t, err) + require.Nil(t, got.CategoryID, "torrent must be detached from the deleted category") +} + func TestCategories_NameUnique(t *testing.T) { db := newTestDB(t) c := NewCategories(db) From dd5a961178af077c6e1166be5d028572cc024391 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:45:52 +0000 Subject: [PATCH 17/37] fix(remote): route handler errors through the sanitizing writeServiceErr Thirteen handlers (ListTorrents, GlobalStats, ListCategories, ListTags, GetDefaultSavePath, GetLimits, ListScheduleRules, ListFeeds, ListFiltersByFeed, RotateAPIKey, CheckForUpdate, InstallUpdate, RefreshBlocklist) wrote the raw internal error text with writeErr(w, 500/502, err), bypassing writeServiceErr's allowlist and leaking SQL strings / file paths / network internals into HTTP responses. All now go through writeServiceErr, which also restores the proper 403/404 mappings for sentinel errors. AddFeedItem additionally returned an implicit 200 with an empty body when decodeJSON failed; it now writes the error like its siblings. The two updater tests move from 500 to 400: "updater disabled" is on writeServiceErr's user-facing validation allowlist, so it surfaces as a 400 with the friendly message. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/remote/handlers.go | 27 ++++++++++++++------------- backend/remote/handlers_test.go | 11 ++++++----- 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/backend/remote/handlers.go b/backend/remote/handlers.go index 73d637e..1c26b73 100644 --- a/backend/remote/handlers.go +++ b/backend/remote/handlers.go @@ -465,7 +465,7 @@ func (h *Handlers) Logout(w http.ResponseWriter, r *http.Request) { func (h *Handlers) ListTorrents(w http.ResponseWriter, r *http.Request) { rows, err := h.svc.ListTorrents(r.Context()) if err != nil { - writeErr(w, http.StatusInternalServerError, err) + writeServiceErr(w, err) return } writeJSON(w, http.StatusOK, rows) @@ -585,7 +585,7 @@ func (h *Handlers) ClearInspectorFocus(w http.ResponseWriter, r *http.Request) { func (h *Handlers) GlobalStats(w http.ResponseWriter, r *http.Request) { st, err := h.svc.GlobalStats(r.Context()) if err != nil { - writeErr(w, http.StatusInternalServerError, err) + writeServiceErr(w, err) return } writeJSON(w, http.StatusOK, st) @@ -602,7 +602,7 @@ type createCategoryRequest struct { func (h *Handlers) ListCategories(w http.ResponseWriter, r *http.Request) { cats, err := h.svc.ListCategories(r.Context()) if err != nil { - writeErr(w, http.StatusInternalServerError, err) + writeServiceErr(w, err) return } writeJSON(w, http.StatusOK, cats) @@ -663,7 +663,7 @@ type createTagRequest struct { func (h *Handlers) ListTags(w http.ResponseWriter, r *http.Request) { tags, err := h.svc.ListTags(r.Context()) if err != nil { - writeErr(w, http.StatusInternalServerError, err) + writeServiceErr(w, err) return } writeJSON(w, http.StatusOK, tags) @@ -750,7 +750,7 @@ func (h *Handlers) SetTorrentCategory(w http.ResponseWriter, r *http.Request) { func (h *Handlers) GetDefaultSavePath(w http.ResponseWriter, r *http.Request) { v, err := h.svc.GetDefaultSavePath(r.Context()) if err != nil { - writeErr(w, http.StatusInternalServerError, err) + writeServiceErr(w, err) return } writeJSON(w, http.StatusOK, map[string]string{"path": v}) @@ -776,7 +776,7 @@ func (h *Handlers) SetDefaultSavePath(w http.ResponseWriter, r *http.Request) { func (h *Handlers) GetLimits(w http.ResponseWriter, r *http.Request) { l, err := h.svc.GetLimits(r.Context()) if err != nil { - writeErr(w, http.StatusInternalServerError, err) + writeServiceErr(w, err) return } writeJSON(w, http.StatusOK, l) @@ -955,7 +955,7 @@ func (h *Handlers) SetBlocklist(w http.ResponseWriter, r *http.Request) { func (h *Handlers) RefreshBlocklist(w http.ResponseWriter, r *http.Request) { if err := h.svc.RefreshBlocklist(r.Context()); err != nil { - writeErr(w, http.StatusBadGateway, err) + writeServiceErr(w, err) return } writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) @@ -1014,7 +1014,7 @@ func (h *Handlers) RemoveTracker(w http.ResponseWriter, r *http.Request) { func (h *Handlers) ListScheduleRules(w http.ResponseWriter, r *http.Request) { rules, err := h.svc.ListScheduleRules(r.Context()) if err != nil { - writeErr(w, http.StatusInternalServerError, err) + writeServiceErr(w, err) return } writeJSON(w, http.StatusOK, rules) @@ -1063,7 +1063,7 @@ func (h *Handlers) DeleteScheduleRule(w http.ResponseWriter, r *http.Request) { func (h *Handlers) ListFeeds(w http.ResponseWriter, r *http.Request) { feeds, err := h.svc.ListFeeds(r.Context()) if err != nil { - writeErr(w, http.StatusInternalServerError, err) + writeServiceErr(w, err) return } writeJSON(w, http.StatusOK, feeds) @@ -1117,7 +1117,7 @@ func (h *Handlers) ListFiltersByFeed(w http.ResponseWriter, r *http.Request) { } filters, err := h.svc.ListFiltersByFeed(r.Context(), feedID) if err != nil { - writeErr(w, http.StatusInternalServerError, err) + writeServiceErr(w, err) return } writeJSON(w, http.StatusOK, filters) @@ -1183,6 +1183,7 @@ func (h *Handlers) AddFeedItem(w http.ResponseWriter, r *http.Request) { SavePath string `json:"save_path"` } if err := decodeJSON(w, r, &body); err != nil { + writeServiceErr(w, err) return } if body.URL == "" { @@ -1236,7 +1237,7 @@ func (h *Handlers) SetWebPassword(w http.ResponseWriter, r *http.Request) { func (h *Handlers) RotateAPIKey(w http.ResponseWriter, r *http.Request) { key, err := h.svc.RotateAPIKey(r.Context()) if err != nil { - writeErr(w, http.StatusInternalServerError, err) + writeServiceErr(w, err) return } writeJSON(w, http.StatusOK, map[string]string{"api_key": key}) @@ -1264,7 +1265,7 @@ func (h *Handlers) SetUpdaterConfig(w http.ResponseWriter, r *http.Request) { func (h *Handlers) CheckForUpdate(w http.ResponseWriter, r *http.Request) { info, err := h.svc.CheckForUpdate(r.Context()) if err != nil { - writeErr(w, http.StatusInternalServerError, err) + writeServiceErr(w, err) return } writeJSON(w, http.StatusOK, info) @@ -1272,7 +1273,7 @@ func (h *Handlers) CheckForUpdate(w http.ResponseWriter, r *http.Request) { func (h *Handlers) InstallUpdate(w http.ResponseWriter, r *http.Request) { if err := h.svc.InstallUpdate(r.Context()); err != nil { - writeErr(w, http.StatusInternalServerError, err) + writeServiceErr(w, err) return } writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) diff --git a/backend/remote/handlers_test.go b/backend/remote/handlers_test.go index ecaf672..d3d0e38 100644 --- a/backend/remote/handlers_test.go +++ b/backend/remote/handlers_test.go @@ -225,24 +225,25 @@ func TestHandlers_Updater_RejectsUnknownChannel(t *testing.T) { require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) } -func TestHandlers_Updater_CheckWithoutUpdater_500s(t *testing.T) { +func TestHandlers_Updater_CheckWithoutUpdater_400s(t *testing.T) { // fixture Service has no updater attached → CheckForUpdate returns the - // "updater disabled" error → handler maps to 500. + // "updater disabled" error → writeServiceErr recognizes it as a + // user-facing validation message and maps it to 400. f := newFixture(t) key, _ := f.svc.RotateAPIKey(sysCtx()) rec := httptest.NewRecorder() f.router.ServeHTTP(rec, authedReq(t, key, http.MethodPost, "/api/updater/check", nil)) - require.Equal(t, http.StatusInternalServerError, rec.Code, rec.Body.String()) + require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) } -func TestHandlers_Updater_InstallWithoutUpdater_500s(t *testing.T) { +func TestHandlers_Updater_InstallWithoutUpdater_400s(t *testing.T) { f := newFixture(t) key, _ := f.svc.RotateAPIKey(sysCtx()) rec := httptest.NewRecorder() f.router.ServeHTTP(rec, authedReq(t, key, http.MethodPost, "/api/updater/install", nil)) - require.Equal(t, http.StatusInternalServerError, rec.Code, rec.Body.String()) + require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) } func TestHandlers_Version_OK(t *testing.T) { From 9b561c825eab74064e0a9ab96b17278eaba75867 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:46:18 +0000 Subject: [PATCH 18/37] fix(remote): key ResetUserPassword's rate limit by the acting caller MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The limiter check ran before the service's admin authorization and was keyed by the TARGET user id, sharing buckets with ChangeMyPassword — so any authenticated user could drain another user's password-change bucket by spamming admin resets they weren't allowed to perform. Keying by the acting caller makes the pre-authorization charge land on the abuser's own bucket while still throttling a compromised admin session. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/remote/handlers.go | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/backend/remote/handlers.go b/backend/remote/handlers.go index 1c26b73..9aa54ad 100644 --- a/backend/remote/handlers.go +++ b/backend/remote/handlers.go @@ -1445,10 +1445,13 @@ func (h *Handlers) ResetUserPassword(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, errors.New("bad user id")) return } - // Rate-limit keyed by the *target* user id so a compromised admin - // session can't grind through a password-reset oracle for a victim - // account. - if !h.passwordLimiter.allow(id) { + // Rate-limit keyed by the ACTING caller, not the target. The limiter + // runs before the service's admin check, so a target-keyed bucket let + // any authenticated user drain a victim's bucket (shared with + // ChangeMyPassword) just by spamming this endpoint and eating the 403s. + // Caller-keyed, the pre-authorization charge only ever costs the abuser + // their own budget, while still throttling a compromised admin session. + if !h.passwordLimiter.allow(api.CallerFrom(r.Context()).UserID) { w.Header().Set("Retry-After", strconv.Itoa(loginRetryAfterSecs)) writeErr(w, http.StatusTooManyRequests, errors.New("too many password attempts")) return From d934a325c633fbf16f5e14803340d77af67728ed Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:48:09 +0000 Subject: [PATCH 19/37] fix(remote): apply the OriginGuard to /api/login (login CSRF) /api/login was mounted outside the OriginGuard group, so a cross-site form post could silently log a victim's browser into an attacker-controlled account. The guard's existing semantics are preserved unchanged: same-origin Origin (or Referer) passes, mismatched or absent both is rejected, and Bearer-carrying requests skip the check. The SPA is same-origin and always sends Origin on fetch, so legitimate logins are unaffected; tests now set a matching Origin via a shared loginReq helper. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/remote/handlers_test.go | 40 +++++++++++++++++++++++++++------ backend/remote/server.go | 7 ++++-- backend/remote/server_test.go | 14 ++++++++++-- 3 files changed, 50 insertions(+), 11 deletions(-) diff --git a/backend/remote/handlers_test.go b/backend/remote/handlers_test.go index d3d0e38..83b2dc7 100644 --- a/backend/remote/handlers_test.go +++ b/backend/remote/handlers_test.go @@ -156,7 +156,7 @@ func TestHandlers_WebConfigAndPasswordRotation(t *testing.T) { body, _ := json.Marshal(map[string]string{"username": "remote", "password": "p4ssword!"}) rec = httptest.NewRecorder() - f.router.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/api/login", bytes.NewReader(body))) + f.router.ServeHTTP(rec, loginReq(bytes.NewReader(body))) require.Equal(t, http.StatusOK, rec.Code) // Rotate API key — old key still works for the PUT but a new one comes back. @@ -265,7 +265,7 @@ func TestLogin_CookieHasSameSiteStrict(t *testing.T) { body, _ := json.Marshal(map[string]string{"username": "alice", "password": "s3cret"}) rec := httptest.NewRecorder() - f.router.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/api/login", bytes.NewReader(body))) + f.router.ServeHTTP(rec, loginReq(bytes.NewReader(body))) require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) var sessionCookie *http.Cookie @@ -290,14 +290,14 @@ func TestLogin_RateLimitReturns429AfterFiveFailures(t *testing.T) { // 6th from the same IP must trip the limiter and return 429. for i := 0; i < 5; i++ { rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/login", bytes.NewReader(body)) + req := loginReq(bytes.NewReader(body)) req.RemoteAddr = "10.0.0.7:54321" f.router.ServeHTTP(rec, req) require.Equal(t, http.StatusUnauthorized, rec.Code, "attempt %d", i+1) } rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/login", bytes.NewReader(body)) + req := loginReq(bytes.NewReader(body)) req.RemoteAddr = "10.0.0.7:54321" f.router.ServeHTTP(rec, req) require.Equal(t, http.StatusTooManyRequests, rec.Code, rec.Body.String()) @@ -305,12 +305,38 @@ func TestLogin_RateLimitReturns429AfterFiveFailures(t *testing.T) { // Different IP gets its own bucket. rec = httptest.NewRecorder() - req = httptest.NewRequest(http.MethodPost, "/api/login", bytes.NewReader(body)) + req = loginReq(bytes.NewReader(body)) req.RemoteAddr = "10.0.0.8:54321" f.router.ServeHTTP(rec, req) require.Equal(t, http.StatusUnauthorized, rec.Code) } +// TestLogin_RejectsCrossOriginPOST covers login CSRF: a cross-site form post +// to /api/login must be rejected by the OriginGuard before credentials are +// even examined, so a malicious page can't silently log the victim's browser +// into an attacker-controlled account. +func TestLogin_RejectsCrossOriginPOST(t *testing.T) { + f := newFixture(t) + f.seedCreds(t, "alice", "s3cret") + + body, _ := json.Marshal(map[string]string{"username": "alice", "password": "s3cret"}) + req := httptest.NewRequest(http.MethodPost, "/api/login", bytes.NewReader(body)) + req.Host = "mosaic.local:8080" + req.Header.Set("Origin", "https://evil.example.com") + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + f.router.ServeHTTP(rec, req) + require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String()) + + // Missing both Origin and Referer is rejected too — same semantics as + // the rest of the guarded surface. + req = httptest.NewRequest(http.MethodPost, "/api/login", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + rec = httptest.NewRecorder() + f.router.ServeHTTP(rec, req) + require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String()) +} + func TestOriginGuard_RejectsMismatchedOriginOnPOST(t *testing.T) { f := newFixture(t) f.seedCreds(t, "alice", "s3cret") @@ -506,7 +532,7 @@ func TestLogin_BodyOver1MiBReturns413BeforeRateLimit(t *testing.T) { body := append([]byte(`{"username":"alice","password":"`), junk...) body = append(body, []byte(`"}`)...) - req := httptest.NewRequest(http.MethodPost, "/api/login", bytes.NewReader(body)) + req := loginReq(bytes.NewReader(body)) req.RemoteAddr = "10.0.0.99:12345" rec := httptest.NewRecorder() f.router.ServeHTTP(rec, req) @@ -517,7 +543,7 @@ func TestLogin_BodyOver1MiBReturns413BeforeRateLimit(t *testing.T) { good, _ := json.Marshal(map[string]string{"username": "alice", "password": "s3cret"}) for i := 0; i < 5; i++ { rec = httptest.NewRecorder() - req = httptest.NewRequest(http.MethodPost, "/api/login", bytes.NewReader(good)) + req = loginReq(bytes.NewReader(good)) req.RemoteAddr = "10.0.0.99:12345" f.router.ServeHTTP(rec, req) require.Equal(t, http.StatusOK, rec.Code, "login %d", i+1) diff --git a/backend/remote/server.go b/backend/remote/server.go index 77879e0..b0f083d 100644 --- a/backend/remote/server.go +++ b/backend/remote/server.go @@ -61,8 +61,11 @@ func MountWithOptions(svc *api.Service, sessions *SessionStore, hub *Hub, static csrf := OriginGuard() r.Route("/api", func(api chi.Router) { - // public - api.Post("/login", h.Login) + // public — Login still gets the OriginGuard: a cross-site form post + // could otherwise silently log the victim's browser into an + // attacker-controlled account (login CSRF). The SPA is same-origin so + // legitimate logins always carry a matching Origin. + api.With(csrf).Post("/login", h.Login) api.Get("/bootstrap", h.Bootstrap) // gated api.Group(func(g chi.Router) { diff --git a/backend/remote/server_test.go b/backend/remote/server_test.go index 7d9f5b9..3f97960 100644 --- a/backend/remote/server_test.go +++ b/backend/remote/server_test.go @@ -62,6 +62,16 @@ func newFixture(t *testing.T) *fixture { return &fixture{svc: svc, fb: fb, sessions: sessions, router: router} } +// loginReq builds a POST /api/login request with a same-origin Origin header. +// /api/login sits behind the OriginGuard (login-CSRF defense), which rejects +// browser-shaped POSTs lacking a matching Origin/Referer; the SPA always +// sends Origin on fetch, so tests mimic that. +func loginReq(body io.Reader) *http.Request { + req := httptest.NewRequest(http.MethodPost, "/api/login", body) + req.Header.Set("Origin", "http://"+req.Host) + return req +} + func (f *fixture) seedCreds(t *testing.T, user, pass string) { t.Helper() require.NoError(t, f.svc.SetWebConfig(sysCtx(), api.WebConfigDTO{Username: user})) @@ -72,7 +82,7 @@ func (f *fixture) loginCookie(t *testing.T, user, pass string) *http.Cookie { t.Helper() body, _ := json.Marshal(map[string]string{"username": user, "password": pass}) rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/login", bytes.NewReader(body)) + req := loginReq(bytes.NewReader(body)) f.router.ServeHTTP(rec, req) require.Equal(t, http.StatusOK, rec.Code) for _, c := range rec.Result().Cookies() { @@ -90,7 +100,7 @@ func TestServer_LoginRejectsWrongCreds(t *testing.T) { body, _ := json.Marshal(map[string]string{"username": "alice", "password": "wrong"}) rec := httptest.NewRecorder() - f.router.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/api/login", bytes.NewReader(body))) + f.router.ServeHTTP(rec, loginReq(bytes.NewReader(body))) require.Equal(t, http.StatusUnauthorized, rec.Code) } From 64f4b18d3f56ee3937750443cfa367c210f50413 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:49:14 +0000 Subject: [PATCH 20/37] feat(remote): add POST /api/feeds/{id}/poll backing the SPA's per-feed refresh The browser transport invoked PollFeedNow but no REST route existed, so the per-feed "Refresh now" button failed outside Wails. Add the route + handler (service enforces CanManageRSS like the other feed mutations) and the matching PollFeedNow entry in the HTTP transport's ROUTES table. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/remote/handlers.go | 16 ++++++++++++++++ backend/remote/handlers_test.go | 14 ++++++++++++++ backend/remote/server.go | 1 + frontend/src/lib/http_transport.ts | 1 + 4 files changed, 32 insertions(+) diff --git a/backend/remote/handlers.go b/backend/remote/handlers.go index 9aa54ad..22574aa 100644 --- a/backend/remote/handlers.go +++ b/backend/remote/handlers.go @@ -1163,6 +1163,22 @@ func (h *Handlers) DeleteFilter(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) } +// PollFeedNow triggers an immediate poll of one feed, bypassing its scheduled +// interval. Backs the SPA's per-feed "Refresh now" button; permission +// (CanManageRSS) is enforced by the service like the other feed mutations. +func (h *Handlers) PollFeedNow(w http.ResponseWriter, r *http.Request) { + id, err := strconv.Atoi(chi.URLParam(r, "id")) + if err != nil { + writeServiceErr(w, err) + return + } + if err := h.svc.PollFeedNow(r.Context(), id); err != nil { + writeServiceErr(w, err) + return + } + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + func (h *Handlers) GetFeedItems(w http.ResponseWriter, r *http.Request) { feedID, err := strconv.Atoi(chi.URLParam(r, "feedID")) if err != nil { diff --git a/backend/remote/handlers_test.go b/backend/remote/handlers_test.go index 83b2dc7..5e82365 100644 --- a/backend/remote/handlers_test.go +++ b/backend/remote/handlers_test.go @@ -171,6 +171,20 @@ func TestHandlers_WebConfigAndPasswordRotation(t *testing.T) { require.NotEqual(t, key, rot.APIKey) } +// TestHandlers_PollFeedNow_RouteWired pins the POST /api/feeds/{id}/poll +// route the SPA's per-feed "Refresh now" button calls. The fixture has no +// RSS poller attached, so the service returns "rss poller not attached" — +// a user-facing validation message writeServiceErr maps to 400. A missing +// route would yield 404/405 instead. +func TestHandlers_PollFeedNow_RouteWired(t *testing.T) { + f := newFixture(t) + key, _ := f.svc.RotateAPIKey(sysCtx()) + + rec := httptest.NewRecorder() + f.router.ServeHTTP(rec, authedReq(t, key, http.MethodPost, "/api/feeds/1/poll", nil)) + require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) +} + func TestHandlers_Stats(t *testing.T) { f := newFixture(t) key, _ := f.svc.RotateAPIKey(sysCtx()) diff --git a/backend/remote/server.go b/backend/remote/server.go index b0f083d..4d00c6f 100644 --- a/backend/remote/server.go +++ b/backend/remote/server.go @@ -157,6 +157,7 @@ func MountWithOptions(svc *api.Service, sessions *SessionStore, hub *Hub, static g.Post("/feeds", h.CreateFeed) g.Put("/feeds", h.UpdateFeed) g.Delete("/feeds/{id}", h.DeleteFeed) + g.Post("/feeds/{id}/poll", h.PollFeedNow) g.Get("/feeds/{feedID}/items", h.GetFeedItems) g.Post("/torrents/url", h.AddFeedItem) g.Get("/feeds/{feedID}/filters", h.ListFiltersByFeed) diff --git a/frontend/src/lib/http_transport.ts b/frontend/src/lib/http_transport.ts index 9985b43..8a8ff3f 100644 --- a/frontend/src/lib/http_transport.ts +++ b/frontend/src/lib/http_transport.ts @@ -322,6 +322,7 @@ const ROUTES: Record = { unwrap: okEnvelope, }, DeleteFeed: {method: 'DELETE', path: ([id]) => `/api/feeds/${id}`, unwrap: okEnvelope}, + PollFeedNow: {method: 'POST', path: ([id]) => `/api/feeds/${id}/poll`, unwrap: okEnvelope}, GetFeedItems: {method: 'GET', path: ([feedID]) => `/api/feeds/${feedID}/items`}, AddFeedItem: { method: 'POST', From 6ff534152ea83f456482d7abfc3c2962f3f3ecd5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:42:01 +0000 Subject: [PATCH 21/37] fix(daemon): enforce seeding limits in mosaicd via shared tick loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Service.CheckSeedLimits was only wired into the desktop-only streamWailsEvents loop, so the headless daemon never paused torrents that hit their ratio/time limits. Move the 30s seed-check ticker into bootstrap.StreamTicks (svc-level, flavor-agnostic, runs in both entry points) and remove it from streamWailsEvents so the desktop — which runs both loops — doesn't check twice. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- app.go | 9 ++------- backend/bootstrap/ticks.go | 11 +++++++++++ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/app.go b/app.go index 3f95149..fb8c792 100644 --- a/app.go +++ b/app.go @@ -577,24 +577,19 @@ func (a *App) SetTorrentSeedPolicy(infohash string, p api.SeedPolicyDTO) error { // streamWailsEvents emits state snapshots to the embedded SPA via Wails // events. The companion bootstrap.StreamTicks goroutine, started alongside // this one in startup(), handles the per-user hub fan-out for connected -// browser clients. seedCheck is wedged in here because it's a periodic -// service-level operation rather than a publish, and there's no better -// place for it. +// browser clients — and also owns the periodic seed-limit enforcement +// (CheckSeedLimits), so it runs in the daemon too and never twice here. func (a *App) streamWailsEvents(ctx context.Context) { torrents := time.NewTicker(500 * time.Millisecond) stats := time.NewTicker(1 * time.Second) inspector := time.NewTicker(1 * time.Second) - seedCheck := time.NewTicker(30 * time.Second) defer torrents.Stop() defer stats.Stop() defer inspector.Stop() - defer seedCheck.Stop() for { select { case <-ctx.Done(): return - case <-seedCheck.C: - a.svc.CheckSeedLimits(ctx) case <-torrents.C: rows, err := a.svc.ListTorrents(ctx) if err != nil { diff --git a/backend/bootstrap/ticks.go b/backend/bootstrap/ticks.go index 765af2a..a543484 100644 --- a/backend/bootstrap/ticks.go +++ b/backend/bootstrap/ticks.go @@ -26,6 +26,12 @@ import ( // produces zero traffic. Fingerprints for users who disconnect are pruned each // tick so a reconnecting client always gets a fresh first frame. // +// Beyond publishing, this loop also runs the periodic seed-limit enforcement +// (Service.CheckSeedLimits). That's a service-level operation rather than a +// fan-out, but it must run in BOTH flavors — keeping it here (and only here) +// means the daemon enforces seeding limits and the desktop doesn't run the +// check twice. +// // Desktop entry point: call this in a goroutine alongside streamWailsEvents // (which handles the embedded-SPA Wails event emission separately). // Daemon entry point: call this as the sole tick goroutine. @@ -33,9 +39,11 @@ func StreamTicks(ctx context.Context, svc *api.Service, hub *remote.Hub) { torrents := time.NewTicker(1 * time.Second) stats := time.NewTicker(1 * time.Second) inspector := time.NewTicker(1 * time.Second) + seedCheck := time.NewTicker(30 * time.Second) defer torrents.Stop() defer stats.Stop() defer inspector.Stop() + defer seedCheck.Stop() lastTorrentsFrame := make(map[int][32]byte) @@ -44,6 +52,9 @@ func StreamTicks(ctx context.Context, svc *api.Service, hub *remote.Hub) { case <-ctx.Done(): return + case <-seedCheck.C: + svc.CheckSeedLimits(ctx) + case <-torrents.C: uids := hub.ConnectedUserIDs() if len(uids) == 0 { From baaf7cb647c27defa367502930b2668ea16b030e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:42:15 +0000 Subject: [PATCH 22/37] fix(updater): include *.tar.gz in SHA256SUMS manifest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The darwin in-app updater downloads Mosaic--darwin-universal.tar.gz and validates it against the SHA256SUMS release asset, but make-checksums.sh never hashed tarballs — so every macOS in-app update hard-failed checksum validation. Add *.tar.gz to the artifact glob. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- scripts/make-checksums.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/make-checksums.sh b/scripts/make-checksums.sh index ec6bab3..2762c49 100755 --- a/scripts/make-checksums.sh +++ b/scripts/make-checksums.sh @@ -10,7 +10,10 @@ cd "${BIN_DIR}" shopt -s nullglob ARTIFACTS=() -for f in *.dmg *.deb *.rpm *.AppImage *-installer.exe *-portable.exe; do +# *.tar.gz covers the macOS auto-update tarball (Mosaic--darwin- +# universal.tar.gz from build-macos.sh) — the darwin updater validates it +# against this manifest, and a missing row is a hard checksum failure. +for f in *.dmg *.deb *.rpm *.AppImage *.tar.gz *-installer.exe *-portable.exe; do if [[ -f "${f}" ]]; then ARTIFACTS+=("${f}") fi From 468c1a4a6102403f1b80a2f8aa2cc219dd9135e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:42:56 +0000 Subject: [PATCH 23/37] fix(updater): target $APPIMAGE for self-update instead of squashfs mount MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When running inside an AppImage, selfupdate.ExecutablePath() resolves to the payload binary on the read-only FUSE mount (/tmp/.mount_*/usr/bin/ mosaic), so every in-app update failed at the write step. The AppImage runtime exports APPIMAGE= — the same signal DetectInstallSource already trusts — and the downloaded Linux asset is itself a new AppImage, so swap that file instead. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/updater/updater.go | 10 ++++++++++ backend/updater/updater_test.go | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/backend/updater/updater.go b/backend/updater/updater.go index f1c2958..41d320e 100644 --- a/backend/updater/updater.go +++ b/backend/updater/updater.go @@ -3,6 +3,7 @@ package updater import ( "context" "fmt" + "os" "sync" "time" @@ -113,6 +114,15 @@ func (u *Updater) Install(ctx context.Context, info Info) error { if !info.Available { return fmt.Errorf("no update available") } + // Inside a running AppImage, os.Executable() (what ExecutablePath + // resolves) points at the payload binary on the read-only squashfs FUSE + // mount (/tmp/.mount_*/usr/bin/mosaic) — writing there always fails. + // The runtime exports APPIMAGE= + // (same detection as DetectInstallSource), and the Linux release asset + // IS a new AppImage, so swap that file instead. + if appImage := os.Getenv("APPIMAGE"); appImage != "" { + return u.cfg.Source.Install(ctx, appImage) + } exe, err := selfupdate.ExecutablePath() if err != nil { return fmt.Errorf("executable path: %w", err) diff --git a/backend/updater/updater_test.go b/backend/updater/updater_test.go index a0032b1..6ff2eac 100644 --- a/backend/updater/updater_test.go +++ b/backend/updater/updater_test.go @@ -151,6 +151,27 @@ func TestInstall_DelegatesToSourceWhenAvailable(t *testing.T) { } } +func TestInstall_TargetsAppImagePathWhenWrapped(t *testing.T) { + // Inside an AppImage the resolved executable lives on a read-only + // squashfs mount; Install must target the .AppImage file itself. + t.Setenv("APPIMAGE", "/home/user/Applications/Mosaic.AppImage") + src := &fakeSource{ + latestTag: "v0.8.0", + latestAsset: "Mosaic-v0.8.0-linux-amd64.AppImage", + } + u := New(Config{CurrentVersion: "v0.7.0", Source: src}) + info, err := u.Check(context.Background()) + if err != nil { + t.Fatal(err) + } + if err := u.Install(context.Background(), info); err != nil { + t.Fatalf("Install returned error: %v", err) + } + if src.installExe != "/home/user/Applications/Mosaic.AppImage" { + t.Fatalf("expected install target to be $APPIMAGE, got %q", src.installExe) + } +} + func TestInstall_ErrorsWhenNotAvailable(t *testing.T) { src := &fakeSource{} u := New(Config{CurrentVersion: "v0.7.0", Source: src}) From ec6a282bc6be892c07d5aa5547e2474b2c3c4629 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:43:43 +0000 Subject: [PATCH 24/37] fix(updater): honor pre-release identifiers in version comparison compareVersions stripped everything after the numeric core, so v0.8.0-rc1 compared equal to v0.8.0 and rc users were never offered rc2 or the final release. Split off the pre-release identifier (and drop +build metadata), treat a pre-release as lower than the same-numbered release, and compare two pre-releases lexicographically. Add table tests. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/updater/updater.go | 39 ++++++++++++++++++++--- backend/updater/updater_test.go | 56 +++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 4 deletions(-) diff --git a/backend/updater/updater.go b/backend/updater/updater.go index 41d320e..0125df3 100644 --- a/backend/updater/updater.go +++ b/backend/updater/updater.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "os" + "strings" "sync" "time" @@ -132,9 +133,16 @@ func (u *Updater) Install(ctx context.Context, info Info) error { // compareVersions returns negative / zero / positive for a < / == / > b // using simple semver-ish numeric segment compare. Tolerant of "v" prefix. +// Pre-release identifiers follow semver precedence in spirit: a pre-release +// sorts below the same-numbered release (v0.8.0-rc1 < v0.8.0), and two +// pre-releases of the same core version compare lexicographically (close +// enough for our rcN/betaN tag scheme — without this, rc users were never +// offered rc2 or the final release). func compareVersions(a, b string) int { - pa := parseSegments(a) - pb := parseSegments(b) + coreA, preA := splitPrerelease(a) + coreB, preB := splitPrerelease(b) + pa := parseSegments(coreA) + pb := parseSegments(coreB) n := len(pa) if len(pb) > n { n = len(pb) @@ -154,7 +162,30 @@ func compareVersions(a, b string) int { return 1 } } - return 0 + switch { + case preA == preB: + return 0 + case preA == "": // a is the release, b a pre-release of it + return 1 + case preB == "": // b is the release, a a pre-release of it + return -1 + case preA < preB: + return -1 + default: + return 1 + } +} + +// splitPrerelease splits "0.8.0-rc1+build5" into ("0.8.0", "rc1"). Build +// metadata after '+' is dropped (semver: ignored for precedence). +func splitPrerelease(v string) (core, pre string) { + if i := strings.IndexByte(v, '+'); i >= 0 { + v = v[:i] + } + if i := strings.IndexByte(v, '-'); i >= 0 { + return v[:i], v[i+1:] + } + return v, "" } func parseSegments(v string) []int { @@ -176,7 +207,7 @@ func parseSegments(v string) []int { have = false } if c != '.' { - break // stop at first non-dot non-digit (e.g. "-rc1") + break // stop at first non-dot non-digit } } if have { diff --git a/backend/updater/updater_test.go b/backend/updater/updater_test.go index 6ff2eac..f5d7fc5 100644 --- a/backend/updater/updater_test.go +++ b/backend/updater/updater_test.go @@ -108,6 +108,62 @@ func TestCheck_NetworkError(t *testing.T) { } } +func TestCompareVersions(t *testing.T) { + cases := []struct { + a, b string + want int // sign of compareVersions(a, b) + }{ + {"v0.7.0", "v0.7.0", 0}, + {"v0.8.0", "v0.7.0", 1}, + {"v0.7.0", "v0.8.0", -1}, + {"v0.7.10", "v0.7.9", 1}, + {"v1.0", "v1.0.0", 0}, // missing segments are zero + {"0.8.0", "v0.8.0", 0}, + // Pre-release sorts below the same-numbered release. + {"v0.8.0-rc1", "v0.8.0", -1}, + {"v0.8.0", "v0.8.0-rc1", 1}, + // Pre-releases of the same core compare lexicographically. + {"v0.8.0-rc1", "v0.8.0-rc2", -1}, + {"v0.8.0-rc2", "v0.8.0-rc1", 1}, + {"v0.8.0-rc1", "v0.8.0-rc1", 0}, + {"v0.8.0-beta", "v0.8.0-rc1", -1}, + // Pre-release of a HIGHER core version still wins. + {"v0.9.0-rc1", "v0.8.0", 1}, + {"v0.8.0-rc1", "v0.7.5", 1}, + // Build metadata is ignored for precedence. + {"v0.8.0+build5", "v0.8.0", 0}, + {"v0.8.0-rc1+build5", "v0.8.0-rc1", 0}, + } + sign := func(n int) int { + switch { + case n < 0: + return -1 + case n > 0: + return 1 + } + return 0 + } + for _, tc := range cases { + if got := sign(compareVersions(tc.a, tc.b)); got != tc.want { + t.Errorf("compareVersions(%q, %q) = %d, want sign %d", tc.a, tc.b, got, tc.want) + } + } +} + +func TestCheck_PrereleaseUserOfferedFinal(t *testing.T) { + u := New(Config{ + CurrentVersion: "v0.8.0-rc1", + Source: &fakeSource{latestTag: "v0.8.0"}, + }) + info, err := u.Check(context.Background()) + if err != nil { + t.Fatal(err) + } + if !info.Available { + t.Fatal("expected rc user to be offered the final release") + } +} + func TestSchedule_TickRespectsCancel(t *testing.T) { u := New(Config{ CurrentVersion: "v0.7.0", From f4b403dea8498d6b30db6fa5ecf2eae8c052c619 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:45:25 +0000 Subject: [PATCH 25/37] fix(updater): apply channel + enabled toggles at runtime, not just boot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GitHubSource baked the channel into its cached go-selfupdate handle at first use, and main.go only started the Schedule goroutine when the toggle was on at boot — so SetUpdaterConfig changes silently required a restart. Now: - GitHubSource.SetChannel mutates the channel under the lock and lazyInit rebuilds the cached updater (and drops the stale release) when the channel it was built for no longer matches. - Service gains an OnUpdaterConfigChange hook (mirrors OnWebConfigChange / OnDesktopIntegrationChange), fired after SetUpdaterConfig commits. - main.go wires the hook to push the channel into the live source and start/stop the Schedule goroutine (guarded so flapping the toggle doesn't stack goroutines; apt-managed installs stay dormant). https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/api/service.go | 31 ++++++++++++++++++++++- backend/updater/source.go | 18 ++++++++++++- main.go | 53 ++++++++++++++++++++++++++++++++++----- 3 files changed, 94 insertions(+), 8 deletions(-) diff --git a/backend/api/service.go b/backend/api/service.go index 201ca2a..5e156e8 100644 --- a/backend/api/service.go +++ b/backend/api/service.go @@ -61,6 +61,9 @@ type Service struct { desktopHookMu sync.RWMutex onDesktopChanged func(DesktopIntegrationDTO) + updaterHookMu sync.RWMutex + onUpdaterChanged func(UpdaterConfigDTO) + updater *updater.Updater // may be nil if not yet attached appVersion string installSource updater.InstallSource // "apt" | "appimage" | "manual" @@ -551,7 +554,33 @@ func (s *Service) SetUpdaterConfig(ctx context.Context, c UpdaterConfigDTO) erro if err := s.setBoolSetting(ctx, settingUpdaterEnabled, c.Enabled); err != nil { return err } - return s.settings.Set(ctx, settingUpdaterChannel, c.Channel) + if err := s.settings.Set(ctx, settingUpdaterChannel, c.Channel); err != nil { + return err + } + s.fireUpdaterConfigChanged(s.GetUpdaterConfig(ctx)) + return nil +} + +// OnUpdaterConfigChange registers a synchronous callback invoked after a +// SetUpdaterConfig commit, mirroring OnWebConfigChange / +// OnDesktopIntegrationChange. main.go uses it to push channel changes into +// the live GitHubSource and to start/stop the periodic check goroutine — +// without it, both silently required an app restart. Pass nil to unregister. +// Only one callback is supported. The daemon never registers one (auto-update +// is intentionally not wired there); firing is nil-safe. +func (s *Service) OnUpdaterConfigChange(cb func(UpdaterConfigDTO)) { + s.updaterHookMu.Lock() + s.onUpdaterChanged = cb + s.updaterHookMu.Unlock() +} + +func (s *Service) fireUpdaterConfigChanged(c UpdaterConfigDTO) { + s.updaterHookMu.RLock() + cb := s.onUpdaterChanged + s.updaterHookMu.RUnlock() + if cb != nil { + cb(c) + } } func (s *Service) CheckForUpdate(ctx context.Context) (UpdateInfoDTO, error) { diff --git a/backend/updater/source.go b/backend/updater/source.go index 6c2232a..1a6c3ba 100644 --- a/backend/updater/source.go +++ b/backend/updater/source.go @@ -47,15 +47,27 @@ type GitHubSource struct { Owner string Repo string // Channel is "stable" (default) or "beta"; beta accepts pre-release tags. + // Set at construction; runtime changes must go through SetChannel. Channel string mu sync.Mutex cached *selfupdate.Updater + cachedFor string // Channel the cached updater was built with lastRelease *selfupdate.Release } +// SetChannel switches the release channel at runtime (Settings → Updates). +// The cached *selfupdate.Updater bakes the channel into its Prerelease flag, +// so lazyInit compares cachedFor against Channel and rebuilds on mismatch — +// without this, a channel change silently required an app restart. +func (s *GitHubSource) SetChannel(channel string) { + s.mu.Lock() + defer s.mu.Unlock() + s.Channel = channel +} + func (s *GitHubSource) lazyInit() (*selfupdate.Updater, error) { - if s.cached != nil { + if s.cached != nil && s.cachedFor == s.Channel { return s.cached, nil } src, err := selfupdate.NewGitHubSource(selfupdate.GitHubConfig{}) @@ -99,6 +111,10 @@ func (s *GitHubSource) lazyInit() (*selfupdate.Updater, error) { return nil, fmt.Errorf("new updater: %w", err) } s.cached = u + s.cachedFor = s.Channel + // A release detected under the previous channel may not be offered on + // the new one; force a fresh DetectLatest before any Install. + s.lastRelease = nil return u, nil } diff --git a/main.go b/main.go index 936b514..9c9c7ce 100644 --- a/main.go +++ b/main.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" goruntime "runtime" + "sync" "github.com/rs/zerolog/log" "github.com/wailsapp/wails/v2" @@ -196,13 +197,14 @@ func main() { // Auto-update: GitHub-backed updater, fan out new releases to both the // Wails desktop session and any connected browser sessions. Schedule only // runs the goroutine when the user hasn't disabled checks in Settings. + ghSource := &updater.GitHubSource{ + Owner: "exec", + Repo: "mosaic", + Channel: svc.UpdaterChannel(ctx), + } upd := updater.New(updater.Config{ CurrentVersion: version, - Source: &updater.GitHubSource{ - Owner: "exec", - Repo: "mosaic", - Channel: svc.UpdaterChannel(ctx), - }, + Source: ghSource, OnAvailable: func(info updater.Info) { dto := svc.MakeUpdateInfoDTO(info) if back.Hub != nil { @@ -213,6 +215,31 @@ func main() { }) installSource := updater.DetectInstallSource() svc.AttachUpdater(upd, version, installSource) + // Schedule lifecycle: started/stopped at runtime as the user flips the + // Settings → Updates toggle (via OnUpdaterConfigChange below), not just + // at boot. Guarded so a toggle flapped on/on doesn't stack goroutines. + var ( + schedMu sync.Mutex + schedCancel context.CancelFunc + ) + startSchedule := func() { + schedMu.Lock() + defer schedMu.Unlock() + if schedCancel != nil { + return // already running + } + sctx, cancel := context.WithCancel(ctx) + schedCancel = cancel + go upd.Schedule(sctx) + } + stopSchedule := func() { + schedMu.Lock() + defer schedMu.Unlock() + if schedCancel != nil { + schedCancel() + schedCancel = nil + } + } // Apt-managed installs defer upgrades to apt — running our own // updater on top would either need root to rewrite the dpkg // database (gross), or get clobbered on the next `apt upgrade` @@ -221,8 +248,22 @@ func main() { if installSource == updater.InstallSourceAPT { log.Info().Msg("auto-updater disabled: managed by apt — use `sudo apt upgrade mosaic` for updates") } else if svc.UpdaterEnabled(ctx) { - go upd.Schedule(ctx) + startSchedule() } + // React to Settings → Updates changes without requiring a restart: + // push the channel into the live source (it rebuilds its cached + // go-selfupdate handle on change) and start/stop the periodic check. + svc.OnUpdaterConfigChange(func(c api.UpdaterConfigDTO) { + ghSource.SetChannel(c.Channel) + if installSource == updater.InstallSourceAPT { + return + } + if c.Enabled { + startSchedule() + } else { + stopSchedule() + } + }) // Close-to-tray on Linux/Windows is gated on desktop.tray_enabled + // desktop.close_to_tray. On macOS we set HideWindowOnClose: true below, From fe2ae769674969c4dfb62fd83560998e44fb420a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:46:06 +0000 Subject: [PATCH 26/37] fix(bootstrap): don't persist ephemeral fallback over a configured listen port MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A benign second no-args launch (EarlyForwardLaunchArgs only forwards when args exist; macOS never does) runs bootstrap.Init before Wails's SingleInstanceLock can dispatch it. The engine finds the configured port held by the first instance, falls back to an OS-picked ephemeral, and bootstrap persisted that throwaway port into the shared DB — silently breaking the user's router port-forward for the next launch. Persist the actual-bound port only when no port was configured (listen_port 0 = OS-picked), preserving the original first-run intent of pinning an OS-assigned port. A fallback that differs from an explicitly configured port is now log-only; the configured value is kept so the next start retries it. Also refresh main.go's stale comment claiming port-bind failure is fatal. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/bootstrap/backend.go | 27 +++++++++++++++++++-------- main.go | 15 +++++++++------ 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/backend/bootstrap/backend.go b/backend/bootstrap/backend.go index fcd97b9..7b5b934 100644 --- a/backend/bootstrap/backend.go +++ b/backend/bootstrap/backend.go @@ -141,15 +141,26 @@ func Init(ctx context.Context, cfg Config) (*Backend, func(), error) { } closers = append(closers, func() { _ = anacrolixBackend.Close() }) - // If the configured port was taken and anacrolix fell back to an OS-picked - // ephemeral, persist the actual port. Without this the next launch races - // the same port, loses again, and picks a *different* random — meaning the - // user's router port-forward never sticks across restarts. + // Persist the actual bound port ONLY when no port was configured + // (listenPort 0 = "let the OS pick"): pinning the OS-assigned port on + // first run keeps it stable across restarts so a router port-forward + // can stick. When an explicitly configured port was taken and anacrolix + // fell back to an ephemeral, do NOT persist: the common cause is a + // benign second launch racing the running instance's bind (our + // bootstrap runs before Wails's SingleInstanceLock dispatch), and + // persisting the throwaway port would overwrite the user's chosen port + // in the shared DB — killing their port-forward on the next launch. + // Keeping the configured value means the next start retries it. if actual := anacrolixBackend.ListenPort(); actual > 0 && actual != listenPort { - log.Info().Int("configured", listenPort).Int("actual", actual). - Msg("listen port fell back to OS-picked; persisting for next launch") - if err := settingsDAO.Set(ctx, "peer_listen_port", strconv.Itoa(actual)); err != nil { - log.Warn().Err(err).Msg("persist fallback listen port") + if listenPort == 0 { + log.Info().Int("actual", actual). + Msg("no listen port configured; persisting OS-picked port for next launch") + if err := settingsDAO.Set(ctx, "peer_listen_port", strconv.Itoa(actual)); err != nil { + log.Warn().Err(err).Msg("persist OS-picked listen port") + } + } else { + log.Warn().Int("configured", listenPort).Int("actual", actual). + Msg("configured listen port unavailable; using ephemeral fallback for this run only (configured port kept for next launch)") } } diff --git a/main.go b/main.go index 9c9c7ce..0640282 100644 --- a/main.go +++ b/main.go @@ -37,12 +37,15 @@ var version = "dev" func main() { // On Windows + Linux, when the file manager launches us with a // .torrent path while another Mosaic is already running, we MUST - // forward args + exit before touching anacrolix's listen port - // (port-bind would fail and log.Fatal would kill us before reaching - // the second-instance dispatch). Windows uses Wails's mutex+WM_COPYDATA - // wire; Linux uses our own Unix socket because Wails's D-Bus single- - // instance silently fails on common setups (Wayland, sandboxed - // launchers, missing XDG_RUNTIME_DIR). See + // forward args + exit before touching anacrolix's listen port. A + // failed port-bind is no longer fatal (the engine falls back to an + // OS-picked ephemeral — see backend/engine/anacrolix.go), but a second + // instance that gets that far still opens the shared DB, re-announces + // every torrent, and runs on a throwaway port before Wails's + // SingleInstanceLock can dispatch it. Windows uses Wails's + // mutex+WM_COPYDATA wire; Linux uses our own Unix socket because + // Wails's D-Bus single-instance silently fails on common setups + // (Wayland, sandboxed launchers, missing XDG_RUNTIME_DIR). See // backend/platform/single_instance_*.go. No-op on macOS. if platform.EarlyForwardLaunchArgs("io.github.exec.mosaic") { os.Exit(0) From 635f1cd6bcf9d47240a0af52052a5ab9801462e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:50:41 +0000 Subject: [PATCH 27/37] fix(desktop): make startup context race-free, drain buffered launch args, add shutdown grace Four related lifecycle fixes in the Wails shell: - a.ctx was written by startup() and read unsynchronized from the tray, the Linux second-instance listener, and the updater callback. Publish it under a mutex and route every read through a.context(). - HandleLaunchArgs could run before startup() set the context (the second-instance listener binds before Wails runs); AddMagnet with a nil ctx panicked in a bare goroutine and aborted the process. Args that arrive pre-startup are now buffered and drained by startup(), matching the queueing main.go's comment always promised. - Wails never cancels the OnStartup context, so streamWailsEvents and bootstrap.StreamTicks kept calling the engine/DB while main's deferred cleanup tore them down. The tick goroutines now run on a cancellable child context; the new App.shutdown (wired as OnShutdown) cancels it and sleeps a 200ms grace, mirroring mosaicd. - main.go's log.Fatal after wails.Run skipped all deferred teardown (engine/DB never closed); log the error and return instead. Also gate Wails tick emission on window visibility: while hidden in the tray (close-to-tray hide, StartHidden) the 2Hz list + 1Hz stats/detail snapshots are skipped; ShowWindow/ShowSettings flip the flag back before showing. macOS AppKit-level hide isn't observable, so the flag conservatively stays true there. Seed-limit enforcement lives in bootstrap.StreamTicks and is unaffected. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- app.go | 316 ++++++++++++++++++++++++++++++++++++++------------------ main.go | 46 ++++++--- 2 files changed, 242 insertions(+), 120 deletions(-) diff --git a/app.go b/app.go index fb8c792..62d71f1 100644 --- a/app.go +++ b/app.go @@ -7,6 +7,7 @@ import ( "os/exec" "runtime" "strings" + "sync" "sync/atomic" "time" @@ -26,17 +27,51 @@ import ( type App struct { svc *api.Service hub *remote.Hub // for the per-user tick goroutine started in startup() - ctx context.Context + + // ctxMu guards ctx, cancelTicks, and pendingArgs. ctx is published once + // by startup() (Wails OnStartup) but is read from goroutines that may run + // before or concurrently with it: the Linux second-instance listener, + // tray callbacks, and the updater's OnAvailable. context() is the only + // accessor. Launch args forwarded before startup() are buffered in + // pendingArgs and drained once the context exists. + ctxMu sync.Mutex + ctx context.Context + cancelTicks context.CancelFunc // stops the tick goroutines; see shutdown() + pendingArgs [][]string // quitFully is set by QuitFully so the OnBeforeClose hook in main.go // can distinguish "tray asked us to fully quit" from "user clicked X // while close-to-tray is enabled". Without this the hook would hide // the window every time, including when the tray's Quit was used. quitFully atomic.Bool + + // windowVisible mirrors whether the OS window is currently shown. + // streamWailsEvents skips Wails event emission while it's false (hidden + // in the tray, nobody can see the SPA) to save the 2Hz list + 1Hz + // stats/detail churn. Only the paths we control flip it (close-to-tray + // WindowHide in main.go, tray ShowWindow/ShowSettings, StartHidden); on + // macOS the X button hides at the AppKit layer without telling us, so + // the flag conservatively stays true there. Seed-limit enforcement lives + // in bootstrap.StreamTicks and is never gated by this. + windowVisible atomic.Bool } func NewApp(svc *api.Service, hub *remote.Hub) *App { - return &App{svc: svc, hub: hub} + a := &App{svc: svc, hub: hub} + a.windowVisible.Store(true) + return a +} + +// context returns the startup-published context, or nil before startup(). +func (a *App) context() context.Context { + a.ctxMu.Lock() + defer a.ctxMu.Unlock() + return a.ctx +} + +// setWindowVisible records OS-window visibility; see the field comment. +func (a *App) setWindowVisible(v bool) { + a.windowVisible.Store(v) } func (a *App) startup(ctx context.Context) { @@ -44,12 +79,30 @@ func (a *App) startup(ctx context.Context) { // caller (full access, sees all torrents). Carrying it on a.ctx means all // the a.svc.* calls below inherit it without per-call plumbing; Wails // runtime calls ignore the extra context value. - a.ctx = api.WithCaller(ctx, api.SystemCaller) + ctx = api.WithCaller(ctx, api.SystemCaller) + // The tick goroutines get their own cancellable child: Wails never + // cancels the OnStartup context, so without this they'd keep calling + // the engine/DB while main.go's deferred cleanup tears everything down. + // Cancelled in shutdown(), mirroring mosaicd's cancelCtx + grace sleep + // (see cmd/mosaicd/main.go). + tickCtx, cancelTicks := context.WithCancel(ctx) + a.ctxMu.Lock() + a.ctx = ctx + a.cancelTicks = cancelTicks + pending := a.pendingArgs + a.pendingArgs = nil + a.ctxMu.Unlock() // Two tick goroutines: one drives the embedded SPA via Wails events, // the other drives connected browser clients via the shared per-user // hub stream. The hub goroutine is a no-op when no one is connected. - go a.streamWailsEvents(a.ctx) - go bootstrap.StreamTicks(a.ctx, a.svc, a.hub) + go a.streamWailsEvents(tickCtx) + go bootstrap.StreamTicks(tickCtx, a.svc, a.hub) + // Drain launch args that arrived before the context existed (e.g. a + // file-handler forward from the Linux second-instance listener racing + // boot — main.go binds that listener before Wails runs). + for _, args := range pending { + go a.HandleLaunchArgs(args) + } // macOS routes Finder-clicked .torrent files and browser-clicked magnet: // URLs through Apple Events, not argv. Register NSAppleEventManager // handlers that funnel both into HandleLaunchArgs. No-op on other OSes. @@ -81,16 +134,31 @@ func (a *App) startup(ctx context.Context) { // (Wails or the OS may pass internal flags we don't care about). // Exported so main.go's SingleInstanceLock OnSecondInstanceLaunch can call it. // +// Safe to call before startup(): args forwarded while we're still booting +// (the Linux second-instance listener binds before Wails runs) are buffered +// and drained by startup() once the context exists — calling svc.AddMagnet +// with a nil context here used to panic in a bare goroutine and abort the +// whole process. +// // Each invocation emits a `launch:notice` Wails event with the outcome so the // SPA can toast immediately — useful both as user feedback and as a // diagnostic when file-association routing seems silent. func (a *App) HandleLaunchArgs(args []string) { + a.ctxMu.Lock() + ctx := a.ctx + if ctx == nil { + a.pendingArgs = append(a.pendingArgs, args) + a.ctxMu.Unlock() + log.Info().Strs("args", args).Msg("HandleLaunchArgs: buffered until startup completes") + return + } + a.ctxMu.Unlock() log.Info().Strs("args", args).Msg("HandleLaunchArgs invoked") a.emitLaunchNotice(map[string]any{"event": "received", "count": len(args), "args": args}) for _, arg := range args { switch { case strings.HasPrefix(arg, "magnet:"): - id, err := a.svc.AddMagnet(a.ctx, arg, "") + id, err := a.svc.AddMagnet(ctx, arg, "") if err != nil { log.Warn().Err(err).Msg("launch arg: AddMagnet failed") a.emitLaunchNotice(map[string]any{"event": "magnet_error", "error": err.Error(), "magnet": arg}) @@ -99,7 +167,7 @@ func (a *App) HandleLaunchArgs(args []string) { log.Info().Str("magnet", arg).Str("id", string(id)).Msg("added magnet from launch arg") a.emitLaunchNotice(map[string]any{"event": "magnet_added", "id": string(id)}) case strings.HasSuffix(strings.ToLower(arg), ".torrent"): - id, err := a.svc.AddTorrentFile(a.ctx, arg, "") + id, err := a.svc.AddTorrentFile(ctx, arg, "") if err != nil { log.Warn().Err(err).Str("path", arg).Msg("launch arg: AddTorrentFile failed") a.emitLaunchNotice(map[string]any{"event": "torrent_error", "error": err.Error(), "path": arg}) @@ -114,15 +182,33 @@ func (a *App) HandleLaunchArgs(args []string) { } func (a *App) emitLaunchNotice(payload map[string]any) { - if a.ctx == nil { + ctx := a.context() + if ctx == nil { return } - wailsruntime.EventsEmit(a.ctx, "launch:notice", payload) + wailsruntime.EventsEmit(ctx, "launch:notice", payload) +} + +// shutdown is wired as Wails's OnShutdown hook. It cancels the tick +// goroutines started in startup() and then sleeps a brief grace so an +// in-flight tick can finish (or notice cancellation) before main.go's +// deferred cleanup closes the hub, engine, and DB underneath them — +// the same mitigation mosaicd applies after SIGTERM (cmd/mosaicd/main.go). +func (a *App) shutdown(_ context.Context) { + a.ctxMu.Lock() + cancel := a.cancelTicks + a.cancelTicks = nil + a.ctxMu.Unlock() + if cancel == nil { + return + } + cancel() + time.Sleep(200 * time.Millisecond) } // AddMagnet adds a magnet link. Returns the torrent ID. func (a *App) AddMagnet(magnet, savePath string) (string, error) { - id, err := a.svc.AddMagnet(a.ctx, magnet, savePath) + id, err := a.svc.AddMagnet(a.context(), magnet, savePath) if err != nil { return "", err } @@ -131,14 +217,14 @@ func (a *App) AddMagnet(magnet, savePath string) (string, error) { // ListTorrents returns the current list as DTOs. func (a *App) ListTorrents() ([]api.TorrentDTO, error) { - return a.svc.ListTorrents(a.ctx) + return a.svc.ListTorrents(a.context()) } // PickAndAddTorrent opens a native file dialog, lets the user choose a // .torrent file, and adds it to the engine + persistence. Returns the new // torrent ID, or "" if the user cancelled. func (a *App) PickAndAddTorrent(savePath string) (string, error) { - path, err := wailsruntime.OpenFileDialog(a.ctx, wailsruntime.OpenDialogOptions{ + path, err := wailsruntime.OpenFileDialog(a.context(), wailsruntime.OpenDialogOptions{ Title: "Select .torrent file", Filters: []wailsruntime.FileFilter{ {DisplayName: "Torrent files (*.torrent)", Pattern: "*.torrent"}, @@ -150,7 +236,7 @@ func (a *App) PickAndAddTorrent(savePath string) (string, error) { if path == "" { // user cancelled return "", nil } - id, err := a.svc.AddTorrentFile(a.ctx, path, savePath) + id, err := a.svc.AddTorrentFile(a.context(), path, savePath) if err != nil { return "", err } @@ -158,208 +244,208 @@ func (a *App) PickAndAddTorrent(savePath string) (string, error) { } // Pause/Resume/Remove operate by id. -func (a *App) Pause(id string) error { return a.svc.Pause(a.ctx, engine.TorrentID(id)) } -func (a *App) Resume(id string) error { return a.svc.Resume(a.ctx, engine.TorrentID(id)) } -func (a *App) Recheck(id string) error { return a.svc.Recheck(a.ctx, engine.TorrentID(id)) } +func (a *App) Pause(id string) error { return a.svc.Pause(a.context(), engine.TorrentID(id)) } +func (a *App) Resume(id string) error { return a.svc.Resume(a.context(), engine.TorrentID(id)) } +func (a *App) Recheck(id string) error { return a.svc.Recheck(a.context(), engine.TorrentID(id)) } func (a *App) Remove(id string, deleteFiles bool) error { - return a.svc.Remove(a.ctx, engine.TorrentID(id), deleteFiles) + return a.svc.Remove(a.context(), engine.TorrentID(id), deleteFiles) } func (a *App) GlobalStats() (api.GlobalStats, error) { - return a.svc.GlobalStats(a.ctx) + return a.svc.GlobalStats(a.context()) } // SetInspectorFocus tells the backend the inspector is open on torrent `id` // with `tabs` visible. The next inspector:tick (and subsequent ticks at 1Hz) // will include data scoped to those tabs. func (a *App) SetInspectorFocus(id string, tabs []string) error { - return a.svc.SetInspectorFocus(a.ctx, id, tabs) + return a.svc.SetInspectorFocus(a.context(), id, tabs) } // ClearInspectorFocus stops inspector:tick emission until SetInspectorFocus is called again. func (a *App) ClearInspectorFocus() { - a.svc.ClearInspectorFocus(a.ctx) + a.svc.ClearInspectorFocus(a.context()) } func (a *App) ListCategories() ([]api.CategoryDTO, error) { - return a.svc.ListCategories(a.ctx) + return a.svc.ListCategories(a.context()) } func (a *App) CreateCategory(name, defaultPath, color string) (int, error) { - return a.svc.CreateCategory(a.ctx, name, defaultPath, color) + return a.svc.CreateCategory(a.context(), name, defaultPath, color) } func (a *App) UpdateCategory(id int, name, defaultPath, color string) error { - return a.svc.UpdateCategory(a.ctx, id, name, defaultPath, color) + return a.svc.UpdateCategory(a.context(), id, name, defaultPath, color) } func (a *App) DeleteCategory(id int) error { - return a.svc.DeleteCategory(a.ctx, id) + return a.svc.DeleteCategory(a.context(), id) } func (a *App) ListTags() ([]api.TagDTO, error) { - return a.svc.ListTags(a.ctx) + return a.svc.ListTags(a.context()) } func (a *App) CreateTag(name, color string) (int, error) { - return a.svc.CreateTag(a.ctx, name, color) + return a.svc.CreateTag(a.context(), name, color) } func (a *App) DeleteTag(id int) error { - return a.svc.DeleteTag(a.ctx, id) + return a.svc.DeleteTag(a.context(), id) } func (a *App) AssignTag(infohash string, tagID int) error { - return a.svc.AssignTag(a.ctx, infohash, tagID) + return a.svc.AssignTag(a.context(), infohash, tagID) } func (a *App) UnassignTag(infohash string, tagID int) error { - return a.svc.UnassignTag(a.ctx, infohash, tagID) + return a.svc.UnassignTag(a.context(), infohash, tagID) } func (a *App) SetTorrentCategory(infohash string, categoryID *int) error { - return a.svc.SetTorrentCategory(a.ctx, infohash, categoryID) + return a.svc.SetTorrentCategory(a.context(), infohash, categoryID) } func (a *App) SetFilePriorities(infohash string, prios map[int]string) error { - return a.svc.SetFilePriorities(a.ctx, infohash, prios) + return a.svc.SetFilePriorities(a.context(), infohash, prios) } func (a *App) AddTracker(infohash, trackerURL string) error { - return a.svc.AddTracker(a.ctx, infohash, trackerURL) + return a.svc.AddTracker(a.context(), infohash, trackerURL) } func (a *App) RemoveTracker(infohash, trackerURL string) error { - return a.svc.RemoveTracker(a.ctx, infohash, trackerURL) + return a.svc.RemoveTracker(a.context(), infohash, trackerURL) } func (a *App) GetDefaultSavePath() (string, error) { - return a.svc.GetDefaultSavePath(a.ctx) + return a.svc.GetDefaultSavePath(a.context()) } func (a *App) SetDefaultSavePath(path string) error { - return a.svc.SetDefaultSavePath(a.ctx, path) + return a.svc.SetDefaultSavePath(a.context(), path) } func (a *App) AddTorrentBytes(blob []byte, savePath string) (string, error) { - id, err := a.svc.AddTorrentBytes(a.ctx, blob, savePath) + id, err := a.svc.AddTorrentBytes(a.context(), blob, savePath) if err != nil { return "", err } return string(id), nil } -func (a *App) GetLimits() (api.LimitsDTO, error) { return a.svc.GetLimits(a.ctx) } -func (a *App) SetLimits(l api.LimitsDTO) error { return a.svc.SetLimits(a.ctx, l) } -func (a *App) ToggleAltSpeed() (bool, error) { return a.svc.ToggleAltSpeed(a.ctx) } +func (a *App) GetLimits() (api.LimitsDTO, error) { return a.svc.GetLimits(a.context()) } +func (a *App) SetLimits(l api.LimitsDTO) error { return a.svc.SetLimits(a.context(), l) } +func (a *App) ToggleAltSpeed() (bool, error) { return a.svc.ToggleAltSpeed(a.context()) } -func (a *App) GetQueueLimits() api.QueueLimitsDTO { return a.svc.GetQueueLimits(a.ctx) } -func (a *App) SetQueueLimits(q api.QueueLimitsDTO) error { return a.svc.SetQueueLimits(a.ctx, q) } +func (a *App) GetQueueLimits() api.QueueLimitsDTO { return a.svc.GetQueueLimits(a.context()) } +func (a *App) SetQueueLimits(q api.QueueLimitsDTO) error { return a.svc.SetQueueLimits(a.context(), q) } -func (a *App) GetPeerLimits() api.PeerLimitsDTO { return a.svc.GetPeerLimits(a.ctx) } -func (a *App) SetPeerLimits(p api.PeerLimitsDTO) error { return a.svc.SetPeerLimits(a.ctx, p) } +func (a *App) GetPeerLimits() api.PeerLimitsDTO { return a.svc.GetPeerLimits(a.context()) } +func (a *App) SetPeerLimits(p api.PeerLimitsDTO) error { return a.svc.SetPeerLimits(a.context(), p) } func (a *App) SetQueuePosition(infohash string, pos int) error { - return a.svc.SetQueuePosition(a.ctx, infohash, pos) + return a.svc.SetQueuePosition(a.context(), infohash, pos) } func (a *App) SetForceStart(infohash string, force bool) error { - return a.svc.SetForceStart(a.ctx, infohash, force) + return a.svc.SetForceStart(a.context(), infohash, force) } func (a *App) SetSequential(infohash string, enabled bool) error { - return a.svc.SetSequential(a.ctx, infohash, enabled) + return a.svc.SetSequential(a.context(), infohash, enabled) } func (a *App) ListScheduleRules() ([]api.ScheduleRuleDTO, error) { - return a.svc.ListScheduleRules(a.ctx) + return a.svc.ListScheduleRules(a.context()) } func (a *App) CreateScheduleRule(r api.ScheduleRuleDTO) (int, error) { - return a.svc.CreateScheduleRule(a.ctx, r) + return a.svc.CreateScheduleRule(a.context(), r) } func (a *App) UpdateScheduleRule(r api.ScheduleRuleDTO) error { - return a.svc.UpdateScheduleRule(a.ctx, r) + return a.svc.UpdateScheduleRule(a.context(), r) } func (a *App) DeleteScheduleRule(id int) error { - return a.svc.DeleteScheduleRule(a.ctx, id) + return a.svc.DeleteScheduleRule(a.context(), id) } func (a *App) GetBlocklist() api.BlocklistDTO { - return a.svc.GetBlocklist(a.ctx) + return a.svc.GetBlocklist(a.context()) } func (a *App) SetBlocklistURL(url string, enabled bool) error { - return a.svc.SetBlocklistURL(a.ctx, url, enabled) + return a.svc.SetBlocklistURL(a.context(), url, enabled) } func (a *App) RefreshBlocklist() error { - return a.svc.RefreshBlocklist(a.ctx) + return a.svc.RefreshBlocklist(a.context()) } func (a *App) ListFeeds() ([]api.FeedDTO, error) { - return a.svc.ListFeeds(a.ctx) + return a.svc.ListFeeds(a.context()) } func (a *App) CreateFeed(f api.FeedDTO) (int, error) { - return a.svc.CreateFeed(a.ctx, f) + return a.svc.CreateFeed(a.context(), f) } func (a *App) UpdateFeed(f api.FeedDTO) error { - return a.svc.UpdateFeed(a.ctx, f) + return a.svc.UpdateFeed(a.context(), f) } func (a *App) DeleteFeed(id int) error { - return a.svc.DeleteFeed(a.ctx, id) + return a.svc.DeleteFeed(a.context(), id) } // PollFeedNow polls a single RSS feed immediately, bypassing its // scheduled interval. Surfaced by the SPA's per-row refresh icon. func (a *App) PollFeedNow(id int) error { - return a.svc.PollFeedNow(a.ctx, id) + return a.svc.PollFeedNow(a.context(), id) } func (a *App) GetFeedItems(feedID int) ([]api.FeedItemDTO, error) { - return a.svc.GetFeedItems(a.ctx, feedID) + return a.svc.GetFeedItems(a.context(), feedID) } func (a *App) AddFeedItem(torrentURL, savePath string) error { - _, err := a.svc.AddFeedItem(a.ctx, torrentURL, savePath) + _, err := a.svc.AddFeedItem(a.context(), torrentURL, savePath) return err } func (a *App) ListFiltersByFeed(feedID int) ([]api.FilterDTO, error) { - return a.svc.ListFiltersByFeed(a.ctx, feedID) + return a.svc.ListFiltersByFeed(a.context(), feedID) } func (a *App) CreateFilter(f api.FilterDTO) (int, error) { - return a.svc.CreateFilter(a.ctx, f) + return a.svc.CreateFilter(a.context(), f) } func (a *App) UpdateFilter(f api.FilterDTO) error { - return a.svc.UpdateFilter(a.ctx, f) + return a.svc.UpdateFilter(a.context(), f) } func (a *App) DeleteFilter(id int) error { - return a.svc.DeleteFilter(a.ctx, id) + return a.svc.DeleteFilter(a.context(), id) } func (a *App) GetWebConfig() api.WebConfigDTO { - return a.svc.GetWebConfig(a.ctx) + return a.svc.GetWebConfig(a.context()) } func (a *App) SetWebConfig(c api.WebConfigDTO) error { - return a.svc.SetWebConfig(a.ctx, c) + return a.svc.SetWebConfig(a.context(), c) } func (a *App) SetWebPassword(plain string) error { - return a.svc.SetWebPassword(a.ctx, plain) + return a.svc.SetWebPassword(a.context(), plain) } func (a *App) RotateAPIKey() (string, error) { - return a.svc.RotateAPIKey(a.ctx) + return a.svc.RotateAPIKey(a.context()) } // AppVersion returns the build-time version string (e.g. "v0.7.0" or "dev"). @@ -371,25 +457,25 @@ func (a *App) AppVersion() string { // the system-tray + close-to-tray + Settings UI depend on. The DTO field names // are part of the wire contract with the frontend (see api.DesktopIntegrationDTO). func (a *App) GetDesktopIntegration() api.DesktopIntegrationDTO { - return a.svc.GetDesktopIntegration(a.ctx) + return a.svc.GetDesktopIntegration(a.context()) } func (a *App) SetDesktopIntegration(c api.DesktopIntegrationDTO) error { - return a.svc.SetDesktopIntegration(a.ctx, c) + return a.svc.SetDesktopIntegration(a.context(), c) } func (a *App) GetWatchFolder() api.WatchFolderDTO { - return a.svc.GetWatchFolder(a.ctx) + return a.svc.GetWatchFolder(a.context()) } func (a *App) SetWatchFolder(c api.WatchFolderDTO) error { - return a.svc.SetWatchFolder(a.ctx, c) + return a.svc.SetWatchFolder(a.context(), c) } // PickWatchFolder opens a native directory dialog so the user can choose a // watch folder path. Returns the selected path or "" if cancelled. func (a *App) PickWatchFolder() (string, error) { - return wailsruntime.OpenDirectoryDialog(a.ctx, wailsruntime.OpenDialogOptions{ + return wailsruntime.OpenDirectoryDialog(a.context(), wailsruntime.OpenDialogOptions{ Title: "Select Watch Folder", }) } @@ -399,11 +485,12 @@ func (a *App) PickWatchFolder() (string, error) { // hook would just hide the window again, leaving the app un-quit-able from // the tray. func (a *App) QuitFully() { - if a.ctx == nil { + ctx := a.context() + if ctx == nil { return } a.quitFully.Store(true) - wailsruntime.Quit(a.ctx) + wailsruntime.Quit(ctx) } // QuittingFully reports whether the most recent quit request was from @@ -416,49 +503,54 @@ func (a *App) QuittingFully() bool { // ShowWindow is the tray "Show Mosaic" callback target — un-minimize and // raise the window. Safe to call before startup() (no-ops if ctx is nil). func (a *App) ShowWindow() { - if a.ctx == nil { + ctx := a.context() + if ctx == nil { return } - wailsruntime.WindowUnminimise(a.ctx) - wailsruntime.WindowShow(a.ctx) + a.setWindowVisible(true) + wailsruntime.WindowUnminimise(ctx) + wailsruntime.WindowShow(ctx) } // ShowSettings raises the window AND emits navigate:settings so the SPA can // route to the Settings pane. Used by the tray's "Settings…" item. func (a *App) ShowSettings() { - if a.ctx == nil { + ctx := a.context() + if ctx == nil { return } - wailsruntime.WindowUnminimise(a.ctx) - wailsruntime.WindowShow(a.ctx) - wailsruntime.EventsEmit(a.ctx, "navigate:settings") + a.setWindowVisible(true) + wailsruntime.WindowUnminimise(ctx) + wailsruntime.WindowShow(ctx) + wailsruntime.EventsEmit(ctx, "navigate:settings") } func (a *App) GetUpdaterConfig() api.UpdaterConfigDTO { - return a.svc.GetUpdaterConfig(a.ctx) + return a.svc.GetUpdaterConfig(a.context()) } func (a *App) SetUpdaterConfig(c api.UpdaterConfigDTO) error { - return a.svc.SetUpdaterConfig(a.ctx, c) + return a.svc.SetUpdaterConfig(a.context(), c) } func (a *App) CheckForUpdate() (api.UpdateInfoDTO, error) { - return a.svc.CheckForUpdate(a.ctx) + return a.svc.CheckForUpdate(a.context()) } func (a *App) InstallUpdate() error { - return a.svc.InstallUpdate(a.ctx) + return a.svc.InstallUpdate(a.context()) } // NotifyUpdateAvailable emits the Wails-side `update:available` event so the // desktop SPA can render its toast. Called from main.go's updater OnAvailable // callback, off the updater goroutine; safe to invoke before startup() has -// run (a.ctx may be nil) — emission is silently skipped in that case. +// run (the context may be nil) — emission is silently skipped in that case. func (a *App) NotifyUpdateAvailable(info api.UpdateInfoDTO) { - if a.ctx == nil { + ctx := a.context() + if ctx == nil { return } - wailsruntime.EventsEmit(a.ctx, "update:available", info) + wailsruntime.EventsEmit(ctx, "update:available", info) } // Platform returns the OS the desktop shell is running on ("darwin", "windows", @@ -482,10 +574,10 @@ func (a *App) GnomeTrayStatus() string { if runtime.GOOS != "linux" { return string(tray.GnomePromptStatusNotApplicable) } - if a.svc.IsGnomeAppIndicatorPromptDismissed(a.ctx) { + if a.svc.IsGnomeAppIndicatorPromptDismissed(a.context()) { return string(tray.GnomePromptStatusNotApplicable) } - return string(tray.EvaluateGnomePromptStatus(a.ctx)) + return string(tray.EvaluateGnomePromptStatus(a.context())) } // EnableGnomeTray flips the dconf key that gnome-shell reads at startup @@ -500,7 +592,7 @@ func (a *App) EnableGnomeTray() error { if !tray.IsGnomeSession() { return fmt.Errorf("EnableGnomeTray: not a Gnome session") } - return tray.EnableAppIndicatorExtension(a.ctx) + return tray.EnableAppIndicatorExtension(a.context()) } // DismissGnomeTrayPrompt persists the user's "don't show this again" @@ -508,32 +600,35 @@ func (a *App) EnableGnomeTray() error { // setting (we don't surface a UI for that yet — re-installing the deb // also doesn't clear it, by design). func (a *App) DismissGnomeTrayPrompt() error { - return a.svc.DismissGnomeAppIndicatorPrompt(a.ctx) + return a.svc.DismissGnomeAppIndicatorPrompt(a.context()) } // WindowMinimise minimizes the desktop window. func (a *App) WindowMinimise() { - if a.ctx == nil { + ctx := a.context() + if ctx == nil { return } - wailsruntime.WindowMinimise(a.ctx) + wailsruntime.WindowMinimise(ctx) } // WindowMaximise toggles between maximized and restored states. func (a *App) WindowMaximise() { - if a.ctx == nil { + ctx := a.context() + if ctx == nil { return } - wailsruntime.WindowToggleMaximise(a.ctx) + wailsruntime.WindowToggleMaximise(ctx) } // WindowClose quits the app. Single-window desktop convention: closing the // only window terminates the process. func (a *App) WindowClose() { - if a.ctx == nil { + ctx := a.context() + if ctx == nil { return } - wailsruntime.Quit(a.ctx) + wailsruntime.Quit(ctx) } // OpenFolder reveals the given path in the OS file manager. Desktop-only — @@ -556,22 +651,22 @@ func (a *App) OpenFolder(path string) error { // GetSeedingDefaults returns global seeding stop-condition defaults. func (a *App) GetSeedingDefaults() api.SeedingDefaultsDTO { - return a.svc.GetSeedingDefaults(a.ctx) + return a.svc.GetSeedingDefaults(a.context()) } // SetSeedingDefaults persists global seeding stop-condition defaults. func (a *App) SetSeedingDefaults(d api.SeedingDefaultsDTO) error { - return a.svc.SetSeedingDefaults(a.ctx, d) + return a.svc.SetSeedingDefaults(a.context(), d) } // GetTorrentSeedPolicy returns the per-torrent seed policy override. func (a *App) GetTorrentSeedPolicy(infohash string) (api.SeedPolicyDTO, error) { - return a.svc.GetTorrentSeedPolicy(a.ctx, infohash) + return a.svc.GetTorrentSeedPolicy(a.context(), infohash) } // SetTorrentSeedPolicy sets (or clears) the per-torrent seed policy override. func (a *App) SetTorrentSeedPolicy(infohash string, p api.SeedPolicyDTO) error { - return a.svc.SetTorrentSeedPolicy(a.ctx, infohash, p) + return a.svc.SetTorrentSeedPolicy(a.context(), infohash, p) } // streamWailsEvents emits state snapshots to the embedded SPA via Wails @@ -579,6 +674,12 @@ func (a *App) SetTorrentSeedPolicy(infohash string, p api.SeedPolicyDTO) error { // this one in startup(), handles the per-user hub fan-out for connected // browser clients — and also owns the periodic seed-limit enforcement // (CheckSeedLimits), so it runs in the daemon too and never twice here. +// +// While the window is hidden in the tray (windowVisible false) the emission +// work is skipped entirely — nobody can see the SPA, so the 2Hz list + 1Hz +// stats/detail snapshots are pure waste. The flag flips back before the +// window is shown again, so at most one tick interval of staleness is +// visible on restore. func (a *App) streamWailsEvents(ctx context.Context) { torrents := time.NewTicker(500 * time.Millisecond) stats := time.NewTicker(1 * time.Second) @@ -591,6 +692,9 @@ func (a *App) streamWailsEvents(ctx context.Context) { case <-ctx.Done(): return case <-torrents.C: + if !a.windowVisible.Load() { + continue + } rows, err := a.svc.ListTorrents(ctx) if err != nil { log.Error().Err(err).Msg("list torrents during tick") @@ -598,6 +702,9 @@ func (a *App) streamWailsEvents(ctx context.Context) { } wailsruntime.EventsEmit(ctx, "torrents:tick", rows) case <-stats.C: + if !a.windowVisible.Load() { + continue + } s, err := a.svc.GlobalStats(ctx) if err != nil { log.Error().Err(err).Msg("global stats during tick") @@ -605,6 +712,9 @@ func (a *App) streamWailsEvents(ctx context.Context) { } wailsruntime.EventsEmit(ctx, "stats:tick", s) case <-inspector.C: + if !a.windowVisible.Load() { + continue + } detail, err := a.svc.DetailForFocus(ctx) if err != nil { log.Error().Err(err).Msg("detail for focus during tick") diff --git a/main.go b/main.go index 0640282..3eb7705 100644 --- a/main.go +++ b/main.go @@ -293,21 +293,30 @@ func main() { if !trayAvailable { return false } - if app.ctx != nil { - wailsruntime.WindowHide(app.ctx) + if hideCtx := app.context(); hideCtx != nil { + // Mark hidden BEFORE hiding so streamWailsEvents stops emitting + // tick events nobody can see; ShowWindow flips it back. + app.setWindowVisible(false) + wailsruntime.WindowHide(hideCtx) } return true } + // StartHidden honors the desktop.start_minimized preference. The + // frontend still mounts and connects to the WS / fetches state on + // load — only the OS window is hidden until the user opens it from + // the tray. + startHidden := desktopCfg.StartMinimized && desktopCfg.TrayEnabled && trayAvailable && goruntime.GOOS != "darwin" + if startHidden { + // Suppress Wails tick emission until the tray shows the window. + app.setWindowVisible(false) + } + opts := &options.App{ - Title: "Mosaic", - Width: 1200, - Height: 800, - // StartHidden honors the desktop.start_minimized preference. The - // frontend still mounts and connects to the WS / fetches state on - // load — only the OS window is hidden until the user opens it from - // the tray. - StartHidden: desktopCfg.StartMinimized && desktopCfg.TrayEnabled && trayAvailable && goruntime.GOOS != "darwin", + Title: "Mosaic", + Width: 1200, + Height: 800, + StartHidden: startHidden, // On macOS, X button hides the app (Cmd+H equivalent) at the AppKit // layer instead of triggering OnBeforeClose. Dock-click auto-unhides. // Cmd+Q and dock right-click → Quit still terminate cleanly via the @@ -339,14 +348,15 @@ func main() { SingleInstanceLock: &options.SingleInstanceLock{ UniqueId: "io.github.exec.mosaic", OnSecondInstanceLaunch: func(d options.SecondInstanceData) { - if app.ctx != nil { - wailsruntime.WindowUnminimise(app.ctx) - wailsruntime.WindowShow(app.ctx) - } + app.ShowWindow() go app.HandleLaunchArgs(d.Args) }, }, OnStartup: app.startup, + // OnShutdown cancels the tick goroutines and grants a short grace so + // in-flight ticks drain before the deferred cleanup above closes the + // hub/engine/DB they're reading — see App.shutdown. + OnShutdown: app.shutdown, Bind: []any{ app, }, @@ -357,8 +367,10 @@ func main() { if goruntime.GOOS == "windows" || goruntime.GOOS == "linux" { opts.Frameless = true } - err = wails.Run(opts) - if err != nil { - log.Fatal().Err(err).Msg("wails run") + // log.Fatal would os.Exit and skip every deferred teardown above + // (engine, DB, tray, listener) — log the error and fall off main so + // the defers run. + if err := wails.Run(opts); err != nil { + log.Error().Err(err).Msg("wails run") } } From 5b307d49704df3a837586782b0998dc1fc92837a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:51:45 +0000 Subject: [PATCH 28/37] fix(config): reject unknown YAML keys, out-of-range ports, and missing home dir - Unknown YAML keys were silently ignored, so a typo'd key (e.g. listen-port) silently fell back to defaults. Decode with KnownFields(true) so typos fail loudly, consistent with corrupt YAML already being fatal. Empty/comment-only files still load defaults. - listen_port accepted any int; validate the merged result (YAML + env) to [0, 65535], mirroring mosaicd's --port flag validation. - defaults() ignored the os.UserHomeDir error, producing a CWD-relative "Downloads" save path. Leave the default empty on error and fail Load with a clear message unless YAML/env supplies default_save_path. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/config/config.go | 33 +++++++++++++--- backend/config/config_test.go | 73 +++++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+), 5 deletions(-) diff --git a/backend/config/config.go b/backend/config/config.go index 4e45541..305996c 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -1,8 +1,10 @@ package config import ( + "bytes" "errors" "fmt" + "io" "io/fs" "os" "path/filepath" @@ -20,23 +22,35 @@ type Config struct { } func defaults() Config { - home, _ := os.UserHomeDir() - return Config{ + cfg := Config{ ListenPort: 6881, - DefaultSavePath: filepath.Join(home, "Downloads"), EnableDHT: true, EnableEncryption: true, } + // os.UserHomeDir fails when $HOME is unset (stripped-down service + // environments, odd launchers). Joining "" with "Downloads" would yield + // a CWD-relative path that scatters downloads wherever the process + // happened to start; leave the default empty instead and let Load fail + // loudly if neither YAML nor env supplies a path. + if home, err := os.UserHomeDir(); err == nil { + cfg.DefaultSavePath = filepath.Join(home, "Downloads") + } + return cfg } // Load returns config built from defaults, then overlaid with the YAML file at // `path` (if it exists), then overlaid with env vars (prefix MOSAIC_). -// Missing files are not an error. +// Missing files are not an error; unknown YAML keys and out-of-range values +// are (a typo'd key silently falling back to defaults is worse than a +// startup failure — consistent with corrupt YAML already being fatal). func Load(path string) (Config, error) { cfg := defaults() if data, err := os.ReadFile(path); err == nil { - if err := yaml.Unmarshal(data, &cfg); err != nil { + dec := yaml.NewDecoder(bytes.NewReader(data)) + dec.KnownFields(true) + // io.EOF means the file is empty (or only comments) — keep defaults. + if err := dec.Decode(&cfg); err != nil && !errors.Is(err, io.EOF) { return cfg, fmt.Errorf("parse config %s: %w", path, err) } } else if !errors.Is(err, fs.ErrNotExist) { @@ -60,5 +74,14 @@ func Load(path string) (Config, error) { cfg.EnableEncryption = v == "true" || v == "1" } + // Validate the merged result (defaults + YAML + env). Mirrors mosaicd's + // --port flag validation; 0 means "let the OS pick". + if cfg.ListenPort < 0 || cfg.ListenPort > 65535 { + return cfg, fmt.Errorf("listen_port must be between 0 and 65535 (got %d)", cfg.ListenPort) + } + if cfg.DefaultSavePath == "" { + return cfg, errors.New("no default save path: home directory could not be resolved — set default_save_path in mosaic.yaml or MOSAIC_DEFAULT_SAVE_PATH") + } + return cfg, nil } diff --git a/backend/config/config_test.go b/backend/config/config_test.go index e9709c5..865330c 100644 --- a/backend/config/config_test.go +++ b/backend/config/config_test.go @@ -49,3 +49,76 @@ func TestLoad_EnvOverridesFile(t *testing.T) { require.Equal(t, 9999, cfg.ListenPort) } + +func TestLoad_UnknownYAMLKeyFails(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "mosaic.yaml") + // "listen-port" is a typo of "listen_port" — must fail loudly rather + // than silently keeping the default. + require.NoError(t, os.WriteFile(path, []byte(`listen-port: 51413`), 0o644)) + + _, err := Load(path) + require.Error(t, err) + require.Contains(t, err.Error(), "listen-port") +} + +func TestLoad_EmptyFileKeepsDefaults(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "mosaic.yaml") + require.NoError(t, os.WriteFile(path, []byte("# comments only\n"), 0o644)) + + cfg, err := Load(path) + require.NoError(t, err) + require.Equal(t, 6881, cfg.ListenPort) +} + +func TestLoad_ListenPortRangeValidated(t *testing.T) { + for _, tc := range []struct { + name string + yaml string + env string + ok bool + }{ + {name: "negative yaml", yaml: "listen_port: -1", ok: false}, + {name: "too large yaml", yaml: "listen_port: 65536", ok: false}, + {name: "too large env", env: "70000", ok: false}, + {name: "zero means OS-picked", yaml: "listen_port: 0", ok: true}, + {name: "max valid", yaml: "listen_port: 65535", ok: true}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "mosaic.yaml") + if tc.yaml != "" { + require.NoError(t, os.WriteFile(path, []byte(tc.yaml), 0o644)) + } + if tc.env != "" { + t.Setenv("MOSAIC_LISTEN_PORT", tc.env) + } + _, err := Load(path) + if tc.ok { + require.NoError(t, err) + } else { + require.Error(t, err) + require.Contains(t, err.Error(), "listen_port") + } + }) + } +} + +func TestLoad_NoHomeDirFailsWithoutConfiguredSavePath(t *testing.T) { + // With $HOME unset os.UserHomeDir errors; the old code silently fell + // back to a CWD-relative "Downloads". Now it must fail loudly... + t.Setenv("HOME", "") + dir := t.TempDir() + + _, err := Load(filepath.Join(dir, "missing.yaml")) + require.Error(t, err) + require.Contains(t, err.Error(), "default_save_path") + + // ...unless the config (or env) supplies a save path explicitly. + path := filepath.Join(dir, "mosaic.yaml") + require.NoError(t, os.WriteFile(path, []byte(`default_save_path: /srv/dl`), 0o644)) + cfg, err := Load(path) + require.NoError(t, err) + require.Equal(t, "/srv/dl", cfg.DefaultSavePath) +} From 44cad21d262a360ccd121e67ea446e422d7c61ad Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 16:52:36 +0000 Subject: [PATCH 29/37] fix(platform): harden Linux single-instance socket dir and stale-bind race - /tmp fallback dir (/tmp/mosaic-, used when XDG_RUNTIME_DIR is unset): MkdirAll accepts a pre-existing path, which another local user could have planted to hijack or eavesdrop on the socket. After MkdirAll, Lstat and require a real directory owned by the current UID with no group/other permission bits, else error out. - Stale-socket recovery raced: two simultaneous starters could both probe-fail and Remove, with the bind loser giving up permanently. Loop the bind/probe/remove sequence up to 3 times so the loser re-probes the (now live) winner or binds the freed path. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/platform/single_instance_linux.go | 94 +++++++++++++++++------ 1 file changed, 71 insertions(+), 23 deletions(-) diff --git a/backend/platform/single_instance_linux.go b/backend/platform/single_instance_linux.go index 9374263..7782220 100644 --- a/backend/platform/single_instance_linux.go +++ b/backend/platform/single_instance_linux.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "io" + "io/fs" "net" "os" "path/filepath" @@ -118,6 +119,17 @@ func StartSecondInstanceListener(uniqueId string, onArgs func(args []string)) er if err := os.MkdirAll(filepath.Dir(socketPath), 0o700); err != nil { return fmt.Errorf("create socket dir: %w", err) } + // When XDG_RUNTIME_DIR is unset, the socket dir is the world-writable + // /tmp fallback (/tmp/mosaic-) — MkdirAll happily accepts a + // pre-existing directory, which another local user could have planted + // (symlink, wrong owner, loose mode) to hijack or eavesdrop on the + // socket. Verify before binding. XDG_RUNTIME_DIR itself is created by + // systemd-logind with the right ownership, so it's left alone. + if os.Getenv("XDG_RUNTIME_DIR") == "" { + if err := verifyPrivateDir(filepath.Dir(socketPath)); err != nil { + return fmt.Errorf("socket dir %s: %w", filepath.Dir(socketPath), err) + } + } listener, err := bindSingleInstanceSocket(socketPath) if err != nil { @@ -155,32 +167,68 @@ var ( registeredCleanupSocket string ) +// verifyPrivateDir checks that path is a real directory (not a symlink) +// owned by the current user with no group/other permission bits. Guards the +// /tmp fallback socket dir against a pre-planted attacker-owned path. +func verifyPrivateDir(path string) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + if !info.IsDir() { + return fmt.Errorf("not a directory (mode %v) — possible squatting, refusing to use it", info.Mode()) + } + st, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return errors.New("cannot determine directory owner") + } + if int(st.Uid) != os.Getuid() { + return fmt.Errorf("owned by uid %d, not us (uid %d) — refusing to use it", st.Uid, os.Getuid()) + } + if perm := info.Mode().Perm(); perm&0o077 != 0 { + return fmt.Errorf("mode %#o is accessible to other users (want 0700) — refusing to use it", perm) + } + return nil +} + // bindSingleInstanceSocket binds the socket, recovering from a stale socket // file left by a crashed previous owner. Returns the listener. +// +// The probe → remove → re-bind sequence is raced when two instances start +// simultaneously: both can probe-fail the same stale socket, both Remove, +// and the bind loser would give up even though the winner is now live (or +// the path is simply free again). Loop a few times so the loser re-probes — +// on the next pass it either connects to the winner (clean "owned by other +// instance" error) or binds the freed path itself. func bindSingleInstanceSocket(socketPath string) (net.Listener, error) { - listener, err := net.Listen("unix", socketPath) - if err == nil { - return listener, nil - } - // EADDRINUSE: someone bound this path. Probe by connecting — if we can, - // a real first instance exists (this code path means EarlyForwardLaunchArgs - // missed it, e.g. no args were passed). If we can't, the socket is stale. - if !errors.Is(err, syscall.EADDRINUSE) { - return nil, err - } - probe, probeErr := net.DialTimeout("unix", socketPath, connectTimeout) - if probeErr == nil { - _ = probe.Close() - // A live owner exists. The caller can still run as a "logical first - // instance" of its own UI, but we won't be able to receive forwarded - // args. Surface the conflict so the caller can decide. - return nil, fmt.Errorf("another mosaic instance owns %s", socketPath) - } - // Stale socket — remove and retry once. - if rmErr := os.Remove(socketPath); rmErr != nil { - return nil, fmt.Errorf("remove stale socket %s: %w", socketPath, rmErr) - } - return net.Listen("unix", socketPath) + var lastErr error + for attempt := 0; attempt < 3; attempt++ { + listener, err := net.Listen("unix", socketPath) + if err == nil { + return listener, nil + } + // EADDRINUSE: someone bound this path. Probe by connecting — if we can, + // a real first instance exists (this code path means EarlyForwardLaunchArgs + // missed it, e.g. no args were passed). If we can't, the socket is stale. + if !errors.Is(err, syscall.EADDRINUSE) { + return nil, err + } + lastErr = err + probe, probeErr := net.DialTimeout("unix", socketPath, connectTimeout) + if probeErr == nil { + _ = probe.Close() + // A live owner exists. The caller can still run as a "logical first + // instance" of its own UI, but we won't be able to receive forwarded + // args. Surface the conflict so the caller can decide. + return nil, fmt.Errorf("another mosaic instance owns %s", socketPath) + } + // Stale socket — remove and loop back to retry the bind. A concurrent + // starter may have removed it first; that's fine. + if rmErr := os.Remove(socketPath); rmErr != nil && !errors.Is(rmErr, fs.ErrNotExist) { + return nil, fmt.Errorf("remove stale socket %s: %w", socketPath, rmErr) + } + } + return nil, fmt.Errorf("gave up after repeated bind races: %w", lastErr) } func acceptSecondInstances(listener net.Listener, out chan<- []string) { From 3ebe27012eaddbf08418d47c86293334e1ddbdc2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 20:03:41 +0000 Subject: [PATCH 30/37] fix(daemon): force-exit on a second SIGINT/SIGTERM during teardown If engine/DB shutdown hangs after the first signal, further signals were silently swallowed by the buffered channel, leaving a foreground operator no way out short of SIGKILL. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- cmd/mosaicd/main.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/cmd/mosaicd/main.go b/cmd/mosaicd/main.go index 62b66ad..d9bcc7b 100644 --- a/cmd/mosaicd/main.go +++ b/cmd/mosaicd/main.go @@ -236,6 +236,14 @@ func main() { stop := make(chan os.Signal, 1) signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM) sig := <-stop + // A second SIGINT/SIGTERM during teardown force-exits. If engine or DB + // shutdown ever hangs, a foreground operator shouldn't have to reach for + // SIGKILL — at that point skipping the remaining defers is the lesser evil. + go func() { + s := <-stop + log.Warn().Str("signal", s.String()).Msg("mosaicd: second signal, forcing exit") + os.Exit(1) + }() cancelCtx() // Brief grace so the StreamTicks goroutine sees ctx.Done before the // deferred cleanup() starts tearing down the hub + DB underneath it. From b9349225cd73ab0194d2a80be31c9de60cb87424 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 20:14:38 +0000 Subject: [PATCH 31/37] fix(engine): honor user peer cap on resume, dedupe snapshot saves, fix per-peer rate and limiter races MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four related anacrolix backend fixes: - Resume and ScheduledPause's re-enable path hardcoded SetMaxEstablishedConns(80), resetting a user's configured MaxPeersPerTorrent on any pause/resume or scheduler churn. The cap now lives in an atomic on the backend (initialized from config, updated by ApplyPerTorrentMaxPeers) and both paths restore it; the stale comment claiming "resuming will pick up the new cap" is fixed. - Per-peer rate sampling in DetailedSnapshot shared one prev-sample map across all consumers, so two back-to-back callers (two web users focused on the same torrent) saw dt of microseconds and zero/spiking rates — the same multi-reader hazard the torrent-level sampler already fixed. Per-peer rates only matter while a Peers tab is focused, so a central sampler would burn cycles when nobody is looking; instead a 250ms minimum-dt guard reuses the previously computed rate and keeps the old sample for the next real tick. - Per-torrent limiter lifecycle is now tracked with an explicit running flag under perLimitMu. Clearing limits to (0,0) and re-setting them within one 500ms tick could spawn a second runPerTorrentLimiter while the first never observed the transient (0,0); the two then fought over Allow/DisallowDataDownload. The goroutine clears the flag under the lock with a limits re-check before exiting, so set-after-clear either reuses the live limiter or deterministically starts a fresh one. - List() spawned a saveSnapshotIfComplete goroutine per completed torrent per tick; with a nil snapshot store or persistent write failures the flag never latched and N goroutines leaked several times a second forever, each taking the client lock. List now skips when the store is nil, and spawnSnapshotSave adds an in-flight guard plus a 30s retry backoff after failures (cleared on Remove/Recheck). https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/engine/anacrolix.go | 151 ++++++++++++++++++++++++++++++++---- 1 file changed, 135 insertions(+), 16 deletions(-) diff --git a/backend/engine/anacrolix.go b/backend/engine/anacrolix.go index 42f24ae..4813482 100644 --- a/backend/engine/anacrolix.go +++ b/backend/engine/anacrolix.go @@ -141,6 +141,14 @@ type AnacrolixBackend struct { // Keyed (TorrentID, "ip:port"); guarded by rateMu. prevPeerRates map[TorrentID]map[string]peerRateSample + // maxConnsPerTorrent is the user-configured per-torrent established-conn + // cap (anacrolix's default of 80 when the setting is 0/unset). Initialized + // from AnacrolixConfig.MaxPeersPerTorrent, updated by + // ApplyPerTorrentMaxPeers, and read by Resume / ScheduledPause's re-enable + // path — pre-fix both hardcoded SetMaxEstablishedConns(80), so any + // pause/resume cycle or scheduler churn silently reset a user's cap to 80. + maxConnsPerTorrent atomic.Int64 + // pausedMu guards paused, queuePos, forceStart, scheduledPause, sequential. // We extend the existing read-mostly mutex rather than introducing a new // one — these maps are all read together by snapshotFor and written through @@ -177,6 +185,15 @@ type AnacrolixBackend struct { perLimitMu sync.RWMutex perTorrentDown map[TorrentID]int64 // bytes/sec, 0=unlimited perTorrentUp map[TorrentID]int64 // bytes/sec, 0=unlimited + // limiterRunning marks torrents with a live runPerTorrentLimiter + // goroutine. SetTorrentRateLimits sets it (under perLimitMu) before + // spawning; the goroutine clears it (under the same lock, re-checking + // the limits) before exiting on the both-limits-zero path. Pre-fix the + // "needs a goroutine" test compared against the previous limit values, + // so a clear-to-(0,0) followed by a non-zero set within one 500ms tick + // could spawn a second limiter while the first never observed the (0,0) + // state — two goroutines then fought over Allow/DisallowDataDownload. + limiterRunning map[TorrentID]bool // pieceCompletion is the shared bolt-backed piece-completion store // rooted in cfg.DataDir, so anacrolix's "is this piece valid" @@ -203,6 +220,15 @@ type AnacrolixBackend struct { // fast-resume path. snapshotMu sync.Mutex snapshotSaved map[TorrentID]bool + // snapshotInflight marks ids with a List()-spawned saveSnapshotIfComplete + // goroutine currently running; snapshotRetryAt is the earliest next + // attempt after a failed write. Pre-fix List() spawned one goroutine per + // completed torrent per tick unconditionally — snapshotSaved is only set + // on a SUCCESSFUL write, so a persistent failure (read-only engine dir, + // full disk) leaked N goroutines several times a second forever, each + // taking the client lock. Both guarded by snapshotMu. + snapshotInflight map[TorrentID]bool + snapshotRetryAt map[TorrentID]time.Time // onError is the engine-side hook for surfacing per-torrent errors // (out-of-disk-space being the canonical case). Wired by Engine via @@ -253,9 +279,13 @@ type rateValue struct { // peerRateSample is a single tick's worth of per-peer cumulative data // counters. The next tick's rate is (current - sample) / (now - at). +// rate is the rate computed AT this sample, kept so back-to-back +// DetailedSnapshot calls (dt below minPeerRateSampleInterval) can reuse +// it instead of resampling — see the scope.Peers block in DetailedSnapshot. type peerRateSample struct { at time.Time down int64 + rate int64 } // NewAnacrolixBackend opens a torrent.Client with our config. @@ -405,8 +435,11 @@ func NewAnacrolixBackend(cfg AnacrolixConfig) (*AnacrolixBackend, error) { expectedComplete: make(map[TorrentID]bool), filesMissing: make(map[TorrentID]bool), snapshotSaved: make(map[TorrentID]bool), + snapshotInflight: make(map[TorrentID]bool), + snapshotRetryAt: make(map[TorrentID]time.Time), perTorrentDown: make(map[TorrentID]int64), perTorrentUp: make(map[TorrentID]int64), + limiterRunning: make(map[TorrentID]bool), dlLim: dlLim, ulLim: ulLim, ipBlock: ipBlock, @@ -415,6 +448,11 @@ func NewAnacrolixBackend(cfg AnacrolixConfig) (*AnacrolixBackend, error) { engineCancel: engineCancel, preallocateFullFiles: cfg.PreallocateFullFiles, } + conns := cfg.MaxPeersPerTorrent + if conns <= 0 { + conns = 80 // anacrolix default + } + b.maxConnsPerTorrent.Store(int64(conns)) // Publish an empty cache up front so the first List() before the sampler's // first tick reads a non-nil map (every torrent → 0 B/s) instead of // nil-dereferencing. @@ -434,6 +472,13 @@ func NewAnacrolixBackend(cfg AnacrolixConfig) (*AnacrolixBackend, error) { // so observed rate granularity is unchanged. const rateSampleInterval = 500 * time.Millisecond +// minPeerRateSampleInterval is the floor below which DetailedSnapshot reuses +// the previous per-peer sample (and its computed rate) instead of resampling. +// Per-peer rates can't go through the central sampler — they're only worth +// computing while someone has the Peers tab focused — so back-to-back calls +// from multiple consumers are de-conflicted by this minimum-dt guard instead. +const minPeerRateSampleInterval = 250 * time.Millisecond + // sampleRates is the ONE goroutine that owns prevRates. Every tick it walks // the live torrents, computes each torrent's down/up rate from the delta // since its previous sample, and publishes an immutable snapshot map into @@ -1144,7 +1189,7 @@ func (a *AnacrolixBackend) Resume(id TorrentID) error { if !ok { return errors.New("not found") } - t.SetMaxEstablishedConns(80) + t.SetMaxEstablishedConns(int(a.maxConnsPerTorrent.Load())) a.pausedMu.Lock() a.paused[id] = false delete(a.scheduledPause, id) @@ -1166,11 +1211,13 @@ func (a *AnacrolixBackend) Resume(id TorrentID) error { // ApplyPerTorrentMaxPeers updates SetMaxEstablishedConns on every running // torrent. Used when the user changes the "max peers per torrent" setting. // Already-paused torrents keep their cap of 0 (we set it to 0 to pause); -// resuming will pick up the new cap. +// the new cap is stored in maxConnsPerTorrent so Resume (and the +// scheduler's re-enable path) restore it instead of a hardcoded default. func (a *AnacrolixBackend) ApplyPerTorrentMaxPeers(n int) error { if n <= 0 { n = 80 // anacrolix default } + a.maxConnsPerTorrent.Store(int64(n)) a.pausedMu.RLock() paused := make(map[TorrentID]bool, len(a.paused)) for id, v := range a.paused { @@ -1206,9 +1253,11 @@ func (a *AnacrolixBackend) Recheck(id TorrentID) error { } // Clear the in-memory dedup so saveSnapshotIfComplete re-runs after the // recheck finishes (it's the same write the original goroutine did - // inline pre-v0.4.4). + // inline pre-v0.4.4). The retry-backoff stamp goes too — a user-driven + // recheck should attempt the save immediately. a.snapshotMu.Lock() delete(a.snapshotSaved, id) + delete(a.snapshotRetryAt, id) a.snapshotMu.Unlock() a.setVerifying(id, true) a.verifyWg.Add(1) @@ -1246,6 +1295,7 @@ func (a *AnacrolixBackend) Remove(id TorrentID, deleteFiles bool) error { a.pausedMu.Unlock() a.snapshotMu.Lock() delete(a.snapshotSaved, id) + delete(a.snapshotRetryAt, id) a.snapshotMu.Unlock() a.rateMu.Lock() delete(a.prevRates, id) @@ -1311,9 +1361,9 @@ func (a *AnacrolixBackend) List() []Snapshot { out := make([]Snapshot, 0, len(ts)) // Collect newly-completed ids inside the locked region; persist their // fast-resume snapshots in goroutines after the locks are released so - // the file I/O doesn't block the tick. saveSnapshotIfComplete dedupes - // against snapshotSaved, so subsequent ticks observe completion as a - // no-op until Recheck or Remove clears the flag. + // the file I/O doesn't block the tick. spawnSnapshotSave dedupes against + // snapshotSaved / the in-flight guard, so subsequent ticks observe + // completion as a no-op until Recheck or Remove clears the flag. var completed []completedFor // Rates come from the centralized sampler's immutable cache — this loop // only reads, never mutates prevRates, so concurrent List() calls (one @@ -1329,18 +1379,49 @@ func (a *AnacrolixBackend) List() []Snapshot { } snap := snapshotFor(t, rate, a.paused[id], a.queuePos[id], a.forceStart[id], a.sequential[id], a.scheduledPause[id], a.verifying[id], a.filesMissing[id]) out = append(out, snap) - if snap.Completed { + if snap.Completed && a.snapshotStore != nil { completed = append(completed, completedFor{id: id, t: t}) } } a.verifyMu.RUnlock() a.pausedMu.RUnlock() for _, c := range completed { - go a.saveSnapshotIfComplete(c.id, c.t) + a.spawnSnapshotSave(c.id, c.t) } return out } +// snapshotSaveRetryBackoff is how long spawnSnapshotSave waits after a failed +// snapshot write before trying that torrent again. +const snapshotSaveRetryBackoff = 30 * time.Second + +// spawnSnapshotSave runs saveSnapshotIfComplete on a goroutine, at most one +// in flight per torrent. List() used to `go saveSnapshotIfComplete(...)` for +// every completed torrent on every tick; snapshotSaved is only set on a +// successful write, so a persistently failing snapshot store spawned N +// goroutines several times per second forever, each taking the client lock. +// Failures back off for snapshotSaveRetryBackoff before the next attempt. +func (a *AnacrolixBackend) spawnSnapshotSave(id TorrentID, t *torrent.Torrent) { + a.snapshotMu.Lock() + if a.snapshotSaved[id] || a.snapshotInflight[id] || time.Now().Before(a.snapshotRetryAt[id]) { + a.snapshotMu.Unlock() + return + } + a.snapshotInflight[id] = true + a.snapshotMu.Unlock() + go func() { + a.saveSnapshotIfComplete(id, t) + a.snapshotMu.Lock() + delete(a.snapshotInflight, id) + if a.snapshotSaved[id] { + delete(a.snapshotRetryAt, id) + } else { + a.snapshotRetryAt[id] = time.Now().Add(snapshotSaveRetryBackoff) + } + a.snapshotMu.Unlock() + }() +} + type completedFor struct { id TorrentID t *torrent.Torrent @@ -1542,17 +1623,30 @@ func (a *AnacrolixBackend) DetailedSnapshot(id TorrentID, scope DetailScope) (De peerStats := pc.Stats() cumDown := peerStats.ConnStats.BytesReadUsefulData.Int64() var dlRate int64 + sample := peerRateSample{at: now, down: cumDown} if !complete { if prev, ok := prevPeers[peerKey]; ok { - if dt := now.Sub(prev.at).Seconds(); dt > 0 { - dlRate = int64(float64(cumDown-prev.down) / dt) + if dt := now.Sub(prev.at); dt < minPeerRateSampleInterval { + // A second consumer called back-to-back (two web users + // focused on the same torrent each get a per-user + // DetailForFocus tick): dt is microseconds, so a fresh + // delta would read as 0 B/s or spike — the same + // multi-reader hazard the torrent-level sampler fixed + // centrally (see sampleRates). Reuse the previously + // computed rate and keep the old sample so the next + // real tick still has a meaningful dt. + dlRate = prev.rate + sample = prev + } else if secs := dt.Seconds(); secs > 0 { + dlRate = int64(float64(cumDown-prev.down) / secs) if dlRate < 0 { dlRate = 0 } + sample.rate = dlRate } } } - nextPeers[peerKey] = peerRateSample{at: now, down: cumDown} + nextPeers[peerKey] = sample d.Peers = append(d.Peers, PeerEntry{ IP: ip, Port: port, @@ -1785,15 +1879,26 @@ func (a *AnacrolixBackend) SetTorrentRateLimits(id TorrentID, downBPS, upBPS int upBPS = 0 } a.perLimitMu.Lock() - prev := a.perTorrentDown[id] != 0 || a.perTorrentUp[id] != 0 a.perTorrentDown[id] = downBPS a.perTorrentUp[id] = upBPS - needsStart := !prev && (downBPS != 0 || upBPS != 0) + // Lifecycle is tracked via limiterRunning, NOT the previous limit values: + // a clear-to-(0,0) followed by a non-zero set within one tick leaves the + // old goroutine alive (it never observes the transient 0,0), so spawning + // another would race it. The goroutine clears the flag under perLimitMu + // with a limits re-check before exiting, so set-after-clear either reuses + // the live limiter or deterministically starts a fresh one. + needsStart := (downBPS != 0 || upBPS != 0) && !a.limiterRunning[id] + if needsStart { + a.limiterRunning[id] = true + } a.perLimitMu.Unlock() if needsStart { t, ok := a.find(id) if !ok { + a.perLimitMu.Lock() + delete(a.limiterRunning, id) + a.perLimitMu.Unlock() return errors.New("not found") } a.verifyWg.Add(1) @@ -1862,8 +1967,22 @@ func (a *AnacrolixBackend) runPerTorrentLimiter(id TorrentID, t *torrent.Torrent upLimit := a.perTorrentUp[id] a.perLimitMu.RUnlock() - // Both limits cleared — re-enable and exit. + // Both limits cleared — re-enable and exit. Confirm under the write + // lock and clear limiterRunning atomically with the re-check: a + // SetTorrentRateLimits that re-set non-zero limits between our + // RLock read and here must either be observed (keep running) or + // happen strictly after the flag is cleared (spawns a fresh + // limiter). Without the re-check this goroutine could exit just as + // the setter saw it as still-running and skipped the spawn, + // leaving the torrent unlimited. if downLimit == 0 && upLimit == 0 { + a.perLimitMu.Lock() + if a.perTorrentDown[id] != 0 || a.perTorrentUp[id] != 0 { + a.perLimitMu.Unlock() + continue + } + delete(a.limiterRunning, id) + a.perLimitMu.Unlock() if dlBlocked { t.AllowDataDownload() } @@ -2056,7 +2175,7 @@ func applySequentialPriorities(t *torrent.Torrent, sequential bool) { } // ScheduledPause is the scheduler's pause channel — independent from the -// user's manual Pause. It uses the same SetMaxEstablishedConns(0/80) trick +// user's manual Pause. It uses the same SetMaxEstablishedConns(0/cap) trick // the manual Pause uses, but writes only the scheduledPause map flag so // snapshots can distinguish "user-paused" from "queue-held". // @@ -2086,7 +2205,7 @@ func (a *AnacrolixBackend) ScheduledPause(id TorrentID, paused bool) { if paused { t.SetMaxEstablishedConns(0) } else { - t.SetMaxEstablishedConns(80) + t.SetMaxEstablishedConns(int(a.maxConnsPerTorrent.Load())) } a.pausedMu.Lock() a.scheduledPause[id] = paused From 546f0be547dc9e96b51e81796e4bcac549144936 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 20:15:39 +0000 Subject: [PATCH 32/37] fix(schedule): support midnight-wrapping rules and re-apply edited active rules Two schedule-engine tick bugs: - The active-window check (minutes < StartMin || minutes >= EndMin) meant a rule spanning midnight (StartMin > EndMin, e.g. 22:00-06:00) never matched. Window containment now lives in ruleWindowContains: when StartMin > EndMin the window wraps, active when minutes >= StartMin || minutes < EndMin. - Change detection keyed on the active rule's ID only, so editing the currently-active rule's limits was silently ignored until the rule deactivated and reactivated. The applied key now includes the rule's DownKbps/UpKbps/AltOnly values, so an edit re-applies on the next tick. Adds a table test for the window logic (incl. wrap boundaries) and a deterministic tick-driven test for the edit-reapply path. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/api/schedule_engine.go | 37 +++++++++++++---- backend/api/schedule_engine_test.go | 62 +++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 7 deletions(-) diff --git a/backend/api/schedule_engine.go b/backend/api/schedule_engine.go index 114c6d5..3ac6d56 100644 --- a/backend/api/schedule_engine.go +++ b/backend/api/schedule_engine.go @@ -18,11 +18,22 @@ type ScheduleEngine struct { location *time.Location mu sync.RWMutex - lastApplied int // rule ID we last applied (0 = none/cleared) + lastApplied appliedRule // rule + limits we last applied (zero = none/cleared) stop chan struct{} } +// appliedRule is the change-detection key for tick: the active rule's ID plus +// the limit values we applied for it. Keying on ID alone meant editing the +// currently-active rule's limits did nothing until the rule deactivated and +// reactivated — the edited values weren't re-applied because "same rule". +type appliedRule struct { + id int + downKbps int + upKbps int + altOnly bool +} + func NewScheduleEngine(svc *Service, rules *persistence.ScheduleRules, loc *time.Location) *ScheduleEngine { if loc == nil { loc = time.Local @@ -68,7 +79,7 @@ func (se *ScheduleEngine) tick(ctx context.Context) { if r.DaysMask&dayBit == 0 { continue } - if minutes < r.StartMin || minutes >= r.EndMin { + if !ruleWindowContains(r.StartMin, r.EndMin, minutes) { continue } active = r @@ -76,15 +87,15 @@ func (se *ScheduleEngine) tick(ctx context.Context) { } se.mu.Lock() - prevID := se.lastApplied - nextID := 0 + prev := se.lastApplied + var next appliedRule if active != nil { - nextID = active.ID + next = appliedRule{id: active.ID, downKbps: active.DownKbps, upKbps: active.UpKbps, altOnly: active.AltOnly} } - se.lastApplied = nextID + se.lastApplied = next se.mu.Unlock() - if prevID == nextID { + if prev == next { return } @@ -105,3 +116,15 @@ func (se *ScheduleEngine) tick(ctx context.Context) { log.Info().Int("rule_id", active.ID).Int("down", active.DownKbps).Int("up", active.UpKbps). Msg("schedule_engine: applied rule") } + +// ruleWindowContains reports whether a rule's [startMin, endMin) window +// contains the given minutes-since-midnight. startMin > endMin means the +// window wraps midnight (e.g. 22:00–06:00, StartMin=1320 EndMin=360): the +// rule is active past the start OR before the end. startMin == endMin is an +// empty window, matching the pre-wrap behavior. +func ruleWindowContains(startMin, endMin, minutes int) bool { + if startMin <= endMin { + return minutes >= startMin && minutes < endMin + } + return minutes >= startMin || minutes < endMin +} diff --git a/backend/api/schedule_engine_test.go b/backend/api/schedule_engine_test.go index 7faa5c8..7218d91 100644 --- a/backend/api/schedule_engine_test.go +++ b/backend/api/schedule_engine_test.go @@ -68,6 +68,68 @@ func TestScheduleEngine_NoActiveRule_RestoresUserLimits(t *testing.T) { }, 2*time.Second, 25*time.Millisecond) } +func TestRuleWindowContains(t *testing.T) { + cases := []struct { + name string + startMin, endMin, minutes int + want bool + }{ + {"normal window, inside", 9 * 60, 17 * 60, 12 * 60, true}, + {"normal window, before start", 9 * 60, 17 * 60, 8 * 60, false}, + {"normal window, at start", 9 * 60, 17 * 60, 9 * 60, true}, + {"normal window, at end (exclusive)", 9 * 60, 17 * 60, 17 * 60, false}, + {"empty window never matches", 10 * 60, 10 * 60, 10 * 60, false}, + {"midnight wrap, late evening", 22 * 60, 6 * 60, 23 * 60, true}, + {"midnight wrap, at start", 22 * 60, 6 * 60, 22 * 60, true}, + {"midnight wrap, early morning", 22 * 60, 6 * 60, 3 * 60, true}, + {"midnight wrap, at end (exclusive)", 22 * 60, 6 * 60, 6 * 60, false}, + {"midnight wrap, midday outside", 22 * 60, 6 * 60, 12 * 60, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, ruleWindowContains(tc.startMin, tc.endMin, tc.minutes)) + }) + } +} + +// TestScheduleEngine_EditingActiveRuleReapplies covers the change-detection +// key: editing the currently-active rule's limits must be re-applied on the +// next tick, not deferred until the rule deactivates and reactivates. +func TestScheduleEngine_EditingActiveRuleReapplies(t *testing.T) { + svc, fb := newTestService(t) + ctx := sysCtx() + + now := time.Now() + dayBit := 1 << int(now.Weekday()) + startMin := now.Hour()*60 + now.Minute() - 1 + if startMin < 0 { + startMin = 0 + } + endMin := startMin + 10 + id, err := svc.CreateScheduleRule(ctx, ScheduleRuleDTO{ + DaysMask: dayBit, StartMin: startMin, EndMin: endMin, + DownKbps: 999, UpKbps: 333, Enabled: true, + }) + require.NoError(t, err) + + // Drive ticks directly (no goroutine) so the test is deterministic. + se := &ScheduleEngine{svc: svc, rules: svc.scheduleRules, location: time.Local, stop: make(chan struct{})} + se.tick(ctx) + d, u := fb.GlobalRateLimits() + require.Equal(t, 999*1024, d) + require.Equal(t, 333*1024, u) + + // Edit the active rule's limits — same ID, same window. + require.NoError(t, svc.UpdateScheduleRule(ctx, ScheduleRuleDTO{ + ID: id, DaysMask: dayBit, StartMin: startMin, EndMin: endMin, + DownKbps: 555, UpKbps: 111, Enabled: true, + })) + se.tick(ctx) + d, u = fb.GlobalRateLimits() + require.Equal(t, 555*1024, d) + require.Equal(t, 111*1024, u) +} + func TestService_ScheduleRuleCRUD_RoundTrip(t *testing.T) { svc, _ := newTestService(t) ctx := sysCtx() From b34fcb95bfa73ca8181a966f440a413eb84e85cc Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 20:16:47 +0000 Subject: [PATCH 33/37] fix(api): stop synthesizing added_at, serialize zero times as 0, gate CheckForUpdate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ListTorrentsFromSnapshot gave a torrent missing its DB record addedAt = time.Now(), which changed every tick — scrambling the added_at sort and defeating streamTicks' frame dedup. It now uses the zero time, and toDTO/detailToDTO serialize timestamps through unixOrZero so a zero time becomes added_at=0 instead of time.Time{}.Unix()'s -62135596800 (which DetailDTO emitted whenever lookupRecordTimes failed). - CheckForUpdate performed an outbound HTTP check and wrote two settings rows with no permission check, unlike its siblings InstallUpdate and SetUpdaterConfig. It now requires CanChangeSettings(); the updater runtime toggles introduced recently are untouched. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/api/service.go | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/backend/api/service.go b/backend/api/service.go index 5e156e8..b9c3777 100644 --- a/backend/api/service.go +++ b/backend/api/service.go @@ -584,6 +584,12 @@ func (s *Service) fireUpdaterConfigChanged(c UpdaterConfigDTO) { } func (s *Service) CheckForUpdate(ctx context.Context) (UpdateInfoDTO, error) { + // Same gate as InstallUpdate / SetUpdaterConfig: the check performs an + // outbound HTTP request and writes two settings rows, neither of which a + // caller without the settings permission should be able to trigger. + if !CallerFrom(ctx).CanChangeSettings() { + return UpdateInfoDTO{}, ErrForbidden + } if s.updater == nil { return UpdateInfoDTO{CurrentVersion: s.appVersion}, fmt.Errorf("updater disabled") } @@ -802,6 +808,16 @@ type TorrentDTO struct { Access string `json:"access"` } +// unixOrZero serializes a record timestamp for the wire, mapping the zero +// time (record missing or lookup failed) to 0. time.Time{}.Unix() is +// -62135596800, which the SPA would render as a date in year 1. +func unixOrZero(t time.Time) int64 { + if t.IsZero() { + return 0 + } + return t.Unix() +} + func toDTO(s engine.Snapshot, addedAt time.Time) TorrentDTO { prog := 0.0 if s.TotalBytes > 0 { @@ -821,7 +837,7 @@ func toDTO(s engine.Snapshot, addedAt time.Time) TorrentDTO { Seeds: s.Seeds, Paused: s.Paused, Completed: s.Completed, - AddedAt: addedAt.Unix(), + AddedAt: unixOrZero(addedAt), QueuePosition: s.QueuePosition, ForceStart: s.ForceStart, Sequential: s.Sequential, @@ -1231,7 +1247,11 @@ func (s *Service) ListTorrentsFromSnapshot(ctx context.Context, tick TorrentTick access = lvl } rec, ok := tick.byHash[hash] - addedAt := time.Now() + // No DB record (engine-only torrent, e.g. a restore raced the tick): + // use the zero time, which unixOrZero serializes as added_at=0. A + // fresh time.Now() here changed every tick, scrambling the added_at + // sort below and defeating streamTicks' frame dedup. + var addedAt time.Time if ok { snap.SavePath = rec.SavePath if snap.Magnet == "" { @@ -1477,7 +1497,7 @@ func detailToDTO(d engine.Detail, addedAt time.Time, completedAt *time.Time) Det TotalUp: snap.BytesUp, Peers: snap.Peers, Seeds: snap.Seeds, - AddedAt: addedAt.Unix(), + AddedAt: unixOrZero(addedAt), Paused: snap.Paused, Completed: snap.Completed, FilesMissing: snap.FilesMissing, From bd1000b6776d5ff6823d46e4c66a09c7f6fa8b4f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 20:17:49 +0000 Subject: [PATCH 34/37] fix(notifications): rune-aware truncate, safe Stop-before-Start, enforce single Start - truncate sliced bytes (s[:n-1]) and could split a UTF-8 sequence mid-rune, sending mojibake to the OS notifier for non-ASCII torrent names. It now counts and slices runes. - Stop() blocked forever on <-s.done when Start was never called (nothing ever closes done). It now tracks started/stopped under the existing mutex: a no-op wait before Start, idempotent after. - Start's doc comment claimed calling it twice panics, but it silently double-subscribed to the engine event bus. It now enforces the documented contract. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/notifications/notifier_test.go | 48 ++++++++++++++++++++++++++ backend/notifications/subscriber.go | 44 ++++++++++++++++++----- 2 files changed, 83 insertions(+), 9 deletions(-) diff --git a/backend/notifications/notifier_test.go b/backend/notifications/notifier_test.go index 7a3901b..12f258c 100644 --- a/backend/notifications/notifier_test.go +++ b/backend/notifications/notifier_test.go @@ -1,9 +1,12 @@ package notifications import ( + "context" "errors" "sync" "testing" + "time" + "unicode/utf8" "github.com/stretchr/testify/require" @@ -225,4 +228,49 @@ func TestTruncate(t *testing.T) { require.Equal(t, "abc", truncate("abc", 5)) require.Equal(t, "ab…", truncate("abcdef", 3)) require.Equal(t, "a", truncate("abc", 1)) + require.Equal(t, "", truncate("abc", 0)) +} + +// TestTruncate_RuneAware ensures truncation counts runes, not bytes — slicing +// bytes split multi-byte UTF-8 sequences mid-rune and produced mojibake in +// OS notifications for non-ASCII torrent names. +func TestTruncate_RuneAware(t *testing.T) { + require.Equal(t, "日本…", truncate("日本語のトレント", 3)) + require.Equal(t, "日", truncate("日本語", 1)) + require.Equal(t, "日本語", truncate("日本語", 3)) + for n := 0; n <= 10; n++ { + require.True(t, utf8.ValidString(truncate("héllo wörld🙂", n)), "n=%d", n) + } +} + +// TestSubscriber_StopBeforeStartDoesNotBlock: Stop must be a no-op (not a +// deadlock on <-s.done) when Start was never called — nothing will ever +// close the done channel in that case. +func TestSubscriber_StopBeforeStartDoesNotBlock(t *testing.T) { + sub := NewSubscriber(&fakeNotifier{}, Settings{}) + done := make(chan struct{}) + go func() { + sub.Stop() + sub.Stop() // still idempotent + close(done) + }() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("Stop blocked without a prior Start") + } +} + +// TestSubscriber_StartTwicePanics enforces the documented run-once contract — +// a silent second Start used to double-subscribe to the engine event bus. +func TestSubscriber_StartTwicePanics(t *testing.T) { + eng := engine.NewEngine(engine.NewFakeBackend(), 50*time.Millisecond) + t.Cleanup(func() { _ = eng.Close() }) + + sub := NewSubscriber(&fakeNotifier{}, Settings{}) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + sub.Start(ctx, eng) + require.Panics(t, func() { sub.Start(ctx, eng) }) + sub.Stop() } diff --git a/backend/notifications/subscriber.go b/backend/notifications/subscriber.go index 615fdd3..c725906 100644 --- a/backend/notifications/subscriber.go +++ b/backend/notifications/subscriber.go @@ -35,6 +35,12 @@ type Subscriber struct { // errored[id] = true once we've fired an "error" notification; same reset. errored map[engine.TorrentID]bool + // started/stopped track the consumer-goroutine lifecycle (guarded by mu): + // Start enforces its documented run-once contract, and Stop must not + // block on done when Start never ran (nothing will ever close it). + started bool + stopped bool + stop chan struct{} done chan struct{} } @@ -65,18 +71,31 @@ func (s *Subscriber) SetSettings(cfg Settings) { // Start spawns the consumer goroutine. ctx cancellation OR Stop() terminates it. // Calling Start more than once panics (callers shouldn't need to re-subscribe). func (s *Subscriber) Start(ctx context.Context, eng *engine.Engine) { + s.mu.Lock() + if s.started { + s.mu.Unlock() + panic("notifications: Subscriber.Start called more than once") + } + s.started = true + s.mu.Unlock() ch := eng.Subscribe() go s.run(ctx, ch) } -// Stop terminates the consumer goroutine. Idempotent. +// Stop terminates the consumer goroutine. Idempotent, and a no-op (beyond +// closing the stop channel) when Start was never called — waiting on done in +// that case would block forever since no goroutine will ever close it. func (s *Subscriber) Stop() { - select { - case <-s.stop: + s.mu.Lock() + started, alreadyStopped := s.started, s.stopped + if !alreadyStopped { + s.stopped = true + close(s.stop) + } + s.mu.Unlock() + if alreadyStopped || !started { return - default: } - close(s.stop) <-s.done } @@ -180,12 +199,19 @@ func (s *Subscriber) NotifyUpdateInstalled(version string) { } } +// truncate caps s at n runes (not bytes — slicing bytes could split a UTF-8 +// sequence mid-rune and hand the OS notifier mojibake), appending an ellipsis +// when something was cut. func truncate(s string, n int) string { - if len(s) <= n { + if n <= 0 { + return "" + } + r := []rune(s) + if len(r) <= n { return s } - if n <= 1 { - return s[:n] + if n == 1 { + return string(r[:1]) } - return s[:n-1] + "…" + return string(r[:n-1]) + "…" } From abec11243ce4a9a645d71fcbb8366f933f8c8bb0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 20:19:10 +0000 Subject: [PATCH 35/37] fix(rss): validate filter regex on create and update MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CreateFilter/UpdateFilter stored the pattern verbatim; compilation only happens per-poll in rss_poller.go, which logs and skips invalid filters — so a bad regex was accepted silently and simply never matched. Both paths now run regexp.Compile and return a "filter regex is invalid: …" error, registered in userFacingValidationPrefixes so the SPA gets a 400 with the parse error instead of a generic 500. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/api/feeds.go | 19 +++++++++++++++++++ backend/api/service_test.go | 23 +++++++++++++++++++++++ backend/remote/handlers.go | 1 + 3 files changed, 43 insertions(+) diff --git a/backend/api/feeds.go b/backend/api/feeds.go index 0262f66..ab9c9dc 100644 --- a/backend/api/feeds.go +++ b/backend/api/feeds.go @@ -3,6 +3,7 @@ package api import ( "context" "fmt" + "regexp" "mosaic/backend/persistence" ) @@ -181,10 +182,25 @@ func (s *Service) ListFiltersByFeed(ctx context.Context, feedID int) ([]FilterDT return out, nil } +// validateFilterRegex rejects patterns that won't compile. The poller +// compiles each filter per poll and skips (with a log) any that fail — so an +// invalid pattern stored here would be accepted silently and simply never +// match. The message prefix is registered in remote/handlers.go's +// userFacingValidationPrefixes so the SPA gets a 400 with the parse error. +func validateFilterRegex(pattern string) error { + if _, err := regexp.Compile(pattern); err != nil { + return fmt.Errorf("filter regex is invalid: %v", err) + } + return nil +} + func (s *Service) CreateFilter(ctx context.Context, dto FilterDTO) (int, error) { if !CallerFrom(ctx).CanManageRSS() { return 0, ErrForbidden } + if err := validateFilterRegex(dto.Regex); err != nil { + return 0, err + } return s.filters.Create(ctx, persistence.Filter{ FeedID: dto.FeedID, Regex: dto.Regex, CategoryID: dto.CategoryID, SavePath: dto.SavePath, Enabled: dto.Enabled, @@ -195,6 +211,9 @@ func (s *Service) UpdateFilter(ctx context.Context, dto FilterDTO) error { if !CallerFrom(ctx).CanManageRSS() { return ErrForbidden } + if err := validateFilterRegex(dto.Regex); err != nil { + return err + } return s.filters.Update(ctx, persistence.Filter{ ID: dto.ID, FeedID: dto.FeedID, Regex: dto.Regex, CategoryID: dto.CategoryID, SavePath: dto.SavePath, Enabled: dto.Enabled, diff --git a/backend/api/service_test.go b/backend/api/service_test.go index ab6bdb9..b22785b 100644 --- a/backend/api/service_test.go +++ b/backend/api/service_test.go @@ -367,6 +367,29 @@ func TestService_FilterCRUD(t *testing.T) { require.Empty(t, got) } +// TestService_FilterRejectsInvalidRegex covers create AND update: the poller +// compiles each filter per poll and skips invalid ones, so a bad pattern +// stored here would be accepted silently and simply never match. +func TestService_FilterRejectsInvalidRegex(t *testing.T) { + svc, _ := newTestService(t) + ctx := sysCtx() + + feedID, err := svc.CreateFeed(ctx, FeedDTO{URL: "https://example.com/rss", Name: "f", IntervalMin: 30, Enabled: true}) + require.NoError(t, err) + + _, err = svc.CreateFilter(ctx, FilterDTO{FeedID: feedID, Regex: `ubuntu(`, Enabled: true}) + require.ErrorContains(t, err, "filter regex is invalid") + got, _ := svc.ListFiltersByFeed(ctx, feedID) + require.Empty(t, got, "invalid filter must not be stored") + + filterID, err := svc.CreateFilter(ctx, FilterDTO{FeedID: feedID, Regex: `^debian`, Enabled: true}) + require.NoError(t, err) + err = svc.UpdateFilter(ctx, FilterDTO{ID: filterID, FeedID: feedID, Regex: `[a-`, Enabled: true}) + require.ErrorContains(t, err, "filter regex is invalid") + got, _ = svc.ListFiltersByFeed(ctx, feedID) + require.Equal(t, `^debian`, got[0].Regex, "failed update must not clobber the stored regex") +} + func TestService_DeleteFeed_CascadesFilters(t *testing.T) { svc, _ := newTestService(t) ctx := sysCtx() diff --git a/backend/remote/handlers.go b/backend/remote/handlers.go index 22574aa..493737d 100644 --- a/backend/remote/handlers.go +++ b/backend/remote/handlers.go @@ -431,6 +431,7 @@ var userFacingValidationPrefixes = []string{ "max peers per torrent must be ", "no blocklist URL configured", "rss poller not attached", + "filter regex is invalid", "URL is empty", "URL has no host", "URL scheme must be http or https", From 58fbceddc9d0e56fe98a3415ec903cdbe5948cc8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 20:20:14 +0000 Subject: [PATCH 36/37] fix(persistence): detach rss_filters when deleting a category MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Categories.Delete was recently fixed to NULL out torrents.category_id in a transaction, but rss_filters.category_id (migrations/0005_rss.sql) has the same no-ON-DELETE FK — deleting a category referenced by an RSS filter still failed with an FK violation surfaced as a 500. The same transaction now detaches rss_filters too; the in-use delete test covers both references. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/persistence/categories.go | 14 +++++++++----- backend/persistence/categories_test.go | 15 +++++++++++++-- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/backend/persistence/categories.go b/backend/persistence/categories.go index 45e18cd..dad38c9 100644 --- a/backend/persistence/categories.go +++ b/backend/persistence/categories.go @@ -68,11 +68,12 @@ func (c *Categories) Update(ctx context.Context, cat Category) error { return err } -// Delete removes a category, detaching any torrents still assigned to it. -// torrents.category_id REFERENCES categories(id) with no ON DELETE action and -// foreign_keys is on, so deleting an in-use category would otherwise fail -// with an FK violation. Both statements run in one transaction so a failed -// delete can't leave torrents detached from a category that still exists. +// Delete removes a category, detaching any torrents and RSS filters still +// assigned to it. Both torrents.category_id and rss_filters.category_id +// REFERENCE categories(id) with no ON DELETE action and foreign_keys is on, +// so deleting an in-use category would otherwise fail with an FK violation. +// All statements run in one transaction so a failed delete can't leave rows +// detached from a category that still exists. func (c *Categories) Delete(ctx context.Context, id int) error { tx, err := c.db.SQL().BeginTx(ctx, nil) if err != nil { @@ -82,6 +83,9 @@ func (c *Categories) Delete(ctx context.Context, id int) error { if _, err := tx.ExecContext(ctx, `UPDATE torrents SET category_id = NULL WHERE category_id = ?`, id); err != nil { return err } + if _, err := tx.ExecContext(ctx, `UPDATE rss_filters SET category_id = NULL WHERE category_id = ?`, id); err != nil { + return err + } if _, err := tx.ExecContext(ctx, `DELETE FROM categories WHERE id = ?`, id); err != nil { return err } diff --git a/backend/persistence/categories_test.go b/backend/persistence/categories_test.go index 4e1fb6b..02eaf1b 100644 --- a/backend/persistence/categories_test.go +++ b/backend/persistence/categories_test.go @@ -62,13 +62,16 @@ func TestCategories_Delete(t *testing.T) { } // TestCategories_DeleteInUse covers deleting a category still assigned to a -// torrent: torrents.category_id has no ON DELETE action and foreign_keys is -// on, so Delete must detach the torrents (category_id → NULL) in the same +// torrent AND referenced by an RSS filter: torrents.category_id and +// rss_filters.category_id both have no ON DELETE action and foreign_keys is +// on, so Delete must detach both (category_id → NULL) in the same // transaction instead of failing with an FK violation. func TestCategories_DeleteInUse(t *testing.T) { db := newTestDB(t) c := NewCategories(db) tor := NewTorrents(db) + feeds := NewFeeds(db) + filters := NewFilters(db) ctx := context.Background() id, err := c.Create(ctx, Category{Name: "Movies"}) @@ -76,6 +79,10 @@ func TestCategories_DeleteInUse(t *testing.T) { require.NoError(t, tor.Save(ctx, TorrentRecord{ InfoHash: "aaa", Name: "film", SavePath: "/tmp", CategoryID: &id, AddedAt: time.Now(), })) + feedID, err := feeds.Create(ctx, Feed{URL: "https://x.test/rss", Name: "f", IntervalMin: 30, Enabled: true}) + require.NoError(t, err) + filterID, err := filters.Create(ctx, Filter{FeedID: feedID, Regex: ".*", CategoryID: &id, Enabled: true}) + require.NoError(t, err) require.NoError(t, c.Delete(ctx, id)) _, err = c.Get(ctx, id) @@ -84,6 +91,10 @@ func TestCategories_DeleteInUse(t *testing.T) { got, err := tor.Get(ctx, "aaa") require.NoError(t, err) require.Nil(t, got.CategoryID, "torrent must be detached from the deleted category") + + fil, err := filters.Get(ctx, filterID) + require.NoError(t, err) + require.Nil(t, fil.CategoryID, "rss filter must be detached from the deleted category") } func TestCategories_NameUnique(t *testing.T) { From b3ff243420f1093ff227a17dcb792d450a1fe464 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 10 Jun 2026 20:25:39 +0000 Subject: [PATCH 37/37] fix(api): persist cumulative transfer totals so ratio seed limits survive restarts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CheckSeedLimits computed ratio from anacrolix's session-scoped BytesUp, which resets every process start — ratio limits restarted from 0 on every launch and effectively never fired across sessions. It also issued one torrents.Get per completed torrent every 30s pass. - Migration 0016 adds total_uploaded/total_downloaded columns on torrents, with a Torrents.AddTransferTotals DAO that increments them. - CheckSeedLimits now bulk-loads records once per pass via the existing list DAO, and checkpoints the engine's session counters into the persisted totals for every persisted torrent: an in-memory map of last-observed counters per infohash yields per-pass deltas; a counter lower than the last observation means an engine restart and the full current value is the delta. Failed writes roll the observation back so the delta is retried next pass; observations for removed torrents are pruned so a re-added infohash starts fresh. - The ratio check now uses the persisted cumulative upload over BytesDone (denominator unchanged — piece completion is already stable across restarts). Covered by DAO tests plus service-level tests for the pause threshold, the counter-reset (restart) accumulation, and download-phase checkpointing; FakeBackend grows a SetSessionStats helper. https://claude.ai/code/session_0112xsVQpsrg8TzRqPRqzbZ7 --- backend/api/seed_limits_test.go | 115 ++++++++++++++++++ backend/api/service.go | 93 +++++++++++++- backend/engine/fake.go | 16 +++ .../migrations/0016_transfer_totals.sql | 12 ++ backend/persistence/torrents.go | 23 +++- backend/persistence/torrents_test.go | 27 ++++ 6 files changed, 279 insertions(+), 7 deletions(-) create mode 100644 backend/api/seed_limits_test.go create mode 100644 backend/persistence/migrations/0016_transfer_totals.sql diff --git a/backend/api/seed_limits_test.go b/backend/api/seed_limits_test.go new file mode 100644 index 0000000..0a145eb --- /dev/null +++ b/backend/api/seed_limits_test.go @@ -0,0 +1,115 @@ +package api + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// floatPtr is a tiny literal helper for SeedingDefaultsDTO.RatioLimit. +func floatPtr(f float64) *float64 { return &f } + +// TestCheckSeedLimits_RatioPausesWhenExceeded covers the basic in-session +// path: a completed torrent whose cumulative upload crosses the ratio limit +// gets paused; one below it does not. +func TestCheckSeedLimits_RatioPausesWhenExceeded(t *testing.T) { + svc, fb := newTestService(t) + ctx := sysCtx() + + require.NoError(t, svc.SetSeedingDefaults(ctx, SeedingDefaultsDTO{RatioLimit: floatPtr(1.0)})) + + id, err := svc.AddMagnet(ctx, "magnet:?xt=urn:btih:seedratio", "") + require.NoError(t, err) + + // Completed, uploaded 2x the payload (TotalBytes is 1 GiB in the fake). + fb.SetSessionStats(id, 0, 2<<30, true) + svc.CheckSeedLimits(ctx) + + snap, err := fb.Snapshot(id) + require.NoError(t, err) + require.True(t, snap.Paused, "ratio 2.0 >= limit 1.0 must pause the torrent") + + // Totals were checkpointed to the DB. + rec, err := svc.torrents.Get(ctx, string(id)) + require.NoError(t, err) + require.Equal(t, int64(2<<30), rec.TotalUploaded) +} + +// TestCheckSeedLimits_RatioBelowLimitDoesNotPause is the negative control. +func TestCheckSeedLimits_RatioBelowLimitDoesNotPause(t *testing.T) { + svc, fb := newTestService(t) + ctx := sysCtx() + + require.NoError(t, svc.SetSeedingDefaults(ctx, SeedingDefaultsDTO{RatioLimit: floatPtr(1.0)})) + + id, err := svc.AddMagnet(ctx, "magnet:?xt=urn:btih:seedlow", "") + require.NoError(t, err) + + fb.SetSessionStats(id, 0, 1<<29, true) // ratio 0.5 + svc.CheckSeedLimits(ctx) + + snap, err := fb.Snapshot(id) + require.NoError(t, err) + require.False(t, snap.Paused) +} + +// TestCheckSeedLimits_RatioSurvivesCounterReset covers the cross-session bug: +// anacrolix's BytesUp counter resets every process start, so a ratio computed +// from it restarted at 0 each launch. The persisted totals must accumulate +// across a counter reset (observed as the session counter dropping), so the +// combined upload trips the limit even though no single session does. +func TestCheckSeedLimits_RatioSurvivesCounterReset(t *testing.T) { + svc, fb := newTestService(t) + ctx := sysCtx() + + require.NoError(t, svc.SetSeedingDefaults(ctx, SeedingDefaultsDTO{RatioLimit: floatPtr(1.0)})) + + id, err := svc.AddMagnet(ctx, "magnet:?xt=urn:btih:seedreset", "") + require.NoError(t, err) + + // Session 1: uploaded 0.75x — below the limit. + fb.SetSessionStats(id, 0, 3<<28, true) + svc.CheckSeedLimits(ctx) + snap, err := fb.Snapshot(id) + require.NoError(t, err) + require.False(t, snap.Paused, "0.75 ratio must not pause") + + // "Restart": the session counter drops to a lower value (0.5x this + // session). Session-scoped math would see ratio 0.5 and never pause; + // the persisted totals make it 0.75 + 0.5 = 1.25 >= 1.0. + fb.SetSessionStats(id, 0, 1<<29, true) + svc.CheckSeedLimits(ctx) + + rec, err := svc.torrents.Get(ctx, string(id)) + require.NoError(t, err) + require.Equal(t, int64(3<<28+1<<29), rec.TotalUploaded) + + snap, err = fb.Snapshot(id) + require.NoError(t, err) + require.True(t, snap.Paused, "cumulative ratio 1.25 >= limit 1.0 must pause") +} + +// TestCheckSeedLimits_CheckpointsIncompleteTorrents ensures the transfer +// checkpoint runs for every persisted torrent, not just completed ones — +// upload during the download phase must count toward the eventual ratio. +func TestCheckSeedLimits_CheckpointsIncompleteTorrents(t *testing.T) { + svc, fb := newTestService(t) + ctx := sysCtx() + + id, err := svc.AddMagnet(ctx, "magnet:?xt=urn:btih:seedpartial", "") + require.NoError(t, err) + + fb.SetSessionStats(id, 1<<20, 1<<19, false) + svc.CheckSeedLimits(ctx) + fb.SetSessionStats(id, 3<<20, 1<<20, false) + svc.CheckSeedLimits(ctx) + + rec, err := svc.torrents.Get(ctx, string(id)) + require.NoError(t, err) + require.Equal(t, int64(1<<20), rec.TotalUploaded) + require.Equal(t, int64(3<<20), rec.TotalDownloaded) + + snap, err := fb.Snapshot(id) + require.NoError(t, err) + require.False(t, snap.Paused, "incomplete torrents are never paused by seed limits") +} diff --git a/backend/api/service.go b/backend/api/service.go index b9c3777..ee602b7 100644 --- a/backend/api/service.go +++ b/backend/api/service.go @@ -93,6 +93,21 @@ type Service struct { // every call. Invalidated alongside session revocation — see // invalidateCaller. callers *callerCache + + // lastSeedCounters is the last-observed session transfer counters per + // infohash. CheckSeedLimits adds the delta since the previous observation + // to the persisted cumulative totals each pass — the engine's counters + // reset every process start, so ratio limits computed straight from them + // restarted at 0 on every launch. Guarded by seedCheckMu. + seedCheckMu sync.Mutex + lastSeedCounters map[string]sessionCounters +} + +// sessionCounters is one observation of the engine's session-scoped transfer +// counters for a torrent. See Service.lastSeedCounters. +type sessionCounters struct { + up int64 + down int64 } // SessionRevoker is the subset of *remote.SessionStore that api.Service needs @@ -165,6 +180,7 @@ func NewService( defaultSavePath: defaultSavePath, focus: make(map[int]focusState), callers: newCallerCache(), + lastSeedCounters: make(map[string]sessionCounters), } } @@ -2396,17 +2412,37 @@ type seedPolicyJSON struct { // CheckSeedLimits inspects every completed, non-paused torrent and pauses // any that have exceeded their effective seeding limit (ratio or time). // It is designed to be called on a periodic ticker (e.g. every 30 seconds). +// +// Each pass also checkpoints the engine's session-scoped transfer counters +// into the persisted total_uploaded/total_downloaded columns (for every +// persisted torrent, not just completed ones), and computes the ratio from +// the persisted total — anacrolix's BytesUp resets each process start, so a +// ratio computed from it restarted at 0 on every launch and ratio limits +// effectively never fired across sessions. func (s *Service) CheckSeedLimits(ctx context.Context) { ctx = WithCaller(ctx, SystemCaller) defaults := s.GetSeedingDefaults(ctx) snaps := s.engine.List() + // One bulk SELECT per pass instead of a per-torrent Get every 30s. + records, err := s.torrents.List(ctx) + if err != nil { + log.Warn().Err(err).Msg("seed policy: list torrents failed") + return + } + byHash := make(map[string]persistence.TorrentRecord, len(records)) + for _, r := range records { + byHash[r.InfoHash] = r + } now := time.Now() + live := make(map[string]struct{}, len(snaps)) for _, snap := range snaps { - if !snap.Completed || snap.Paused { + live[string(snap.ID)] = struct{}{} + rec, ok := byHash[string(snap.ID)] + if !ok { continue } - rec, err := s.torrents.Get(ctx, string(snap.ID)) - if err != nil { + totalUp := s.checkpointTransferTotals(ctx, &rec, snap) + if !snap.Completed || snap.Paused { continue } // Determine effective policy: per-torrent override wins over global default. @@ -2434,7 +2470,7 @@ func (s *Service) CheckSeedLimits(ctx context.Context) { } exceeded := false if ratioLimit != nil && snap.BytesDone > 0 { - ratio := float64(snap.BytesUp) / float64(snap.BytesDone) + ratio := float64(totalUp) / float64(snap.BytesDone) if ratio >= *ratioLimit { exceeded = true } @@ -2453,4 +2489,53 @@ func (s *Service) CheckSeedLimits(ctx context.Context) { } } } + // Prune observations for torrents no longer in the engine so a removed + // and re-added infohash starts from fresh counters and the map doesn't + // grow unbounded across remove cycles. + s.seedCheckMu.Lock() + for hash := range s.lastSeedCounters { + if _, ok := live[hash]; !ok { + delete(s.lastSeedCounters, hash) + } + } + s.seedCheckMu.Unlock() +} + +// checkpointTransferTotals persists the delta between the engine's +// session-scoped transfer counters and the last value this process observed +// for the torrent, returning the updated cumulative uploaded total. A counter +// lower than the last observation means the engine restarted (counters reset +// to zero) — the full current value is the delta. On a write failure the +// observation is rolled back so the delta is retried next pass instead of +// being lost. +func (s *Service) checkpointTransferTotals(ctx context.Context, rec *persistence.TorrentRecord, snap engine.Snapshot) int64 { + hash := string(snap.ID) + s.seedCheckMu.Lock() + last, seen := s.lastSeedCounters[hash] + upDelta, downDelta := snap.BytesUp-last.up, snap.BytesDown-last.down + if upDelta < 0 { + upDelta = snap.BytesUp + } + if downDelta < 0 { + downDelta = snap.BytesDown + } + s.lastSeedCounters[hash] = sessionCounters{up: snap.BytesUp, down: snap.BytesDown} + s.seedCheckMu.Unlock() + if upDelta == 0 && downDelta == 0 { + return rec.TotalUploaded + } + if err := s.torrents.AddTransferTotals(ctx, hash, upDelta, downDelta); err != nil { + log.Warn().Err(err).Str("id", hash).Msg("seed policy: persist transfer totals failed") + s.seedCheckMu.Lock() + if seen { + s.lastSeedCounters[hash] = last + } else { + delete(s.lastSeedCounters, hash) + } + s.seedCheckMu.Unlock() + return rec.TotalUploaded + } + rec.TotalUploaded += upDelta + rec.TotalDownloaded += downDelta + return rec.TotalUploaded } diff --git a/backend/engine/fake.go b/backend/engine/fake.go index 76a5e81..ca86bd6 100644 --- a/backend/engine/fake.go +++ b/backend/engine/fake.go @@ -244,6 +244,22 @@ func (f *FakeBackend) SetFilePriorities(id TorrentID, prios map[int]Priority) er return nil } +// SetSessionStats is a test helper: overwrites the session byte counters and +// completion flag the way the anacrolix backend would report them. Completed +// torrents report BytesDone == TotalBytes, matching the real backend. +func (f *FakeBackend) SetSessionStats(id TorrentID, down, up int64, completed bool) { + f.mu.Lock() + defer f.mu.Unlock() + if t, ok := f.torrents[id]; ok { + t.BytesDown = down + t.BytesUp = up + t.Completed = completed + if completed { + t.BytesDone = t.TotalBytes + } + } +} + // AdvanceProgress is a test helper: bumps BytesDone for a torrent. func (f *FakeBackend) AdvanceProgress(id TorrentID, by int64) { f.mu.Lock() diff --git a/backend/persistence/migrations/0016_transfer_totals.sql b/backend/persistence/migrations/0016_transfer_totals.sql new file mode 100644 index 0000000..d35f120 --- /dev/null +++ b/backend/persistence/migrations/0016_transfer_totals.sql @@ -0,0 +1,12 @@ +-- +goose Up +-- Cumulative transfer totals in bytes, across engine sessions. anacrolix's +-- BytesWrittenData/BytesReadData counters reset every process start, so a +-- ratio computed from them restarted from 0 on every launch and ratio-based +-- seeding limits effectively never fired. CheckSeedLimits checkpoints the +-- session deltas into these columns each pass (see Torrents.AddTransferTotals). +ALTER TABLE torrents ADD COLUMN total_uploaded INTEGER NOT NULL DEFAULT 0; +ALTER TABLE torrents ADD COLUMN total_downloaded INTEGER NOT NULL DEFAULT 0; + +-- +goose Down +ALTER TABLE torrents DROP COLUMN total_downloaded; +ALTER TABLE torrents DROP COLUMN total_uploaded; diff --git a/backend/persistence/torrents.go b/backend/persistence/torrents.go index 6592ece..4a95516 100644 --- a/backend/persistence/torrents.go +++ b/backend/persistence/torrents.go @@ -32,6 +32,12 @@ type TorrentRecord struct { // Used by the seed-policy enforcement loop to measure seeding duration. SeedingStartedAt *time.Time Sequential bool + // TotalUploaded / TotalDownloaded are cumulative byte counters across + // engine sessions, checkpointed by CheckSeedLimits via AddTransferTotals. + // The engine's own counters reset every process start, so ratio-based + // seeding limits are computed from these instead. + TotalUploaded int64 + TotalDownloaded int64 } // Torrents is the DAO for the torrents table. @@ -117,7 +123,7 @@ func nullableBytes(b []byte) any { // Get returns a single record by infohash. func (t *Torrents) Get(ctx context.Context, infohash string) (TorrentRecord, error) { row := t.db.SQL().QueryRowContext(ctx, ` -SELECT infohash, name, COALESCE(magnet, ''), save_path, category_id, added_at, completed_at, paused, queue_position, force_start, metainfo, down_rate_limit, up_rate_limit, seed_policy, seeding_started_at, sequential +SELECT infohash, name, COALESCE(magnet, ''), save_path, category_id, added_at, completed_at, paused, queue_position, force_start, metainfo, down_rate_limit, up_rate_limit, seed_policy, seeding_started_at, sequential, total_uploaded, total_downloaded FROM torrents WHERE infohash = ?`, infohash) return scanTorrent(row) } @@ -125,7 +131,7 @@ FROM torrents WHERE infohash = ?`, infohash) // List returns all records ordered by added_at descending. func (t *Torrents) List(ctx context.Context) ([]TorrentRecord, error) { rows, err := t.db.SQL().QueryContext(ctx, ` -SELECT infohash, name, COALESCE(magnet, ''), save_path, category_id, added_at, completed_at, paused, queue_position, force_start, metainfo, down_rate_limit, up_rate_limit, seed_policy, seeding_started_at, sequential +SELECT infohash, name, COALESCE(magnet, ''), save_path, category_id, added_at, completed_at, paused, queue_position, force_start, metainfo, down_rate_limit, up_rate_limit, seed_policy, seeding_started_at, sequential, total_uploaded, total_downloaded FROM torrents ORDER BY added_at DESC`) if err != nil { return nil, err @@ -224,7 +230,7 @@ func scanTorrent(s scanner) (TorrentRecord, error) { var metainfo []byte var seedPolicy sql.NullString var seedingStartedAt sql.NullInt64 - if err := s.Scan(&r.InfoHash, &r.Name, &r.Magnet, &r.SavePath, &categoryID, &addedAt, &completedAt, &paused, &r.QueuePosition, &forceStart, &metainfo, &r.DownRateLimit, &r.UpRateLimit, &seedPolicy, &seedingStartedAt, &sequential); err != nil { + if err := s.Scan(&r.InfoHash, &r.Name, &r.Magnet, &r.SavePath, &categoryID, &addedAt, &completedAt, &paused, &r.QueuePosition, &forceStart, &metainfo, &r.DownRateLimit, &r.UpRateLimit, &seedPolicy, &seedingStartedAt, &sequential, &r.TotalUploaded, &r.TotalDownloaded); err != nil { if errors.Is(err, sql.ErrNoRows) { return r, ErrNotFound } @@ -253,6 +259,17 @@ func scanTorrent(s scanner) (TorrentRecord, error) { return r, nil } +// AddTransferTotals adds session-counter deltas to the persisted cumulative +// transfer totals. CheckSeedLimits checkpoints these every pass so that +// ratio-based seeding limits survive restarts — the engine's own byte +// counters reset to zero each process start. Missing rows are not an error. +func (t *Torrents) AddTransferTotals(ctx context.Context, infohash string, upDelta, downDelta int64) error { + _, err := t.db.SQL().ExecContext(ctx, + `UPDATE torrents SET total_uploaded = total_uploaded + ?, total_downloaded = total_downloaded + ? WHERE infohash = ?`, + upDelta, downDelta, infohash) + return err +} + // SetRateLimits persists per-torrent download and upload bandwidth caps. // Pass 0 for either to mean unlimited. func (t *Torrents) SetRateLimits(ctx context.Context, infohash string, downBytesPerSec, upBytesPerSec int64) error { diff --git a/backend/persistence/torrents_test.go b/backend/persistence/torrents_test.go index ad72b0b..094987d 100644 --- a/backend/persistence/torrents_test.go +++ b/backend/persistence/torrents_test.go @@ -186,3 +186,30 @@ func TestTorrents_CategoryAssignment(t *testing.T) { got, _ = tor.Get(ctx, "h1") require.Nil(t, got.CategoryID) } + +// TestTorrents_AddTransferTotals covers the cumulative cross-session counters +// CheckSeedLimits checkpoints: totals default to 0, accumulate per call, and +// updates to missing rows are not an error. +func TestTorrents_AddTransferTotals(t *testing.T) { + db := newTestDB(t) + tor := NewTorrents(db) + ctx := context.Background() + + require.NoError(t, tor.Save(ctx, TorrentRecord{ + InfoHash: "tt", Name: "n", SavePath: "/p", AddedAt: time.Now(), + })) + + got, err := tor.Get(ctx, "tt") + require.NoError(t, err) + require.Zero(t, got.TotalUploaded) + require.Zero(t, got.TotalDownloaded) + + require.NoError(t, tor.AddTransferTotals(ctx, "tt", 100, 200)) + require.NoError(t, tor.AddTransferTotals(ctx, "tt", 50, 25)) + got, err = tor.Get(ctx, "tt") + require.NoError(t, err) + require.Equal(t, int64(150), got.TotalUploaded) + require.Equal(t, int64(225), got.TotalDownloaded) + + require.NoError(t, tor.AddTransferTotals(ctx, "missing", 1, 1)) +}