Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: harden peer-hosted media streaming against disabled peers, stale entries, and stalled bodies

Adam Eivy73c6d14984c8
diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsx
index 15395fe162..bb9f32a7fa 100644
--- a/client/src/pages/MediaCollectionDetail.jsx
+++ b/client/src/pages/MediaCollectionDetail.jsx
@@ -95,13 +95,13 @@ export default function MediaCollectionDetail() {
// (its /data/images URL falls through to the peer server-side). Videos need
// no stub: their rows arrive with the synced video history.
const galleryRows = useMemo(() => {
- if (isUnsorted || page.hasMore) return page.items;
+ if (isUnsorted) return page.items;
const present = new Set(page.items.filter(row => row.kind === 'image').map(row => row.data.filename));
const remoteStubs = (collection?.items || [])
.filter(item => item.kind === 'image' && item.location === 'remote' && !present.has(item.ref))
.map(item => ({ kind: 'image', data: { filename: item.ref, prompt: '', createdAt: item.addedAt } }));
return remoteStubs.length ? [...page.items, ...remoteStubs] : page.items;
- }, [page.items, page.hasMore, collection, isUnsorted]);
+ }, [page.items, collection, isUnsorted]);
const items = useMemo(() => galleryRows.filter(row => isUnsorted || collection?.items?.some(ref => ref.kind === row.kind && ref.ref === (row.kind === 'image' ? row.data.filename : row.data.id)))
.map(normalizeMediaRow), [galleryRows, collection, isUnsorted]);
const remoteKeys = useMemo(() => (collection?.items || []).filter(item => item.location === 'remote').map(item => `${item.kind}:${item.ref}`), [collection]);
diff --git a/server/routes/mediaCollections.js b/server/routes/mediaCollections.js
index 64b10982fe..bdcb107e63 100644
--- a/server/routes/mediaCollections.js
+++ b/server/routes/mediaCollections.js
@@ -20,7 +20,7 @@ import { z } from 'zod';
import { asyncHandler, ServerError, createServiceErrorMapper } from '../lib/errorHandler.js';
import { validateRequest, mediaCollectionBulkItemsSchema, isPaginationRequested, paginateArray } from '../lib/validation.js';
import * as svc from '../services/mediaCollections.js';
-import { resolveMediaLocations, unmarkHosted } from '../services/peerHostedMedia.js';
+import { resolveMediaLocations, unmarkHosted, findHostPeer } from '../services/peerHostedMedia.js';
import { pullMissingAssetsFromPeer, collectionVideoRefToFilename } from '../services/sharing/peerSyncAssets.js';
const router = Router();
@@ -104,6 +104,7 @@ router.post('/:id/localize', asyncHandler(async (req, res) => {
});
const started = [...byPeer.values()].reduce((n, list) => n + list.length, 0);
Promise.all([...byPeer.entries()].map(async ([peerId, list]) => {
+ if (!await findHostPeer(peerId)) return; // disabled or removed peer: nothing to pull from
await pullMissingAssetsFromPeer(peerId, list, { includeMismatched: false });
await Promise.all(list.map((entry) => unmarkHosted(entry.kind, entry.filename)));
})).catch((err) => console.error(`❌ localize collection media failed: ${err.message}`));
diff --git a/server/services/peerHostedMedia.js b/server/services/peerHostedMedia.js
index b3c605a5ab..3f33020bad 100644
--- a/server/services/peerHostedMedia.js
+++ b/server/services/peerHostedMedia.js
@@ -100,6 +100,13 @@ export async function takeHostedAssets(peerInstanceId, missingAssets, collection
return remaining;
}
+function forgetHosted(kind, filename) {
+ return queueWrite(async () => {
+ const entries = await readEntries();
+ if (delete entries[hostedKey(kind, filename)]) await writeEntries(entries);
+ }).catch(() => {});
+}
+
/** Drop a hosted entry once its bytes are local; a still-absent file keeps its entry. */
export function unmarkHosted(kind, filename) {
return queueWrite(async () => {
@@ -136,6 +143,12 @@ export async function resolveMediaLocations(items) {
// importing it (that module would drag the whole peer-sync graph in here).
const videoRefToFilename = (ref) => (isStr(ref) ? (/\.[a-z0-9]+$/i.test(ref) ? ref : `${ref}.mp4`) : null);
+/** The registered, ENABLED peer behind a hosted entry (a disabled peer stops every direction). */
+export async function findHostPeer(instanceId) {
+ const peers = await getPeers().catch(() => []);
+ return peers.find((p) => p.instanceId === instanceId && p.enabled !== false) || null;
+}
+
async function lookupHosted(kind, filename) {
const entries = await readEntriesOrEmpty();
return entries[hostedKey(kind, filename)] || null;
@@ -151,11 +164,11 @@ async function resolveHostedRequest(mount, filename) {
if (!safe) return null;
if (mount === '/data/images') {
const hosted = await lookupHosted('image', safe);
- return hosted && { peerId: hosted.peerId, url: `${KIND_PREFIX.image}/${encodeURIComponent(safe)}` };
+ return hosted && { peerId: hosted.peerId, url: `${KIND_PREFIX.image}/${encodeURIComponent(safe)}`, drop: { kind: 'image', filename: safe } };
}
if (mount === '/data/videos') {
const hosted = await lookupHosted('video', safe);
- return hosted && { peerId: hosted.peerId, url: `${KIND_PREFIX.video}/${encodeURIComponent(safe)}` };
+ return hosted && { peerId: hosted.peerId, url: `${KIND_PREFIX.video}/${encodeURIComponent(safe)}`, drop: { kind: 'video', filename: safe } };
}
if (mount === '/data/image-thumbnails') {
// `<stem>.webp` is derived from `<stem>.png`; the peer serves its own
@@ -187,10 +200,9 @@ export function hostedAssetFallback(mount) {
if (!filename || filename.includes('/')) return next();
const target = await resolveHostedRequest(mount, filename).catch(() => null);
if (!target) return next();
- const peers = await getPeers().catch(() => []);
- const peer = peers.find((p) => p.instanceId === target.peerId);
+ const peer = await findHostPeer(target.peerId);
if (!peer) return next();
- await streamFromPeer(peer, target.url, req, res).catch((err) => {
+ await streamFromPeer(peer, target.url, req, res, target.drop).catch((err) => {
console.warn(`⚠️ peerHostedMedia: stream ${mount} from ${peer.name || 'peer'} failed: ${err.message}`);
if (!res.headersSent) res.status(502).end();
else res.destroy();
@@ -198,13 +210,16 @@ export function hostedAssetFallback(mount) {
};
}
-async function streamFromPeer(peer, path, req, res) {
+async function streamFromPeer(peer, path, req, res, drop) {
const headers = {};
if (isStr(req.headers.range)) headers.Range = req.headers.range;
const upstream = await withAbortTimeout(STREAM_TIMEOUT_MS, (signal) =>
peerStreamRequest(`${peerBaseUrl(peer)}${path}`, { signal, headers }, peer));
if (upstream.status !== 200 && upstream.status !== 206) {
upstream.stream.resume();
+ // The peer no longer has it (deleted, or a snapshot referenced bytes it never
+ // held): forget the entry so the collection stops advertising it as hosted.
+ if (upstream.status === 404 && drop) await forgetHosted(drop.kind, drop.filename);
res.status(upstream.status === 404 ? 404 : 502).end();
return;
}
@@ -222,5 +237,7 @@ async function streamFromPeer(peer, path, req, res) {
upstream.stream.destroy();
return res.end();
}
+ // The header-wait timer is spent by now; bound a stalled body too.
+ upstream.stream.setTimeout?.(STREAM_TIMEOUT_MS, () => upstream.stream.destroy(new Error('peer media stream idle timeout')));
await pipeline(upstream.stream, res);
}
diff --git a/server/services/peerHostedMedia.test.js b/server/services/peerHostedMedia.test.js
index 3aaf6250bc..1ae1e64bed 100644
--- a/server/services/peerHostedMedia.test.js
+++ b/server/services/peerHostedMedia.test.js
@@ -18,7 +18,8 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => (
afterAll(() => rmSync(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
const PEER = { id: 'p1', instanceId: 'peer-instance-1', name: 'Studio Mac', host: 'peer.example.com', port: 5555 };
-vi.mock('./instances.js', () => ({ getPeers: vi.fn(async () => [PEER]) }));
+const getPeers = vi.fn(async () => [PEER]);
+vi.mock('./instances.js', () => ({ getPeers: (...args) => getPeers(...args) }));
const streamRequest = vi.fn();
vi.mock('../lib/peerHttpClient.js', () => ({ peerStreamRequest: (...args) => streamRequest(...args) }));
@@ -37,6 +38,7 @@ beforeAll(() => {
beforeEach(async () => {
streamRequest.mockReset();
+ getPeers.mockImplementation(async () => [PEER]);
rmSync(join(tempRoot, 'peer-hosted-media.json'), { force: true });
});
@@ -137,4 +139,19 @@ describe('static-mount fallback', () => {
const res = await request(app).get('/data/images/offline.png');
expect(res.status).toBe(502);
});
+
+ it('never streams from a disabled peer', async () => {
+ await markHosted(PEER.instanceId, [{ kind: 'image', filename: 'paused.png' }]);
+ getPeers.mockImplementation(async () => [{ ...PEER, enabled: false }]);
+ const res = await request(app).get('/data/images/paused.png');
+ expect(res.status).toBe(404);
+ expect(streamRequest).not.toHaveBeenCalled();
+ });
+
+ it('forgets a hosted entry once the peer answers 404, so it stops reading as remote', async () => {
+ await markHosted(PEER.instanceId, [{ kind: 'image', filename: 'gone.png' }]);
+ streamRequest.mockResolvedValue(upstream('nope', 404));
+ expect((await request(app).get('/data/images/gone.png')).status).toBe(404);
+ expect((await resolveMediaLocations([{ kind: 'image', ref: 'gone.png' }]))[0].location).toBe('missing');
+ });
});