Skip to content

studio: attach youtube transcripts from pasted chat links - #8648

Merged
danielhanchen merged 8 commits into
unslothai:mainfrom
mahiatlinux:feat/studio-youtube-transcript
Aug 14, 2026
Merged

danielhanchen merged 8 commits into
unslothai:mainfrom
mahiatlinux:feat/studio-youtube-transcript

Conversation

@mahiatlinux

Copy link
Copy Markdown
Contributor

Pasting a YouTube link in the chat composer now offers to attach the video's transcript as a text file, so the model reads what was said instead of a bare URL. Covers the transcript item from #8526.

Behaviour

Paste a YouTube link and a bar appears above the composer asking "Attach this video's transcript?", with Dismiss and Attach transcript. It uses the same treatment as the prompt-queue stack that already sits there, and it retracts on its own once the link leaves the draft, which also covers sending.

Accepting builds a <title> transcript.txt File and hands it to aui.composer().addAttachment, the same entry point as paste, drag-drop and the file picker, so TextAttachmentAdapter handles it exactly like any other text attachment: same chip, same remove button, same <attachment name=...> wrapping on send. The file carries the title, channel, duration, URL and caption language ahead of the transcript.

Implementation

Backend, studio/backend/core/youtube_transcript.py behind POST /api/youtube/transcript:

  • extract_video_id accepts /watch, youtu.be, /shorts, /embed, /live and /v on the youtube.com, youtu.be and youtube-nocookie.com hosts, and rejects everything else, so a path segment cannot stand in for the host.
  • fetch_transcript calls youtubei/v1/player with the ANDROID client, selects a caption track, and downloads it as fmt=json3. The caption URL is re-checked against the youtube.com hosts before it is fetched, and the download is streamed under a 4 MB cap.
  • _flatten_events drops the aAppend rolling-window cues that separate ASR lines and are not transcript text.

The ANDROID client is the reason this needs no third-party package. Caption URLs taken from the watch page's ytInitialPlayerResponse belong to the WEB client, and YouTube answers those with 200 and an empty body unless the request carries a proof-of-origin token that only its BotGuard JS can mint. The ANDROID client's URLs still resolve unsigned.

Track selection prefers the requested languages, human-written captions over auto-generated ones, and falls back to the track paired with the video's default audio track rather than index 0. Multi-language videos list captions alphabetically, so index 0 is usually a translation of a language nobody in the video is speaking.

Frontend:

  • features/chat/utils/youtube-url.ts mirrors the host and id rules so the offer only appears for real YouTube links.
  • features/chat/api/youtube-api.ts wraps the route.
  • features/chat/components/youtube-transcript-prompt.tsx renders the offer, builds the file, and aborts an in-flight fetch if the link leaves the draft mid-request.
  • components/assistant-ui/thread.tsx reads the pasted text/plain in the existing onPaste handler and derives the offer from the current draft rather than clearing it in an effect.

Verification

  • Backend against live YouTube: dQw4w9WgXcQ, jNQXAC9IVRw and aircAruvnKk, including languages: ["fr"] correctly selecting the French track over alphabetical track 0.
  • Route over ASGI against live YouTube: 200, 400 for a non-YouTube host, 422 for an unavailable video, 422 for an oversize body.
  • Full stack: the real backend serving the real web UI, pasted link to attached Me at the zoo transcript.txt with live captions. Also exercised by hand.
  • Browser: the offer renders, attaching produces the document attachment, a failed fetch shows the error toast with the offer still up for retry, Dismiss clears it.
  • tests/test_youtube_transcript.py (29 cases) covers URL acceptance and rejection, track selection and cue flattening. tests/youtube-url.test.ts covers the frontend detector, including look-alike hosts.
  • Frontend suite (2020 tests), tsc, eslint, biome, ruff and strict i18n parity all pass.

No GPU checks apply; nothing in this change touches a model path.

Pasting a YouTube link in the chat composer now offers to attach the video's
transcript as a text file, so the model reads what was said instead of a bare
URL. Part of unslothai#8526.

The offer renders above the composer surface with the same treatment as the
prompt-queue stack, and retracts on its own once the link leaves the draft.
Accepting builds a `<title> transcript.txt` File and hands it to
`aui.composer().addAttachment`, the same entry point as paste, drag-drop and the
file picker, so `TextAttachmentAdapter` handles it exactly like any other text
attachment. The file carries the title, channel, duration, URL and caption
language ahead of the transcript.

Backend, in `core/youtube_transcript.py` behind `POST /api/youtube/transcript`:
`extract_video_id` accepts /watch, youtu.be, /shorts, /embed, /live and /v on
the youtube.com, youtu.be and youtube-nocookie.com hosts, and rejects everything
else so a path segment cannot stand in for the host. `fetch_transcript` calls
`youtubei/v1/player` with the ANDROID client, picks a track, and downloads it as
fmt=json3.

The ANDROID client is the reason this works without a third-party package.
Caption URLs taken from the watch page's `ytInitialPlayerResponse` belong to the
WEB client, and YouTube answers those with 200 and an empty body unless the
request carries a proof-of-origin token that only its BotGuard JS can mint. The
ANDROID client's URLs still resolve unsigned. Track selection prefers the
requested languages, human-written captions over auto-generated ones, and falls
back to the track paired with the video's default audio track rather than index
0, which on a multi-language video is usually an unrelated translation.
@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create an environment for this repo.

@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 92a66f3a69

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +120 to +122
{fetching
? "Fetching the transcript…"
: "Attach this video's transcript?"}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Route the new prompt strings through i18n

When Studio is using any non-English locale, the loading text, question, buttons, and error toast in this new prompt remain English because they are hard-coded rather than obtained through useT. This bypasses the repository's i18n contribution requirement for new user-facing UI and produces a partially untranslated composer; add message keys and the corresponding locale overlays.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not doing this here. The chat composer is not on the i18n path at all: components/assistant-ui/thread.tsx contains zero useT calls, and only 2 of 30 .tsx files under features/chat use it. Every string this prompt sits next to is hard-coded the same way, including the composer placeholder "Ask anything", the dropzone "Drop files here", the "Could not paste files." toast, and the prompt-queue row buttons. Routing five strings through useT while the composer around them stays English would make the bar inconsistent with its own surroundings rather than more translated. Migrating the composer is its own change.

_select_track scanned tracks once per requested language and accepted a
base-language match on the way, so a pt-BR request took the pt-PT track when
that one was listed first. Each language now tries an exact locale match before
falling back to the base language, still preferring human-written captions over
auto-generated ones.

The composer prompt is now keyed by URL. Pasting a second link while the first
transcript was still loading reused the component instance, so the unmount
cleanup never aborted the first request; it completed, attached the wrong
video's transcript, and dismissed the offer for the link now in the draft.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: b47fdf7c49

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

Two isolated Studios, merge base 22cb12ec6 and head c5a0d7f4c, same scene: paste a bare watch URL into the chat composer with a real clipboard write plus Ctrl+V, then shoot the composer.

before and after

                         BEFORE   AFTER
offer_visible            false    true
offer_text               null     Attach this video's transcript? Dismiss Attach transcript
transcript_route_status  405      400   (POST /api/youtube/transcript with a non-video URL)
composer_text_has_url    true     true

The 400 on the head is extract_video_id rejecting the URL before any outbound call, which is the right answer. youtube.com is reachable from this host, but the scene deliberately never clicks Attach transcript: the offer is a pure frontend URL-detection result and should not depend on the network to be demonstrable.

Security, in order

  1. follow_redirects = True (youtube_transcript.py:111) defeats the caption host allowlist. The same client does both hops and the host check on line 219 validates only the pre-redirect URL, so a 302 from www.youtube.com to http://169.254.169.254/... or a loopback port would be followed and its body streamed. Scoping this honestly: the caption baseUrl comes from YouTube's own player response, not from the user, who controls only an 11 character video id, and I did not find a way to steer it. But the check is load-bearing and trivially bypassable as written, and follow_redirects = False on _fetch_track_text, or re-validating each hop, costs nothing.

  2. Nothing bounds what reaches the model. The 4 MB caption cap is the only limit. That flattens to megabytes of text, becomes a text/plain File, and lands in TextAttachmentAdapter.send, which does await attachment.file.text() with no truncation. There is no character or byte cap on text attachments anywhere in runtime-provider.tsx. A long-video transcript will silently blow the context window. Cap the transcript before building the File, with a note in the header.

  3. parse_qs at lines 221 to 223 silently rewrites the caption URL. keep_blank_values defaults to False, so blank-valued parameters are dropped:

    in:  ...timedtext?v=abc&opi=&caps=&exp=xbt&signature=XYZ&lang=en
    out: ...timedtext?v=abc&exp=xbt&signature=XYZ&lang=en&fmt=json3
    

    Any key= parameter YouTube puts in a timedtext URL is lost. Pass keep_blank_values = True, or append &fmt=json3 textually.

  4. _fetch_player reads the player response fully into memory with response.json(), no cap. Same allowed host, so low severity, but it is the one unbounded read left.

  5. httpx.Timeout(20.0) is per-operation, not a deadline. A server trickling a byte every 19 s keeps the read alive until the 4 MB cap ends it. The route is async def so it ties up a connection rather than a worker, but there is no overall budget.

One frontend race

youtube-transcript-prompt.tsx:751-759 checks controller.signal.aborted before await aui.composer().addAttachment(file). Send the message while that await is pending and the prompt unmounts, the cleanup calls abort(), but abort does nothing to an already-resolved fetch, so the file is still added to a composer that has moved on. The check after the await runs too late. Narrow, but it is exactly the "exactly one attachment ever lands" question and the answer is no.

Also worth stating in the description if it is intended: the offer only fires on a paste of a bare URL. extractYoutubeVideoId(pastedText) runs new URL() on the whole clipboard string, so "look at this https://youtu.be/ID" throws and returns null, and typing or dropping a link never offers at all.

Checked and fine

  • The 4 MB cap is a real streaming cap. client.stream plus async for chunk in response.aiter_bytes() with the length check inside the loop, so at most one chunk overshoots. aiter_bytes yields decompressed bytes, so a gzip bomb is bounded too.
  • Look-alike hosts: all rejected by both parsers. youtube.com.evil.tld fails the hostname set; https://[email protected]/... gives evil.tld from both urlsplit().hostname and URL.hostname; Cyrillic-е punycode normalises to xn--... and is not in the set. Python's urlsplit strips \t\r\n before parsing.
  • Auth: routes/youtube.py:381 uses Depends(get_current_subject), same as the other routers. Not an unauthenticated fetcher.
  • The other races (paste A then B, remove mid-fetch, dismiss then repaste) are handled: key={youtubeOfferUrl} remounts on a new link so the unmount cleanup aborts the stale request, and youtubeOfferUrl is derived from composerText.includes(...) so editing the link out retracts the offer.
  • 403, consent wall, empty caption list: surfaced, not silent. raise_for_status becomes a 502 "Could not reach YouTube", no tracks becomes a 422 with the specific detail, both reach toast.error and leave the prompt mounted with fetching reset, so retry works.

Tests

studio/backend $ python -m pytest tests/test_youtube_transcript.py -q
30 passed in 5.36s

studio/frontend $ npm test
tests 2032, pass 2032, fail 0

The test file is explicit that the network hops are not exercised, so the streaming cap, the redirect behaviour and the parse_qs rewrite above are all unit-untested. No live InnerTube call was made from here either.

Good feature. Items 1 and 2 are the ones I would want fixed before it lands.

danielhanchen pushed a commit to mahiatlinux/unsloth that referenced this pull request Aug 13, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 62f5b6c651

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2105 to +2107
const pastedText = event.clipboardData?.getData("text/plain") ?? "";
if (extractYoutubeVideoId(pastedText)) {
setYoutubeLink(pastedText.trim());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Add the transcript offer to the shared compare composer

When either model-comparison view is active, chat-page.tsx renders SharedComposer instead of this composer, and the paste handler in shared-composer.tsx only processes clipboard files. Consequently, pasting the same YouTube URL in Compare or LoRA Compare sends only the bare link and never exposes the new transcript action; wire the detector and attachment flow into that composer as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The premise is right, the conclusion is a feature request rather than a fix, so I am leaving it.

SharedComposer does not just skip non-file clipboard content, it refuses anything that is not an image or audio: shared-composer.tsx:963 throws Unsupported compare attachment and the toast at :968 says "Compare supports images and audio within the attachment size limits." There is no addAttachment and no AttachmentAdapter in that component at all, only pendingImages and pendingAudio. The transcript flow depends on aui.composer().addAttachment(file) and the TextAttachmentAdapter registered in runtime-provider.tsx:1513, none of which Compare has.

So wiring the detector in is not a two-line change, it is building a text-attachment pipeline for Compare. Nothing regresses without it either: Compare has never accepted text attachments, so a pasted YouTube link there behaves exactly as it does on main. Worth doing, but as its own change.

Comment on lines +248 to +251
async for chunk in response.aiter_bytes():
body.extend(chunk)
if len(body) > limit:
raise TranscriptUnavailable(message)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Enforce the response cap before growing the buffer

For a large gzip-encoded player or caption response, httpx.Response.aiter_bytes() yields decoded data and may return a single decompressed chunk far larger than limit. Extending body before checking its size therefore allocates the entire oversized chunk, so a highly compressible caption track can consume tens or hundreds of megabytes despite the advertised 4 MB cap; consume or slice decoded data in bounded increments rather than appending an unchecked chunk.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mechanism is real and I reproduced it, but the fix you describe does not change anything, so I am not taking it.

Reproduced with a real local server and a transport that rewrites only the socket target, so the URL the module builds and validates still reads https://www.youtube.com/api/timedtext?fmt=json3:

decompressed 512 MiB -> gzip 521844 bytes (ratio 1029:1)
max single decoded chunk from aiter_bytes: 67.4 MB
cap raised: too large; peak alloc during read = 148.8 MB   (cap is 4.2 MB)

Then I implemented exactly what you asked, body.extend(chunk[:room]), buffer never above 4 MB, no unchecked append:

bounded-slice variant: peak alloc = 148.5 MB

148.5 against 148.8. The allocation is not ours. Response.aiter_bytes does decoded = decoder.decode(raw_bytes) and only then feeds a ByteChunker, so the full decoded chunk exists before anything is yielded to us, and chunk_size sits downstream of the decoder. Anything on our side of the async for is cosmetic.

Two corrections to the framing. It is bounded, not accumulating: one 64 KiB socket read (READ_NUM_BYTES in httpcore's http11) times DEFLATE's 1032:1 ceiling is about 67 MB, and _read_capped raises on the next check. And reachability is the weak class here, since _validated_caption_url pins scheme to https and host to _CAPTION_HOSTS with every redirect hop re-validated, so the body can only come from youtube.com over TLS. A real json3 track compresses about 5:1, which is a 330 KB chunk.

The only mitigations that actually work are dropping Accept-Encoding on the caption hop, which costs real bandwidth on every legitimate fetch, or reading aiter_raw() and driving zlib.decompressobj().decompress(data, max_length) ourselves. Neither is worth it for a bomb that YouTube would have to serve. Noting for the record that br is in httpx's supported decoders and Brotli has no 1032:1 ceiling, so the bound above is gzip only.

Comment on lines +43 to +45
_MAX_PLAYER_BYTES = 4 * 1024 * 1024
# Roughly 25k tokens. A three hour video's captions run past 200k characters, which
# would swallow the model's context window on its own.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Size transcripts to the loaded model's context

For a long video used with the default local chat configuration, this static 100,000-character allowance is roughly 25,000 English tokens, while features/chat/types/runtime.ts defaults maxSeqLength to 4,096. Because the whole attachment is placed in the final user message and the local inference path reports an over-context error rather than trimming it, many ordinary long transcripts make the subsequent send fail; derive the transcript budget from the active model's remaining context or truncate again before attaching.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 4096 premise does not hold for the path you name, so I am leaving the flat cap.

DEFAULT_INFERENCE_PARAMS.maxSeqLength = 4096 is not what a default GGUF load sends. resolveLoadMaxSeqLength in presets/preset-policy.ts returns 0 for a GGUF load on the builtin Default preset (line 335) and again for any GGUF load without a custom context (line 341); maxSeqLength is only reached at line 344, the non-GGUF fallback. 0 means native n_ctx_train, as the comment at shared-composer.tsx:1269 says. 25k tokens fits any modern GGUF's trained context.

Transcripts are also not special. TextAttachmentAdapter takes .txt, .md, .py, .csv and about sixty other extensions up to 20 MB with no context sizing whatsoever, and main has since landed pasteLongTextAsFile, which silently attaches any paste over 2000 characters as a file, again unbudgeted. 100k characters is already far stricter than the generic path it sits beside. Gating transcripts alone would be an inconsistency rather than a fix.

And overflow is not silent: isContextLimitError raises a "Context limit reached" toast pointing at the Context Length setting.

Deriving the budget from remaining context would also be wrong for external providers with 200k windows, and the model can be switched after the attach.

danielhanchen added a commit to mahiatlinux/unsloth that referenced this pull request Aug 13, 2026
@danielhanchen
danielhanchen force-pushed the feat/studio-youtube-transcript branch from 62f5b6c to cb92498 Compare August 13, 2026 13:36
@danielhanchen

Copy link
Copy Markdown
Member

Took this over and pushed a hardening commit. Re-ran the two-install evidence afterwards against the fixed head.

Before and after

Before: pasting a YouTube link put a URL in the composer and the model got a URL.

After: the composer offers to attach the transcript.

                         BEFORE   AFTER
offer_visible            false    true
offer_text               null     Attach this video's transcript? Dismiss Attach transcript
transcript_route_status  405      400   (POST /api/youtube/transcript, non-video URL)
composer_text_has_url    true     true

The 400 is extract_video_id rejecting the URL before any outbound call, which is the right answer. Real feature, real gap.

Cross-browser, driven against the real Studio: the offer appears in Chromium, Firefox and WebKit alike, with a trusted clipboard paste in all three.

What I pushed, security first

1. follow_redirects = True defeated the caption host allowlist. The same client did both hops and the host check validated only the pre-redirect URL, so a 302 from an allowed host to 169.254.169.254 or a loopback port would be followed and its body streamed. Scoped honestly: the caption baseUrl comes from YouTube's own player response, not from the user, who controls only an 11 character video id, and no way to steer it was found. But the check was load-bearing and trivially bypassable.

Fixed with bounded, re-validated hops rather than an outright refusal. The timedtext endpoint is undocumented and unstable and I could not establish that YouTube never 302s it, so refusing outright risked silently breaking a working feature. _fetch_track_text now sets follow_redirects = False per request and walks up to 3 hops itself, resolving each Location with urljoin and running the host validator on the result before the next request. A 4th hop raises. The client-level setting is left alone for the player hop, whose URL is a module constant with no user input.

2. Nothing bounded what reached the model. The 4 MB caption cap was the only limit, and the formatted transcript became a text/plain File that TextAttachmentAdapter.send read with await attachment.file.text(), no truncation anywhere. A long-video transcript would silently blow the context window. Capped at 100k characters, cut back to the last newline so the model does not get a mangled half-line. That is roughly 25k tokens, which fits a full 90 minute video while stopping a 3 hour one (200k to 400k characters) from eating the window on its own. The truncation is surfaced, not silent: a truncated flag flows through the response type to a header line in the attachment, so both the model and the user see it.

3. parse_qs silently rewrote the caption URL. keep_blank_values defaults to False, so blank-valued parameters were dropped:

in:  ...timedtext?v=abc&opi=&caps=&exp=xbt&signature=XYZ&lang=en
out: ...timedtext?v=abc&exp=xbt&signature=XYZ&lang=en&fmt=json3

Any key= parameter YouTube puts in a timedtext URL was lost. Fixed with keep_blank_values = True rather than a textual append, which would have raised a new question about a duplicated fmt.

4. An attachment could land on the next message. The aborted check ran before await addAttachment(file), so sending the message while that await was pending left the file attached to a composer that had moved on: the cleanup called abort(), but abort does nothing to an already-resolved fetch. The composer accessor is now captured once, the aborted check is the last statement before addAttachment, and a second check after it removes the attachment by id if the signal fired during the await.

5. _fetch_player read the player response fully into memory. Now streamed through the same capped reader as the caption path, 4 MB.

Not changed: the overall deadline. httpx.Timeout exposes connect/read/write/pool only, with no overall-deadline option, so there is no small fix. The available route is wrapping the client block in asyncio.timeout, which raises TimeoutError, neither TranscriptUnavailable nor httpx.HTTPError, so the route would 500 without a third handler. Residual exposure is small: the peer must already be on the allowlist over https, and the 4 MB cap plus the per-read timeout bound it.

Simulation

A real local HTTP server, with a transport subclass rewriting only the socket target so every URL the module builds and validates still says www.youtube.com. Against the pushed code:

(a) caption URL 302s to a loopback address
    refused: YouTube returned a caption URL from an unexpected host.
(b) caption body larger than the cap
    capped at 4194304 bytes: This video's captions are too large to attach.
(c) timedtext URL carrying blank-valued params
    server received: v=dQw4w9WgXcQ&opi=&caps=&exp=xbt&signature=XYZ&lang=en&fmt=json3
    ok opi=  ok caps=  ok signature=XYZ  ok exp=xbt  ok lang=en  ok fmt=json3
all scenarios held

Against the pre-fix code, to prove it is a differential rather than a test that passes either way:

(a) FAIL: followed the redirect and read 'LOOPBACK SECRET, MUST NOT BE READ'
(c) FAIL opi=   FAIL caps=
3 failure(s)

(b) passes on both, as expected, since the byte cap already existed and this confirms the redirect rework did not lose it.

Does it break anything

Everything here is additive or a tightening of an outbound request. No existing route changes shape, no schema, no stored data. An older Studio is unaffected because the route did not exist there. The one user-visible change from my commit is that a very long transcript now arrives truncated with a header line saying so, instead of arriving whole and overflowing the context.

The look-alike host cases were checked and all reject on both parsers: youtube.com.evil.tld fails the hostname set, https://[email protected]/... gives evil.tld from both urlsplit().hostname and URL.hostname, and Cyrillic-е punycode normalises to xn--.... routes/youtube.py uses Depends(get_current_subject), same as the other routers, so this is not an unauthenticated fetcher.

Tests

studio/backend  $ python -m pytest tests/test_youtube_transcript.py -q   40 passed
studio/frontend $ npm test                                                2020 passed, 0 failed
studio/frontend $ npx tsc -p tsconfig.test.json / tsc -b                  both exit 0

Seven new backend tests cover the blank-value survival, host rejection across four shapes, the transcript cap on a line boundary, a redirect off the allowlist, a redirect that stays on YouTube, a redirect loop, and the oversized body. Those hops now run against httpx.MockTransport, so the file no longer claims the network paths are unexercised.

One thing to know before merging

This branch now conflicts with main in studio/frontend/src/components/assistant-ui/thread.tsx. Main moved, not anything in this PR. Needs a rebase.

Worth stating in the description if it is intended: the offer only fires on a paste of a bare URL. extractYoutubeVideoId(pastedText) runs new URL() on the whole clipboard string, so "look at this https://youtu.be/ID" throws and returns null, and typing or dropping a link never offers at all.

Of the batch I have been through, this is the one I would want a second pair of eyes on before merge, purely because it is the only one that makes outbound network requests on user input.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: cb9249805f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

danielhanchen added a commit to mahiatlinux/unsloth that referenced this pull request Aug 13, 2026
@mahiatlinux
mahiatlinux force-pushed the feat/studio-youtube-transcript branch from ffed622 to f00a3ed Compare August 13, 2026 22:17
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: cef775f92c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 6c5385a into unslothai:main Aug 14, 2026
7 of 56 checks passed
danielhanchen added a commit that referenced this pull request Aug 16, 2026
…ce defects

main has been red since Aug 14 and every open PR inherits it. Five clusters, none
of them caused by the PRs that were showing them.

context_length (13 tests, plus 4 more in disguise). #8700 added an unguarded
llama_backend.context_length read to the chat-completions path and updated five
test files, missing three. The real LlamaCppBackend has had the property for a
long time, so no user was ever affected; the doubles were simply
under-specified. The four gguf_stream_slot_release failures are the SAME bug:
those doubles reach the same line, but the AttributeError is swallowed into the
response task and surfaces as a 20 second timeout, which reads as a flake.

Nine hand-written doubles across five files each re-declared the same attribute
block with no shared base, so one new read broke whichever files happened not to
be updated. They now share FakeLlamaCppBackend, and a canary drives the real
route with a bare double so the next such read fails in one place, named, at the
point of the change. The stream waits no longer discard the driving task's
exception, so that class of failure cannot present as a bare timeout again.

youtube_router (2 tests). routes/__init__.py exports it and main.py imports it;
the app is fine. test_desktop_auth stubs sys.modules[routes] with a hardcoded
list of 17 routers, deliberately, to avoid importing the ML stack. #8648 added a
router and did not update it, the second time this has happened after
openai_codex_auth_router in #8511. The stub is now derived from main.py's own
import block, so it cannot go stale.

Repo tests (CPU), 6 failures, of which two are real source defects:
llama-extra-args.ts put the Studio brand into a user-visible validation message,
which the desktop branding contract forbids in runtime surfaces, and
test_playwright_server_lifecycle.py read checked-in files without an encoding,
which is a real Windows cp1252 crash the lint exists to catch. Both fixed in the
source. The other four are stale assertions chasing text that #8702 legitimately
moved or reflowed; they now assert the behaviour instead, via the real
override_lookup_candidates() and the element-scan pattern their own siblings
already use.

Not addressed here: pip scan-packages :: hf-stack reports 173 findings in
third-party deps under SCAN_ENFORCE=1 and is red on main too. Baselining a
supply-chain scanner to get green is the wrong reflex, so it wants its own look.
danielhanchen added a commit that referenced this pull request Aug 16, 2026
…ce defects (#8956)

* Fix CI on main: stale test doubles, a stale router stub, and two source defects

main has been red since Aug 14 and every open PR inherits it. Five clusters, none
of them caused by the PRs that were showing them.

context_length (13 tests, plus 4 more in disguise). #8700 added an unguarded
llama_backend.context_length read to the chat-completions path and updated five
test files, missing three. The real LlamaCppBackend has had the property for a
long time, so no user was ever affected; the doubles were simply
under-specified. The four gguf_stream_slot_release failures are the SAME bug:
those doubles reach the same line, but the AttributeError is swallowed into the
response task and surfaces as a 20 second timeout, which reads as a flake.

Nine hand-written doubles across five files each re-declared the same attribute
block with no shared base, so one new read broke whichever files happened not to
be updated. They now share FakeLlamaCppBackend, and a canary drives the real
route with a bare double so the next such read fails in one place, named, at the
point of the change. The stream waits no longer discard the driving task's
exception, so that class of failure cannot present as a bare timeout again.

youtube_router (2 tests). routes/__init__.py exports it and main.py imports it;
the app is fine. test_desktop_auth stubs sys.modules[routes] with a hardcoded
list of 17 routers, deliberately, to avoid importing the ML stack. #8648 added a
router and did not update it, the second time this has happened after
openai_codex_auth_router in #8511. The stub is now derived from main.py's own
import block, so it cannot go stale.

Repo tests (CPU), 6 failures, of which two are real source defects:
llama-extra-args.ts put the Studio brand into a user-visible validation message,
which the desktop branding contract forbids in runtime surfaces, and
test_playwright_server_lifecycle.py read checked-in files without an encoding,
which is a real Windows cp1252 crash the lint exists to catch. Both fixed in the
source. The other four are stale assertions chasing text that #8702 legitimately
moved or reflowed; they now assert the behaviour instead, via the real
override_lookup_candidates() and the element-scan pattern their own siblings
already use.

Not addressed here: pip scan-packages :: hf-stack reports 173 findings in
third-party deps under SCAN_ENFORCE=1 and is red on main too. Baselining a
supply-chain scanner to get green is the wrong reflex, so it wants its own look.

* Studio: break the settings/chat import cycle that stopped the UI rendering

#8932 added SIDEBAR_ORGANIZATION_STORAGE_KEY to the @/features/chat barrel and
had general-tab.tsx read it back out of that barrel. The key is used at MODULE
scope, in the storage-key list, and the barrel is part of an import cycle that
reaches this file, so the binding is still in its temporal dead zone when the
list is built:

  Cannot access 'SIDEBAR_ORGANIZATION_STORAGE_KEY' before initialization

That kills the whole module graph, so the page renders nothing. It is why
Frontend CI has been failing on main with a Playwright locator that finds no
elements, which reads as a flaky browser test rather than a module-init error.

Importing the key straight from its module breaks the cycle. Verified by
bisection with the real browser smoke: it passes at cfee137 (before #8932),
fails on main with the TDZ error above, and passes again with this one-line
change. Typecheck clean, 2756 frontend tests pass.

#8932's own branch was already red with this exact failure before it merged.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Security: fix the filesystem-enumeration false positives in scan-packages

The hf-stack shard of pip scan-packages has been red on main. One CRITICAL
was blocking it, and tracking it down turned up a pattern bug behind nine of
the entries already in the baseline.

The blocking finding, unsloth-zoo/llama_cpp.py under "Harvests environment
variables/secrets AND makes network calls", is first-party: _github_auth_headers()
reads GH_TOKEN so the llama.cpp releases API call is not rate limited. That
file and check were already reviewed and baselined. It reopened because
unsloth-zoo 2026.8.12 replaced

    keynames = "\n" + "\n".join(os.environ.keys())

with a targeted _is_colab_environment() helper. Every other matched line is
byte identical to what was reviewed, so the current code is a strict subset of
the approved evidence. The entry is refreshed, with the hash generated by
--write-baseline rather than by hand. No PR caused this; it is the baseline's
reopen-on-change working as designed against an upstream release.

The pattern bug is in RE_FS_ENUM:

    r"|\bhistory\b.*\bread\b"  # reading shell history

Under re.DOTALL that .* spans the whole file, so any module containing the
word "history" anywhere before the word "read" anywhere is filesystem
enumeration, and with a network call in the same file that is a CRITICAL.
That is httpx's Response.history, retries.history in urllib3, IPython's
history module, torch's CUDA memory history. Nine of the eleven baselined
CRITICALs under this check were that one alternative, each suppressing a whole
file for the check.

Meanwhile the precise half was dead. \b\.bash_history\b puts \b between "/"
and "." in "~/.bash_history", where neither side is a word character, so it
could never match; same for \b\.zsh_history\b. This is the unsatisfiable-\b
bug already fixed once for /proc/self/status. Checked against the old pattern:
it matched none of five real history-file reads and all four benign cases.

Naming the files instead inverts that. The nine dead baseline entries are
removed, which narrows the allowlist rather than widening it, and three tests
pin both directions.

Verified by running all three shards locally against the same requirements
transform CI uses: hf-stack now exits 0 (was 1), studio and extras stay at 0,
and no removed entry resurfaced.

* Fix two more stale sidebar contract tests left by #8932

Both fail on pristine origin/main, so they are not from this branch. #8932
moved the sidebar's user-visible copy into the locale file and rewrote the
delete-switch predicate to cover its new bulk targets. Neither change breaks a
contract; both broke a grep of app-sidebar.tsx.

test_the_delete_switch_does_not_promise_project_files greps for the sentence
"This chat's own sandbox folder is removed from disk." It is still there,
verbatim, in studio/frontend/src/i18n/locales/en.ts. The promise is the
contract, not its address, so the test now searches the frontend sources and
survives the next move while still failing on a reworded promise.

test_the_delete_switch_reaches_a_chat_moved_into_a_project pinned one spelling
of deleteTargetHasFiles:

    -return target.kind === "project" || target.kind === "chat";
    +return target.kind !== "run";

Same answer for a chat and for a project, plus the new "chats" / "projects"
bulk kinds. What must hold is that a run is excluded and that project
membership is never consulted, so the test reads the brace-matched function
body and asserts that instead of the old one-liner.

Both were checked by mutation: reinstating the misleading copy, and gating
deleteTargetHasFiles on target.item.projectId, each fail the rewritten test.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Address the review: scope a contract test, keep a parity check, close a scanner gap

Four items, all confirmed against the code at head before changing anything.

1. tests/studio/test_model_picker_contracts.py: the rollback ordering assertion
searched the whole of chat-page.tsx, which takes the same snapshot in the hub
auto-load path at line 2558. The only applyModelLoadConfigToRuntime call is at
3262, so the index comparison was satisfied by the unrelated occurrence: deleting
the snapshot inside selectWithConfig outright still passed both assertions.
Verified by mutation. Now scoped to the selectWithConfig body, which fails on
that deletion.

2. studio/backend/tests/test_research_internal_call_tool_gate.py: dropping
perf_callback from the kwargs comparison hid presence as well as identity, so the
opt-out losing its callback on one path would have gone unnoticed and cost that
path its tok/s readout. Assert both are callable (or both absent) first, then
exclude. Verified by mutation at routes/inference.py:14512.

3. tests/studio/test_model_picker_contracts.py was source-only and ran without the
backend environment; calling the real ladder for a standalone .gguf pulled in
hub.utils.gguf, then loggers, then structlog, so a bare pytest run failed after
183 passes. CI installs studio.txt and is unaffected, so coverage there is
unchanged. The helper now skips on a missing third-party package only; a missing
first-party module still fails.

4. scripts/scan_packages.py: fish stores history at $XDG_DATA_HOME/fish/fish_history
with no leading dot (fishshell.com/docs/current/cmds/history.html), so the dotted
alternative could never match the real path and narrowing the pattern left an
exfiltration blind spot. Added a non-dotted form. The fish read plus a network call
is a CRITICAL again, the dotted shells still match, and the false positives stay
suppressed.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten comments added by the CI repair

* Fix two more stale studio contract constants left by #8932

Both fail on pristine origin/main, so neither comes from this branch, and in
both the source is right and the test-side constant is stale.

INLINE_ROW_IDS in tests/studio/playwright_mac_tab_capabilities.py still listed
four rows. #7863 had put Video under "More" as layout v5, so the script dropped
it: an unpinned row renders no data-testid and every assertion on it silently
observes nothing. #8932 pins Video under Images again, and records it in the
migration history as v7, so it is deliberate and versioned rather than an
accidental revert. Video is observable again, so the script samples it again.
test_inline_row_ids_match_the_frontends_default_pinned_set exists precisely to
catch this tuple drifting from the store in either direction, and it did its job.

test_multi_chat_prompt_queue_contract.py pinned the zero-argument spelling
"return await clearStoredChats();". #8932 gave the call an options argument,
which changes nothing about the ordering the assertion is there to hold, so it
now matches on the call prefix, the same way the sibling assertion three lines
up already does.

Both mutation-checked: unpinning Video in the store fails the first, and moving
requestPromptQueueStop after clearStoredChats fails the second.

* Narrow a contract search I made too wide, and read it once

Self-audit of an earlier fix in this branch, under the same standard applied to
everything else here.

test_the_delete_switch_does_not_promise_project_files greps for a promise the
delete dialog must make. #8932 moved that copy into the locale file, so the
original grep of app-sidebar.tsx broke, and my fix widened the search to the
whole frontend tree. That is the same defect the review caught in the rollback
ordering assertion: a search wide enough to be satisfied by an unrelated
occurrence proves nothing. The sentence appearing in any of ~1200 files, a
comment or a dead module included, would have passed it.

Now scoped by intent. The promise the dialog MUST make is looked for where the
sidebar's user-visible copy lives, the locales and the component. The promise it
must NOT make is still looked for across all of src, since breadth only makes a
negative stricter.

Mutation-checked: rewording the real string and planting the original in an
unrelated module fails the test, where the whole-tree form passed.

The two scopes are also read through an lru_cache. The wide one concatenates
about 1200 files, and it was re-reading every one of them on each call.

* Address the second review: real scoping, not the appearance of it

Five items, each reproduced against the code at head before changing anything.
Three are cases where my own earlier fix looked scoped but was not.

deleteTargetHasFiles: the negative assertions did not establish the contract.
`return target.kind === "run";` -- the exact inversion, which hides the delete
switch for every chat and project -- mentions "run", mentions no projectId, and
contains neither prohibited expression, so it passed all four checks. Confirmed
by construction. Now the direction is pinned: run is the kind excluded, never
the one included.

The selectWithConfig slice ran to end of file, not to the callback's closing
brace: 13,566 characters rather than 579. Moving applyModelLoadConfigToRuntime
out of the callback while leaving the snapshot behind still passed. Brace-matched
now, and that mutation fails.

asgi_stream_helpers returned on the frame without inspecting the task, so a
send() that sets the event and then raises left both futures done, the frame
branch won, and the caller's gather(return_exceptions = True) discarded the
exception. That is the silence the helper exists to break. Reproduced directly.
The task is checked first now, and the message says whether the failure came
before or after the frame.

Two scanner gaps, both from narrowing RE_FS_ENUM. Constructed fish paths put a
quote rather than a separator before the basename, so Path.home() / "fish" /
"fish_history" and os.path.join(h, "fish", "fish_history") did not match. And the
dotted list omitted PowerShell's ConsoleHost_history.txt, Ruby's .irb_history and
SQLite's .sqlite_history. A quote now counts as a boundary and those names are
covered, case-insensitively for the Windows one. Ten read forms match, and the
httpx, urllib3, IPython and torch false positives stay suppressed.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
@mahiatlinux
mahiatlinux deleted the feat/studio-youtube-transcript branch September 25, 2026 05:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants