Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
b03bbea
fix(chat): deleted conversation files go to the approval queue as rem…
mrveiss Nov 1, 2026
a9225b1
chore(merge): merge origin/main into issue-20234-file-cleanup-proposa…
mrveiss Nov 1, 2026
cd7c1ee
fix(frontend): re-pin the reach floors this branch moved (#20234)
mrveiss Nov 1, 2026
73135c3
fix(chat): name the conversation file cleanup registration apart from…
mrveiss Nov 1, 2026
52a04b2
Merge remote-tracking branch 'origin/main' into issue-20234-file-clea…
mrveiss Nov 1, 2026
5a1bb73
fix(frontend): re-pin the reach floors this branch moved (#20234)
mrveiss Nov 1, 2026
e6caf4c
fix(chat): re-propose failed or expired file cleanups, gate hard_dele…
mrveiss Nov 1, 2026
2d1fa12
fix(chat): keep _hard_delete_file, note it is unwired behind the gate…
mrveiss Nov 1, 2026
376e425
fix(chat): one pending cleanup proposal per file in the database, ref…
mrveiss Nov 1, 2026
b7b524e
chore(merge): merge origin/main into issue-20234-file-cleanup-proposa…
mrveiss Nov 1, 2026
9db6364
fix(frontend): re-pin the reach floors this branch moved (#20234)
mrveiss Nov 1, 2026
c34dbb7
fix(chat): name the cleanup attempt cap apart from other retry helper…
mrveiss Nov 2, 2026
941e1e8
chore(merge): merge origin/main into issue-20234-file-cleanup-proposa…
mrveiss Nov 2, 2026
04f7672
fix(frontend): re-pin the reach floors this branch moved (#20234)
mrveiss Nov 2, 2026
607c06e
Merge main into issue-20234-file-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 2, 2026
f1e63a7
fix(chat): show and reset stuck file cleanups, fail the migration on …
mrveiss Nov 2, 2026
c744d94
fix(chat): list and decide pending removal proposals in the admin pan…
mrveiss Nov 2, 2026
0046ebc
Merge remote-tracking branch 'origin/issue-20234-file-cleanup-proposa…
mrveiss Nov 2, 2026
535b2b4
fix(chat): the cleanup panel uses utility classes and annotations, i1…
mrveiss Nov 2, 2026
cf928b9
fix(chat): the cleanup panel shows a load error with Retry on a non-a…
mrveiss Nov 2, 2026
99a8d00
fix(chat): conversation uploads stop reading at the size cap and resp…
mrveiss Nov 2, 2026
7cebb14
Merge main into issue-20233-chat-file-defects (auto-sync) [skip ci]
github-actions[bot] Nov 2, 2026
79b2760
fix(chat): upload quota enforced in the store path with stable error …
mrveiss Nov 2, 2026
9f6e3f8
Merge remote-tracking branch 'origin/issue-20233-chat-file-defects' i…
mrveiss Nov 2, 2026
c9a4e62
test(i18n): record the upload error keys on the new base (#20217)
mrveiss Nov 2, 2026
4d26a27
fix(chat): coded 413 on create/generate size cap, translated create r…
mrveiss Nov 2, 2026
1aa2d0e
chore(merge): merge origin/main into issue-20234-file-cleanup-proposa…
mrveiss Nov 2, 2026
1e8b69f
fix(chat): the file cleanup migration follows main's head instead of …
mrveiss Nov 2, 2026
9fff794
Merge remote-tracking branch 'origin/issue-20234-file-cleanup-proposa…
mrveiss Nov 2, 2026
6e00066
fix(chat): the file cleanup migration's references follow its new num…
mrveiss Nov 2, 2026
e474ca5
test(chat): the table count's eighth table is file_cleanup_attempts, …
mrveiss Nov 2, 2026
4fad5e7
chore(merge): merge #20540's head into the upload quota branch (#20217)
mrveiss Nov 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions autobot-backend/api/conversation_file_cleanup_admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""Admin view of deleted conversation files waiting on a human, and the reset for a stuck one (#20234, #17038).

A deleted file's bytes stay on disk until an approved proposal removes them. A file whose removal was
refused ``AUTOBOT_CONVERSATION_FILE_CLEANUP_MAX_ATTEMPTS`` times is no longer proposed (a "stuck" file);
without this module nothing showed it to anyone. Mounted at ``/api/conversation-files/cleanup`` and
shown by ``components/llc/StuckFileCleanupPanel.vue``.

* ``GET /cleanup/status`` -- pending and stuck counts, bytes, and the stuck list. Read only.
* ``POST /cleanup/{file_id}/reset`` -- a person lets a stuck file be proposed again. It zeroes the
refusal counter and audits who did it. It removes no bytes: the new proposal still needs an approval.
"""

from __future__ import annotations

from typing import Any, Dict

from fastapi import APIRouter, Depends, HTTPException, Request

from auth_middleware import check_admin_permission, resolve_human_user
from autobot_shared.logging_manager import get_logger
from conversation_file_cleanup import cleanup_status, reset_cleanup_attempts
from services.audit_logger import audit_log

logger = get_logger(__name__)

router = APIRouter(prefix="/cleanup", dependencies=[Depends(check_admin_permission)])


def _manager(request: Request):
manager = getattr(request.app.state, "conversation_file_manager", None)
if manager is None:
raise HTTPException(status_code=503, detail="File management service temporarily unavailable")
return manager


@router.get("/status")
async def get_cleanup_status(request: Request) -> Dict[str, Any]:
"""Deleted files whose bytes still await removal, and those stuck after repeated refusals."""
return await cleanup_status(_manager(request))


@router.post("/{file_id}/reset")
async def reset_stuck_cleanup(request: Request, file_id: str) -> Dict[str, Any]:
"""Let a stuck file be proposed again; a person's action, audited, and it removes nothing."""
manager = _manager(request)
if not await reset_cleanup_attempts(manager, file_id):
raise HTTPException(status_code=404, detail="No refused cleanup is recorded for this file")
user = await resolve_human_user(request) or {}
await audit_log(
"conversation_file.cleanup_reset",
user_id=user.get("username") or user.get("user_id") or "internal-service",
resource=f"conversation_file:{file_id}",
details={"effect": "file may be proposed for removal again; no bytes removed"},
)
from services.conversation_file_cleanup_proposals import propose_due_cleanups_logged

await propose_due_cleanups_logged(manager) # raises a proposal only; the bytes wait for an approval
return {"file_id": file_id, "reset": True}
54 changes: 28 additions & 26 deletions autobot-backend/api/conversation_file_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,48 +8,50 @@
here so ``conversation_files.py`` stays under its size ceiling while it gains the owner gate.
"""

from typing import Awaitable, Callable

from fastapi import HTTPException, UploadFile

from conversation_file_quota import file_too_large
from security.upload_filename_policy import is_safe_file
from utils.catalog_http_exceptions import raise_invalid_input

# Maximum file size (50MB) - consistent with general file API
MAX_FILE_SIZE = 50 * 1024 * 1024

_CHUNK_BYTES = 1024 * 1024

async def validate_and_read_upload_file(
file: UploadFile,
) -> bytes:
"""
Validate and read uploaded file content.

Issue #281: Extracted from upload_conversation_file to reduce function
length and improve reusability of validation logic.
async def _read_within(file: UploadFile, limit: int, refuse: Callable[[], Awaitable[HTTPException]]) -> bytes:
"""Read *file* in chunks; raise ``await refuse()`` the moment it passes *limit*, so no oversize body is buffered."""
chunks: list[bytes] = []
total = 0
while chunk := await file.read(_CHUNK_BYTES):
total += len(chunk)
if total > limit:
raise await refuse()
chunks.append(chunk)
return b"".join(chunks)


async def _too_large() -> HTTPException:
return file_too_large(MAX_FILE_SIZE)


Args:
file: Uploaded file object
async def validate_and_read_upload_file(file: UploadFile, quota_manager=None, user_id: str | None = None) -> bytes:
"""Validate the name, then read the body under the size cap and *user_id*'s remaining quota (#20217).

Returns:
File content as bytes
``quota_manager`` (the conversation file manager) says what the user may still store; ``None`` = no
quota. The stricter limit ends the read early, each refusal with its own stable code.

Raises:
HTTPException: If validation fails (400, 413)
HTTPException: 400 for a bad name; 413 (``UploadRefused``) for an oversize file or an exhausted quota
"""
# Validate filename
if not file.filename:
raise_invalid_input("filename", "required")

if not is_safe_file(file.filename):
raise_invalid_input("filename", f"file type not allowed: {file.filename}")

# Read file content
content = await file.read()

# Check file size
if len(content) > MAX_FILE_SIZE:
raise HTTPException(
status_code=413,
detail=f"File too large. Maximum size: {MAX_FILE_SIZE // (1024*1024)}MB",
)

return content
remaining = None if quota_manager is None else await quota_manager.remaining_upload_quota(user_id)
if remaining is not None and remaining < MAX_FILE_SIZE:
return await _read_within(file, max(remaining, 0), lambda: quota_manager.upload_quota_refusal(user_id))
return await _read_within(file, MAX_FILE_SIZE, _too_large)
8 changes: 2 additions & 6 deletions autobot-backend/api/conversation_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,8 @@ async def upload_conversation_file(
"""Upload a file to a conversation session (Issue #398: refactored)."""
try:
user_data = await _authorize_file_operation(request, session_id, "upload", existing_only=True)
content = await validate_and_read_upload_file(file)
file_manager = _get_required_file_manager(request)
content = await validate_and_read_upload_file(file, file_manager, user_data.get("username"))

file_info_dict = await file_manager.upload_file(
session_id=session_id,
Expand All @@ -158,11 +158,7 @@ async def upload_conversation_file(
"conversation_file_upload",
user_data,
session_id,
{
"filename": file.filename,
"file_id": file_info.file_id,
"size": len(content),
},
{"filename": file.filename, "file_id": file_info.file_id, "size": len(content)},
)

upload_id = f"upload_{datetime.now(tz=timezone.utc).strftime('%Y%m%d_%H%M%S')}_{secrets.token_hex(4)}"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ async def _owner(_session_id):

manager = create_autospec(ConversationFileManager, instance=True) # a method it lacks would fail here (#20225)
manager.upload_file.side_effect = lambda **kw: _file_info(kw["session_id"], kw["user_id"])
manager.remaining_upload_quota.return_value = 1 << 30 # the real manager reads the user's stored bytes (#20217)
manager.list_files.return_value = {"files": [], "total_files": 0, "total_size": 0}
app = FastAPI()
app.include_router(module.router, prefix="/api")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
"""Conversation-file uploads stop reading at the size cap and refuse a user past their quota (#20217)."""

from __future__ import annotations

import asyncio
import io

import pytest
from fastapi import HTTPException, UploadFile

import conversation_file_quota as quota
from api import conversation_file_upload as upload
from api.conversation_files_owner_upload_20133_test import world # noqa: F401 -- fixture
from api.conversation_files_real_manager_20225_test import _SESSION, _upload, real # noqa: F401 -- fixture


class _CountingStream(io.BytesIO):
"""A body that records how many bytes the reader actually pulled."""

pulled = 0

def read(self, size=-1):
data = super().read(size)
self.pulled += len(data)
return data


def _file(body: io.BytesIO, name="big.txt") -> UploadFile:
return UploadFile(file=body, filename=name)


def test_an_oversize_body_stops_the_read_early(monkeypatch):
monkeypatch.setattr(upload, "MAX_FILE_SIZE", 2 * upload._CHUNK_BYTES)
body = _CountingStream(b"x" * (50 * upload._CHUNK_BYTES))
with pytest.raises(HTTPException) as caught:
asyncio.run(upload.validate_and_read_upload_file(_file(body)))
assert caught.value.status_code == 413 and caught.value.detail["code"] == quota.FILE_TOO_LARGE
assert body.pulled == 3 * upload._CHUNK_BYTES # cap + the one chunk that crossed it, not the whole body


def test_a_body_exactly_at_the_cap_is_read_whole(monkeypatch):
monkeypatch.setattr(upload, "MAX_FILE_SIZE", 10)
assert asyncio.run(upload.validate_and_read_upload_file(_file(io.BytesIO(b"x" * 10)))) == b"x" * 10


def test_the_remaining_quota_ends_the_read_with_its_own_code(real, monkeypatch): # noqa: F811
monkeypatch.setattr(quota, "USER_QUOTA_BYTES", 5)
body = _CountingStream(b"x" * (10 * upload._CHUNK_BYTES))
with pytest.raises(HTTPException) as caught:
asyncio.run(upload.validate_and_read_upload_file(_file(body), real.real, "alice"))
assert caught.value.status_code == 413 and caught.value.detail["code"] == quota.QUOTA_EXCEEDED
assert body.pulled == upload._CHUNK_BYTES


def test_a_user_past_their_quota_is_refused_by_the_route_and_nothing_is_stored(real, monkeypatch): # noqa: F811
monkeypatch.setattr(quota, "USER_QUOTA_BYTES", 20)
assert _upload(real, body=b"x" * 15).status_code == 200
response = _upload(real, name="two.txt", body=b"y" * 10)
assert response.status_code == 413 and response.json()["detail"]["code"] == quota.QUOTA_EXCEEDED
assert asyncio.run(real.real.remaining_upload_quota("alice")) == 5


def test_the_quota_is_per_user_not_shared(real, monkeypatch): # noqa: F811
monkeypatch.setattr(quota, "USER_QUOTA_BYTES", 20)
assert _upload(real, body=b"x" * 20).status_code == 200
assert asyncio.run(real.real.remaining_upload_quota("alice")) == 0
assert asyncio.run(real.real.remaining_upload_quota("bob")) == 20


def test_the_quota_limit_is_the_registered_env_default():
from autobot_shared.env_registry import REGISTRY

assert REGISTRY["AUTOBOT_CONVERSATION_FILE_USER_QUOTA_BYTES"].default == quota.USER_QUOTA_BYTES == 1 << 30
Loading
Loading