Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(server): add resources-only WebDAV adapter (#1435)

yeyitech232dfbfaeee6
diff --git a/docs/en/api/03-filesystem.md b/docs/en/api/03-filesystem.md
index ba18fe5ba..1fce1976e 100644
--- a/docs/en/api/03-filesystem.md
+++ b/docs/en/api/03-filesystem.md
@@ -2,6 +2,27 @@
OpenViking provides Unix-like file system operations for managing context.
+## WebDAV (Phase 1)
+
+OpenViking Server also exposes a minimal WebDAV adapter for resource files:
+
+```text
+/webdav/resources
+```
+
+Phase 1 intentionally keeps the scope narrow:
+
+- Resources only. Memories, skills, sessions, and other namespaces are not exposed.
+- Text-first writes. `PUT` currently accepts UTF-8 text content only.
+- WebDAV subset only. `OPTIONS`, `PROPFIND`, `GET`, `HEAD`, `PUT`, `DELETE`, `MKCOL`, and `MOVE` are supported.
+- Semantic sidecars stay internal. Derived files such as `.abstract.md`, `.overview.md`, `.relations.json`, and `.path.ovlock` are hidden from listings and cannot be accessed directly through WebDAV.
+
+Behavior notes:
+
+- Creating a new file through WebDAV triggers OpenViking semantic generation for that file path.
+- Replacing an existing file through WebDAV refreshes related semantics and vectors, same as `write()`.
+- User-created dot-directories and dot-files remain visible unless they match one of the reserved internal filenames above.
+
## API Reference
### abstract()
diff --git a/docs/zh/api/03-filesystem.md b/docs/zh/api/03-filesystem.md
index a21a615e2..79bd9040c 100644
--- a/docs/zh/api/03-filesystem.md
+++ b/docs/zh/api/03-filesystem.md
@@ -2,6 +2,27 @@
OpenViking 提供类 Unix 的文件系统操作来管理上下文。
+## WebDAV(Phase 1)
+
+OpenViking Server 也提供了一个面向资源文件的精简 WebDAV 适配层:
+
+```text
+/webdav/resources
+```
+
+Phase 1 有意把范围控制得比较小:
+
+- 仅开放 `resources` 命名空间,不暴露 memories、skills、sessions 等其他空间。
+- 以文本写入为主,当前 `PUT` 只接受 UTF-8 文本内容。
+- 只实现一小部分 WebDAV 方法:`OPTIONS`、`PROPFIND`、`GET`、`HEAD`、`PUT`、`DELETE`、`MKCOL`、`MOVE`。
+- 语义侧边文件保持内部可见。`.abstract.md`、`.overview.md`、`.relations.json`、`.path.ovlock` 这些派生文件不会出现在 WebDAV 列表中,也不能被直接访问。
+
+行为说明:
+
+- 通过 WebDAV 新建文件时,会对该文件路径触发 OpenViking 的语义生成。
+- 通过 WebDAV 覆盖已有文件时,会像 `write()` 一样刷新相关语义和向量。
+- 用户自己创建的点目录或点文件仍然可见,只有上面列出的保留内部文件名会被隐藏。
+
## API 参考
### abstract()
diff --git a/openviking/server/app.py b/openviking/server/app.py
index 00a4acdd8..c96725c44 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -31,6 +31,7 @@ from openviking.server.routers import (
stats_router,
system_router,
tasks_router,
+ webdav_router,
)
from openviking.service.core import OpenVikingService
from openviking.service.task_tracker import get_task_tracker
@@ -233,6 +234,7 @@ def create_app(
app.include_router(observer_router)
app.include_router(metrics_router)
app.include_router(tasks_router)
+ app.include_router(webdav_router)
app.include_router(bot_router, prefix="/bot/v1")
return app
diff --git a/openviking/server/routers/__init__.py b/openviking/server/routers/__init__.py
index 6c969a8c1..b303bf6da 100644
--- a/openviking/server/routers/__init__.py
+++ b/openviking/server/routers/__init__.py
@@ -17,6 +17,7 @@ from openviking.server.routers.sessions import router as sessions_router
from openviking.server.routers.stats import router as stats_router
from openviking.server.routers.system import router as system_router
from openviking.server.routers.tasks import router as tasks_router
+from openviking.server.routers.webdav import router as webdav_router
__all__ = [
"admin_router",
@@ -34,4 +35,5 @@ __all__ = [
"metrics_router",
"observer_router",
"tasks_router",
+ "webdav_router",
]
diff --git a/openviking/server/routers/webdav.py b/openviking/server/routers/webdav.py
new file mode 100644
index 000000000..c0944366c
--- /dev/null
+++ b/openviking/server/routers/webdav.py
@@ -0,0 +1,450 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Minimal WebDAV adapter for resources scope."""
+
+from __future__ import annotations
+
+import mimetypes
+import xml.etree.ElementTree as ET
+from datetime import timezone
+from email.utils import format_datetime
+from typing import Any, Optional
+from urllib.parse import quote, unquote, urlparse
+
+from fastapi import APIRouter, Depends, Request
+from fastapi.responses import PlainTextResponse
+from fastapi.responses import Response as FastAPIResponse
+
+from openviking.server.auth import get_request_context
+from openviking.server.dependencies import get_service
+from openviking.server.identity import RequestContext
+from openviking.utils.time_utils import parse_iso_datetime
+from openviking_cli.exceptions import InvalidArgumentError, NotFoundError
+from openviking_cli.utils.uri import VikingURI
+
+router = APIRouter(prefix="/webdav/resources", tags=["webdav"])
+
+_DAV_NAMESPACE = "DAV:"
+_RESERVED_FILENAMES = frozenset(
+ {
+ ".abstract.md",
+ ".overview.md",
+ ".relations.json",
+ ".path.ovlock",
+ }
+)
+_WEBDAV_METHODS = "OPTIONS, PROPFIND, GET, HEAD, PUT, DELETE, MKCOL, MOVE"
+_TEXT_MEDIA_FALLBACK = "text/plain; charset=utf-8"
+
+
+def _webdav_headers() -> dict[str, str]:
+ return {
+ "Allow": _WEBDAV_METHODS,
+ "DAV": "1",
+ "MS-Author-Via": "DAV",
+ }
+
+
+def _error(status_code: int, message: str) -> PlainTextResponse:
+ return PlainTextResponse(message, status_code=status_code, headers=_webdav_headers())
+
+
+def _normalized_resource_path(resource_path: str) -> str:
+ decoded = unquote(resource_path or "").strip("/")
+ if not decoded:
+ return ""
+
+ parts: list[str] = []
+ for part in decoded.split("/"):
+ if not part:
+ continue
+ if part in {".", ".."}:
+ raise InvalidArgumentError(f"unsafe WebDAV path segment: {part}")
+ if "\\" in part:
+ raise InvalidArgumentError(f"unsafe WebDAV path separator in segment: {part}")
+ if len(part) >= 2 and part[1] == ":" and part[0].isalpha():
+ raise InvalidArgumentError(f"unsafe WebDAV drive-prefixed segment: {part}")
+ parts.append(part)
+ return "/".join(parts)
+
+
+def _ensure_exposed_path(resource_path: str) -> None:
+ if not resource_path:
+ return
+ parts = resource_path.split("/")
+ if any(part in _RESERVED_FILENAMES for part in parts):
+ raise NotFoundError(resource_path, "resource")
+
+
+def _resource_uri(resource_path: str) -> str:
+ return "viking://resources" if not resource_path else f"viking://resources/{resource_path}"
+
+
+def _href_for_path(request: Request, resource_path: str, *, is_dir: bool) -> str:
+ base = request.scope.get("root_path", "") + "/webdav/resources"
+ if resource_path:
+ href = f"{base}/{quote(resource_path, safe='/')}"
+ else:
+ href = base
+ if is_dir and not href.endswith("/"):
+ href += "/"
+ return href
+
+
+def _content_type_for_name(name: str, *, is_dir: bool) -> str:
+ if is_dir:
+ return "httpd/unix-directory"
+ guessed, _ = mimetypes.guess_type(name)
+ if guessed:
+ return guessed
+ return _TEXT_MEDIA_FALLBACK
+
+
+def _http_last_modified(raw: str) -> Optional[str]:
+ if not raw:
+ return None
+ try:
+ dt = parse_iso_datetime(raw)
+ except Exception:
+ return None
+ return format_datetime(dt.astimezone(timezone.utc), usegmt=True)
+
+
+def _entry_from_stat(
+ request: Request,
+ resource_path: str,
+ stat: dict[str, Any],
+ *,
+ root_name: str = "resources",
+) -> dict[str, Any]:
+ is_dir = bool(stat.get("isDir", False))
+ name = stat.get("name") or (
+ resource_path.rstrip("/").split("/")[-1] if resource_path else root_name
+ )
+ return {
+ "href": _href_for_path(request, resource_path, is_dir=is_dir),
+ "name": name,
+ "is_dir": is_dir,
+ "size": int(stat.get("size", 0) or 0),
+ "mod_time": stat.get("modTime", ""),
+ "content_type": _content_type_for_name(str(name), is_dir=is_dir),
+ }
+
+
+def _propfind_xml(entries: list[dict[str, Any]]) -> bytes:
+ ET.register_namespace("d", _DAV_NAMESPACE)
+ multistatus = ET.Element(f"{{{_DAV_NAMESPACE}}}multistatus")
+
+ for entry in entries:
+ response = ET.SubElement(multistatus, f"{{{_DAV_NAMESPACE}}}response")
+ ET.SubElement(response, f"{{{_DAV_NAMESPACE}}}href").text = entry["href"]
+
+ propstat = ET.SubElement(response, f"{{{_DAV_NAMESPACE}}}propstat")
+ prop = ET.SubElement(propstat, f"{{{_DAV_NAMESPACE}}}prop")
+
+ ET.SubElement(prop, f"{{{_DAV_NAMESPACE}}}displayname").text = entry["name"]
+ resource_type = ET.SubElement(prop, f"{{{_DAV_NAMESPACE}}}resourcetype")
+ if entry["is_dir"]:
+ ET.SubElement(resource_type, f"{{{_DAV_NAMESPACE}}}collection")
+ else:
+ ET.SubElement(prop, f"{{{_DAV_NAMESPACE}}}getcontentlength").text = str(entry["size"])
+ ET.SubElement(prop, f"{{{_DAV_NAMESPACE}}}getcontenttype").text = entry["content_type"]
+
+ last_modified = _http_last_modified(entry["mod_time"])
+ if last_modified:
+ ET.SubElement(prop, f"{{{_DAV_NAMESPACE}}}getlastmodified").text = last_modified
+
+ ET.SubElement(propstat, f"{{{_DAV_NAMESPACE}}}status").text = "HTTP/1.1 200 OK"
+
+ return ET.tostring(multistatus, encoding="utf-8", xml_declaration=True)
+
+
+def _depth_header(request: Request) -> int:
+ depth = (request.headers.get("Depth", "1") or "1").strip().lower()
+ if depth == "0":
+ return 0
+ return 1
+
+
+def _destination_path(destination: str) -> str:
+ parsed = urlparse(destination)
+ raw_path = parsed.path if parsed.scheme else destination
+ normalized = raw_path.rstrip("/")
+ prefix = "/webdav/resources"
+ if normalized == prefix:
+ return ""
+ if not normalized.startswith(prefix + "/"):
+ raise InvalidArgumentError("Destination must stay under /webdav/resources")
+ return _normalized_resource_path(normalized[len(prefix) + 1 :])
+
+
+async def _write_text_resource(service, uri: str, content: str, ctx: RequestContext) -> None:
+ """Persist UTF-8 text content and refresh derived summaries before returning."""
+ await service.viking_fs.write_file(uri, content, ctx=ctx)
+ await service.resources.summarize([uri], ctx=ctx)
+
+
+async def _safe_stat(service, uri: str, ctx: RequestContext) -> Optional[dict[str, Any]]:
+ try:
+ return await service.fs.stat(uri, ctx=ctx)
+ except (FileNotFoundError, NotFoundError):
+ return None
+
+
+async def _ensure_parent_directory(
+ service, uri: str, ctx: RequestContext
+) -> Optional[dict[str, Any]]:
+ parent = VikingURI(uri).parent
+ if parent is None:
+ return None
+ return await _safe_stat(service, parent.uri, ctx)
+
+
+def _exposed_child_entries(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ exposed: list[dict[str, Any]] = []
+ for entry in entries:
+ name = str(entry.get("name", "") or "")
+ if not name or name in {".", ".."}:
+ continue
+ if name in _RESERVED_FILENAMES:
+ continue
+ exposed.append(entry)
+ return exposed
+
+
[email protected]_route("", methods=["OPTIONS"])
[email protected]_route("/{resource_path:path}", methods=["OPTIONS"])
+async def options(resource_path: str = ""):
+ return FastAPIResponse(status_code=204, headers=_webdav_headers())
+
+
[email protected]_route("", methods=["PROPFIND"])
[email protected]_route("/{resource_path:path}", methods=["PROPFIND"])
+async def propfind(
+ request: Request,
+ resource_path: str = "",
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ try:
+ normalized_path = _normalized_resource_path(resource_path)
+ _ensure_exposed_path(normalized_path)
+ except InvalidArgumentError as exc:
+ return _error(400, exc.message)
+ except NotFoundError:
+ return _error(404, "Not found")
+
+ service = get_service()
+ uri = _resource_uri(normalized_path)
+ stat = await _safe_stat(service, uri, _ctx)
+ if stat is None:
+ return _error(404, "Not found")
+
+ entries = [_entry_from_stat(request, normalized_path, stat)]
+ if _depth_header(request) > 0 and stat.get("isDir", False):
+ children = await service.fs.ls(
+ uri,
+ ctx=_ctx,
+ output="original",
+ show_all_hidden=True,
+ node_limit=10000,
+ )
+ for child in _exposed_child_entries(children):
+ child_name = str(child["name"])
+ child_path = child_name if not normalized_path else f"{normalized_path}/{child_name}"
+ entries.append(_entry_from_stat(request, child_path, child))
+
+ return FastAPIResponse(
+ content=_propfind_xml(entries),
+ status_code=207,
+ media_type="application/xml",
+ headers=_webdav_headers(),
+ )
+
+
[email protected]_route("", methods=["GET", "HEAD"])
[email protected]_route("/{resource_path:path}", methods=["GET", "HEAD"])
+async def get_or_head(
+ request: Request,
+ resource_path: str = "",
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ try:
+ normalized_path = _normalized_resource_path(resource_path)
+ _ensure_exposed_path(normalized_path)
+ except InvalidArgumentError as exc:
+ return _error(400, exc.message)
+ except NotFoundError:
+ return _error(404, "Not found")
+
+ if not normalized_path:
+ return _error(405, "GET is only supported for files")
+
+ service = get_service()
+ uri = _resource_uri(normalized_path)
+ stat = await _safe_stat(service, uri, _ctx)
+ if stat is None:
+ return _error(404, "Not found")
+ if stat.get("isDir", False):
+ return _error(405, "GET is only supported for files")
+
+ body = b"" if request.method == "HEAD" else await service.fs.read_file_bytes(uri, ctx=_ctx)
+ headers = _webdav_headers()
+ headers["Content-Length"] = str(int(stat.get("size", 0) or 0))
+ last_modified = _http_last_modified(str(stat.get("modTime", "") or ""))
+ if last_modified:
+ headers["Last-Modified"] = last_modified
+
+ return FastAPIResponse(
+ content=body,
+ media_type=_content_type_for_name(str(stat.get("name", "")), is_dir=False),
+ headers=headers,
+ )
+
+
[email protected]_route("", methods=["PUT"])
[email protected]_route("/{resource_path:path}", methods=["PUT"])
+async def put(
+ request: Request,
+ resource_path: str = "",
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ try:
+ normalized_path = _normalized_resource_path(resource_path)
+ _ensure_exposed_path(normalized_path)
+ except InvalidArgumentError as exc:
+ return _error(400, exc.message)
+ except NotFoundError:
+ return _error(404, "Not found")
+
+ if not normalized_path:
+ return _error(405, "PUT requires a file path")
+
+ raw_body = await request.body()
+ try:
+ content = raw_body.decode("utf-8")
+ except UnicodeDecodeError:
+ return _error(415, "Phase 1 WebDAV only supports UTF-8 text content")
+
+ service = get_service()
+ uri = _resource_uri(normalized_path)
+ stat = await _safe_stat(service, uri, _ctx)
+
+ parent_stat = await _ensure_parent_directory(service, uri, _ctx)
+ if parent_stat is None or not parent_stat.get("isDir", False):
+ return _error(409, "Parent collection does not exist")
+
+ if stat is not None:
+ if stat.get("isDir", False):
+ return _error(405, "PUT is only supported for files")
+ await _write_text_resource(service, uri, content, _ctx)
+ return FastAPIResponse(status_code=204, headers=_webdav_headers())
+
+ await _write_text_resource(service, uri, content, _ctx)
+ headers = _webdav_headers()
+ headers["Location"] = _href_for_path(request, normalized_path, is_dir=False)
+ return FastAPIResponse(status_code=201, headers=headers)
+
+
[email protected]_route("", methods=["DELETE"])
[email protected]_route("/{resource_path:path}", methods=["DELETE"])
+async def delete(
+ resource_path: str = "",
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ try:
+ normalized_path = _normalized_resource_path(resource_path)
+ _ensure_exposed_path(normalized_path)
+ except InvalidArgumentError as exc:
+ return _error(400, exc.message)
+ except NotFoundError:
+ return _error(404, "Not found")
+
+ if not normalized_path:
+ return _error(405, "Deleting the resources root is not supported")
+
+ service = get_service()
+ uri = _resource_uri(normalized_path)
+ stat = await _safe_stat(service, uri, _ctx)
+ if stat is None:
+ return _error(404, "Not found")
+
+ await service.fs.rm(uri, ctx=_ctx, recursive=bool(stat.get("isDir", False)))
+ return FastAPIResponse(status_code=204, headers=_webdav_headers())
+
+
[email protected]_route("", methods=["MKCOL"])
[email protected]_route("/{resource_path:path}", methods=["MKCOL"])
+async def mkcol(
+ resource_path: str = "",
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ try:
+ normalized_path = _normalized_resource_path(resource_path)
+ _ensure_exposed_path(normalized_path)
+ except InvalidArgumentError as exc:
+ return _error(400, exc.message)
+ except NotFoundError:
+ return _error(404, "Not found")
+
+ if not normalized_path:
+ return _error(405, "MKCOL requires a collection path")
+
+ service = get_service()
+ uri = _resource_uri(normalized_path)
+ stat = await _safe_stat(service, uri, _ctx)
+ if stat is not None:
+ return _error(405, "Collection already exists")
+
+ parent_stat = await _ensure_parent_directory(service, uri, _ctx)
+ if parent_stat is None or not parent_stat.get("isDir", False):
+ return _error(409, "Parent collection does not exist")
+
+ await service.fs.mkdir(uri, ctx=_ctx)
+ return FastAPIResponse(status_code=201, headers=_webdav_headers())
+
+
[email protected]_route("", methods=["MOVE"])
[email protected]_route("/{resource_path:path}", methods=["MOVE"])
+async def move(
+ request: Request,
+ resource_path: str = "",
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ destination = request.headers.get("Destination", "")
+ if not destination:
+ return _error(400, "Destination header is required")
+
+ try:
+ normalized_path = _normalized_resource_path(resource_path)
+ _ensure_exposed_path(normalized_path)
+ destination_path = _destination_path(destination)
+ _ensure_exposed_path(destination_path)
+ except InvalidArgumentError as exc:
+ return _error(400, exc.message)
+ except NotFoundError:
+ return _error(404, "Not found")
+
+ if not normalized_path:
+ return _error(405, "Moving the resources root is not supported")
+
+ service = get_service()
+ src_uri = _resource_uri(normalized_path)
+ dst_uri = _resource_uri(destination_path)
+ src_stat = await _safe_stat(service, src_uri, _ctx)
+ if src_stat is None:
+ return _error(404, "Not found")
+
+ dst_parent_stat = await _ensure_parent_directory(service, dst_uri, _ctx)
+ if dst_parent_stat is None or not dst_parent_stat.get("isDir", False):
+ return _error(409, "Destination parent collection does not exist")
+
+ overwrite = (request.headers.get("Overwrite", "T") or "T").strip().upper() != "F"
+ dst_stat = await _safe_stat(service, dst_uri, _ctx)
+ if dst_stat is not None:
+ if not overwrite:
+ return _error(412, "Destination already exists")
+ await service.fs.rm(dst_uri, ctx=_ctx, recursive=bool(dst_stat.get("isDir", False)))
+
+ await service.fs.mv(src_uri, dst_uri, ctx=_ctx)
+ status_code = 204 if dst_stat is not None else 201
+ return FastAPIResponse(status_code=status_code, headers=_webdav_headers())
diff --git a/tests/server/test_api_webdav.py b/tests/server/test_api_webdav.py
new file mode 100644
index 000000000..b44b03638
--- /dev/null
+++ b/tests/server/test_api_webdav.py
@@ -0,0 +1,175 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+"""Tests for the resources-only WebDAV adapter."""
+
+import xml.etree.ElementTree as ET
+
+import httpx
+
+
+def _dav_display_names(xml_bytes: bytes) -> list[str]:
+ root = ET.fromstring(xml_bytes)
+ return [node.text or "" for node in root.findall(".//{DAV:}displayname")]
+
+
+def _webdav_path_from_uri(uri: str) -> str:
+ prefix = "viking://resources"
+ assert uri.startswith(prefix)
+ return uri[len(prefix) :].lstrip("/")
+
+
+async def test_webdav_options_advertises_dav(client: httpx.AsyncClient):
+ resp = await client.request("OPTIONS", "/webdav/resources")
+ assert resp.status_code == 204
+ assert resp.headers["DAV"] == "1"
+ assert "PROPFIND" in resp.headers["Allow"]
+
+
+async def test_webdav_propfind_hides_reserved_files_but_keeps_user_dotdirs(client_with_resource):
+ client, uri = client_with_resource
+ webdav_path = _webdav_path_from_uri(uri)
+
+ mkcol_resp = await client.request("MKCOL", f"/webdav/resources/{webdav_path}/.obsidian")
+ assert mkcol_resp.status_code == 201
+
+ put_resp = await client.request(
+ "PUT",
+ f"/webdav/resources/{webdav_path}/.obsidian/config.json",
+ content='{"theme":"light"}'.encode("utf-8"),
+ )
+ assert put_resp.status_code == 201
+
+ resp = await client.request(
+ "PROPFIND",
+ f"/webdav/resources/{webdav_path}",
+ headers={"Depth": "1"},
+ )
+ assert resp.status_code == 207
+
+ names = _dav_display_names(resp.content)
+ assert ".obsidian" in names
+ assert ".abstract.md" not in names
+ assert ".overview.md" not in names
+ assert ".relations.json" not in names
+
+
+async def test_webdav_rejects_direct_access_to_reserved_semantic_files(client_with_resource):
+ client, uri = client_with_resource
+ webdav_path = _webdav_path_from_uri(uri)
+
+ resp = await client.get(f"/webdav/resources/{webdav_path}/.abstract.md")
+ assert resp.status_code == 404
+
+
+async def test_webdav_put_create_get_and_replace_text_file(client: httpx.AsyncClient):
+ mkcol_resp = await client.request("MKCOL", "/webdav/resources/scratch")
+ assert mkcol_resp.status_code == 201
+
+ create_resp = await client.request(
+ "PUT",
+ "/webdav/resources/scratch/notes.md",
+ content="# Notes\n\nhello".encode("utf-8"),
+ )
+ assert create_resp.status_code == 201
+
+ get_resp = await client.get("/webdav/resources/scratch/notes.md")
+ assert get_resp.status_code == 200
+ assert get_resp.text == "# Notes\n\nhello"
+
+ replace_resp = await client.request(
+ "PUT",
+ "/webdav/resources/scratch/notes.md",
+ content="# Notes\n\nupdated".encode("utf-8"),
+ )
+ assert replace_resp.status_code == 204
+
+ get_resp = await client.get("/webdav/resources/scratch/notes.md")
+ assert get_resp.status_code == 200
+ assert get_resp.text == "# Notes\n\nupdated"
+
+
+async def test_webdav_put_replace_reuses_direct_write_path(
+ client: httpx.AsyncClient,
+ service,
+ monkeypatch,
+):
+ assert (await client.request("MKCOL", "/webdav/resources/replace-space")).status_code == 201
+ assert (
+ await client.request(
+ "PUT",
+ "/webdav/resources/replace-space/notes.md",
+ content="first version".encode("utf-8"),
+ )
+ ).status_code == 201
+
+ calls: list[tuple[str, object]] = []
+
+ async def _unexpected_fs_write(*args, **kwargs):
+ raise AssertionError("WebDAV replace should not use service.fs.write")
+
+ async def _tracked_write_file(uri, content, ctx=None):
+ calls.append(("write_file", uri, content))
+
+ async def _tracked_summarize(resource_uris, ctx=None, **kwargs):
+ calls.append(("summarize", tuple(resource_uris)))
+ return {"status": "success"}
+
+ monkeypatch.setattr(service.fs, "write", _unexpected_fs_write)
+ monkeypatch.setattr(service.viking_fs, "write_file", _tracked_write_file)
+ monkeypatch.setattr(service.resources, "summarize", _tracked_summarize)
+
+ replace_resp = await client.request(
+ "PUT",
+ "/webdav/resources/replace-space/notes.md",
+ content="second version".encode("utf-8"),
+ )
+
+ assert replace_resp.status_code == 204
+ assert calls == [
+ ("write_file", "viking://resources/replace-space/notes.md", "second version"),
+ ("summarize", ("viking://resources/replace-space/notes.md",)),
+ ]
+
+
+async def test_webdav_put_rejects_non_utf8_content(client: httpx.AsyncClient):
+ assert (await client.request("MKCOL", "/webdav/resources/binary-space")).status_code == 201
+
+ resp = await client.request(
+ "PUT",
+ "/webdav/resources/binary-space/blob.bin",
+ content=b"\xff\xfe\xfd",
+ )
+
+ assert resp.status_code == 415
+
+
+async def test_webdav_move_and_delete_text_file(client: httpx.AsyncClient):
+ assert (await client.request("MKCOL", "/webdav/resources/move-space")).status_code == 201
+ assert (
+ await client.request(
+ "PUT",
+ "/webdav/resources/move-space/source.md",
+ content="source body".encode("utf-8"),
+ )
+ ).status_code == 201
+
+ move_resp = await client.request(
+ "MOVE",
+ "/webdav/resources/move-space/source.md",
+ headers={"Destination": "http://testserver/webdav/resources/move-space/renamed.md"},
+ )
+ assert move_resp.status_code == 201
+
+ missing_resp = await client.get("/webdav/resources/move-space/source.md")
+ assert missing_resp.status_code == 404
+
+ moved_resp = await client.get("/webdav/resources/move-space/renamed.md")
+ assert moved_resp.status_code == 200
+ assert moved_resp.text == "source body"
+
+ delete_resp = await client.request("DELETE", "/webdav/resources/move-space/renamed.md")
+ assert delete_resp.status_code == 204
+
+ deleted_resp = await client.get("/webdav/resources/move-space/renamed.md")
+ assert deleted_resp.status_code == 404