Matches the template's index.astro (subtitle || description). The editor
shows the description as a full-strength placeholder that typing replaces.
Co-authored-by: Cursor <cursoragent@cursor.com>
18 days ago
feat: port the template's new page layout to the editor and published articles
The editor view and the published page now use the research-article-template
layout mirrored in frontend/src/styles/template-layout/: one CSS grid with
named lines (screen, page, toc, outset, body, margin) and the 1280+ /
1101-1279 / <=1100 tiers, for both the "article" and "paper" templates.
Published page (backend/src/publisher):
- layout-chrome.ts renders the template markup: centered hero (title,
subtitle, then banner), meta columns (authors, affiliations, published +
reading time + DOI, Resources with PDF/Cite buttons and the links row),
line TOC rail with slim top bar and drawer, paper hero with link pills,
footer without citation/DOI blocks for "paper"
- <main class="tiptap"> is the page grid; wide, full-width and sidenote
wrappers get the template classes, wide embeds get html-embed--wide
- the generated layout runtime replaces the old inline TOC/hash scripts:
heading anchors, scroll-spy, margin sidenote placement, Cite popover,
debug grid on ?grid
- <html data-t…
build: mirror the research-article-template page layout
Add `npm run sync:template-layout` (backend/scripts/sync-template-layout.mjs).
It copies the template's grid tokens and layout stylesheets into
frontend/src/styles/template-layout/ with @custom-media resolved (neither
Vite nor the publisher runs PostCSS), lifts the paper hero styles out of
HeroPaper.astro, copies the link icons, and bundles the layout scripts
(TOC, heading anchors, sidenotes, meta columns, debug grid on ?grid) into
backend/src/publisher/layout-runtime.generated.ts. `--check` reports drift.
Co-authored-by: Cursor <cursoragent@cursor.com>
POST /api/upload had no auth check: anyone could push files to the HF
dataset with the Space owner's token, and any cookie value was cached as
the storage token. It now goes through requireEditor (after the per-IP
rate limit, before the body is buffered), accepts PNG, JPEG, GIF, WebP
and AVIF only (detected from the bytes, SVG refused) and answers 413
past 10 MB.
requireEditor now tells apart 401 (no or invalid session) from 403
(signed in without write access). The citation routes, which fetch
DOIs and URLs on the server, use it too.
Co-authored-by: Cursor <cursoragent@cursor.com>
perf(frontend): load Mermaid, Shiki grammars and language detection on demand
- Mermaid is imported when a diagram renders
- the editor uses shiki/core with the JavaScript regex engine and fetches
each grammar the first time a block needs it; only SHIKI_LANGS ship
- highlight.js language detection loads with the first language-less block
- the chat panel and Embed Studio are lazy components
- shiki-langs.ts holds the shared language/theme constants without a
runtime Shiki import; the publisher keeps the eager highlighter
Entry chunk: 2.79 MB -> 1.60 MB (813 KB -> 492 KB gzip).
Co-authored-by: Cursor <cursoragent@cursor.com>
refactor(shared): move the Markdown renderer and publish types to shared
The renderer is a pure TipTap-JSON walk; living in backend/src/shared lets
the frontend reuse it (the shared folder is the only backend code the
frontend image build copies).
Co-authored-by: Cursor <cursoragent@cursor.com>
20 days ago
feat(mcp): chart and publish tools, structured errors, JSON 404s
- Chart tools for external agents: create_embed (contract validation,
data files, version 1, rendering check), insert_embed (after a block
with expected_rev, caption, also in apply_edits), update_embed (html,
patch or config values, expected_version, Studio draft guard),
restore_embed_version, get_embed, list_embeds, check_embed. Every
write is a version attributed to the agent; session undo and "Undo
its changes" also revert charts.
- publish and get_publish_status run the Publish button's flow (now a
shared publish service): idempotent while a publish runs, absolute
URLs, agent-attributed version. get_article_info states that a Space
hosts a single article.
- Errors carry a stable code and details in structuredContent
(rev_conflict, version_conflict, draft_in_progress, invalid_embed...).
- Unknown /.well-known, /mcp and /api paths answer a JSON 404 instead of
the editor page, so MCP OAuth discovery falls back to the bearer token.
- One headless Chromium job at a…
- Tweak panel: embeds declare 2 to 6 settings in a data-embed-config JSON
block (contract + agent prompt updated, runtime 1.2.0 exposes them as
ctx.config and applies embedConfig messages live). Sliders, colors,
selects, toggles and text update the preview instantly with no model
call and are saved back as "manual tweak" versions.
- Inspect: a point-and-click inspector in the studio preview; the picked
element becomes an @this pointer for the next message, and a label held
by a text setting can be edited without the AI.
- Automatic check after each iteration: POST /api/embed-check renders the
chart in headless Chromium (light/dark, 360/680 px, CDN-only network,
one at a time) with the embed checker, now in src/embed-check, and the
studio shows "N checks passed, 1 warning [Fix]".
- Launcher for new figures (description, CSV drop, 4 gallery starters from
GET /api/embed-starters, existing charts) from the top bar and the slash
menu, instead of opening a random chart.…
feat(embed-studio): error loop, versions, chips and preview controls
- Preview errors reach the agent: a studio-only reporter in the srcdoc
relays uncaught errors, rejections, failed loads and embed:error to the
parent; the studio shows "The chart threw ... [Fix it]" and sends one
automatic fix per user message.
- Versions per agent turn in Y.Map("embed-versions") (shared, capped at
20): vN / Restore / Compare under each reply, Undo last change; restore
appends a copy so history stays linear.
- Starter and follow-up prompt chips, preview width presets (Article,
Wide, 360) and a local light/dark toggle pushed with setTheme.
- The agent's title and source land on the node; Shiki code view with
Copy and Download.
- Provider errors keep their HTTP status; 401/402/429 become actionable
messages with Retry; model name in the header; Done replaces
Save & Close; no more fake "Generating chart..." banner.
- Minimal mobile layout: files drawer and Chat / Preview tabs under 900px.
Co-authored-by: Cursor <cursoragent@cursor.com>
fix(persistence): save during non-stop editing and before a document unloads
- The Database store hook now flushes the pending debounced save.
Hocuspocus runs it at most every 10 s while editing goes on and right
before unloading a document, so saves no longer wait for a 2 s pause
and a reconnect right after the last writer left no longer reloads a
stale disk copy.
- debouncedSave writes the previous Y.Doc's pending state at once when
a reloaded document (new instance) comes in.
- HF pushes wait at most 3x their debounce, so continuous saves cannot
postpone the upload forever.
- Drop the per-change "[persist] onChange" log line.
- Regression scenarios 2.5.20 / 2.5.21; unit tests for flushSave and
the reload case, and 2.1.3 now edits one document as in production.
Co-authored-by: Cursor <cursoragent@cursor.com>
fix(storage): merge with the stored copy on push, retry failed loads; add HF storage scenarios
- Pushes merge the CRDT state with the bucket/dataset copy first, so two
servers on the same storage no longer erase each other's edits.
- A failed document load closes the socket (1013) so every client,
including stale tabs on old bundles, reconnects and retries instead
of staying stuck on permission-denied.
- Create the dataset before writing live-store.json on a new Space.
- HF_PUSH_DEBOUNCE_MS / HF_PUSH_RETRY_MS overrides for scenarios.
- Scenario harness gains a fault-injecting fake Hub (Node loader hook
over @huggingface/hub) and wiped-disk rebuilds; 8 cloud scenarios.
Co-authored-by: Cursor <cursoragent@cursor.com>
feat(safety): rescue text removed by someone else's change, with real-life scenario tests
Deleting a paragraph in Yjs deletes everything inside it, so an agent
revert, a version restore, a stale tab's delete or offline edits into a
paragraph removed meanwhile silently dropped other people's words.
- The server copies text deleted by someone other than its author into
the doc's "rescued" map (authorship learned per Yjs client from the
authenticated connection and kept in the doc).
- Each tab copies its own text when a remote change removes it, the only
place text typed into an already-deleted paragraph still exists.
- History panel lists removed text with Put back / Copy / Dismiss; the
author gets a banner pointing there.
- tests/scenarios: real server process, browser-equivalent tabs and a
chaos proxy (freeze, offline, server death) covering stale tabs,
deploys, crashes, offline work and bulk removals.
Co-authored-by: Cursor <cursoragent@cursor.com>
feat(versions): version history, agent revert and safer MCP edits
- Checkpoints (local + dataset versions/<doc>/) every ~15 min of editing,
before and after each agent session, on publish, on demand and before
any restore, attributed to the humans and agents who edited.
- History panel: versions grouped by day, block-level diff against the
current text, restore applied as a minimal new change.
- Agent avatars offer "Undo its changes", reverting everything the live
session wrote while keeping other people's edits.
- MCP: block rev in read_article with expected_rev checks, atomic
apply_edits batches, save_version, and structuredContent results.
Co-authored-by: Cursor <cursoragent@cursor.com>
feat(storage): keep the live document in an HF Storage Bucket, alert on failing saves
The live Yjs state is saved every few seconds; as git commits on the
dataset that bloats history and hits commit rate limits. It now goes to
an overwrite-in-place Storage Bucket (HF_BUCKET_ID, default
<SPACE_ID>-live). A live-store.json marker in the dataset records the
move so a stale dataset copy is never loaded or written again; before
the marker exists both copies are merged as CRDT updates. Tokens that
can't use buckets fall back to the dataset.
Cloud save failures lasting over 2 minutes show a banner to everyone
editing with a backup download, and ALERT_WEBHOOK_URL is posted to after
5 minutes and on recovery.
Co-authored-by: Cursor <cursoragent@cursor.com>
feat(mcp): remote MCP server so external agents edit as collaborators
Claude Code, Cursor, Codex and other MCP clients connect to /mcp
(Streamable HTTP) with an HF token. Each session is a headless Hocuspocus
peer with its own awareness entry and "<Name> agent" focus label, checked
by the same write-permission gate as a browser login.
- Tools: read_article (outline / section), replace_text (minimal diff that
keeps formatting and comment anchors), insert_blocks, replace_block,
delete_block, update_metadata, comments, focus, undo (own steps only).
- Stable block ids from Yjs item ids; Markdown in, source-syntax Markdown
out ([@key] citations, ^[footnotes]).
- Origin validation, token-bound sessions, idle cleanup.
- End-to-end test with a live server, a human peer and the SDK client,
including schema validation of everything the agent writes.
Co-authored-by: Cursor <cursoragent@cursor.com>
fix(publisher): derive KaTeX CSS version from the installed package
A stale pinned URL plus integrity hash made browsers drop the stylesheet, so published equations fell back to raw MathML.
Co-authored-by: Cursor <cursoragent@cursor.com>
feat(embeds): shared Embed.mount runtime, checker, gallery and evals
- Own the embed runtime and authoring guides in embed-kit/ and generate the
runtime and agent skill into backend/src from them.
- Embed Studio prompts and tools target the Embed.mount contract; seed
embeds are migrated to it.
- Add a headless checker (check:embeds), an eval harness with comparison
report, and a gallery of showcase embeds and banners.
Co-authored-by: Cursor <cursoragent@cursor.com>
feat(collab)!: migrate to Hocuspocus v4 and harden persistence
- Upgrade Hocuspocus 3 -> 4.8, Tiptap 3.33, @tiptap/y-tiptap 3.2, Yjs 13.6.33
and require Node 22 (Docker images and README).
- Wire Hocuspocus v4 custom integration (web Request, forwarded messages and
close events) and freeze inbound edits before the final shutdown snapshot.
- Fail-closed document loading, atomic local writes, ordered HF pushes with
retry, and a cloud-pull error stage in the sync indicator.
- Run typecheck and tests as blocking steps in the Docker build, the only CI
gate for a Space that deploys on push.
- Add data-safety, storage-ordering, shutdown-flush and auth-guard suites,
plus an opt-in Playwright collab-sync E2E test.
BREAKING CHANGE: Node 22+ is required; y-tiptap 3.2 drops position
migrations, so every collaborating client must reload after deploy.
Co-authored-by: Cursor <cursoragent@cursor.com>
fix(highlight): auto-detect language for code blocks without explicit lang
Code blocks authored without a language rendered as plain text in both the
editor and the published output (Shiki falls back to "text"). Add a shared
lowlight-based detector and use it as a fallback in the editor decorations
and the publish transformer, so language-less blocks get highlighted
identically everywhere - including in already-written articles.
Co-authored-by: Cursor <cursoragent@cursor.com>
fix(publisher): render math server-side via KaTeX
TipTap's math extension emits empty inline/block-math placeholders during
generateHTML (rendering is a view-only step). Add a math transformer that
fills those placeholders with static KaTeX HTML so formulas appear in the
published article. Pin the KaTeX CSS CDN version to the server-side katex.
Co-authored-by: Cursor <cursoragent@cursor.com>
feat(editor): inline author editor with affiliation typeahead and DnD
Simplify the Authors & affiliations modal UX without changing the data
schema:
- Add/edit authors inline (drop the separate AuthorInlineForm modal).
- Attach affiliations via a single typeahead that matches an existing one
or creates a new one in one gesture.
- Collapse the affiliations list (reorder + rename + URL) behind a
disclosure since it is rarely touched.
- Replace up/down chevrons with a grip handle and native drag-and-drop
reordering for both authors and affiliations.
Store gains atomic addAuthor/updateAuthor (create + attach new
affiliations in one transaction) and auto-prunes orphan affiliations with
1-based index remapping. The agent tooling and system prompt follow the
new author-driven affiliation model.
Co-authored-by: Cursor <cursoragent@cursor.com>
fix(publisher): render banner in fullBleed mode to match the editor
The editor preview builds the banner srcdoc with `{ fullBleed: true }`
(FrontmatterHero), but the publisher built it with no options. Without
fullBleed the published banner kept the default 16px body padding, lacked
the 100%-height chain, and ran the height reporter (resizing the iframe to
the content scrollHeight instead of the parent's 5:2 aspect-ratio box) -
so the published banner looked different from the editor. Pass
`{ fullBleed: true }` for parity.
Co-authored-by: Cursor <cursoragent@cursor.com>
feat(editor): Iframe embed component for remote URLs
Adds a new atomic component `Iframe` (slash menu icon 🔗) that embeds an
arbitrary remote URL via `<iframe src=...>` instead of inlining HTML
from the embed store. Use case: integrating widget Spaces (e.g. carbon-
tokenization-widgets) without having to download and adapt their HTML
to the strict create-html-embed conventions.
- Shared component def (atomic, fields: src, title, desc, height, wide)
- Custom NodeView with live iframe preview, Settings + Reload buttons,
auto-resize when the remote page emits postMessage({type:"embedResize"})
- Publisher transformer emits <figure class="html-embed"> reusing the
existing iframe/figcaption markup so styling and figure numbering
carry over for free
- llms.txt renderer surfaces the URL as a Markdown link
- 3 publisher tests covering happy path, empty-src drop, and wide flag
Co-authored-by: Cursor <cursoragent@cursor.com>
fix(auth): cookie lifetime now matches the JWT exp, not a stale 8h fallback
Users who came back to the editor 9+ hours after logging in were
getting a confusing "OAuth token has expired" error from HF when
the server tried to push to the dataset on their behalf. The
underlying HF JWT is valid for 30 days but our cookie was set
to 8 hours, so the cookie died first, the browser stopped
sending it, /api/auth/status flipped to unauthenticated, and
the background push retried with the old _cachedToken until it
finally got 401'd by HF.
Fix the cookie lifetime to match the real JWT exp claim:
- Decode the JWT (no signature verification - we just want exp,
HF re-checks the signature on every API call anyway) and use
`exp - now` directly. That's the most authoritative "when does
this stop working" signal available.
- Fall back to `expires_in` from the OAuth /token response if
decoding fails (malformed JWT, future format change, ...).
- Floor at 30 days. The previous fallback was 8 hours which
guaranteed friction even when HF returned a healthy long-lived
…
feat(storage): first-class data - no silent failures in the persistence pipeline
The "Saved" label in the top bar used to be a comforting lie:
several failure modes (createRepo 403 on a missing manage-repos
scope, writeFileSync on a readonly FS, uploadFile mid-debounce
network blip) all collapsed into a console.error that the editor
never surfaced. A user could type for an hour, see "Saved" the
whole time, lose their tab, and discover only after the container
rebuilt that nothing had ever made it to the dataset.
Make every link in the chain observable, and make the worst signal
always win in the UI.
Backend
-------
- In-memory `StorageStatus` tracker in hf-storage.ts:
- `datasetReady` (createRepo succeeded or returned 409)
- `lastLocalSaveAt` / `lastCloudPushAt` epoch ms
- `pendingPush` (a debounce timer is armed)
- `lastError {stage, message, statusCode, at, docName}` where
`stage` is one of `dataset-create | local-save | cloud-push`
Every write path records success; every error path records the
failure. Success on one stage clears the error for …
feat(storage): private dataset by default + /d/* reverse proxy
The dataset that backs persistence was being created `private: false`
on every first write. For org-owned Spaces with strict data
policies (notably `HuggingFaceBio/carbon-tokenization`) this could
either silently fail (org blocks public dataset creation) or be
flat-out wrong (working drafts of an internal research paper
shouldn't be sitting on a public dataset).
Flip the default to `private: true`. The complication this creates
is that published articles' `<img>` tags, og:image and PDF
download all pointed at `huggingface.co/datasets/.../resolve/...`
URLs that would now 401 for anonymous viewers. Solve that with a
small reverse-proxy route on the editor itself.
- New `GET /d/:path*` handler streams from
`huggingface.co/datasets/${id}/resolve/main/${path}` to the
caller, attaching the right HF token along the way:
1. cookie token from the current request (most viewers are
signed in on private Spaces anyway)
2. last-known cached user token (any signed-in request warm…
revert(auth): drop OAuth popup flow, restore plain new-tab login
The popup + window.top.location workaround (bdbc54d, e94e499)
turned out to break the very thing it was meant to improve. In
practice modern browsers blocked the cookie on iframe reload
because of third-party cookie policies, and the fallback that
navigated window.top dumped the visitor out of the HF embed
altogether - net result: extra moving parts AND a worse UX than
the original target="_blank" tab.
Revert to the original behavior: the "Sign in" button is a plain
<a href="/oauth/authorize" target="_blank"> that opens the auth
flow in a new tab. The new tab lands on *.hf.space/editor
first-party once auth completes; the visitor uses that tab.
Specifically this revert removes:
- The pendingStates entry shape upgrade (popup boolean). Map
is back to a flat Map<string, number> timestamp store.
- The ?popup=1 query in handleOAuthAuthorize.
- The popup branch in handleOAuthCallback that served a
self-closing landing page.
- The renderPopupClosePage() helper.
- The inlin…
fix(auth): drop HF iframe on popup close so cookie is first-party
The popup OAuth flow shipped in bdbc54d had a latent third-party
cookie problem that only surfaces on modern browsers:
- The popup runs as its own top-level browsing context with
top-level = *.hf.space. The Set-Cookie at the end of the
OAuth round-trip therefore lands as a first-party cookie
there. So far so good.
- The parent iframe's top-level is huggingface.co (HF embeds
every Space inside huggingface.co/spaces/<owner>/<name>).
Reloading the iframe issues a request to *.hf.space FROM
that top-level - i.e. a third-party request.
- Chrome 124+'s ongoing TPC phase-out, Safari ITP, and Firefox
strict mode all refuse to attach the *.hf.space cookie to a
third-party request now. The reload therefore arrives with
no auth cookie and the login page reappears, looking like
"the popup did nothing".
Fix: when the popup closes, navigate window.top (not window) to
*.hf.space/editor. That's a cross-origin top-level navigation,
which browsers ALLOW (o…
Wraps the user chip in the topbar with a dropdown that exposes a
"Sign out" action. Matches the visual + interaction pattern of the
adjacent "More actions" menu so the two feel like a coherent
toolbar element rather than a one-off.
Backend (routes/auth.ts + auth.ts):
- New POST /api/auth/logout (with a GET alias for ops/debug).
handleOAuthLogout clears the hf_access_token cookie, mirroring
every attribute the original res.cookie(...) used in
handleOAuthCallback - browsers only delete a cookie if the new
"expired" Set-Cookie matches path/secure/sameSite, otherwise we
end up shipping two cookies and the session sticks.
- POST is the canonical method so the call can't be hijacked by a
cross-site <img>/<form> request; GET stays available for curl
debugging and incident response.
Frontend (TopBar.tsx):
- Chip becomes a <button> with aria-haspopup="menu" that toggles
an account menu. Color/avatar/name unchanged - same visual.
- Dedicated state + ref (accountMenu…
feat(auth): OAuth popup window instead of full-tab redirect
When the visitor is inside the HF Space iframe (i.e. browsing
huggingface.co/spaces/<owner>/<name> rather than the bare
*.hf.space backend URL), clicking "Sign in" used to open a brand
new full-screen tab. That kicks the user out of the Space's
visual context, drops them on the *.hf.space origin until they
manually navigate back, and requires a hard refresh of the
iframe to pick up the new cookie.
Replace with a centered popup window that closes itself once
the auth round-trip completes:
Frontend (login page, served by renderLoginPage):
- Inline script intercepts the button click ONLY when we're in
an iframe (window.self !== window.top). Same-tab direct
visits keep the classic href behavior - that path was already
optimal.
- Appends ?popup=1 to /oauth/authorize so the backend knows to
render a self-closing landing page on return.
- Polls w.closed every 400ms; on close, reloads the iframe to
pick up the freshly-set cookie.
- If window.open returns null (popup blocke…
fix(publisher): footer credit links to the editor Space
The footer credit used to point at the legacy Astro-only static
template (tfrere/research-article-template). The editor is now
the canonical entry point - it bundles the static renderer and is
what people fork to start a new article. Update the credit link
accordingly so readers landing on a published article find the
right starting point.
Snapshot refreshed.
Co-authored-by: Cursor <cursoragent@cursor.com>
fix(hf-storage): forward OAuth token on the direct-fetch fallback
Private (org-owned) Spaces back their published artefacts on a
private HF dataset. \`pullPublishedAssets\` walks that dataset on
boot and after each login to restore the latest published file
set. Two issues showed up in the Space logs:
1. When the Hub lib already returned a clean 404 ("file isn't on
the repo"), we still re-tried with a direct \`fetch()\`. That
second call had no token, so on a private dataset it 401'd -
double the noise per missing file (404 + 401 lines), and the
401 looks scarier than it is because it suggests an auth
problem where there isn't one. Skip the fallback when the Hub
lib gave us a definitive 404.
2. The direct-fetch fallback never carried the bearer token, so
it could never actually substitute for the Hub lib on private
datasets - even a real network glitch would silently 401. Pass
the same \`accessToken\` we use for the Hub call. Anonymous
fallback is still allowed (no header) when there's no token,
matching the old beh…
chore(ws): verbose auth logs to triage Disconnected reports
Add structured logging on both ends of the WS handshake so a
"Disconnected" label in the editor top bar can be pinpointed
without guessing:
- Upgrade handler logs the cookie header size and whether
extractToken found our session cookie. This catches the case
where the browser doesn't ship cookies on the WS upgrade
(some HF Space gating + private/org setups strip them on
upgrade even when plain HTTP requests send them fine).
- onAuthenticate logs which source supplied the token (the
client subprotocol or the server-side cookie fallback), the
resolved user, the configured Space owner, and any
accessIssue surfaced by resolveUser. Errors thrown to
Hocuspocus now also include the username + accessIssue so the
reason is visible in the rejected-connection log line, not
just a generic "Unauthorized".
Logs intentionally avoid printing the token itself - they only
expose its length and origin, matching the existing privacy
posture of the auth pipeline.
Co-authored-by: Curs…
fix(auth): use roleInOrg from whoami, drop broken members API
The Space owned by an org never let any signed-in user through to
the editor, even with full org write access. Root cause: we were
reading the role from
\`https://huggingface.co/api/organizations/{name}/members\`, but
that endpoint returns members as plain user records
(\`{ user, fullname, avatarUrl, isPro, type, _id }\`) with no
\`role\` field. The check \`member.role === "write" || "admin"\`
was therefore always false and every org-member visitor ended up
on the login screen.
Switch to the \`roleInOrg\` field that whoami already returns in
\`info.orgs[i]\`. It carries one of \`admin | write | contributor |
read\`, exactly what we need, and we already paid for that
round-trip via \`whoAmI()\`. The org-members API call is dropped
entirely.
Also pick up the \`resourceGroups\` field from the same payload:
HF lets \`contributor\` users get \`write\`/\`admin\` on specific
groups, and the Space may live in one of those groups. Treat
"contributor at org level + any write/admin group" as wr…
feat(publisher): editor pill shows who you're signed in as
Upgrade the editor quick-link from a bare pencil icon to a
proper pill that contextualises the action:
┌──────────────────────────────────────────────────────┐
│ [avatar] Signed in as @tfrere [✎ Edit article] │
└──────────────────────────────────────────────────────┘
The visitor sees who they're authenticated as before clicking,
which makes the "would I be writing to the real file?" question
self-answering. Useful when multiple HF accounts share the same
browser session, or when a collaborator wants to confirm they're
not editing on someone else's behalf.
Implementation:
- Render placeholder content (\"@you\" + empty <img>) so the
layout doesn't shift when /api/auth/status comes back. The
pill is still \`hidden\` by default - no flash for anonymous
visitors.
- Inline script fills the <img>.src (preferring
user.avatarUrl, falling back to /api/users/<name>/avatar)
and the @handle, then drops the \`hidden\` attribute.
- New \`.edit-pill\` styles: rounded pill, pa…
feat(publisher): editor quick-link for signed-in editors
The published article and the editor share the same Space, but a
visitor who already has edit rights had no way to jump from one
to the other without retyping \`/editor\` in the URL bar. Add a
small pencil icon top-right, mirroring the existing theme toggle
on the top-left, that links to /editor.
Visibility:
- Hidden by default (\`<a id="edit-link" ... hidden>\`) so non-
editors / anonymous visitors never see a flash.
- An inline script probes \`/api/auth/status\` on load and removes
the \`hidden\` attribute when \`canEdit\` is true. Fetch failures
(offline preview, exported HTML opened from disk, etc.) are
silently swallowed - the button just stays hidden.
- Hidden under 1100px (same breakpoint as the theme toggle) so
mobile / tablet layouts aren't cluttered.
Styling: matches the theme toggle (40px circle, page-bg fill,
1px border, soft shadow) so the page stays balanced visually.
\`mix(--primary-color)\` tint on hover hints at the destination.
Snapshot updated to reflect…
fix(agent): disable response buffering for chat streaming
The AI SDK streams tokens chunk-by-chunk via \`streamText\` +
\`toUIMessageStreamResponse\`, but on a HF Space the response
went through layers that re-coalesced everything into one big
payload arriving at message end:
- Nginx in front of the Space buffers responses by default
unless \`X-Accel-Buffering: no\` is set;
- transparent gzip on the path holds chunks until the
compression window fills;
- TCP_NODELAY off keeps small writes in the kernel until they
reach MTU.
End result: the user saw \"Thinking...\" then the whole
assistant reply dropped at once, masking the streaming.
Fix:
- Set \`X-Accel-Buffering: no\` and \`Content-Encoding: identity\`
on the streamed response so proxies pass bytes through as
they arrive.
- Add \`Cache-Control: no-cache, no-transform\` to also block
transforming/compressing intermediaries.
- Call \`res.flushHeaders()\` so the browser commits to streaming
mode immediately (first-byte triggers progressive rendering
of the assistant bubble)…
fix(agent): forbid re-pasting tool output in the text reply
After calling \`createEmbed\` / \`patchEmbed\` (embed chat) or
\`insertAtCursor\` / \`applyDiff\` (main chat), the model would
re-emit the just-inserted code/prose verbatim inside its text
reply. The chart is already live in the preview pane and the
doc is already updated, so the dump is pure noise - it pollutes
the chat history, looks like a "did it stream?" stall to the
user (the long reply only appears once the full text is buffered
on the client), and bloats the next turn's context window.
Tighten both prompts:
- embed-system-prompt: new "Reply format (STRICT)" section.
Caps the reply at 1-2 sentences, explicitly forbids fenced
code blocks of the chart source, bullet "feature" lists and
phrases like "Voici le code" / "Just paste this where you
want the banner". Keeps an escape hatch for "show me the
code" requests (short relevant snippet only).
- system-prompt: extend the anti-patterns list with a "NEVER
paste the content you just inserted/replaced back into your
te…
The HfUser block was rendering as the generic AtomicView - a
dashed placeholder card with three labelled inputs - which looked
nothing like the actual upstream component (avatar + display name
+ @handle). Authors couldn't tell what the published page would
look like without a round-trip through publish.
Replace it with a dedicated NodeView that reproduces the exact
DOM of `app/src/components/HfUser.astro` in the editor:
.hf-user
└─ .hf-user__left
├─ .hf-user__avatar (img or "?" placeholder when empty)
└─ .hf-user__text
├─ .hf-user__name (display name)
└─ .hf-user__row
└─ .hf-user__username (@handle)
Inline editor:
- Revealed when the node is selected, or when `username` is still
empty right after insertion (prompts the author to fill at
least the handle).
- Three rows: Username / Display name / URL. URL placeholder
switches to `https://huggingface.co/<username>` once a handle
is known, so the user can see they don't need to…
fix(embed): SVG text now follows the iframe theme
Three stacked bugs were keeping the chart text black in dark mode:
1. EmbedStudio mounted both preview iframes with
sandbox="allow-scripts" only (no allow-same-origin). The bootstrap
script couldn't reach window.parent.document, so the cascade fell
through localStorage to matchMedia(prefers-color-scheme) - which
returns the OS preference, not the app theme. Result: the iframe
could land on a different theme than the article. Aligned the
sandbox with HtmlEmbedView ("allow-scripts allow-same-origin").
2. The THEME_BOOTSTRAP in shared/embed-doc.ts always overwrote the
srcdoc-provided data-theme attribute, even when every detection
path failed. Honour the existing data-theme before falling back
to matchMedia so an explicit isDark from buildEmbedSrcdoc wins.
3. SVG text/line/path don't inherit CSS color the way HTML elements
do - their default fill/stroke is "black", not "currentColor".
Charts that scoped colours via `body { color: var(--text-color) }`
…
feat(embed-studio): make agent-generated charts theme-aware
The iframe already supports live light/dark swap via CSS variables and
a postMessage(setTheme) hot-swap, but the LLM kept generating charts
that hardcode colours into SVG attributes (fill="#333", stroke="black",
...). Those values can't be overridden by the parent's data-theme
attribute, so the chart looked correct on whatever theme the model
guessed and broken on the other one.
Two complementary fixes:
1. Forward the current theme (light/dark) from EmbedStudio through
useEmbedChat into the request context, and surface it in the
system prompt as a "Current theme" section. The model now knows
which background it's painting against and can self-correct.
2. Rewrite the "Colors & theming" section of the embed system prompt
with a concrete CSS pattern (scoped .d3-* rules driving fill/stroke
via var(--text-color), --axis-color, --grid-color, ...) and an
explicit ban on hardcoded SVG colour attributes. Add a hint about
window.__chartRerender for JS-driven palettes.
No…
fix(agent): default back to gpt-oss-120b, pin Llama 3.3 to Together
Groq (HF Router's :fastest pick for Llama 3.3 70B) validates tool calls
very strictly and was rejecting the editor's 18-tool registry with
"Failed to call a function. Please adjust your prompt." Fireworks has
deprecated the Llama 3.3 checkpoint; Nscale doesn't support the `tools`
parameter at all. Together serves the same model with full
tool-calling support, so pin Llama 3.3 to `:together`.
Restore openai/gpt-oss-120b as the default - it's HF's trending
tool-calling model and the reasoning-strip fix already covers the
Cerebras round-trip case.
Co-authored-by: Cursor <cursoragent@cursor.com>
fix(agent): strip reasoning_content from history, default to Llama 3.3 70B
Reasoning models (gpt-oss-*, DeepSeek R1, ...) emit a `reasoning` UI part
alongside their text answer. The AI SDK persists those parts and on the
next turn round-trips them as `reasoning_content` on the assistant
message - which some HF Inference Providers (notably Cerebras, the
default for gpt-oss) reject with 400 wrong_api_format. The model doesn't
need to see its own prior reasoning to keep the conversation going, so
filter those parts out before convertToModelMessages.
While we're at it, swap the default model from gpt-oss-120b to
meta-llama/Llama-3.3-70B-Instruct: it doesn't emit reasoning, works
across every provider exposing it, and is a more conservative starting
point for first-time forkers.
Co-authored-by: Cursor <cursoragent@cursor.com>
feat(agent): switch AI backend from OpenRouter to HF Inference Providers
The chat panel and embed studio now call Hugging Face Inference Providers
(OpenAI-compatible router at https://router.huggingface.co/v1) via
@ai-sdk/openai-compatible, using the logged-in editor's OAuth token when
available and falling back to HF_TOKEN. Forking the Space no longer
requires wiring an OpenRouter API key - the user's own HF token funds
their own inference.
- Replace @openrouter/ai-sdk-provider with @ai-sdk/openai-compatible
- Forward the OAuth cookie token per request, fallback to HF_TOKEN
- Refresh AVAILABLE_MODELS to HF-served, tool-calling-capable models
(gpt-oss 120B/20B, Llama 3.3 70B, Qwen3 Coder 480B, DeepSeek V3.1)
- Add inference-api to hf_oauth_scopes and document the new env vars
(HF_INFERENCE_MODEL, expanded HF_TOKEN role) in README + SPECIFICATION
- Update agent-chat tests to expect the new "Hugging Face token" error
Co-authored-by: Cursor <cursoragent@cursor.com>
feat(publisher): generate llms.txt Markdown twin for LLM agents
External LLMs/agents (Claude, Perplexity, ...) struggle with the
heavy published HTML: theme bootstrap, KaTeX/Mermaid runtimes,
~7 inlined CSS files, TOC chrome, and D3 charts wrapped in
<iframe srcdoc>. The static research-article-template already
ships an `llms.txt` (Astro build plugin); the editor's publisher
now does the same, walking the TipTap-JSON we already extract
for the HTML/PDF pipeline.
Pipeline addition (publisher/index.ts):
- After writing index.html, render the same JSON to Markdown via
the new markdown-renderer.ts and write `published/<doc>/llms.txt`
- Re-render with the public HF meta and include it in the dataset
upload commit (hf-storage.ts adds llms.txt to the file list)
Routing (create-app.ts):
- GET /llms.txt serves the published Markdown twin with
Content-Type: text/markdown; charset=utf-8 (404 before publish)
- GET /robots.txt advertises it via the `LLMs-Txt:` header,
mirroring the upstream template
Conventions in the renderer mirror the upstream Ast…
fix(publisher): render HF user card via dedicated transformer
The hfUser atomic node was serialized to an empty
`<div data-component="hfUser">` placeholder with no transformer to
turn it into the actual profile card, so it rendered as nothing in
published articles. Add `hfUserTransformer` mirroring the upstream
`HfUser.astro` (avatar + name + @handle), register it in the pipeline,
ship the matching `.hf-user` styles in `_publisher.css`, and cover the
three cases (full attrs, fallback to username, missing username) with
unit tests.
Made-with: Cursor
refactor(login-page): neutral title, outlined CTA, drop wordmark
- Title back to default text color (dropping the primary tint)
- Switch the CTA from a filled pill to an outlined pill: 1.5px primary
border, transparent background, color-mix tint on hover/active
- Remove the "Research Article Template Editor" wordmark for a cleaner
silhouette
Made-with: Cursor
feat(login-page): full HF logo, primary title, pill CTA, refined layout
- Inline the complete official Hugging Face logo SVG (face + both hugging
hands), fixing the previously truncated mark in the button
- Move the title to primary color and bump it to a fluid clamp size with
Apple-grade letter-spacing
- Replace the outlined CTA with a pill-shaped primary button: vertical
gradient fill, layered inset highlights, soft elevation, 1px lift on
hover with deeper shadow, slightly tighter letter-spacing
- Drop the "after signing in, refresh this page" hint since the OAuth flow
redirects automatically
- Add a soft radial primary tint on the page background and a discreet
wordmark below the CTA for brand presence
- Use the SF / Source Sans Pro stack with antialiasing tuned for both light
and dark modes
- Simplify renderLoginPage: hint slot removed, callers now only pass title
and description
Made-with: Cursor
feat(login-page): align with app design tokens, bigger outlined HF button
- Extract a single renderLoginPage() helper used by both the editor login
gate and the published-article fallback (no more duplicated inline HTML)
- Use the app's primary color (OKLCH) and Source Sans Pro font, with proper
light/dark via prefers-color-scheme so the page no longer looks like an
unrelated dark stub
- Replace the small filled button with a bigger outlined CTA (14×22 px
padding, 1.5px primary border, color-mix hover)
- Inline the official Hugging Face brand logo SVG (no external network
dependency, no emoji fallback)
- Escape user-controlled hint substitutions through a dedicated escapeHtml()
Made-with: Cursor
fix(ui,publisher): kill theme/color flickers and translation prompts
- Published page and its banner iframe now inline a synchronous theme
bootstrap in <head>, so the first paint already uses the correct
data-theme (no dark -> light flicker on navigation).
- <meta name="google|robots" content="notranslate"> on both the
editor (frontend/index.html) and the published article so Chrome
stops proposing to translate the page to French.
- CollaborationCursorV3: silence a peer's caret + label (via the
.collaboration-cursor--silenced class) when that same peer also
broadcasts an agentFocus. Fixes the duplicate "<Name>" + "<Name>
agent" labels that stacked while a chat action was active.
- Embed Studio preview container pinned to --page-bg and the iframe
element forced to background: transparent + color-scheme: light
dark, so the preview tracks dark mode instead of falling through
to the browser's default white.
- App.tsx primaryHue sync: when the Yjs settings map has no
primaryHue (fresh state or after reset-article), drop the inline
--p…