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…
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>
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): drafts with Apply to article, compare, data drawer
- The studio edits a shared draft (Y.Map("embed-drafts")); the article
keeps the applied chart until "Apply to article". New charts from the
slash menu or the top bar get their node only on Apply, at the cursor
position kept as a Yjs relative position: no more empty nodes.
- Closing with unapplied changes offers apply, keep draft or discard;
the node shows "X is editing this chart" (awareness) or "Unapplied
draft by X". Charts already in the article are not renamed.
- Before/after compare reuses the two preview iframes side by side, with
a line diff in the Code tab.
- Docked data drawer with typed columns and a "used by this chart" flag;
files dropped on the chat and tables pasted into it become data files
attached to the next message.
- "Writing chart... N lines" while the tool input streams.
- The conversation of each chart is shared in Y.Map("embed-chats")
(readable text only) instead of localStorage.
Co-authored-by: Cursor <cursoragent@cursor.com>
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>
test(load): add a load test with simulated users, MCP agents and chaos
npm run test:load runs a real server on the fake Hub (production push
timings) with users in child processes typing keystroke by keystroke,
churn (wifi drops, sleeping laptops, reloads), MCP agents, a 15k-word
article and optional HF outage + deploy on a wiped disk. It reports
propagation latency, server CPU/RSS, HTTP and agent latency, Hub
pushes, then checks that nothing was lost or diverged on any tab, in
the cloud copy and on a fresh container.
The scenario harness gains realTimings, wrap, env, nodeArgs, pid,
errorLines and a bounded log buffer; Tab.open accepts any { port }.
Documented in TESTS.md section 2.6 with results on an M1 Pro.
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(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>
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(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…
Three references slipped through the HF Inference migration:
the system diagram, the API route table (/api/chat description)
and the agent sequence diagram all still named OpenRouter as the
LLM backend. Replace them with HF Inference (Providers) to match
the actual implementation in stream-handler.ts.
Co-authored-by: Cursor <cursoragent@cursor.com>
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>
docs: refresh README, architecture, spec and add agent teams proposal
- README: align env var table with real backend (OPENROUTER_API_KEY, HF_DATASET_ID, SPACE_ID,
PUBLISH_BASE_URL, ENABLE_PDF, OAUTH_SCOPES) and fix prerequisites
- ARCHITECTURE / SPECIFICATION: describe the new transformer pipeline, embed studio flow,
mobile TOC + CommentPopover; drop the deleted CommentsSidebar reference
- TESTS: announce the Playwright E2E suite as part of the stack and add 4.1.4 for the
upload rate limiter; note the split between fast hermetic suite and opt-in E2E
- Add AGENT_TEAMS_PROPOSAL.md to track the upcoming multi-agent collaboration design
Made-with: Cursor
feat(backend): rate-limit /api/upload to prevent anonymous abuse
Upload stays intentionally unauthenticated (covered by spec 4.1.3), so guard it with a
simple per-IP sliding-window limiter (30 uploads / 60s). The limiter returns 429 with a
Retry-After header and uses the X-Forwarded-For head when behind a proxy.
Spec updated with the new 4.1.4 test line.
Made-with: Cursor
Phase 1 - Publisher pipeline:
- Extract ~370 lines of inline CSS from html-renderer.ts into _publisher.css
- Create shared/component-defs.ts as single source of truth for component definitions
- Replace 6 regex blocks in postProcess() with linkedom DOM manipulation
- Add GET /api/preview/:docName for testing renders without publishing
- Add 12 snapshot tests for each postProcess transformation (46 tests total)
Phase 2 - Remove MUI:
- Replace all MUI components with native HTML elements + custom CSS
- Create _ui.css with editor chrome styles using --ed-* CSS tokens
- Create Tooltip.tsx using Floating UI (lightweight replacement)
- Replace @mui/icons-material with lucide-react
- Delete theme.ts, remove @mui/* and @emotion/* dependencies
Phase 3 - Documentation:
- Add docs/ARCHITECTURE.md covering CSS layers, HF Spaces constraints,
shared registry, publisher pipeline, and test coverage
Made-with: Cursor
fix: prevent seed race condition with Y.Map guard and defensive checks
- Add Y.Map("meta").seeded flag to prevent multiple clients from
seeding the same empty doc concurrently (Yjs merge duplication)
- Set seededRef early to prevent re-entry
- Add authors array length check in seedFrontmatter as extra guard
Made-with: Cursor
test: add vitest test suite for publisher, auth, security, utils