mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-04 20:39:45 +08:00
fix: embedding concurrency, local Lemonade, reading fences, and learner nav (#1783)
* fix(embedding): do not serialize requests when batch delay is zero The spacing lock was held around every embedding HTTP call, so concurrent indexing stayed serial even when batch_delay was 0. Fixes #1779 * fix(embedding): treat LAN Lemonade endpoints as keyless local servers OpenAI-compatible profiles pointed at a private Lemonade port were still required to have an API key, so LlamaIndex knowledge bases failed to initialize. Fixes #1782 * fix(reading): keep headings that follow fenced code examples The reader treated any line starting with the fence character as a toggle, so an example fence swallowed every later heading. Fixes #1641 * fix(learning): hide surfaces a learner account cannot use The auth status already returned the learning policy, but the sidebar ignored it, and model options answered 403 for those accounts. Fixes #1222 * fix(github-source): refresh unchanged sync state (#1490) * test: freeze naive FIXED_NOW for cross-platform TZ stability (#1733) * test: pin TZ in runtime_context date assertions for cross-timezone stability * test: freeze naive FIXED_NOW for cross-platform TZ stability Rework of568c522f0per review: datetime.now() returns a naive datetime, so .astimezone() only attaches the host zone without shifting the calendar date. The aware frozen clock made astimezone() convert across zones and west-of-UTC hosts rendered the previous day. Making FIXED_NOW naive fixes every timezone on every OS (including Windows) with no TZ env or tzset() global-state churn; the tz-pinning fixture is reverted as unnecessary. --------- Co-authored-by: XZH <cto@xzh.ai> * test(partners): lock outbound dispatch timeout semantics (#1763) _dispatch_outbound's 'except asyncio.TimeoutError: continue' is the 1s idle-poll timeout on an empty outbound queue, not a message skip: a cancelled Queue.get() pops nothing and a consume finishing despite the timeout has its result returned by wait_for. Channel send timeouts are Exception subclasses retried inside _send_with_retry (backoff 1s/2s/4s, send_max_retries attempts) and logged on give-up. Document this on the handler and lock it with focused tests (idle poll then deliver, send timeout retried in-dispatch, retries exhausted after max attempts). Co-authored-by: XZH <cto@xzh.ai> * test: add tex_downloader/tex_chunker toolchain tests (#1748) Co-authored-by: XZH <cto@xzh.ai> * test(question): pin mimic websocket error-path and stdout interceptor failure contracts (#1741) * test(question): pin mimic websocket error-path and stdout interceptor failure contracts Failure-injection characterization tests for the two DT-22 HIGH findings on websocket_mimic_generate: the outer error broadcast swallow and the StdoutInterceptor terminal-write swallow (ex-TeeWrite). Pins that send/write failures stay isolated, process stdout is always restored, and the websocket still closes. 现状豁免 recorded in docstrings: the swallows are silent by design today; surfacing them is a code change outside this test-only card. * style(tests): reformat question router mimic websocket test for ruff format --------- Co-authored-by: XZH <cto@xzh.ai> * test(api): cover learning-records account isolation and read boundaries (#1739) * test(api): cover learning-records account isolation and read boundaries Regression protection for GET /api/mastery-paths/reading/records (#1109/#1130): cross-account invisibility through the real require_learning_surface auth stack, the 200-entry most-recent-first activity tail, the empty-account branch, 401 on missing/invalid tokens, 405 on writes, and 400 on conflicting workspace scopes. * test(api): fix ruff import order and formatting in learning-records tests --------- Co-authored-by: XZH <cto@xzh.ai> * test(reading): cover the bilingual EPUB pairing pipeline edge cases (#1738) * test(reading): cover the bilingual EPUB pairing pipeline edge cases * style(reading): apply ruff format to bilingual EPUB unit tests --------- Co-authored-by: XZH <cto@xzh.ai> * test(storage): lock file library disk-deletion failure paths (#1719) Merge the six DT-22 regression cases (previously on a separate test_file_library_deletion.py branch) into the existing per-module test file, right after the delete_file / hard_delete_file sections: - successful delete prunes now-empty parents, keeps non-empty ones and the library root itself - missing on-disk target is a silent no-op; hard delete still clears the DB row when the disk file vanished out-of-band - unlink failure is only logged (list-vs-disk inconsistency window) - an exception while pruning parents is swallowed: file still removed, empty dirs left behind, caller unaffected (current behaviour pinned) Coverage of deeptutor.services.storage.file_library: 84% -> 87% (196-197 and 203-206 now covered). No product code changes. Co-authored-by: XZH <cto@xzh.ai> * test(book): cover engine stage transitions (#1718) * test(book): cover engine stage transitions Pin the three guarantees a long book generation depends on: stage order with per-stage artefact persistence, single-stage failure retry without duplicating output (exploration degrade + page-level compile retry), and pause/resume recovery that never re-pays finished pages. All agents and the compiler are faked — no LLM, no long tasks. * docs: add PR evidence for book engine stage transition tests --------- Co-authored-by: XZH <cto@xzh.ai> * test(plugins): pin entry-point loader contract across load, isolation, duplicate and gating paths (#1740) * test(plugins): pin entry-point loader contract across load, isolation, duplicate and gating paths * style(plugins): format test_entrypoint_loader to satisfy ruff format --------- Co-authored-by: XZH <cto@xzh.ai> * test(co-writer): lock router contract for CRUD, 4xx payloads, export failures (#1768) Coverage gap: deeptutor/api/routers/co_writer.py had 246 missing lines (40.0%). Add tests/api/routers/test_co_writer_contract.py (40 cases): document CRUD request/response shapes, illegal-payload 4xx handling, export/import failure branches, edit/automark agent passthrough, and history/tool-calls endpoints. All storage and agent work is stubbed to tmp_path; no product code changed. Evidence: evidence/co-writer-tests-20261003/ (40 passed on origin/main ef2d9e5c3; no failing cases, contract currently holds). Co-authored-by: XZH <cto@xzh.ai> * test(session): cover pocketbase_store failure branches and pagination edges (#1773) * test(session): cover pocketbase_store failure branches and pagination edges * docs: add PR evidence for pocketbase_store fallback coverage --------- Co-authored-by: XZH <cto@xzh.ai> * test(launcher): cover lifecycle termination, port cleanup and marker corruption paths (#1769) * test(launcher): cover lifecycle termination, port cleanup and marker corruption paths * style(tests): sort imports in test_launcher_lifecycle to satisfy ruff I001 --------- Co-authored-by: XZH <cto@xzh.ai> * style: apply ruff format to spine_synthesizer tests (#1750) * test(book): cover SpineSynthesizer materialise, revise loop and fallback paths 20 offline cases over the spine_synthesizer seams the LLM-call test does not reach: payload-to-chapter/graph materialisation, the draft-critique- revise loop with on_round events, unusable-output fallbacks, and the deterministic invariants (count, order, clamping). Module coverage 14.0% -> 94%. All LLM traffic is replayed via BaseAgent.stream_llm; each test seeds its own agents.yaml home so no runtime install is required. * style: apply ruff format to spine_synthesizer tests * docs: add PR evidence for spine_synthesizer coverage --------- Co-authored-by: XZH <cto@xzh.ai> * chore(tests): keep regression coverage without internal audit artifacts * fix(llm): avoid tokenizing image payloads in request fingerprints (#1712) * perf(llm): deduplicate repeated inline user images per request (#1714) * perf(llm): deduplicate repeated inline user images per request * fix(llm): preserve image fallback and stable replay references * fix(learning): prevent compounding SRS lapses during multi-turn qualitative repairs (#1781) (#1794) * fix(mastery-path): allow editing legacy objective counts (#1790) * fix(crawler): ignore absurd robots.txt crawl-delay values (#1787) A hostile robots.txt could park every request to a host (and the shared per-host pace lock) on one unbounded sleep; delays beyond 60s are now treated as "no directive" and the default interval applies instead (RFC 9309 lets crawlers cap unreasonable values). * fix: decode escaped emoji in ask_user cards as real characters (#1780) decode_escaped_unicode_for_display repairs double-encoded \uXXXX runs (#973) with the unicode_escape codec, which turns a surrogate-pair escape for an emoji into two lone surrogates instead of one emoji. The result cannot be encoded as UTF-8, so an ask_user card or mastery question whose escaped text contains an emoji fails when the event is persisted to SQLite or sent over the WebSocket. Decode each run as a JSON string instead, matching the web decoder's JSON.parse, and leave runs with an unpaired surrogate escaped. * fix(services): surface fsync failures in atomic writers as rate-limited warnings (#1751) Co-authored-by: XZH <cto@xzh.ai> * fix(partners): stop telegram typing loop for denied senders and dropped media-group stragglers (#1746) * test(partners): telegram message parsing, chunking and typing contract suite Red-first coverage for deeptutor/partners/channels/telegram.py (coverage gap: 418 missing / 30.2%). 28 green tests pin current behavior; 2 red tests encode real defects for a fix card: 1. media-group straggler arriving while _flush_media_group dispatches is buffered but never flushed (message dropped, buffer leaks) 2. typing indicator for an ACL-denied sender runs forever No product code changed. Evidence in evidence/telegram-tests-20261003/. * fix(partners): stop telegram typing loop for denied senders and dropped media-group stragglers - start the typing indicator only for senders passing is_allowed: a denied sender never receives a reply, so the 4-second send_chat_action loop used to run until channel restart - release the media-group task slot before dispatching the buffered album, so a straggler item arriving mid-dispatch schedules its own follow-up flush instead of being silently dropped (and leaking its buffer); the finally guard only drops the task's own registration * test(partners): telegram suite lint polish; drop internal evidence dir - fix ruff F541 (redundant f-string) and apply ruff format - reword red-test docstrings: both defects are fixed on this branch - remove evidence/telegram-tests-20261003/ (internal tracking artifacts, kept on the v1 branch) so the tree matches upstream conventions --------- Co-authored-by: XZH <cto@xzh.ai> * fix(api): warn when a deferred tool's definition fails to load (#1731) * fix(api): warn when a deferred tool's definition fails to load build_tool_options swallowed get_definition() errors on deferred (MCP) tools with a bare continue, so a broken tool silently vanished from the options surface with no trace of why it was unavailable. The skip now logs a warning naming the provider and adapter class plus the failure reason; enumeration of the remaining tools is unchanged. * style(api): ruff-format deferred tool definition warning changes --------- Co-authored-by: XZH <cto@xzh.ai> * fix(rag): classify invalid persisted index errors and include re-index steps (#1702) * fix(rag): classify invalid persisted index errors and include re-index steps Searching a knowledge base whose persisted vector store contains invalid vectors (issue #440) was misclassified: the ValueError raised at index load wraps a provider-facing "Details: ..." tail, so search_error_result matched the embedding-provider branch first and returned invalid_embedding_provider_response without needs_reindex, blaming the provider instead of the damaged index. Check the persisted-index diagnosis first, include the recorded failure reason (which store file, which vector) in the user-facing answer, and spell out recovery: run the knowledge base's 'Re-index' action; re-uploading documents reuses the damaged store and cannot repair it. * test(codebuddy): make credential fixture expiry relative to now test_load_credentials_parses_session wrote a hard-coded expiresAt of 1791055241000 (2026-10-03 15:40:41 UTC) and asserted is_expired() is False. Once that instant passed the assertion flipped, so the test now fails on every Python version for every branch. Derive expiresAt / refreshExpiresAt from time.time() so the fixture always describes a live session, and assert against the value written. --------- Co-authored-by: XZH <cto@xzh.ai> * fix(knowledge): surface swallowed KB status, progress and folder-sync failures (#1706) * fix(knowledge): make update_kb_status write failures observable The ready-transition metadata refresh swallowed every exception (`except Exception: pass`), and a kb_config.json persist failure surfaced only as an opaque raise inside fire-and-forget callers, so a lost status update left the persisted KB state stale with no diagnostic. - Log a warning naming the KB when the best-effort ready-transition metadata refresh fails, instead of silently passing. - Log an error with the KB name and status when persisting the config fails, then re-raise so callers still receive the exception (the write is authoritative, not best-effort). Tests: a persist failure is logged and re-raised; a metadata refresh failure is logged and does not propagate. * fix(knowledge): make progress WS failures visible instead of silent The websocket_progress endpoint swallowed five failure points with `except Exception: pass`: timestamp parsing (x2), error-frame delivery, socket close, and user-context reset. A corrupt progress snapshot or a broken teardown path therefore vanished without a trace. - Share a _progress_age_seconds helper for both freshness checks: narrow the catch to (TypeError, ValueError), keep the inactive/stale fallback, and log unparseable timestamps at warning level. - Reuse the already-parsed snapshot age in the replay decision, so one corrupt timestamp warns once per connection instead of once per freshness check. - Trace failed error-frame delivery and failed close at debug level (usually an already-disconnected client, not a fault). - Log a failed reset_current_user at warning level: leaking the user context is a real fault, not a disconnect. Tests: malformed timestamp degrades with a warning; cleanup failures are logged and never propagate; normal disconnects stay silent. * fix(knowledge): stop swallowing a failed reindex error-progress write The reindex failure path wrapped its ProgressTracker ERROR update in `except Exception: pass`, so when that write itself failed the rebuild's failure alert disappeared and the KB progress view silently stayed stale. Log a warning instead; the task-level error status remains authoritative. * fix(knowledge): log folder sync state recording failures update_folder_sync_state() swallowed per-file mtime recording errors with 'except Exception: pass', so a file whose state could not be recorded silently degraded the persisted sync state while last_sync still advanced. Log the failure at WARNING and keep the un-recorded fallback so the next scan re-syncs the file. * test(codebuddy): make credential fixture expiry relative to now test_load_credentials_parses_session wrote a hard-coded expiresAt of 1791055241000 (2026-10-03 15:40:41 UTC) and asserted is_expired() is False. Once that instant passed the assertion flipped, so the test now fails on every Python version for every branch. Derive expiresAt / refreshExpiresAt from time.time() so the fixture always describes a live session, and assert against the value written. --------- Co-authored-by: XZH <cto@xzh.ai> * fix(co-writer): keep a placeholder row and warn when DOCX table row parsing fails (#1700) * fix(co-writer): warn and keep placeholder row when DOCX table row parsing fails _table_to_markdown swallowed per-row cell errors with 'except Exception: continue', silently dropping rows (e.g. malformed merged cells) from the converted markdown. Log a warning with the table/row ordinal and keep a placeholder row so the loss is visible in the output itself. Use an English placeholder '(unparseable row)' so non-Chinese documents are not polluted, and keep test imports sorted for CI. * test(codebuddy): make credential fixture expiry relative to now test_load_credentials_parses_session wrote a hard-coded expiresAt of 1791055241000 (2026-10-03 15:40:41 UTC) and asserted is_expired() is False. Once that instant passed the assertion flipped, so the test now fails on every Python version for every branch. Derive expiresAt / refreshExpiresAt from time.time() so the fixture always describes a live session, and assert against the value written. --------- Co-authored-by: XZH <cto@xzh.ai> * fix(runtime): surface launcher termination and port-kill signal failures (#1715) _terminate and _kill_port_listeners wrapped every tree signal in bare except-pass blocks, so a child or port listener the signals could not reach survived shutdown with no log line to trace: zombie children and occupied ports after restart, with nothing to investigate. Signal delivery now goes through _signal_target, which logs each failure at WARNING with its cause; the SIGTERM -> wait -> SIGKILL ladder and its timeouts are unchanged. A target that is already gone is not a failure: ESRCH from os.kill/os.killpg is treated as terminated, and on Windows _send_tree_signal now checks taskkill's exit code, staying quiet for its "process not found" (128) while raising for real failures such as access denied, so the Windows path is observable too. Co-authored-by: XZH <cto@xzh.ai> * fix(rag): log swallowed embedding/image progress and LightRAG meta failures (#1703) * fix(embedding): log progress callback failures instead of swallowing them embed/embed_contents wrapped progress_callback in 'except Exception: pass'. A failing progress sink vanished without a trace while indexing continued, making KB index progress untrustworthy (stalled reads with no diagnostics). Keep the callback best-effort (embedding runs must not fail on UI feedback) but log a warning with batch context and the underlying exception. * fix: log image progress callback failures instead of swallowing them _describe_one wrapped image_progress_callback in 'except Exception: pass', so a broken progress sink silently dropped indexing progress updates with no trace. Log a warning with completed/total context and keep the batch running; add a focused test covering visible failure logging and uninterrupted loading. * fix(lightrag): warn when workspace meta.json exists but is unusable workspace_for() swallowed OSError/ValueError when reading meta.json and silently fell back to the path-hash workspace name, which can open an empty store with no log trail. Missing files stay silent; unreadable or corrupt meta now logs a warning with the path and exception type while keeping the same fallback behavior. * test(codebuddy): make credential fixture expiry relative to now test_load_credentials_parses_session wrote a hard-coded expiresAt of 1791055241000 (2026-10-03 15:40:41 UTC) and asserted is_expired() is False. Once that instant passed the assertion flipped, so the test now fails on every Python version for every branch. Derive expiresAt / refreshExpiresAt from time.time() so the fixture always describes a live session, and assert against the value written. --------- Co-authored-by: XZH <cto@xzh.ai> * docs(tools): add tools surface guide (#1716) Co-authored-by: XZH <cto@xzh.ai> * docs(events): add event and progress chain guide (#1717) Co-authored-by: XZH <cto@xzh.ai> * feat(visualize): add Mermaid mindmap visualizer (#1295) Co-authored-by: XZH <cto@xzh.ai> * perf(mastery): seed fresh status before the first model call (#1713) Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com> * fix(visualize): validate mindmap roots and complete translations * test(rag): exercise current image client and portable read failures * docs(events): distinguish handler isolation from durable replay * test(settings): cover CLI-app model persistence end to end (#1630) (#1745) * test(settings): apply PR #1634 draft test verbatim Applies the exact test change from PR #1634 (codex/test/subagent-settings-draft,fc8ef2f36) on top of dev to verify it passes without any fix commit. * test(settings): cover CLI-app model persistence end to end (#1630) Mounts the real SubagentSettingsEditor inside SettingsProvider with the settings toolbar and a network-level mock backend. Verifies the three paths from issue #1630: live model edits flush through PUT /api/subagents/settings before POST /api/settings/apply and survive a remount; a draft parked server-side applies even when its editor is not mounted; a restored draft applies from the editor's page and survives a reload. --------- Co-authored-by: XZH <cto@xzh.ai> * test(quiz): add QuizViewer smoke and grading interaction coverage (#1775) Co-authored-by: XZH <cto@xzh.ai> * test(web): smoke ChatWorkspace empty home, streaming turn, failure banner (#1767) * test(web): smoke ChatWorkspace empty home, streaming turn, failure banner ChatWorkspace.tsx had 0% unit coverage (DT-21 top-15 gap #2). Mount the real surface with the ChatStateAdapter mocked at its boundary and stub the heavy leaf components, then assert: - empty draft renders the greeting home and bootstraps newSession() - a first send reaches sendMessage with the composed turn config - streamed deltas drive message-list/composer streaming flags until done - submission failure shows the composer-adjacent error banner with a working Resend, and the needs-review variant drops the Resend - an unloadable URL session settles into the retryable failure state File coverage: 0% -> 50.3% lines (476/947), 47.4% statements. * docs(evidence): add PR draft for ChatWorkspace smoke tests --------- Co-authored-by: XZH <cto@xzh.ai> * test(web): cover VisualizationViewer render branches (mermaid/svg/chartjs/html/plugin/manim) (#1749) Add web/tests/visualize/VisualizationViewer.spec.tsx with 22 vitest cases covering the three core states (loading, render success, render-failure fallback) plus the remaining render dispatch branches: svg sanitize/split, chartjs parse/destroy, html iframe bridge, plugin iframe, geogebra, unknown renderer, manim delegation, toolbar/fullscreen/code panel. VisualizationViewer.tsx coverage: statements 1.69% -> 74.57%, branches 0% -> 50.86%, functions 0% -> 71.69%, lines 1.49% -> 61.56%. Full suite 114 files / 493 tests green; typecheck + eslint clean. No product code changed. Evidence: evidence/test-visualization-viewer-20261003/ Co-authored-by: XZH <cto@xzh.ai> * test(web): smoke coverage for StandaloneComposer send gating (#1744) Pins the composer's own state pool: empty-input guard, full submission payload with one-shot state consumption, the isStreaming lock and its awaitingUserReply escape hatch. ChatComposer is stubbed so the tests exercise StandaloneComposer's decisions, not the presentation. Covers the 0%-coverage Top-20 entry from evidence/coverage-2026-10-02. Co-authored-by: XZH <cto@xzh.ai> * test(web): cover the settings store and memory-graph helpers (#1710) * test(web): cover settings store persistence and normalization * test(web): cover memory-graph pure functions * test(codebuddy): make credential fixture expiry relative to now test_load_credentials_parses_session wrote a hard-coded expiresAt of 1791055241000 (2026-10-03 15:40:41 UTC) and asserted is_expired() is False. Once that instant passed the assertion flipped, so the test now fails on every Python version for every branch. Derive expiresAt / refreshExpiresAt from time.time() so the fixture always describes a live session, and assert against the value written. --------- Co-authored-by: XZH <cto@xzh.ai> * test(api): add contract tests for upload guards, quiz judge, reading progress, notebook and memory routers (#1709) * test(api): lock knowledge-base upload and delete guard contracts * test(api): unit-cover the quiz-judge WebSocket router * test(reading): pin the reading progress API durability contract * test(notebook): pin the question notebook API source, dedup and concurrency contract * test(memory): cover the memory workbench router contract * test(codebuddy): make credential fixture expiry relative to now test_load_credentials_parses_session wrote a hard-coded expiresAt of 1791055241000 (2026-10-03 15:40:41 UTC) and asserted is_expired() is False. Once that instant passed the assertion flipped, so the test now fails on every Python version for every branch. Derive expiresAt / refreshExpiresAt from time.time() so the fixture always describes a live session, and assert against the value written. --------- Co-authored-by: XZH <cto@xzh.ai> * fix(courses): surface course deletion failure instead of silent redirect (#1754) The confirm handler fired deleteCourse with void and no .catch, so a failed delete left an unhandled rejection, gave the learner no feedback, and still navigated away from the course page. Await the call in a try/catch: stay on the page with a visible alert (and the dialog open for retry) on failure, push /courses only on success, and disable the confirm button while pending. Co-authored-by: XZH <cto@xzh.ai> * fix(reading): converge the mobile header and dock the selection panel (#1734) Below 768px the reader header converges to back, title + chapter, bookmark and more: forward moves into the more menu (also when the workspace hosts it), the file icon yields its width, and the chapter indicator truncates inside a bounded share of the row instead of disappearing. The selection panel becomes a bottom card on phones: collapsed rows for short content, a capped scrollable body for the note editor and overflow actions, a drag handle for pull-down-to- dismiss, and safe-area padding; the desktop popover is unchanged. Refs #916 Co-authored-by: XZH <cto@xzh.ai> * fix(reading): respect fence indentation and verify learner navigation --------- Co-authored-by: Rockynowzzz <198366628+Rockynowzzz@users.noreply.github.com> Co-authored-by: AoHanBei <dongaohan21@gmail.com> Co-authored-by: evan188199-tech <evan188199@gmail.com> Co-authored-by: XZH <cto@xzh.ai> Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com> Co-authored-by: ZyPulse <sysu2752225139@gmail.com> Co-authored-by: OrdoAbChao <58732249+OrdoAbChao7@users.noreply.github.com> Co-authored-by: KennySimpson <70093673+KennyMcSimpson@users.noreply.github.com> Co-authored-by: Jinguang Gu <simongu@gmail.com> Co-authored-by: Mohammad Hijjawi <51020382+MohammadHijjawi97@users.noreply.github.com>
This commit is contained in:
@@ -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 ""
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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", ""),
|
||||
|
||||
@@ -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={
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
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
|
||||
|
||||
|
||||
@@ -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.");
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -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({
|
||||
|
||||
37
web/tests/learner-navigation.spec.tsx
Normal file
37
web/tests/learner-navigation.spec.tsx
Normal file
@@ -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"]);
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user