diff --git a/backend/app/llm/languages.py b/backend/app/llm/languages.py new file mode 100644 index 0000000..8681aa7 --- /dev/null +++ b/backend/app/llm/languages.py @@ -0,0 +1,66 @@ +"""The app's interface language, so AI output follows it. + +The mobile app sends X-App-Language (a code such as "es") when its interface is not English. The middleware in +main.py puts it in a context variable for the request. Jobs created during the request carry it in their params +(services/jobs.py), and the worker restores it while it runs them. Pipelines that already take a language get the +English name as their default, and an explicit language (picked in the app or named in chat) still wins. With no +header, nothing changes: AI output stays in the language of the sources.""" + +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar + +# Keep in step with LANGUAGES in mobile/src/i18n/index.ts. English is absent on purpose: the app sends no header. +APP_LANGUAGES: dict[str, str] = { + "es": "Spanish", + "fr": "French", + "de": "German", + "pt": "Portuguese", + "ar": "Arabic", + "ur": "Urdu", + "zh": "Chinese (Simplified)", + "ja": "Japanese", + "ko": "Korean", +} + +HEADER = "x-app-language" +PARAM = "app_language" # the code, kept in a job's params + +_current: ContextVar[str | None] = ContextVar("app_language", default=None) + + +def parse(value: str | None) -> str | None: + """A supported code from a header value such as "es", "es-MX" or "zh-Hans", else None.""" + if not value: + return None + code = value.strip().lower().replace("_", "-").split("-")[0] + return code if code in APP_LANGUAGES else None + + +def app_language() -> str | None: + """The current request's (or job's) app language code, or None.""" + return _current.get() + + +def app_language_name() -> str | None: + """The English name of the current app language ("Spanish"), or None.""" + code = _current.get() + return APP_LANGUAGES.get(code) if code else None + + +@contextmanager +def use_app_language(code: str | None) -> Iterator[None]: + token = _current.set(parse(code)) + try: + yield + finally: + _current.reset(token) + + +def reply_language_note() -> str: + """A line for the writer notes in chat, or "" when the app is in English.""" + name = app_language_name() + if not name: + return "" + return (f"Reply language: write the answer in {name}, the language of the writer's app. If the writer's message " + "is written in another language, answer in the language of the message instead.") diff --git a/backend/app/main.py b/backend/app/main.py index 8026702..ed5b697 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -9,6 +9,8 @@ from fastapi.responses import PlainTextResponse from app.config import settings +from app.llm.languages import HEADER as APP_LANGUAGE_HEADER +from app.llm.languages import use_app_language from app.llm.provider import configure_default from app.routers import ( artifacts, @@ -87,6 +89,13 @@ async def lifespan(app: FastAPI): ) +@app.middleware("http") +async def app_language(request: Request, call_next): + # The mobile app's interface language (llm/languages.py): AI output made for this request follows it. + with use_app_language(request.headers.get(APP_LANGUAGE_HEADER)): + return await call_next(request) + + @app.middleware("http") async def request_id(request: Request, call_next): rid = request.headers.get("x-request-id") or uuid.uuid4().hex[:12] diff --git a/backend/app/pipeline/research.py b/backend/app/pipeline/research.py index 744b201..5876321 100644 --- a/backend/app/pipeline/research.py +++ b/backend/app/pipeline/research.py @@ -35,6 +35,7 @@ from app.chat_memory.tools import ChatTools, is_chat_path from app.config import settings from app.corpus import Corpus, CorpusError, ScopedTools +from app.llm.languages import reply_language_note from app.llm.postprocess import strip_em_dashes from app.llm.provider import agent_lm, fast_lm, track_usage, triage_lm, writer_lm from app.llm.signatures import ( @@ -1142,6 +1143,12 @@ def _memory_parts(notes: str) -> str: return ", ".join(parts) or "empty" +def with_reply_language(profile: str | None) -> str: + """The writer notes plus, when the app is not in English, which language to answer in (llm/languages.py).""" + note = reply_language_note() + return "\n".join(p for p in ((profile or "").strip(), note) if p) + + def research( corpus: Corpus, allowed: dict[str, str], @@ -1480,7 +1487,8 @@ def log(kind: str, detail: str) -> None: tool_list += external_tools inputs = dict(question=external_question(route.question) if external_only else route.question, conversation=conversation_text(history), - archive_guide=archive_guide(tools), writer_profile=profile or "(none)", answer_length=route.detail, + archive_guide=archive_guide(tools), writer_profile=with_reply_language(profile) or "(none)", + answer_length=route.detail, prefetched="(none)") if external_only: signature = ResearchExternal diff --git a/backend/app/routers/sources.py b/backend/app/routers/sources.py index f910f72..f569a47 100644 --- a/backend/app/routers/sources.py +++ b/backend/app/routers/sources.py @@ -24,7 +24,7 @@ rebuild_index, store_entries, ) -from app.services.jobs import create_job, pending_job, serialize_job +from app.services.jobs import create_job, pending_job, queue_for_documents, serialize_job from app.services.plans import effective_plan, plan_limit_error, post_room from app.services.storage import storage from app.services.url_policy import classify_url @@ -424,10 +424,10 @@ def _queue_notebooklm_processing(ctx: Ctx, changed: list[uuid.UUID]) -> None: if not changed or not settings.llm_api_key: return ids = [str(doc_id) for doc_id in changed] - create_job(ctx.db, ctx.workspace.id, "topics", {"document_ids": ids}, max_attempts=2) - create_job(ctx.db, ctx.workspace.id, "ideas", {"document_ids": ids}, max_attempts=2) + queue_for_documents(ctx.db, ctx.workspace.id, "topics", ids, max_attempts=2) + queue_for_documents(ctx.db, ctx.workspace.id, "ideas", ids, max_attempts=2) if settings.post_cards_enabled: - create_job(ctx.db, ctx.workspace.id, "post_cards", {"document_ids": ids}, max_attempts=2) + queue_for_documents(ctx.db, ctx.workspace.id, "post_cards", ids, max_attempts=2) if not pending_job(ctx.db, ctx.workspace.id, "resurface_scan"): create_job(ctx.db, ctx.workspace.id, "resurface_scan", {}, max_attempts=2) diff --git a/backend/app/services/jobs.py b/backend/app/services/jobs.py index fe239a5..d7a4f96 100644 --- a/backend/app/services/jobs.py +++ b/backend/app/services/jobs.py @@ -12,10 +12,12 @@ from datetime import UTC, datetime, timedelta from fastapi.concurrency import run_in_threadpool -from sqlalchemy import or_, select +from sqlalchemy import case, or_, select from sqlalchemy.orm import Session from app.config import settings +from app.llm.languages import PARAM as APP_LANGUAGE_PARAM +from app.llm.languages import app_language, app_language_name from app.models import Job, UsageEvent TERMINAL = {"done", "failed"} @@ -52,6 +54,48 @@ def pending_job(db: Session, workspace_id: uuid.UUID, kind: str) -> bool: Job.status.in_(("queued", "running"))).limit(1)) is not None +def queue_for_documents(db: Session, workspace_id: uuid.UUID, kind: str, ids: list[str], **kw) -> Job | None: + """Enqueue a per-post job (topics, ideas, post_cards) for these posts, or fold them into one of that kind still + waiting in the queue (never tried yet), so a batch of uploads makes one job instead of one per file. A queued job with no + document_ids already covers every post. SKIP LOCKED passes over a job a worker is claiming right now.""" + if not ids: + return None + params = with_app_language(kind, {"document_ids": ids}) + waiting = db.scalars( + select(Job) + .where(Job.workspace_id == workspace_id, Job.kind == kind, Job.status == "queued", + Job.attempts == 0) # not one waiting out a retry + .order_by(Job.created_at) + .with_for_update(skip_locked=True) + ).all() + for job in waiting: + theirs = {k: v for k, v in (job.params or {}).items() if k != "document_ids"} + if theirs != {k: v for k, v in params.items() if k != "document_ids"}: + continue # different options (another language, force): kept apart + have = job.params.get("document_ids") + if have is not None: + job.params = {**job.params, "document_ids": list(dict.fromkeys([*have, *ids]))} + db.commit() + return job + return create_job(db, workspace_id, kind, {"document_ids": ids}, **kw) + + +# Jobs whose pipeline takes params["language"] (falling back to the language of the sources when it is empty). +LANGUAGE_KINDS = frozenset({"quiz", "flashcards", "report", "report_block", "slide_deck", "audio_overview"}) + + +def with_app_language(kind: str, params: dict) -> dict: + """Carry the app language into the job: its code always (the worker restores it, so jobs the job starts inherit + it), and its name as the default output language for kinds that take one. An explicit language wins.""" + code = app_language() + if not code: + return params + out = {**params, APP_LANGUAGE_PARAM: code} + if kind in LANGUAGE_KINDS and not str(params.get("language") or "").strip(): + out["language"] = app_language_name() + return out + + def create_job( db: Session, workspace_id: uuid.UUID, @@ -66,7 +110,7 @@ def create_job( job = Job( workspace_id=workspace_id, kind=kind, - params=params or {}, + params=with_app_language(kind, params or {}), artifact_id=artifact_id, status="queued", max_attempts=max_attempts, @@ -108,13 +152,17 @@ def update_job( # Consumer side (worker) +# Imports someone is watching a progress bar for: taken before the background work earlier imports queued. +FOREGROUND_KINDS = ("ingest", "import_url", "import_upload") + + def claim_next(db: Session, worker_id: str) -> uuid.UUID | None: - """Atomically take the oldest runnable job. SKIP LOCKED lets parallel workers pass each other.""" + """Atomically take the oldest runnable job, imports first. SKIP LOCKED lets parallel workers pass each other.""" now = utcnow() job = db.scalar( select(Job) .where(Job.status == "queued", or_(Job.run_after.is_(None), Job.run_after <= now)) - .order_by(Job.created_at) + .order_by(case((Job.kind.in_(FOREGROUND_KINDS), 0), else_=1), Job.created_at) .limit(1) .with_for_update(skip_locked=True) ) diff --git a/backend/app/worker.py b/backend/app/worker.py index 677c090..a3bd44b 100644 --- a/backend/app/worker.py +++ b/backend/app/worker.py @@ -29,6 +29,8 @@ from app.chat_memory.organize import forget_orphans, organize_chat, rebuild_chat from app.config import settings from app.db import SessionLocal, engine +from app.llm.languages import PARAM as APP_LANGUAGE_PARAM +from app.llm.languages import use_app_language from app.models import ( Artifact, Chat, @@ -62,6 +64,7 @@ claim_next, create_job, pending_job, + queue_for_documents, record_usage, retry_or_fail, stale_jobs, @@ -94,10 +97,10 @@ def _after_import(db: Session, job: Job, workspace_id: uuid.UUID, changed: list[ first import builds the writing voice, so none of these need a button press.""" if not changed or not settings.llm_api_key: return - create_job(db, workspace_id, "topics", {"document_ids": changed}, max_attempts=2) - create_job(db, workspace_id, "ideas", {"document_ids": changed}, max_attempts=2) + queue_for_documents(db, workspace_id, "topics", changed, max_attempts=2) + queue_for_documents(db, workspace_id, "ideas", changed, max_attempts=2) if settings.post_cards_enabled: - create_job(db, workspace_id, "post_cards", {"document_ids": changed}, max_attempts=2) + queue_for_documents(db, workspace_id, "post_cards", changed, max_attempts=2) if not pending_job(db, workspace_id, "resurface_scan"): create_job(db, workspace_id, "resurface_scan", {}, max_attempts=2) vp = db.scalar(select(VoiceProfile).where(VoiceProfile.workspace_id == workspace_id)) @@ -417,7 +420,9 @@ def run_job( update_job(db, job, status="failed", error=f"No handler for job kind {job.kind!r}") return try: - outcome = handler(db, job) + # The app language of the request that queued the job, so its output and any job it starts follow it. + with use_app_language((job.params or {}).get(APP_LANGUAGE_PARAM)): + outcome = handler(db, job) except PermanentJobError as exc: db.rollback() job = db.get(Job, job_id) diff --git a/backend/tests/test_app_language.py b/backend/tests/test_app_language.py new file mode 100644 index 0000000..3bbebe4 --- /dev/null +++ b/backend/tests/test_app_language.py @@ -0,0 +1,104 @@ +"""The mobile app's interface language reaches AI output (app/llm/languages.py).""" + +import uuid + +import pytest +from fastapi import APIRouter +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from sqlalchemy.pool import StaticPool + +import app.models # noqa: F401 +from app.db import Base +from app.llm import languages +from app.models import Job, Workspace +from app.pipeline.research import with_reply_language +from app.services import jobs as q +from app.worker import Done, run_job + + +@pytest.fixture() +def factory(): + engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool) + Base.metadata.create_all(engine) + return sessionmaker(bind=engine, expire_on_commit=False) + + +@pytest.fixture() +def ws(factory): + with factory() as db: + w = Workspace(name="w", owner_id=uuid.uuid4()) + db.add(w) + db.commit() + return w.id + + +def make(factory, ws, kind, params): + with factory() as db: + return q.create_job(db, ws, kind, params) + + +@pytest.mark.parametrize("value,code", [("es", "es"), ("es-MX", "es"), ("zh-Hans", "zh"), ("AR", "ar"), + ("en", None), ("xx", None), ("", None), (None, None)]) +def test_parse(value, code): + assert languages.parse(value) == code + + +def test_no_app_language_leaves_params_alone(factory, ws): + job = make(factory, ws, "quiz", {"topic": "t"}) + assert job.params == {"topic": "t"} + + +def test_app_language_becomes_the_default_output_language(factory, ws): + with languages.use_app_language("fr"): + job = make(factory, ws, "quiz", {"topic": "t", "language": None}) + assert job.params == {"topic": "t", "language": "French", "app_language": "fr"} + + +def test_explicit_language_wins(factory, ws): + with languages.use_app_language("fr"): + job = make(factory, ws, "slide_deck", {"language": "German"}) + assert job.params["language"] == "German" + + +def test_kinds_without_a_language_only_carry_the_code(factory, ws): + with languages.use_app_language("ja"): + job = make(factory, ws, "ingest", {"source_id": "s"}) + assert job.params == {"source_id": "s", "app_language": "ja"} + + +def test_worker_restores_the_language_for_the_job(factory, ws): + with languages.use_app_language("ko"): + jid = make(factory, ws, "compound_action", {}).id + seen = {} + + def handler(db, job: Job): + seen["code"] = languages.app_language() + return Done() + + run_job(jid, factory, {"compound_action": handler}) + assert seen["code"] == "ko" + assert languages.app_language() is None + + +def test_chat_writer_notes_name_the_reply_language(): + assert with_reply_language("tone: plain") == "tone: plain" + with languages.use_app_language("ur"): + notes = with_reply_language("tone: plain") + assert notes.startswith("tone: plain\nReply language: write the answer in Urdu") + with languages.use_app_language("ur"): + assert with_reply_language(None).startswith("Reply language:") + + +def test_header_sets_the_language_for_the_request(client): + from app.main import app + + router = APIRouter() + + @router.get("/__test/app-language") + def probe(): # a sync route runs in the threadpool, as most routes here do + return {"code": languages.app_language()} + + app.include_router(router) + assert client.get("/__test/app-language", headers={"X-App-Language": "pt-BR"}).json() == {"code": "pt"} + assert client.get("/__test/app-language").json() == {"code": None} diff --git a/backend/tests/test_queue.py b/backend/tests/test_queue.py index e73fb2a..0f06b6a 100644 --- a/backend/tests/test_queue.py +++ b/backend/tests/test_queue.py @@ -137,3 +137,31 @@ async def collect(): seen = asyncio.run(collect()) assert [s["status"] for s in seen] == ["queued", "running", "done"] assert seen[1]["message"] == "halfway" + + +def test_imports_are_claimed_before_older_background_work(factory, ws): + topics = enqueue(factory, ws, "topics") + upload = enqueue(factory, ws, "import_upload") + with factory() as db: + assert q.claim_next(db, "w1") == upload + assert q.claim_next(db, "w1") == topics + + +def test_per_post_jobs_fold_into_one_still_queued(factory, ws): + with factory() as db: + first = q.queue_for_documents(db, ws, "topics", ["a"], max_attempts=2) + again = q.queue_for_documents(db, ws, "topics", ["b", "a"], max_attempts=2) + assert again.id == first.id + assert get(factory, first.id).params["document_ids"] == ["a", "b"] + # Once a worker has it, the next posts get a job of their own + with factory() as db: + assert q.claim_next(db, "w1") == first.id + third = q.queue_for_documents(db, ws, "topics", ["c"], max_attempts=2) + assert third.id != first.id and get(factory, third.id).params["document_ids"] == ["c"] + + +def test_per_post_jobs_keep_different_options_apart(factory, ws): + with factory() as db: + everything = q.create_job(db, ws, "post_cards", {"force": True}) + mine = q.queue_for_documents(db, ws, "post_cards", ["a"]) + assert mine.id != everything.id diff --git a/frontend/public/samples/notestack-sample-article.pdf b/frontend/public/samples/notestack-sample-article.pdf deleted file mode 100644 index f69caf0..0000000 Binary files a/frontend/public/samples/notestack-sample-article.pdf and /dev/null differ diff --git a/frontend/public/samples/solar-system-01-sun-and-formation.pdf b/frontend/public/samples/solar-system-01-sun-and-formation.pdf new file mode 100644 index 0000000..f80b015 Binary files /dev/null and b/frontend/public/samples/solar-system-01-sun-and-formation.pdf differ diff --git a/frontend/public/samples/solar-system-02-inner-planets.pdf b/frontend/public/samples/solar-system-02-inner-planets.pdf new file mode 100644 index 0000000..3bac012 Binary files /dev/null and b/frontend/public/samples/solar-system-02-inner-planets.pdf differ diff --git a/frontend/public/samples/solar-system-03-giant-planets.pdf b/frontend/public/samples/solar-system-03-giant-planets.pdf new file mode 100644 index 0000000..c7858f1 Binary files /dev/null and b/frontend/public/samples/solar-system-03-giant-planets.pdf differ diff --git a/frontend/public/samples/solar-system-04-small-bodies.pdf b/frontend/public/samples/solar-system-04-small-bodies.pdf new file mode 100644 index 0000000..0a80200 Binary files /dev/null and b/frontend/public/samples/solar-system-04-small-bodies.pdf differ diff --git a/frontend/public/samples/solar-system-05-edges-and-exploration.pdf b/frontend/public/samples/solar-system-05-edges-and-exploration.pdf new file mode 100644 index 0000000..735c0ef Binary files /dev/null and b/frontend/public/samples/solar-system-05-edges-and-exploration.pdf differ diff --git a/frontend/scripts/build_samples.mjs b/frontend/scripts/build_samples.mjs new file mode 100644 index 0000000..d1eb856 --- /dev/null +++ b/frontend/scripts/build_samples.mjs @@ -0,0 +1,29 @@ +// Renders the onboarding sample papers (scripts/samples/*.html) to public/samples/*.pdf with headless Chromium. +// Set CHROME to the binary; defaults to Playwright's chrome-headless-shell, which prints CSS page margin boxes. +import { execFileSync } from "node:child_process"; +import { existsSync, readdirSync } from "node:fs"; +import { homedir } from "node:os"; +import { join, resolve } from "node:path"; + +const here = resolve(import.meta.dirname); +const out = resolve(here, "..", "public", "samples"); +const chrome = + process.env.CHROME ?? + join(homedir(), "Library/Caches/ms-playwright/chromium_headless_shell-1234/chrome-headless-shell-mac-arm64/chrome-headless-shell"); +if (!existsSync(chrome)) { + console.error(`Chrome not found at ${chrome}. Set CHROME to a headless Chromium binary.`); + process.exit(1); +} + +for (const file of readdirSync(join(here, "samples")).filter((f) => f.endsWith(".html")).sort()) { + const pdf = join(out, file.replace(/\.html$/, ".pdf")); + execFileSync(chrome, [ + "--headless", + "--no-sandbox", + "--disable-gpu", + "--no-pdf-header-footer", + `--print-to-pdf=${pdf}`, + `file://${join(here, "samples", file)}`, + ], { stdio: "ignore", timeout: 60_000 }); + console.log(`wrote ${pdf}`); +} diff --git a/frontend/scripts/samples/paper.css b/frontend/scripts/samples/paper.css new file mode 100644 index 0000000..28798ed --- /dev/null +++ b/frontend/scripts/samples/paper.css @@ -0,0 +1,33 @@ +@page { + size: A4; + margin: 24mm 22mm 22mm; + @bottom-center { + content: counter(page); + font-family: Georgia, "Times New Roman", serif; + font-size: 9pt; + color: #444; + } +} +html { font-family: Georgia, "Times New Roman", Times, serif; color: #111; } +body { margin: 0; font-size: 10.8pt; line-height: 1.55; } +header { text-align: center; margin: 0 auto 18pt; max-width: 150mm; } +header p { text-align: center; } +header .series { font-size: 9pt; letter-spacing: 0.08em; text-transform: uppercase; color: #444; margin: 0 0 10pt; } +header h1 { font-size: 19pt; line-height: 1.25; font-weight: normal; margin: 0 0 10pt; } +header .byline { font-size: 10pt; font-style: italic; margin: 0 0 3pt; } +header .date { font-size: 9.5pt; color: #444; margin: 0 0 16pt; } +.abstract { text-align: center; max-width: 130mm; margin: 0 auto 6pt; } +.abstract h2 { font-size: 10pt; letter-spacing: 0.1em; text-transform: uppercase; font-weight: bold; margin: 0 0 5pt; } +header .abstract p { font-size: 9.8pt; text-align: justify; text-align-last: center; margin: 0; } +header .keywords { text-align: center; font-size: 9pt; color: #333; margin: 8pt 0 0; } +hr { border: 0; border-top: 0.6pt solid #888; width: 40%; margin: 18pt auto; } +h2 { font-size: 12pt; margin: 16pt 0 5pt; text-align: center; font-weight: bold; } +h3 { font-size: 10.8pt; font-style: italic; font-weight: normal; margin: 10pt 0 3pt; } +p { text-align: justify; hyphens: auto; margin: 0 0 7pt; } +table { border-collapse: collapse; margin: 8pt auto 10pt; font-size: 9.5pt; } +caption { caption-side: top; font-size: 9pt; font-style: italic; margin-bottom: 4pt; } +th, td { border-top: 0.5pt solid #999; border-bottom: 0.5pt solid #999; padding: 3pt 9pt; text-align: center; } +th { font-weight: bold; } +.references h2 { margin-top: 20pt; } +.references ol { font-size: 9pt; padding-left: 16pt; margin: 0; } +.references li { margin-bottom: 4pt; text-align: left; } diff --git a/frontend/scripts/samples/solar-system-01-sun-and-formation.html b/frontend/scripts/samples/solar-system-01-sun-and-formation.html new file mode 100644 index 0000000..9cf9f66 --- /dev/null +++ b/frontend/scripts/samples/solar-system-01-sun-and-formation.html @@ -0,0 +1,69 @@ + + +
+ +Solar System Studies · No. 1
+November 2026
+The Solar System formed about 4.568 billion years ago from the gravitational collapse of a fragment of a molecular cloud. Nearly all of that material settled into the Sun, which today holds 99.86 percent of the system's mass, while the remainder flattened into a disc from which the planets grew. This review summarises the evidence for that origin, the physical character of the Sun as a main-sequence star, the dynamical events that rearranged the young planetary system, and the expected evolution of the Sun over the next several billion years.
+Keywords: nebular hypothesis, protoplanetary disc, main sequence, stellar evolution, planetary migration
+The Solar System is the gravitationally bound system of the Sun and the bodies that orbit it: eight planets, their natural satellites, dwarf planets, and a very large population of smaller objects. Understanding how it formed is central to planetary science, because the conditions of that first period fixed the composition, spacing and orbits that are observed today. This paper reviews the formation of the system and the life of its central star.
+ +The age of the Solar System is measured from the oldest solid materials known, calcium and aluminium rich inclusions found in primitive meteorites. Radiometric dating of these inclusions gives an age of 4,568.2 million years, with an uncertainty of a few hundred thousand years. Because these grains condensed directly from the hot gas surrounding the young Sun, their age is taken as the start of the system's history.
+ +The prevailing explanation, the nebular hypothesis, holds that a region of a giant molecular cloud, probably several light-years across, collapsed under its own gravity. As it contracted, conservation of angular momentum made it spin faster, and the collapsing material flattened into a rotating protoplanetary disc roughly 200 astronomical units (AU) in diameter, with a hot, dense protostar at its centre.
+Most of the mass fell inward to form the Sun. The rest remained in the disc, where dust grains collided and stuck together, building up planetesimals and eventually planets. Temperature controlled what could condense where. Close to the young Sun only rock and metal could stay solid, so the inner planets formed from a scarce supply of refractory material and remained small. In the first million years, heat from accretion also drove volatile hydrocarbons out of the inner disc, a boundary sometimes called the soot line, which has since moved inside the orbit of the Earth.
+ +The Sun is a G-type main-sequence star of spectral class G2V. It has a radius of about 700,000 kilometres, or 0.0047 AU, and is composed of roughly 98 percent hydrogen and helium by mass, the same proportions found in Jupiter and Saturn. Its mass, about 332,900 times that of the Earth, dominates the dynamics of every other body in the system.
+Hydrogen fusion in the solar core began within about 50 million years of the initial collapse. The young Sun was considerably fainter than it is today, shining at about 70 percent of its present brightness. Its luminosity has increased slowly ever since, a trend that continues as helium accumulates in the core.
+ +Energy released by fusion travels outward and leaves the Sun as light and as the solar wind, a continuous stream of charged particles. The solar wind inflates a vast bubble, the heliosphere, which surrounds the entire planetary system and marks the region in which the Sun's influence exceeds that of interstellar space.
+ +The planets did not necessarily form where they orbit today. Simulations known collectively as the Nice model propose that gravitational encounters between the giant planets and a disc of remaining planetesimals caused the giants to migrate, triggering a period of orbital instability that left them in their present positions. A related idea, the grand tack hypothesis, suggests that Jupiter first migrated inward and then reversed direction, scattering much of the material in what is now the asteroid belt. Such migrations may explain the Late Heavy Bombardment, an epoch of intense impacts recorded on the Moon and the inner planets.
+Over very long timescales the system is chaotic: small perturbations grow, and the precise positions of the planets cannot be predicted indefinitely. External influences also play a role. A star passes within about 0.8 light-years of the Sun roughly once every 100,000 years, disturbing the most distant objects that orbit it.
+ +| Stage | Approximate time |
|---|---|
| Collapse of the presolar nebula | 4.568 billion years ago |
| Onset of core hydrogen fusion | within 50 million years of collapse |
| End of core hydrogen supply | about 5 billion years from now |
| Total main-sequence lifetime | about 10 billion years |
The Sun is roughly halfway through a main-sequence lifetime of about ten billion years. In approximately five billion years the hydrogen in its core will be exhausted. The core will contract while the outer layers expand, and the Sun will become a red giant up to about 260 times its present diameter, with a cooler surface of around 2,600 kelvin. Mercury and Venus are expected to be engulfed and vaporised, and the Earth and Mars will become uninhabitable.
+After a relatively brief phase of helium burning, the Sun will shed its outer layers, possibly forming a planetary nebula. What remains will be a white dwarf: an exposed stellar core with about half of the Sun's original mass compressed into a body roughly the size of the Earth, which will cool and fade over an extremely long time.
+ +The Solar System began as a collapsing cloud of gas and dust, and the distribution of temperature in the resulting disc shaped the rocky inner planets and the massive outer ones. The Sun, which captured almost all of the original material, has brightened steadily since fusion began and will eventually swell, shed its envelope and end as a white dwarf. The dynamical upheavals of the early system, recorded in impact craters and in the orbits of small bodies, remain an active field of research.
+ +Solar System Studies · No. 2
+November 2026
+The four planets closest to the Sun are small, dense bodies of rock and metal. They formed inside the frost line, where only refractory material could condense, and as a result none of them grew large enough to hold a substantial envelope of hydrogen and helium. This review compares their orbits, surfaces and atmospheres, and considers why worlds built from similar ingredients evolved into an airless, cratered Mercury, a hot and pressurised Venus, a temperate and inhabited Earth, and a cold, thin-aired Mars.
+Keywords: terrestrial planets, frost line, planetary atmospheres, habitable zone, comparative planetology
+The inner Solar System contains four terrestrial planets: Mercury, Venus, Earth and Mars. They share a broadly similar structure, with a metallic core, a rocky mantle and a solid crust, yet their present conditions differ enormously. Comparing them is one of the most productive approaches in planetary science, because differences in size, distance from the Sun and atmospheric history can be tested against a common starting point.
+ +In the disc of gas and dust that surrounded the young Sun, temperature fell with distance. The frost line marks the boundary beyond which volatile compounds such as water, ammonia and methane could remain solid as ices. It lay at roughly 5 AU, about five times the distance of the Earth from the Sun. Inside it, only metals and silicates condensed, and these refractory materials made up only a small fraction of the nebula. The planets that formed there therefore stayed relatively small and could not capture large amounts of nebular gas, in contrast with the giant planets that grew beyond the line.
+ +| Planet | Orbital period (days) | Known moons |
|---|---|---|
| Mercury | 87.97 | 0 |
| Venus | 224.70 | 0 |
| Earth | 365.26 | 1 |
| Mars | 686.98 | 2 |
Mercury is the smallest planet and the closest to the Sun, following a markedly eccentric orbit that ranges from about 0.31 to 0.59 AU. It completes one orbit in just under 88 days. With almost no atmosphere to retain or distribute heat, its surface temperature swings from about minus 170 degrees Celsius at night to around 420 degrees Celsius in daylight. Its heavily cratered surface preserves a long record of impacts. Mercury has no moons and no rings.
+ +Venus is similar to the Earth in size, which once led to it being described as a sister planet. Its conditions, however, are extreme. A dense atmosphere composed mainly of carbon dioxide produces a surface pressure about 90 times that at sea level on Earth, and a powerful greenhouse effect keeps the surface above 400 degrees Celsius, hotter than Mercury despite being nearly twice as far from the Sun. Venus rotates in the opposite direction to most planets, a retrograde rotation whose origin is still debated. Like Mercury, it has no moons.
+ +The Earth orbits at an average distance of 1 AU and is the largest of the terrestrial planets. Its atmosphere is about 78 percent nitrogen and 21 percent oxygen, and liquid water covers most of its surface. It is the only body known to support life. The Earth has a single natural satellite, the Moon, whose diameter is about a quarter of the Earth's, an unusually large ratio for a planet and its moon.
+ +The habitable zone is the range of distances from a star at which a planet with a suitable atmosphere could keep liquid water on its surface. In the Solar System, the Earth and Mars are the only planets that orbit within it. Their differing fates show that position alone does not guarantee habitability: mass, atmospheric retention and geological activity matter as well.
+ +Mars orbits between about 1.38 and 1.67 AU and takes almost 687 days to circle the Sun. Its radius is roughly half that of the Earth. Its atmosphere is very thin, with a surface pressure about 0.6 percent of the Earth's, so liquid water cannot persist on the surface today, although landforms indicate that it once flowed. Mars has two small, irregular moons, Phobos, with a mean radius of about 11 kilometres, and Deimos, with a mean radius of about 6 kilometres.
+ +The contrasts among the terrestrial planets can be traced to a few factors. Mercury is small and close to the Sun, so it lost any early atmosphere. Venus retained a thick atmosphere that trapped heat in a runaway greenhouse. Mars, smaller than the Earth and with weaker gravity, lost much of its atmosphere and cooled. The Earth occupies a middle ground, large enough to retain an atmosphere and geologically active enough to recycle carbon over long periods, which has helped to stabilise its climate. None of the four planets has a ring system.
+ +The terrestrial planets formed from the same scarce, rocky material inside the frost line, yet diverged into very different worlds. Their study helps to explain the conditions that make a planet habitable, and provides a framework for interpreting the many rocky planets now being discovered around other stars.
+ +Solar System Studies · No. 3
+November 2026
+Beyond the frost line lie the four giant planets, Jupiter, Saturn, Uranus and Neptune, which together contain about 99 percent of the mass that orbits the Sun. Jupiter and Saturn are gas giants dominated by hydrogen and helium; Uranus and Neptune are ice giants richer in water, ammonia and methane. This review describes their composition and orbits, their ring systems and their extensive families of moons, and the evidence that their orbits changed early in the history of the Solar System.
+Keywords: gas giants, ice giants, planetary rings, natural satellites, planetary migration
+The outer planets are far larger than the terrestrial worlds and differ from them in almost every respect. They lack solid surfaces of the kind found on Earth, have deep atmospheres, and are surrounded by rings and by moons numbering in the dozens or hundreds. Their great mass also makes them the dominant gravitational influence on the smaller bodies of the Solar System.
+ +Outside the frost line, at roughly 5 AU from the Sun, volatile compounds could freeze into solid ice. Ices were far more abundant than rock and metal, so solid cores grew quickly to large masses. Once a core was massive enough, it could capture hydrogen and helium directly from the surrounding nebula, producing the enormous envelopes of gas that characterise the giant planets.
+ +The four giants fall into two groups. Jupiter and Saturn, the gas giants, are composed mainly of hydrogen and helium in proportions close to those of the Sun. Together they hold more than 90 percent of all the mass in the Solar System outside the Sun itself. Uranus and Neptune, the ice giants, are much smaller, with a combined mass of about 31 Earth masses, and contain a larger share of heavier compounds such as water, ammonia and methane.
+ +| Planet | Class | Distance from the Sun (AU) |
|---|---|---|
| Jupiter | Gas giant | 4.95 to 5.46 |
| Saturn | Gas giant | 9.08 to 10.12 |
| Uranus | Ice giant | 18.3 to 20.1 |
| Neptune | Ice giant | 29.9 to 30.5 |
Jupiter is the largest planet, with a radius of about 71,000 kilometres, and orbits at an average distance of 5.2 AU. Its mass is greater than that of all the other planets combined. It has well over a hundred confirmed moons, including the four large Galilean satellites discovered in the early seventeenth century. One of them, Ganymede, is the largest moon in the Solar System and is larger in diameter than the planet Mercury, although it is less massive.
+ +Saturn orbits between about 9.1 and 10.1 AU from the Sun. It possesses the most prominent ring system of any planet, the only one easily visible from the Earth through a small telescope. Saturn also has the largest number of confirmed moons. Its largest moon, Titan, is likewise larger than Mercury and is notable for its thick atmosphere.
+ +Uranus orbits between about 18.3 and 20.1 AU. Its most unusual feature is its axial tilt, which exceeds 90 degrees, so that the planet effectively rotates on its side relative to its orbit. This tilt produces extreme seasons in which each pole faces the Sun for decades at a time. Uranus has a faint ring system and more than two dozen known moons.
+ +Neptune is the outermost planet, orbiting at about 30 AU. It was identified in 1846 after irregularities in the orbit of Uranus pointed to the gravitational pull of an unseen planet. Its largest moon, Triton, orbits in the direction opposite to Neptune's rotation. Such a retrograde orbit suggests that Triton did not form around Neptune but was captured, possibly from the population of icy bodies beyond the planets.
+ +All four giant planets have ring systems, ranging from Saturn's broad, bright rings to the narrow, dark rings of Uranus and Neptune. Their orbits, meanwhile, may not be where they began. The Nice model proposes that interactions between the giant planets and a disc of leftover planetesimals caused them to migrate and passed through a phase of instability before settling into their current orbits. The grand tack hypothesis adds that Jupiter migrated inward and then back outward, reshaping the region that became the asteroid belt.
+ +The giant planets owe their size to the abundance of ice beyond the frost line, which allowed rapid growth and the capture of nebular gas. Their rings, their many moons and their likely history of migration make them central to understanding how the Solar System as a whole reached its present arrangement.
+ +Solar System Studies · No. 4
+November 2026
+Alongside the eight planets, the Solar System contains more than a million known minor planets, thousands of comets and an uncounted quantity of meteoroids and dust. These small bodies are concentrated in a few broad reservoirs: the asteroid belt between Mars and Jupiter, the Trojan populations that share planetary orbits, and the Kuiper belt and scattered disc beyond Neptune. This review describes each population, the dwarf planets found among them, and the comets and dust that move between them. Because many small bodies have changed little since they formed, they preserve evidence of the early Solar System.
+Keywords: asteroid belt, Kuiper belt, dwarf planets, comets, meteoroids, Trojans
+Small bodies are the leftovers of planet formation: planetesimals that never merged into planets, or fragments of larger objects broken apart by collisions. Their orbits and compositions record the conditions and events of the early Solar System, including the migration of the giant planets. They are also numerous. Catalogues list more than 1.5 million minor planets and several thousand comets, and new discoveries are made continually.
+ +The main asteroid belt occupies the region between about 2.3 and 3.3 AU from the Sun, between the orbits of Mars and Jupiter. It may contain millions of objects larger than one kilometre across, yet its total mass is unlikely to exceed one thousandth of the Earth's. The gravity of Jupiter is thought to have prevented the material here from assembling into a planet.
+The largest object in the belt is Ceres, about 940 kilometres across and the only dwarf planet in the region. The next largest are Vesta and Pallas. Together these few bodies account for a large fraction of the belt's total mass.
+ +Trojans are small bodies that share the orbit of a larger body, gathered around two stable points 60 degrees ahead of it and 60 degrees behind it, known as the L4 and L5 Lagrange points. Every planet except Mercury is known to have at least one Trojan companion. Jupiter's Trojans are especially numerous, with a population that may rival that of the main asteroid belt.
+ +Beyond Neptune, between about 30 and 50 AU, lies the Kuiper belt, a broad ring of icy bodies. It is estimated to contain more than 100,000 objects larger than 50 kilometres across, although its total mass is small, perhaps between one tenth and one hundredth of the Earth's. The population drops sharply beyond about 50 AU, a feature known as the Kuiper cliff.
+Overlapping the Kuiper belt and extending far beyond it is the scattered disc, whose members follow eccentric orbits that can reach several hundred AU. These orbits are thought to result from past gravitational encounters with Neptune, and the scattered disc is regarded as the main source of short-period comets.
+ +| Body | Location |
|---|---|
| Ceres | Asteroid belt |
| Pluto | Kuiper belt |
| Haumea | Kuiper belt |
| Makemake | Kuiper belt |
| Eris | Scattered disc |
A dwarf planet is a body massive enough to have pulled itself into a nearly round shape, but which has not cleared its orbital neighbourhood of other material. Five objects are formally recognised as dwarf planets: Ceres, Pluto, Haumea, Makemake and Eris. Several others, including Orcus, Quaoar, Gonggong and Sedna, are generally considered to qualify as well.
+Pluto, which orbits between about 29.7 and 49.3 AU, was regarded as the ninth planet until 2006, when a formal definition of a planet led to its reclassification. It has five known moons. Eris, on a more distant and eccentric orbit, is about a quarter more massive than Pluto. Sedna follows one of the most extreme orbits known, taking roughly 11,400 years to circle the Sun.
+ +Centaurs are icy bodies orbiting among the giant planets, with orbits between roughly 5.5 and 30 AU. They are thought to be objects in transition, scattered inward from the Kuiper belt. Comets are small bodies, typically a few kilometres across, made largely of volatile ices. When a comet approaches the Sun, these ices vaporise and form a glowing coma and tail. Short-period comets, with orbits of less than 200 years, are believed to come from the Kuiper belt and scattered disc; long-period comets, with orbits lasting thousands of years, from the much more distant Oort cloud.
+ +The smallest solid bodies are meteoroids, defined by the International Astronomical Union since 2017 as objects between about 30 micrometres and one metre across. Smaller particles are classed as dust. When a meteoroid enters the Earth's atmosphere it produces a streak of light called a meteor, and meteor showers occur when the Earth crosses streams of particles moving on parallel paths. A cloud of fine dust in the inner Solar System scatters sunlight to produce the faint zodiacal light, while a second dust cloud between about 10 and 40 AU is probably supplied by collisions in the Kuiper belt.
+ +The small bodies of the Solar System are diverse in size, composition and orbit, but together they form a record of how the planets assembled and moved. Continued surveys and spacecraft visits, including those that have returned samples from asteroids and comets, are steadily refining that record.
+ +Solar System Studies · No. 5
+November 2026
+Where the Solar System ends depends on the definition used. The solar wind carves out a bubble, the heliosphere, that extends past the orbits of the planets; the Sun's gravity holds a distant cloud of comets far beyond that; and the system as a whole moves through the Milky Way as one member of a vast galaxy. This review describes these outer boundaries, the Solar System's place in its galactic surroundings, and the scientific and spaceflight milestones through which this picture was assembled.
+Keywords: heliosphere, heliopause, Oort cloud, Hill sphere, Milky Way, space exploration
+For most of history the Solar System was understood as the Sun, the Moon and the visible planets. Today its boundaries are drawn in several ways: by the reach of the solar wind, by the extent of objects bound to the Sun by gravity, and by the transition to the interstellar medium. Each boundary lies at a very different distance, and each has been studied by different means, from theoretical models to direct measurements by spacecraft.
+ +The Sun continuously emits a stream of charged particles, the solar wind, which inflates a bubble in the surrounding interstellar medium called the heliosphere. Moving outward, the solar wind first slows abruptly at the termination shock, at about 80 to 100 AU in the direction of the Sun's motion and perhaps around 200 AU in the opposite direction. Beyond the shock the wind becomes compressed and turbulent, forming a region called the heliosheath.
+The outer boundary of the heliosphere is the heliopause, where the pressure of the solar wind is balanced by that of the interstellar medium. It is regarded as the beginning of interstellar space. Spacecraft have detected it at about 120 AU. The heliosphere is not symmetrical: its northern edge extends several AU farther than its southern edge, and a bow shock in the interstellar medium may lie at roughly 230 AU.
+ +| Boundary | Approximate distance |
|---|---|
| Orbit of Neptune | 30 AU |
| Termination shock | 80 to 100 AU |
| Heliopause | about 120 AU |
| Oort cloud | 2,000 to 200,000 AU |
| Proxima Centauri | 269,000 AU (4.25 light-years) |
Far beyond the heliopause lies the Oort cloud, a hypothesised spherical reservoir of icy bodies thought to extend from about 2,000 AU to as far as 200,000 AU, with most of its material between 3,000 and 100,000 AU. It has never been observed directly. Its existence is inferred from long-period comets, which arrive from all directions on orbits that take them thousands of years to complete. The Oort cloud is so distant that passing stars and the tide of the galaxy can disturb its members and send some of them inward. The Voyager 1 spacecraft, currently the most distant human-made object, is not expected to reach the inner Oort cloud for about 300 years.
+ +Another way to define the edge of the Solar System is by gravity. The Hill sphere of the Sun is the region within which its gravity dominates over that of the galaxy as a whole, extending to roughly 230,000 AU, or more than three light-years. The nearest star, Proxima Centauri, lies only slightly farther away, at about 4.25 light-years, and is known to host at least one planet.
+ +The Solar System is located in the Milky Way, a barred spiral galaxy about 100,000 light-years across containing more than 100 billion stars. The Sun lies in the Orion arm, also called the Local Spur, at a distance of about 26,000 light-years from the galactic centre. It moves at roughly 220 kilometres per second and completes one orbit of the galaxy in about 230 to 240 million years. The plane of the planets is inclined by about 60 degrees to the plane of the galaxy.
+ +Modern understanding of the Solar System began with the heliocentric model of Nicolaus Copernicus, which placed the Sun at the centre. Johannes Kepler refined it by showing that planetary orbits are ellipses. In the seventeenth century Galileo Galilei and Simon Marius observed the four largest moons of Jupiter, and Christiaan Huygens discovered Titan and correctly described the shape of Saturn's rings. In 1705 Edmond Halley recognised that a bright comet returned every 75 to 76 years. Friedrich Bessel measured the parallax of a star in 1838, confirming the immense distances between stars, and in 1846 Neptune was located from its effect on the orbit of Uranus.
+ +From the 1960s, telescopes in space and robotic probes transformed the field. By 1989 spacecraft had visited all eight planets. The Apollo missions landed astronauts on the Moon, and later missions returned samples from comets and asteroids and visited the dwarf planets Pluto and Ceres. Missions such as the Voyager probes used gravity assists from the giant planets to reach the outer Solar System, and the two Voyagers have since crossed the heliopause. In 2006 a formal definition of the term planet led to the reclassification of Pluto as a dwarf planet.
+ +The Solar System has no single edge. The solar wind gives way to interstellar space at around 120 AU, the comets of the Oort cloud may extend more than a thousand times farther, and the Sun's gravity competes with that of its neighbours at distances of light-years. Centuries of observation and decades of spaceflight have made it possible to describe these boundaries, while many questions, particularly about the Oort cloud, remain open.
+ +