Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
450e6a1
fix comments icon vanishing after yt music player bar update (0.1.1)
FahadBinHussain Oct 1, 2026
0d48d36
harvest innertube context same-origin so comment threads keep loading
FahadBinHussain Oct 1, 2026
c39c293
add agent notes: icon anchor strategies, context harvest, logging, wi…
FahadBinHussain Oct 1, 2026
0235163
add like support for comments and replies
FahadBinHussain Sep 19, 2026
3509b1c
fix like not available: send sapisidhash on next so youtube returns l…
FahadBinHussain Sep 19, 2026
a08e0c1
quiet the console: one-shot diagnostics (0.2.2)
FahadBinHussain Sep 19, 2026
21681b8
notes: warnOnce diagnostics + storage.local is a dead transport
FahadBinHussain Sep 19, 2026
2c3e4f1
fix probe false negative: log raw logged_in serialization (0.2.3)
FahadBinHussain Sep 19, 2026
03345dc
probe D: cookies-only + session cookie inventory (0.2.4)
FahadBinHussain Sep 19, 2026
8234c87
notes: innertube landscape - upstream dead, YouTube.js auth still cur…
FahadBinHussain Oct 1, 2026
8d765a7
hash sapisid over page origin so comment like actually authenticates …
FahadBinHussain Oct 2, 2026
323d799
notes: restore icon anchor, client context and logging sections for t…
FahadBinHussain Oct 2, 2026
b555f10
notes: cherry-pick conflict rules for version and agent notes files
FahadBinHussain Oct 2, 2026
21fe274
docs: readme covers like support and the same-origin context harvest
FahadBinHussain Oct 6, 2026
a88fb2b
notes: upstream revived - landscape and pr status updated
FahadBinHussain Oct 20, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# ytm-comments — agent notes

## like support (0.2.1)

- **root cause of `logged_in=0` on EVERY probe, incl. cookies-only (fixed 0.2.6)**: `getSapisidAuth()` hashed the SAPISIDHASH over the constant `https://www.youtube.com`, but youtube validates the hash against the `Origin` header the browser actually sends — a `music.youtube.com` page always sends `Origin: https://music.youtube.com`. www-hashed headers were therefore invalid and youtube served every extension request logged-out: `yt_li=0`, account_menu without identity, and the engagement surface replacing `likeCommand` with a sign-in `modalEndpoint` ("Want to join the conversation?"). confirmed with a live header matrix (2026-10-01): hash over `location.origin` → `yt_li=1` on both music.* and www.* targets; www-origin hash from a music page → `0` or `400`. fix: hash `location.origin` (`lib/auth.ts`), never a hardcoded host. note: `document.cookie` cannot see httpOnly `HSID`/`SSID`/`LOGIN_INFO` — an inventory from JS looks "partial" even when the jar is fine; use CDP `Storage.getCookies` before blaming cookies.
- **root cause of "Like not available for this comment" (0.2.0)**: the `/youtubei/v1/next` fetches never sent the `Authorization: SAPISIDHASH` header. YouTube only returns `engagementToolbarSurfaceEntityPayload` (which holds `likeCommand`/`unlikeCommand`) to *authenticated* requests. cookies alone were enough for locale + like *state* in some cases but not the like *commands*. fix: `postRaw()` now spreads `buildAuthHeaders()` into every request, so the primary path carries the surface commands.
- 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 <timestamp>_<sha1(timestamp + ' ' + SAPISID + ' ' + location.origin)>` from `SAPISID` or `__Secure-3PAPISID` cookie. generate via `crypto.subtle.digest('SHA-1', ...)`. origin MUST be the page origin (`location.origin`, i.e. `https://music.youtube.com`) — see root-cause note above. 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: the surface entity stores the command **wrapped in `innertubeCommand`** (`{innertubeCommand: {clickTrackingParams, commandMetadata, performCommentActionEndpoint: {action}}}`) — `extractActionPayload()` must unwrap it recursively or the body contains a key the endpoint schema does not know and youtube answers `400 INVALID_ARGUMENT`. canonical POST body (confirmed working 2026-10-01): `{context, actions: [action], clickTrackingParams}` — action normalized to `actions[]` like YouTube.js `Actions.execute`. the endpoint-wrapped spread `{context, clickTrackingParams, commandMetadata, performCommentActionEndpoint}` is ALWAYS 400 and is kept only as last shape-drift probe; if a non-primary variant succeeds the loop warns `perform-comment-variant` (no silent fallback). don't invent proto — reuse the command object youtube returns. fails LOUDLY on last variant if all 4xx. 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.<id>` 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`.
- fallback policy: if the surface command is still missing after auth, `performFallbackLikeById()` tries a synthetic `commentId`-keyed body (4 shape variants). this 2nd method is shown LOUDLY as an amber `FALLBACK: synthetic commentId method` badge next to the button — it never pretends to be the primary path, and any failure rolls back + shows the server's own error text. per global rule, no silent fallback ever.
- debug: **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 (the gated-surface warn alone fired ~20 times per page). keys in use: `request auth headers`, `AUTH PROBE <label>` (`probeAuthState`, one-shot via `_authProbed`), `parse debug`, `surface-gated`, `surface-prepare-coexist`, `performCommentAction payload`, `like-blocked` / `reply-like-blocked`, `ctx-harvest-*`. check these in the music.youtube.com tab console (page console, not the extension popup) when like misbehaves.
- **chrome.storage.local is a dead diagnostic transport here**: `browser.storage.local.set` succeeds but edge's leveldb (`User Data/Default/Local Extension Settings/<id>/000003.log`) never flushed to disk — the file stayed 0 bytes for hours, even across extension reloads. do not bring back the `ytmDebugParse`/`ytmDebugLike` stash; console pastes are the only channel that works.

## innertube landscape (rechecked 2026-10-20)

- upstream `andronedev/ytm-comments` **revived** after5 months dormant — v0.2.0 (2026-10-18) reworked the player bar injection (new miniplayer + legacy bar), added `lib/i18n`, moved comment loading to anonymous `credentials: 'omit'` requests, and dropped the clientContext harvest; v0.2.1 (2026-10-19) centered the icon. the maintainer reviews actively again — always check upstream before assuming it is stale. our icon PR (#1) was superseded by that rework and is closed; the like PR (#2) got a scope offer instead: anonymous /next stays, auth only on the like request itself, opt-in prompt + drawer toggle, ONE body shape with a clear error (no probes, no variant loop, no synthetic fallback), strings via lib/i18n, no AGENTS.md, no version bump, fresh PR against current main. parked for now — the one design wrinkle: the like `action` token only arrives in an authenticated /next, so enabling likes must refetch with auth at that moment.
- `LuanRT/YouTube.js` (reference innertube impl, v18.1.0 as of 2026-09-22) confirms our auth approach is still current: `HTTPClient` sends exactly `Authorization: SAPISIDHASH` from the `SAPISID` cookie + `X-Goog-Visitor-Id` + `X-Goog-Authuser` (`account_index`, we hardcode 0) + `credentials: 'include'`. two deltas worth knowing: (1) it now appends `alt=json` to every innertube URL (`prettyPrint=false&alt=json`) — changes response serialization to plain JSON, which is how `logged_in` shows as a real bool instead of `{"key":...,"value":...}` pairs; (2) `Actions.execute` normalizes `action` -> `actions: [action]`, same as our variant-2/3 bodies — our body shapes match YouTube.js behavior.
- YouTube.js PR #1248 (`feat: BotGuardManager`, open, unmerged) adds attestation plumbing (`/att/get`, `RunAttestationCommand`, `eacr_token`) — targets YouTube Studio Web actions, NOT comment engagement, and not on main. if comment liking ever gets attestation-gated, that PR + `LuanRT/BgUtils` is the reference. do not implement attestation preemptively.
- the ViewModel + mutations comment architecture (`commentViewModel.commentKey` -> `frameworkUpdates.entityBatchUpdate.mutations[].entityKey` join) has been current since ~Apr 2026 and is what `buildEntityMaps()` already does — not a new break.

## 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/<hash>/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` 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 (patch for fixes, minor for features like like support) in same commit as code — tampermonkey/browser update checks only fire on higher version.

## fragile files

- `lib/parseComments.ts` — yt reshapes `frameworkUpdates` paths a few times a year. keep `?.` chains and fallback brute-force `includes(commentId)` check.
- **button click isolation** (2026-10-01): with the miniplayer anchor our button lands inside yt's `ytVideoActionBarViewModelHost` — an unhandled click bubbling into it triggers yt's router store subscription (`music_polymer_inlined_html.js` `WZ`) which `pushState('/')` within ~1ms, kicking the page off `/watch`. the click listener therefore lives on the `yt-button-shape` (covers inner-button AND shape-padding clicks) and calls `stopPropagation()` — moving it back to the inner button re-opens that hole. symptom if broken: page navigates home right after clicking the comments icon.

## git

- cherry-picks between the icon branch and the like branch always conflict on `package.json` (the version line) and `AGENTS.md`. resolve with `git checkout --theirs -- <file>` — the incoming side already carries the right version — then `git -c core.editor=true cherry-pick --continue`. never hand-edit around conflict markers; a `-replace` that only swapped the version line once shipped nested markers into a whole test branch and the picks had to be redone.
- in powershell a multi-line `git log --format=%B` result becomes an array, and `git commit -m $array` sends each line (including empty ones) as a pathspec — fatal. rely on `cherry-pick --continue`, which reuses the original message.
23 changes: 15 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ A speech-bubble icon shows up in the player bar between the like button and
the three-dot menu. Click it and a drawer slides up with the comments of the
track playing right now.

Read-only: you can browse, sort Top / Newest, and expand replies. You can't
post or like — that would need real auth and isn't what this is for.
Read and like: browse, sort Top / Newest, expand replies, and like any
comment or reply from your own signed-in YouTube session. You still can't
post new comments — writing would need a different endpoint and isn't what
this is for.

**Heads up — current limitation:** the button only shows comments when the
track has a real YouTube video counterpart (i.e. music videos). For
Expand Down Expand Up @@ -68,6 +70,10 @@ itself hits when you open a video. Two calls per track: first
`{continuation: token}` for the first page. CORS works because the manifest
declares `host_permissions` for `youtube.com`, and the user's existing
YouTube cookies are sent so locale and personalised like state come through.
Each request also carries a `SAPISIDHASH` auth header derived from the page's
own origin — that header is what makes YouTube hand over the like commands
alongside the comments at all; unauthenticated asks get the comments without
them.

Track changes inside YT Music are picked up via WXT's `wxt:locationchange`
event. The videoId in `music.youtube.com/watch?v=…` is the same string as
Expand All @@ -78,21 +84,22 @@ on regular YouTube, so reading `?v=` is enough — no mapping.
- `entrypoints/ytm.content/` — content script, Vue root
- `components/` — drawer, comment list, item, replies, sort menu
- `composables/` — `useVideoId`, `useComments`, `useReplies`, `usePlayerBarButton`
- `lib/` — `youtubeApi.ts`, `clientContext.ts`, parsers, types
- `lib/` — `youtubeApi.ts`, `auth.ts`, `clientContext.ts`, parsers, types

The most fragile file is `lib/parseComments.ts`. YouTube reshapes the JSON
paths a few times a year, so every hop is `?.` chained.

## Things that can break

- The hard-coded `clientVersion` gets rejected. `clientContext.ts` falls back
to scraping the live value from `https://www.youtube.com/` and caches it
in session storage.
- The hard-coded `clientVersion` gets rejected. `clientContext.ts` scrapes
the live value from the current page itself (the www homepage is
CORS-blocked from a content script), rewrites the music client to the web
client that serves comments, and caches it in session storage.
- Some tracks have comments off or are pure-audio uploads with no public
YouTube video — the drawer is empty in that case. See the heads-up at the
top.
- Signed out: read still works, just no personalised like state on each
comment.
- Signed out: reading still works, just no personalised like state on each
comment — gated comments show "Sign in to like" instead of a like button.

## License

Expand Down
Loading