ThreatFeedAlgo v2 — our recommender, published in full
The honest version: this is a client-side recommender that runs entirely in your browser. There is no server profiling, no account, and no viewing history sent anywhere. Your taste profile, seen history and saved list live only in your own browser's localStorage — clear your browser storage and the algorithm forgets you, because it never knew you anywhere else. Every weight below is a plain number you can inspect, and the complete production source is on this page.
⬇ Download threatfeed-algo.jsDownload README.md Try it live in THE FEED →
How a video earns its place
1 · Signals — dwell time
Dwell is measured when a card leaves the screen (a card counts as active at ~65% visible). Both the item's tags and its category receive the adjustment.
| Time on card | Signal | Reading |
|---|---|---|
| Under 2.5s | −2 | Fast skip — probably not for you |
| 2.5 – 8s | 0 | Not enough evidence — no signal |
| 8 – 25s | +2 | A real watch |
| Over 25s | +5 | A strong watch |
2 · Signals — explicit actions
| Action | Signal | Extra effect |
|---|---|---|
| Boost ▲ | +6 | — |
| Save ★ | +8 | Saved items are exempt from seen-rotation |
| Share ↗ | +10 | Any share target, or copy-link |
| Not Interested ✕ | −10 | Item marked seen; upcoming items sharing ≥2 tags or a title word are pulled from the queue |
| Tap a #tag | +2 | Feed switches to that tag |
3 · The scoring formula
Affinity = the sum of your profile weights for the item's tags, plus 1.5× your weight for its category, floored at 0. Popularity = for Archive items, log10(1+downloads) / log10(1+maxDownloads); other items carry fixed editorial values (0.45 YouTube, 0.5 TikTok, 0.62 community uploads, 0.85 seed films, 0.3 default). Jitter is deliberate randomness: weight 0.15 in steady state, boosted to 0.35 for the session's first 20 picks so a fresh visit opens with variety. (Short summaries quote “jitter × 0.15” — the code below is authoritative, and it boosts the opening.)
4 · Blending — 70 / 20 / 10
| Slots in each batch of 10 | Source |
|---|---|
| 7 | Affinity — highest-scored unseen items |
| 2 | Discovery — cross-source, ranked by downloads/popularity, preferring topics outside your current top tags |
| 1 | Wildcard — a random unseen item, preferring a deep Archive.org film |
The opening 10 cards are different by design: a session-seeded shuffle (mulberry32 PRNG, new seed every page load) of the unseen pool — which is why the feed doesn't greet you with the same videos twice — with 3–4 Archive films spliced into positions 3–10 as they load. Cards 11+ are score-ordered under the boosted opening jitter.
5 · Seen-tracking & reshuffle
A card active for ~1 second joins your seen history and won't headline a later visit. Your own added videos and Saved items are exempt. Unseen items always win; only when every item in the pool has been seen is the seen set cleared and the full pool reshuffled. Behind that, four Archive.org endpoints page in fresh films whenever unseen stock runs low — the pool is effectively endless.
6 · The topic affinity model
Your profile is two plain objects: tags and cats, each mapping a name to a number. Items get up to 8 tags: their own hashtags plus matches against a fixed vocabulary (defcon, malware, phishing, osint, ransomware, darkweb, retro, …) found in the title and caption. Categories: Serious, Funny, Documentaries, Talks, Retro, Edits. No embeddings, no collaborative filtering — with no server, there is nobody else's data to collaborate with. That is the privacy trade, made on purpose.
7 · localStorage schema
| Key | Shape | Meaning |
|---|---|---|
ts_feed_algo_v2 | {"tags":{}, "cats":{}} | Your taste profile |
ts_feed_seen_v2 | [itemId, …] | Shown history — drives no-repeat rotation |
ts_feed_saved_v2 | [itemId, …] | Saved list (mirrored to legacy tsFeedSaved) |
ts_feed_user_items_v1 | [rawItem, …] | Videos you added — pinned to the top of your feed |
Inspect yours live in the feed's ThreatFeedAlgo tuning drawer, or reset it any time with “Reset Algo & History”.
8 · Full source — exactly as it runs
This code view and the threatfeed-algo.js download are generated from the same file, so they cannot drift. The code was extracted verbatim from the production feed page on 2026-11-25; only the header comment and section banners were added. Plain-language companion: README.md.
/* * ============================================================================ * ThreatFeedAlgo v2 — the THREATSPHERE /feed recommendation algorithm * ============================================================================ * What it is: The complete client-side recommender that orders THE FEED * (https://www.thethreatwire.com/feed/). It learns from dwell * time and explicit actions (Boost / Save / Share / Not * Interested), scores every candidate, and blends each batch * 70/20/10 — affinity / cross-source discovery / wildcard. * Where it runs: Entirely in the visitor's browser. There is no server * profiling: the taste profile, seen history and saved list * live only in the visitor's own localStorage * (ts_feed_algo_v2 / ts_feed_seen_v2 / ts_feed_saved_v2). * Source: Extracted verbatim from the live feed page source * (feed-index.html) on 2026-11-25. The three sections below * are byte-for-byte copies of the production code: (1) the * core algorithm script, (2) the dwell-scoring function from * the player script, (3) the explicit-action handlers. * Only this header and the section banners were added. * License: Published by THREATSPHERE for study. Read it, learn from * it, check our math. The algorithm is presented as-is, as * it runs in production. * ============================================================================ */ /* ============================================================ * SECTION 1 of 3 — CORE ALGORITHM (verbatim production script) * ============================================================ */ "use strict"; /* ============================================================ ThreatFeedAlgo v2 — client-side, zero backend. Profile: localStorage ts_feed_algo_v2 {tags:{}, cats:{}} Seen: localStorage ts_feed_seen_v2 [ids] Saved: localStorage ts_feed_saved_v2 [ids] (+ legacy tsFeedSaved) Dwell: <2.5s -2 · 8-25s +2 · >25s +5 (tags AND category) Actions: Boost +6 · Save +8 · Share +10 · Not Interested -10 Score = affinity*0.65 + popularity*0.20 + jitter*0.15 Opening: session-seeded shuffle (fresh every load) + jitter 0.35 for the session's first 20 picks; Archive river spliced into the first 10. Shown = seen: a card active ~1s joins ts_feed_seen_v2 (own picks + Saved exempt). SINGLE-AUDIO: iframe players (Archive/TikTok) mount ONLY on the active card. Mix per 10: 7 affinity · 2 cross-source discovery · 1 wildcard ============================================================ */ var ALGO_KEY = "ts_feed_algo_v2", SEEN_KEY = "ts_feed_seen_v2", SAVED_KEY = "ts_feed_saved_v2", USER_KEY = "ts_feed_user_items_v1"; function lsGet(k, d){ try { var v = localStorage.getItem(k); return v ? JSON.parse(v) : d; } catch(e){ return d; } } function lsSet(k, v){ try { localStorage.setItem(k, JSON.stringify(v)); } catch(e){} } var profile = lsGet(ALGO_KEY, { tags:{}, cats:{} }); if (!profile.tags) profile.tags = {}; if (!profile.cats) profile.cats = {}; var seenSet = {}; lsGet(SEEN_KEY, []).forEach(function(id){ seenSet[id] = 1; }); var savedSet = {}; lsGet(SAVED_KEY, []).forEach(function(id){ savedSet[id] = 1; }); lsGet("tsFeedSaved", []).forEach(function(id){ savedSet[id] = 1; }); /* legacy carry-over */ var userItems = lsGet(USER_KEY, []); var S = { mode: "foryou", tagFilter: null, active: -1, queue: [], pool: {}, poolList: [], watched: 0, streak: 0, sound: (localStorage.getItem("tsFeedSound") !== "off"), unlocked: false, apiReady: false, fetching: false, pages: [1,1,1,1], epCursor: 0, maxDownloads: 1, exhausted: {}, sessionPicks: 0, seed: Math.floor(Math.random() * 1e9) + 1, archiveHeadDone: false }; function saveProfile(){ lsSet(ALGO_KEY, profile); } function saveSeen(){ lsSet(SEEN_KEY, Object.keys(seenSet)); } function saveSaved(){ lsSet(SAVED_KEY, Object.keys(savedSet)); lsSet("tsFeedSaved", Object.keys(savedSet)); } function applySignal(item, delta){ if (!item) return; (item.tags || []).forEach(function(t){ profile.tags[t] = (profile.tags[t] || 0) + delta; }); if (item.category) profile.cats[item.category] = (profile.cats[item.category] || 0) + delta; saveProfile(); } function affinity(item){ var a = 0; (item.tags || []).forEach(function(t){ a += (profile.tags[t] || 0); }); a += (profile.cats[item.category] || 0) * 1.5; return a; } function score(item){ var aff = Math.max(0, affinity(item)); var pop = item.downloads ? (Math.log10(1 + item.downloads) / Math.log10(1 + S.maxDownloads)) : (item.popularity || 0.3); var jw = (S.sessionPicks || 0) < 20 ? 0.35 : 0.15; /* opening variety: stronger jitter for the session's first 20 picks */ return aff * 0.65 + pop * 0.20 + Math.random() * jw; } /* Session-seeded shuffle: a fresh seed every page load deals a different head */ function mulberry32(a){ return function(){ a |= 0; a = (a + 0x6D2B79F5) | 0; var t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } function shuffleSeeded(arr){ var rnd = mulberry32(S.seed), i, j, tmp; for (i = arr.length - 1; i > 0; i--){ j = Math.floor(rnd() * (i + 1)); tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } return arr; } function isUserItem(it){ return !!(it && it.id && it.id.indexOf("usr-") === 0); } function seenExempt(it){ return isUserItem(it) || !!savedSet[it.id]; } /* own picks + Saved never rotate away */ function isIframeKind(item){ return item.sourceType === "archive" || item.platform === "tiktok"; } function topTags(n){ return Object.keys(profile.tags).sort(function(a,b){ return Math.abs(profile.tags[b]) - Math.abs(profile.tags[a]); }).slice(0, n || 3); } /* ================= Normalization into the unified FeedItem schema ================= */ var TAGWORDS = ["defcon","hacking","malware","espionage","encryption","surveillance","privacy","osint","scam","phishing","retro","coldwar","cspan","documentary","lecture","security","cyber","darkweb","ransomware","passwords","wifi","cloud","windows","linux","network","forensics","intelligence","spying","viruses","gadgets","funny","ai"]; function normTag(t){ return String(t || "").toLowerCase().replace(/^#/, "").replace(/[^a-z0-9]+/g, ""); } function extractTags(text, base){ var out = {}, hay = " " + String(text || "").toLowerCase() + " "; (base || []).forEach(function(t){ var n = normTag(t); if (n) out[n] = 1; }); TAGWORDS.forEach(function(w){ if (hay.indexOf(w) >= 0) out[w] = 1; }); if (hay.indexOf("def con") >= 0) out["defcon"] = 1; if (hay.indexOf("cold war") >= 0) out["coldwar"] = 1; return Object.keys(out).slice(0, 8); } function ytCategory(c){ var text = ((c.title || "") + " " + (c.caption || "")).toLowerCase(); if (c.cat === "Funny") return "Funny"; if (/documentary|documentary film/.test(text)) return "Documentaries"; if (/def con|defcon|black hat|keynote|talk|lecture|panel|conference/.test(text)) return "Talks"; return "Serious"; } function addToPool(item){ if (!item || !item.id || S.pool[item.id]) return false; S.pool[item.id] = item; S.poolList.push(item); if (item.downloads && item.downloads > S.maxDownloads) S.maxDownloads = item.downloads; return true; } function normalizeYT(c){ return { id: c.id, sourceType: "youtube", vid: c.id, embedUrl: "https://www.youtube.com/embed/" + c.id, thumbnailUrl: "https://i.ytimg.com/vi/" + c.id + "/hqdefault.jpg", title: c.title || "", category: ytCategory(c), tags: extractTags(c.title + " " + (c.caption || ""), c.tags), author: c.creator || "THREATSPHERE", handle: c.handle || "", isVerified: true, year: "", desc: c.caption || "", downloads: 0, popularity: 0.45, vertical: false, shareUrl: c.url || ("https://www.youtube.com/watch?v=" + c.id), pill: "YOUTUBE · VERIFIED" }; } function normalizeTT(c){ return { id: c.id, sourceType: "youtube", vid: c.vid, platform: "tiktok", embedUrl: "https://www.tiktok.com/embed/v2/" + c.vid, thumbnailUrl: c.thumb || "", title: c.title || "", category: "Funny", tags: extractTags(c.title, c.tags).concat(["edits"]), author: (c.creator || "LVO") + (c.handle ? " " + c.handle : ""), handle: c.handle || "", isVerified: true, year: "", desc: c.caption || "", downloads: 0, popularity: 0.5, vertical: true, shareUrl: c.url || "", pill: "YOUTUBE · VERIFIED" }; } function normalizeUpload(u){ return { id: u.id, sourceType: "community", platform: "upload", embedUrl: u.fileUrl, thumbnailUrl: u.posterUrl || "", title: u.title || "Community upload", category: "Serious", tags: extractTags(u.title + " " + (u.category || ""), ["community"]), author: u.uploader || "Community", handle: "", isVerified: false, year: "", desc: "Community wire upload via thethreatwire.com/feed/upload.", downloads: 0, popularity: 0.62, vertical: (u.height && u.width) ? (u.height > u.width) : false, shareUrl: "https://www.thethreatwire.com/feed/", pill: "COMMUNITY WIRE" }; } function archiveCategory(doc, tags){ var coll = doc.collection || [], text = ((doc.title || "") + " " + (doc.subject || "")).toLowerCase(); if ((Array.isArray(coll) && coll.indexOf("computerchronicles") >= 0) || /computer chronicles/.test(text)) return "Retro"; if (/documentary/.test(text)) return "Documentaries"; if (/def ?con|blackhat|conference|lecture|talk|summit|convention|presentation|cspan/.test(text)) return "Talks"; return "Serious"; } function stripHtml(s){ var d = document.createElement("div"); d.innerHTML = String(s || ""); return (d.textContent || "").replace(/\s+/g, " ").trim(); } function normalizeArchive(doc){ var id = doc.identifier; if (!id) return null; var subjects = []; if (Array.isArray(doc.subject)) subjects = doc.subject; else if (doc.subject) subjects = [doc.subject]; var tags = extractTags((doc.title || "") + " " + subjects.join(" "), subjects); var cat = archiveCategory(doc, tags); if (cat === "Documentaries" || cat === "Talks") tags.push("documentary" === cat.toLowerCase() ? "documentary" : "lecture"); return { id: "arc-" + id, sourceType: "archive", identifier: id, embedUrl: "https://archive.org/embed/" + id + "?autoplay=1", thumbnailUrl: "https://archive.org/services/img/" + id, title: doc.title || id, category: cat, tags: tags.slice(0, 8), author: "Internet Archive", handle: "", isVerified: true, year: doc.year || "", desc: stripHtml(doc.description).slice(0, 420), downloads: doc.downloads || 0, popularity: 0, vertical: false, shareUrl: "https://archive.org/details/" + id, pill: "ARCHIVE.ORG · FULL FILM" }; } function normalizeSeed(s){ return { id: "arc-" + s.identifier, sourceType: "archive", identifier: s.identifier, embedUrl: "https://archive.org/embed/" + s.identifier + "?autoplay=1", thumbnailUrl: "https://archive.org/services/img/" + s.identifier, title: s.title, category: s.category, tags: s.tags.slice(), author: "Internet Archive", handle: "", isVerified: true, year: String(s.year), desc: s.desc, downloads: 50000, popularity: 0.85, vertical: false, shareUrl: "https://archive.org/details/" + s.identifier, pill: "ARCHIVE.ORG · FULL FILM" }; } /* ================= Pool seeding: user items, uploads, existing catalog, seeds ================= */ var rankedOrder = null; function firstPaintItems(){ var yt = RAW_YT.map(normalizeYT), tt = RAW_TT.map(normalizeTT); var merged = [], yi = 0, ti = 0, total = yt.length + tt.length; while (yi < yt.length || ti < tt.length){ var ttDue = ti < tt.length && merged.length >= Math.floor((ti + 0.5) * total / tt.length); if (ttDue && yi > 0) merged.push(tt[ti++]); else if (yi < yt.length) merged.push(yt[yi++]); else merged.push(tt[ti++]); } if (rankedOrder){ var rank = {}; rankedOrder.forEach(function(id, i){ rank[id] = i; }); merged.sort(function(a, b){ return (rank[a.id] != null ? rank[a.id] : 500 + merged.indexOf(a)) - (rank[b.id] != null ? rank[b.id] : 500 + merged.indexOf(b)); }); } return merged; /* seed films no longer spliced at fixed spots — they rotate through the general pool (buildInitialQueue) */ } /* ================= Archive endless pipeline (4 endpoints) ================= */ var ENDPOINTS = [ 'subject:(hacking OR cybersecurity OR "computer security" OR defcon OR malware OR espionage OR "cyber warfare" OR cryptology)', 'title:(defcon OR "DEF CON" OR hope OR blackhat OR ccc)', 'subject:(espionage OR surveillance OR "computer crime" OR encryption OR intelligence)', 'collection:(computerchronicles)' ]; function fetchArchivePageAt(epIdx, page){ var q = ENDPOINTS[epIdx] + " AND mediatype:(movies)"; var url = "https://archive.org/advancedsearch.php?q=" + encodeURIComponent(q) + "&fl[]=identifier&fl[]=title&fl[]=description&fl[]=subject&fl[]=year&fl[]=downloads&fl[]=collection" + "&sort[]=downloads+desc&rows=100&page=" + page + "&output=json"; return fetch(url).then(function(r){ return r.json(); }).then(function(d){ var docs = (d && d.response && d.response.docs) || [], added = 0; docs.forEach(function(doc){ var it = normalizeArchive(doc); if (it && addToPool(it)) added++; }); return { added: added, docs: docs.length }; }).catch(function(){ return { added: 0, docs: 0 }; }); } function fetchArchivePage(epIdx){ var page = S.pages[epIdx]; return fetchArchivePageAt(epIdx, page).then(function(res){ if (!res.docs || res.docs < 100) S.exhausted[epIdx] = 1; S.pages[epIdx]++; return res.added; }); } /* Archive river in the OPENING: page 1 + one random page (2-40) from the cyber and hacker-talks endpoints at load; 3-4 items spliced into positions 3-10 as they land. */ function fetchArchiveHead(){ if (S.archiveHeadDone || S.mode !== "foryou") return; S.archiveHeadDone = true; var rndPage = function(){ return 2 + Math.floor(Math.random() * 39); }; Promise.all([fetchArchivePageAt(0, 1), fetchArchivePageAt(0, rndPage()), fetchArchivePageAt(1, 1), fetchArchivePageAt(1, rndPage())]).then(function(){ var arcs = S.poolList.filter(function(it){ return it.sourceType === "archive" && !seenSet[it.id]; }); if (!arcs.length) return; shuffleSeeded(arcs); var inQ = {}; S.queue.forEach(function(it){ inQ[it.id] = 1; }); var picks = arcs.filter(function(it){ return !inQ[it.id]; }).slice(0, 4); if (!picks.length) return; var userTop = 0; while (userTop < S.queue.length && isUserItem(S.queue[userTop])) userTop++; var cur = S.active, slots = [2, 4, 6, 8]; picks.forEach(function(it, i){ var pos = userTop + slots[i]; if (pos <= cur + 1) pos = cur + 2; /* never shift the card on screen or its mounted neighbour */ if (pos > S.queue.length) pos = S.queue.length; S.queue.splice(pos, 0, it); S.sessionPicks++; }); renderAll(); if (cur > 0) scrollToIdx(cur); else if (S.queue.length) setTimeout(function(){ var c = cards[0]; if (c) activate(c); }, 60); }).catch(function(){}); } function prefetch(){ if (S.fetching) return; var unseen = S.poolList.filter(function(it){ return !seenSet[it.id]; }).length; if (unseen >= 8) return; S.fetching = true; var tries = 0; (function next(){ if (tries >= 4 || S.poolList.filter(function(it){ return !seenSet[it.id]; }).length >= 60){ S.fetching = false; return; } var ep = S.epCursor % 4; S.epCursor++; tries++; if (S.exhausted[ep]) { next(); return; } fetchArchivePage(ep).then(next); })(); } /* ================= Queue building (modes + 70/20/10 blending) ================= */ function blendBatch(candidates){ var unseen = candidates.filter(function(it){ return !seenSet[it.id]; }); if (!unseen.length) return []; var tops = topTags(3); var scored = unseen.slice().sort(function(a, b){ return score(b) - score(a); }); var batch = [], used = {}; function take(it){ if (it && !used[it.id]){ used[it.id] = 1; batch.push(it); S.sessionPicks++; } } scored.slice(0, 7).forEach(take); /* 7 affinity */ var discovery = unseen.filter(function(it){ return !used[it.id]; }) .sort(function(a, b){ return (b.downloads || b.popularity || 0) - (a.downloads || a.popularity || 0); }); var srcSeen = {}; discovery.forEach(function(it){ if (batch.length < 9 && !(it.tags || []).some(function(t){ return tops.indexOf(t) >= 0 && profile.tags[t] > 4; })) { take(it); } }); discovery.forEach(function(it){ if (batch.length < 9) take(it); }); var rest = unseen.filter(function(it){ return !used[it.id]; }); /* 1 wildcard */ if (rest.length && batch.length < 10){ var deep = rest.filter(function(it){ return it.sourceType === "archive"; }); take((deep.length ? deep : rest)[Math.floor(Math.random() * (deep.length ? deep.length : rest.length))]); } while (batch.length < 10 && scored.length > batch.length){ var nx = scored[batch.length]; if (nx && !used[nx.id]) take(nx); else break; } return batch; } function modeFilter(mode){ if (mode === "serious") return function(it){ return it.category === "Serious"; }; if (mode === "funny") return function(it){ return it.category === "Funny"; }; if (mode === "docs") return function(it){ return it.category === "Documentaries" || it.category === "Talks"; }; if (mode === "saved") return function(it){ return !!savedSet[it.id]; }; if (mode === "tag") return function(it){ return (it.tags || []).indexOf(S.tagFilter) >= 0; }; return function(){ return true; }; } function buildInitialQueue(){ S.sessionPicks = 0; S.archiveHeadDone = false; var items = firstPaintItems(); items.forEach(function(it){ addToPool(it); }); SEEDS.map(normalizeSeed).forEach(function(it){ addToPool(it); }); /* seed films rotate through the general pool — no fixed opening block */ var userQ = []; userItems.forEach(function(raw){ var it = userItemNormalize(raw); if (it){ addToPool(it); userQ.unshift(it); } }); var f = modeFilter(S.mode); var base = items.filter(f); /* Rotation: cards shown in earlier sessions leave the opening (own picks + Saved exempt) */ var fresh = base.filter(function(it){ return !seenSet[it.id] || seenExempt(it); }); var headPool = fresh.length >= 4 ? fresh : base; var shuffled = shuffleSeeded(headPool.slice()); /* session-seeded head: a different first card every visit */ var head = shuffled.slice(0, 10); head.forEach(function(){ S.sessionPicks++; }); S.queue = userQ.filter(f).concat(head); var rest = shuffled.slice(10); /* cards 11+: ThreatAlgo scoring under the boosted opening jitter */ if (rest.length){ var scoredRest = rest.slice().sort(function(a, b){ return score(b) - score(a); }); scoredRest.slice(0, 10).forEach(function(it){ S.queue.push(it); S.sessionPicks++; }); scoredRest.slice(10).forEach(function(it){ S.queue.push(it); }); } if (S.mode !== "foryou"){ var inQ0 = {}; S.queue.forEach(function(it){ inQ0[it.id] = 1; }); S.poolList.forEach(function(it){ if (f(it) && !inQ0[it.id]) S.queue.push(it); }); } if (S.mode === "foryou"){ var inQ = {}; S.queue.forEach(function(it){ inQ[it.id] = 1; }); blendBatch(S.poolList.filter(function(it){ return !inQ[it.id]; })).forEach(function(it){ S.queue.push(it); }); fetchArchiveHead(); /* Archive river spliced into the first 10 as it lands */ } } function extendQueue(){ var f = modeFilter(S.mode); var batch; if (S.mode === "foryou" || S.mode === "all" || S.mode === "tag") batch = blendBatch(S.poolList.filter(f)); else { var unseen = S.poolList.filter(function(it){ return f(it) && !seenSet[it.id]; }) .sort(function(a, b){ return score(b) - score(a); }); batch = unseen.slice(0, 10); } if (!batch.length){ var anyLeft = S.poolList.filter(f); if (anyLeft.length && anyLeft.every(function(it){ return seenSet[it.id]; })){ anyLeft.forEach(function(it){ delete seenSet[it.id]; }); saveSeen(); /* pool exhausted — reshuffle cleanly, roll on */ toast("The wire never stops — reshuffling the full pool."); return extendQueue(); } prefetch(); return 0; } var before = S.queue.length; batch.forEach(function(it){ S.queue.push(it); renderCard(it, S.queue.length - 1); }); prefetch(); return S.queue.length - before; } /* ============================================================ * SECTION 2 of 3 — DWELL SCORING (verbatim: deactivate(), from the * player script — this is where dwell time becomes a signal) * ============================================================ */ function deactivate(card){ if (card.seenTimer){ clearTimeout(card.seenTimer); card.seenTimer = null; } if (card.activatedAt && !card.dwellDone){ var secs = (Date.now() - card.activatedAt) / 1000, d = 0; if (secs < 2.5) d = -2; else if (secs >= 8 && secs <= 25) d = 2; else if (secs > 25) d = 5; if (d) applySignal(card.item, d); card.dwellDone = true; } card.activatedAt = 0; try { if (card.player && card.kind === "youtube") card.player.pauseVideo(); } catch(e){} try { if (card.player && card.kind === "video") card.player.pause(); } catch(e){} if (card.player && card.kind === "iframe") unmountPlayer(card); /* stop off-screen audio at once */ } /* ============================================================ * SECTION 3 of 3 — EXPLICIT ACTIONS (verbatim: Boost / Save / * Not Interested / Reshuffle handlers, from the player script) * ============================================================ */ /* ================= Explicit actions ================= */ function doBoost(item, btn){ applySignal(item, +6); if (btn){ btn.classList.remove("pulse"); void btn.offsetWidth; btn.classList.add("pulse"); btn.classList.add("on"); setTimeout(function(){ btn.classList.remove("on"); }, 600); } toast("Boosted — more like this in your feed."); } function doSave(item, btn){ if (savedSet[item.id]){ delete savedSet[item.id]; toast("Removed from Saved."); if (btn){ btn.classList.remove("saved"); btn.querySelector("span").textContent = "SAVE"; } } else { savedSet[item.id] = 1; applySignal(item, +8); toast("Saved — find it under the Saved pill."); if (btn){ btn.classList.add("saved"); btn.querySelector("span").textContent = "SAVED"; } } saveSaved(); } function doNotInterested(item, idx){ applySignal(item, -10); seenSet[item.id] = 1; saveSeen(); var words = (item.title || "").toLowerCase().split(/[^a-z0-9]+/).filter(function(w){ return w.length > 4; }); for (var i = S.queue.length - 1; i > idx; i--){ var q = S.queue[i]; var shared = (q.tags || []).filter(function(t){ return (item.tags || []).indexOf(t) >= 0; }).length; var titleHit = words.some(function(w){ return (q.title || "").toLowerCase().indexOf(w) >= 0; }); if (shared >= 2 || titleHit){ S.queue.splice(i, 1); } } renderAll(); scrollToIdx(Math.min(idx, S.queue.length - 1)); toast("Got it — less of that. Similar titles pulled from your queue."); } function doReshuffle(idx){ var head = S.queue.slice(0, idx + 1), tail = S.queue.slice(idx + 1); var fresh = [], guard = 0; while (tail.length && guard++ < 12){ var b = blendBatch(tail); if (!b.length) break; b.forEach(function(it){ var p = tail.indexOf(it); if (p >= 0) tail.splice(p, 1); fresh.push(it); }); } S.queue = head.concat(fresh).concat(tail); renderAll(); scrollToIdx(idx); toast("Upcoming queue re-ranked."); }