4674 Commits

Author SHA1 Message Date
Bingxi Zhao (Frank)
e159c49791 test(api): verify exact native paths for connections and output reveal (#3172) 2026-12-02 05:27:59 -05:00
Bingxi Zhao (Frank)
8726ce667d docs: add section on moving data between deployments (#2855) 2026-12-02 05:27:59 -05:00
马修权
3a8efc7f46 fix(desktop): restore Windows bounds on the display with the most overlap (#2969)
* fix(desktop): restore Windows bounds on the display with the most overlap

* fix(desktop): retry transient macOS DMG creation failures

Retry hdiutil Resource busy failures with bounded backoff and remove partial images before retrying. Preserve immediate failure for permanent errors and cover retries, cleanup, and child-process diagnostics with regression tests.

* fix(desktop): harden Windows window state persistence and recovery

Flush pending window state on minimized or fullscreen exit, retain deferred display clamping across native transitions, and validate maximized state strictly.

Preserve maximization when a saved display is unavailable and add real Electron lifecycle and cold-start regression tests with documented hardware verification limits.

* test(desktop): initialize Electron before Windows tests

---------

Co-authored-by: Codex <codex@openai.com>
2026-12-02 18:11:53 +08:00
yaqi
4f8cfe1110 chore(api): rebuild the router index for the settings route change 2026-12-02 18:02:28 +08:00
yaqi
02e0e50e78 chore(i18n): translate the fallback-chain strings for every web locale 2026-12-02 18:02:09 +08:00
yaqi
c94231c1cc docs(settings): explain what the fallback chain covers 2026-12-02 18:01:52 +08:00
yaqi
67a384b6bd fix(failover): anchor the chat chain on the turn's model, not the catalog default 2026-12-02 18:01:52 +08:00
yaqi
46faec536a fix(settings): sync the chain editor with the catalog after it loads 2026-12-02 18:01:52 +08:00
yaqi
4d5c6c4dd9 fix(failover): keep the caller's model, fast-fail with a chain, reset the ladder 2026-12-02 18:01:52 +08:00
yaqi
dbebb33608 fix(settings): stop the chain editor from offering an already chosen model 2026-12-02 18:01:52 +08:00
yaqi
874ea33d76 feat(settings): edit the fallback chain from the language models page 2026-12-02 18:01:51 +08:00
yaqi
4b48ca1493 feat(settings): show the fallback chain on the language models page 2026-12-02 18:01:51 +08:00
yaqi
21c2e67008 test(failover): cover both call paths and land the switch copy 2026-12-02 18:01:51 +08:00
yaqi
ab85ace897 fix(settings): keep an unchanged llm service unchanged 2026-12-02 18:01:51 +08:00
yaqi
f284197d29 feat(settings): persist and validate the fallback chain in the catalog
Backend half of #2693 P3.

- `ModelCatalogService` normalizes `services.llm.fallbacks` on every save: only
  well-formed `{profile_id, model_id}` entries survive, duplicates collapse, and
  the list is capped at 4 so a failure cannot multiply the retry budget.
- `POST /api/settings/apply/service` no longer drops the chain. The settings UI
  edits providers and does not carry a `fallbacks` key, and that endpoint
  replaces the whole service object — so an absent key now means "keep what is
  stored" instead of "clear it". An explicit key still replaces the chain.
- Covered by tests for normalization, save round-trip and the preserve rule.

Still to come: the read-only chain display on the LLM settings page, the
`provider_switched` copy, and the integrated chat/services failover tests.
2026-12-02 18:01:51 +08:00
yaqi
5cb774ff35 feat(chat): fail over to the next candidate on a pre-output failure
Chat-path wiring for #2693 P1. `AgenticChatPipeline` now builds its client
through `build_chain_client`, which returns today's single client unless the
catalog declares fallbacks *and* at least two candidates are healthy — so the
default configuration is untouched.

When a chain exists, the loop spends its existing pre-output retry on the next
candidate: it records the failure (cooling that candidate down), advances,
announces the switch, and retries the same round. This happens only where the
loop already knows nothing was emitted, so no partial answer is ever replayed.
After the switch the provider label and fallback count come from the new
candidate, so the P0 failure copy keeps telling the truth.

Not in this commit: the services-layer path (P2), catalog validation and the
settings editor (P3). Those, plus the integrated failover tests, are next.
2026-12-02 18:01:51 +08:00
yaqi
26c2cd4675 feat(llm): ordered fallback with cooldown-based failback
Core of #2693 P1/P2, deliberately not wired into the call paths yet: this
commit adds the pieces, their contract and their tests, so the two integrations
(catalog-driven client construction and the agent loop's pre-output retry) can
be reviewed on their own.

- `resolve_candidates()` builds the ordered chain: active model first, then the
  catalog's declared fallbacks, de-duplicated, unresolvable entries dropped.
- `ProviderHealthRegistry` cools a candidate down instead of removing it
  (rate limits honour their hint, transport failures 30s, auth disables until the
  profile is edited, consecutive failures escalate 60s → 5m → 15m). Expiry is the
  failback: the next request tries the primary again. State is per owner, so one
  account's exhausted key cannot cool a shared profile for everyone.
- `call_with_failover()` walks the healthy candidates, records each failure and
  reports every switch; non-provider exceptions are re-raised untouched, and an
  exhausted chain raises `AllProvidersUnavailable` with the attempt list.
- `drop_foreign_message_state()` strips `thinking_blocks`,
  `_provider_response_state` and `_responses_output_items` so a candidate never
  receives another provider's private replay state.
2026-12-02 18:01:36 +08:00
yaqi
e5a20ba12e feat(chat): surface the provider's own retry waits
The 10-minute silence in #2693 does not come from the agent loop: a 401/429/5xx
is retried inside the provider on the configured schedule (5s → 120s per attempt,
8 attempts), and those sleeps emit no stream events at all. The turn looks
frozen until the final error.

- `LLMProvider` gains an optional async `retry_observer`, called before each
  retry sleep with the attempt number, total and delay. A failing observer is
  logged and ignored: visibility must never turn a retry into a failure.
- The agent loop attaches an observer before every model call and emits the same
  `provider_retry` notice the transport-retry path already used, now with the
  provider label, attempt count and `retry_delay_s` /
  `fallbacks_configured` in the trace metadata.
- Covered by unit tests for the observer contract (called once per retry, and
  inert when it raises).
2026-12-02 18:01:36 +08:00
yaqi
5c61a9bfe1 feat(chat): name the failing provider and the unused alternatives
Part of #2693, visibility only: the turn still runs the one active model, but a
failed turn no longer reads as "the provider connection was interrupted" with
no name, no attempt count, and no hint that an alternative is already
configured.

- `provider_visibility.py` builds the retry and final-failure copy from a
  pipeline's binding, model and endpoint host, plus the number of configured
  fallbacks (`services/model_selection/fallbacks.py`: read-only, bounded,
  tolerant of a hand-edited catalog).
- Non-transport provider errors (401/403/429/5xx, model-not-found) are mapped
  through the existing error taxonomy before they are raised, so the user reads
  "provider X returned a server-side error" instead of the SDK's raw
  "Error code: 502" — while the typed error, status code and retry flags that
  the loop and the forced-finish path branch on are preserved.
- The failure trace metadata gains `provider`, `attempts` and
  `fallbacks_configured`.
- zh and en chat prompt copy updated; other capabilities keep the code defaults
  until their prompt packs are updated.

No failover yet: switching, cooldowns and failback land in P1.
2026-12-02 18:01:08 +08:00
Antonio-Faure
88f649283c fix(mastery): keep an unchanged lesson packet in place so requests stay cacheable
prepare_model_request removed and re-appended the lesson packet (and its
original-page images) at the end of every model request. Each tool round
therefore moved ~3.3K tokens of packet and pages behind the new tool
results, and the next turn removed the stored packet from history, so no
request was a prefix extension of the previous one and every round re-paid
the packet and everything after it.

Deliver the packet like a runtime snapshot: an unchanged packet stays at
the position where it was first sent (within the turn and in replayed
history), and only a changed packet replaces it. The page images are
projected right after the packet instead of at the end of the request.

Refs #3186
2026-12-02 17:38:54 +08:00
wojiecihuo
c9017be166 Merge pull request #3185 from zszz3/fix/chat-stable-tool-surface
fix(chat): keep per-turn-gated tools mounted for the rest of the session
2026-12-02 17:31:14 +08:00
wojiecihuo
22561bfc82 Merge pull request #3184 from zszz3/fix/chat-forced-finish-tools
fix(chat): keep the loop's tools in the forced final round
2026-12-02 17:31:00 +08:00
Antonio-Faure
1358629d57 fix(chat): keep per-turn-gated tools mounted for the rest of the session
tools[] heads the provider prompt-cache key, so a tool that one turn mounts
and the next drops re-bills the whole history on both turns. Three gates were
still read off a single turn:

- has_kb: detaching the knowledge base removed rag / kb_files /
  knowledge_frontier. They now stay mounted once seen (outside exclusive
  capabilities); while no KB is attached, dispatch passes an empty
  _attached_kb_names and the tools refuse every kb_name, so this never
  reaches a detached KB.
- has_book_authoring: a turn without a single referenced book page dropped
  propose_book_edit. It stays; the tool already refuses without a page.
- has_scientific_research where nothing can be deferred (a partner whitelist
  without load_tools): the message regex mounted the research tools for one
  message only. Once mounted they stay.

Also, the setup capability's message/intro heuristic no longer activates on a
partner turn (which can write nothing and is already not offered the deferred
setup tools); with a whitelist lacking load_tools it mounted the setup tools
and a system block on a fresh install's first message and dropped them next.

Adds tools_gated_by() to tool_composition so the sticky checks name gated
tools from the single _CONDITIONAL_MOUNT_FLAGS table.

Refs #3183
2026-12-02 16:58:59 +08:00
zszz3
246aa1426b fix(chat): keep the loop's tools in the forced final round
Prompt caches key on tools, then system, then messages. Every round of a
chat-loop turn sends the loop's tool schemas, but the forced finish (round
budget spent) sent the request with tool_schemas=None. That changed the
very start of the request, so the whole turn history (often 10k-60k
tokens) missed the cache on the final round. tool_choice="none" is no
fix: on DeepSeek it caches exactly like a request without tools.

The forced finish now sends the same tool list the last normal round
sent (taken from the request snapshot, since the deferred tool loader
appends to the live list after a request goes out) with tool_choice left
at auto; the finish instruction already tells the model to stop calling
tools. A tool call it returns anyway is never dispatched, and no ask_user
draft card is published for it. The round is kept in the history as text
only (a call without a result is rejected by the next request; Responses
function_call items are dropped too), a repair note asks for a plain-text
answer, and one more attempt runs. If that also calls a tool, the turn
ends with the existing empty-response fallback. The forced finish still
counts as one loop round. The persisted model_turn tools and the context
budget now reflect what the final request really carried.

The context-exploration pre-pass had the same pattern on its last round
(tools dropped); it now keeps the tools, does not run a tool call there,
repairs once, and otherwise degrades to the existing single pass.

The finish instructions (chat, mastery, explore_context; en/zh) now say
the tools are still listed but no call will run. Same approach as the
staged pipelines' forced finish (#3080).

Refs #3182
2026-12-02 16:58:58 +08:00
wojiecihuo
93e3121ff1 Merge pull request #3180 from zszz3/fix/mid-conversation-system
fix(llm): keep mid-conversation system messages in place
2026-12-02 16:29:13 +08:00
Rudy Mizrahi Celekli
19348d46eb fix(hints): cache completed results after waiters cancel (#2781) 2026-12-02 16:28:22 +08:00
iSanae233
ec3e2d43da ci(mobile): enable Gradle cache writes on dev
Keep pull request and other branch caches read-only, while allowing main and dev builds to persist Gradle dependencies. Include stack traces and dependency resolution diagnostics in Android CI logs.

Co-Authored-By: GPT-6.2 Sol
2026-12-02 16:16:51 +08:00
Antonio-Faure
8b565918ce fix(math_animator): keep layout warnings visible without extra repairs (#2246)
The post-render geometry probe is record-only: the pre-render rounds own the repair budget. Forcing passed=True hid the layout warning in the viewer and contradicted the v1.7.2 behavior that preserves review failures (#2243).

Keep passed=False and add CodeRetryManager(review_is_advisory=True) so the result carries the warning without calling repair_callback again. Add advisory and non-advisory regression tests.

Co-authored-by: Antonio-Faure <209759495+Antonio-Faure@users.noreply.github.com>
2026-12-02 15:51:01 +08:00
zszz3
37f5565bb2 fix(llm): keep mid-conversation system messages in place
Anthropic Messages has one top-level system and the Responses API one
instructions field. The Anthropic converter kept only the last system
message, so a deep_solve context checkpoint or a Mastery lesson notice
replaced the whole system prompt. The Responses converter joined every
system message into instructions, so each appended notice rewrote the
start of the request.

Leading system messages still become system/instructions. A later one
stays where it was: an Anthropic user text block labelled [System note]
(after any tool_result blocks), or a Responses developer message.
2026-12-02 15:44:33 +08:00
Qiu
d5cb782f4b fix(books): scope pending attachment reads to the active page chat (#3102) 2026-12-02 15:38:30 +08:00
Leveling
8a85d5eb6e fix(mastery): name the materials a PDF-grounded scope leaves out (#2874)
A Mastery Path objective that selects both a PDF knowledge base and a Markdown
one builds a PDF-only evidence scope: `selected_scope()` skips sources with no
PDF pages. That restriction is deliberate and correct -- questions are verified
against rendered original pages, so a Markdown source cannot take part in that,
and widening the scope would let unverified material count as verified.

What was broken was the reporting. The skip was silent, so a mixed topic looked
fully PDF-grounded, and the two failures a learner could actually hit both
misled:

- `prepare_lesson()` said "This source-grounded path no longer has selected PDF
  materials", which is not what a mixed topic is.
- `bind_questions()` ended at "The selected source does not support this exact
  question and answer key", a per-question verdict that cannot tell the tutor a
  whole selected source sits outside the evidence chain.

The tutor was then pushed to quiz on unread PDF material or retry until the
round budget ran out.

`selected_scope()` now records the label of every source it skips, through an
optional output list. It stays the single place that rule is decided, so nothing
re-derives the predicate and drifts. `describe_skipped()` turns that into a
sentence, appended to the three failures above; `validate_evidence()` passes its
own list through so `bind_questions()` does not scan knowledge bases a second
time for a diagnostic.

Nothing about authorisation changes. A skipped source is still absent from the
scope, still cannot cite, and cannot authorize a question; the tests assert that
directly.

This is the low-risk half of #2859. Actually *supporting* mixed PDF and text
evidence is an evidence-model change -- a third state alongside "PDF-grounded"
and "text-tutoring" -- and should be agreed with a maintainer before anyone
builds it.

Review follow-up
----------------

- `skipped_labels` is now collected per question, not pooled across the batch.
  Questions may belong to different knowledge points, so the shared list let
  one question report materials that were selected only for another. The note
  is rendered per question in `_support_contract()`, kept in a side dict so it
  never leaks into the model payload.
- The singular message read "These selected materials has no PDF pages"; it now
  says "This selected material has ... so it is outside the evidence chain".

Tests
-----

`tests/services/rag/test_mastery_mixed_source_scope.py` covers the skip report,
the silent all-PDF case, the messages, the grammar, the multi-KP case, and the
unchanged security property. Reverting just the per-question collection makes
the multi-KP test fail (`q-pdf` wrongly reports "Beginner guide").

Related suites: `tests/capabilities` plus `test_mastery_source_pages.py` ->
934 passed, 2 skipped. `ruff check` and `ruff format --check` clean.

One bug this work introduced and the suite caught: `validate_evidence()` rebound
its `skipped` parameter to a local list, so callers collected nothing. It is
fixed, with a test pinning the output-parameter contract.
2026-12-02 15:34:21 +08:00
bluefateludi
8478b63267 fix(cli): preserve literal text in session commands (#2983)
Co-authored-by: Chirag Singhal <76880977+chirag127@users.noreply.github.com>
2026-12-02 15:27:11 +08:00
hongwei-2026
99804c9d81 fix(i18n): regenerate with the current reply language (#3060)
Co-authored-by: 于鸿伟 <16595344+yyyyyyydwdw@user.noreply.gitee.com>
2026-12-02 15:05:36 +08:00
A_Zhe
346752163d fix: discover all MCP tool pages (#2930)
* fix: discover all MCP tool pages

* fix: preserve the MCP discovery timeout and retry delay

---------

Co-authored-by: 王俊哲 <wangjunzhe@wangjunzhedeMacBook-Air.local>
2026-12-02 15:05:26 +08:00
Zeming-Yuan
9b71995804 test(knowledge): guard optional bm25 retriever import on Python 3.14 2026-12-02 12:32:44 +08:00
Bingxi Zhao (Frank)
51f3854b7c test(runtime): let dead-owner recovery settle on Windows
A just-exited PID stays visible to psutil for a few milliseconds on Windows, so one immediate recovery tick can defer without being wrong. Poll with a bounded deadline instead of asserting the very first tick.
2026-12-02 12:06:10 +08:00
Bingxi Zhao (Frank)
18c767768d fix(runtime): keep the Windows kill round distinct from terminate 2026-12-02 11:59:20 +08:00
Bingxi Zhao (Frank)
4b9bcea12b ci: print a per-file Windows baseline summary 2026-12-02 11:39:49 +08:00
Bingxi Zhao (Frank)
f82ecd937c test: scope POSIX-only sandbox fallback and file-mode checks 2026-12-02 11:37:45 +08:00
Zeming-Yuan
bbcf020386 chore(api): rebuild router index after knowledge router update 2026-12-02 11:19:56 +08:00
Bingxi Zhao (Frank)
e6e3725933 test: stop probing worker liveness with os.kill on Windows
On Windows os.kill(pid, 0) is not a probe: signal 0 is CTRL_C_EVENT, so CPython broadcasts Ctrl+C to every process on the console. The three existence checks in test_worker_stream aborted pytest and the shell that started it, so the file could not run on Windows at all. Use deeptutor.runtime.process.probe_process_liveness, which already documents the hazard, and leave the POSIX path unchanged.

Refs #2354
2026-12-02 11:02:14 +08:00
Antonio-Faure
63ef9b7c2c chore: remove dead Python modules and helpers (#2253)
* chore: remove dead Python modules and helpers

Delete unreferenced P0 code identified by the dead-code audit:
- services/llm/registry.py and its test-only coverage
- logging/adapters package (LlamaIndex log forwarding)
- textbook_struct.chapter_rebuild.detect_frames
- load_config_with_main_async and its async file helper
- memory.trace.iter_by_ids / latest_ts
- TokenTracker.format_summary
- WeixinChannel._api_get
- ArxivSearchTool.extract_arxiv_id_from_url
- FileLibraryStore migration scaffolding (_run_migrations et al.)
- eight small dead helpers in services, api/utils, and knowledge
- redundant runtime C2CMessage import in the QQ channel

* chore: drop the prompt-language shim and a dead storage helper

The book agents were the last in-tree users of blocks/_language.py, which
only re-exported services.prompt.language. Import the real module and
delete the shim. storage._storage_path_from_version_entry had no caller.

Verified: ruff F401/F811/F841/F821 on changed files; py_compile.

---------

Co-authored-by: Antonio-Faure <209759495+Antonio-Faure@users.noreply.github.com>
2026-12-02 10:50:16 +08:00
swjtuhuangjunfu
3bc07bdebb fix(llm): send none, not the rejected minimal, to gemini-3.8 (#2702) (#2703)
Co-authored-by: swjtuhuangjunfu <7245859+swjtuhuangjunfu@users.noreply.github.com>
2026-12-02 10:50:07 +08:00
马修权
c33f468f3a feat(web): style Windows desktop sidebar and content frame (#2979) 2026-12-02 10:49:26 +08:00
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
Zeming-Yuan
a6943d4684 fix(knowledge): update indexed document paths when moving KB files 2026-12-02 10:28:23 +08:00
Zeming-Yuan
016137fe0e fix(mastery): tolerate preference strategy, normalize evidence quotes, and report path_revision 2026-12-02 10:12:23 +08:00
Benjamin Schwing
e6b61bf3b8 Merge remote-tracking branch 'origin/dev' into HEAD
# Conflicts:
#	deeptutor/api/router_index.json
#	web/locales/de/app.json
#	web/locales/en/app.json
#	web/locales/fr/app.json
#	web/locales/hu/app.json
#	web/locales/it/app.json
#	web/locales/ja/app.json
#	web/locales/ko/app.json
#	web/locales/pl/app.json
#	web/locales/pt/app.json
#	web/locales/tr/app.json
#	web/locales/uk/app.json
#	web/locales/vi/app.json
#	web/locales/zh/app.json
2026-12-02 02:01:54 +00:00
WolveBrown
eac18a2bf2 test(api): verify exact native paths for connections and output reveal 2026-12-02 09:55:44 +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