Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(workbench): make attachment uploads reliable (#1284)

Call White3240978fead8
diff --git a/core/workbench_media.py b/core/workbench_media.py
index 2dbf1ed47..30f0e58ba 100644
--- a/core/workbench_media.py
+++ b/core/workbench_media.py
@@ -22,9 +22,12 @@ import io
import logging
import os
import re
+import threading
import uuid
+from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
+from typing import BinaryIO
from urllib.parse import urlparse
from sqlalchemy.engine import Connection
@@ -37,6 +40,12 @@ logger = logging.getLogger(__name__)
MAX_SHOW_SCREENSHOT_LONG_EDGE = 2048
MAX_SHOW_SCREENSHOT_BYTES = 25 * 1024 * 1024
+MAX_WORKBENCH_ATTACHMENT_BYTES = 100 * 1024 * 1024
+_WORKBENCH_UPLOAD_CHUNK_BYTES = 1024 * 1024
+_WORKBENCH_UPLOAD_ID_RE = re.compile(r"[A-Za-z0-9_-]{16,80}")
+_WORKBENCH_BASE64_WHITESPACE_DELETE = str.maketrans("", "", " \t\r\n\v\f")
+_WORKBENCH_UPLOAD_LOCKS_GUARD = threading.Lock()
+_WORKBENCH_UPLOAD_LOCKS: dict[str, "_WorkbenchUploadLock"] = {}
_SHOW_SCREENSHOT_DATA_URL_RE = re.compile(
r"\Adata:(image/(?P<format>png|webp));base64,(?P<data>[A-Za-z0-9+/=]+)\Z",
re.IGNORECASE,
@@ -56,6 +65,198 @@ class MaterializedShowScreenshot:
height: int
+class WorkbenchAttachmentUploadError(ValueError):
+ """A user-correctable workbench attachment upload failure."""
+
+ def __init__(self, code: str, message: str, status: int) -> None:
+ super().__init__(message)
+ self.code = code
+ self.message = message
+ self.status = status
+
+
+@dataclass(frozen=True)
+class MaterializedWorkbenchAttachment:
+ token: str
+ name: str
+ mime: str
+ size: int
+ kind: str
+ path: str
+ width: int | None
+ height: int | None
+ created: bool
+
+
+@dataclass
+class _WorkbenchUploadLock:
+ lock: threading.Lock
+ users: int = 0
+
+
+def normalize_workbench_upload_id(value: object) -> str | None:
+ """Validate the optional stable browser key used for upload retries."""
+ if value is None or value == "":
+ return None
+ if not isinstance(value, str) or _WORKBENCH_UPLOAD_ID_RE.fullmatch(value) is None:
+ raise WorkbenchAttachmentUploadError("invalid_upload", "Upload ID is invalid", 400)
+ return value
+
+
+def decode_legacy_workbench_attachment(data: str) -> io.BytesIO:
+ """Decode the pre-multipart JSON contract without relaxing validation."""
+ encoded_data = data
+ if encoded_data.startswith("data:") and "," in encoded_data:
+ encoded_data = encoded_data.split(",", 1)[1]
+ encoded_data = encoded_data.translate(_WORKBENCH_BASE64_WHITESPACE_DELETE)
+ max_encoded_bytes = ((MAX_WORKBENCH_ATTACHMENT_BYTES + 2) // 3) * 4
+ if len(encoded_data) > max_encoded_bytes:
+ raise WorkbenchAttachmentUploadError(
+ "too_large",
+ "Attachment exceeds the size limit",
+ 413,
+ )
+ try:
+ return io.BytesIO(base64.b64decode(encoded_data, validate=True))
+ except (binascii.Error, ValueError) as exc:
+ raise WorkbenchAttachmentUploadError(
+ "invalid_upload",
+ "Attachment data is invalid",
+ 400,
+ ) from exc
+
+
+@contextmanager
+def workbench_attachment_upload_lock(session_id: str, upload_id: str | None):
+ """Serialize retries for one upload key without serializing other files."""
+ if upload_id is None:
+ yield
+ return
+ key = f"{session_id}\0{upload_id}"
+ with _WORKBENCH_UPLOAD_LOCKS_GUARD:
+ entry = _WORKBENCH_UPLOAD_LOCKS.get(key)
+ if entry is None:
+ entry = _WorkbenchUploadLock(lock=threading.Lock())
+ _WORKBENCH_UPLOAD_LOCKS[key] = entry
+ entry.users += 1
+ entry.lock.acquire()
+ try:
+ yield
+ finally:
+ entry.lock.release()
+ with _WORKBENCH_UPLOAD_LOCKS_GUARD:
+ entry.users -= 1
+ if entry.users == 0:
+ _WORKBENCH_UPLOAD_LOCKS.pop(key, None)
+
+
+def materialize_workbench_attachment(
+ conn: Connection,
+ *,
+ scope_id: str | None,
+ session_id: str,
+ file_name: object,
+ content_type: object,
+ source: BinaryIO,
+ upload_id: object = None,
+) -> MaterializedWorkbenchAttachment:
+ """Stream one browser upload to disk and register its media capability.
+
+ The multipart parser already enforces the same cap while receiving the body;
+ this second boundary also covers the legacy JSON compatibility path and any
+ future caller that hands us a file-like object directly.
+ """
+ raw_name = file_name.strip() if isinstance(file_name, str) else ""
+ name = raw_name.replace("\\", "/").rsplit("/", 1)[-1].strip() or "upload"
+ raw_mime = content_type.strip() if isinstance(content_type, str) else ""
+ mime = raw_mime[:255] or "application/octet-stream"
+ safe_name = re.sub(r"[^A-Za-z0-9._-]+", "_", name).strip("_") or "upload"
+ safe_name = safe_name[-160:]
+ stable_upload_id = normalize_workbench_upload_id(upload_id)
+
+ upload_dir = paths.get_attachments_dir() / "avibe" / session_id
+ upload_dir.mkdir(parents=True, exist_ok=True)
+ path_id = stable_upload_id or uuid.uuid4().hex[:16]
+ if stable_upload_id:
+ for candidate in sorted(upload_dir.glob(f"{stable_upload_id}_*")):
+ if not candidate.is_file():
+ continue
+ candidate_path = str(candidate.resolve())
+ existing = media_service.get_live_user_upload_by_path(
+ conn,
+ session_id=session_id,
+ local_path=candidate_path,
+ )
+ if existing:
+ return MaterializedWorkbenchAttachment(
+ token=existing["token"],
+ name=existing.get("file_name") or name,
+ mime=existing.get("content_type") or mime,
+ size=existing.get("size_bytes") or candidate.stat().st_size,
+ kind=existing.get("kind") or "file",
+ path=candidate_path,
+ width=existing.get("width_px"),
+ height=existing.get("height_px"),
+ created=False,
+ )
+ candidate.unlink(missing_ok=True)
+ for stale_temp in upload_dir.glob(f".{stable_upload_id}.*.tmp"):
+ stale_temp.unlink(missing_ok=True)
+
+ local_path = upload_dir / f"{path_id}_{safe_name}"
+ canonical_path = str(local_path.resolve())
+ temp_path = upload_dir / f".{path_id}.{uuid.uuid4().hex[:8]}.tmp"
+ size = 0
+ try:
+ with temp_path.open("xb") as target:
+ while True:
+ chunk = source.read(_WORKBENCH_UPLOAD_CHUNK_BYTES)
+ if not chunk:
+ break
+ if not isinstance(chunk, bytes):
+ raise TypeError("attachment stream must return bytes")
+ size += len(chunk)
+ if size > MAX_WORKBENCH_ATTACHMENT_BYTES:
+ raise WorkbenchAttachmentUploadError(
+ "too_large",
+ "File exceeds the attachment size limit",
+ 413,
+ )
+ target.write(chunk)
+ if size == 0:
+ raise WorkbenchAttachmentUploadError("empty_file", "File is empty", 400)
+ os.replace(temp_path, local_path)
+ canonical_path = str(local_path.resolve(strict=True))
+ kind = "image" if mime.startswith("image/") else "file"
+ token = media_service.register(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ kind=kind,
+ source="user_upload",
+ local_path=canonical_path,
+ file_name=name,
+ content_type=mime,
+ )
+ row = media_service.get_by_token(conn, token)
+ except Exception:
+ temp_path.unlink(missing_ok=True)
+ local_path.unlink(missing_ok=True)
+ raise
+
+ return MaterializedWorkbenchAttachment(
+ token=token,
+ name=name,
+ mime=mime,
+ size=size,
+ kind=kind,
+ path=canonical_path,
+ width=row.get("width_px") if row else None,
+ height=row.get("height_px") if row else None,
+ created=True,
+ )
+
+
def register_agent_reply_media(
conn: Connection,
*,
diff --git a/storage/media_service.py b/storage/media_service.py
index 88866ccaf..4c36f6316 100644
--- a/storage/media_service.py
+++ b/storage/media_service.py
@@ -148,3 +148,21 @@ def get_by_token(conn: Connection, token: str) -> Optional[dict[str, Any]]:
return None
row = conn.execute(select(media_objects).where(media_objects.c.token == token)).mappings().first()
return dict(row) if row else None
+
+
+def get_live_user_upload_by_path(
+ conn: Connection,
+ *,
+ session_id: str,
+ local_path: str,
+) -> Optional[dict[str, Any]]:
+ """Return an existing idempotent browser upload for this session/path."""
+ row = conn.execute(
+ select(media_objects).where(
+ media_objects.c.session_id == session_id,
+ media_objects.c.source == "user_upload",
+ media_objects.c.local_path == local_path,
+ media_objects.c.revoked_at.is_(None),
+ )
+ ).mappings().first()
+ return dict(row) if row else None
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 11872ce6a..34dd7bb20 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -6,10 +6,12 @@ from types import SimpleNamespace
import pytest
+from fastapi import Request as FastAPIRequest
from storage.importer import ensure_sqlite_state
from vibe.ui_compat import (
TEST_REMOTE_ADDR_HEADER,
CompatApp,
+ _read_json_payload,
normalize_response,
route_path_to_fastapi,
run_maybe_async,
@@ -2308,6 +2310,52 @@ def test_run_maybe_async_offloads_sync_handlers_without_losing_context():
assert tick == "tick"
+def test_json_payload_parsing_runs_off_the_asgi_loop(monkeypatch):
+ parse_threads: list[int] = []
+ original_loads = json.loads
+
+ def tracked_loads(payload):
+ parse_threads.append(threading.get_ident())
+ return original_loads(payload)
+
+ monkeypatch.setattr("vibe.ui_compat.json.loads", tracked_loads)
+
+ async def receive():
+ return {
+ "type": "http.request",
+ "body": b'{"attachment":"legacy"}',
+ "more_body": False,
+ }
+
+ starlette_request = FastAPIRequest(
+ {
+ "type": "http",
+ "asgi": {"version": "3.0"},
+ "http_version": "1.1",
+ "method": "POST",
+ "scheme": "http",
+ "path": "/legacy-upload",
+ "raw_path": b"/legacy-upload",
+ "query_string": b"",
+ "headers": [(b"content-type", b"application/json")],
+ "client": ("127.0.0.1", 12345),
+ "server": ("testserver", 80),
+ },
+ receive,
+ )
+
+ async def exercise():
+ loop_thread = threading.get_ident()
+ payload = await _read_json_payload(starlette_request)
+ return loop_thread, payload
+
+ loop_thread, payload = asyncio.run(exercise())
+
+ assert payload == {"attachment": "legacy"}
+ assert parse_threads
+ assert parse_threads[0] != loop_thread
+
+
def test_wechat_qr_poll_marks_bind_hint_and_schedules_managed_restart(monkeypatch):
from vibe import runtime
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 2a9f693e7..2a15edd46 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -13,7 +13,9 @@ from __future__ import annotations
import json
import sqlite3
import sys
+from contextlib import contextmanager
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -322,8 +324,6 @@ def test_workbench_dispatch_propagates_attachment_and_resolved_identity(
isolated_state,
tmp_path,
):
- import base64
-
from vibe.ui_server import app
_, session_id = _make_session(tmp_path)
@@ -332,14 +332,12 @@ def test_workbench_dispatch_propagates_attachment_and_resolved_identity(
headers = csrf_headers(client, "http://127.0.0.1:15131")
upload = client.post(
f"/api/sessions/{session_id}/attachments",
- json={
- "name": "diagram.png",
- "mime": "image/png",
- "data": base64.b64encode(b"attachment-bytes").decode("ascii"),
- },
+ data={"upload_id": "upload-id-123456"},
+ files={"file": ("diagram.png", b"attachment-bytes", "image/png")},
headers=headers,
base_url="http://127.0.0.1:15131",
)
+ assert upload.status_code == 201
with patch("vibe.internal_client.dispatch_async", dispatch):
response = client.post(
@@ -1668,13 +1666,14 @@ def test_patch_session_rejects_unknown_target_scope_as_invalid_value(isolated_st
assert response.status_code == 400
-def test_standalone_session_accepts_attachment_upload(isolated_state):
+def test_standalone_session_accepts_attachment_upload(isolated_state, monkeypatch):
import base64
+ import threading
from core.services import sessions as sessions_service
from storage.db import create_sqlite_engine
from storage.models import media_objects
- from vibe.ui_server import app
+ from vibe import ui_server
engine = create_sqlite_engine()
with engine.begin() as conn:
@@ -1685,13 +1684,44 @@ def test_standalone_session_accepts_attachment_upload(isolated_state):
visibility="foreground",
)
- client = app.test_client()
+ loop_threads: list[int] = []
+ engine_threads: list[int] = []
+ session_threads: list[int] = []
+ decode_threads: list[int] = []
+ original_dispatch = ui_server._dispatch_native_ui_request
+ original_projects_engine = ui_server._projects_engine
+ original_get_session = sessions_service.get_session
+ original_b64decode = base64.b64decode
+
+ async def tracked_dispatch(starlette_request, handler):
+ loop_threads.append(threading.get_ident())
+ return await original_dispatch(starlette_request, handler)
+
+ def tracked_projects_engine():
+ engine_threads.append(threading.get_ident())
+ return original_projects_engine()
+
+ def tracked_get_session(*args, **kwargs):
+ session_threads.append(threading.get_ident())
+ return original_get_session(*args, **kwargs)
+
+ def tracked_b64decode(*args, **kwargs):
+ decode_threads.append(threading.get_ident())
+ return original_b64decode(*args, **kwargs)
+
+ monkeypatch.setattr(ui_server, "_dispatch_native_ui_request", tracked_dispatch)
+ monkeypatch.setattr(ui_server, "_projects_engine", tracked_projects_engine)
+ monkeypatch.setattr(sessions_service, "get_session", tracked_get_session)
+ monkeypatch.setattr(base64, "b64decode", tracked_b64decode)
+
+ client = ui_server.app.test_client()
response = client.post(
f"/api/sessions/{session['id']}/attachments",
json={
"name": "standalone.txt",
"mime": "text/plain",
- "data": base64.b64encode(b"standalone upload").decode("ascii"),
+ "data": "data:text/plain;base64,"
+ + base64.b64encode(b"standalone upload").decode("ascii"),
},
headers=csrf_headers(client),
)
@@ -1704,6 +1734,343 @@ def test_standalone_session_accepts_attachment_upload(isolated_state):
).mappings().one()
assert row["scope_id"] is None
assert row["session_id"] == session["id"]
+ assert len(loop_threads) == 1
+ assert engine_threads
+ assert session_threads
+ assert decode_threads
+ assert all(
+ thread_id != loop_threads[0]
+ for thread_id in (*engine_threads, *session_threads, *decode_threads)
+ )
+
+
+def test_legacy_attachment_upload_preserves_json_contract(isolated_state, tmp_path, monkeypatch):
+ import base64
+
+ from core import workbench_media
+ from storage import media_service
+ from storage.db import create_sqlite_engine
+ from vibe.ui_server import app
+
+ raw = b"legacy upload"
+ monkeypatch.setattr(workbench_media, "MAX_WORKBENCH_ATTACHMENT_BYTES", len(raw))
+ encoded = base64.b64encode(raw).decode("ascii")
+ wrapped = " \t\r\n\v\f".join(encoded[index : index + 4] for index in range(0, len(encoded), 4))
+ _, session_id = _make_session(tmp_path)
+ client = app.test_client()
+ response = client.post(
+ f"/api/sessions/{session_id}/attachments",
+ content=json.dumps(
+ {
+ "name": "legacy.txt",
+ "mime": "text/plain",
+ "data": f"data:text/plain;base64,{wrapped}",
+ }
+ ),
+ headers={
+ **csrf_headers(client),
+ "Content-Type": "application/vnd.avibe+json; charset=utf-8",
+ },
+ )
+
+ assert response.status_code == 201
+ payload = response.get_json()
+ assert payload["size"] == len(raw)
+ with create_sqlite_engine().connect() as conn:
+ row = media_service.get_by_token(conn, payload["token"])
+ assert row is not None
+ assert Path(row["local_path"]).read_bytes() == raw
+
+
+def test_legacy_attachment_upload_rejects_invalid_base64(isolated_state, tmp_path):
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ client = app.test_client()
+ response = client.post(
+ f"/api/sessions/{session_id}/attachments",
+ json={"name": "broken.txt", "mime": "text/plain", "data": "aGVs!bG8="},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 400
+ assert response.get_json()["code"] == "invalid_upload"
+
+
+def test_legacy_attachment_upload_rejects_oversized_base64(isolated_state, tmp_path, monkeypatch):
+ import base64
+
+ from core import workbench_media
+ from vibe.ui_server import app
+
+ monkeypatch.setattr(workbench_media, "MAX_WORKBENCH_ATTACHMENT_BYTES", 4)
+ _, session_id = _make_session(tmp_path)
+ client = app.test_client()
+ response = client.post(
+ f"/api/sessions/{session_id}/attachments",
+ json={
+ "name": "large.txt",
+ "mime": "text/plain",
+ "data": base64.b64encode(b"1234567").decode("ascii"),
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 413
+ assert response.get_json()["code"] == "too_large"
+ assert response.get_json()["max_file_bytes"] == 4
+
+
+def test_attachment_upload_preserves_unicode_name_and_binary_body(isolated_state, tmp_path):
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ client = app.test_client()
+
+ response = client.post(
+ f"/api/sessions/{session_id}/attachments",
+ data={"upload_id": "upload-id-123456"},
+ files={"file": ("报告.txt", b"raw-binary\x00body", "text/plain")},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 201
+ payload = response.get_json()
+ assert payload["name"] == "报告.txt"
+ assert payload["mime"] == "text/plain"
+ assert payload["size"] == 15
+
+ from storage import media_service
+ from storage.db import create_sqlite_engine
+
+ with create_sqlite_engine().connect() as conn:
+ row = media_service.get_by_token(conn, payload["token"])
+ assert row is not None
+ assert Path(row["local_path"]).read_bytes() == b"raw-binary\x00body"
+
+
+def test_attachment_upload_rejects_oversized_part_without_partial_file(
+ isolated_state,
+ tmp_path,
+ monkeypatch,
+):
+ from config import paths
+ from core import workbench_media
+ from vibe.ui_server import app
+
+ monkeypatch.setattr(workbench_media, "MAX_WORKBENCH_ATTACHMENT_BYTES", 4)
+ _, session_id = _make_session(tmp_path)
+ client = app.test_client()
+
+ response = client.post(
+ f"/api/sessions/{session_id}/attachments",
+ data={"upload_id": "upload-id-123456"},
+ files={"file": ("large.bin", b"12345", "application/octet-stream")},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 413
+ assert response.get_json() == {
+ "ok": False,
+ "error": {
+ "code": "too_large",
+ "message": "The file exceeds the attachment size limit.",
+ },
+ "code": "too_large",
+ "message": "The file exceeds the attachment size limit.",
+ "max_file_bytes": 4,
+ }
+ upload_dir = paths.get_attachments_dir() / "avibe" / session_id
+ assert not upload_dir.exists() or not list(upload_dir.iterdir())
+
+
+def test_attachment_upload_cleans_partial_file_after_registration_failure(
+ isolated_state,
+ tmp_path,
+ monkeypatch,
+):
+ from config import paths
+ from storage import media_service
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+
+ def fail_register(*_args, **_kwargs):
+ raise OSError("database unavailable")
+
+ monkeypatch.setattr(media_service, "register", fail_register)
+ client = app.test_client()
+ response = client.post(
+ f"/api/sessions/{session_id}/attachments",
+ data={"upload_id": "upload-id-123456"},
+ files={"file": ("note.txt", b"hello", "text/plain")},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 500
+ assert response.get_json()["error"]["code"] == "upload_failed"
+ upload_dir = paths.get_attachments_dir() / "avibe" / session_id
+ assert not upload_dir.exists() or not list(upload_dir.iterdir())
+
+
+def test_attachment_upload_cleans_failed_commit_before_releasing_upload_lock(
+ isolated_state,
+ tmp_path,
+ monkeypatch,
+):
+ from config import paths
+ from core import workbench_media
+ from storage import media_service
+ from storage.db import create_sqlite_engine
+ from vibe import ui_server
+
+ _, session_id = _make_session(tmp_path)
+ engine = create_sqlite_engine()
+ original_begin = engine.begin
+ original_lock = workbench_media.workbench_attachment_upload_lock
+ original_unlink = Path.unlink
+ fail_commit = True
+ lock_held = False
+ cleanup_lock_states: list[bool] = []
+
+ @contextmanager
+ def fail_first_commit():
+ nonlocal fail_commit
+ with original_begin() as conn:
+ yield conn
+ if fail_commit:
+ fail_commit = False
+ raise OSError("commit failed")
+
+ @contextmanager
+ def tracked_upload_lock(*args, **kwargs):
+ nonlocal lock_held
+ with original_lock(*args, **kwargs):
+ lock_held = True
+ try:
+ yield
+ finally:
+ lock_held = False
+
+ def tracked_unlink(path: Path, *args, **kwargs):
+ if path.name.startswith("upload-id-123456_"):
+ cleanup_lock_states.append(lock_held)
+ return original_unlink(path, *args, **kwargs)
+
+ monkeypatch.setattr(engine, "begin", fail_first_commit)
+ monkeypatch.setattr(ui_server, "_projects_engine", lambda: engine)
+ monkeypatch.setattr(
+ workbench_media,
+ "workbench_attachment_upload_lock",
+ tracked_upload_lock,
+ )
+ monkeypatch.setattr(Path, "unlink", tracked_unlink)
+
+ client = ui_server.app.test_client()
+ headers = csrf_headers(client)
+ first = client.post(
+ f"/api/sessions/{session_id}/attachments",
+ data={"upload_id": "upload-id-123456"},
+ files={"file": ("note.txt", b"first", "text/plain")},
+ headers=headers,
+ )
+ retried = client.post(
+ f"/api/sessions/{session_id}/attachments",
+ data={"upload_id": "upload-id-123456"},
+ files={"file": ("note.txt", b"retry", "text/plain")},
+ headers=headers,
+ )
+
+ assert first.status_code == 500
+ assert cleanup_lock_states == [True]
+ assert retried.status_code == 201
+ with engine.connect() as conn:
+ row = media_service.get_by_token(conn, retried.get_json()["token"])
+ assert row is not None
+ assert Path(row["local_path"]).read_bytes() == b"retry"
+ upload_dir = paths.get_attachments_dir() / "avibe" / session_id
+ assert list(upload_dir.iterdir()) == [Path(row["local_path"])]
+
+
+def test_attachment_upload_retry_reuses_committed_file_and_token(isolated_state, tmp_path):
+ from config import paths
+ from storage.db import create_sqlite_engine
+ from storage.models import media_objects
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ client = app.test_client()
+ headers = csrf_headers(client)
+
+ first = client.post(
+ f"/api/sessions/{session_id}/attachments",
+ data={"upload_id": "upload-id-123456"},
+ files={"file": ("note.txt", b"hello", "text/plain")},
+ headers=headers,
+ )
+ retried = client.post(
+ f"/api/sessions/{session_id}/attachments",
+ data={"upload_id": "upload-id-123456"},
+ files={"file": ("note.txt", b"hello", "text/plain")},
+ headers=headers,
+ )
+
+ assert first.status_code == 201
+ assert retried.status_code == 200
+ assert retried.get_json()["token"] == first.get_json()["token"]
+ upload_dir = paths.get_attachments_dir() / "avibe" / session_id
+ assert len(list(upload_dir.iterdir())) == 1
+ with create_sqlite_engine().connect() as conn:
+ rows = conn.execute(
+ select(media_objects.c.token).where(
+ media_objects.c.session_id == session_id,
+ media_objects.c.source == "user_upload",
+ )
+ ).all()
+ assert rows == [(first.get_json()["token"],)]
+
+
+def test_attachment_upload_errors_follow_configured_language(isolated_state, monkeypatch):
+ import threading
+
+ from core.services import settings as settings_service
+ from vibe import ui_server
+
+ loop_threads: list[int] = []
+ config_threads: list[int] = []
+ original_dispatch = ui_server._dispatch_native_ui_request
+
+ async def tracked_dispatch(starlette_request, handler):
+ loop_threads.append(threading.get_ident())
+ return await original_dispatch(starlette_request, handler)
+
+ def load_config():
+ config_threads.append(threading.get_ident())
+ return SimpleNamespace(language="zh")
+
+ monkeypatch.setattr(ui_server, "_dispatch_native_ui_request", tracked_dispatch)
+ monkeypatch.setattr(
+ settings_service,
+ "load_config_or_default",
+ load_config,
+ )
+ client = ui_server.app.test_client()
+
+ response = client.post(
+ "/api/sessions/ses_missing/attachments",
+ data={"upload_id": "upload-id-123456"},
+ files={"file": ("note.txt", b"hello", "text/plain")},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 404
+ assert response.get_json()["error"] == {
+ "code": "session_not_found",
+ "message": "当前会话已不可用。",
+ }
+ assert len(loop_threads) == 1
+ assert config_threads
+ assert all(thread_id != loop_threads[0] for thread_id in config_threads)
def test_patch_agent_name_only_backend_switch_blocked_while_turn_in_flight(isolated_state, tmp_path):
diff --git a/tests/test_workbench_media.py b/tests/test_workbench_media.py
index 62227c4ba..5627724dd 100644
--- a/tests/test_workbench_media.py
+++ b/tests/test_workbench_media.py
@@ -14,7 +14,7 @@ from datetime import datetime, timezone
from sqlalchemy import select
-from core.workbench_media import rewrite_agent_media
+from core.workbench_media import MAX_WORKBENCH_ATTACHMENT_BYTES, rewrite_agent_media
from storage import media_service, settings_service
from storage.db import create_sqlite_engine
from storage.migrations import run_migrations
@@ -25,6 +25,10 @@ def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+def test_workbench_attachment_limit_is_100_mib():
+ assert MAX_WORKBENCH_ATTACHMENT_BYTES == 100 * 1024 * 1024
+
+
def _png_bytes(width: int, height: int) -> bytes:
"""A genuinely valid PNG of the given pixel size (stdlib only), so the
dimension probe reads the real header instead of a hand-faked one."""
diff --git a/ui/src/components/workbench/Composer.attachmentRetry.test.tsx b/ui/src/components/workbench/Composer.attachmentRetry.test.tsx
new file mode 100644
index 000000000..72a679da1
--- /dev/null
+++ b/ui/src/components/workbench/Composer.attachmentRetry.test.tsx
@@ -0,0 +1,109 @@
+/* @vitest-environment jsdom */
+
+import { createInstance } from 'i18next';
+import { createRef, type ReactElement } from 'react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.hoisted(() => {
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: vi.fn().mockReturnValue({ matches: false }),
+ });
+});
+
+import { ToastProvider } from '../../context/ToastProvider';
+import en from '../../i18n/en.json';
+import { WorkbenchUploadError } from '../../lib/workbenchUpload';
+
+const uploadWorkbenchAttachment = vi.hoisted(() => vi.fn());
+
+vi.mock('../../lib/workbenchUpload', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../../lib/workbenchUpload')>(),
+ uploadWorkbenchAttachment,
+}));
+
+import { Composer, type ComposerHandle } from './Composer';
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const providers = (ui: ReactElement) => (
+ <I18nextProvider i18n={i18n}>
+ <ToastProvider>{ui}</ToastProvider>
+ </I18nextProvider>
+);
+
+afterEach(cleanup);
+beforeEach(() => uploadWorkbenchAttachment.mockReset());
+
+describe('Composer attachment retry', () => {
+ it('disables a failed upload retry when the composer becomes read-only', async () => {
+ uploadWorkbenchAttachment
+ .mockRejectedValueOnce(new TypeError('Failed to fetch'))
+ .mockResolvedValue({
+ token: 'media-token',
+ name: 'note.txt',
+ mime: 'text/plain',
+ size: 5,
+ kind: 'file',
+ url: '/api/media/media-token',
+ });
+ const ref = createRef<ComposerHandle>();
+ const composer = (disabled: boolean) => providers(
+ <Composer
+ ref={ref}
+ sessionId="ses-1"
+ disabled={disabled}
+ onSend={() => undefined}
+ />,
+ );
+ const view = render(composer(false));
+
+ act(() => ref.current?.addFiles([new File(['hello'], 'note.txt', { type: 'text/plain' })]));
+ const retry = await screen.findByLabelText(en.chat.compose.retryAttachment);
+ expect((retry as HTMLButtonElement).disabled).toBe(false);
+ expect(uploadWorkbenchAttachment).toHaveBeenCalledTimes(1);
+
+ view.rerender(composer(true));
+ await waitFor(() => expect((screen.getByLabelText(
+ en.chat.compose.retryAttachment,
+ ) as HTMLButtonElement).disabled).toBe(true));
+ fireEvent.click(screen.getByLabelText(en.chat.compose.retryAttachment));
+ expect(uploadWorkbenchAttachment).toHaveBeenCalledTimes(1);
+ });
+
+ it('withholds retry when the same file cannot succeed', async () => {
+ uploadWorkbenchAttachment
+ .mockRejectedValueOnce(new WorkbenchUploadError('too_large', 'File is too large', 413))
+ .mockResolvedValue({
+ token: 'unexpected-retry',
+ name: 'large.bin',
+ mime: 'application/octet-stream',
+ size: 5,
+ kind: 'file',
+ url: '/api/media/unexpected-retry',
+ });
+ const ref = createRef<ComposerHandle>();
+ render(providers(
+ <Composer
+ ref={ref}
+ sessionId="ses-1"
+ onSend={() => undefined}
+ />,
+ ));
+
+ act(() => ref.current?.addFiles([new File(['hello'], 'large.bin')]));
+ await screen.findByText(en.chat.compose.attachmentTooLarge);
+
+ expect(screen.getByText('large.bin')).toBeTruthy();
+ expect(screen.queryByLabelText(en.chat.compose.retryAttachment)).toBeNull();
+ expect(uploadWorkbenchAttachment).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index 0bf66c754..b45cecbd6 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -44,6 +44,11 @@ import {
VoiceRealtimeSession,
type VoiceRealtimeFinal,
} from '../../lib/voiceRealtime';
+import {
+ isWorkbenchUploadRetryable,
+ uploadWorkbenchAttachment,
+ workbenchUploadErrorTranslationKey,
+} from '../../lib/workbenchUpload';
import { Button } from '../ui/button';
import {
MentionEditor,
@@ -67,33 +72,20 @@ export type ComposerAttachment = {
width?: number;
height?: number;
status: 'uploading' | 'ready' | 'error';
+ retryable?: boolean;
};
-// Read a File/Blob as bare base64 (no ``data:...,`` prefix) for the JSON upload
-// + transcribe endpoints — the auth/CSRF-guarded compat route parses JSON, not
-// multipart, so binaries ride as base64.
-function readFileAsBase64(file: Blob): Promise<string> {
- return new Promise((resolve, reject) => {
- const reader = new FileReader();
- reader.onerror = () => reject(reader.error);
- reader.onload = () => {
- const result = String(reader.result || '');
- const comma = result.indexOf(',');
- resolve(comma >= 0 ? result.slice(comma + 1) : result);
- };
- reader.readAsDataURL(file);
- });
-}
-
-// Parallel-upload pool size. A multi-file batch reads each file as base64
-// (~33% larger) and POSTs it; cap how many are in flight so a big drop of large
-// files (up to 25 MB each) doesn't materialize every request body at once.
+// Parallel-upload pool size. Multipart keeps each request binary, but bounded
+// concurrency still prevents a large drop from saturating the connection.
const UPLOAD_CONCURRENCY = 4;
// Unique-enough id for an optimistic attachment chip before the server token
// lands. Date.now() collides within a batch, so the random suffix separates
// files staged in the same tick.
-const newLocalId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+const newLocalId = () => (
+ globalThis.crypto?.randomUUID?.()
+ ?? `${Date.now()}-${Math.random().toString(36).slice(2, 14)}`
+);
type VoiceSegment = VoiceTranscriptionSegment & {
task: Promise<void>;
@@ -404,6 +396,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
// Blocks a same-tick double-submit before the optimistic clear re-renders.
const pendingRef = useRef(false);
const fileInputRef = useRef<HTMLInputElement | null>(null);
+ const attachmentFilesRef = useRef(new Map<string, File>());
const [attachments, setAttachments] = useState<ComposerAttachment[]>([]);
const [asrAvailable, setAsrAvailable] = useState(false);
const [asrMaxFileBytes, setAsrMaxFileBytes] = useState<number | null>(null);
@@ -541,6 +534,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
// the composer by session.
useEffect(() => {
setAttachments([]);
+ attachmentFilesRef.current.clear();
setRealtimeAnnouncement('');
setVoiceRetainedSession(null);
setRestoringRecording(
@@ -549,23 +543,17 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
}, [sessionId]);
const removeAttachment = (localId: string) => {
+ attachmentFilesRef.current.delete(localId);
setAttachments((cur) => cur.filter((a) => a.localId !== localId));
};
- // Upload one already-staged file (its chip exists as 'uploading'): POST it as
- // base64-JSON, then flip the chip to ready (carrying the server token + proxy
- // URL) or to error. ``sid`` is threaded in so the fan-out below stays typed
- // after the session guard.
+ // Upload one already-staged file, then flip its chip to ready or retryable.
+ // ``sid`` is threaded in so the fan-out below stays typed after the guard.
const uploadOne = async (file: File, localId: string, sid: string) => {
try {
- const data = await readFileAsBase64(file);
- const res = await apiFetch(`/api/sessions/${encodeURIComponent(sid)}/attachments`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ name: file.name, mime: file.type, data }),
- });
- const json = await res.json().catch(() => null);
- if (!res.ok || !json?.token) throw new Error('upload failed');
+ const json = await uploadWorkbenchAttachment(sid, file, localId);
+ if (attachmentFilesRef.current.get(localId) !== file) return;
+ attachmentFilesRef.current.delete(localId);
setAttachments((cur) =>
cur.map((a) =>
a.localId === localId
@@ -579,15 +567,32 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
width: typeof json.width === 'number' ? json.width : undefined,
height: typeof json.height === 'number' ? json.height : undefined,
status: 'ready',
+ retryable: undefined,
}
: a,
),
);
- } catch {
- setAttachments((cur) => cur.map((a) => (a.localId === localId ? { ...a, status: 'error' } : a)));
+ } catch (error) {
+ if (attachmentFilesRef.current.get(localId) !== file) return;
+ const retryable = isWorkbenchUploadRetryable(error);
+ if (!retryable) attachmentFilesRef.current.delete(localId);
+ setAttachments((cur) => cur.map((a) => (
+ a.localId === localId ? { ...a, status: 'error', retryable } : a
+ )));
+ showToast(t(workbenchUploadErrorTranslationKey(error)), 'error');
}
};
+ const retryAttachment = (localId: string) => {
+ if (!sessionId || disabledRef.current || voiceDraftReadOnly) return;
+ const file = attachmentFilesRef.current.get(localId);
+ if (!file) return;
+ setAttachments((cur) => cur.map((a) => (
+ a.localId === localId ? { ...a, status: 'uploading', retryable: undefined } : a
+ )));
+ void uploadOne(file, localId, sessionId);
+ };
+
// Upload a whole batch — multi-select from the picker or a chat-page drag-drop
// (handed in via the imperative handle below). Stage every chip up front in one
// update so the user sees the full batch at once, then upload with bounded
@@ -596,6 +601,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
if (!sessionId) return;
const sid = sessionId;
const staged = files.map((file) => ({ file, localId: newLocalId() }));
+ for (const { file, localId } of staged) attachmentFilesRef.current.set(localId, file);
setAttachments((cur) => [
...cur,
...staged.map(({ file, localId }) => ({
@@ -1211,6 +1217,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
setHasText(false);
onDraftChange?.('');
setAttachments([]);
+ attachmentFilesRef.current.clear();
referencesRef.current = [];
if (useMentions) mentionRef.current?.clear();
try {
@@ -1256,6 +1263,19 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
<span className={clsx('max-w-[160px] truncate', att.status === 'error' ? 'text-pink' : 'text-foreground')}>
{att.name}
</span>
+ {att.status === 'error' && att.retryable && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ disabled={disabled || voiceDraftReadOnly}
+ onClick={() => retryAttachment(att.localId)}
+ aria-label={t('chat.compose.retryAttachment')}
+ className="size-5 shrink-0 text-muted hover:text-foreground"
+ >
+ <RotateCcw className="size-3.5" />
+ </Button>
+ )}
<Button
type="button"
variant="ghost"
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index c471095b0..6eacee0f0 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3226,6 +3226,12 @@
"voicePermissionFailed": "Microphone access failed. Check your browser permission and try again.",
"voiceStartFailed": "Voice recording could not start in this browser. Reload the page or try a supported browser.",
"voiceDraftChanged": "The draft changed during voice input. The recovered transcript is available to copy.",
+ "attachmentTooLarge": "This file exceeds the 100 MB attachment limit.",
+ "attachmentEmpty": "Empty files cannot be attached.",
+ "attachmentSessionUnavailable": "This session is no longer available.",
+ "attachmentNetwork": "The upload connection failed. Try again.",
+ "attachmentFailed": "The file could not be uploaded. Try again.",
+ "retryAttachment": "Retry upload",
"removeAttachment": "Remove",
"dropOverlay": "Drop files to attach"
},
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 467c06b02..3f9c68789 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3226,6 +3226,12 @@
"voicePermissionFailed": "无法使用麦克风,请检查浏览器权限后重试。",
"voiceStartFailed": "当前浏览器无法启动语音录制,请刷新页面或更换支持的浏览器。",
"voiceDraftChanged": "语音输入期间草稿已变化,已保留整理结果供复制。",
+ "attachmentTooLarge": "文件超过 100 MB 的附件上限。",
+ "attachmentEmpty": "不能上传空文件。",
+ "attachmentSessionUnavailable": "当前会话已不可用。",
+ "attachmentNetwork": "上传连接失败,请重试。",
+ "attachmentFailed": "文件上传失败,请重试。",
+ "retryAttachment": "重试上传",
"removeAttachment": "移除",
"dropOverlay": "拖放文件以添加"
},
diff --git a/ui/src/lib/apiFetch.test.ts b/ui/src/lib/apiFetch.test.ts
index a2946c20c..ffbe8029a 100644
--- a/ui/src/lib/apiFetch.test.ts
+++ b/ui/src/lib/apiFetch.test.ts
@@ -69,6 +69,135 @@ describe('apiFetch remote auth recovery', () => {
expect(remoteAuth.deferRemoteAuthRedirect).not.toHaveBeenCalled();
});
+ it('replays a rejected mutation with the cookie that replaced its header token', async () => {
+ let cookie = 'vibe_csrf_token=stale-token';
+ vi.stubGlobal('document', {
+ get cookie() {
+ return cookie;
+ },
+ set cookie(value: string) {
+ cookie = value.includes('Max-Age=0') ? '' : value.split(';', 1)[0];
+ },
+ });
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const token = new Headers(init?.headers).get('X-Vibe-CSRF-Token');
+ if (token === 'stale-token') {
+ document.cookie = 'vibe_csrf_token=fresh-token; path=/';
+ return Response.json({ ok: false, message: 'Forbidden: invalid csrf token' }, { status: 403 });
+ }
+ return Response.json({ ok: true }, { status: 201 });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const response = await apiFetch('/api/sessions/ses-1/attachments', {
+ method: 'POST',
+ body: new FormData(),
+ });
+
+ expect(response.status).toBe(201);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(new Headers(fetchMock.mock.calls[1][1]?.headers).get('X-Vibe-CSRF-Token')).toBe('fresh-token');
+ });
+
+ it('shares a CSRF refresh with mutations that start while the cookie is cleared', async () => {
+ let cookie = 'vibe_csrf_token=stale-token';
+ let resolveToken!: (response: Response) => void;
+ vi.stubGlobal('document', {
+ get cookie() {
+ return cookie;
+ },
+ set cookie(value: string) {
+ cookie = value.includes('Max-Age=0') ? '' : value.split(';', 1)[0];
+ },
+ });
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ if (input === '/api/csrf-token') {
+ return new Promise<Response>((resolve) => {
+ resolveToken = resolve;
+ });
+ }
+ const token = new Headers(init?.headers).get('X-Vibe-CSRF-Token');
+ if (token === 'stale-token') {
+ cookie = '';
+ return Response.json({ ok: false, message: 'Forbidden: invalid csrf token' }, { status: 403 });
+ }
+ return Response.json({ ok: true }, { status: 201 });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const retrying = apiFetch('/api/attachments', { method: 'POST', body: new FormData() });
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ const concurrent = apiFetch('/api/settings', { method: 'POST' });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(fetchMock.mock.calls.filter(([input]) => input === '/api/csrf-token')).toHaveLength(1);
+
+ document.cookie = 'vibe_csrf_token=fresh-token; path=/';
+ resolveToken(Response.json({ csrf_token: 'fresh-token' }));
+
+ await expect(Promise.all([retrying, concurrent])).resolves.toEqual([
+ expect.objectContaining({ status: 201 }),
+ expect.objectContaining({ status: 201 }),
+ ]);
+ expect(fetchMock.mock.calls.filter(([input]) => input === '/api/csrf-token')).toHaveLength(1);
+ });
+
+ it('rechecks a token cookie overwritten by another tab before replaying', async () => {
+ let cookie = 'vibe_csrf_token=stale-token';
+ let resolveToken!: (response: Response) => void;
+ let mutationCalls = 0;
+ const currentToken = () => cookie.startsWith('vibe_csrf_token=')
+ ? cookie.slice('vibe_csrf_token='.length)
+ : '';
+ vi.stubGlobal('document', {
+ get cookie() {
+ return cookie;
+ },
+ set cookie(value: string) {
+ cookie = value.includes('Max-Age=0') ? '' : value.split(';', 1)[0];
+ },
+ });
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ if (input === '/api/csrf-token') {
+ return new Promise<Response>((resolve) => {
+ resolveToken = resolve;
+ });
+ }
+ mutationCalls += 1;
+ const token = new Headers(init?.headers).get('X-Vibe-CSRF-Token');
+ if (mutationCalls === 1) {
+ cookie = '';
+ return Response.json({ ok: false, message: 'Forbidden: invalid csrf token' }, { status: 403 });
+ }
+ return Response.json({ ok: token === currentToken() }, {
+ status: token === currentToken() ? 201 : 403,
+ });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const request = apiFetch('/api/attachments', { method: 'POST', body: new FormData() });
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ document.cookie = 'vibe_csrf_token=tab-a-token; path=/';
+ resolveToken(Response.json({ csrf_token: 'tab-a-token' }));
+ document.cookie = 'vibe_csrf_token=tab-b-token; path=/';
+
+ await expect(request).resolves.toEqual(expect.objectContaining({ status: 201 }));
+ expect(new Headers(fetchMock.mock.calls.at(-1)?.[1]?.headers).get('X-Vibe-CSRF-Token'))
+ .toBe('tab-b-token');
+ });
+
+ it('does not retry an unrelated forbidden mutation', async () => {
+ vi.stubGlobal('document', { cookie: 'vibe_csrf_token=token' });
+ const fetchMock = vi.fn(async () =>
+ Response.json({ ok: false, message: 'Forbidden' }, { status: 403 }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+
+ const response = await apiFetch('/api/settings', { method: 'POST' });
+
+ expect(response.status).toBe(403);
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+
it('honors the request signal while a shared CSRF request is pending', async () => {
let resolveCsrf!: (response: Response) => void;
const fetchMock = vi.fn(
@@ -137,4 +266,56 @@ describe('apiFetch remote auth recovery', () => {
});
expect(fetchMock).toHaveBeenCalledTimes(3);
});
+
+ it('evicts a stalled shared CSRF refresh after a rejected mutation aborts', async () => {
+ let cookie = 'vibe_csrf_token=stale-token';
+ let tokenFetches = 0;
+ let mutationCalls = 0;
+ vi.stubGlobal('document', {
+ get cookie() {
+ return cookie;
+ },
+ set cookie(value: string) {
+ cookie = value.includes('Max-Age=0') ? '' : value.split(';', 1)[0];
+ },
+ });
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ if (input === '/api/csrf-token') {
+ tokenFetches += 1;
+ if (tokenFetches === 1) {
+ return new Promise<Response>(() => undefined);
+ }
+ document.cookie = 'vibe_csrf_token=fresh-token; path=/';
+ return Response.json({ csrf_token: 'fresh-token' });
+ }
+
+ mutationCalls += 1;
+ if (mutationCalls === 1) {
+ cookie = '';
+ return Response.json({ ok: false, message: 'Forbidden: invalid csrf token' }, { status: 403 });
+ }
+ const token = new Headers(init?.headers).get('X-Vibe-CSRF-Token');
+ return Response.json({ ok: token === 'fresh-token' }, {
+ status: token === 'fresh-token' ? 200 : 403,
+ });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const controller = new AbortController();
+
+ const stalled = apiFetch('/api/attachments', {
+ method: 'POST',
+ body: new FormData(),
+ signal: controller.signal,
+ });
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ const stalledResult = expect(stalled).rejects.toMatchObject({ name: 'TimeoutError' });
+ controller.abort(new DOMException('upload timed out', 'TimeoutError'));
+
+ await stalledResult;
+ await expect(apiFetch('/api/settings', { method: 'POST' })).resolves.toMatchObject({
+ status: 200,
+ });
+ expect(tokenFetches).toBe(2);
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ });
});
diff --git a/ui/src/lib/apiFetch.ts b/ui/src/lib/apiFetch.ts
index edfc77f83..403bf334d 100644
--- a/ui/src/lib/apiFetch.ts
+++ b/ui/src/lib/apiFetch.ts
@@ -73,12 +73,7 @@ const waitForSignal = <Value>(promise: Promise<Value>, signal?: AbortSignal): Pr
});
};
-export async function ensureCsrfToken(signal?: AbortSignal): Promise<string> {
- const existing = readCookie(CSRF_COOKIE_NAME);
- if (existing) {
- return existing;
- }
-
+async function acquireCsrfToken(signal?: AbortSignal): Promise<string> {
if (!csrfTokenPromise) {
startCsrfTokenFetch();
}
@@ -95,6 +90,43 @@ export async function ensureCsrfToken(signal?: AbortSignal): Promise<string> {
}
}
+export async function ensureCsrfToken(signal?: AbortSignal): Promise<string> {
+ const existing = readCookie(CSRF_COOKIE_NAME);
+ if (existing) {
+ return existing;
+ }
+
+ return acquireCsrfToken(signal);
+}
+
+async function refreshRejectedCsrfToken(
+ signal?: AbortSignal,
+): Promise<string> {
+ const current = readCookie(CSRF_COOKIE_NAME);
+ // This is a double-submit token, not server-side session state. A 403 means
+ // the request's header and shared browser cookie crossed; rotating a present
+ // cookie here only creates another race with other tabs.
+ if (current) return current;
+
+ const fetched = await acquireCsrfToken(signal);
+ return readCookie(CSRF_COOKIE_NAME) || fetched;
+}
+
+async function isInvalidCsrfResponse(response: Response): Promise<boolean> {
+ if (response.status !== 403) return false;
+ try {
+ const payload = await response.json();
+ return payload?.message === 'Forbidden: invalid csrf token';
+ } catch {
+ return false;
+ }
+}
+
+function canReplayRequest(input: RequestInfo | URL, body: BodyInit | null | undefined): boolean {
+ if (typeof Request !== 'undefined' && input instanceof Request) return false;
+ return !(typeof ReadableStream !== 'undefined' && body instanceof ReadableStream);
+}
+
export async function apiFetch(input: RequestInfo | URL, init: RequestInit = {}): Promise<Response> {
const method = (init.method || 'GET').toUpperCase();
const nextInit: RequestInit = { ...init };
@@ -107,13 +139,29 @@ export async function apiFetch(input: RequestInfo | URL, init: RequestInit = {})
headers.set('Accept', 'application/json');
}
+ let csrfToken = '';
if (MUTATING_METHODS.has(method)) {
- const token = await ensureCsrfToken(init.signal ?? undefined);
- headers.set(CSRF_HEADER_NAME, token);
+ csrfToken = await ensureCsrfToken(init.signal ?? undefined);
+ headers.set(CSRF_HEADER_NAME, csrfToken);
}
nextInit.headers = headers;
- const response = await fetch(input, nextInit);
+ let response = await fetch(input, nextInit);
+ // The CSRF guard rejects before the endpoint runs, so this exact response is
+ // safe to replay once. It covers a cookie/header race or a stale page without
+ // turning arbitrary 403s or non-replayable request streams into retries.
+ if (
+ csrfToken
+ && canReplayRequest(input, init.body)
+ && await isInvalidCsrfResponse(response.clone())
+ ) {
+ const recoveredToken = await refreshRejectedCsrfToken(init.signal ?? undefined);
+ // Cookies are shared across tabs while the acquisition promise is not.
+ // Read once more at the replay boundary in case another tab won the race.
+ csrfToken = readCookie(CSRF_COOKIE_NAME) || recoveredToken;
+ headers.set(CSRF_HEADER_NAME, csrfToken);
+ response = await fetch(input, { ...nextInit, headers });
+ }
// Global remote-access auth recovery. The AuthGuard validates the session
// once and then stops re-running on ordinary navigation (so it doesn't
// re-mount the shell on every sidebar click). If the Avibe Cloud cookie
diff --git a/ui/src/lib/workbenchUpload.test.ts b/ui/src/lib/workbenchUpload.test.ts
new file mode 100644
index 000000000..be12fba74
--- /dev/null
+++ b/ui/src/lib/workbenchUpload.test.ts
@@ -0,0 +1,113 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const api = vi.hoisted(() => ({ apiFetch: vi.fn() }));
+vi.mock('./apiFetch', () => api);
+
+import {
+ isWorkbenchUploadRetryable,
+ MAX_WORKBENCH_ATTACHMENT_BYTES,
+ uploadWorkbenchAttachment,
+ WorkbenchUploadError,
+} from './workbenchUpload';
+
+describe('workbench attachment upload', () => {
+ beforeEach(() => {
+ api.apiFetch.mockReset();
+ });
+
+ it('keeps the browser boundary at 100 MiB', () => {
+ expect(MAX_WORKBENCH_ATTACHMENT_BYTES).toBe(100 * 1024 * 1024);
+ });
+
+ it('uploads the original binary as multipart form data', async () => {
+ api.apiFetch.mockResolvedValue(Response.json({
+ token: 'media-token',
+ name: '报告.txt',
+ mime: 'text/plain',
+ size: 5,
+ kind: 'file',
+ url: '/api/media/media-token',
+ }, { status: 201 }));
+ const file = new File(['hello'], '报告.txt', { type: 'text/plain' });
+
+ await expect(uploadWorkbenchAttachment('ses/one', file, 'upload-id-123456')).resolves.toMatchObject({
+ token: 'media-token',
+ size: 5,
+ });
+
+ const [path, init] = api.apiFetch.mock.calls[0];
+ expect(path).toBe('/api/sessions/ses%2Fone/attachments');
+ expect(init.method).toBe('POST');
+ expect(init.headers).toBeUndefined();
+ expect((init.body as FormData).get('upload_id')).toBe('upload-id-123456');
+ expect((init.body as FormData).get('file')).toMatchObject({
+ name: '报告.txt',
+ size: 5,
+ type: 'text/plain',
+ });
+ });
+
+ it('rejects oversized files before starting a request', async () => {
+ const file = new File(['x'], 'large.bin');
+ Object.defineProperty(file, 'size', { value: MAX_WORKBENCH_ATTACHMENT_BYTES + 1 });
+
+ await expect(uploadWorkbenchAttachment('ses-1', file, 'upload-id-123456')).rejects.toMatchObject({
+ code: 'too_large',
+ status: 413,
+ });
+ expect(api.apiFetch).not.toHaveBeenCalled();
+ });
+
+ it('preserves a structured server failure for localized UI handling', async () => {
+ api.apiFetch.mockResolvedValue(Response.json({
+ ok: false,
+ error: { code: 'session_not_found', message: 'Session not found' },
+ }, { status: 404 }));
+
+ const promise = uploadWorkbenchAttachment(
+ 'missing',
+ new File(['x'], 'x.txt'),
+ 'upload-id-123456',
+ );
+
+ await expect(promise).rejects.toEqual(expect.objectContaining({
+ name: 'WorkbenchUploadError',
+ code: 'session_not_found',
+ status: 404,
+ }));
+ });
+
+ it('classifies fetch failures as retryable network errors', async () => {
+ api.apiFetch.mockRejectedValue(new TypeError('Failed to fetch'));
+
+ await expect(
+ uploadWorkbenchAttachment('ses-1', new File(['x'], 'x.txt'), 'upload-id-123456'),
+ ).rejects.toMatchObject({ code: 'network_error' });
+ });
+
+ it('keeps response-body failures retryable after successful headers', async () => {
+ const response = new Response(null, { status: 201 });
+ vi.spyOn(response, 'json').mockRejectedValue(new TypeError('terminated'));
+ api.apiFetch.mockResolvedValue(response);
+
+ const error = await uploadWorkbenchAttachment(
+ 'ses-1',
+ new File(['x'], 'x.txt'),
+ 'upload-id-123456',
+ ).catch((caught: unknown) => caught);
+
+ expect(error).toMatchObject({ code: 'network_error' });
+ expect(isWorkbenchUploadRetryable(error)).toBe(true);
+ });
+
+ it('only retries failures that can succeed with the same file and session', () => {
+ expect(isWorkbenchUploadRetryable(new WorkbenchUploadError('network_error', 'offline'))).toBe(true);
+ expect(isWorkbenchUploadRetryable(new WorkbenchUploadError('upload_failed', 'server', 503))).toBe(true);
+ expect(isWorkbenchUploadRetryable(new WorkbenchUploadError('too_large', 'large', 413))).toBe(false);
+ expect(isWorkbenchUploadRetryable(new WorkbenchUploadError('empty_file', 'empty', 400))).toBe(false);
+ expect(isWorkbenchUploadRetryable(
+ new WorkbenchUploadError('session_not_found', 'missing', 404),
+ )).toBe(false);
+ expect(isWorkbenchUploadRetryable(new WorkbenchUploadError('upload_failed', 'invalid', 400))).toBe(false);
+ });
+});
diff --git a/ui/src/lib/workbenchUpload.ts b/ui/src/lib/workbenchUpload.ts
new file mode 100644
index 000000000..7fb9e37e4
--- /dev/null
+++ b/ui/src/lib/workbenchUpload.ts
@@ -0,0 +1,109 @@
+import { apiFetch } from './apiFetch';
+
+// Product safety limit, enforced again by core/workbench_media.py. This is an
+// Avibe attachment policy, not an upstream proxy limit.
+export const MAX_WORKBENCH_ATTACHMENT_BYTES = 100 * 1024 * 1024;
+
+export type WorkbenchUploadErrorCode =
+ | 'empty_file'
+ | 'network_error'
+ | 'session_not_found'
+ | 'too_large'
+ | 'upload_failed';
+
+export class WorkbenchUploadError extends Error {
+ readonly code: WorkbenchUploadErrorCode;
+ readonly status?: number;
+
+ constructor(
+ code: WorkbenchUploadErrorCode,
+ message: string,
+ status?: number,
+ ) {
+ super(message);
+ this.name = 'WorkbenchUploadError';
+ this.code = code;
+ this.status = status;
+ }
+}
+
+export type WorkbenchUploadResult = {
+ token: string;
+ name: string;
+ mime: string;
+ size: number;
+ kind: 'image' | 'file';
+ url: string;
+ width?: number | null;
+ height?: number | null;
+};
+
+type ErrorPayload = {
+ error?: { code?: string; message?: string };
+};
+
+const normalizedErrorCode = (code: unknown): WorkbenchUploadErrorCode => {
+ if (code === 'too_large' || code === 'empty_file' || code === 'session_not_found') return code;
+ return 'upload_failed';
+};
+
+export async function uploadWorkbenchAttachment(
+ sessionId: string,
+ file: File,
+ uploadId: string,
+): Promise<WorkbenchUploadResult> {
+ if (file.size === 0) throw new WorkbenchUploadError('empty_file', 'File is empty', 400);
+ if (file.size > MAX_WORKBENCH_ATTACHMENT_BYTES) {
+ throw new WorkbenchUploadError('too_large', 'File exceeds the attachment size limit', 413);
+ }
+
+ const form = new FormData();
+ form.append('upload_id', uploadId);
+ form.append('file', file, file.name);
+
+ let response: Response;
+ try {
+ response = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}/attachments`, {
+ method: 'POST',
+ body: form,
+ });
+ } catch (error) {
+ throw new WorkbenchUploadError(
+ 'network_error',
+ error instanceof Error ? error.message : 'Network request failed',
+ );
+ }
+
+ let payload: (WorkbenchUploadResult & ErrorPayload) | null;
+ try {
+ payload = await response.json() as (WorkbenchUploadResult & ErrorPayload) | null;
+ } catch (error) {
+ throw new WorkbenchUploadError(
+ 'network_error',
+ error instanceof Error ? error.message : 'Upload response could not be read',
+ );
+ }
+ if (!response.ok || !payload?.token) {
+ throw new WorkbenchUploadError(
+ normalizedErrorCode(payload?.error?.code),
+ payload?.error?.message || `Upload failed (${response.status})`,
+ response.status,
+ );
+ }
+ return payload;
+}
+
+export function workbenchUploadErrorTranslationKey(error: unknown): string {
+ if (!(error instanceof WorkbenchUploadError)) return 'chat.compose.attachmentFailed';
+ if (error.code === 'too_large') return 'chat.compose.attachmentTooLarge';
+ if (error.code === 'empty_file') return 'chat.compose.attachmentEmpty';
+ if (error.code === 'session_not_found') return 'chat.compose.attachmentSessionUnavailable';
+ if (error.code === 'network_error') return 'chat.compose.attachmentNetwork';
+ return 'chat.compose.attachmentFailed';
+}
+
+export function isWorkbenchUploadRetryable(error: unknown): boolean {
+ if (!(error instanceof WorkbenchUploadError)) return true;
+ if (error.code === 'network_error') return true;
+ return error.code === 'upload_failed' && (error.status == null || error.status >= 500);
+}
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 0584c176e..77d66836c 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -224,6 +224,14 @@
}
},
"sessionArchived": "This session is archived and can no longer be changed.",
+ "workbenchAttachment": {
+ "session_not_found": "This session is no longer available.",
+ "file_required": "Choose a file to upload.",
+ "empty_file": "Empty files cannot be uploaded.",
+ "too_large": "The file exceeds the attachment size limit.",
+ "invalid_upload": "The file upload is invalid.",
+ "upload_failed": "The file could not be saved. Please try again."
+ },
"agentArchive": {
"agent_builtin": {
"message": "Agent `{agent}` is built in and cannot be deleted.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index bd64dc888..119abef25 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -224,6 +224,14 @@
}
},
"sessionArchived": "该会话已归档,无法再修改。",
+ "workbenchAttachment": {
+ "session_not_found": "当前会话已不可用。",
+ "file_required": "请选择要上传的文件。",
+ "empty_file": "不能上传空文件。",
+ "too_large": "文件超过附件大小限制。",
+ "invalid_upload": "文件上传请求无效。",
+ "upload_failed": "文件保存失败,请重试。"
+ },
"agentArchive": {
"agent_builtin": {
"message": "Agent `{agent}` 是内置 Agent,无法删除。",
diff --git a/vibe/ui_compat.py b/vibe/ui_compat.py
index 2a3d4e1dc..e9992cee0 100644
--- a/vibe/ui_compat.py
+++ b/vibe/ui_compat.py
@@ -528,18 +528,18 @@ def _test_remote_addr_from_scope(scope: Any) -> str | None:
async def _read_json_payload(request: FastAPIRequest) -> Any:
content_type = request.headers.get("content-type", "")
- if not _is_json_content_type(content_type):
+ if not is_json_content_type(content_type):
return None
body = await request.body()
if not body:
return None
try:
- return json.loads(body)
+ return await run_in_threadpool(json.loads, body)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Malformed JSON")
-def _is_json_content_type(content_type: str) -> bool:
+def is_json_content_type(content_type: str) -> bool:
media_type = content_type.split(";", 1)[0].strip().lower()
return media_type == "application/json" or (
media_type.startswith("application/") and media_type.endswith("+json")
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 6ea7801ee..a457ab77d 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -34,7 +34,17 @@ from starlette.datastructures import UploadFile as StarletteUploadFile
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.formparsers import MultiPartException, MultiPartParser
-from vibe.ui_compat import CompatApp, Response, TEST_REMOTE_ADDR_HEADER, g, jsonify, redirect, request, send_file
+from vibe.ui_compat import (
+ CompatApp,
+ Response,
+ TEST_REMOTE_ADDR_HEADER,
+ g,
+ is_json_content_type,
+ jsonify,
+ redirect,
+ request,
+ send_file,
+)
from config import paths
from config.v2_config import CONFIG_LOCK, V2Config
@@ -8003,83 +8013,171 @@ def media_meta(token: str):
)
[email protected]("/api/sessions/<session_id>/attachments", methods=["POST"])
-def sessions_attachments_create(session_id: str):
- """Persist a user-uploaded file (base64 JSON) and register it for the media
- proxy. Returns an opaque token + proxy URL; the browser never holds a path.
- base64-over-JSON keeps uploads on the existing auth + CSRF-guarded compat
- route (the compat layer parses JSON, not multipart)."""
- import base64
- import re
- import uuid
+_WORKBENCH_ATTACHMENT_ERROR_CODES = {
+ "session_not_found",
+ "file_required",
+ "empty_file",
+ "too_large",
+ "invalid_upload",
+ "upload_failed",
+}
- from config import paths
- from core.services import sessions as workbench_sessions_service
- from storage import media_service
- payload = request.json or {}
- name = (payload.get("name") or "upload").strip() or "upload"
- mime = (payload.get("mime") or payload.get("content_type") or "application/octet-stream").strip()
- data_b64 = payload.get("data") or ""
- if not isinstance(data_b64, str) or not data_b64:
- return jsonify({"error": "data is required"}), 400
- if data_b64.startswith("data:") and "," in data_b64:
- data_b64 = data_b64.split(",", 1)[1]
- try:
- raw = base64.b64decode(data_b64)
- except Exception:
- return jsonify({"error": "invalid base64"}), 400
- if not raw:
- return jsonify({"error": "empty file"}), 400
- if len(raw) > 25 * 1024 * 1024:
- return jsonify({"error": "file too large"}), 413
+async def _workbench_attachment_error(code: str, status: int):
+ from core.workbench_media import MAX_WORKBENCH_ATTACHMENT_BYTES
+ from core.services import settings as settings_service
- engine = _projects_engine()
- try:
- with engine.connect() as conn:
- session = workbench_sessions_service.get_session(conn, session_id)
- except LookupError:
- return jsonify({"error": "session_not_found"}), 404
+ message_code = code if code in _WORKBENCH_ATTACHMENT_ERROR_CODES else "invalid_upload"
+ config = await asyncio.to_thread(settings_service.load_config_or_default)
+ extra: dict[str, Any] = {}
+ if code == "too_large":
+ extra["max_file_bytes"] = MAX_WORKBENCH_ATTACHMENT_BYTES
+ return _coded_error_response(
+ code,
+ t(f"error.workbenchAttachment.{message_code}", config.language),
+ status,
+ **extra,
+ )
- safe = re.sub(r"[^A-Za-z0-9._-]+", "_", name.rsplit("/", 1)[-1]).strip("_") or "upload"
- upload_dir = paths.get_attachments_dir() / "avibe" / session_id
- upload_dir.mkdir(parents=True, exist_ok=True)
- local_path = upload_dir / f"{uuid.uuid4().hex[:8]}_{safe}"
- local_path.write_bytes(raw)
- kind = "image" if mime.startswith("image/") else "file"
- with engine.begin() as conn:
- token = media_service.register(
- conn,
- scope_id=session["scope_id"],
- session_id=session_id,
- kind=kind,
- source="user_upload",
- local_path=str(local_path.resolve()),
- file_name=name,
- content_type=mime,
- )
- # Read back the pixel dimensions register() captured (NULL for non-images
- # / unreadable) so the client can reserve the image box and never shift the
- # transcript when the upload renders.
- row = media_service.get_by_token(conn, token)
+def _workbench_attachment_response(result: Any):
return (
jsonify(
{
- "token": token,
- "name": name,
- "mime": mime,
- "size": len(raw),
- "kind": kind,
- "url": f"/api/media/{token}",
- "width": row.get("width_px") if row else None,
- "height": row.get("height_px") if row else None,
+ "token": result.token,
+ "name": result.name,
+ "mime": result.mime,
+ "size": result.size,
+ "kind": result.kind,
+ "url": f"/api/media/{result.token}",
+ "width": result.width,
+ "height": result.height,
}
),
- 201,
+ 201 if result.created else 200,
)
[email protected]("/api/sessions/{session_id}/attachments", include_in_schema=False)
+async def sessions_attachments_create(session_id: str, starlette_request: FastAPIRequest):
+ """Stream a user upload into the session's media store.
+
+ Multipart is the current browser contract. Base64 JSON remains accepted so
+ a page opened before a service upgrade can finish uploading without a forced
+ refresh; it should not be used by new clients.
+ """
+
+ async def handler():
+ from core import workbench_media
+ from core.file_browser_service import FileBrowserError
+ from core.services import sessions as workbench_sessions_service
+
+ def load_session():
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ session = workbench_sessions_service.get_session(conn, session_id)
+ return engine, session
+
+ try:
+ engine, session = await asyncio.to_thread(load_session)
+ except LookupError:
+ return await _workbench_attachment_error("session_not_found", 404)
+
+ form = None
+ try:
+ source = None
+ legacy_data_b64 = None
+ content_type = starlette_request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
+ if content_type == "multipart/form-data":
+ _validate_file_upload_content_length(
+ starlette_request.headers,
+ workbench_media.MAX_WORKBENCH_ATTACHMENT_BYTES,
+ )
+ form = await _parse_file_upload_form(
+ starlette_request,
+ max_file_bytes=workbench_media.MAX_WORKBENCH_ATTACHMENT_BYTES,
+ )
+ upload = form.get("file")
+ if not isinstance(upload, StarletteUploadFile):
+ return await _workbench_attachment_error("file_required", 400)
+ await upload.seek(0)
+ source = upload.file
+ name = upload.filename
+ mime = upload.content_type
+ upload_id = form.get("upload_id")
+ elif is_json_content_type(content_type):
+ payload = request.json or {}
+ data_b64 = payload.get("data") or ""
+ if not isinstance(data_b64, str) or not data_b64:
+ return await _workbench_attachment_error("file_required", 400)
+ legacy_data_b64 = data_b64
+ name = payload.get("name")
+ mime = payload.get("mime") or payload.get("content_type")
+ upload_id = payload.get("upload_id")
+ else:
+ return await _workbench_attachment_error("invalid_upload", 415)
+
+ stable_upload_id = workbench_media.normalize_workbench_upload_id(upload_id)
+
+ def persist_attachment():
+ attachment_source = source
+ if legacy_data_b64 is not None:
+ attachment_source = workbench_media.decode_legacy_workbench_attachment(
+ legacy_data_b64
+ )
+ if attachment_source is None:
+ raise workbench_media.WorkbenchAttachmentUploadError(
+ "file_required",
+ "File is required",
+ 400,
+ )
+ with workbench_media.workbench_attachment_upload_lock(
+ session_id, stable_upload_id
+ ):
+ result = None
+ try:
+ with engine.begin() as conn:
+ result = workbench_media.materialize_workbench_attachment(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ file_name=name,
+ content_type=mime,
+ source=attachment_source,
+ upload_id=stable_upload_id,
+ )
+ return result
+ except Exception:
+ # Registration and commit are one logical publish. Keep
+ # rollback under the same key lock so a waiting retry
+ # cannot recreate this path before cleanup completes.
+ if result is not None and result.created:
+ Path(result.path).unlink(missing_ok=True)
+ raise
+
+ result = await asyncio.to_thread(persist_attachment)
+ return _workbench_attachment_response(result)
+ except workbench_media.WorkbenchAttachmentUploadError as exc:
+ return await _workbench_attachment_error(exc.code, exc.status)
+ except MultiPartException as exc:
+ if "too large" in str(exc).lower():
+ return await _workbench_attachment_error("too_large", 413)
+ return await _workbench_attachment_error("invalid_upload", 400)
+ except FileBrowserError as exc:
+ code = "too_large" if exc.code == "too_large" else "invalid_upload"
+ return await _workbench_attachment_error(code, exc.status_code)
+ except StarletteHTTPException:
+ return await _workbench_attachment_error("invalid_upload", 400)
+ except Exception:
+ logger.exception("workbench attachment upload failed for session %s", session_id)
+ return await _workbench_attachment_error("upload_failed", 500)
+ finally:
+ if form is not None:
+ await form.close()
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
@app.route("/api/asr/transcribe", methods=["POST"])
async def asr_transcribe():
"""Transcribe recorded audio (base64 JSON) via the avibe.bot ASR client and