Update library lists when a move finishes (#1)
CI / test (push) Successful in 1m14s

The Library now follows moves on both servers: an item shows "Moving to …" while it moves and "Moved to …" until the source's Jellyfin drops
it after its rescan; the list reloads when a move finishes and checks again every 20 s for a few minutes. The destination shows the new item
straight away.
This commit is contained in:
IxianPixel committed 2026-11-06 17:21:22 +00:00
1 parent 484ac50508
commit 2bd4489b1a
9 files changed
+236 -61

No files matched your search

+7 -2
View File
@@ -5,6 +5,7 @@
import Jobs from './lib/Jobs.svelte';
import StatusView from './lib/StatusView.svelte';
import Trash from './lib/Trash.svelte';
import { watchMoves } from './lib/moves.svelte';
type Tab = 'library' | 'jobs' | 'trash' | 'status';
let tab = $state<Tab>('library');
@@ -23,7 +24,11 @@
onMount(() => {
loadStatus();
const t = setInterval(loadStatus, 30_000);
return () => clearInterval(t);
const stopWatching = watchMoves();
return () => {
clearInterval(t);
stopWatching();
};
});
const localName = $derived(status?.node.node_name ?? 'this server');
@@ -63,7 +68,7 @@
{/if}
{#if tab === 'library'}
<Library {localName} {peerName} onmoved={() => (tab = 'jobs')} />
<Library {localName} {peerName} />
{:else if tab === 'jobs'}
<Jobs {localName} />
{:else if tab === 'trash'}
+9 -37
View File
@@ -1,52 +1,24 @@
<script lang="ts">
import { onMount } from 'svelte';
import { api, bytes, STAGE_LABEL, STAGES, type Job } from './api';
import { moves, trackMove } from './moves.svelte';
interface Props {
localName: string;
}
let { localName }: Props = $props();
let jobs = $state<Record<string, Job>>({});
let peerError = $state<string | null>(null);
let error = $state<string | null>(null);
let retryError = $state<string | null>(null);
let open = $state<Record<string, boolean>>({});
const sorted = $derived(Object.values(jobs).sort((a, b) => b.created.localeCompare(a.created)));
async function load() {
try {
const view = await api.jobs();
const next: Record<string, Job> = {};
for (const j of [...view.local, ...view.peer]) next[j.id] = j;
jobs = next;
peerError = view.peer_error;
error = null;
} catch (e) {
error = (e as Error).message;
}
}
onMount(() => {
load();
// Live progress for jobs running here; poll for jobs running on the peer.
const es = new EventSource('/api/events');
es.addEventListener('job', (ev) => {
const j = JSON.parse((ev as MessageEvent).data) as Job;
jobs[j.id] = j;
});
const t = setInterval(load, 2000);
return () => {
es.close();
clearInterval(t);
};
});
const sorted = $derived(Object.values(moves.jobs).sort((a, b) => b.created.localeCompare(a.created)));
const error = $derived(retryError ?? moves.error);
async function retry(id: string) {
try {
jobs[id] = await api.retry(id);
trackMove(await api.retry(id));
retryError = null;
} catch (e) {
error = (e as Error).message;
retryError = (e as Error).message;
}
}
@@ -75,9 +47,9 @@
</script>
{#if error}<p class="panel msg error">{error}</p>{/if}
{#if peerError}<p class="panel msg muted">Couldn't load moves running on the peer: {peerError}</p>{/if}
{#if moves.peerError}<p class="panel msg muted">Couldn't load moves running on the peer: {moves.peerError}</p>{/if}
{#if !sorted.length}
{#if moves.loaded && !sorted.length}
<p class="panel empty muted">No moves yet. Pick something in Library to get started.</p>
{/if}
+98 -21
View File
@@ -1,13 +1,13 @@
<script lang="ts">
import { onMount } from 'svelte';
import { api, bytes, type Library, type LibraryItem, type Movable, type SeasonItem, type Side } from './api';
import { moves, onMoveDone, trackMove } from './moves.svelte';
interface Props {
localName: string;
peerName: string;
onmoved: () => void;
}
let { localName, peerName, onmoved }: Props = $props();
let { localName, peerName }: Props = $props();
let side = $state<Side>('local');
let libraries = $state<Library[]>([]);
@@ -28,22 +28,57 @@
const shown = $derived(
sort === 'size' ? [...items].sort((a, b) => (b.size?.bytes ?? -1) - (a.size?.bytes ?? -1)) : items,
);
const measuring = $derived(items.filter((i) => !i.size).length);
const total = $derived(items.reduce((n, i) => n + (i.size?.bytes ?? 0), 0));
// Sizes are worked out in the background on the server that has the
// files; ask again until they've all arrived.
// Items with a move under way, or one that finished recently but that the
// source's Jellyfin still lists (it drops them after its own rescan).
const RECENT_MS = 15 * 60_000;
type Mark = { moving: boolean; to: string };
const marks = $derived.by(() => {
const out: Record<string, Mark> = {};
const now = Date.now();
for (const j of Object.values(moves.jobs)) {
if (j.dry_run || j.source_node !== sourceName) continue;
const active = j.status.kind === 'Queued' || j.status.kind === 'Running';
if (active) {
out[j.source_item_id] = { moving: true, to: j.target_node };
} else if (j.status.kind === 'Done' && now - Date.parse(j.updated) < RECENT_MS) {
out[j.source_item_id] ??= { moving: false, to: j.target_node };
}
}
return out;
});
let poll: ReturnType<typeof setTimeout> | undefined;
let recheck: ReturnType<typeof setTimeout> | undefined;
let rechecks = 0;
let generation = 0;
function stopPolling() {
clearTimeout(poll);
clearTimeout(recheck);
poll = undefined;
recheck = undefined;
}
/** While a moved item is still listed, look again every 20 s for a few minutes. */
function recheckMoved(gen: number) {
if (rechecks >= 12 || !items.some(gone)) return;
rechecks++;
recheck = setTimeout(() => {
if (gen === generation) loadItems();
}, 20_000);
}
/** An item that has moved away: its folder is gone, so it has no size to wait for. */
const gone = (i: LibraryItem) => !!marks[i.id] && !marks[i.id].moving;
const measuring = $derived(items.filter((i) => !i.size && !gone(i)).length);
function pollSizes(gen: number, attempt = 0) {
stopPolling();
if (!items.some((i) => !i.size) || attempt >= 150) return;
clearTimeout(poll);
if (!items.some((i) => !i.size && !gone(i)) || attempt >= 150) return;
poll = setTimeout(async () => {
try {
const fresh = await api.items(side, libraryId, search.trim());
@@ -62,10 +97,15 @@
const have = seasons[item.id];
if (!open[item.id] || (have && 'list' in have)) return;
seasons[item.id] = { loading: true };
await loadSeasons(item.id);
}
async function loadSeasons(id: string) {
try {
seasons[item.id] = { list: await api.seasons(side, item.id) };
const list = await api.seasons(side, id);
if (open[id]) seasons[id] = { list };
} catch (e) {
seasons[item.id] = { error: (e as Error).message };
if (open[id]) seasons[id] = { error: (e as Error).message };
}
}
@@ -93,7 +133,10 @@
libraries = [];
try {
libraries = await api.libraries(s);
const prev = libraryId;
libraryId = libraries[0]?.id ?? '';
// Same library ID on the other server: the effect won't fire, so load here.
if (libraryId === prev) loadItems();
} catch (e) {
error = (e as Error).message;
}
@@ -110,6 +153,7 @@
if (gen !== generation) return;
items = got;
pollSizes(gen);
recheckMoved(gen);
} catch (e) {
if (gen !== generation) return;
error = (e as Error).message;
@@ -129,7 +173,16 @@
onMount(() => {
loadLibraries(side);
// When a move to or from the server being browsed finishes, show the
// result: the item leaves the source and appears on the destination.
const unsubscribe = onMoveDone((job) => {
if (job.source_node !== sourceName && job.target_node !== sourceName) return;
rechecks = 0;
loadItems();
for (const id of Object.keys(open)) if (open[id]) loadSeasons(id);
});
return () => {
unsubscribe();
generation++;
stopPolling();
};
@@ -148,12 +201,10 @@
notice = null;
error = null;
try {
await api.move(side, item, dryRun);
if (dryRun) {
notice = `Planning a dry run for “${item.name}”. Check Moves for the plan.`;
} else {
onmoved();
}
trackMove(await api.move(side, item, dryRun));
notice = dryRun
? `Planning a dry run for “${item.name}”. Check Moves for the plan.`
: `Moving “${item.name}” to ${destName}. Follow its progress in Moves.`;
} catch (e) {
error = (e as Error).message;
} finally {
@@ -162,6 +213,14 @@
}
</script>
{#snippet moveTag(mark: Mark)}
{#if mark.moving}
<span class="tag moving">Moving to {mark.to}…</span>
{:else}
<span class="tag" title="{sourceName}'s Jellyfin will drop it from this list after its next scan">Moved to {mark.to}</span>
{/if}
{/snippet}
<section class="toolbar">
<div class="sides" role="radiogroup" aria-label="Browse which server">
<button role="radio" aria-checked={side === 'local'} class="local" class:on={side === 'local'} onclick={() => choose('local')}>
@@ -219,15 +278,19 @@
{/if}
</div>
<span class="size" title={item.size ? fileCount(item.size.files) : 'Working out the size…'}>
{#if item.size}{bytes(item.size.bytes)}{:else}<span class="muted">measuring…</span>{/if}
{#if item.size}{bytes(item.size.bytes)}{:else if !gone(item)}<span class="muted">measuring…</span>{/if}
</span>
<div class="actions">
<button disabled={busy === item.id} onclick={() => move(item, true)} title="Check and plan without copying anything">
Dry run
</button>
<button class="primary" disabled={busy === item.id} onclick={() => move(item, false)}>
Move to {destName} →
</button>
{#if marks[item.id]}
{@render moveTag(marks[item.id])}
{:else}
<button disabled={busy === item.id} onclick={() => move(item, true)} title="Check and plan without copying anything">
Dry run
</button>
<button class="primary" disabled={busy === item.id} onclick={() => move(item, false)}>
Move to {destName} →
</button>
{/if}
</div>
</div>
{#if open[item.id]}
@@ -247,7 +310,9 @@
<td class="muted">{part ? fileCount(part.files) : ''}</td>
<td class="num">{part ? bytes(part.bytes) : ''}</td>
<td class="acts">
{#if season.path}
{#if marks[season.id]}
{@render moveTag(marks[season.id])}
{:else if season.path}
<button class="small" disabled={busy === season.id} onclick={() => move(what, true)} title="Check and plan without copying anything">
Dry run
</button>
@@ -381,6 +446,18 @@
padding-right: 0;
white-space: nowrap;
}
.tag {
font-size: 0.82rem;
border: 1px solid var(--line);
border-radius: 6px;
padding: 0.2rem 0.55rem;
color: var(--muted);
white-space: nowrap;
}
.tag.moving {
color: var(--peer);
border-color: color-mix(in srgb, var(--peer) 50%, var(--line));
}
.seasons-msg {
margin: 0.5rem 0 0 3.5rem;
font-size: 0.88rem;
+84
View File
@@ -0,0 +1,84 @@
// Every move on either server, kept up to date for the whole app: live
// events for moves running here, and polling for moves running on the peer
// (fast while something is moving, slow otherwise).
import { api, type Job } from './api';
export const moves = $state({
jobs: {} as Record<string, Job>,
error: null as string | null,
peerError: null as string | null,
loaded: false,
});
type DoneListener = (job: Job) => void;
const listeners = new Set<DoneListener>();
/** Call `fn` whenever a move (not a dry run) finishes. Returns an unsubscribe. */
export function onMoveDone(fn: DoneListener): () => void {
listeners.add(fn);
return () => listeners.delete(fn);
}
const isActive = (j: Job) => j.status.kind === 'Queued' || j.status.kind === 'Running';
/** Record a job snapshot and tell listeners if it has just finished. */
function put(job: Job) {
const before = moves.jobs[job.id];
moves.jobs[job.id] = job;
const finished = job.status.kind === 'Done' && !job.dry_run && before && before.status.kind !== 'Done';
// A move we only learn about once it's done (e.g. it finished between
// polls) still counts, as long as the list had loaded before.
const unseen = job.status.kind === 'Done' && !job.dry_run && !before && moves.loaded;
if (finished || unseen) for (const fn of listeners) fn(job);
}
export async function refreshMoves() {
try {
const view = await api.jobs();
const all = [...view.local, ...view.peer];
for (const j of all) put(j);
// Forget jobs that no longer exist anywhere.
const ids = new Set(all.map((j) => j.id));
for (const id of Object.keys(moves.jobs)) if (!ids.has(id)) delete moves.jobs[id];
moves.peerError = view.peer_error;
moves.error = null;
moves.loaded = true;
} catch (e) {
moves.error = (e as Error).message;
}
}
let timer: ReturnType<typeof setTimeout> | undefined;
let running = false;
async function tick() {
clearTimeout(timer);
await refreshMoves();
if (!running) return;
const busy = Object.values(moves.jobs).some(isActive);
timer = setTimeout(tick, busy ? 2000 : 10_000);
}
/** Note a move just started here, and check on it soon. */
export function trackMove(job: Job) {
put(job);
if (running) {
clearTimeout(timer);
timer = setTimeout(tick, 1000);
}
}
/** Start watching for the lifetime of the app. Returns a stop function. */
export function watchMoves(): () => void {
if (running) return () => {};
running = true;
const es = new EventSource('/api/events');
es.addEventListener('job', (ev) => put(JSON.parse((ev as MessageEvent).data) as Job));
tick();
return () => {
running = false;
clearTimeout(timer);
es.close();
};
}