Files
DeepTutor/tests/services/workspace/test_file_manager.py
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

529 lines
23 KiB
Python

"""Workspace file manager: grant bookkeeping and write-side safety.
Covers the explicit-grant model, path confinement, the protected-surface
refusals, upload limits and the soft-delete/restore round trip. Fixtures
mirror ``test_content_workspace``: a private ``PathService`` per test so no
real account tree is touched.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from deeptutor.multi_user.context import reset_current_user, set_current_user
from deeptutor.multi_user.models import CurrentUser, UserScope
from deeptutor.services.path_service import PathService
from deeptutor.services.workspace import ContentWorkspaceService, WorkspaceError, file_grants, files
@pytest.fixture
def workspace_service(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
from deeptutor.services.workspace import service as service_module
paths = PathService(workspace_root=tmp_path / "runtime")
paths.ensure_all_directories()
monkeypatch.setattr(service_module, "get_path_service", lambda: paths)
monkeypatch.delenv("DEEPTUTOR_WORKSPACE_ROOT", raising=False)
monkeypatch.delenv("DEEPTUTOR_WORKSPACE_ALLOWED_ROOTS", raising=False)
from deeptutor.services.workspace import file_grants as grants_module
monkeypatch.setattr(grants_module, "get_path_service", lambda: paths)
return ContentWorkspaceService(), paths
@pytest.fixture(autouse=True)
def _user(tmp_path: Path):
token = set_current_user(
CurrentUser(
id="u_files_test",
username="files-test",
role="admin",
scope=UserScope("admin", "u_files_test", tmp_path),
)
)
yield
reset_current_user(token)
# ── grants ──────────────────────────────────────────────────────────────────
def test_write_without_grant_is_refused(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
with pytest.raises(file_grants.FileGrantError, match="not enabled"):
file_grants.require_file_grant(binding.workspace_id)
def test_grant_round_trip(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
assert file_grants.grant_status(binding.workspace_id)["granted"] is False
granted = file_grants.grant_files(binding.workspace_id)
assert granted["granted"] is True
assert file_grants.has_file_grant(binding.workspace_id) is True
file_grants.require_file_grant(binding.workspace_id) # no raise
revoked = file_grants.revoke_files(binding.workspace_id)
assert revoked["granted"] is False
with pytest.raises(file_grants.FileGrantError):
file_grants.require_file_grant(binding.workspace_id)
def test_grant_is_per_workspace(workspace_service, tmp_path: Path) -> None:
service, _ = workspace_service
first = service.current_binding(ensure_output=True)
other = tmp_path / "second-workspace"
other.mkdir()
second = service.set_workspace(other)
file_grants.grant_files(first.workspace_id)
assert file_grants.has_file_grant(first.workspace_id) is True
assert file_grants.has_file_grant(second.workspace_id) is False
# ── listing ─────────────────────────────────────────────────────────────────
def test_listing_hides_protected_entries(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
(binding.root / "notes").mkdir()
(binding.root / "notes" / "a.md").write_text("hello", encoding="utf-8")
(binding.root / ".deeptutor").mkdir(exist_ok=True)
(binding.root / ".deeptutor" / "session.db").write_bytes(b"db")
(binding.root / "legacy.db").write_bytes(b"db")
(binding.root / "skills").mkdir()
(binding.root / "skills" / "probe.md").write_text("skill", encoding="utf-8")
listing = files.list_managed_entries(service, binding, ".")
names = {row["name"] for row in listing["entries"]}
assert "notes" in names
assert ".deeptutor" not in names
assert "legacy.db" not in names
assert "skills" not in names
# ── create folder ───────────────────────────────────────────────────────────
def test_create_folder_requires_grant_then_works(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
with pytest.raises(file_grants.FileGrantError):
files.create_folder(service, binding, "题库/历年")
file_grants.grant_files(binding.workspace_id)
created = files.create_folder(service, binding, "题库/历年")
assert created["kind"] == "directory"
assert (binding.root / "题库" / "历年").is_dir()
def test_create_folder_refuses_escaping_paths(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
with pytest.raises(files.FileManagerError, match="internal|cannot leave"):
files.create_folder(service, binding, ".deeptutor/escape")
with pytest.raises(files.FileManagerError, match="cannot leave"):
files.create_folder(service, binding, "../outside")
with pytest.raises(files.FileManagerError, match="cannot leave"):
files.create_folder(service, binding, "a/b/c.txt/../..")
def test_create_folder_refuses_duplicate(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
(binding.root / "notes").mkdir()
with pytest.raises(files.FileManagerError, match="already exists"):
files.create_folder(service, binding, "notes")
# ── upload ──────────────────────────────────────────────────────────────────
def test_upload_round_trip_and_overwrite(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
(binding.root / "题库").mkdir()
saved = files.save_upload(service, binding, "题库", "总汇.md", "第一版".encode("utf-8"))
assert saved["size_bytes"] == len("第一版".encode("utf-8"))
files.save_upload(service, binding, "题库", "总汇.md", "第二版更长".encode("utf-8"))
assert (binding.root / "题库" / "总汇.md").read_text(encoding="utf-8") == "第二版更长"
def test_upload_rejects_oversize_and_bad_names(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
with pytest.raises(files.FileManagerError, match="50 MB"):
files.save_upload(service, binding, ".", "big.bin", b"x" * (50 * 1024 * 1024 + 1))
with pytest.raises(files.FileManagerError, match="path separators"):
files.save_upload(service, binding, ".", "a/b.txt", b"x")
with pytest.raises(files.FileManagerError, match="file type"):
files.save_upload(service, binding, ".", "dump.db", b"x")
def test_upload_targets_must_exist(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
with pytest.raises(files.FileManagerError, match="does not exist"):
files.save_upload(service, binding, "missing-dir", "a.md", b"x")
# ── rename ──────────────────────────────────────────────────────────────────
def test_rename_keeps_directory_and_refuses_collisions(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
(binding.root / "旧名").mkdir()
(binding.root / "已有").mkdir()
renamed = files.rename_entry(service, binding, "旧名", "新名")
assert renamed["path"] == "新名"
assert (binding.root / "新名").is_dir() is True
assert (binding.root / "旧名").exists() is False
with pytest.raises(files.FileManagerError, match="already exists"):
files.rename_entry(service, binding, "新名", "已有")
def test_rename_cannot_target_protected_suffix(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
(binding.root / "a.txt").write_text("x", encoding="utf-8")
with pytest.raises(files.FileManagerError, match="file type"):
files.rename_entry(service, binding, "a.txt", "a.db")
# ── soft delete and restore ─────────────────────────────────────────────────
def test_trash_and_restore_round_trip(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
(binding.root / "题库").mkdir()
(binding.root / "题库" / "真题.md").write_text("题目", encoding="utf-8")
trashed = files.trash_entry(service, binding, "题库/真题.md")
assert trashed["trashed"] is True
assert (binding.root / "题库" / "真题.md").exists() is False
listing = files.list_managed_entries(service, binding, "题库")
assert listing["entries"] == []
trash = files.list_trash(service, binding)
assert len(trash["batches"]) == 1
assert trash["batches"][0]["items"][0]["name"] == "真题.md"
item = trash["batches"][0]["items"][0]
restored = files.restore_entry(
service, binding, trash["batches"][0]["batch"], item["slot"], "题库"
)
assert restored["path"] == "题库/真题.md"
assert (binding.root / "题库" / "真题.md").read_text(encoding="utf-8") == "题目"
def test_trash_refuses_protected_paths(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
(binding.root / ".deeptutor").mkdir(exist_ok=True)
(binding.root / "cache.db").write_bytes(b"db")
with pytest.raises(files.FileManagerError, match="internal"):
files.trash_entry(service, binding, ".deeptutor/data")
with pytest.raises(files.FileManagerError, match="file type|Database"):
files.trash_entry(service, binding, "cache.db")
def test_restore_rejects_bad_batch(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
with pytest.raises(files.FileManagerError, match="invalid"):
files.restore_entry(service, binding, "../../etc", "x")
with pytest.raises(files.FileManagerError, match="no longer exists|invalid"):
files.restore_entry(service, binding, "20200101-000000", "no-such-slot")
# ── preview ─────────────────────────────────────────────────────────────────
def test_preview_reads_managed_text_only(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
(binding.root / "note.md").write_text("内容", encoding="utf-8")
(binding.root / ".deeptutor").mkdir(exist_ok=True)
(binding.root / ".deeptutor" / "secret.md").write_text("secret", encoding="utf-8")
payload = files.read_managed_text(service, binding, "note.md")
assert "内容" in str(payload.get("content", ""))
with pytest.raises(files.FileManagerError, match="internal"):
files.read_managed_text(service, binding, ".deeptutor/secret.md")
# ── root destination (regression: #review root 400) ─────────────────────────
def test_upload_into_workspace_root(workspace_service) -> None:
"""The workspace root is a legitimate upload target, not a stray ``.``.
``_normalise_relative`` rejects ``"."`` because a file path may never be
empty; the *destination directory* default is the root, so it must bypass
that normalisation instead of failing with "cannot leave the workspace".
"""
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
saved = files.save_upload(service, binding, ".", "root.md", "根目录".encode("utf-8"))
assert saved["path"] == "root.md"
assert (binding.root / "root.md").read_text(encoding="utf-8") == "根目录"
# The empty string is the history-file default and must behave the same.
saved_blank = files.save_upload(service, binding, "", "root2.md", b"x")
assert saved_blank["path"] == "root2.md"
def test_restore_into_workspace_root(workspace_service) -> None:
"""Restoring with the default destination returns to the original folder."""
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
(binding.root / "loose.md").write_text("root file", encoding="utf-8")
trashed = files.trash_entry(service, binding, "loose.md")
assert (binding.root / "loose.md").exists() is False
item = files.list_trash(service, binding)["batches"][0]["items"][0]
restored = files.restore_entry(service, binding, trashed["batch"], item["slot"])
assert restored["path"] == "loose.md"
assert (binding.root / "loose.md").read_text(encoding="utf-8") == "root file"
def test_restore_returns_to_original_subfolder(workspace_service) -> None:
"""A deleted file goes back where it came from, not to the browse folder."""
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
(binding.root / "题库").mkdir()
(binding.root / "题库" / "真题.md").write_text("题目", encoding="utf-8")
trashed = files.trash_entry(service, binding, "题库/真题.md")
assert trashed["trash_path"].startswith(".deeptutor/trash/")
# The entry lives in its own slot; the original path is recorded in the
# batch manifest so restore knows where it came from.
assert "/entries/" in trashed["trash_path"]
item = files.list_trash(service, binding)["batches"][0]["items"][0]
assert item["original"] == "题库/真题.md"
item = files.list_trash(service, binding)["batches"][0]["items"][0]
restored = files.restore_entry(service, binding, trashed["batch"], item["slot"])
assert restored["path"] == "题库/真题.md"
assert (binding.root / "题库" / "真题.md").read_text(encoding="utf-8") == "题目"
def test_same_name_in_two_folders_does_not_collide(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
for folder in ("甲", "乙"):
(binding.root / folder).mkdir()
(binding.root / folder / "同名.md").write_text(folder, encoding="utf-8")
first = files.trash_entry(service, binding, "甲/同名.md")
second = files.trash_entry(service, binding, "乙/同名.md")
assert first["trash_path"] != second["trash_path"]
listing = files.list_managed_entries(service, binding, "甲")
assert listing["entries"] == []
def test_trash_listing_exposes_original_path(workspace_service) -> None:
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
(binding.root / "notes").mkdir()
(binding.root / "notes" / "a.md").write_text("x", encoding="utf-8")
files.trash_entry(service, binding, "notes/a.md")
trash = files.list_trash(service, binding)
item = trash["batches"][0]["items"][0]
assert item["original"] == "notes/a.md"
assert item["slot"]
def test_restore_keeps_original_name(workspace_service) -> None:
"""A restore uses the recorded name, never a trash-side suffix."""
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
(binding.root / "dup.md").write_text("v1", encoding="utf-8")
trashed = files.trash_entry(service, binding, "dup.md")
item = files.list_trash(service, binding)["batches"][0]["items"][0]
restored = files.restore_entry(service, binding, trashed["batch"], item["slot"])
assert restored["name"] == "dup.md"
assert (binding.root / "dup.md").read_text(encoding="utf-8") == "v1"
def test_preview_refuses_database_suffix(workspace_service) -> None:
"""The listing hides ``.db``; the preview must refuse it too."""
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
with pytest.raises(files.FileManagerError, match="file type|Database"):
files.read_managed_text(service, binding, "cache.sqlite3")
# ── folder trash / restore (regression: folders vanished from trash) ─────────
def test_trash_empty_folder_appears_and_restores(workspace_service) -> None:
"""An empty folder must be listed and restorable, not silently dropped."""
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
(binding.root / "空文件夹").mkdir()
trashed = files.trash_entry(service, binding, "空文件夹")
assert "空文件夹" in trashed["trash_path"]
trash = files.list_trash(service, binding)
items = [i for b in trash["batches"] for i in b["items"]]
assert len(items) == 1
assert items[0]["original"] == "空文件夹"
assert items[0]["kind"] == "directory"
restored = files.restore_entry(service, binding, trashed["batch"], items[0]["slot"])
assert restored["path"] == "空文件夹"
assert (binding.root / "空文件夹").is_dir()
def test_trash_folder_with_children_restores_whole(workspace_service) -> None:
"""A deleted folder is one trash row, and restoring it brings the tree back."""
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
(binding.root / "题库").mkdir()
(binding.root / "题库" / "真题.md").write_text("题目", encoding="utf-8")
(binding.root / "题库" / "解析.md").write_text("解析", encoding="utf-8")
trashed = files.trash_entry(service, binding, "题库")
assert (binding.root / "题库").exists() is False
trash = files.list_trash(service, binding)
items = [i for b in trash["batches"] for i in b["items"]]
# One row for the folder — its children are not listed separately.
assert len(items) == 1
assert items[0]["original"] == "题库"
assert items[0]["kind"] == "directory"
restored = files.restore_entry(service, binding, trashed["batch"], items[0]["slot"])
assert restored["path"] == "题库"
assert (binding.root / "题库" / "真题.md").read_text(encoding="utf-8") == "题目"
assert (binding.root / "题库" / "解析.md").read_text(encoding="utf-8") == "解析"
def test_restore_recreates_missing_parent_folder(workspace_service) -> None:
"""Restoring a file whose parent was trashed must not 400 on the missing dir."""
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
(binding.root / "外").mkdir()
(binding.root / "外" / "内").mkdir()
(binding.root / "外" / "内" / "a.md").write_text("x", encoding="utf-8")
# Trash the file, then trash the whole parent tree.
trashed_file = files.trash_entry(service, binding, "外/内/a.md")
files.trash_entry(service, binding, "外")
assert (binding.root / "外").exists() is False
# The file's own slot must still restore, rebuilding the missing parents.
restored = files.restore_entry(service, binding, trashed_file["batch"], trashed_file["slot"])
assert restored["path"] == "外/内/a.md"
assert (binding.root / "外" / "内" / "a.md").read_text(encoding="utf-8") == "x"
def test_each_delete_in_a_batch_is_its_own_row(workspace_service) -> None:
"""Two same-named files deleted in one second stay distinguishable."""
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
for folder in ("甲", "乙"):
(binding.root / folder).mkdir()
(binding.root / folder / "同名.md").write_text(folder, encoding="utf-8")
first = files.trash_entry(service, binding, "甲/同名.md")
second = files.trash_entry(service, binding, "乙/同名.md")
assert first["slot"] != second["slot"]
items = [
i
for b in files.list_trash(service, binding)["batches"]
if b["batch"] == first["batch"]
for i in b["items"]
]
assert sorted(i["original"] for i in items) == ["乙/同名.md", "甲/同名.md"]
# Restore one and leave the other alone.
target = next(i for i in items if i["original"] == "甲/同名.md")
files.restore_entry(service, binding, first["batch"], target["slot"])
assert (binding.root / "甲" / "同名.md").read_text(encoding="utf-8") == "甲"
assert (binding.root / "乙" / "同名.md").exists() is False
@pytest.mark.parametrize("name", ["report.1", "data.2", "v1.10", "a.b.c", "正常.md"])
def test_restore_keeps_names_that_look_like_collision_suffixes(
workspace_service, name: str
) -> None:
"""A trailing ``.N`` is part of the name, not a trash collision marker.
Once slot directories carry the identity, the trash never appends ``.1`` /
``.2``; stripping a numeric tail would corrupt ``report.1`` or ``v1.10``.
"""
service, _ = workspace_service
binding = service.current_binding(ensure_output=True)
file_grants.grant_files(binding.workspace_id)
(binding.root / name).write_text("payload", encoding="utf-8")
trashed = files.trash_entry(service, binding, name)
item = next(
item
for batch in files.list_trash(service, binding)["batches"]
if batch["batch"] == trashed["batch"]
for item in batch["items"]
)
restored = files.restore_entry(service, binding, trashed["batch"], item["slot"])
assert restored["name"] == name
assert (binding.root / name).read_text(encoding="utf-8") == "payload"