diff --git a/CHANGELOG.md b/CHANGELOG.md
index c888c02..b364089 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,13 @@
# Changelog
+## Unreleased
+
+### Fixed
+
+- Without the agent's console, the console says why for each case (one
+ running without `--serve` too), as a 503 with `Retry-After`. Its page
+ reloads itself.
+
## 0.16.0 (2026-11-10)
Needs `tracepanel-agent` 0.16.0 (installed with it).
diff --git a/src/tracepanel/asgi/middleware.py b/src/tracepanel/asgi/middleware.py
index a6b7f74..547424e 100644
--- a/src/tracepanel/asgi/middleware.py
+++ b/src/tracepanel/asgi/middleware.py
@@ -236,6 +236,7 @@ async def _console(self, scope: Scope, receive: Receive, send: Send, path: str)
content_type=headers.get(b"content-type", b"").decode("latin-1"),
local=is_local(str(client[0])),
too_large=too_large,
+ accept=headers.get(b"accept", b"").decode("latin-1"),
)
# The console reads SQLite (and may wait for the writer): off the event loop.
response = await asyncio.to_thread(console.dispatch, request)
diff --git a/src/tracepanel/console/app.py b/src/tracepanel/console/app.py
index 232dc0f..4d5ec46 100644
--- a/src/tracepanel/console/app.py
+++ b/src/tracepanel/console/app.py
@@ -46,7 +46,7 @@ def handle(request: Request) -> Response:
document = proxy.trace(trace_id) if trace_id else None
if _service(document) not in {"", conf.get_config().service}:
forwarded = proxy.forward(request, request.path, timeout=proxy.EXPLAIN_TIMEOUT_S)
- return forwarded or _no_agent(api=True)
+ return forwarded or _no_console(request)
span = _span(document, request.query.get("span", ""))
attrs = span.get("attrs") if span else None
if span is None or span.get("kind") != "sql" or not isinstance(attrs, dict):
@@ -136,7 +136,7 @@ def dispatch(request: Request) -> Response:
connected = getattr(transport.get_writer(), "connected", None)
if callable(connected):
connected()
- return proxy.forward(request, request.path) or _no_agent(api=path is not None)
+ return proxy.forward(request, request.path) or _no_console(request)
def _refused_write(request: Request) -> Response | None:
@@ -148,14 +148,52 @@ def _refused_write(request: Request) -> Response | None:
return None
-def _no_agent(*, api: bool) -> Response:
- """The console without an agent: why, and what to do."""
- reason = agent.unavailable(conf.get_config())
- if api:
- return json_response({"error": f"No tracepanel agent: {reason}"}, status=SERVICE_UNAVAILABLE)
- page = (
- "
tracepanel"
- ""
- f"tracepanel
The console comes from the tracepanel agent, and {html.escape(reason)}
"
- )
- return Response(status=SERVICE_UNAVAILABLE, content_type="text/html; charset=utf-8", body=page.encode())
+# While the console doesn't answer: the browser asks again this often, and the page reloads itself as often.
+RETRY_S = 2
+
+
+def _no_console(request: Request) -> Response:
+ """No console: 503 with why and what to do.
+
+ A browser's page (it accepts HTML) gets a small page that reloads itself until the console answers; the console's
+ API calls and its files get `{"error": ...}`.
+ """
+ why = agent.no_console(conf.get_config())
+ headers = {"Retry-After": str(RETRY_S), "Cache-Control": "no-store"}
+ if "text/html" in request.accept:
+ body = page(why).encode()
+ return Response(status=SERVICE_UNAVAILABLE, content_type="text/html; charset=utf-8", body=body, headers=headers)
+ body = json.dumps({"error": why.detail}, separators=(",", ":")).encode()
+ return Response(status=SERVICE_UNAVAILABLE, body=body, headers=headers)
+
+
+def page(why: agent.NoConsole) -> str:
+ """The page in the console's look (its dark tokens), with nothing to load: the console is the thing missing."""
+ title, detail = (html.escape(text, quote=True) for text in why)
+ return f"""
+
+
+
+
+
+Tracepanel: {title}
+
+
+
+
+{title}
+{detail}
+This page reloads itself every {RETRY_S} seconds and shows the console once it answers.
+
+
+
+"""
diff --git a/src/tracepanel/console/messages.py b/src/tracepanel/console/messages.py
index c4d13f4..75c6240 100644
--- a/src/tracepanel/console/messages.py
+++ b/src/tracepanel/console/messages.py
@@ -29,6 +29,8 @@ class Request:
local: bool = False
# Its body was over MAX_BODY: not read, answered 413.
too_large: bool = False
+ # Its Accept header: a browser's page (text/html) gets a page that says why when there is no console.
+ accept: str = ""
@dataclass(slots=True)
diff --git a/src/tracepanel/django/console.py b/src/tracepanel/django/console.py
index 4802347..e334da8 100644
--- a/src/tracepanel/django/console.py
+++ b/src/tracepanel/django/console.py
@@ -50,6 +50,7 @@ def dispatch(request: HttpRequest, path: str) -> HttpResponseBase:
content_type=request.content_type or "" if body else "",
local=from_this_machine(request),
too_large=too_large,
+ accept=request.headers.get("Accept", ""),
)
)
if isinstance(response.native, HttpResponseBase):
diff --git a/src/tracepanel/storage/agent.py b/src/tracepanel/storage/agent.py
index 818e134..0fcc12b 100644
--- a/src/tracepanel/storage/agent.py
+++ b/src/tracepanel/storage/agent.py
@@ -34,7 +34,7 @@
import time
from collections.abc import Callable, Iterator
from pathlib import Path
-from typing import BinaryIO
+from typing import BinaryIO, NamedTuple
if sys.platform == "win32":
import msvcrt
@@ -221,6 +221,55 @@ def unavailable(config: conf.Config) -> str:
return f"the agent isn't running (see {store_dir(config) / LOG_FILE}): traces aren't kept until it is."
+class NoConsole(NamedTuple):
+ """Why the console doesn't answer, and what to do: the console's 503 (console.app), in the other SDKs' words."""
+
+ title: str
+ detail: str
+
+
+def no_console(config: conf.Config) -> NoConsole:
+ """What keeps the project's console from answering, as far as this process can tell."""
+ if config.agent == "off":
+ return NoConsole(
+ "Tracepanel's agent is off",
+ "Tracepanel's agent is off (the agent setting, TRACEPANEL_AGENT=off): traces aren't kept and there is no "
+ "console. Set it to auto to have the app start it.",
+ )
+ if config.agent != "auto":
+ return NoConsole(
+ "The console doesn't answer",
+ f"No console answers at {config.console_url} (the console_url setting) for the agent at {config.agent}. "
+ "Start that agent with --serve, or correct the address.",
+ )
+ directory = store_dir(config)
+ if answers(address(config)):
+ # The agent writes its console's address before its own: one that answers without a console was started so.
+ return NoConsole(
+ "Tracepanel's agent runs without its console",
+ "The project's agent runs without its console (it was started without --serve). Stop it: the next "
+ f"request starts one with its console. Store: {directory}.",
+ )
+ explicit = os.environ.get("TRACEPANEL_AGENT_BIN")
+ if explicit and not Path(explicit).is_file():
+ return NoConsole(
+ "No tracepanel-agent to start",
+ f"TRACEPANEL_AGENT_BIN names {explicit}, which isn't there. Set it to the tracepanel-agent binary's path.",
+ )
+ if binary() is None:
+ return NoConsole(
+ "No tracepanel-agent to start",
+ f"No tracepanel-agent binary to start for this platform ({sys.platform}, {platform.machine()}): set "
+ "TRACEPANEL_AGENT_BIN to the agent's path, or use an agent on another machine: "
+ "TRACEPANEL_AGENT=tcp:HOST:PORT.",
+ )
+ return NoConsole(
+ "Tracepanel's agent didn't start",
+ f"Tracepanel's agent didn't start: {directory / LOG_FILE} says why. It is tried again within "
+ f"{RESTART_S:.0f} seconds.",
+ )
+
+
_start_lock = forks.lock()
_start_after = 0.0
diff --git a/src/tracepanel/wsgi/__init__.py b/src/tracepanel/wsgi/__init__.py
index 317618f..a5e2c9c 100644
--- a/src/tracepanel/wsgi/__init__.py
+++ b/src/tracepanel/wsgi/__init__.py
@@ -299,6 +299,7 @@ def _console(environ: dict[str, Any], path: str, start_response: StartResponse)
content_type=str(environ.get("CONTENT_TYPE", "")) if readable else "",
local=is_local(str(environ.get("REMOTE_ADDR", ""))),
too_large=too_large,
+ accept=str(environ.get("HTTP_ACCEPT", "")),
)
response = console.dispatch(request)
status = f"{response.status} {http.HTTPStatus(response.status).phrase}"
diff --git a/tests/console/test_no_console.py b/tests/console/test_no_console.py
new file mode 100644
index 0000000..d574d12
--- /dev/null
+++ b/tests/console/test_no_console.py
@@ -0,0 +1,129 @@
+"""No console answers: 503, why and what to do; a browser's page gets a page that reloads itself until it does."""
+
+import json
+import re
+import socket
+from collections.abc import Iterator
+from pathlib import Path
+
+import pytest
+
+from tracepanel.console import app
+from tracepanel.console.messages import Request
+from tracepanel.core import conf
+from tracepanel.storage import agent
+
+HTML = "text/html,application/xhtml+xml"
+RETRY = {"Retry-After": "2", "Cache-Control": "no-store"}
+
+
+@pytest.fixture
+def store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """The project's store, no agent of its own; the tests never start one (under pytest the SDK doesn't)."""
+ directory = tmp_path / ".tracepanel"
+ directory.mkdir()
+ monkeypatch.setenv("TRACEPANEL_DIR", str(directory))
+ monkeypatch.setenv("TRACEPANEL_AGENT", "auto")
+ monkeypatch.setenv("TRACEPANEL_AGENT_BIN", str(tmp_path / "no-such-agent"))
+ conf.reset()
+ return directory
+
+
+@pytest.fixture
+def without_console(store: Path) -> Iterator[Path]:
+ """An agent that takes traces and serves no console (started without --serve): its address in the store."""
+ with socket.create_server(("127.0.0.1", 0)) as listening:
+ (store / "agent.addr").write_text(f"tcp:127.0.0.1:{listening.getsockname()[1]}\n")
+ yield store
+
+
+def answered(accept: str = "") -> dict[str, object]:
+ response = app.dispatch(Request(method="GET", path="api/counts" if not accept else "", accept=accept))
+ return {
+ "status": response.status,
+ "type": response.content_type,
+ "headers": response.headers,
+ "body": response.body.decode(),
+ }
+
+
+def error(message: str) -> dict[str, object]:
+ return {
+ "status": 503,
+ "type": "application/json",
+ "headers": RETRY,
+ "body": json.dumps({"error": message}, separators=(",", ":")),
+ }
+
+
+def runs_without_console(store: Path) -> str:
+ return (
+ "The project's agent runs without its console (it was started without --serve). Stop it: the next request "
+ f"starts one with its console. Store: {store}."
+ )
+
+
+def test_an_agent_without_its_console_gets_a_page_that_says_to_stop_it_and_reloads(without_console: Path) -> None:
+ page = answered(HTML)
+ body = str(page["body"])
+
+ assert page == {"status": 503, "type": "text/html; charset=utf-8", "headers": RETRY, "body": body}
+
+ assert '' in body
+ assert "Tracepanel's agent runs without its console
" in body
+ detail = runs_without_console(without_console).replace("'", "'")
+ assert f"{detail}
" in body
+
+
+def test_an_agent_without_its_console_its_console_address_left_over(without_console: Path) -> None:
+ (without_console / "console.addr").write_text("http://127.0.0.1:9/\n")
+
+ assert answered() == error(runs_without_console(without_console))
+
+
+def test_the_agent_off_says_so(store: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("TRACEPANEL_AGENT", "off")
+ conf.reset()
+
+ assert answered() == error(
+ "Tracepanel's agent is off (the agent setting, TRACEPANEL_AGENT=off): traces aren't kept and there is no "
+ "console. Set it to auto to have the app start it."
+ )
+
+
+def test_a_named_agent_without_a_console_says_where_it_looked(store: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("TRACEPANEL_AGENT", "tcp:127.0.0.1:9")
+ monkeypatch.setenv("TRACEPANEL_CONSOLE_URL", "http://127.0.0.1:9/")
+ conf.reset()
+
+ assert answered() == error(
+ "No console answers at http://127.0.0.1:9/ (the console_url setting) for the agent at tcp:127.0.0.1:9. "
+ "Start that agent with --serve, or correct the address."
+ )
+
+
+def test_no_binary_to_start_says_how_to_get_one(store: Path) -> None:
+ missing = store.parent / "no-such-agent"
+
+ assert answered() == error(
+ f"TRACEPANEL_AGENT_BIN names {missing}, which isn't there. Set it to the tracepanel-agent binary's path."
+ )
+
+
+def test_an_agent_that_does_not_start_points_to_its_log(store: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ binary = store.parent / "tracepanel-agent"
+ binary.write_text("#!/bin/sh\nexit 1\n")
+ monkeypatch.setenv("TRACEPANEL_AGENT_BIN", str(binary))
+
+ assert answered() == error(
+ f"Tracepanel's agent didn't start: {store / 'agent.log'} says why. It is tried again within 30 seconds."
+ )
+
+
+def test_the_page_needs_nothing_from_elsewhere_and_what_it_says_makes_no_markup() -> None:
+ page = app.page(agent.NoConsole("A title", "Store: /tmp/\"x\" & 'y'."))
+
+ assert "Tracepanel: A <b>title</b>" in page
+ assert "Store: /tmp/"x" & 'y'.
" in page
+
+ assert re.search(r"<(script|link|img)\b|https?:", page) is None
diff --git a/tests/django/test_widget.py b/tests/django/test_widget.py
index 7a7c151..25db216 100644
--- a/tests/django/test_widget.py
+++ b/tests/django/test_widget.py
@@ -58,13 +58,13 @@ def test_widget_can_be_disabled(client: Client, traces: list[Trace], db: None, s
def test_without_an_agent_no_script_and_the_console_says_why(client: Client, traces: list[Trace], db: None) -> None:
# The panel is the agent's: without one (the tests turn it off) the page gets the headers, not the script.
body = client.get("/html/").content.decode()
- console = client.get("/__tracepanel__/")
+ console = client.get("/__tracepanel__/", headers={"Accept": "text/html"})
api = client.get("/__tracepanel__/api/counts")
assert "