Commit Graph

1357 Commits

Author SHA1 Message Date
Bingxi Zhao (Frank)
bd80a4d28a release: v1.5.17
Partners stop being a deployment-wide admin resource and become
per-user: three nested rights (manage / use / neither) replace the
blanket admin gate on the router, each member can build and own their
own, and every person's conversations with a partner stay private to
their account. Grants keep working and now offer only admin-managed
partners. Channel runtime state moves from one directory per channel to
one per partner — copied, not moved, and only when its owner is
unambiguous — so two partners can finally run the same channel.

Around that: a knowledge base can track GitHub repositories and re-sync
their Markdown (#903); Antigravity CLI joins My Agents now that Gemini
CLI is retired (#828); personal WeChat signs in from a QR code drawn in
the browser instead of the server log (#951); a chat account can be
linked to a DeepTutor account with /link; containers re-apply the extras
they declare instead of losing them at compose down (#762); and
`deeptutor doctor` answers whether a workspace is ready to run (#959).

Reliability, largely from community PRs: embeddings survive a
rate-limited provider through key rotation, a retry budget and a global
throttle (#962); MinerU parsing and code execution work on Windows
(#844, #964); indexing fails bounded instead of hanging (#946); MinerU
page-layout blocks stop being indexed as content (#949); voice uploads
carry a MIME the transcription API accepts (#945); and reasoning effort
can be overridden per conversation (#641).

Release plumbing: notes in assets/releases/ver1-5-17.md, v1.5.13
archived, __version__ 1.5.17, README Releases row and all eleven
translations synced.

Two defects found by the release gate and fixed here:

- Six partner routes — the four channel-onboarding endpoints and both
  WeChat QR endpoints — kept the _auth-only mount they had inherited
  from the blanket admin gate, so any signed-in account could start a
  QR login for someone else's partner and write a bot token into its
  channel config. All six now declare _MANAGEABLE, and a sweep test
  asserts no {partner_id} route is left ungated.
- A configured api_key became `str | list[str]` when key rotation
  landed, but ten call sites pass it somewhere that takes one key; a
  list would have rendered into an Authorization header verbatim.
  keypool.primary_api_key reduces at each boundary.

Gates: pre-commit (all 15 hooks), ruff check + format, pytest
5276 passed, web 605 node tests, docs build.
v1.5.17
2026-08-25 02:24:35 +08:00
Bingxi Zhao
87ccedd549 test(partners): assert the admin gate by request, not by route internals (#983)
The admin-gate test from #952 read `route.include_context`. That attribute
only exists from FastAPI 0.141, where `include_router` stopped flattening the
sub-router into the parent app; before that the routes are copied onto
`app.routes` and there is no `include_context` at all. This project pins
`fastapi>=0.100.0` with no upper bound, so the test passed on CI (which
installs the latest) and raised `StopIteration` on any older satisfying
install — `5115 passed, 1 failed` locally on 0.135.1.

No structural assertion works across that range, so assert the actual
property instead: send a valid `role=user` token and require 403. A response
code does not care how the router is represented.

An unauthenticated request would not have been enough — `require_auth` alone
answers that with 401, so downgrading the router from `_admin` to `_auth`
would still have looked gated. With a real non-admin token, both weakenings
(`_admin` → `_auth`, and dropping the dependency entirely) let the request
reach the handler and fail the test. Also patches `AUTH_SECRET`, without
which `decode_token` rejects every token in a bare test environment and the
403 could never be distinguished from a 401.

Co-authored-by: Frank <bingxizhao@novix.science>
2026-08-24 17:54:04 +08:00
evan188199-tech
50f8ccbaa4 feat: split knowledge sync - add GitHub source sync (#903)
* feat(knowledge): add GitHub source sync

* fix(github-sync): contain downloaded paths inside the KB raw dir

Destinations were built as `raw_dir / rel` where `rel` is derived from the
GitHub tree/compare response — remote input. Two shapes escaped: a `..`
segment, and an absolute path, which is the quieter one because
`Path("/kb") / "/etc/x"` is `/etc/x`, silently discarding the base. The only
filters in the way checked the file extension and the glob, so a matching
path would have been written — and, on the removal branch, deleted — outside
the knowledge base.

git rejects both shapes in tree entries today, so this is defence in depth
rather than a live exploit; a downloader still should not delegate to the
remote the question of where it writes. One `_contained_dest` seam now guards
the full-sync write, the incremental write, and the removal, and logs what it
refused.

---------

Co-authored-by: XZH <cto@xzh.ai>
Co-authored-by: Frank <bingxizhao@novix.science>
2026-08-24 16:55:47 +08:00
Valor
efc4a3d3ca fix(rag): surface local LightRAG provenance (#754)
Co-authored-by: Valor <210239105+zrh805@users.noreply.github.com>
Co-authored-by: Frank <bingxizhao@novix.science>
2026-08-24 16:54:25 +08:00
Wong
1625cdd105 fix(embedding): survive provider rate limits — key rotation, retry budget, global throttle (#962)
* T028(Codex交付,ZC核验代提交): KeyPool多key轮换层(provider×model×key池·429冷却·单key兼容) · api_key/api_token字段兼容数组 · 三处接入(embedding/mineru/llm) · 图片描述gather+Semaphore并发化 · 303单测全过(含官方既有测试回归)

* FIX-EMB-429: 火山embedding 429根治(上游PR候选) · ①429重试按Retry-After等30s(滑窗等过) ②resolver从profile读batch_size/batch_delay(火山RPM极低必须限速) · 实测batch5/delay2s下语文reindex突破processing · 三key池x2冷却机制已验

* HARDEN-429: embedding限流重试1→8次+全冷却等待65s再取 · 单key池滑动窗口瞬时429不再报废数小时reindex整跑(08-22三烧教训) · 月度额度429仍8轮后raise不空转

* FIX-UNBOUND: 限流重试槽位for耗尽静默穿落到data引用 · 槽位1+max(MAX_RETRIES,10)兜住8轮限流 · t035镜像UnboundLocalError根因(逻辑走查复现)

* THROTTLE-GLOBAL: embedding跨实例全局节流锁 · 类级锁串行化'间隔+发帖'(多文档并行reindex各自client叠加超RPM=08-22历史库六烧终根因) · batch_delay升级为全局最小间隔 · 手动单发200而进程内全429的分歧由此闭合

* FIX-LOCK: 节流锁asyncio→threading · LlamaIndex _run_in_new_loop每线程新event loop,asyncio.Lock绑创建loop跨loop不互斥(根因三层剥洋葱终层) · 静态方法装饰修正 · 容器内3线程串行化实测2.01s通过

* PR-PREP: 中性化 fork 痕迹注释(中文→英文 provider 通用表述) · 上游v1.5.16已有_as_api_key数组支持,删我方重复实现保留上游版 · 测试148+86全过 · 密钥扫描分支历史+工作树双清(A类指纹0命中,B类28处=上游自带fixture)

* LINT: ruff format 6文件对齐CI(上游基线0债,全是我方引入) + import顺序修正

* FIX-CI: 图片处理块整体采纳上游v1.5.16版(_describe_image新签名+批量embed_contents) · 删越域的fork逐图并发测试(记档将来独立PR) · 592测全过

* FIX-CI: _build_openai_client合并壳与实现(上游sanitize保留+key池数组兼容) · placeholder_key改用primary_key(list哈希修复) · 889测全过

* fix(keypool): never refuse the only key

`KeyPool` is built even for a single-key config, and `next()` raised
`RuntimeError("All API keys are cooling down")` once every key was cooling.
For the common one-key setup that meant two 429s took every LLM and embedding
call down for the full 60s window — and it bypassed the rotation layer's own
429 handling entirely, since the RuntimeError surfaces before
`_KeyRotatingCompletions.create` can mark the strike and re-raise the real
provider error. `sdk_max_retries=0` had already handed retry duty to that
layer.

Cooling is a preference hint, not a circuit breaker: when everything is
cooling, return the key that recovers soonest and let the provider's own 429
surface to be retried.

The existing single-key test asserted the raise while calling itself
"keeps single key compatible" — it now pins the behaviour the name promises,
plus the soonest-recovery ordering for the multi-key case.

---------

Co-authored-by: interia <interia@interiadeMac-mini.local>
Co-authored-by: Frank <bingxizhao@novix.science>
2026-08-24 16:54:14 +08:00
落雨✦
6f0c7fdb47 fix: Windows MinerU parsing — subprocess UTF-8 decoding & render-thread crash (#844)
* fix: Windows robustness — MinerU UTF-8 decode, render-thread crash & atomic-write PermissionError

- mineru/local.py: pass encoding="utf-8", errors="replace" to subprocess.Popen so MinerU's combined stdout/stderr is decoded as UTF-8 instead of the platform default (GBK on zh-CN Windows), which previously crashed with a UnicodeDecodeError (0x8b).
- mineru/models.py: set MINERU_PDF_RENDER_THREADS=1 in model_env_overrides to avoid MinerU's multi-threaded PDF rendering heap-corruption crash (0xc0000409) on Windows.
- services/file_io.py: retry atomic replace on transient PermissionError (e.g. target locked by antivirus/indexer) with exponential backoff, instead of failing the whole write on Windows.

* fix(mineru): gate the render-thread guard to Windows

`MINERU_PDF_RENDER_THREADS=1` was set unconditionally, but the variable is
honored on Linux and macOS too (upstream default 3-4 render workers), so a
Windows-only heap-corruption workaround was serializing page rendering for
every platform. It also sat in `model_env_overrides`, whose contract is the
model-weight download source — and adding a key there broke that function's
exact-equality test.

Move it to its own `render_env_overrides()` next to the other MinerU env
knowledge, guarded on `sys.platform`, and merge it into the subprocess env at
the local-CLI branch in `backend.py`. Only that branch renders pages in this
process tree; cloud mode never does.

---------

Co-authored-by: Frank <bingxizhao@novix.science>
2026-08-24 16:54:05 +08:00
john00010
dcbb1d3393 fix(sandbox): support Windows code execution (#964)
* fix(sandbox): support Windows code execution

* refactor(sandbox): vary only the shell clause in the workspace note

The Windows branch duplicated the whole workspace paragraph, so the note
existed in four near-identical copies (zh/en x posix/windows) that would drift
apart on the next edit. Only the "how do I get a script into a file" clause
actually depends on the host shell, so vary that clause and keep one template
per language.

Also prefer `pwsh` (PowerShell 7+) when it is on PATH — it defaults to UTF-8
and is the version still receiving updates; the generated commands are written
in 5.1-compatible syntax, which 7 accepts too. And hoist `import sys` to module
scope now that two methods need it.

Adds the tests this note never had: each host gets the syntax that works there
(a Bash heredoc is a syntax error in PowerShell, and the model would silently
produce no file), and the host-independent half stays byte-identical.

---------

Co-authored-by: Frank <bingxizhao@novix.science>
2026-08-24 16:52:04 +08:00
ZQR1101
7edddbec61 fix(web): pin chat to late-mounted quiz cards (#960)
* fix(web): pin chat to late-mounted quiz cards

QuizViewer loads after the 4s post-stream scroll window, so mastery quiz cards stay below the fold until the user scrolls. Watch [data-chat-grow] for 12s without re-pinning unrelated details expands.

Related to #955

* fix(web): extend the existing post-stream window for late viewers

The post-stream effect already existed for exactly this case — its comment
names QuizViewer — so a second, parallel MutationObserver with its own 12s
window meant two observers racing for the same pin, each unaware of the
other's deadline.

Fold the extension into that one effect: the window starts at 4s and only a
*newly appearing* ``[data-chat-grow]`` node pushes it out to 12s. Gating on
appearance rather than presence matters — presence alone is satisfied
permanently by any quiz card from an earlier turn, which would have re-pinned
the user on every later DOM mutation, the precise mis-classification the
short window exists to avoid. The teardown timer follows the current
deadline, so a turn with no late viewer stops observing at 4s as before.

---------

Co-authored-by: ZQR1101 <278034003+ZQR1101@users.noreply.github.com>
Co-authored-by: Frank <bingxizhao@novix.science>
2026-08-24 16:52:00 +08:00
0xTidalBore
8d6a6e3a59 fix(llamaindex): fail bounded when indexing stalls (#953)
* fix(llamaindex): fail bounded when indexing stalls

Indexing steps run in a sync executor thread. An embedding provider that
accepts a request but never completes it can stall the executor future
forever: HTTP timeouts only bound a single attempt and provider retries
extend the wait far beyond any reasonable budget. Add a stall guard that
watches the embedding progress heartbeat and raises a clear error once no
progress has been reported for a bounded window (default 10 minutes),
instead of hanging indefinitely.

Fixes #946

* fix(rag): re-arm the stall heartbeat each poll tick

`set_progress_callback` writes to the process-global LlamaIndex `Settings`
embed model, which holds exactly one callback slot. A second indexing job
started while the first runs displaced the first job's heartbeat, so its
`last_progress` stopped advancing and the guard raised `IndexingStallError`
against a job that was indexing normally — turning what used to be merely
lost progress reporting into a hard failure.

Reclaim the slot on every poll tick. Missing a few notifications for one
tick is harmless; never observing our own progress again is not. The guard is
now consciously biased toward false negatives: it can be slow to notice a
genuine stall while another job indexes, and never fails a job that is
making progress.

---------

Co-authored-by: 0xtidalbore <ahmed@itcloud.ca>
Co-authored-by: Frank <bingxizhao@novix.science>
2026-08-24 16:51:56 +08:00
ZQR1101
ac25a5c868 fix(voice): strip MediaRecorder codec params from STT uploads (#948)
* fix(voice): strip MediaRecorder codec params from STT uploads

Chrome sends audio/webm;codecs=opus; OpenAI-compatible transcription APIs reject that as an unknown format.

Fixes #945

* refactor(voice): normalize the STT MIME once, at the wire boundary

The codec-parameter strip was applied at four layers: the recorder hook, the
route, the `transcribe_audio` facade, and `_post_multipart`. Only the last of
those decides what actually goes on the wire, and `openai_compat` is the sole
registered STT adapter, so the two middle copies were pure duplication —
and they made the route's contract ambiguous about who owns the value.

Keep the client-side strip (it sets the Blob type, which is what the browser
puts in the multipart part) and the adapter strip; drop the route and facade
copies along with the now-unused facade re-export. The adapter-level test
already pins the wire contract; the route test now asserts what the route
actually promises — verbatim forwarding.

---------

Co-authored-by: ZQR1101 <278034003+ZQR1101@users.noreply.github.com>
Co-authored-by: Frank <bingxizhao@novix.science>
2026-08-24 16:51:49 +08:00
pederbe
9be3b0cf59 feat(cli): add setup doctor command (#959) 2026-08-24 16:51:44 +08:00
pederbe
1e99da1a93 fix: reject duplicate mastery quiz options (#956) 2026-08-24 16:51:36 +08:00
WeiNing-sara
8333c0b562 fix(cli): declare missing standalone runtime dependencies (#954)
* fix(cli): declare standalone runtime dependencies

* style: satisfy ruff format in the packaging metadata test

`ruff format --check .` is a CI gate and wanted the `open("rb")` call on one
line (99 chars). This was the only red check; every test job passed.

---------

Co-authored-by: Frank <bingxizhao@novix.science>
2026-08-24 16:51:31 +08:00
NoxsMedia
6bc366e567 fix(rag): filter MinerU page-layout blocks before indexing (#949)
* fix(rag): filter MinerU page-layout blocks before indexing

* fix(rag): preserve MinerU decision audit history

* fix(rag): index unrecognized MinerU blocks instead of failing the ingest

`require_accepted()` ran on the live ingest path and raised on any block type
without a policy entry, so a MinerU release that renames or adds a type broke
LightRAG indexing outright — where before this policy existed the block was
simply indexed. `V2_AUXILIARY_EQUIVALENTS` made that concrete and worse: it
recorded the knowledge that a newer parser emits `page_header`/`page_footer`/
`page_aside_text`, wrote it into the audit ledger, and then hard-failed on
exactly those values, because the map was never applied to anything.

Two changes, same principle — filter only what is positively recognized as
page chrome:

- Apply the v2 map. Newer auxiliary names normalize onto the vocabulary the
  policy is written in, so upgrading MinerU keeps filtering chrome instead of
  reporting every layout block as unrecognized. Parser blocks stay unmutated;
  only the classification key is normalized.
- Unknown types are indexed and counted, never dropped and never fatal. An
  unrecognized type is far more likely to be new content than new chrome, so
  the failure mode of guessing wrong should be an unclassified block in the
  index, not a dead knowledge base. The ledger records the count (and only
  the count — document text must never reach an audit file), the pipeline logs
  a warning naming the types, and the attempt outcome `unknown_types` says
  the policy needs extending.

---------

Co-authored-by: nox <work@noxsmedia.com>
Co-authored-by: Frank <bingxizhao@novix.science>
2026-08-24 16:35:00 +08:00
evan188199-tech
c72185aad6 fix(rag): improve local LlamaIndex pipeline compatibility (#864)
* fix(rag): improve local pipeline compatibility

* fix(rag): resolve tqdm progress at call time, not at import

`show_progress: bool = should_show_progress()` is a default argument, so
Python evaluated it once when the module was first imported and froze the
result for the process lifetime. That defeated the fix in both directions:
a server started from a terminal froze `True` and kept writing tqdm bars
into the pipe whose read end can close mid-indexing (the BrokenPipeError
this guards against), while a CLI launched with piped stdout froze `False`
and never showed progress again.

Take `show_progress: bool | None = None` and resolve inside the body of the
two functions that consume the value; the pure forwarders pass `None`
through so the decision is made once, at the point of use.

The accompanying test was green only because pytest captures stdout, so the
frozen default already read `False` — it never exercised the mechanism. It
now asserts both directions and fails under `pytest -s` if the default
argument comes back.

---------

Co-authored-by: XZH <cto@xzh.ai>
Co-authored-by: Frank <bingxizhao@novix.science>
2026-08-24 16:34:55 +08:00
Ademola Balogun
e4dda9ff77 feat: add per-conversation reasoning-effort override (#641) (#958)
* feat: add per-conversation reasoning-effort override (#641)

* refactor(config): parse the LLM selection once

`apply_llm_selection_to_catalog` already calls `LLMSelection.from_payload`,
so resolving the override parsed the same payload a second time — meaning a
malformed `reasoning_effort` was validated and raised from two places.
`from_payload` is idempotent on an already-parsed value, so parse once and
pass the object through.

Also correct the `VALID_REASONING_EFFORTS` comment: it called itself the
single source of truth while pointing at two things that are not the same
vocabulary. `reasoning_params.py` maps a level onto a provider's actual knob,
and the per-backend `efforts` lists say what each subagent CLI accepts (some
are empty — no effort flag at all). This constant is only the
request-validation union.

---------

Co-authored-by: Ademola <ademicho@gmail>
Co-authored-by: Frank <bingxizhao@novix.science>
2026-08-24 16:34:50 +08:00
evan188199-tech
ec4ee2356a feat(partners): add QR channel onboarding (#952)
Co-authored-by: XZH <cto@xzh.ai>
2026-08-24 16:34:29 +08:00
Bingxi Zhao (Frank)
8515dfdbe6 release: v1.5.16
Release notes: assets/releases/ver1-5-16.md

Content bundled into this commit:

* Release notes for v1.5.16 and the version bump to 1.5.16.
* README: the Releases row for v1.5.16, and MarginNote 4 added to the two
  places that enumerate the retrieval engines (Key Features, Knowledge
  Center) — the engine list was the only prose the release made stale.
* All 11 translated READMEs patched for that same engine-list change.
* Book: make the reader's row a flex column. v1.5.15 added the capture
  inbox as a second child without it, so `PageReader`'s `h-full`
  collapsed to `auto` — the body stopped scrolling and the page-turn
  footer was clipped away.
* progress_tracker: annotate the progress dict as `dict[str, object]`.
  The i18n work added a dict-valued `message_params` to a mapping mypy
  had inferred as `dict[str, int | str]`.
* prettier on the two MarginNote 4 frontend files it had not yet seen.

Gates: pre-commit (15/15), `ruff check .` clean, pytest 5007 passed /
22 skipped, `npm run test:node` 586/586, and the docs site builds.
v1.5.16
2026-08-22 01:36:30 +08:00
Bingxi Zhao (Frank)
323c4d6e7a feat(knowledge): surface MarginNote 4 in the Knowledge Center grid
The connected source only existed inside the create modal's link list, so
the Knowledge Center home offered Obsidian as something you can connect
and said nothing about MarginNote. Anyone who did not already know to
open the modal and switch to "Link existing" had no way to find it.

Give it the card Obsidian has, in the same place and with the same
behaviour: the connected-library count when there is one, and a click
that opens the unified create flow pre-set to this source.
2026-08-22 00:08:30 +08:00
Bingxi Zhao (Frank)
081a73a15c fix(marginnote4): stop two libraries from claiming one store
Registration checked the name and nothing else, but the default store
path keeps only alphanumerics, `-` and `_`, so "My Lib" and "My/Lib" both
resolve to My_Lib.db. Two libraries sharing that file would merge their
objects, and a device paired to either would sync into both.

Reject at registration instead, naming the library that already owns the
store. The same check covers an explicitly pinned `db_path` pointing at
another library's file.
2026-08-21 23:03:41 +08:00
Bingxi Zhao (Frank)
2af5ba7abf feat(knowledge): give MarginNote 4 libraries a frontend
The connected KB type landed with no way to create one and no way to
pair the add-on that fills it, so the feature was unreachable from the
app.

Connecting: a MarginNote card in the create modal's link sources. It
asks for a name and nothing else — `db_path` is deliberately not sent, so
the store's location keeps one rule and pairing, the add-on's syncs and
the capability binding cannot disagree.

Feeding it: a Devices tab on the library, with the paired-device list,
revoke, and the one-time token shown once at pairing (the server keeps
only a hash). Every call names its library through `X-MN4-KB`, which is
what makes the token findable by the syncs that present it.

The detail view's sections are now derived rather than fixed: a library
owns no raw files and builds no index, so Files / Add documents / Index
versions rendered empty against it, the header read "llamaindex ·
Default embedding" for a pipeline it never runs, Settings offered an
on-disk path that does not exist, and Retry indexing offered to re-run
nothing. Each now reports what the library actually has.
2026-08-21 22:51:05 +08:00
Bingxi Zhao (Frank)
0989dcbbd9 fix(marginnote4): one rule for where a library's store lives
"Pinned `db_path`, else derived from the name" was written twice — in the
capability binding and, in its derived half only, in the HTTP bridge. A
KB that pinned a path therefore paired devices into one file while the
tools read another, so the add-on would have synced into a store nothing
queried. `resolve_db_path` is now the single rule, and the binding, the
pairing endpoints and the device endpoints all go through it.

Deleting the KB now removes that store. Unlike an Obsidian vault it is
ours — `data/user/marginnote4/<name>.db`, created by us — so leaving it
behind both contradicted what the delete says and resurrected every
paired device as soon as a library of the same name was connected again.
Best-effort, on the same reasoning as the index directory above it: an
orphan file beats a config entry stuck in the list.
2026-08-21 22:50:55 +08:00
Bingxi Zhao (Frank)
10297532b5 feat(knowledge): make indexing progress lines translatable
Every progress line the knowledge log box shows was a hardcoded English
string — 22 producers across the initializer, the document adder and the
router, rendered verbatim in the UI. #933 added one more ("Describing
images: m/n"), which is what surfaced the class.

Indexing runs detached from any request, so the backend has no viewer
language and the language of record lives in the browser anyway. So the
wire now carries the English `{{name}}` template plus its values, and the
frontend renders it with `t()` where the language is actually known.
`ProgressTracker.update` fills `message` from that same template, so
every consumer without i18n of its own — logs, the persisted snapshot,
the CLI — reads what it read before, and no call site spells the string
twice.

Untouched producers keep working: `progressMessage()` falls back to the
rendered `message` when no template is named.
2026-08-21 16:58:42 +08:00
Bingxi Zhao (Frank)
ac18b75056 docs(llm): name two contracts the LightRAG convergence relies on
Both were load-bearing and neither said so.

`map_error` returns an existing `LLMError` *itself* rather than a
replacement — re-running the rules would demote a precise error to a
vaguer one, and the LightRAG adapter re-raises the terminal exception and
compares identity. That makes filling in `provider` an in-place write on
the caller's exception; it is the only field the function mutates.

The vision adapter passes `allow_image_fallback=False`, which is a
behaviour change rather than a tidy-up: a model that turns out not to
take images no longer gets a text-only retry. That fallback salvages an
answer elsewhere, but here the image *is* the question, so a description
produced without it would be invented and then indexed as fact.
2026-08-21 16:58:01 +08:00
Bingxi Zhao (Frank)
48ba9d405c fix(chat): bound the provider error body written to the log
The tool-schema rejection log exists so a user can attach
`deeptutor.jsonl` to a bug report. `error_text()` returns the whole body,
and some providers echo the rejected request back — the tool schemas,
sometimes the messages — which would put a copy of the conversation into
a file headed for a public issue.

`logged_error_text()` caps it and says how much it dropped. The parameter
a provider objects to is always near the front, so the diagnostic keeps
working; the compat predicates keep reading the unbounded text.
2026-08-21 16:58:01 +08:00
Bingxi Zhao (Frank)
f58654e0bf fix(marginnote4): close the device bridge's auth boundary
`/sync` and `/heartbeat` are the only endpoints reachable without a
DeepTutor session, and both resolved their store before checking the
credential. Two consequences:

- Constructing a `MarginNoteStore` mkdir's and installs the schema, so an
  unauthenticated `POST /sync` created a database per distinct `X-MN4-KB`
  value. `MarginNoteStore.open_existing` gives the device path a way to
  look without writing; no file, no store, 403.
- Pairing runs under `require_auth` and lands in the caller's own
  workspace, while the device endpoints carry no session and resolve the
  default one. Wherever those differ the token issued at pairing could
  never be found again, so every sync 403'd forever. Both paths now name
  the workspace they mean through one resolver, and pairing refuses
  rather than hand out a credential the sync path cannot read.

Also bound one batch (`objects` / `deleted_ids` / `cursor` / device
name), and promote `_default_db_path` to `default_db_path` since two
other modules already import it across the package boundary.
2026-08-21 16:57:45 +08:00
Bingxi Zhao (Frank)
083ff4fe3d fix(docker): give the development image the web source it compiles from
`docker compose -f docker-compose.dev.yml up` came up with a dead frontend:
the development stage's supervisor program runs `node scripts/dev.mjs`, and
that path does not exist in the image. The stage builds `FROM production`,
whose ./web is `.next/standalone/`, then cherry-picked three files on top.

Verified against a real standalone build — its root holds exactly
`server.js`, `package.json`, a traced `node_modules` and the dist dir. Every
source file and every config is absent, so `scripts/` was only the first
thing to fail; `tsconfig.json`, `tailwind.config.js`, `postcss.config.js`,
`features/`, `types/` and `proxy.ts` were missing too, and the compose mount
list covers none of them either.

So take the builder's web tree wholesale instead of naming files that keep
drifting as web/ grows top-level entries. `--chown` during the copy keeps
node_modules from being re-layered, and the inherited production build is
cleared so `next dev` starts from an empty cache rather than a half-valid
one.

#906 also reported this as two `[program:frontend]` blocks in one supervisor
config, with the fix being to delete the dev.mjs one. That reading is wrong:
the blocks are in different build stages (`FROM production AS development`),
the production image has exactly one and is unaffected, and deleting the dev
block would have made the development image serve a production build with no
hot reload. The production stage is untouched here.

Not build-verified — no Docker daemon available on this machine.
2026-08-21 16:29:06 +08:00
Bingxi Zhao (Frank)
c4a6f1b228 fix(embedding): recover from gateways that require an explicit encoding_format
ModelScope reads a missing `encoding_format` as `''` and refuses the request:
`encoding_format must be 'float' or 'base64', got ''`. So the probe and every
real embedding call failed for #934, while the same config worked through the
vendor SDK, which defaults the field to "float".

The report's root cause is right and its suggested fix keys off the wrong
thing. Special-casing the qwen3-embedding family reads the constraint as
belonging to the model, but it belongs to the gateway, and the gateways
disagree: SiliconFlow rejects the param when it is *present* (#651, which is
why it is omitted), ModelScope when it is *absent*. The same Qwen3-Embedding
weights are served on both sides of that disagreement, so no default and no
model-family rule can satisfy both.

Recover from the provider's own refusal instead. The happy path is
byte-identical — the param is still omitted, so every working config sends
exactly what it sent before — and a 400 that names both the parameter and the
value we are about to send earns one retry with `encoding_format="float"`.
Requiring the body to name "float" is what separates "you must send this"
from "I do not support this", so a gateway in the second camp is not retried
into the same failure. The retry is bounded by the param then being present.

Also notes at the omit site why a default must not be reintroduced there:
it would trade #934 for #651.
2026-08-21 16:25:18 +08:00
Bingxi Zhao (Frank)
f2fac28d7b fix(llm): resolve model-intrinsic overrides from the model, not the route
Kimi models lock temperature server-side and reject any explicit value with
HTTP 400 "invalid temperature: only 1 is allowed for this model". The
moonshot spec has dropped the parameter for them since before v1.5.5, but
the lookup ran over the *configured binding's* spec, so it only fired for
someone who had picked binding="moonshot". #938 picked binding="openai" and
pointed it at Moonshot — what most people do with an OpenAI-compatible
endpoint — and kept getting the 400 two months after the fix landed.

The route is not what enforces the limit, so the route should not be what
decides. `model_overrides_for` states that once: the configured spec wins
when it says something about this model, otherwise the model's own vendor
spec answers. `find_by_model` already skipped gateway and local entries, so
it lands on the vendor whose API enforces the limit; it was simply never
consulted on this path.

This generalises past kimi — every model-intrinsic override was being lost
behind a generic gateway binding, and a spec-less config got none at all.

The override had no test, which is how it stayed half-wired. The added ones
are written as the reporter's scenario, and pin the two things that must not
break: an explicit binding still wins, and the tunable moonshot-v1-* series
(no "kimi" in the name) keeps the caller's temperature.
2026-08-21 16:22:58 +08:00
Bingxi Zhao (Frank)
9e4233c3ae fix(chat): assign streamed tool-call ids instead of appending them
A router in front of an OpenAI-compatible provider re-sends the complete
`id` on every delta chunk rather than only on the first. The chat loop and
the explore capability appended it, so the id grew one copy per chunk —
#937 observed 551, 754, 870, 1566, 9715, 17864 and 47241 characters. Past
the provider's own 64-character ceiling every round died with HTTP 400
`Invalid 'messages[i].tool_calls[0].id': string too long`, the
forced-finish call died the same way, and the turn surfaced as "I could not
produce a useful response from the model output."

The report named one site and declared `name` correct as-is. There were two
sites, and both had the identical defect on `name`, which a repeat corrupts
into an unresolvable `toolnametoolnametoolname` — latent for that
reporter's gateway, fatal for any gateway that repeats the name.

Rather than restate the per-field rule a third and fourth time, converge
the three core-layer sites (chat loop, explore capability, labeled step)
onto one accumulator that states it once: `id` and `name` arrive whole and
are assigned, `arguments` arrives in fragments and is concatenated. That
rule is not new — it is what the services-layer provider's `_accum_tc` has
always done, which is the evidence that assigning `name` is safe across
every gateway users have configured. That accumulator stays where it is:
it reads deltas that may be plain dicts, so folding it in would widen the
blast radius without fixing anything.

Coercing a missing `index` to 0 also removes a latent crash in the labeled
step runner, where a `None` key made the final `sorted()` raise as soon as
one real index appeared.
2026-08-21 16:20:13 +08:00
Bingxi Zhao (Frank)
23ead9e6d6 docs(book): reflow the partition_knowledge_bases docstring 2026-08-21 16:13:21 +08:00
evan188199-tech
1413cd8ed0 feat(knowledge): add MarginNote 4 as a connected knowledge base (#931)
* feat(marginnote4): add connected KB type, read-only tools, and sync bridge

Add MarginNote 4 as a connected knowledge base type that syncs study data
(notes, excerpts, cards, mindmap nodes) from MN4 via the official Add-on API
into a dedicated SQLite store, then exposes it to the chat loop through seven
read-only tools.

New package: deeptutor/capabilities/marginnote4/
- models.py: MarginNoteObject, SyncBatch, PairedDevice, LearningEvent
- store.py: SQLite CRUD + search + device pairing with hashed tokens
- binding.py: per-turn resolution of the selected MN4 library
- tools.py: search, read, list, documents, links, tags, cards
- capability.py: KnowledgeCapability (exclusive turn ownership)
- prompts/{en,zh}/system.md

HTTP bridge: deeptutor/api/routers/marginnote4.py
- POST /pair (session auth) -- register a device, get one-time token
- POST /sync (device-token auth) -- incremental upsert + tombstones
- POST /heartbeat (device-token auth) -- liveness + object count
- GET /devices, DELETE /devices/{id}, GET /status (session auth)

Integration points:
- kb_types.py: MARGINNOTE4_KB_TYPE added to CONNECTED_KB_TYPES
- manager.py: db_path surfaced in get_metadata allowlist
- registry.py: MarginNoteCapability registered in LOOP_CAPABILITIES
- builtin/__init__.py: MARGINNOTE_TOOL_TYPES in BUILTIN_TOOL_TYPES
- api/main.py: router mounted at /api/v1/marginnote4

Phase 1 scope: device pairing, read-only sync, tool navigation.
Write-back (propose/apply/verify), learning events, and mastery bridge
are planned for Phase 2-3.

Refs: #756 (Obsidian external knowledge source pattern), #180

* fix(marginnote4): search scope, store caching, prompts, KB registration

Testing and experience improvements:

- Search now includes document_title in scope: searching for a textbook
  name returns results instead of zero hits
- Store instances cached by db_path so schema init runs once, not per
  tool call within a turn
- object_type parameters carry enum constraints so the LLM knows valid
  types without guessing
- System prompts (en/zh) rewritten with domain context: explains the
  five object types, link traversal strategy, and citation guidance
- KB registration: register_marginnote4_kb manager method +
  /connect-marginnote4 API endpoint, mirroring the Obsidian connect flow
- Fix indentation inconsistencies in manager.py and main.py
- New tests: document_title search scope, KB registration (create,
  default path, duplicate rejection)

65 tests pass, 0 regressions, ruff clean.

* style(marginnote4): apply repository formatter

* fix(marginnote4): keep MN4 libraries out of the rag_search sweep

``MARGINNOTE4_KB_TYPE`` joined ``CONNECTED_KB_TYPES`` but not
``NON_RETRIEVABLE_KB_TYPES``, so ``supports_rag_retrieval`` answered true
for a library that has no index and no retrieval API — its objects live
in ``mn4_objects`` and are reachable only through the seven
``marginnote_*`` tools. Book's source explorer would have swept it,
gotten nothing back, and reported it as a source with no relevant
content rather than one that needs its own tools.

MN4 belongs with ``obsidian`` and ``subagent``, not with ``linked`` /
``lightrag_server`` / ``ima``, which do resolve to an index or an HTTP
retrieval API. Tests pin both halves of that split, since collapsing it
the other way has cost Book its connected sources before.

---------

Co-authored-by: XZH <cto@xzh.ai>
Co-authored-by: evan <evan@dazongguandeMac-mini.local>
Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com>
2026-08-21 16:10:22 +08:00
Srini Jagadeesh
ef97983814 fix: log provider error body on tool-schema rejection fallback (#930)
* fix: log provider error body on tool-schema rejection fallback

AgentLoop._create_response_stream silently strips tools and retries
when a provider rejects the native tool schema, discarding the raw
error body. That's the missing diagnostic in #708 (gpt-5.6-luna/
-terra/-sol lose all tool-calling): the fallback trips, the model
degrades to prose, and there is no record of what the provider
actually rejected.

Log the body via the existing error_text() helper before falling
back, so the next report includes the exact rejection payload.

* style: satisfy ruff format on the tool-schema rejection log

---------

Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com>
2026-08-21 16:10:17 +08:00
LamXwah
e7dead14f9 fix(chat): prune deleted knowledge base references from sessions (#936)
* fix(chat): prune deleted knowledge base references from sessions

* style(chat): drop the unrelated reformat from the KB-pruning change

ChatMessages.tsx arrived with ~50 lines of prettier output that the fix
does not need: `.map()` arrow bodies unwrapped for bookReferences,
notebookReferences, historyReferences and memoryReferences, plus a union
type joined onto one line. `dev` does not follow prettier for this file
(`prettier --check` flags it on `dev` too), and CI gates neither prettier
nor tsc for web, so the churn would have landed silently.

Restore those hunks and keep only what threads `availableKbNames`
through: the two prop declarations, the two destructures, the pass-down,
and the `.filter()` in front of the knowledge-base context items. The
remaining reindent inside that `.map()` is intrinsic to inserting the
filter ahead of it.

---------

Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com>
2026-08-21 15:58:26 +08:00
NoxsMedia
7411315b6b fix: converge LightRAG transport failures and cancellation (#940)
* fix: bound LightRAG adapter retries

* fix: harden LightRAG retry boundaries

* fix: propagate Codex transport failures

* fix: converge LightRAG cancellation cleanup

---------

Co-authored-by: nox <work@noxsmedia.com>
2026-08-21 15:42:39 +08:00
LamXwah
965885b760 fix(rag): parallelize image descriptions in the LlamaIndex RAG pipeline with timeout and progress (#933) 2026-08-21 15:42:34 +08:00
Bingxi Zhao (Frank)
31bf66b5e1 release: v1.5.15
Self-hostable PageIndex, a fileable question bank, and third-party plugins.

- PageIndex: adds PageIndex OSS as its own knowledge-base type, bound to
  the base's local library and driven by the configured LLM rather than a
  PageIndex API key. Retrieval moves off the built-in MCP server (removed)
  onto a workflow-owned reading loop that walks the document tree.
- Question bank: addEntryToCategory shipped in v1.3.6 and was never called
  from the frontend, so categories could be created but never filled. The
  quiz card now uses the shared CategoryMenu, the page is rebuilt around
  search / batch selection / an unfiled inbox, and a new question_bank tool
  lets the tutor file questions instead of misrouting them to write_note.
- Plugins: deeptutor.plugins was imported behind a try/except but the
  module never existed — implemented, plus a deeptutor.loop_capabilities
  group so third-party packages can register chat-loop capabilities.
  Builtins win on name collisions; broken entry points are skipped.
- Parsing: remote Apache Tika engine (TIKA_SERVER_URL), with no local
  package and no model download.
- LightRAG: the three indexing knobs from #877 get inputs under their own
  Indexing divider; unsupported keywords are dropped with a warning.
- Knowledge bases: uploads take a destination folder, same-named documents
  from different subtrees stop dropping one another, and linked folders
  keep their source-relative structure — closing #866.
- Book: a learning-capture inbox with an explicit status lifecycle, and
  drift warnings scoped to the KB documents that actually changed.
- Whisper: /whisper moves out of the primary nav into Learning Space →
  More Projects, credited to its contributor; the room needs its own
  capability package. The reusable half is CAPABILITY_COMPLETE forwarding
  of a capability-declared body and its declared extras.
- README: a Collaborate badge beside the Docs badge, in all twelve
  languages.
- Lint: nosec B608 on four false-positive question-bank queries (literal
  fragments only, every value bound), and three mypy fixes.

Release notes: assets/releases/ver1-5-15.md
v1.5.15
2026-08-20 14:15:53 +08:00
Bingxi Zhao (Frank)
1f4de01e70 fix(whisper): make the page's copy translatable
The /whisper surface shipped with 23 hardcoded strings — 22 English plus one
literal 结束 on the End-session button — so it rendered the same words whatever
language the user had chosen. A Chinese user got an English page with one
Chinese button; an English user got "结束". None of the four files even imported
useTranslation.

Route all of it through t() and add both locales. Two details worth naming:

* The session-id label reuses no generic key. `session` already exists as the
  Chinese counter suffix ("3 个会话"), so a bare t("session") would have rendered
  "个会话 abc12345…". It is now an interpolated "Session {{id}}".
* "Whisper" was already translated as 密语 for the sidebar, so the new strings
  use that term rather than introducing 耳语 beside it.

The Chinese literals left in page.tsx are protocol, not copy: it sends 结束 as
psych-academy's is_end_command and matches the room-ended text the capability
streams back. The new test says so, and checks the rest — every t() key present
in both locales, the zh side not echoing English, no CJK copy in the components.
2026-08-20 01:46:19 +08:00
Bingxi Zhao (Frank)
38b056fced ci: run eslint on the frontend
The web job ran the node tests but never linted, so #921 merged with two real
React violations in it — a predicate named like a hook, which tripped
rules-of-hooks, and a synchronous setState inside an effect. Both were invisible
to every gate the repo had.

Errors only: `npx eslint .` exits 0 on the 79 warnings the tree still carries
(i18n literals, next/image suggestions), so this starts catching the class of
bug that just slipped through without demanding an unrelated cleanup first.
2026-08-20 01:46:19 +08:00
Bingxi Zhao (Frank)
49d8d1bd63 docs(book): state what actually makes BookStorage's writes safe
The class carried an ``asyncio.Lock`` that nothing ever acquired — every method
here is sync, so it could not be — which read as protection the store did not
have. #926 then added a read-modify-write helper next to it, and the natural
question was whether concurrent captures could lose one.

They cannot, and the reason is worth writing down rather than re-deriving:
DeepTutor serves from a single process with no worker fan-out, both capture
routes call this store synchronously with no ``await`` between their read and
their write, so the sequence holds the event loop end to end, and every write
lands through an atomic replace.

Replace the unused lock with that invariant, plus the two changes that would
break it (``asyncio.to_thread``, multiple workers) so the next person adding
either knows locking has to come first.
2026-08-20 01:46:19 +08:00
Bingxi Zhao (Frank)
4a68ccea1e feat(knowledge): expose LightRAG's indexing knobs in the engine settings
#877 landed the three indexing knobs in runtime settings and the API, but
the settings page never grew inputs for them, so they were reachable only
by editing the config by hand. The knobs sit under their own Indexing
divider because they are a different axis from the query knobs above:
they shape how a knowledge base is built, so a change applies to the next
build rather than the next question.
2026-08-20 01:32:35 +08:00
Bingxi Zhao (Frank)
83c13ccc1f docs(assets): refresh the guide screenshots for the current UI 2026-08-20 01:30:28 +08:00
Bingxi Zhao (Frank)
b471160680 refactor(web): rebuild the question bank and fix filing from a quiz card
addEntryToCategory shipped in v1.3.6 and was never called from the
frontend, so a learner could create categories but never put anything
in them. The quiz card's bespoke dropdown is replaced by the shared
CategoryMenu that does call it, and the bank page is rebuilt around the
three things the flat list could not do: search, batch selection, and
an inbox for questions nobody has filed yet.
2026-08-20 01:30:28 +08:00
Bingxi Zhao (Frank)
b71aef2b5b feat(mastery): carry explanation and difficulty into the question bank
A mastery attempt reached the bank as a bare right/wrong, reviewable
only as a score. mastery_quiz now takes both fields, held server-side
like expected_answer so neither leaks onto the card being answered, and
the sync writes them through. An unrecognised difficulty is dropped
rather than rejected — a mislabelled badge must not cost the learner a
question.
2026-08-20 01:29:55 +08:00
Bingxi Zhao (Frank)
2503c2ccc4 feat(tools): add a question_bank tool so the tutor can file questions
Asking the tutor to group wrong answers had no writable handle on the
bank, so it reached for write_note and the request silently became a
notebook record — the zh write_note hint even listed 错题分析 as a
reason to append. The new tool is name-addressed: organize takes a
category name and creates it when missing, so filing is one call after
one listing. Auto-mounted only when the bank has entries, and both
write_note hints now point categorisation at it.
2026-08-20 01:29:55 +08:00
Bingxi Zhao (Frank)
83b5db6cbb feat(api): add question-bank listing filters and an entries probe
The bank page could only ask for a flat page of entries, so search,
category views and the unfiled inbox had nowhere to come from. Filters
arrive as a QuestionBankQuery value object rather than more positional
parameters: the store's _run helper only forwards positional args, so
every past filter meant threading another parameter through three
layers. Same-batch upserts share a timestamp, so ordering falls back to
the row id to keep pagination stable.

has_question_bank_entries() is the auto-mount gate the question_bank
tool needs.
2026-08-20 01:29:55 +08:00
Bingxi Zhao (Frank)
ea8e271fdc feat(knowledge): choose which KB folder an upload batch lands in
The last piece of #866. #899 stopped a linked folder's subdirectories from
collapsing, and same-named documents no longer overwrite or vanish — but the
reporter's actual workflow still could not rebuild his tree. He added one
subtree at a time, and a browser folder pick reports each file's path
relative to the chosen directory: `应用开发/钉钉CLI/` arrives as
`钉钉CLI/...`, with no way to say it belongs under `应用开发/`. Every batch
piled up at the KB root, and the ancestor was not missing data — it was
never in the payload.

Uploads now take an optional destination folder, composed ahead of each
file's own relative path. The picker offers the KB's existing folders (and
its root, the default) once files are staged, so batching a large tree is a
matter of picking where each part goes. It runs through the same
_sanitize_rel_subdir guard as a directory upload's own path, so a crafted
value cannot escape raw/.

Listing folders is best-effort: if that call fails the picker simply does
not appear and the batch goes to the root exactly as before.

Linked-folder sync keeps its own root-relative staging and does not take a
destination prefix yet — that needs the prefix persisted per linked folder
in metadata, which is a separate change.
2026-08-20 00:56:34 +08:00
Bingxi Zhao (Frank)
7cc213f24d fix(chat): end a stuck session load in a retryable state
#923 fixed the blank transcript in #912 — an orphaned message tree. The
same report's other screenshot is a different failure that survived it: the
overlay stuck on "Loading conversation / Still loading…" with the request
already answered in devtools.

Two paths led there, and both told the user their history was gone:

* The wait was unbounded ("the overlay stays until the API responds (no
  timeout)"). A fetch that never settled span forever, and the only exit was
  ✕ — which abandons the conversation. The wait is now bounded, and the 8s
  hint is no longer the last thing that ever happens.
* A cold open that *failed* ran router.replace("/home"), dropping the
  session id from the URL. A transient error was indistinguishable from a
  lost conversation, and the id needed to retry was gone.

Both now end in one terminal, retryable state with the id still in the URL:
the overlay shows the failure and a Retry, ✕ still means "leave". A failed
background revalidate is unchanged — the cached transcript stays on screen
rather than being replaced by an error.

Which of the three aborts counts as a failure is the whole subtlety (a
newer load and the user's ✕ own the state that replaces this one; a timeout
owns nothing), so that decision lives in a tested predicate rather than
inline in the component.
2026-08-20 00:56:34 +08:00
Bingxi Zhao (Frank)
2739a28871 fix(knowledge): keep same-named documents instead of dropping one
Builds on #899, which stopped a linked folder's subdirectories from
collapsing into raw/'s top level. Preserving structure removes most name
clashes but not the one #866 actually hit: a folder too large to sync at
once is added one subfolder at a time, and each batch roots at its own
folder, so `cli/README.md` and `events/README.md` both want raw/README.md.
The second was skipped as a "filename collision" — a document the user
asked to index, dropped with nothing in the response to say so.

A clash between different bytes now stages under a free sibling name.
Identical bytes still recover the staged copy, and content-level dedup via
file_hashes is untouched, so a repeated sync neither duplicates nor churns.
The staging log also reports the path a file actually landed at rather than
its source basename, which is no longer the same thing.
2026-08-20 00:56:34 +08:00
Bingxi Zhao (Frank)
8450a928c4 fix(obsidian): make vault failures legible instead of opaque
Builds on #922, which made read-only scans tolerate undecodable bytes and
kept the read-modify-write paths strict. Strict was the right call, but the
refusal was invisible: append_note / set_property let a raw
UnicodeDecodeError escape, _ObsidianTool.execute catches only VaultError,
so the model was told "an unknown error occurred" — the exact failure mode
#914 reported spending rounds guessing at.

* The two write paths raise VaultError naming the note, the byte offset and
  the fix. The vault is still never rewritten with U+FFFD in place of the
  user's bytes.
* Both decoders now live in one place each (_read_text / _read_text_exact)
  rather than four repeated read_text calls, so which of the two a new
  caller wants is a decision the module states once.
* execute() reports any other unexpected exception to the model by type and
  message, and logs the traceback for the operator.
* Frontmatter dates serialise through isoformat() rather than str(), so a
  YAML timestamp reaches the model as 2026-08-11T09:30:00 instead of
  2026-08-11 09:30:00, which is not a date it can hand back.
2026-08-20 00:56:34 +08:00