gabriel / musehub public
test_mists_wave_fixes.py python
551 lines 26.4 KB Hotspot
Raw
sha256:3cdbbfe4d7fbc1558b9d36cfbc1902be7d9f749dd76374719511a42dd35e9f1a fix(mists): a Mist's content is immutable — PATCH and MCP r… Opus 5.5 minor ⚠ breaking 1 day ago
1 """Regression tests for the Mists wave (musehub#316–#323, #277).
2
3 DB-free: the service layer is patched or driven with a fake session, and the app is exercised in-process. The
4 docs-contract pins for the same tickets live in ``tests/docs_contract/test_mists.py``.
5 """
6
7 from __future__ import annotations
8
9 from collections.abc import Iterator
10 from datetime import datetime, timezone
11 from typing import Any
12 from unittest.mock import AsyncMock, patch
13
14 import pytest
15 from fastapi.routing import iter_route_contexts
16 from fastapi.testclient import TestClient
17 from starlette.routing import compile_path
18
19 from musehub.api.routes.musehub import ui_mists, ui_repo
20 from musehub.db import get_db
21 from musehub.main import app
22 from musehub.models.mists import MistListEntry, MistListResponse
23 from musehub.services import musehub_mists
24
25 pytestmark = pytest.mark.no_db
26
27 _NOW = datetime(2026, 11, 14, 12, 0, tzinfo=timezone.utc)
28
29
30 def _first_endpoint(method: str, path: str) -> Any:
31 """The endpoint of the first route, in declaration order, that matches ``method path``: the one a request reaches."""
32 for ctx in iter_route_contexts(app.routes):
33 if ctx.path is None or (ctx.methods is not None and method not in ctx.methods):
34 continue
35 regex, _, _ = compile_path(ctx.path)
36 if regex.match(path):
37 return ctx.endpoint
38 return None
39
40
41 class _Db:
42 async def commit(self) -> None: ...
43 async def rollback(self) -> None: ...
44
45
46 @pytest.fixture
47 def fake_db() -> Iterator[None]:
48 async def _db() -> Any:
49 yield _Db()
50
51 app.dependency_overrides[get_db] = _db
52 try:
53 yield
54 finally:
55 app.dependency_overrides.pop(get_db, None)
56
57
58 def _entry(mist_id: str = "aB3xKq9dPwNm", artifact_type: str = "code", **kw: Any) -> MistListEntry:
59 fields: dict[str, Any] = {
60 "mist_id": mist_id, "url": "", "owner": "alice", "artifact_type": artifact_type, "language": "python",
61 "filename": "a.py", "title": "A title", "size_bytes": 3, "version": 1, "signed": False, "agent_id": "",
62 "model_id": "", "fork_parent_id": None, "fork_depth": 0, "fork_count": 0, "view_count": 0,
63 "visibility": "public", "tags": [], "primary_symbol": "a.py::f", "created_at": _NOW, "updated_at": _NOW,
64 }
65 fields.update(kw)
66 return MistListEntry(**fields)
67
68
69 # ── musehub#317: the web list pages ─────────────────────────────────────────
70
71
72 class TestListPagesAreReachable:
73 def test_explore_and_owner_list_reach_the_mist_pages(self) -> None:
74 assert _first_endpoint("GET", "/mists/explore") is ui_mists.mist_explore_page
75 assert _first_endpoint("GET", "/alice/mists") is ui_mists.mist_list_page
76
77 def test_repo_pages_named_like_mist_segments_still_resolve(self) -> None:
78 """A repo named ``explore``, ``raw`` or ``embed`` is still a repo page, and a repo named ``mists`` keeps its
79 sub-pages: only the exact two list paths are taken."""
80 for path in ("/alice/explore", "/alice/raw", "/alice/embed", "/mists/other"):
81 assert _first_endpoint("GET", path) is ui_repo.repo_page, path
82 sub = _first_endpoint("GET", "/alice/mists/issues")
83 assert sub is not None and sub.__module__.endswith(".ui_issues"), sub
84
85 def test_mist_detail_raw_and_embed_still_resolve(self) -> None:
86 assert _first_endpoint("GET", "/alice/mists/aB3xKq9dPwNm") is ui_mists.mist_detail_page
87 assert _first_endpoint("GET", "/alice/mists/aB3xKq9dPwNm/raw") is ui_mists.mist_raw
88 assert _first_endpoint("GET", "/alice/mists/aB3xKq9dPwNm/embed") is ui_mists.mist_embed_page
89
90 @pytest.mark.parametrize("path", ["/mists/explore", "/alice/mists"])
91 def test_list_pages_render_html(self, fake_db: None, path: str) -> None:
92 page = MistListResponse(total=3, next_cursor="2026-11-14T12:00:00+00:00", mists=[_entry(), _entry("bB3xKq9dPwNm", "data")])
93 with patch.object(musehub_mists, "list_mists", new=AsyncMock(return_value=page)) as listed:
94 resp = TestClient(app).get(path, params={"artifact_type": "code"})
95 assert resp.status_code == 200, resp.text[:500]
96 assert resp.headers["content-type"].startswith("text/html")
97 body = resp.text
98 assert "/alice/mists/aB3xKq9dPwNm" in body and "a.py::f" in body
99 # the cursor link is percent-encoded and keeps the owner path (the list page used to print "/{{ owner }}")
100 assert "cursor=2026-11-14T12%3A00%3A00%2B00%3A00" in body
101 assert "{{" not in body
102 if path == "/alice/mists":
103 assert 'href="/alice/mists?cursor=' in body
104 assert listed.await_args.kwargs["include_secret"] is False and listed.await_args.kwargs["owner"] == "alice"
105 else:
106 assert listed.await_args.kwargs["owner"] is None and listed.await_args.kwargs["include_secret"] is False
107
108 def test_filter_chips_are_the_detected_types(self, fake_db: None) -> None:
109 from muse.plugins.mist import plugin as mist_plugin
110
111 detected = {t for t, _ in mist_plugin._EXT_MAP.values()} | {"abi", "json_schema", "unknown"} # noqa: SLF001
112 assert set(ui_mists._TYPE_COLORS) == detected # noqa: SLF001
113 page = MistListResponse(total=0, next_cursor=None, mists=[])
114 with patch.object(musehub_mists, "list_mists", new=AsyncMock(return_value=page)):
115 body = TestClient(app).get("/mists/explore").text
116 for t in detected - {"unknown"}:
117 assert f"artifact_type={t}" in body, t
118 for retired in ("schema\"", "dataset", "config"):
119 assert f"artifact_type={retired}" not in body
120
121 def test_no_mist_html_under_api(self) -> None:
122 assert _first_endpoint("GET", "/api/alice/mists/aB3xKq9dPwNm") is not ui_mists.mist_detail_page
123 paths = [c.path for c in iter_route_contexts(app.routes) if c.endpoint in {
124 ui_mists.mist_explore_page, ui_mists.mist_list_page, ui_mists.mist_detail_page, ui_mists.mist_raw, ui_mists.mist_embed_page}]
125 assert all(not p.startswith("/api") for p in paths), paths
126
127
128 # ── musehub#316: delete removes the backing repo, and only that repo ────────
129
130
131 class _DeleteSession:
132 """Fake AsyncSession for ``delete_mist``: records deletes; ``others`` is what the 'still referenced' query sees."""
133
134 def __init__(self, row: Any, repo: Any, others: str | None = None) -> None:
135 self.row, self.repo, self.others = row, repo, others
136 self.deleted: list[Any] = []
137
138 async def get(self, model: Any, key: Any) -> Any:
139 from musehub.db.musehub_repo_models import MusehubMist, MusehubRepo
140
141 return self.row if model is MusehubMist else self.repo if model is MusehubRepo else None
142
143 async def delete(self, obj: Any) -> None:
144 self.deleted.append(obj)
145
146 async def execute(self, stmt: Any) -> Any:
147 from types import SimpleNamespace
148
149 return SimpleNamespace(scalar_one_or_none=lambda: self.others)
150
151 async def flush(self) -> None: ...
152
153
154 class TestDeleteRemovesTheBackingRepo:
155 @staticmethod
156 def _row() -> Any:
157 from types import SimpleNamespace
158
159 return SimpleNamespace(owner="alice", repo_id="repo-1", mist_id="m1")
160
161 async def test_the_mist_repo_is_deleted_after_the_row(self) -> None:
162 from types import SimpleNamespace
163
164 row, repo = self._row(), SimpleNamespace(repo_id="repo-1", domain_id="mist", owner="alice")
165 session = _DeleteSession(row, repo)
166 assert await musehub_mists.delete_mist(session, "m1", "alice") is True # type: ignore[arg-type]
167 assert session.deleted == [row, repo]
168
169 @pytest.mark.parametrize(("domain_id", "others"), [("code", None), ("mist", "otherMist123")])
170 async def test_a_repo_that_is_not_the_mists_own_is_kept(self, domain_id: str, others: str | None) -> None:
171 from types import SimpleNamespace
172
173 row, repo = self._row(), SimpleNamespace(repo_id="repo-1", domain_id=domain_id, owner="alice")
174 session = _DeleteSession(row, repo, others)
175 assert await musehub_mists.delete_mist(session, "m1", "alice") is True # type: ignore[arg-type]
176 assert session.deleted == [row]
177
178 async def test_a_non_owner_deletes_nothing(self) -> None:
179 from types import SimpleNamespace
180
181 session = _DeleteSession(self._row(), SimpleNamespace(repo_id="repo-1", domain_id="mist", owner="alice"))
182 assert await musehub_mists.delete_mist(session, "m1", "bob") is False # type: ignore[arg-type]
183 assert session.deleted == []
184
185
186 # ── musehub#318: the embed card, and only the embed card, can be framed ─────
187
188
189 def _mist(visibility: str = "public", **kw: Any) -> Any:
190 from types import SimpleNamespace
191
192 fields: dict[str, Any] = {
193 "artifact_type": "code", "language": "python", "filename": "a.py", "size_bytes": 3, "version": 1, "title": "",
194 "description": "", "content": "x=1", "mist_id": "m1", "owner": "alice", "visibility": visibility,
195 "fork_count": 0, "agent_id": "", "symbol_anchors": [],
196 }
197 fields.update(kw)
198 return SimpleNamespace(model_dump=lambda mode="json": dict(fields), **fields)
199
200
201 @pytest.fixture
202 def mist_client(fake_db: None) -> Iterator[Any]:
203 """A TestClient whose mist reads return the mist ``set_mist`` is given."""
204 holder: dict[str, Any] = {"mist": _mist()}
205
206 async def _get(*a: Any, **k: Any) -> Any:
207 return holder["mist"]
208
209 with (
210 patch.object(musehub_mists, "get_mist", new=_get),
211 patch.object(musehub_mists, "increment_mist_embed", new=AsyncMock(return_value=None)),
212 patch.object(musehub_mists, "increment_mist_view", new=AsyncMock(return_value=None)),
213 patch.object(musehub_mists, "get_mist_forks", new=AsyncMock(return_value=[])),
214 ):
215 client = TestClient(app)
216 client.set_mist = lambda m: holder.__setitem__("mist", m) # type: ignore[attr-defined]
217 yield client
218
219
220 def _directive(csp: str, name: str) -> str:
221 return next((d.strip() for d in csp.split(";") if d.strip().startswith(name + " ")), "")
222
223
224 class TestEmbedFraming:
225 def test_public_embed_is_frameable_and_may_load_prism(self, mist_client: Any) -> None:
226 resp = mist_client.get("/alice/mists/m1/embed")
227 assert resp.status_code == 200
228 csp = resp.headers["content-security-policy"]
229 assert _directive(csp, "frame-ancestors") == "frame-ancestors *"
230 assert "x-frame-options" not in resp.headers
231 script_src = _directive(csp, "script-src")
232 assert "https://cdnjs.cloudflare.com" in script_src and "'unsafe-inline'" not in script_src
233 assert "https://cdnjs.cloudflare.com" in _directive(csp, "style-src")
234 # the card's own Prism tags are on the allowed origin
235 assert 'src="https://cdnjs.cloudflare.com/ajax/libs/prism/' in resp.text
236
237 @pytest.mark.parametrize("path", ["/alice/mists/m1", "/alice/mists/m1/raw", "/mists/explore", "/muse/mists"])
238 def test_every_other_page_stays_unframeable(self, mist_client: Any, path: str) -> None:
239 page = MistListResponse(total=0, next_cursor=None, mists=[])
240 with patch.object(musehub_mists, "list_mists", new=AsyncMock(return_value=page)):
241 resp = mist_client.get(path)
242 assert resp.status_code == 200, (path, resp.status_code)
243 assert resp.headers["x-frame-options"] == "DENY"
244 assert _directive(resp.headers["content-security-policy"], "frame-ancestors") == "frame-ancestors 'none'"
245 assert "cdnjs" not in _directive(resp.headers["content-security-policy"], "script-src")
246
247 def test_a_secret_mists_embed_is_a_404_that_cannot_be_framed(self, mist_client: Any) -> None:
248 mist_client.set_mist(_mist(visibility="secret"))
249 resp = mist_client.get("/alice/mists/m1/embed")
250 assert resp.status_code == 404
251 assert resp.headers["x-frame-options"] == "DENY"
252 assert "frame-ancestors 'none'" in resp.headers["content-security-policy"]
253
254 def test_the_flag_does_not_leak_into_the_next_request(self, mist_client: Any) -> None:
255 assert mist_client.get("/alice/mists/m1/embed").status_code == 200
256 assert mist_client.get("/alice/mists/m1").headers["x-frame-options"] == "DENY"
257
258
259 # ── musehub#322: one limit maximum, invalid cursors are 422 ─────────────────
260
261
262 class TestListContract:
263 @pytest.mark.parametrize("path", ["/api/mists/explore", "/api/alice/mists", "/mists/explore", "/alice/mists"])
264 def test_an_invalid_cursor_is_a_422(self, fake_db: None, path: str) -> None:
265 with patch.object(musehub_mists, "list_mists", new=AsyncMock(side_effect=musehub_mists.InvalidMistCursor("garbage"))):
266 resp = TestClient(app).get(path, params={"cursor": "garbage"})
267 assert resp.status_code == 422, (path, resp.status_code, resp.text[:200])
268 assert "nextCursor" in resp.text
269
270 @pytest.mark.parametrize("path", ["/api/mists/explore", "/api/alice/mists", "/mists/explore", "/alice/mists"])
271 def test_limit_101_is_refused_everywhere(self, fake_db: None, path: str) -> None:
272 page = MistListResponse(total=0, next_cursor=None, mists=[])
273 with patch.object(musehub_mists, "list_mists", new=AsyncMock(return_value=page)) as listed:
274 client = TestClient(app)
275 assert client.get(path, params={"limit": 101}).status_code == 422, path
276 assert client.get(path, params={"limit": 100}).status_code == 200, path
277 assert listed.await_args.kwargs["limit"] == 100
278
279 async def test_the_service_rejects_a_mangled_cursor_before_querying_rows(self) -> None:
280 """The un-percent-encoded nextCursor ('+00:00' decoded to ' 00:00') is refused, not treated as page 1."""
281 from types import SimpleNamespace
282
283 class _S:
284 async def execute(self, stmt: Any) -> Any:
285 return SimpleNamespace(scalar_one=lambda: 0)
286
287 for bad in ("garbage", "2026-11-14T12:00:00 00:00", "2026-11-14T12:00:00"):
288 with pytest.raises(musehub_mists.InvalidMistCursor):
289 await musehub_mists.list_mists(_S(), None, cursor=bad) # type: ignore[arg-type]
290
291 async def test_mcp_list_clamps_to_100_and_rejects_a_bad_cursor(self) -> None:
292 from musehub.services import musehub_mcp_executor as exe
293
294 page = MistListResponse(total=0, next_cursor=None, mists=[])
295
296 class _Ctx:
297 async def __aenter__(self) -> Any:
298 return object()
299
300 async def __aexit__(self, *a: Any) -> None: ...
301
302 with (
303 patch.object(exe, "_check_db_available", return_value=None),
304 patch.object(exe, "AsyncSessionLocal", new=lambda: _Ctx()),
305 patch.object(musehub_mists, "list_mists", new=AsyncMock(return_value=page)) as listed,
306 ):
307 assert (await exe.execute_list_mists(limit=500)).ok is True
308 assert listed.await_args.kwargs["limit"] == 100
309 assert listed.await_args.kwargs["base_url"] == musehub_mists.public_base_url() != ""
310 listed.side_effect = musehub_mists.InvalidMistCursor("garbage")
311 bad = await exe.execute_list_mists(cursor="garbage")
312 assert bad.ok is False and bad.error_code == "invalid_args"
313
314
315 # ── musehub#320: a content edit re-derives the type fields; raw revalidates ─
316
317
318 class _UpdateSession:
319 def __init__(self, row: Any) -> None:
320 self.row = row
321
322 async def get(self, model: Any, key: Any) -> Any:
323 return self.row
324
325 async def flush(self) -> None: ...
326 async def refresh(self, obj: Any) -> None: ...
327
328
329 def _row(**kw: Any) -> Any:
330 from types import SimpleNamespace
331
332 fields: dict[str, Any] = {
333 "owner": "alice", "mist_id": "m1", "filename": "a.py", "content": "def f():\n return 1\n", "size_bytes": 22,
334 "version": 1, "artifact_type": "code", "language": "python", "symbol_anchors": ["a.py::f"], "updated_at": None,
335 "title": "", "description": "", "visibility": "public", "tags": [],
336 }
337 fields.update(kw)
338 return SimpleNamespace(**fields)
339
340
341 class TestUpdateFollowsContent:
342 async def test_new_content_recomputes_anchors_and_size(self) -> None:
343 """musehub#320 (immutable model): update_mist takes no content — the ID stays the hash of the bytes."""
344 import inspect
345
346 assert "content" not in inspect.signature(musehub_mists.update_mist).parameters
347
348 async def test_a_rename_alone_recomputes_type_without_a_new_version(self) -> None:
349 row = _row(content="[tool]\nx = 1\n")
350 with patch.object(musehub_mists, "_to_mist_response", return_value=None):
351 await musehub_mists.update_mist(_UpdateSession(row), "m1", "alice", filename="c.toml") # type: ignore[arg-type]
352 assert (row.artifact_type, row.language, row.version) == ("data", "toml", 1)
353 assert any(a.startswith("c.toml::tool") for a in row.symbol_anchors)
354
355 async def test_metadata_only_edit_leaves_derived_fields(self) -> None:
356 row = _row()
357 with (
358 patch.object(musehub_mists, "_to_mist_response", return_value=None),
359 patch.object(musehub_mists, "analyse_mist_content") as analysed,
360 ):
361 await musehub_mists.update_mist(_UpdateSession(row), "m1", "alice", title="t") # type: ignore[arg-type]
362 analysed.assert_not_called()
363 assert row.symbol_anchors == ["a.py::f"]
364
365
366 class TestRawRevalidates:
367 @pytest.mark.parametrize("path", ["/api/mists/m1/raw", "/alice/mists/m1/raw"])
368 def test_public_raw_is_revalidated_with_an_etag(self, mist_client: Any, path: str) -> None:
369 import hashlib
370
371 resp = mist_client.get(path)
372 assert resp.status_code == 200
373 assert resp.headers["cache-control"] == "public, no-cache"
374 assert "immutable" not in resp.headers["cache-control"]
375 etag = resp.headers["etag"]
376 assert etag == f'"{hashlib.sha256(b"x=1").hexdigest()}"'
377 again = mist_client.get(path, headers={"If-None-Match": etag})
378 assert again.status_code == 304 and again.headers["etag"] == etag and again.content == b""
379 mist_client.set_mist(_mist(content="x=2"))
380 changed = mist_client.get(path, headers={"If-None-Match": etag})
381 assert changed.status_code == 200 and changed.text == "x=2" and changed.headers["etag"] != etag
382
383 def test_secret_raw_is_never_stored(self, mist_client: Any) -> None:
384 from types import SimpleNamespace
385
386 from musehub.auth.dependencies import optional_token
387
388 mist_client.set_mist(_mist(visibility="secret"))
389 app.dependency_overrides[optional_token] = lambda: SimpleNamespace(handle="alice")
390 try:
391 resp = mist_client.get("/api/mists/m1/raw")
392 finally:
393 app.dependency_overrides.pop(optional_token, None)
394 assert resp.status_code == 200
395 assert resp.headers["cache-control"] == "private, no-store" and "etag" not in resp.headers
396
397
398 # ── musehub#321: NUL content is a 422 on every write path ───────────────────
399
400
401 class TestNulContent:
402 def test_rest_create_and_patch_bodies_reject_nul(self) -> None:
403 from pydantic import ValidationError
404
405 from musehub.models.mists import MistCreateRequest, MistUpdateRequest
406
407 with pytest.raises(ValidationError, match="NUL"):
408 MistCreateRequest.model_validate({"filename": "a.bin", "content": "a\x00b"})
409 with pytest.raises(ValidationError, match="extra_forbidden|Extra inputs"):
410 MistUpdateRequest.model_validate({"content": "a\x00b"}) # content is immutable (musehub#320)
411
412 async def test_mcp_create_and_update_reject_nul_before_any_write(self) -> None:
413 from musehub.mcp.write_tools import mists as tools
414
415 with patch.object(tools, "_check_db_available", side_effect=AssertionError("must not reach the database")):
416 created = await tools.execute_create_mist(filename="nul.bin", content="a\x00b", actor="alice")
417 assert (created.ok, created.error_code) == (False, "invalid_args")
418
419 async def test_the_service_rejects_nul_too(self) -> None:
420 with pytest.raises(ValueError, match="NUL"):
421 from musehub.models.mists import validate_mist_fields
422
423 validate_mist_fields(content="a\x00b")
424
425 # ── musehub#323: a missing grammar is logged, not silent ────────────────────
426
427
428 class TestMissingGrammarIsLogged:
429 def test_a_js_mist_without_the_grammar_logs_the_package(self, caplog: pytest.LogCaptureFixture) -> None:
430 import importlib.util
431
432 musehub_mists._missing_anchor_grammar.cache_clear() # noqa: SLF001
433 real = importlib.util.find_spec
434 with patch("importlib.util.find_spec", side_effect=lambda n, *a: None if n == "tree_sitter_javascript" else real(n, *a)):
435 with caplog.at_level("WARNING", logger="musehub.services.musehub_mists"):
436 musehub_mists.warn_if_anchor_grammar_missing("a.js", [])
437 musehub_mists._missing_anchor_grammar.cache_clear() # noqa: SLF001
438 assert any("tree-sitter-javascript" in r.getMessage() for r in caplog.records), caplog.text
439
440 @pytest.mark.parametrize(("filename", "anchors"), [("a.py", []), ("a.md", []), ("a.csv", []), ("a.js", ["a.js::f"])])
441 def test_nothing_is_logged_when_no_grammar_is_missing(self, caplog: pytest.LogCaptureFixture, filename: str, anchors: list[str]) -> None:
442 with caplog.at_level("WARNING", logger="musehub.services.musehub_mists"):
443 musehub_mists.warn_if_anchor_grammar_missing(filename, anchors)
444 assert not caplog.records, caplog.text
445
446
447 # ── musehub#319: one snippet generator (iframe only), the deployment's base URL ─
448
449
450 class TestEmbedSnippets:
451 def test_rest_and_mcp_emit_the_same_snippets(self) -> None:
452 s = musehub_mists.embed_snippets("https://h.example", "alice", "m1", 'a"b.py')
453 assert s["embed_url"] == "https://h.example/alice/mists/m1/embed"
454 assert 'title="a"b.py"' in s["iframe"] and 'a"b' not in s["iframe"]
455 assert set(s) == {"embed_url", "iframe"} # no script/badge snippets pointing at assets that do not exist
456
457 async def test_mcp_embed_uses_the_public_url_and_checks_the_owner(self) -> None:
458 from musehub.services import musehub_mcp_executor as exe
459
460 class _Ctx:
461 async def __aenter__(self) -> Any:
462 class _S:
463 async def commit(self) -> None: ...
464 return _S()
465
466 async def __aexit__(self, *a: Any) -> None: ...
467
468 with (
469 patch.object(exe, "_check_db_available", return_value=None),
470 patch.object(exe, "AsyncSessionLocal", new=lambda: _Ctx()),
471 patch.object(musehub_mists, "get_mist", new=AsyncMock(return_value=_mist())),
472 patch.object(musehub_mists, "increment_mist_embed", new=AsyncMock(return_value=None)),
473 ):
474 ok = await exe.execute_read_mist_embed("m1", owner="alice")
475 wrong_owner = await exe.execute_read_mist_embed("m1", owner="mallory")
476 base = musehub_mists.public_base_url()
477 want = musehub_mists.embed_snippets(base, "alice", "m1", "a.py")
478 assert ok.ok and ok.data["iframe"] == want["iframe"] and ok.data["embed_url"] == want["embed_url"]
479 assert not ({"javascript", "badge"} & set(ok.data))
480 assert (wrong_owner.ok, wrong_owner.error_code) == (False, "not_found")
481
482
483 # ── musehub#277 (Phase 1 text tags): the detail page describes the Mist ────
484
485
486 def _head_meta(body: str) -> dict[str, str]:
487 import html as html_lib
488 import re
489
490 head = body.split("</head>", 1)[0]
491 out = {}
492 for attr, key, value in re.findall(r'<meta (property|name)="([^"]+)" content="([^"]*)"', head):
493 out[key] = html_lib.unescape(value)
494 canon = re.search(r'<link rel="canonical" href="([^"]+)"', head)
495 if canon:
496 out["canonical"] = canon.group(1)
497 title = re.search(r"<title>([^<]*)</title>", head)
498 out["title"] = html_lib.unescape(title.group(1)) if title else ""
499 return out
500
501
502 class TestMistDetailOpenGraph:
503 def test_tags_title_and_canonical(self, mist_client: Any) -> None:
504 mist_client.set_mist(_mist(title='Fish & "chips" <×> 🐟', description="A short\n description."))
505 meta = _head_meta(mist_client.get("/alice/mists/m1", headers={"Host": "musehub.ai"}).text)
506 base = musehub_mists.public_base_url()
507 assert meta["og:title"] == meta["twitter:title"] == 'Fish & "chips" <×> 🐟'
508 assert meta["og:description"] == meta["twitter:description"] == "A short description."
509 assert (meta["og:type"], meta["og:site_name"]) == ("article", "MuseHub")
510 assert meta["og:url"] == meta["canonical"] == f"{base}/alice/mists/m1" and base.startswith("https://")
511 assert "twitter:card" in meta
512 assert meta["title"] == 'Fish & "chips" <×> 🐟 · alice — MuseHub'
513
514 def test_fallbacks(self, mist_client: Any) -> None:
515 mist_client.set_mist(_mist(title="", description=""))
516 meta = _head_meta(mist_client.get("/alice/mists/m1").text)
517 assert meta["og:title"] == "a.py" and meta["title"] == "a.py · alice — MuseHub"
518 assert meta["og:description"] == "code Mist by alice on MuseHub"
519
520 def test_long_description_is_cut_on_a_word(self) -> None:
521 from musehub.api.routes.musehub.ui_mists import _og_description
522
523 out = _og_description("word " * 100, "")
524 assert len(out) <= 200 and out.endswith("…") and " " not in out
525
526 def test_secret_mist_is_still_a_404(self, mist_client: Any) -> None:
527 mist_client.set_mist(_mist(visibility="secret", title="hidden"))
528 resp = mist_client.get("/alice/mists/m1")
529 assert resp.status_code == 404 and "hidden" not in resp.text
530
531
532 # ── Review follow-ups L1 / L3 ───────────────────────────────────────────────
533
534
535 class TestReviewFollowUps:
536 async def test_delete_keeps_a_mist_repo_owned_by_someone_else(self) -> None:
537 """L1: the backing repo goes only when it belongs to the mist's owner."""
538 from types import SimpleNamespace
539
540 row = SimpleNamespace(owner="alice", repo_id="repo-1", mist_id="m1")
541 repo = SimpleNamespace(repo_id="repo-1", domain_id="mist", owner="bob")
542 session = _DeleteSession(row, repo)
543 assert await musehub_mists.delete_mist(session, "m1", "alice") is True # type: ignore[arg-type]
544 assert session.deleted == [row]
545
546 def test_ui_raw_escapes_a_quote_in_the_filename(self, mist_client: Any) -> None:
547 """L3: a '"' in the filename cannot end the Content-Disposition parameter early."""
548 mist_client.set_mist(_mist(filename='a"; x=y.py'))
549 resp = mist_client.get("/alice/mists/m1/raw")
550 assert resp.status_code == 200
551 assert resp.headers["content-disposition"] == 'inline; filename="a\\"; x=y.py"'
File History 11 commits
sha256:3cdbbfe4d7fbc1558b9d36cfbc1902be7d9f749dd76374719511a42dd35e9f1a fix(mists): a Mist's content is immutable — PATCH and MCP r… Opus 5.5 minor ⚠ 1 day ago
sha256:d2aba013f6e84cec4f9d3cfcbc7c90bfde5f12a0fa8cb75b74745741f1807b6c fix(mists): offer only the iframe embed — drop the script-t… Opus 5.5 minor ⚠ 1 day ago
sha256:41ed2ded57d17544c111c81960ee6a7a7febc9a0d81a778616319265ac93a654 merge: rc25 — Mists wave (#316 #317 #318 #322; #319 #320 #3… Opus 5.5 minor ⚠ 2 days ago
sha256:217dd826590bc15be90c3f505334270128a9985f7ac6507c90c6dc881229090e fix(mists): delete only the caller's own backing repo; esca… Opus 5.5 patch 2 days ago
sha256:ff17c718b1ca8f72d7ad7c489d3a80ec9fa481cbb7d8d9aa986833a23e223919 feat(mists): Open Graph / Twitter text tags, canonical link… Opus 5.5 patch 2 days ago
sha256:77a1014799b2a1bb9ad914d2c0dea0c6c8ceaf53760edb22c573819e526d0b13 fix(mists): one embed-snippet generator for REST and MCP, o… Opus 5.5 patch 2 days ago
sha256:bcd996529ff074e75f0a165197b1696b5448ca199e2f882d17b0b12bcce36076 fix(mists): PATCH re-derives type fields and raw revalidate… Opus 5.5 minor ⚠ 2 days ago
sha256:24713a1bc91e3f21bcb423f1e3849ab2d0c39679f5a91ab409337ff95133c302 fix(mists): one list limit, 422 on an invalid cursor, url e… Opus 5.5 minor ⚠ 2 days ago
sha256:cc22d4c91c9707a0700270d9a68eb87014436a99729a3327a57e76c9bfc6aafc fix(mists): make the public embed card frameable on purpose… Opus 5.5 minor ⚠ 2 days ago
sha256:e1f7557d1669de53158574bd676f594a6d82eb2977939dcaae13a89b5a565f92 fix(mists): DELETE removes the backing repo so the owner ca… Opus 5.5 patch 2 days ago
sha256:c4341b8be331c768cd3938ce86919e91b0bbe640ba8a9a22a3dd616f29f7b683 fix(mists): serve /mists/explore and /{owner}/mists before … Opus 5.5 minor ⚠ 2 days ago