From 450e6a19a59643219ac0df7fd1eba9e4e04ab4c6 Mon Sep 17 00:00:00 2001 From: FahadBinHussain Date: Thu, 1 Oct 2026 23:31:37 +0600 Subject: [PATCH 01/15] fix comments icon vanishing after yt music player bar update (0.1.1) the icon stopped appearing after yt changed the player bar. the old single anchor (.middle-controls-buttons > ytmusic-menu-renderer) broke two ways: the menu renderer now only stamps when yt serves currentItem.menu, and isMiniplayerEnabled can swap the whole top bar for the lit ytmusic-miniplayer which has no middle-controls at all. placeButton() now walks ordered anchors - menu renderer, like button (unconditional sibling), middle-controls-buttons, then the miniplayer action bar. a non-primary anchor warns once and stamps data-ytm-anchor-strategy on the host; if nothing matches it logs the observed dom structure instead of failing silently. App.vue also warns when /watch loses its ?v= param, since that hides the button with display:none. all diagnostics go through the new warnOnce() helper so a full session logs a handful of lines instead of hundreds. --- composables/usePlayerBarButton.ts | 72 ++++++++++++++++++++++++++----- entrypoints/ytm.content/App.vue | 17 ++++++++ lib/log.ts | 10 +++++ package.json | 2 +- 4 files changed, 89 insertions(+), 12 deletions(-) create mode 100644 lib/log.ts diff --git a/composables/usePlayerBarButton.ts b/composables/usePlayerBarButton.ts index 349e905..b7f63ba 100644 --- a/composables/usePlayerBarButton.ts +++ b/composables/usePlayerBarButton.ts @@ -1,18 +1,54 @@ import { onScopeDispose, watch, type Ref } from 'vue'; +import { warnOnce } from '@/lib/log'; const BUTTON_ID = 'ytm-comments-injected-button'; const STYLE_ID = 'ytm-comments-injected-style'; const ICON_SVG = ``; -function findMenuSibling(): { parent: HTMLElement; after: HTMLElement } | null { - const playerBar = document.querySelector('ytmusic-player-bar'); - if (!playerBar) return null; - const menu = playerBar.querySelector( - '.middle-controls-buttons > ytmusic-menu-renderer', - ) as HTMLElement | null; - if (!menu || !menu.parentElement) return null; - return { parent: menu.parentElement, after: menu }; +// what the player bar actually looks like right now — logged when injection +// fails, so a console paste pins the exact DOM break instead of guessing +function observedStructure(): string { + const mcb = document.querySelector('ytmusic-player-bar .middle-controls-buttons'); + return JSON.stringify({ + playerBar: !!document.querySelector('ytmusic-player-bar'), + miniplayer: !!document.querySelector('ytmusic-miniplayer'), + miniActionBar: !!document.querySelector('.ytMusicMiniPlayerActionBar'), + mcbChildren: mcb ? [...mcb.children].map((c) => c.tagName.toLowerCase()).join(',') : null, + }); +} + +// ytm music reshapes the player bar in updates. anchor order: +// 1. the menu renderer (original target) — only stamped when yt serves +// currentItem.menu, so it can vanish while the bar itself is intact +// 2. the like button — unconditional child of middle-controls-buttons +// 3. middle-controls-buttons itself +// 4. the new lit miniplayer's action bar (yt replaced the top bar with +// ytmusic-miniplayer behind isMiniplayerEnabled — no middle-controls there) +// a non-primary strategy logs loudly once (data-ytm-anchor-strategy on the +// host records it for inspection too); total failure logs the observed DOM. +function placeButton(host: HTMLElement): string | null { + const mcb = document.querySelector('ytmusic-player-bar .middle-controls-buttons') as HTMLElement | null; + if (mcb) { + const menu = mcb.querySelector(':scope > ytmusic-menu-renderer') as HTMLElement | null; + if (menu) { + menu.before(host); + return 'player-bar menu-renderer'; + } + const like = mcb.querySelector(':scope > ytmusic-like-button-renderer') as HTMLElement | null; + if (like) { + like.after(host); + return 'player-bar like-button (menu renderer not stamped)'; + } + mcb.append(host); + return 'player-bar middle-controls-buttons (like + menu both missing)'; + } + const miniBar = document.querySelector('.ytMusicMiniPlayerActionBar') as HTMLElement | null; + if (miniBar) { + (miniBar.shadowRoot ?? miniBar).append(host); + return miniBar.shadowRoot ? 'miniplayer action bar (shadow root)' : 'miniplayer action bar'; + } + return null; } function ensureGlobalStyle() { @@ -101,11 +137,25 @@ export function usePlayerBarButton( function inject(): HTMLElement | null { const existing = document.getElementById(BUTTON_ID); if (existing) return existing; - const anchor = findMenuSibling(); - if (!anchor) return null; ensureGlobalStyle(); const host = createButton(onClick); - anchor.after.insertAdjacentElement('beforebegin', host); + const strategy = placeButton(host); + if (!strategy) { + warnOnce( + 'anchor-missing', + 'comments button NOT injected — no player bar anchor found. observed:', + observedStructure(), + ); + return null; + } + host.setAttribute('data-ytm-anchor-strategy', strategy); + if (strategy !== 'player-bar menu-renderer') { + warnOnce( + `anchor-strategy ${strategy}`, + 'yt music player bar DOM changed — comments button placed via non-primary anchor:', + strategy, + ); + } applyActive(host, active.value); applyVisibility(host, visible.value); return host; diff --git a/entrypoints/ytm.content/App.vue b/entrypoints/ytm.content/App.vue index c03462f..7a8b71b 100644 --- a/entrypoints/ytm.content/App.vue +++ b/entrypoints/ytm.content/App.vue @@ -8,11 +8,28 @@ import { useVideoId } from '@/composables/useVideoId'; import { useComments } from '@/composables/useComments'; import { useReplies } from '@/composables/useReplies'; import { usePlayerBarButton } from '@/composables/usePlayerBarButton'; +import { warnOnce } from '@/lib/log'; const ctx = inject('ctx')!; const { videoId, pathname } = useVideoId(ctx); const isWatchPage = computed(() => pathname.value === '/watch' && !!videoId.value); +// visibility failures are silent by design (button just gets display:none) — +// surface them once so "icon vanished" traces to url detection vs dom anchor +watch( + [pathname, videoId], + ([p, v]) => { + warnOnce(`nav ${p}`, `pathname=${p} videoId=${v || '(none)'}`); + if (p === '/watch' && !v) { + warnOnce('watch-no-video-id', 'on /watch but no ?v= param — comments button hidden. href=', location.href); + } + if (p !== '/watch' && new URLSearchParams(location.search).has('v')) { + warnOnce('watch-path-changed', `video id present but pathname is not /watch — yt music may have changed the route. pathname=${p} href=`, location.href); + } + }, + { immediate: true }, +); + const open = ref(false); const { state, loadMore, setSort } = useComments(videoId, isWatchPage); const replies = useReplies(); diff --git a/lib/log.ts b/lib/log.ts new file mode 100644 index 0000000..8207f9b --- /dev/null +++ b/lib/log.ts @@ -0,0 +1,10 @@ +// edge hides console.debug by default, so diagnostics use console.warn. +// comment scrolling fires dozens of identical api calls and the repeat lines +// bury the signals that actually matter — each key logs once per page load. +const _seen = new Set(); + +export function warnOnce(key: string, ...args: any[]): void { + if (_seen.has(key)) return; + _seen.add(key); + console.warn('[ytm-comments]', ...args); +} diff --git a/package.json b/package.json index 2a1c7bc..b5636f2 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "ytm-comments", "description": "Read YouTube comments inline on music.youtube.com", "private": true, - "version": "0.1.0", + "version": "0.1.1", "license": "MIT", "author": "andronedev", "repository": { From 0d48d36339743d1d566c613b99e5d79bc9822dbf Mon Sep 17 00:00:00 2001 From: FahadBinHussain Date: Thu, 1 Oct 2026 23:31:56 +0600 Subject: [PATCH 02/15] harvest innertube context same-origin so comment threads keep loading fetching the www.youtube.com homepage for INNERTUBE_CONTEXT is CORS-blocked from a music content script, which left the client version stuck on the hardcoded 2.20240101.00.00 fallback - a stale client makes yt return comment pages without the framework updates, so threads silently come back empty. the current origin's own page embeds a fresh context and is same-origin, so harvest from there instead. extraction walks balanced braces (a non-greedy regex stops at the first nested brace and truncates the object). the music page serves WEB_REMIX, which gets no comments at all, so the harvest rewrites it to WEB keeping the date with the canonical .00.00 build. each harvest failure warns once instead of on every refresh. --- lib/clientContext.ts | 104 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 95 insertions(+), 9 deletions(-) diff --git a/lib/clientContext.ts b/lib/clientContext.ts index 3392667..03866ff 100644 --- a/lib/clientContext.ts +++ b/lib/clientContext.ts @@ -1,5 +1,6 @@ import { storage } from '#imports'; import type { ClientContext } from './types'; +import { warnOnce } from './log'; export const FALLBACK_CLIENT_CONTEXT: ClientContext = { client: { @@ -40,20 +41,96 @@ async function writeSessionCache(value: ClientContext): Promise { } } +// balanced-brace extraction: a non-greedy regex stops at the first nested '}', +// which silently truncates INNERTUBE_CONTEXT (it has nested objects) and makes +// JSON.parse fail -> harvest returns null -> stale hardcoded fallback client. +// walk to the matching brace instead, respecting string literals. +function extractJSONObjectAt(html: string, key: string): string | null { + const keyStart = html.indexOf(`"${key}"`); + if (keyStart < 0) return null; + const objStart = html.indexOf('{', keyStart); + if (objStart < 0) return null; + let depth = 0; + let inStr = false; + let escape = false; + for (let i = objStart; i < html.length; i++) { + const c = html[i]; + if (inStr) { + if (escape) escape = false; + else if (c === '\\') escape = true; + else if (c === '"') inStr = false; + continue; + } + if (c === '"') inStr = true; + else if (c === '{') depth++; + else if (c === '}') { + depth--; + if (depth === 0) return html.slice(objStart, i + 1); + } + } + return null; +} + async function harvestLiveContext(): Promise { try { - const res = await fetch('https://www.youtube.com/', { - credentials: 'omit', + // same-origin only: from a music.youtube.com content script, fetching the + // www.youtube.com HOMEPAGE is CORS-blocked (its HTML sends no + // Access-Control-Allow-Origin, unlike the /youtubei API endpoints — that + // silent failure is what left the client version stuck on the 2.5-year-old + // hardcoded fallback, which makes youtube gate the engagement toolbar + // surface behind an inert innertubeCommand placeholder instead of the real + // performCommentActionEndpoint). the current origin's own page embeds a + // fresh INNERTUBE_CONTEXT, and same-origin means no CORS and same-site + // cookies, so it works from the content script. + const res = await fetch(`${location.origin}/`, { + credentials: 'include', headers: { 'accept-language': 'en-US,en;q=0.9' }, }); - if (!res.ok) return null; + if (!res.ok) { + warnOnce('ctx-harvest-status', `client context harvest: same-origin fetch returned ${res.status}`); + return null; + } const html = await res.text(); - const match = html.match(/"INNERTUBE_CONTEXT":(\{.+?\}),"INNERTUBE_CONTEXT_CLIENT_NAME"/); - if (!match) return null; - const parsed = JSON.parse(match[1]); - if (!parsed?.client?.clientName) return null; - return parsed as ClientContext; - } catch { + const raw = extractJSONObjectAt(html, 'INNERTUBE_CONTEXT'); + if (!raw) { + warnOnce('ctx-harvest-missing', 'client context harvest: INNERTUBE_CONTEXT not found in same-origin page html'); + return null; + } + const parsed = JSON.parse(raw); + if (!parsed?.client?.clientName || !parsed?.client?.clientVersion) { + warnOnce('ctx-harvest-incomplete', 'client context harvest: parsed context missing client name/version'); + return null; + } + // the music page serves the WEB_REMIX client ("1.YYYYMMDD.XX.XX"). comment + // threads + the engagement toolbar surface are only served to the WEB + // client ("2.YYYYMMDD.XX.XX") — a WEB_REMIX /next returns no comment + // framework at all ("comments are disabled"). WEB bumps the same date; + // emit the canonical first build of that day (.00.00 always exists, while + // reusing the music build number can name a WEB version that was never + // published and makes youtube gate the surface). rewrite to WEB without + // needing the CORS-blocked www homepage. pass through only fields the + // Context proto actually knows — extras can make youtube's json parser + // reject the whole request. + let clientName: string = parsed.client.clientName; + let clientVersion: string = parsed.client.clientVersion; + if (clientName === 'WEB_REMIX' && clientVersion.startsWith('1.')) { + clientName = 'WEB'; + const datePart = clientVersion.slice(2).split('.')[0]; + clientVersion = `2.${datePart}.00.00`; + } + const ctx: ClientContext = { + client: { + clientName, + clientVersion, + hl: parsed.client.hl ?? 'en', + gl: parsed.client.gl ?? 'US', + userAgent: parsed.client.userAgent ?? (typeof navigator !== 'undefined' ? navigator.userAgent : ''), + }, + }; + console.info(`[ytm-comments] harvested client context: ${clientName} ${clientVersion}`); + return ctx; + } catch (e) { + warnOnce('ctx-harvest-failed', 'client context harvest failed:', e); return null; } } @@ -64,6 +141,15 @@ export async function getClientContext(): Promise { } const cached = await readSessionCache(); if (cached) return cached; + // never serve the stale hardcoded fallback on a cold read path — a 2.5-year-old + // clientVersion makes youtube return comments WITHOUT the engagement toolbar + // surface (no likeCommand), which silently downgrades liking. harvest a live + // context first; only fall back if the harvest itself fails. + const live = await harvestLiveContext(); + if (live) { + await writeSessionCache(live); + return live; + } return FALLBACK_CLIENT_CONTEXT; } From c39c29337be1d5f7dda14fa0e220305341e8ef76 Mon Sep 17 00:00:00 2001 From: FahadBinHussain Date: Thu, 1 Oct 2026 23:31:56 +0600 Subject: [PATCH 03/15] add agent notes: icon anchor strategies, context harvest, logging, windows quirks --- AGENTS.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 AGENTS.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..5061672 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,29 @@ +# ytm-comments — agent notes + +## comments icon anchor (fragile) + +- `composables/usePlayerBarButton.ts` injects the icon into the player bar. the primary anchor `.middle-controls-buttons > ytmusic-menu-renderer` broke in the 2026-09 yt music update twice over: the menu renderer now sits in `template is="dom-if" if="[[currentItem.menu]]"` (never stamps when yt stops serving menu data), and `isMiniplayerEnabled` can swap the whole top bar for the lit `ytmusic-miniplayer` (no middle-controls-buttons at all). +- `placeButton()` walks 4 ordered anchors: menu renderer -> like button (unconditional sibling) -> middle-controls-buttons -> `.ytMusicMiniPlayerActionBar`. non-primary strategies log loudly once and stamp `data-ytm-anchor-strategy` on the host; total failure logs the observed DOM structure instead of staying silent. +- against a future yt update: download the live bundle (`https://music.youtube.com/s//music_polymer_inlined_html.js`, hash in the homepage html), grep for the anchor classes, and only then touch the selectors. + +## client context + +- `lib/clientContext.ts` harvests `INNERTUBE_CONTEXT` from the current origin's own page (same-origin, no CORS) instead of the www.youtube.com homepage, which is CORS-blocked from a music content script. extraction walks balanced braces — a non-greedy regex truncates on nested `}` and silently kills JSON.parse. +- the music page serves `WEB_REMIX` (`1.YYYYMMDD.XX.XX`); comment threads are only served to `WEB` (`2.YYYYMMDD.XX.XX`), so the harvest rewrites the name and keeps the date with the canonical `.00.00` build. never serve the hardcoded `2.20240101.00.00` fallback on a cold read path — a stale client version makes yt drop comment framework updates. + +## logging + +- all diagnostics go through `lib/log.ts` `warnOnce(key, ...)` — each key logs once per page load. edge hides `console.debug` by default, and the parse path runs per comment thread, so an unguarded `console.warn` floods the console within one scroll. + +## windows / pnpm quirks + +- `pnpm install` on this machine fails with `[ERR_PNPM_IGNORED_BUILDS] esbuild`. use `npx vue-tsc --noEmit` (or `npm run compile`) and `npx wxt build` directly — they succeed without install. +- `npx wxt build` writes `.output/chrome-mv3/` — load unpacked from there. + +## manifest version bump + +- version is derived from `package.json:version`. bump it in the same commit as code — browser update checks only fire on a higher version. + +## fragile file + +- `lib/parseComments.ts` — yt reshapes `frameworkUpdates` paths a few times a year. keep `?.` chains and the brute-force `includes(commentId)` fallback. From 023516386ca8244c556bcdad17e5d7649174852a Mon Sep 17 00:00:00 2001 From: Fahad Date: Sat, 19 Sep 2026 09:34:57 +0600 Subject: [PATCH 04/15] add like support for comments and replies --- AGENTS.md | 28 ++--- components/CommentItem.vue | 132 ++++++++++++++++++++- components/ReplyList.vue | 92 +++++++++++++- lib/auth.ts | 33 ++++++ lib/parseComments.ts | 237 ++++++++++++++++++++++++++++++++----- lib/types.ts | 11 ++ lib/youtubeApi.ts | 113 ++++++++++++++++++ package.json | 2 +- 8 files changed, 599 insertions(+), 49 deletions(-) create mode 100644 lib/auth.ts diff --git a/AGENTS.md b/AGENTS.md index 5061672..0ed215d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,29 +1,23 @@ # ytm-comments — agent notes -## comments icon anchor (fragile) +## like support (0.2.0) -- `composables/usePlayerBarButton.ts` injects the icon into the player bar. the primary anchor `.middle-controls-buttons > ytmusic-menu-renderer` broke in the 2026-09 yt music update twice over: the menu renderer now sits in `template is="dom-if" if="[[currentItem.menu]]"` (never stamps when yt stops serving menu data), and `isMiniplayerEnabled` can swap the whole top bar for the lit `ytmusic-miniplayer` (no middle-controls-buttons at all). -- `placeButton()` walks 4 ordered anchors: menu renderer -> like button (unconditional sibling) -> middle-controls-buttons -> `.ytMusicMiniPlayerActionBar`. non-primary strategies log loudly once and stamp `data-ytm-anchor-strategy` on the host; total failure logs the observed DOM structure instead of staying silent. -- against a future yt update: download the live bundle (`https://music.youtube.com/s//music_polymer_inlined_html.js`, hash in the homepage html), grep for the anchor classes, and only then touch the selectors. - -## client context - -- `lib/clientContext.ts` harvests `INNERTUBE_CONTEXT` from the current origin's own page (same-origin, no CORS) instead of the www.youtube.com homepage, which is CORS-blocked from a music content script. extraction walks balanced braces — a non-greedy regex truncates on nested `}` and silently kills JSON.parse. -- the music page serves `WEB_REMIX` (`1.YYYYMMDD.XX.XX`); comment threads are only served to `WEB` (`2.YYYYMMDD.XX.XX`), so the harvest rewrites the name and keeps the date with the canonical `.00.00` build. never serve the hardcoded `2.20240101.00.00` fallback on a cold read path — a stale client version makes yt drop comment framework updates. - -## logging - -- all diagnostics go through `lib/log.ts` `warnOnce(key, ...)` — each key logs once per page load. edge hides `console.debug` by default, and the parse path runs per comment thread, so an unguarded `console.warn` floods the console within one scroll. +- liking uses `POST https://www.youtube.com/youtubei/v1/comment/perform_comment_action` — same `context` as `youtubei/v1/next` but needs extra auth headers. `host_permissions` for `https://www.youtube.com/*` already covers it. +- auth: `Authorization: SAPISIDHASH _` from `SAPISID` or `__Secure-3PAPISID` cookie. generate via `crypto.subtle.digest('SHA-1', ...)` in `lib/auth.ts`. also send `X-Goog-AuthUser: 0` and `X-Goog-Visitor-Id: VISITOR_INFO1_LIVE` if present. `credentials: 'include'` still required so cookies go through. without `SAPISID` the endpoint returns 401 — surface as `Sign in to YouTube to like comments` not silent. +- payload shape: toolbar surface entity (`engagementToolbarSurfaceEntityPayload`) contains `likeCommand` / `unlikeCommand` wrapping `performCommentActionEndpoint`. don't invent proto — reuse the command object youtube returns. `lib/youtubeApi.ts:performCommentAction` tries 3 body variants (raw spread, inner endpoint, actions array) and fails LOUDLY on last variant if all 400. no fallback to fake success. +- parsing: `frameworkUpdates.entityBatchUpdate.mutations` contains 3 payload types: `commentEntityPayload`, `engagementToolbarStateEntityPayload` (`likeState === TOOLBAR_LIKE_STATE_LIKED`), `engagementToolbarSurfaceEntityPayload` (`likeCommand`/`unlikeCommand`/`prepareAccountCommand`). original `lib/parseComments.ts` only kept first two, so like state/commands were lost. now `buildEntityMaps()` keeps all three and maps `commentId -> state/surface` by `entityKey.includes(commentId)` with `JSON.stringify(v).includes(commentId)` brute-force fallback — keys are `comment_toolbar_state.` style but yt reshapes yearly. +- ui: `components/CommentItem.vue` and `ReplyList.vue` do optimistic toggle — flip `isLiked` + `likeCount` (+1/-1 if numeric else keep string), store `likedAnim` for 300ms scale 1.35, rollback on catch and show `role="alert"` error. button disabled when `!canLike` (surface has `prepareAccountCommand`). all icons have motion (`transform` + `transition: cubic-bezier(0.34,1.56,0.64,1)`). +- types: `Comment`/`Reply` now `isLiked`, `isDisliked`, `canLike`, `likeCommand`, `unlikeCommand`. ## windows / pnpm quirks -- `pnpm install` on this machine fails with `[ERR_PNPM_IGNORED_BUILDS] esbuild`. use `npx vue-tsc --noEmit` (or `npm run compile`) and `npx wxt build` directly — they succeed without install. -- `npx wxt build` writes `.output/chrome-mv3/` — load unpacked from there. +- `pnpm install` on this machine fails with `[ERR_PNPM_IGNORED_BUILDS] esbuild` due to ignored-builds policy. don't run `pnpm install` before compile. use `npx vue-tsc --noEmit` and `npx wxt build` directly — they succeed without install. if you must install, run `pnpm install --ignore-scripts` or approve builds, but CI doesn't need it. +- `npx wxt build` writes `.output/chrome-mv3/` — load unpacked from there. `pnpm zip` still works but wraps extra github zip. ## manifest version bump -- version is derived from `package.json:version`. bump it in the same commit as code — browser update checks only fire on a higher version. +- version is derived from `package.json:version`. bump it (patch for fixes, minor for features like like support) in same commit as code — tampermonkey/browser update checks only fire on higher version. ## fragile file -- `lib/parseComments.ts` — yt reshapes `frameworkUpdates` paths a few times a year. keep `?.` chains and the brute-force `includes(commentId)` fallback. +- `lib/parseComments.ts` — yt reshapes `frameworkUpdates` paths a few times a year. keep `?.` chains and fallback brute-force `includes(commentId)` check. diff --git a/components/CommentItem.vue b/components/CommentItem.vue index b0a9b69..35fafad 100644 --- a/components/CommentItem.vue +++ b/components/CommentItem.vue @@ -1,14 +1,88 @@