Commit Graph

4349 Commits

Author SHA1 Message Date
yzy
6fa92cd3cb fix(tools): make TeX source discovery case-consistent (#2985)
Keep the existing lowercase .tex extension rule when the platform glob also returns uppercase matches. Add a regression case that supplies the Windows-style glob result on any CI host.

Related to #2354.
2026-12-02 10:49:15 +08:00
Leveling
920f88b1a2 feat(workspace): add a web file manager with revocable write access (#3128)
* feat(workspace): manage workspace files from the web UI behind an explicit grant

Files inside a workspace (question banks, notes, source material) could only
be placed there over SSH/scp, which locks non-technical users out of the very
folder the app is built around. This adds a file manager to
Settings -> Personal -> Workspace: browse, create folders, upload, rename, and
soft-delete, with a trash view to restore.

The write path is deliberately narrow, because a workspace folder also holds
DeepTutor's own state:

* ``ContentWorkspaceService.resolve(write=True)`` already confined writes to
  ``outputs/`` and demanded "an explicit user grant" for anything else. That
  sentence had no implementation; this adds it rather than widening the rule.
  ``file_grants`` records one grant per workspace id in the caller's own
  account settings tree, so granting one folder never opens another.
* ``.deeptutor/`` (session store, learning progress, caches), ``skills/`` and
  SQLite files are refused for reads and writes alike. The tree holds data
  whose loss is not "file management".
* Deletes move entries into ``.deeptutor/trash/<batch>/`` keeping their
  relative path, so a mis-click on a question bank is reversible without shell
  access. Oldest batches are pruned past 30.
* Uploads are bounded at 50 MB and names are validated for separators,
  reserved names and the protected extensions.
* Every mutating service call re-checks the grant itself. The router check is
  defence in depth, not the only gate: a future caller that imports ``files``
  directly cannot skip it.

The router is mounted from ``server.json`` with ``auth: "admin"``, so the
module loader's ``require_admin`` policy covers every endpoint. A learner
account, or a workspace id belonging to another account, cannot reach it:
``binding_by_id`` re-derives the id from the caller's own bindings.

A missing grant now answers 403 with the prompt the UI needs. Without that
translation FastAPI turned the synchronous ``FileGrantError`` into a 500 and
the panel could not tell "grant this workspace" from a real fault.

Front end: a ``WorkspaceFileManager`` dialog (file list, breadcrumb, upload,
rename, trash/restore, Markdown preview) plus a client in
``lib/workspace-files-api.ts``. Strings go through ``t()`` with en/zh entries;
the panel is reachable from the workspace row in settings.

Tests: 16 service-level cases over grant scoping, path confinement, protected
paths, upload limits and the trash round trip; 3 router cases covering the
manifest's admin policy, the full create/upload/rename/trash/restore cycle and
the 403 mapping; 5 client cases for URL shape, verbs and error surfacing.

Verified locally: pytest 19 passed, ruff clean, tsc clean, eslint clean,
i18n parity OK, dependency-cruiser clean, vitest 5 passed.

* fix(workspace): root uploads, folder-aware trash, bounded uploads

Reviewing the file manager against real use surfaced four correctness bugs
that the original 19 tests missed because they never exercised the root
destination or a deleted folder.

Root destination (#1). ``_normalise_relative`` rejects ``"."`` because a
workspace-relative *file* path may never be empty, but the workspace root is a
legitimate *destination directory* — it is the default upload target and the
default restore target. Both went through the same normalisation and failed
with "cannot leave the workspace" (HTTP 400) on the root. ``_resolve_target_dir``
handles ``""``/``"."`` as the root and leaves every other path on the existing
guard; ``create_folder``/``rename_entry``/``trash_entry`` keep rejecting ``"."``
because those name an entry, not a directory to write into.

Trash structure (#2). Deleting a folder used to scatter its children into
``files/<relative path>`` while ``rglob`` skipped the directory rows, so an
empty folder vanished from the trash entirely and restoring a child of a
deleted folder failed with "The restore folder does not exist." Each delete now
gets its own slot: ``<batch>/entries/<uuid>/<name>`` plus a ``manifest.json``
holding ``original``, so a folder is one restorable row and comes back whole. A
parent removed by the same delete is recreated on restore.

Restore names (#3). With slots carrying identity the trash never appends
``.1``/``.2`` any more, so ``_strip_collision_suffix`` only did harm: a file
legitimately named ``report.1`` or ``v1.10`` came back as ``report`` or ``v1``.
Removed; the recorded name is restored verbatim.

Uploads (#4). The route read the whole body with ``file.read()`` before
``save_upload`` checked the 50 MB cap, so a multi-GB upload would exhaust memory
first. It now streams in 1 MB chunks and answers 413 as soon as the limit is
passed, with an early check on the declared size.

Also: preview now refuses database suffixes like the listing and the write
paths do; ``trash_entry`` no longer resolves a symlink before moving it, so a
link is trashed as a link instead of taking its target with it.

Tests: 19 -> 37. New cases cover root upload/restore, empty and non-empty
folder round trips, parent recreation, same-name entries in one batch, and
names that merely look like collision suffixes.

* fix(workspace): adapt the panel to the slot contract, i18n and input polish

Companion to the backend fix in this same PR. This cannot ship on its own:
the restore contract moved from ``{batch, name, destination, trashed_path}``
to ``{batch, slot, destination}`` and ``list_trash`` now returns one row per
delete operation, so the previously committed client would break the trash
view against the new server.

Contract adaptation:

* ``workspace-files-api.ts`` — ``WorkspaceTrashItem`` carries ``slot``,
  ``restoreWorkspaceEntry`` posts ``{batch, slot, destination}``. An empty
  destination means "put it back where it came from".
* ``WorkspaceFileManager`` — the restore action passes the slot, and the row
  key uses ``${batch}:${item.slot}``. The old ``${batch}:${item.name}``
  collided when two same-named files from different folders were deleted within
  the same second.

Experience fixes:

* Notices went through ``t()`` with en/zh entries. Nine ``setNotice`` calls were
  hard-coded English, so a Chinese UI still showed "Created …", "moved to
  trash", and so on.
* Preview opens ``.MD``/``.TXT`` too — the suffix test was case-sensitive.
* The new-folder and rename inputs submit on Enter, matching every other dialog
  in the app.
* ``Dialog`` gained an optional ``closeTooltip`` (default ``true``) so a dialog
  whose close control sits next to other labelled controls can drop the hover
  bubble. All four file-manager dialogs turn it off; every other dialog in the
  app is untouched.

Also wraps the four dialogs in a fragment: the grant, new-folder and rename
modals were nested inside the manager's children, which trapped their backdrop
and stacked two modals at once when an ungranted write opened the grant prompt.
Those actions now close their own dialog before requesting the grant.

* chore(contracts): regenerate the frontend OpenAPI contract

The `export_frontend_contracts.py --check` job compares
`web/contracts/schema/openapi.json` against what the FastAPI app renders, so
adding a router without regenerating the artifact fails CI.

Regenerated with the documented command:

    python scripts/export_frontend_contracts.py

A deep comparison of the two documents before and after reports 13 differing
leaves, all of them additions: eight `/api/settings/workspace/files*` paths and
five request-body schemas (CreateFolderBody, DeleteBody, RenameBody,
RestoreBody, and the upload multipart body). Nothing was removed or modified;
the large line delta is the JSON being re-serialised with sorted keys.

* chore(contracts): regenerate the generated TypeScript API types

`npm run contracts:check` diffs `web/contracts/generated/api.ts` against a fresh
run of openapi-typescript, so the regenerated schema alone leaves this artifact
stale and fails the check.

Regenerated with:

    npm run contracts:generate

Pure addition: +611 lines, no deletions. It exposes the eight
`/api/settings/workspace/files*` operations and the five request-body types.

* i18n: translate the file-manager copy into all eleven other locales

The English catalog is the source of truth and every first-class locale is
expected to have no missing keys, so a feature that adds 25 keys to `en` and
`zh` leaves ten locales falling back to English. Recent feature commits update
every locale in the same change for this reason.

Translated the 25 file-manager keys into de, fr, hu, it, ja, ko, pl, pt, tr,
uk and vi, inserted at the same position as in the English catalog. Missing
keys per locale drop from 25 to 0; `npm run i18n:check` passes.

* fix(workspace): resume the upload after a first grant and ask before overwriting

Two upload defects found in browser verification.

**The selected file was lost when the grant was pending.** Choosing a file in a
workspace without a grant opened the grant dialog and stashed the action, but
the handler cleared the file input before `withGrant` ran. By the time the user
approved, the `FileList` was empty, so nothing was sent and the file had to be
picked again. The handler now snapshots the files into a plain array and resets
the input up front, and the confirm dialog no longer closes on Escape while a
pending action would be dropped with it.

**A same-named upload replaced the file without asking.** The client always
posted overwrite, and the service always wrote through. Uploads now default to
`overwrite=false` and the service creates the target exclusively, so a conflict
is reported even when the browser's listing is stale rather than being detected
by a racy pre-check. A conflict surfaces as 409 and the panel asks before
retrying with `overwrite=true`; declining keeps the original file and the rest
of the batch continues.

Also adds `UploadConflictBody` to the contract, the `Replace the existing file
"{{name}}"?` key in all thirteen locales, and tests: a router test asserting the
file survives a 409 and is replaced on the retry, an API-client test for the
overwrite flag and conflict error, and a component test covering both the
resumed upload and the declined/accepted replacement paths.

* chore(api): regenerate the router index for the workspace files router

`tests/api/test_router_loader.py::test_repository_index_matches_router_sources`
asserts that `deeptutor/api/router_index.json` carries the fingerprint of the
current router sources. Registering `workspace_files:router` in the module
manifest changed that fingerprint without regenerating the index, so the
assertion failed on every Python leg:

    AssertionError: Run scripts/build_router_index.py
    assert '89681f8f...' == 'cb9ea964...'

Regenerated with `python scripts/build_router_index.py` (56 routers, 742
routes). The diff is the fingerprint plus the eleven `/api/settings/workspace/
files*` operations; no existing entry changed.

---------

Co-authored-by: Qiuner <wdst3635@163.com>
2026-12-01 21:29:16 -03:00
Yuchuan He
e70a6be7e3 fix(llm): recover Responses after a stream read disconnect (#3073) 2026-12-01 21:55:56 +08:00
Tazeem
ae30853303 fix(codebuddy): release SDK login flows after interrupted waits (#2760) 2026-12-01 21:54:26 +08:00
Gaurav Dubey
12ec1f8754 fix(reading): flag oversized files before uploading reading materials (#3152)
The Add Materials dialog sent any file the user picked. A file over the
reader's 200 MiB single-file limit then crossed the Next proxy's 210 MiB
body cap, was truncated, and the submit button kept spinning with no
explanation.

Read the limit from /api/reading/supported-formats (already the server's
source of truth for the picker), mark an oversized file as soon as it is
chosen, and keep submit disabled until it is removed. If the limit cannot
be loaded, behaviour is unchanged and the server's own check still applies.

Closes #3151
2026-12-01 21:51:46 +08:00
我也有友人账
53a827ba9f fix(mastery): keep mastery choice clarifications from blocking fresh practice (#3150)
Co-authored-by: wyyyrz <227647791+wyyyrz@users.noreply.github.com>
2026-12-01 21:38:42 +08:00
greenhand-fjm
a943eb0b1e fix(runtime): add gateway cache breakpoints to the tool loops (#3115)
The research, question and page-index loops (run_labeled_step) and the context explorer call the SDK client directly, so an anthropic/ model on OpenRouter got no cache_control breakpoint and cached nothing on any round. Move the chat loop's check into runtime/agentic/prompt_caching.py and apply it in all three places. Refs #3087.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01J2vr2J41oqPYhmpP8CzSJA
2026-12-01 21:38:18 +08:00
Qiu
0ac31207ee fix(api): unwind API resources after startup failure (#3111) 2026-12-01 21:37:49 +08:00
Qiu
b61c870380 fix(sdk): preserve the caller workspace during SDK replay (#3113) 2026-12-01 21:37:23 +08:00
Qiu
fda9efa57d refactor(turns): share durable turn status classifications (#3122)
* Share durable turn status groups across application and stores

* Verify durable status groups against SQLite active lookup
2026-12-01 21:36:55 +08:00
Yuchuan He
38af3bc518 fix(llm): preserve Responses system instructions across summaries (#2711) 2026-12-01 21:36:30 +08:00
Yuchuan He
a35231eb92 fix(llm): retain Azure streamed response replay state (#2712) 2026-12-01 21:36:03 +08:00
Sanae
b14267bacf fix(llm): preserve Responses wire aliases during tool replay (#2734)
Serialize SDK responses using API field aliases and omit unset optional
fields before persisting native replay state. Repair legacy async_ fields
on a copy at replay time without altering stored history or argument JSON.

Cover streaming and non-streaming SDK continuations, alias precedence,
and legacy SQLite replay.

Co-Authored-By: GPT-6.1 Sol High
2026-12-01 21:35:29 +08:00
Antonio-Faure
572d80c2e7 fix(mcp): bind OAuth Test to the stored server origin (#2763)
* fix(mcp): bind OAuth Test to the stored server origin

A saved OAuth grant is addressed by the path name, but Test accepts an
unsaved payload URL. Without an origin check a valid stored bearer is
attached to any origin the caller names, so a draft can exfiltrate the
grant. Load the owner-scoped stored server and require the draft URL to
match its normalized origin; otherwise return needs-authorization
without opening a transport or touching the grant.

Refs #2589.

* chore(api): regenerate the router index fingerprint

* chore(api): regenerate router_index.json against dev

---------

Co-authored-by: Antonio-Faure <209759495+Antonio-Faure@users.noreply.github.com>
Co-authored-by: OrdoAbChao7 <2369980241@qq.com>
2026-12-01 20:30:43 +08:00
Jaeheon Kim
049a59123d fix(i18n): accept Korean as a backend interface language (#2785)
* fix(i18n): accept Korean as a backend interface language

The web picker offers Korean (added in #2359), but the backend UiLanguage
contract, its normalizers and the settings spec never learned "ko". Choosing
Korean and applying settings therefore fails with HTTP 422 on
PUT /api/settings/ui, and the saved language falls back to English on the
next load.

Register "ko" in the same seams Japanese used in #2213: UiLanguage and
_normalize_language() in interface_settings.py, the launch-settings
normalizer, and _LANGUAGE_CHOICES in settings_spec.py, then regenerate the
frontend API contracts. Add Korean to the existing router and launch-settings
tests, and add a registry test that fails whenever a web APP_LANGUAGES code
is missing from the backend contract.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: apply ruff format

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 20:00:02 +08:00
Shaikh Fardin
8a8cdf785f fix(llm): force temperature 1.0 for gpt-6 and drop reasoning_effort before tools (#2446)
* fix(llm): force temperature 1.0 for gpt-6 and treat reasoning_effort+tools rejection as tool-schema unsupported

* fix(llm): drop reasoning_effort instead of tools when combined request is rejected

---------

Co-authored-by: Shaikh Fardin <152140625+Fardin7798@users.noreply.github.com>
Co-authored-by: OrdoAbChao7 <2369980241@qq.com>
2026-12-01 19:27:05 +08:00
Marcello Pichini
318619e713 fix(mastery): keep apostrophes in study ask-hints (#2851)
The sanitizer deleted every quote character to unwrap a quoted reply,
so "What's ...?" was shown as "Whats ...?". Only unwrap a matching
outer pair, as the chat and reading hints already do.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:51:54 +08:00
Mohammad Hijjawi
f07e262ebe fix: ignore code fences inside <think> reasoning when parsing JSON (#2717)
* fix: ignore code fences inside <think> reasoning when parsing JSON

A fence drafted inside a <think> block was picked as the payload before
the reasoning was stripped, so the real JSON after the block was lost.

* fix: decode fence-in-string JSON from the chosen block's offset

The fence-in-string fallback searched the response for the truncated
block text, which can also appear inside a <think> draft, so the draft
was decoded instead of the payload. Keep the chosen fence match's start
offset and decode from there, allowing raw newlines in string values.
2026-12-01 17:50:42 +08:00
Leveling
efea7b5c8d fix(desktop): explain why Apple notarization produced no result (#2723)
notarize.mjs kept only stdout from notarytool submit and reduced every
outcome to one 'no notarization result' error, so the v1.7.3 macOS jobs
failed with an empty {} artifact and nothing in the log (#2714).

notarytool reports most submission failures on stderr, which the script
discarded. Classify the four cases instead - the process never started,
it exited with no output, it printed no result, or it printed something
that is not JSON - and carry the reason into both the thrown message and
a notarization-submission.error.json artifact that records the exit code,
the spawn error and bounded stdout/stderr tails.

The account and password are redacted from everything written out, and
notarization-submission.json keeps its previous shape (raw stdout or {}),
so the upload step and any existing consumer are unaffected.
2026-12-01 17:41:37 +08:00
bluefateludi
c20e42fd99 fix(llm): record nested prompt cache write counts (#3108) 2026-12-01 17:26:47 +08:00
Antonio-Faure
75636f0735 perf(web): improve knowledge-base and settings accessibility and payload (#3139)
* fix(web): refine knowledge and settings accessibility and layout

Name row controls from their visible titles, portal tooltip descriptions out of tablists, and make the knowledge tabs keyboard-complete. Also stack the KB master-detail on phones, add a section-scroll hint, demote the indexing diagnostic to its detail tab, and consolidate the knowledge type scale.

* perf(web): cut knowledge and settings payload

Serve raster engine marks through next/image, stop preloading the serif face on pages that do not use it, and prefetch settings routes only on hover or keyboard focus instead of on first paint.

* docs(perf): record knowledge and settings audit

Document the protocol, baseline and after medians, payload and accessibility results, limits, and reproduction commands, with mobile before/after screenshots.

* test(web): match the model row's visible accessible name

The row no longer overrides its name with a provider-first aria-label; select it by the model-first text a screen reader now reads, which also contains the visible default/task badge.

* fix(web): keep the MinerU download-type name in the locale catalog

Reuse the existing Download models and Type strings instead of introducing a new t() literal, so the strict i18n audit stays green.

* docs(perf): link the UI audit from the handbook index

The docs contract requires every guide under docs-for-dev to be reachable from README.md.

* docs(perf): record the isolated knowledge-detail LCP

Re-measured the detail route with the host pinned away from unrelated work; the 668 ms row was contention, while the isolated median is 568 ms and the stable repeats overlap the baseline.

---------

Co-authored-by: Antonio-Faure <209759495+Antonio-Faure@users.noreply.github.com>
2026-12-01 17:12:12 +08:00
Carl
242b24beeb fix: keep chats usable after oversized tool calls (#3144)
Closes #2909.

Omit the fewest eligible historical tool-argument payloads so oversized completed exchanges remain replayable, without touching signed/native provider rounds or durable history.
2026-12-01 17:03:29 +08:00
Leoy
8b2448e293 fix(knowledge): fit uploaded names and folder segments into the 255-byte limit (#3140)
Byte-fit KB upload filenames and folder segments to NAME_MAX, and share fit_filename_bytes with attachment/reading stores.
2026-12-01 17:00:42 +08:00
Axton Ji
04eb2ac82e fix: batch indexing journal writes for per-document status updates (#3137)
IndexingRun.document() re-reads the journal and atomically rewrites the
whole .indexing-run.json on every call. The LlamaIndex loader marks each
accepted source "embedding" in a synchronous loop on the event loop, and
publication marks every loaded Document (one per page) "completed" the
same way, so recording n statuses costs O(n^2) bytes of I/O with no
await in between. On a 4,320-document reindex this held the loop for
over 100 s, /health/ready stopped answering, and the desktop supervisor
killed the core.

Add IndexingRun.documents(sources, status, **details), which applies one
status to many sources under a single ownership check and a single
journal write, and use it from the loader, the LlamaIndex publication
step and the RAG service's indexed-file callback. document() now
delegates to it, so single updates behave as before.

Fixes #3046

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:56:02 +08:00
Leveling
d889815577 fix(mastery): resolve formatted choice answers by exact option body (#3129)
Fixes #2863.

Exact normalized option-body matching for resolve_answer (whitespace / Markdown / LaTeX wrappers), without normalized substring false positives. Preserves literal operators and unresolved ambiguity.

Co-authored-by: Chih-Kai-Wang <290806361+Chih-Kai-Wang@users.noreply.github.com>
2026-12-01 16:51:36 +08:00
iron ox
8fe2567c65 fix(knowledge): report live progress for LlamaIndex folder batches (#2483)
Forward embedding-batch progress through DocumentAdder so LlamaIndex folder
syncs and multi-file uploads no longer stay at 0% until the whole batch returns.

Co-authored-by: zhouyao01 <zhouyao01@mucang.cn>
2026-12-01 15:01:46 +08:00
Mohammad Hijjawi
7bd5b99f9a fix(book): match language cues as whole words (#2477)
Automatic book language detection matched its English-word cues as bare
substrings, so a topic that only mentioned a place or a subject forced
the book into another language: "energy policy in Germany" and "Berlin
German dialects" became German, "the main English clubs" became English
over the interface language, and any mention of "Traditional Chinese
Medicine" became Traditional Chinese.

Bound the Latin and Cyrillic cues with word boundaries and require the
phrased "in Traditional Chinese" form, matching how every other English
cue is written. CJK cues are unchanged.
2026-12-01 14:57:45 +08:00
iron ox
97e9ef8d44 fix(llm): omit optional replay status for custom Responses gateways (#2487)
Omit optional status on message/reasoning/function_call items when building
Responses requests for the custom binding, so gateways that reject
unknown_parameter inside an HTTP 200 stream no longer fail durable turns.
Keep the bounded HTTP-error retry for other cases.

Co-authored-by: zhouyao01 <zhouyao01@mucang.cn>
2026-12-01 14:55:05 +08:00
LIziak112
9ea0e96040 fix(desktop): preserve Windows content zoom across restarts (#2970)
* fix(desktop): preserve Windows content zoom across restarts

* fix(desktop): apply rendered Windows content zoom

Use isolated webContents zoom so saved factors scale the rendered page without affecting the shell. Add native Windows Electron coverage for viewport and DPR changes, reloads, and cold-start restoration.
2026-12-01 14:37:47 +08:00
Alex Castillo González
12e3a8ae0d fix(llm): accept list-of-blocks content from OpenAI-compatible providers (#2795)
Mistral reasoning models return `content` as a list of typed blocks
(thinking + text). `_parse_chunks` joined those lists directly and raised
TypeError, and `_parse` / the streaming content callback passed the raw
list through. Normalise with the existing `_extract_text_content` helper.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 14:17:51 +08:00
crimson-gzx
f56225f9b1 fix(llm): send session-scoped prompt_cache_key on Responses API requests (#2827)
Co-authored-by: Josh Guo <crimsongzx@gmail.com>
2026-12-01 14:13:16 +08:00
Andrew Chen
da9f65b6b3 fix(voice): speak \top and \intercal superscripts as transpose (#2828) 2026-12-01 14:08:38 +08:00
lipeh1
c1a2967045 feat(web): filter learning records by type (#2754)
Co-authored-by: lipeih <lipeihan@eazytec.com>
2026-12-01 14:02:04 +08:00
kevin
e8b22fe00e fix(documents): drop XLSX phonetic runs from fallback cell text (#2260) 2026-12-01 13:55:31 +08:00
Yuchuan He
25cc33e475 fix: serialize notebook manager initialization (#2744) 2026-12-01 13:55:22 +08:00
Tazeem
72ae8d4703 fix(config): use selected provider protocol after moving a model (#2759) 2026-12-01 13:55:14 +08:00
Mohammad Hijjawi
be86dc1a9e fix(question): hold the quiz plan to the requested per-type counts (#3057)
The quiz panel sends per_type_counts (e.g. choice=3, fill_in_blank=2)
and the planner prompt asks for that exact mix, but _parse_plan only
enforced the allowed types and difficulty. A planner that returned five
choice templates produced a five-choice quiz.

Retype the surplus templates to the types that are still short, keeping
topics, order and difficulty.
2026-12-01 13:55:05 +08:00
Yuchuan He
73bfa3f9e0 fix(turns): prevent duplicate replies when Stop races persistence (#3074) 2026-12-01 13:54:56 +08:00
wojiecihuo
5eae58dbc9 Merge pull request #3081 from zszz3/refactor/prompt-slimming
refactor: state each prompt rule once across playbooks, tool schemas and language packs
2026-12-01 13:13:28 +08:00
游标卡尺
8b18b7a020 feat(providers): add LiteLLM as a local OpenAI-compatible provider (#2832)
* feat(providers): add LiteLLM as a local OpenAI-compatible provider

* test(web): keep LiteLLM on the generic provider-branding fallback

---------

Co-authored-by: ZQR1101 <278034003+ZQR1101@users.noreply.github.com>
2026-12-01 13:00:40 +08:00
qodelicious
311629415d feat(cli): add --offset and --format json to session list (#2836)
* feat: add session list pagination and JSON output

* test(cli): strip ANSI escapes when checking session list --help output
2026-12-01 12:57:13 +08:00
iQuantum
984260b3f5 fix(imagegen): prefill image models the providers still serve (#2904)
* fix(imagegen): prefill image models the providers still serve

The OpenAI image provider prefilled gpt-image-1, which OpenAI retired on 2026-10-23, and OpenRouter prefilled google/gemini-2.5-flash-image-preview, which OpenRouter no longer lists, so a user who kept the prefill got a failing first request. They now prefill gpt-image-2 and google/gemini-3.1-flash-image.

* fix(imagegen): prefill gpt-image-2.6-flare instead of gpt-image-2

OpenAI shuts gpt-image-2 down on 2027-02-10 and names gpt-image-2.6-flare or -sunburst as the replacement; its image guide recommends the 2.6 models for new integrations. Flare is the general, fast-iteration model and uses the same Images API, so the OpenAI prefill moves to it now instead of to another retiring model.
2026-12-01 11:24:22 +08:00
iQuantum
b5fb281a3e fix: default Anthropic to a Claude model Anthropic still serves (#2888)
AnthropicProvider and the agentic client's Anthropic adapter fell back to claude-sonnet-4-20250514, which Anthropic retired on 2026-06-15, so an Anthropic binding with no model failed with not_found_error. Both now use one DEFAULT_ANTHROPIC_MODEL constant, claude-sonnet-5-5.
2026-12-01 11:20:50 +08:00
zszz3
3bbc0aafc9 test(prompt): scope the single-source scan for the maths rule
The maths single-source scan reads only prompt packs, capability modules,
capability Markdown prompts (such as notes/prompts/*/system.md) and the
fragment files instead of every file in the package. The zh/en playbook
comparison already checks line by line in
tests/capabilities/test_mastery_prompt_slimming.py.

Refs #2975
2026-12-01 11:17:29 +08:00
zszz3
eaf23617b0 fix(prompt): reread shared fragments on cache reset and reject braces
PromptManager.clear_cache() and reload_prompts() dropped cached packs but
the fragment lru_cache kept serving the old fragments/*.yaml, so a
reloaded pack still carried the previous rule text. Both now clear it.
Fragments are checked for "{" and "}" when loaded (the expanded text can
pass through str.format()), with a test over every fragment in en and
zh. The notes capability gets a test that its en and zh instructions
include the shared maths rule.

Refs #2975
2026-12-01 11:17:29 +08:00
zszz3
d411a8542f fix(prompt): fail loudly on a broken {{shared:...}} marker
PromptManager expanded shared fragments inside the try block that guards
reading a prompt file, so an unknown fragment name was caught as a load
failure and the manager quietly served another language's pack (or {}).
A marker that does not match the lowercase name pattern, such as
{{shared:Math}}, was left in the prompt as literal text. Expansion now
runs after the read; unknown names raise KeyError and leftover markers
raise ValueError. A repo scan checks that every marker in a prompt pack
names a fragment present in both en and zh.

Refs #2975
2026-12-01 11:17:29 +08:00
zszz3
5a32e5434e refactor: trim duplicated guidance in ask_user, cron and learning_update schemas
Nested ask_user option and multi_select fields repeated what the
top-level description already says; the option label/description rule
is now stated once in the options description. The cron and
learning_update descriptions drop sentences that their parameter
descriptions repeat. Types, required fields and enums are unchanged.

Refs #2975
2026-12-01 11:17:29 +08:00
zszz3
5961d252e2 refactor: keep each mastery rule in one place, playbook or tool schema
Tool mechanics (teaching_updates evidence, note_explained, grouped quiz
replace/resume, visual sources, option shuffling, repair, skip/defer,
prepare_lesson) now live only in the tool descriptions; the playbook
keeps teaching strategy and when to call which tool. mastery_quiz group
items and the nested revise/profile shapes keep their structure but no
longer repeat every parameter description.

The assessment-result rules added for #2366 move into mastery_assess:
follow a non-passing result's next_step, a coverage_gap result records
nothing and must not trigger unchanged preparation again, and an
incomplete packet is assessed on its covered facets only. The playbook
no longer asks for `passed: true`, which the schema marks as ignored.
An answered pending question is graded from the loop protocol with its
learner_answer and question_id.

The zh playbook is aligned with en line by line: the PDF evidence and
exam practice paragraphs, the multi-turn explanation bullet in its
English position, the registered-assessment wording and the backticked
identifiers. tests/capabilities/test_mastery_prompt_slimming.py checks
the alignment, that each rule is still stated somewhere, and that tool
mechanics are not repeated in the playbook.

Refs #2975
2026-12-01 11:17:29 +08:00
zszz3
744d24a6bc refactor: state the LaTeX maths rule once as a shared prompt fragment
Chat, mastery, question FINISH and notes each carried their own copy of
the dollar-delimiter rule. They now reference {{shared:math_latex}}
(deeptutor/services/prompt/fragments), expanded by PromptManager at load
time; the notes capability expands the marker in its system.md, and
code-built prompts use shared_fragment(). The English notes prompt gains
the rule (and the mermaid line) its Chinese twin already had. The chat
loop no longer repeats the 'concise Markdown' line that runtime_policy
states.

Refs #2975
2026-12-01 11:05:06 +08:00
Rahul selvaraj
5ea8fa1ebc fix(mcp): let operators declare Fake-IP ranges for self-service servers (#2857)
* fix(mcp): let operators declare Fake-IP ranges for self-service servers

A local proxy in Fake-IP mode (Loon, Clash, Surge) answers DNS for public
hostnames with synthetic private addresses, e.g. fd27:712::/32 from Loon,
and routes the connection by hostname. Strict validation then rejects
public MCP Store entries such as GitMCP as private-network targets.

Add DEEPTUTOR_MCP_FAKE_IP_RANGES (comma separated CIDRs, opt-in, read from
the process environment). In strict mode an address a hostname resolves to
inside a declared range is no longer rejected as private. IP-literal URLs,
loopback and the link-local/metadata ranges stay blocked regardless, and
any other private answer for the same host still fails validation.

Closes #2789

Assisted-by: Claude <noreply@anthropic.com>

* fix(mcp): warn on Fake-IP opt-in and document single-user SSRF trade-offs

Address review feedback from JinhangHE126 on #2857:
Document clearly that DEEPTUTOR_MCP_FAKE_IP_RANGES relaxes hostname-based SSRF protection for hostnames resolving into declared ranges (as the proxy resolves targets and connects).
Emit a startup security warning when DEEPTUTOR_MCP_FAKE_IP_RANGES is set, noting that the setting is intended strictly for single-user/desktop installations.

Assisted-by: Gemini (Google Vertex AI)
2026-12-01 10:32:50 +08:00