Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: embedding concurrency, local Lemonade, reading fences, and learner nav (#1783)

Rockynowzzz45bece1b4091
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py
index 6e0dde4ca..1fde8e476 100644
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@ -668,6 +668,11 @@ def _learning_surface_for_path(
# prefix match would open too much.
if route_path and (method.upper(), route_path) in _LEARNER_SETTINGS_WRITE_ROUTES:
return "chat"
+ # Choosing the model for a chat turn is part of chat. The handler is
+ # already grant-filtered. Match this exact path only: a prefix of
+ # /api/settings would also open catalog writes on the same router (#1222).
+ if method.upper() == "GET" and normalized == "/api/settings/llm-options":
+ return "chat"
return ""
diff --git a/deeptutor/services/config/embedding_endpoint.py b/deeptutor/services/config/embedding_endpoint.py
index 10dab12f4..b61c17def 100644
--- a/deeptutor/services/config/embedding_endpoint.py
+++ b/deeptutor/services/config/embedding_endpoint.py
@@ -226,6 +226,10 @@ def normalize_embedding_endpoint_for_display(
return trimmed
if trimmed.endswith("/v1"):
return f"{trimmed}/embeddings"
+ if provider_name == "lemonade":
+ parsed = urlparse(trimmed if "://" in trimmed else f"http://{trimmed}")
+ if parsed.scheme and parsed.netloc and parsed.path.rstrip("/") in {"", "/"}:
+ return _same_origin_url(trimmed, "/v1/embeddings")
if provider_name == "ollama":
if trimmed.endswith("/api/embed"):
return trimmed
diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.py
index 4cf6e8b08..cb9234302 100644
--- a/deeptutor/services/config/provider_runtime.py
+++ b/deeptutor/services/config/provider_runtime.py
@@ -3,6 +3,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
+import ipaddress
import json
from typing import Any
from urllib.parse import urlparse
@@ -1036,6 +1037,53 @@ def _coerce_optional_int(value: Any) -> int | None:
return parsed if parsed > 0 else None
+def _is_nonpublic_embedding_host(hostname: str) -> bool:
+ """Loopback, LAN, and container names that are not a public vendor host."""
+ host = hostname.lower().strip("[]").rstrip(".")
+ if not host:
+ return False
+ if host in {
+ "localhost",
+ "127.0.0.1",
+ "::1",
+ "lemonade",
+ "host.docker.internal",
+ "gateway.docker.internal",
+ }:
+ return True
+ if host.endswith(".local") or host.endswith(".internal"):
+ return True
+ # Docker Compose service names are a single DNS label.
+ if "." not in host:
+ return True
+ try:
+ address = ipaddress.ip_address(host)
+ except ValueError:
+ return False
+ return bool(address.is_private or address.is_loopback or address.is_link_local)
+
+
+def _is_legacy_lemonade_endpoint(api_base: str) -> bool:
+ """Keyless Lemonade servers saved as a generic OpenAI-compatible URL.
+
+ Unraid and Docker installs often point at a LAN address or
+ ``host.docker.internal`` and store the chat root (``/api/v1``) rather than
+ the embeddings path. Those still have to resolve as local Lemonade, or
+ knowledge-base creation demands an API key the server does not use (#1782).
+ A public host on the same port stays a remote OpenAI-compatible endpoint.
+ """
+ try:
+ endpoint = urlparse(api_base if "://" in api_base else f"http://{api_base}")
+ except ValueError:
+ return False
+ if endpoint.port != 13305:
+ return False
+ if not _is_nonpublic_embedding_host(endpoint.hostname or ""):
+ return False
+ path = endpoint.path.rstrip("/")
+ return path.endswith(("/embeddings", "/v1")) or path in {"", "/"}
+
+
def _resolve_embedding_provider(
*,
hint: str | None,
@@ -1043,25 +1091,11 @@ def _resolve_embedding_provider(
api_base: str | None,
provider_pool: dict[str, NormalizedProviderConfig],
) -> str:
- if api_base:
+ if api_base and _is_legacy_lemonade_endpoint(api_base) and hint in {None, "custom", "openai"}:
# Older keyless Lemonade profiles were saved as generic OpenAI
- # Compatible embeddings. Recognize its known endpoint before a Qwen3
- # model name is mistaken for a remote embedding vendor (#1568).
- try:
- endpoint = urlparse(api_base if "://" in api_base else f"http://{api_base}")
- lemonade_endpoint = (
- endpoint.port == 13305
- and endpoint.path.rstrip("/").endswith(("/v1/embeddings", "/api/v1/embeddings"))
- and (
- (endpoint.hostname or "").lower()
- in {"localhost", "127.0.0.1", "::1", "lemonade"}
- or (endpoint.hostname or "").lower().endswith(".local")
- )
- )
- except ValueError:
- lemonade_endpoint = False
- if lemonade_endpoint and hint in {None, "custom", "openai"}:
- return "lemonade"
+ # Compatible embeddings. Recognize that endpoint before a Qwen3 model
+ # name is mistaken for a remote embedding vendor (#1568, #1782).
+ return "lemonade"
if hint and hint in EMBEDDING_PROVIDERS:
return hint
@@ -1145,6 +1179,11 @@ def resolve_embedding_runtime_config(
api_base = gemini_default_embedding_endpoint(resolved_model)
elif spec.default_api_base:
api_base = spec.default_api_base
+ if provider_name == "lemonade" and api_base:
+ # Chat-root URLs such as ``/api/v1`` are what Settings saves for an
+ # OpenAI-compatible Lemonade connection. Embedding calls need the
+ # ``/embeddings`` path or the client rejects them after the key check.
+ api_base = normalize_embedding_endpoint_for_display("lemonade", api_base)
if provider_name == "aliyun":
# DashScope's SDK derives the endpoint from the model id and ignores any
# configured URL, so a saved multimodal endpoint would mislead the
diff --git a/deeptutor/services/embedding/client.py b/deeptutor/services/embedding/client.py
index adf6dbc48..de23e0665 100644
--- a/deeptutor/services/embedding/client.py
+++ b/deeptutor/services/embedding/client.py
@@ -146,17 +146,25 @@ class EmbeddingClient:
input_type=role,
)
try:
- # 全局发帖节流:线程级锁串行化"等待间隔+发帖",跨线程/跨
- # event loop 互斥(asyncio 锁在新 loop 模型下失效的教训)。
- # 非阻塞轮询避免同一 loop 内的并发调用在 acquire() 上互锁。
+ # The spacing lock exists only to keep a configured gap between
+ # requests across threads and event loops (LlamaIndex's pool
+ # gives each thread its own loop, so an asyncio.Lock is not
+ # enough). With the default batch_delay of 0 there is no gap
+ # to protect, and holding the lock around the HTTP call would
+ # flatten every concurrent embed — including LightRAG's — into
+ # one in-flight request (#1779).
from time import monotonic as _mono
- async with EmbeddingClient._hold_spacing_lock():
- if batch_delay > 0:
+ if batch_delay > 0:
+ async with EmbeddingClient._hold_spacing_lock():
elapsed = _mono() - EmbeddingClient._last_request_monotonic
if elapsed < batch_delay:
await asyncio.sleep(batch_delay - elapsed)
- EmbeddingClient._last_request_monotonic = _mono()
+ # The timestamp has to be written inside the lock, or
+ # overlapping callers overwrite it and the gap collapses.
+ EmbeddingClient._last_request_monotonic = _mono()
+ response = await self.adapter.embed(request)
+ else:
response = await self.adapter.embed(request)
except Exception as exc:
# Capture batch context so the task log stream / KB diagnostics
diff --git a/tests/multi_user/test_learning_surface_map.py b/tests/multi_user/test_learning_surface_map.py
index 988b803a5..2bab3295a 100644
--- a/tests/multi_user/test_learning_surface_map.py
+++ b/tests/multi_user/test_learning_surface_map.py
@@ -52,6 +52,10 @@ from deeptutor.api.routers.auth import _learning_surface_for_path
("/api/knowledge-bases/kb1/files/a.pdf", "DELETE", ""),
# Everything else still default-denies.
("/api/settings", "GET", ""),
+ # Model choice for a chat turn. Not a prefix: other settings stay denied.
+ ("/api/settings/llm-options", "GET", "chat"),
+ ("/api/settings/llm-options", "POST", ""),
+ ("/api/settings/llm-options/extra", "GET", ""),
("/api/system/status", "GET", ""),
("/api/dashboard/learning-library/chats", "GET", ""),
("/api/dashboard/learning-library/materials-private", "GET", ""),
diff --git a/tests/services/config/test_embedding_runtime.py b/tests/services/config/test_embedding_runtime.py
index f034beead..7b8e408b5 100644
--- a/tests/services/config/test_embedding_runtime.py
+++ b/tests/services/config/test_embedding_runtime.py
@@ -183,6 +183,55 @@ def test_explicit_openai_binding_to_local_lemonade_is_keyless() -> None:
assert get_embedding_config(catalog=catalog).api_key == ""
+def test_lan_lemonade_openai_binding_is_keyless() -> None:
+ """Unraid/Docker OpenAI-compatible Lemonade roots must not demand a key."""
+ catalog = _build_catalog(
+ embedding_profile={
+ "id": "embedding-p",
+ "binding": "openai",
+ "base_url": "http://192.168.1.40:13305/api/v1",
+ "api_key": "",
+ "models": [
+ {
+ "id": "embedding-m",
+ "model": "Qwen3-Embedding-0.6B-GGUF",
+ }
+ ],
+ }
+ )
+
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
+ assert resolved.provider_name == "lemonade"
+ assert resolved.provider_mode == "local"
+ assert resolved.effective_url == "http://192.168.1.40:13305/api/v1/embeddings"
+ assert get_embedding_config(catalog=catalog).api_key == ""
+
+
+def test_docker_host_lemonade_root_is_keyless() -> None:
+ catalog = _build_catalog(
+ embedding_profile={
+ "id": "embedding-p",
+ "binding": "custom",
+ "base_url": "http://host.docker.internal:13305",
+ "api_key": "",
+ "models": [
+ {
+ "id": "embedding-m",
+ "model": "Qwen3-Embedding-0.6B-GGUF",
+ }
+ ],
+ }
+ )
+
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
+ assert resolved.provider_name == "lemonade"
+ assert resolved.provider_mode == "local"
+ assert resolved.effective_url == "http://host.docker.internal:13305/v1/embeddings"
+ config = get_embedding_config(catalog=catalog)
+ assert config.api_key == ""
+ assert config.effective_url == "http://host.docker.internal:13305/v1/embeddings"
+
+
def test_remote_openai_compatible_endpoint_still_requires_key() -> None:
catalog = _build_catalog(
embedding_profile={
diff --git a/tests/services/embedding/test_client_runtime.py b/tests/services/embedding/test_client_runtime.py
index 44f8606cf..37da74266 100644
--- a/tests/services/embedding/test_client_runtime.py
+++ b/tests/services/embedding/test_client_runtime.py
@@ -79,7 +79,7 @@ async def test_embedding_client_batches_requests(monkeypatch) -> None:
@pytest.mark.asyncio
-async def test_embedding_client_serializes_concurrent_calls_without_blocking_loop(
+async def test_embedding_client_overlaps_calls_when_batch_delay_is_zero(
monkeypatch,
) -> None:
class _NonBlockingOnlyLock:
@@ -134,6 +134,44 @@ async def test_embedding_client_serializes_concurrent_calls_without_blocking_loo
)
assert heartbeat.is_set()
+ assert len(first) == len(second) == 1
+ # batch_delay is 0, so the spacing lock must not serialize the HTTP calls.
+ assert _ConcurrentAdapter.max_in_flight == 2
+
+
+async def test_embedding_client_serializes_when_batch_delay_is_set(monkeypatch) -> None:
+ class _ConcurrentAdapter(_FakeAdapter):
+ in_flight = 0
+ max_in_flight = 0
+
+ async def embed(self, request):
+ type(self).in_flight += 1
+ type(self).max_in_flight = max(type(self).max_in_flight, type(self).in_flight)
+ try:
+ await asyncio.sleep(0.02)
+ return await super().embed(request)
+ finally:
+ type(self).in_flight -= 1
+
+ _FakeAdapter.instances = []
+ monkeypatch.setattr(
+ "deeptutor.services.embedding.client._resolve_adapter_class",
+ lambda _b: _ConcurrentAdapter,
+ )
+ monkeypatch.setattr(EmbeddingClient, "_spacing_lock", None)
+ monkeypatch.setattr(EmbeddingClient, "_last_request_monotonic", 0.0)
+ _ConcurrentAdapter.in_flight = 0
+ _ConcurrentAdapter.max_in_flight = 0
+ config = _build_config("openai")
+ config.batch_delay = 0.05
+ client = EmbeddingClient(config)
+
+ first, second = await asyncio.wait_for(
+ asyncio.gather(client.embed(["first"]), client.embed(["second"])),
+ timeout=1.0,
+ )
+
assert len(first) == len(second) == 1
assert _ConcurrentAdapter.max_in_flight == 1
diff --git a/web/components/sidebar/SidebarNav.tsx b/web/components/sidebar/SidebarNav.tsx
index 5ac32d2c2..bb06cd2e5 100644
--- a/web/components/sidebar/SidebarNav.tsx
+++ b/web/components/sidebar/SidebarNav.tsx
@@ -43,7 +43,9 @@ import {
DEFAULT_COLLAPSED_NAV,
PRIMARY_NAV_HREFS,
isNavActive,
+ navVisibleUnderPolicy,
} from "@/components/sidebar/nav-entries";
+import { useAuthStatus } from "@/hooks/useAuthStatus";
import { Tooltip } from "@/shared/ui/Tooltip";
import { useDragSort, type DragSort } from "@/hooks/useDragSort";
import { placeMenu, type FloatingMenuPosition } from "@/lib/floating-menu";
@@ -109,9 +111,17 @@ export function SidebarNav({
setMoreExpanded(browserStorage.readRaw("local", MORE_EXPANDED_KEY) === "1");
}, []);
+ const { learningPolicy } = useAuthStatus();
+ const moduleHrefs = useMemo(
+ () =>
+ MODULE_NAV_HREFS.filter((href) =>
+ navVisibleUnderPolicy(href, learningPolicy?.allowedSurfaces ?? null),
+ ),
+ [learningPolicy],
+ );
const resolved = useMemo(
- () => resolveNavLayout(MODULE_NAV_HREFS, layout, DEFAULT_COLLAPSED_NAV),
- [layout],
+ () => resolveNavLayout(moduleHrefs, layout, DEFAULT_COLLAPSED_NAV),
+ [layout, moduleHrefs],
);
/** Always edit the resolved order: the stored one may still be empty. */
const editable = useMemo<SidebarNavLayout>(
@@ -527,7 +537,14 @@ export function SidebarHome({
const { t } = useTranslation();
const pathname = usePathname();
const { has } = useCapabilityAccess();
+ const { learningPolicy } = useAuthStatus();
const entry = NAV_BY_HREF.get("/chat")!;
+ if (
+ learningPolicy &&
+ !navVisibleUnderPolicy("/chat", learningPolicy.allowedSurfaces)
+ ) {
+ return null;
+ }
const active = isNavActive(pathname, entry.href);
const locked = entry.requires ? !has(entry.requires) : false;
const lockedTooltip = t("Locked — contact your administrator to get access.");
diff --git a/web/components/sidebar/nav-entries.ts b/web/components/sidebar/nav-entries.ts
index 8e7863939..aad360f4e 100644
--- a/web/components/sidebar/nav-entries.ts
+++ b/web/components/sidebar/nav-entries.ts
@@ -21,6 +21,11 @@ export interface NavEntry {
defaultCollapsed?: boolean
/** Model capability this feature needs; locked when the user lacks it. */
requires?: Capability
+ /**
+ * Learning-account surfaces that may see this entry. Absent means the
+ * entry is hidden whenever a learning policy is in effect (#1222).
+ */
+ surfaces?: readonly string[]
}
/**
@@ -33,7 +38,14 @@ export interface NavEntry {
* the neighbour it follows below rather than at the bottom of their list.
*/
export const PRIMARY_NAV: NavEntry[] = [
- { href: '/chat', label: 'Home', icon: House, tooltipKey: 'Home tooltip', requires: 'llm' },
+ {
+ href: '/chat',
+ label: 'Home',
+ icon: House,
+ tooltipKey: 'Home tooltip',
+ requires: 'llm',
+ surfaces: ['chat'],
+ },
{
href: '/partners',
label: 'Partners',
@@ -46,9 +58,16 @@ export const PRIMARY_NAV: NavEntry[] = [
label: 'Personalized Learning',
icon: GraduationCap,
tooltipKey: 'One tutor, your own way to learn.',
+ surfaces: ['reading', 'chat', 'books'],
},
{ href: '/space', label: 'Learning Space', icon: LayoutGrid, tooltipKey: 'Space tooltip' },
- { href: '/kanban', label: 'Task Board', icon: ListTodo, tooltipKey: 'kanban.intro' },
+ {
+ href: '/kanban',
+ label: 'Task Board',
+ icon: ListTodo,
+ tooltipKey: 'kanban.intro',
+ surfaces: ['chat'],
+ },
{
href: '/co-writer',
label: 'Co-Writer',
@@ -81,3 +100,19 @@ export const NAV_BY_HREF = new Map(
export function isNavActive(pathname: string, href: string) {
return pathname === href || pathname.startsWith(`${href}/`)
}
+
+/**
+ * A learning policy hides every feature the account cannot call. Settings
+ * stays, because the redacted page (theme, language) is still theirs.
+ * ``allowedSurfaces === null`` means no policy: the full sidebar.
+ */
+export function navVisibleUnderPolicy(
+ href: string,
+ allowedSurfaces: readonly string[] | null,
+): boolean {
+ if (allowedSurfaces === null) return true
+ if (href === '/settings') return true
+ const surfaces = NAV_BY_HREF.get(href)?.surfaces
+ if (!surfaces?.length) return false
+ return surfaces.some(surface => allowedSurfaces.includes(surface))
+}
diff --git a/web/hooks/useAuthStatus.ts b/web/hooks/useAuthStatus.ts
index 1b08033a6..a6983417a 100644
--- a/web/hooks/useAuthStatus.ts
+++ b/web/hooks/useAuthStatus.ts
@@ -3,6 +3,11 @@
import { useEffect, useState } from "react";
import { fetchAuthStatus } from "@/lib/auth";
+export interface LearningPolicyState {
+ /** Surfaces this account may open. Everything else is hidden, not a 403. */
+ allowedSurfaces: string[];
+}
+
export interface AuthStatusState {
/** Whether auth is enabled on the backend. */
enabled: boolean;
@@ -16,6 +21,12 @@ export interface AuthStatusState {
statusAvailable: boolean;
/** True until the first status fetch resolves. */
loading: boolean;
+ /**
+ * Effective learning policy from ``GET /api/auth/status``. Null for accounts
+ * without one. The shell reads ``allowedSurfaces`` so denied features are
+ * absent instead of offered and then rejected (#1222).
+ */
+ learningPolicy: LearningPolicyState | null;
}
const INITIAL: AuthStatusState = {
@@ -25,8 +36,20 @@ const INITIAL: AuthStatusState = {
userId: null,
statusAvailable: false,
loading: true,
+ learningPolicy: null,
};
+function learningPolicyFromStatus(
+ status: Awaited<ReturnType<typeof fetchAuthStatus>>,
+): LearningPolicyState | null {
+ const policy = status?.learning_policy;
+ if (!policy) return null;
+ const surfaces = (policy.allowed_surfaces ?? ["chat", "reading"]).filter(
+ (surface) => surface.trim().length > 0,
+ );
+ return { allowedSurfaces: surfaces.length ? surfaces : ["chat", "reading"] };
+}
+
/**
* Resolve auth state at runtime from the backend (`/api/auth/status`).
*
@@ -48,6 +71,7 @@ function loadAuthStatus(): Promise<AuthStatusState> {
: null,
statusAvailable: status !== null,
loading: false,
+ learningPolicy: learningPolicyFromStatus(status),
}));
}
diff --git a/web/lib/reading-outline.ts b/web/lib/reading-outline.ts
index dba105830..95afb0b7d 100644
--- a/web/lib/reading-outline.ts
+++ b/web/lib/reading-outline.ts
@@ -66,6 +66,35 @@ export function extractEpubHeadings(
return headings;
}
+/**
+ * CommonMark fence tracking shared by the in-page outline and the renderer.
+ *
+ * A backtick fence whose info string itself contains a backtick is not a
+ * fence (it is inline code such as ```inline```). A closing line must be a
+ * bare run of the same character at least as long as the opener, so ```py
+ * inside a block stays content and does not swallow every later heading
+ * (#1641).
+ */
+function stepMarkdownFence(
+ fence: string | null,
+ line: string,
+): { fence: string | null; isFence: boolean } {
+ const match = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
+ if (!match) return { fence, isFence: false };
+ const marker = match[1];
+ const info = match[2] ?? "";
+ if (!fence) {
+ if (marker.startsWith("`") && info.includes("`")) {
+ return { fence: null, isFence: false };
+ }
+ return { fence: marker, isFence: true };
+ }
+ if (marker[0] === fence[0] && marker.length >= fence.length && info.trim() === "") {
+ return { fence: null, isFence: true };
+ }
+ return { fence, isFence: false };
+}
+
/**
* Attach outline entries to source lines without changing a single character.
*
@@ -80,14 +109,14 @@ export function readerLinesWithHeadings(
let fence: string | null = null;
let headingIndex = 0;
return text.split("\n").map((line) => {
- const fenceMatch = /^\s*(`{3,}|~{3,})/.exec(line);
- if (fenceMatch) {
+ const next = stepMarkdownFence(fence, line);
+ if (next.isFence) {
// The fence delimiter line itself is reported as `fence: true` too, so
// the renderer never runs Markdown formatting over a stray ``` marker.
- if (!fence) fence = fenceMatch[1];
- else if (line.trim().startsWith(fence)) fence = null;
+ fence = next.fence;
return { text: line, heading: null, fence: true };
}
+ fence = next.fence;
if (fence) return { text: line, heading: null, fence: true };
const parsed = readerHeadingLine(line);
@@ -114,13 +143,9 @@ export function extractReaderHeadings(
if (!source) continue;
let fence: string | null = null;
for (const line of source.split(/\r?\n/)) {
- const fenceMatch = /^\s*(`{3,}|~{3,})/.exec(line);
- if (fenceMatch) {
- if (!fence) fence = fenceMatch[1];
- else if (line.trim().startsWith(fence)) fence = null;
- continue;
- }
- if (fence) continue;
+ const next = stepMarkdownFence(fence, line);
+ fence = next.fence;
+ if (next.isFence || fence) continue;
const heading = readerHeadingLine(line);
if (heading) {
headings.push({
diff --git a/web/tests/learner-navigation.spec.tsx b/web/tests/learner-navigation.spec.tsx
new file mode 100644
index 000000000..3250a6e7a
--- /dev/null
+++ b/web/tests/learner-navigation.spec.tsx
@@ -0,0 +1,37 @@
+import { renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, expect, it, vi } from "vitest";
+import { useAuthStatus } from "@/hooks/useAuthStatus";
+import { PRIMARY_NAV_HREFS, navVisibleUnderPolicy } from "@/components/sidebar/nav-entries";
+import { fetchAuthStatus } from "@/lib/auth";
+
+vi.mock("@/lib/auth", () => ({ fetchAuthStatus: vi.fn() }));
+beforeEach(() => vi.mocked(fetchAuthStatus).mockReset());
+
+it.each([
+ [["reading"], ["/learning"]],
+ [["books"], ["/learning"]],
+ [["chat"], ["/chat", "/learning", "/kanban"]],
+ [[], []],
+] as [string[], string[]][])("filters the actual nav entries for %j", (allowed, expected) => {
+ expect(PRIMARY_NAV_HREFS.filter((href) => navVisibleUnderPolicy(href, allowed))).toEqual(expected);
+ expect(navVisibleUnderPolicy("/settings", allowed)).toBe(true);
+});
+
+it("keeps the full navigation for accounts without a learning policy", () => {
+ expect(PRIMARY_NAV_HREFS.every((href) => navVisibleUnderPolicy(href, null))).toBe(true);
+});
+
+it.each([undefined, [], ["reading"]])("loads policy surfaces and mirrors backend defaults for %j", async (surfaces) => {
+ vi.mocked(fetchAuthStatus).mockResolvedValue({
+ enabled: true,
+ authenticated: true,
+ role: "user",
+ learning_policy: {
+ age_band: "13-15", locked_persona: "", allowed_capabilities: [], default_capability: "chat",
+ allowed_surfaces: surfaces,
+ },
+ });
+ const { result } = renderHook(() => useAuthStatus());
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.learningPolicy?.allowedSurfaces).toEqual(surfaces?.length ? surfaces : ["chat", "reading"]);
+});
diff --git a/web/tests/reading-outline.test.ts b/web/tests/reading-outline.test.ts
index b7c5c4cbb..e7debfd8a 100644
--- a/web/tests/reading-outline.test.ts
+++ b/web/tests/reading-outline.test.ts
@@ -186,6 +186,29 @@ test("page headings are searchable from the workspace navigator", () => {
assert.doesNotMatch(textReader, /segmentTextByQuotes|<mark/);
});
+test("fenced examples do not swallow the headings that follow them", () => {
+ const nested = [
+ "# Guide",
+ "````md",
+ "```py",
+ "# Not a heading",
+ "```",
+ "````",
+ "## Next",
+ ].join("\n");
+ const infoString = ["# Guide", "```", "```py", "# Not a heading", "```", "## Next"].join(
+ "\n",
+ );
+ const inline = "# Guide\n```inline``` code.\n## Next";
+
+ for (const sourceText of [nested, infoString, inline]) {
+ assert.deepEqual(
+ extractReaderHeadings([sourceText], 1).map((heading) => heading.title),
+ ["Guide", "Next"],
+ );
+ }
+});
+
test("lines inside a fenced code block are flagged so the renderer skips Markdown", () => {
const sourceText = "Intro paragraph.\n```md\n**not bold**\n```\nAfter.";
const lines = readerLinesWithHeadings(sourceText, []);
@@ -196,3 +219,17 @@ test("lines inside a fenced code block are flagged so the renderer skips Markdow
);
assert.equal(lines.map((line) => line.text).join("\n"), sourceText);
});
+
+
+test("tab-indented fence markers do not open or close fenced blocks", () => {
+ for (const text of [
+ "\t```md\n# Visible\n",
+ "```md\n\t```\n# Hidden\n```\n# Visible",
+ ]) {
+ const headings = extractReaderHeadings([text], 1);
+ assert.deepEqual(headings.map((heading) => heading.title), ["Visible"]);
+ const lines = readerLinesWithHeadings(text, headings);
+ assert.deepEqual(lines.filter((line) => line.heading).map((line) => line.heading?.title), ["Visible"]);
+ assert.equal(lines.map((line) => line.text).join("\n"), text);
+ }
+});