mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
feat(runtime): support attachments in queued Web messages (#8487)
* feat: 支持 Web 排队消息携带附件 * refactor: 复用上传文件的沙箱准备流程 * fix: 修复排队附件重试、命名和暂存清理 * fix: 清理取消后遗留的排队附件 * fix: 回收已发布暂存并回滚远端排队上传 * fix: 恢复未发布的排队附件并修正代理限制
This commit is contained in:
parent
3d157954e0
commit
5758c1034e
@ -364,6 +364,24 @@ async def _run_startup_trash_sweep(app: FastAPI, startup_config) -> None:
|
||||
logger.warning("Trash retention sweep skipped", exc_info=True)
|
||||
|
||||
|
||||
async def _run_startup_queued_upload_sweep(app: FastAPI) -> None:
|
||||
try:
|
||||
from app.gateway.run_input_cleanup import cleanup_abandoned_queued_uploads
|
||||
from deerflow.config.paths import get_paths
|
||||
|
||||
store = getattr(app.state, "run_store", None)
|
||||
if store is not None:
|
||||
removed = await cleanup_abandoned_queued_uploads(store, get_paths())
|
||||
if removed:
|
||||
logger.info("Removed %d abandoned queued upload stage(s)", removed)
|
||||
except Exception:
|
||||
logger.warning("Queued upload stage cleanup skipped", exc_info=True)
|
||||
|
||||
|
||||
async def _run_startup_storage_sweeps(app: FastAPI, startup_config) -> None:
|
||||
await asyncio.gather(_run_startup_trash_sweep(app, startup_config), _run_startup_queued_upload_sweep(app))
|
||||
|
||||
|
||||
async def _shutdown_startup_trash_sweep(app: FastAPI) -> None:
|
||||
"""Grace-budgeted shutdown for the background startup sweep (§8.3).
|
||||
|
||||
@ -765,15 +783,10 @@ async def _gateway_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
# Must run AFTER langgraph_runtime so app.state.store is available for thread migration
|
||||
await _ensure_admin_user(app)
|
||||
|
||||
# Phase-2 trash tier (§8.3): one retention sweep at startup, beside
|
||||
# the lazy trigger on the trash listing — no daemon, no scheduler.
|
||||
# Runs after langgraph_runtime so app.state.project_document_repo is
|
||||
# available. The per-user reconciliation walks every row and file, so
|
||||
# it is scheduled as a background task: gateway readiness never waits
|
||||
# on it, a failure is logged by the task itself, and shutdown gives the
|
||||
# in-flight sweep a bounded graceful budget before cancelling it; any
|
||||
# already-started file worker drains before the runtime is torn down.
|
||||
app.state.startup_trash_sweep_task = asyncio.create_task(_run_startup_trash_sweep(app, startup_config))
|
||||
# Run both storage sweeps after their repositories are ready, without
|
||||
# delaying gateway readiness. Shutdown drains in-flight writes before
|
||||
# tearing the runtime down.
|
||||
app.state.startup_trash_sweep_task = asyncio.create_task(_run_startup_storage_sweeps(app, startup_config))
|
||||
|
||||
# Best-effort per-document summary generation.
|
||||
# Workers start only when projects.summaries_enabled is true; the
|
||||
|
||||
@ -546,13 +546,12 @@ class _BoundAgentRuns:
|
||||
return (await get_thread_state(thread_id, request)).model_dump(mode="json")
|
||||
|
||||
async def send_input(self, *, thread_id, run_id, text, mode, request_id, context=None):
|
||||
from app.gateway.routers.thread_runs import create_run_input
|
||||
from app.gateway.run_inputs import RunInputRequest
|
||||
from app.gateway.run_inputs import RunInputRequest, submit_run_input
|
||||
|
||||
async with self._request("runs:create", thread_id) as request:
|
||||
body = RunInputRequest(request_id=request_id, text=text, mode=mode, context=_json_object(context) or {})
|
||||
body = body.model_copy(update={"request_id": hashlib.sha256(f"{self._plugin_namespace or 'host'}:{body.request_id}".encode()).hexdigest()})
|
||||
return await create_run_input(thread_id, run_id, body, request)
|
||||
return await submit_run_input(thread_id, run_id, body, request)
|
||||
|
||||
async def dispatch_input(self, *, thread_id, run_id, input_id):
|
||||
from app.gateway.run_inputs import dispatch_one_input
|
||||
|
||||
@ -63,7 +63,7 @@ from app.gateway.conversation_reader import (
|
||||
from app.gateway.deps import get_current_user, get_feedback_repo, get_run_event_store, get_run_manager, get_run_store, get_stream_bridge
|
||||
from app.gateway.internal_auth import INTERNAL_SYSTEM_ROLE, get_trusted_internal_owner_user_id
|
||||
from app.gateway.pagination import trim_run_message_page
|
||||
from app.gateway.run_inputs import RunInputRequest, change_run_input, list_thread_inputs, submit_run_input
|
||||
from app.gateway.run_inputs import RunInputRequest, change_run_input, list_thread_inputs, submit_http_run_input
|
||||
from app.gateway.run_models import RunCreateRequest
|
||||
from app.gateway.services import (
|
||||
abuild_checkpoint_state_accessor,
|
||||
@ -114,10 +114,30 @@ async def revoke_tool_approval_grants(thread_id: ThreadId, request: Request):
|
||||
return await revoke_approval_grants(thread_id, request)
|
||||
|
||||
|
||||
@router.post("/{thread_id}/runs/{run_id}/inputs")
|
||||
@router.post(
|
||||
"/{thread_id}/runs/{run_id}/inputs",
|
||||
openapi_extra={
|
||||
"requestBody": {
|
||||
"required": True,
|
||||
"content": {
|
||||
"application/json": {"schema": RunInputRequest.model_json_schema()},
|
||||
"multipart/form-data": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": ["input", "files"],
|
||||
"properties": {
|
||||
"input": {"type": "string", "description": "JSON input with mode set to queue"},
|
||||
"files": {"type": "array", "items": {"type": "string", "format": "binary"}},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
@require_permission("runs", "create", owner_check=True, require_existing=True)
|
||||
async def create_run_input(thread_id: ThreadId, run_id: str, body: RunInputRequest, request: Request):
|
||||
return await submit_run_input(thread_id, run_id, body, request)
|
||||
async def create_run_input(thread_id: ThreadId, run_id: str, request: Request):
|
||||
return await submit_http_run_input(thread_id, run_id, request)
|
||||
|
||||
|
||||
@router.get("/{thread_id}/inputs")
|
||||
|
||||
100
backend/app/gateway/run_input_cleanup.py
Normal file
100
backend/app/gateway/run_input_cleanup.py
Normal file
@ -0,0 +1,100 @@
|
||||
"""Reclaim old queue attachment stages that are no longer needed."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
from collections.abc import Iterator
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from time import time
|
||||
|
||||
from app.gateway.run_input_files import QUEUED_UPLOADS_DIR, is_staging_id
|
||||
from deerflow.config.paths import Paths
|
||||
from deerflow.runtime.runs.store.base import RunStore
|
||||
from deerflow.uploads.manager import UPLOAD_STAGING_MIN_AGE
|
||||
from deerflow.utils.file_io import await_drained, run_file_io
|
||||
from deerflow.utils.host_paths import extended_length_path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _directory_stat(path: Path) -> os.stat_result | None:
|
||||
try:
|
||||
info = path.lstat()
|
||||
except (FileNotFoundError, NotADirectoryError):
|
||||
return None
|
||||
if stat.S_ISDIR(info.st_mode) and not getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
||||
return info
|
||||
return None
|
||||
|
||||
|
||||
def _directories(path: Path) -> Iterator[tuple[Path, os.stat_result]]:
|
||||
if _directory_stat(path) is None:
|
||||
return
|
||||
try:
|
||||
for child in path.iterdir():
|
||||
if (info := _directory_stat(child)) is not None:
|
||||
yield child, info
|
||||
except (FileNotFoundError, NotADirectoryError):
|
||||
return
|
||||
|
||||
|
||||
def _find_stale_stages(paths: Paths, cutoff: float) -> dict[tuple[str, str], list[tuple[Path, os.stat_result]]]:
|
||||
candidates = {}
|
||||
for owner_dir, _ in _directories(extended_length_path(paths.base_dir / "users")):
|
||||
for thread_dir, _ in _directories(owner_dir / "threads"):
|
||||
scope = owner_dir.name, thread_dir.name
|
||||
try:
|
||||
paths.thread_dir(scope[1], user_id=scope[0])
|
||||
except ValueError:
|
||||
continue # A queued attachment cannot have been staged here.
|
||||
stages = [(path, info) for path, info in _directories(thread_dir / QUEUED_UPLOADS_DIR) if is_staging_id(path.name) and info.st_mtime < cutoff]
|
||||
if stages:
|
||||
candidates[scope] = stages
|
||||
return candidates
|
||||
|
||||
|
||||
def _remove_stale_stages(candidates: list[tuple[Path, os.stat_result]], cutoff: float) -> int:
|
||||
removed = 0
|
||||
for path, original in candidates:
|
||||
try:
|
||||
current = _directory_stat(path)
|
||||
if current is None or current.st_mtime >= cutoff or current.st_ctime_ns != original.st_ctime_ns:
|
||||
continue
|
||||
if not current.st_ino or not os.path.samestat(original, current):
|
||||
continue
|
||||
shutil.rmtree(path)
|
||||
removed += 1
|
||||
except FileNotFoundError:
|
||||
pass # A peer startup sweep or thread deletion already removed it.
|
||||
except OSError:
|
||||
logger.warning("Failed to remove abandoned queued upload stage", exc_info=True)
|
||||
return removed
|
||||
|
||||
|
||||
async def cleanup_abandoned_queued_uploads(store: RunStore, paths: Paths) -> int:
|
||||
cutoff = time() - UPLOAD_STAGING_MIN_AGE.total_seconds()
|
||||
candidates = await run_file_io(_find_stale_stages, paths, cutoff)
|
||||
if not candidates:
|
||||
return 0
|
||||
|
||||
# Discover directories before reading active rows. A peer may have staged
|
||||
# bytes but still be committing its input. If its source is active, keep
|
||||
# the directory. Otherwise the commit either preceded the terminal status
|
||||
# and will be visible in the receipt read below, or can no longer succeed.
|
||||
# Include active rows even when a peer clock put their timestamp in the future.
|
||||
active = await store.list_inflight(before=datetime.max.replace(tzinfo=UTC).isoformat())
|
||||
active_scopes = {((row.get("user_id") or "").lower(), row["thread_id"].lower()) for row in active}
|
||||
removed = 0
|
||||
for (owner_id, thread_id), stages in candidates.items():
|
||||
if (owner_id.lower(), thread_id.lower()) in active_scopes:
|
||||
continue
|
||||
runs = await store.list_input_runs(thread_id, user_id=owner_id, limit=None, ignore_scope_case=True)
|
||||
# A dispatch receipt can be applied before the files reach the sandbox.
|
||||
receipts = (item for run in runs for item in (run.get("run_inputs") or {}).get("items", []))
|
||||
referenced = {stage.get("id") for item in receipts if (stage := item.get("attachment_stage")) and item.get("status") != "cancelled" and stage.get("published") is not True}
|
||||
orphaned = [(path, info) for path, info in stages if path.name not in referenced]
|
||||
if orphaned:
|
||||
removed += await await_drained(run_file_io(_remove_stale_stages, orphaned, cutoff))
|
||||
return removed
|
||||
333
backend/app/gateway/run_input_files.py
Normal file
333
backend/app/gateway/run_input_files.py
Normal file
@ -0,0 +1,333 @@
|
||||
"""Keep queued attachments outside the sandbox until their run is admitted."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
from collections.abc import Awaitable, Callable
|
||||
from pathlib import Path
|
||||
from typing import TypedDict
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
from starlette.datastructures import UploadFile
|
||||
|
||||
from app.gateway.persistent_writes import run_drained_write
|
||||
from app.gateway.routers import uploads
|
||||
from app.gateway.upload_ingestion import prepare_published_uploads
|
||||
from deerflow.config.app_config import AppConfig
|
||||
from deerflow.config.paths import get_paths
|
||||
from deerflow.uploads.companions import register_companion
|
||||
from deerflow.uploads.manager import UPLOAD_STAGING_PREFIX, UPLOAD_STAGING_SUFFIX, normalize_filename
|
||||
from deerflow.utils.atomic_write import publish_bytes_atomically
|
||||
from deerflow.utils.file_io import await_drained, run_file_io
|
||||
from deerflow.utils.host_paths import extended_length_path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
QUEUED_UPLOADS_DIR = ".queued-uploads"
|
||||
|
||||
|
||||
class StagedInputFile(TypedDict):
|
||||
filename: str
|
||||
size: int
|
||||
sha256: str
|
||||
|
||||
|
||||
def is_staging_id(staging_id: str) -> bool:
|
||||
return bool(re.fullmatch(r"[0-9a-f]{32}", staging_id))
|
||||
|
||||
|
||||
def _validate_staging_id(staging_id: str) -> None:
|
||||
if not is_staging_id(staging_id):
|
||||
raise ValueError("Invalid queued upload identifier")
|
||||
|
||||
|
||||
def _staging_dir(thread_id: str, user_id: str, staging_id: str) -> Path:
|
||||
_validate_staging_id(staging_id)
|
||||
# Sandbox mounts and the artifacts API are scoped to user-data; ordinary
|
||||
# thread deletion also removes this sibling directory.
|
||||
return extended_length_path(get_paths().thread_dir(thread_id, user_id=user_id) / QUEUED_UPLOADS_DIR / staging_id)
|
||||
|
||||
|
||||
def _staged_file(directory: Path, index: int, filename: str) -> Path:
|
||||
suffix = Path(filename).suffix.lower()
|
||||
return directory / (f"{index}{suffix}" if suffix in uploads.CONVERTIBLE_EXTENSIONS else str(index))
|
||||
|
||||
|
||||
def _stage_files(directory: Path, files: list[UploadFile], limits: uploads.UploadLimits) -> list[StagedInputFile]:
|
||||
if len(files) > limits.max_files:
|
||||
raise HTTPException(status_code=413, detail=f"Too many files: maximum is {limits.max_files}")
|
||||
try:
|
||||
names = [normalize_filename(file.filename or "") for file in files]
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="Invalid queued attachment filename") from exc
|
||||
|
||||
directory.mkdir(mode=0o700, parents=True)
|
||||
staged = []
|
||||
total = 0
|
||||
for index, (file, filename) in enumerate(zip(files, names, strict=True)):
|
||||
size = 0
|
||||
digest = hashlib.sha256()
|
||||
with _staged_file(directory, index, filename).open("xb") as destination:
|
||||
while chunk := file.file.read(uploads.UPLOAD_CHUNK_SIZE):
|
||||
size += len(chunk)
|
||||
total += len(chunk)
|
||||
if size > limits.max_file_size:
|
||||
raise HTTPException(status_code=413, detail=f"File too large: {filename}")
|
||||
if total > limits.max_total_size:
|
||||
raise HTTPException(status_code=413, detail="Total upload size too large")
|
||||
digest.update(chunk)
|
||||
destination.write(chunk)
|
||||
staged.append(StagedInputFile(filename=filename, size=size, sha256=digest.hexdigest()))
|
||||
return staged
|
||||
|
||||
|
||||
def _discard_staging(directory: Path) -> None:
|
||||
try:
|
||||
shutil.rmtree(directory)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except OSError as exc:
|
||||
logger.warning("Could not discard queued attachment staging (%s)", type(exc).__name__)
|
||||
|
||||
|
||||
async def stage_input_files(thread_id: str, user_id: str, files: list[UploadFile], config: AppConfig) -> tuple[str, list[StagedInputFile]]:
|
||||
staging_id = uuid4().hex
|
||||
directory = await run_file_io(_staging_dir, thread_id, user_id, staging_id)
|
||||
try:
|
||||
staged = await run_drained_write("Stage queued attachments", _stage_files, (HTTPException,), directory, files, uploads._get_upload_limits(config))
|
||||
except BaseException:
|
||||
await await_drained(run_file_io(_discard_staging, directory))
|
||||
raise
|
||||
return staging_id, staged
|
||||
|
||||
|
||||
async def discard_input_files(thread_id: str, user_id: str, staging_id: str) -> None:
|
||||
directory = await run_file_io(_staging_dir, thread_id, user_id, staging_id)
|
||||
await run_drained_write("Discard queued attachments", _discard_staging, (), directory)
|
||||
|
||||
|
||||
def _is_staged_link(source: Path, target: Path) -> bool:
|
||||
try:
|
||||
return os.path.samestat(source.lstat(), target.lstat())
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
|
||||
|
||||
def _rollback_links(links: list[tuple[Path, Path]]) -> None:
|
||||
for source, target in reversed(links):
|
||||
try:
|
||||
if _is_staged_link(source, target):
|
||||
target.unlink(missing_ok=True)
|
||||
except OSError as exc:
|
||||
logger.warning("Could not roll back queued attachment publication (%s)", type(exc).__name__)
|
||||
|
||||
|
||||
def _publish_files(
|
||||
thread_id: str,
|
||||
user_id: str,
|
||||
directory: Path,
|
||||
targets: list[tuple[Path, str]],
|
||||
converted: dict[int, Path],
|
||||
) -> tuple[list[Path], list[tuple[Path, Path]], list[tuple[Path, Path]]]:
|
||||
uploads_dir = uploads.ensure_uploads_dir(thread_id, user_id=user_id)
|
||||
plan = directory / "destinations.json"
|
||||
try:
|
||||
destinations: dict[str, str] = json.loads(plan.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
destinations = {}
|
||||
occupied = {entry.name.casefold(): entry for entry in uploads_dir.iterdir()}
|
||||
seen = {entry.name for entry in occupied.values()} | set(destinations.values())
|
||||
links: list[tuple[Path, Path]] = []
|
||||
|
||||
def link(source: Path, requested: str) -> Path:
|
||||
filename = destinations.get(source.name)
|
||||
if filename is None:
|
||||
uploads._pure_destination(uploads_dir, requested)
|
||||
elif (existing := occupied.get(filename.casefold())) is not None and existing.name != filename:
|
||||
# A different spelling still counts as a collision on case-sensitive filesystems.
|
||||
filename = None
|
||||
while True:
|
||||
if filename is None:
|
||||
filename = uploads.claim_unique_filename(requested, seen)
|
||||
destinations[source.name] = filename
|
||||
# Persist the choice before making a sandbox-visible link so a
|
||||
# pre-graph failure can retry with the same attachment names.
|
||||
publish_bytes_atomically(plan, json.dumps(destinations).encode("utf-8"))
|
||||
try:
|
||||
path = uploads._link_staged_no_overwrite(source, uploads_dir, filename, unlink_staged=False)
|
||||
except FileExistsError:
|
||||
path = uploads_dir / filename
|
||||
if not _is_staged_link(source, path):
|
||||
filename = None
|
||||
continue
|
||||
links.append((source, path))
|
||||
return path
|
||||
|
||||
try:
|
||||
# Claim user-supplied names first so a generated companion cannot
|
||||
# displace an attachment such as report.md accompanying report.pdf.
|
||||
paths = [link(source, filename) for source, filename in targets]
|
||||
companions = [(paths[index], link(source, paths[index].with_suffix(".md").name)) for index, source in converted.items()]
|
||||
except BaseException:
|
||||
_rollback_links(links)
|
||||
raise
|
||||
return paths, companions, links
|
||||
|
||||
|
||||
_REMOTE_UPLOAD_TRANSACTION = """
|
||||
import json, os, stat, sys
|
||||
from pathlib import Path
|
||||
|
||||
action, directory, prefix, suffix, names = json.loads(sys.argv[1])
|
||||
directory = Path(directory)
|
||||
files = [
|
||||
[directory / name, *(directory / f"{prefix}-{index}{kind}{suffix}" for kind in ("", "-next", "-old"))]
|
||||
for index, name in enumerate(names)
|
||||
]
|
||||
|
||||
def info(path):
|
||||
try:
|
||||
return path.lstat()
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
|
||||
def same_file(first, second):
|
||||
return first is not None and second is not None and os.path.samestat(first, second)
|
||||
|
||||
def rollback():
|
||||
# Only touch destinations that still contain this batch's staged inode.
|
||||
for target, staged, _, backup in reversed(files):
|
||||
if same_file(info(staged), info(target)):
|
||||
if info(backup) is None:
|
||||
target.unlink(missing_ok=True)
|
||||
else:
|
||||
os.replace(backup, target)
|
||||
|
||||
if action == 'promote':
|
||||
try:
|
||||
for target, staged, candidate, backup in files:
|
||||
previous = info(target)
|
||||
if same_file(info(staged), previous):
|
||||
continue # The transport may have retried an acknowledged move.
|
||||
if previous is not None:
|
||||
if stat.S_ISDIR(previous.st_mode):
|
||||
raise IsADirectoryError(target)
|
||||
if info(backup) is None:
|
||||
os.link(target, backup, follow_symlinks=False)
|
||||
if info(candidate) is None:
|
||||
os.link(staged, candidate, follow_symlinks=False)
|
||||
os.replace(candidate, target)
|
||||
except BaseException:
|
||||
rollback()
|
||||
raise
|
||||
elif action in ('rollback', 'discard'):
|
||||
if action == 'rollback':
|
||||
rollback()
|
||||
for _, staged, candidate, backup in files:
|
||||
for path in (staged, candidate, backup):
|
||||
path.unlink(missing_ok=True)
|
||||
print(prefix)
|
||||
"""
|
||||
|
||||
|
||||
def _publish_remote_uploads(sandbox, paths: list[Path]) -> None:
|
||||
"""Transfer private files before publishing their names in a remote sandbox."""
|
||||
prefix = f"{UPLOAD_STAGING_PREFIX}{uuid4().hex}"
|
||||
root = getattr(sandbox, "artifact_root", None)
|
||||
directory = f"{root.rstrip('/')}/uploads" if isinstance(root, str) and root else uploads.upload_virtual_path("").rstrip("/")
|
||||
|
||||
def checked_command(action: str) -> None:
|
||||
payload = json.dumps([action, directory, prefix, UPLOAD_STAGING_SUFFIX, [path.name for path in paths]])
|
||||
output = sandbox.execute_command(f"python3 -I -c {shlex.quote(_REMOTE_UPLOAD_TRANSACTION)} {shlex.quote(payload)}", timeout=30)
|
||||
if output.strip() != prefix or getattr(output, "exit_code", 0) != 0:
|
||||
if action == "probe":
|
||||
raise OSError("Remote sandbox does not support queued upload publication with Python 3")
|
||||
raise OSError("Remote queued upload reconciliation was not acknowledged")
|
||||
|
||||
checked_command("probe")
|
||||
action = "discard"
|
||||
try:
|
||||
for index, path in enumerate(paths):
|
||||
staged_name = f"{prefix}-{index}{UPLOAD_STAGING_SUFFIX}"
|
||||
uploads._sync_upload_to_sandbox(sandbox, path, uploads.upload_virtual_path(staged_name))
|
||||
action = "rollback"
|
||||
checked_command("promote")
|
||||
except BaseException:
|
||||
for retry in (False, True):
|
||||
try:
|
||||
checked_command(action)
|
||||
break
|
||||
except Exception:
|
||||
if retry:
|
||||
logger.exception("Failed to reconcile remote queued upload before releasing the sandbox")
|
||||
raise
|
||||
else:
|
||||
try:
|
||||
checked_command("discard")
|
||||
except Exception:
|
||||
logger.exception("Failed to remove temporary remote queued upload files")
|
||||
|
||||
|
||||
async def publish_input_files(thread_id: str, user_id: str, staging_id: str, files: list[StagedInputFile], *, request: Request, config: AppConfig, on_published: Callable[[], Awaitable[None]] | None = None) -> list[dict]:
|
||||
"""Publish only while the destination run owns the thread's run slot."""
|
||||
directory = await run_file_io(_staging_dir, thread_id, user_id, staging_id)
|
||||
targets: list[tuple[Path, str]] = []
|
||||
converted: dict[int, Path] = {}
|
||||
convert = uploads._auto_convert_documents_enabled(config)
|
||||
for index, file in enumerate(files):
|
||||
source = _staged_file(directory, index, file["filename"])
|
||||
targets.append((source, file["filename"]))
|
||||
if convert and source.suffix in uploads.CONVERTIBLE_EXTENSIONS:
|
||||
# Convert while the source is still private. The final staged
|
||||
# pathname is reserved for a fully written conversion.
|
||||
companion = directory / f"{index}.md"
|
||||
if not await run_file_io(companion.is_file):
|
||||
output = await uploads.convert_file_to_markdown(source, output_path=directory / f"{index}.md.part")
|
||||
if output is None:
|
||||
continue
|
||||
await run_file_io(os.replace, output, companion)
|
||||
converted[index] = companion
|
||||
|
||||
async def publish_and_sync() -> list[Path]:
|
||||
links = []
|
||||
lease = None
|
||||
try:
|
||||
provider = await run_file_io(uploads.get_sandbox_provider)
|
||||
if not uploads._uses_thread_data_mounts(provider):
|
||||
# Keep the ordinary upload endpoint's sandbox authorization.
|
||||
# Fresh remote sandboxes can mirror uploads during acquisition.
|
||||
lease = await uploads.try_acquire_sandbox_for_request(request, provider, thread_id, user_id=user_id, app_config=config, owner_prefix="gateway:queued-upload")
|
||||
if not lease.denied and lease.sandbox is None:
|
||||
raise RuntimeError("Failed to acquire sandbox for queued attachments")
|
||||
originals, companions, links = await run_drained_write("Publish queued attachments", _publish_files, (), thread_id, user_id, directory, targets, converted)
|
||||
paths = [target for _, target in links]
|
||||
await prepare_published_uploads(paths)
|
||||
if lease is not None and not lease.denied:
|
||||
await run_file_io(_publish_remote_uploads, lease.sandbox, paths)
|
||||
except BaseException:
|
||||
await run_file_io(_rollback_links, links)
|
||||
raise
|
||||
finally:
|
||||
if lease is not None:
|
||||
try:
|
||||
await lease.release()
|
||||
except Exception:
|
||||
logger.exception("Failed to release the queued attachment sandbox lease")
|
||||
if on_published is not None:
|
||||
await on_published()
|
||||
await run_file_io(_discard_staging, directory)
|
||||
# Unlinking the staged alias changes the inode's ctime. Record the
|
||||
# association afterward, once the upload has its final identity.
|
||||
for original, companion in companions:
|
||||
try:
|
||||
await run_file_io(register_companion, original, companion)
|
||||
except Exception as exc:
|
||||
logger.warning("Could not register queued attachment companion (%s)", type(exc).__name__)
|
||||
return originals
|
||||
|
||||
paths = await await_drained(publish_and_sync())
|
||||
return [{"filename": path.name, "original_filename": file["filename"], "size": file["size"], "path": uploads.upload_virtual_path(path.name), "status": "uploaded"} for file, path in zip(files, paths, strict=True)]
|
||||
@ -1,20 +1,35 @@
|
||||
"""HTTP admission and ordinary AgentRuns dispatch for in-flight user inputs."""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import json
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
from uuid import NAMESPACE_URL, uuid5
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
|
||||
from starlette.datastructures import UploadFile
|
||||
|
||||
from app.gateway.deps import get_agent_runs, get_current_user, get_run_manager
|
||||
from app.gateway.authz import require_permission
|
||||
from app.gateway.deps import get_agent_runs, get_config, get_current_user, get_run_manager
|
||||
from deerflow.config.app_config import AppConfig
|
||||
from deerflow.runtime.runs.inputs import InputCancelled, InputConflict, RunInputs
|
||||
from deerflow.runtime.runs.schemas import RunStatus
|
||||
from deerflow.utils.file_io import await_drained
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class QueuedAttachments:
|
||||
source: RunInputs
|
||||
input_id: str
|
||||
attempt: int
|
||||
stage: dict
|
||||
|
||||
|
||||
class RunInputRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
request_id: str = Field(min_length=1, max_length=96)
|
||||
@ -29,6 +44,46 @@ class RunInputRequest(BaseModel):
|
||||
return self
|
||||
|
||||
|
||||
class QueuedFileInputRequest(RunInputRequest):
|
||||
text: str = Field(max_length=16 * 1024)
|
||||
mode: Literal["queue"]
|
||||
|
||||
|
||||
def _parse_input(model: type[RunInputRequest], data: str | bytearray) -> RunInputRequest:
|
||||
try:
|
||||
return model.model_validate_json(data)
|
||||
except ValidationError as exc:
|
||||
raise HTTPException(422, exc.errors(include_url=False, include_input=False, include_context=False)) from exc
|
||||
|
||||
|
||||
async def submit_http_run_input(thread_id: str, run_id: str, request: Request):
|
||||
if request.headers.get("content-type", "").split(";", 1)[0].strip().lower() == "multipart/form-data":
|
||||
return await _submit_file_run_input(thread_id, run_id, request)
|
||||
# Multipart needs a larger ingress limit. Keep the former 1 MiB limit for
|
||||
# plain JSON even when both payload types share the same proxy location.
|
||||
data = bytearray()
|
||||
async for chunk in request.stream():
|
||||
if len(data) + len(chunk) > 1024 * 1024:
|
||||
raise HTTPException(413, "Run input JSON exceeds 1 MiB")
|
||||
data.extend(chunk)
|
||||
return await submit_run_input(thread_id, run_id, _parse_input(RunInputRequest, data), request)
|
||||
|
||||
|
||||
@require_permission("threads", "write")
|
||||
async def _submit_file_run_input(thread_id: str, run_id: str, request: Request):
|
||||
from app.gateway.routers.uploads import _get_upload_limits
|
||||
|
||||
config = await asyncio.to_thread(get_config)
|
||||
limits = _get_upload_limits(config)
|
||||
async with request.form(max_files=limits.max_files, max_fields=1, max_part_size=256 * 1024) as form:
|
||||
data = form.get("input")
|
||||
files = form.getlist("files")
|
||||
if not isinstance(data, str) or not files or len(form.multi_items()) != 1 + len(files) or not all(isinstance(file, UploadFile) for file in files):
|
||||
raise HTTPException(422, "Expected a queue input and one or more files")
|
||||
body = _parse_input(QueuedFileInputRequest, data)
|
||||
return await await_drained(submit_run_input(thread_id, run_id, body, request, files=files, upload_config=config))
|
||||
|
||||
|
||||
def _store(request):
|
||||
store = get_run_manager(request).input_store
|
||||
if store is None:
|
||||
@ -36,7 +91,15 @@ def _store(request):
|
||||
return store
|
||||
|
||||
|
||||
async def submit_run_input(thread_id: str, run_id: str, body: RunInputRequest, request: Request):
|
||||
async def submit_run_input(
|
||||
thread_id: str,
|
||||
run_id: str,
|
||||
body: RunInputRequest,
|
||||
request: Request,
|
||||
*,
|
||||
files: list[UploadFile] | None = None,
|
||||
upload_config: AppConfig | None = None,
|
||||
):
|
||||
manager = get_run_manager(request)
|
||||
user_id = await get_current_user(request)
|
||||
if user_id is None:
|
||||
@ -52,6 +115,8 @@ async def submit_run_input(thread_id: str, run_id: str, body: RunInputRequest, r
|
||||
from deerflow.persistence.coordination.sql import TaskConflict, TaskNotFound
|
||||
|
||||
if task_id := await managed_task(request, thread_id):
|
||||
if files:
|
||||
raise HTTPException(409, "Managed worker updates accept text only")
|
||||
service, owner, _runs = worker_context(request)
|
||||
if body.mode != "queue":
|
||||
raise HTTPException(409, "Use queue mode to update a managed worker")
|
||||
@ -60,9 +125,20 @@ async def submit_run_input(thread_id: str, run_id: str, body: RunInputRequest, r
|
||||
return _worker_input_receipt(item, run_id, body.request_id)
|
||||
except (TaskConflict, TaskNotFound, AgentRunError) as exc:
|
||||
raise worker_error(exc) from exc
|
||||
row = await _store(request).get(run_id, user_id=user_id)
|
||||
store = _store(request)
|
||||
row = await store.get(run_id, user_id=user_id)
|
||||
if row is None or row.get("run_inputs") is None:
|
||||
raise HTTPException(409, "This Run has not enabled interactive inputs")
|
||||
from app.gateway.run_input_files import discard_input_files, stage_input_files
|
||||
|
||||
stage = None
|
||||
if files:
|
||||
if body.mode != "queue" or upload_config is None:
|
||||
raise HTTPException(422, "Attachments require queue mode")
|
||||
if row["run_inputs"].get("queue_attachments") is not True:
|
||||
raise HTTPException(409, "This Run cannot dispatch queued attachments")
|
||||
stage_id, metadata = await stage_input_files(thread_id, user_id, files, upload_config)
|
||||
stage = {"id": stage_id, "files": metadata}
|
||||
try:
|
||||
from app.gateway.services import _CONTEXT_CONFIGURABLE_KEYS
|
||||
from deerflow.runtime.run_origin import admit_origin
|
||||
@ -71,10 +147,47 @@ async def submit_run_input(thread_id: str, run_id: str, body: RunInputRequest, r
|
||||
if isinstance(body.context.get("locale"), str):
|
||||
context["locale"] = body.context["locale"]
|
||||
source = "extension" if admit_origin(getattr(request.state, "run_origin", None)) is not None else "user"
|
||||
item = await RunInputs(_store(request), run_id, user_id).submit(body.request_id, body.text, body.mode, context=context, source=source)
|
||||
item = await RunInputs(store, run_id, user_id).submit(body.request_id, body.text, body.mode, context=context, source=source, attachment_stage=stage)
|
||||
except InputConflict as exc:
|
||||
if stage is not None:
|
||||
await discard_input_files(thread_id, user_id, stage["id"])
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
return {**item, "target_run_id": run_id}
|
||||
except Exception:
|
||||
if stage is not None:
|
||||
# A failed response from the store can follow a successful commit.
|
||||
# Keep the files unless we can confirm that no item owns them.
|
||||
try:
|
||||
current = await RunInputs(store, run_id, user_id).read()
|
||||
if not any(item.get("attachment_stage", {}).get("id") == stage["id"] for item in current["items"]):
|
||||
await discard_input_files(thread_id, user_id, stage["id"])
|
||||
except Exception:
|
||||
logger.warning("Could not reconcile queued attachments after a RunStore failure")
|
||||
raise
|
||||
if stage is not None and item.get("attachment_stage", {}).get("id") != stage["id"]:
|
||||
await discard_input_files(thread_id, user_id, stage["id"])
|
||||
return _input_receipt(item, run_id)
|
||||
|
||||
|
||||
def _input_receipt(item: dict, run_id: str) -> dict:
|
||||
receipt = {key: value for key, value in item.items() if key not in ("attachment_stage", "attachment_attempt")}
|
||||
stage = item.get("attachment_stage")
|
||||
if stage is not None and item["status"] != "cancelled":
|
||||
receipt["files"] = [{"filename": file["filename"], "size": file["size"]} for file in stage["files"]]
|
||||
return {**receipt, "target_run_id": run_id}
|
||||
|
||||
|
||||
async def _recover_unpublished_input(inputs: RunInputs, thread_id: str, entry: dict) -> dict:
|
||||
stage = entry.get("attachment_stage")
|
||||
child_id = entry.get("run_id")
|
||||
attempt = entry.get("attachment_attempt", 0)
|
||||
if not stage or not child_id or entry["status"] not in ("dispatching", "applied") or stage.get("published") is True or stage.get("publishing_attempt") == attempt:
|
||||
return entry
|
||||
child = await inputs.store.get(child_id, user_id=inputs.user_id)
|
||||
# Older admission records never fenced publication. Missing proof is
|
||||
# ambiguous for those runs, as it is when the worker crossed the fence.
|
||||
if child is None or child["thread_id"] != thread_id or child["status"] not in (RunStatus.error, RunStatus.interrupted, RunStatus.timeout) or (child.get("kwargs") or {}).get("queued_input_checks_publication") is not True:
|
||||
return entry
|
||||
return await inputs.publication_failed(entry["id"], child_id, attempt=attempt, require_unstarted=True)
|
||||
|
||||
|
||||
def _worker_input_receipt(item, run_id, request_id, consuming_run=None, cancelled=False):
|
||||
@ -107,14 +220,19 @@ async def list_thread_inputs(thread_id: str, request: Request):
|
||||
_, run, key = item["request_id"].split(":", 2)
|
||||
items.append(_worker_input_receipt(item, run, key, consuming_run, cancelled))
|
||||
return {"items": items, "active_run_id": active}
|
||||
rows = await _store(request).list_input_runs(thread_id, user_id=user_id)
|
||||
store = _store(request)
|
||||
rows = await store.list_input_runs(thread_id, user_id=user_id)
|
||||
items = []
|
||||
for row in reversed(rows):
|
||||
inputs = RunInputs(store, row["run_id"], user_id)
|
||||
for entry in (row.get("run_inputs") or {}).get("items", []):
|
||||
entry = await _recover_unpublished_input(inputs, thread_id, entry)
|
||||
status = entry["status"]
|
||||
if status in ("pending", "applying") and (row["status"] not in ("pending", "running", "success") or row.get("stop_reason")):
|
||||
status = "not_applied"
|
||||
items.append({key: value for key, value in {**entry, "status": status, "target_run_id": row["run_id"]}.items() if key != "context"})
|
||||
receipt = _input_receipt({**entry, "status": status}, row["run_id"])
|
||||
receipt.pop("context", None)
|
||||
items.append(receipt)
|
||||
# Rank unresolved inputs (pending / not_applied / ...) ahead of terminal
|
||||
# applied/cancelled receipts, prefer the newest entry within each group,
|
||||
# cap at 32 records, then restore chronological order. A plain items[-32:]
|
||||
@ -123,7 +241,7 @@ async def list_thread_inputs(thread_id: str, request: Request):
|
||||
# returns 32 unresolved rows and no receipts for submission reconciliation;
|
||||
# that trade-off follows the priority the issue asks for.
|
||||
keep = sorted(range(len(items)), key=lambda i: (items[i]["status"] in ("applied", "cancelled"), -i))[:32]
|
||||
return {"items": [items[i] for i in sorted(keep)], "active_run_id": await _store(request).active_input_run(thread_id, user_id=user_id)}
|
||||
return {"items": [items[i] for i in sorted(keep)], "active_run_id": await store.active_input_run(thread_id, user_id=user_id)}
|
||||
|
||||
|
||||
async def dispatch_queued_inputs(inputs: RunInputs, *, agent_runs, thread_id: str):
|
||||
@ -174,10 +292,15 @@ async def dispatch_one_input(thread_id, run_id, input_id, request, *, retry=Fals
|
||||
user_id = await get_current_user(request)
|
||||
if user_id is None:
|
||||
raise HTTPException(401, "Authentication required")
|
||||
source = await _store(request).get(run_id, user_id=user_id)
|
||||
store = _store(request)
|
||||
source = await store.get(run_id, user_id=user_id)
|
||||
if source is None or source["thread_id"] != thread_id:
|
||||
raise HTTPException(404, "Run not found")
|
||||
inputs = RunInputs(_store(request), run_id, user_id)
|
||||
inputs = RunInputs(store, run_id, user_id)
|
||||
if retry:
|
||||
original = next((entry for entry in (source.get("run_inputs") or {}).get("items", []) if entry["id"] == input_id), None)
|
||||
if original is not None:
|
||||
await _recover_unpublished_input(inputs, thread_id, original)
|
||||
entry = await inputs.claim(input_id, retry=retry)
|
||||
if entry.get("run_id"):
|
||||
run = await get_run(thread_id, entry["run_id"], request)
|
||||
@ -198,13 +321,18 @@ async def dispatch_one_input(thread_id, run_id, input_id, request, *, retry=Fals
|
||||
message = {"role": "user", "content": entry["text"], "id": message_id}
|
||||
if scope is not None:
|
||||
message["additional_kwargs"] = {KNOWLEDGE_SCOPE_KEY: copy.deepcopy(scope)}
|
||||
attempt = entry.get("attachment_attempt", 0)
|
||||
if stage := entry.get("attachment_stage"):
|
||||
request.state.queued_input_attachments = QueuedAttachments(inputs, input_id, attempt, stage)
|
||||
if entry.get("source", "user") == "user":
|
||||
# This fact comes from the stored, authenticated input, not from text
|
||||
# or an arbitrary extension-supplied metadata flag.
|
||||
request.state.run_origin = None
|
||||
body = RunCreateRequest(assistant_id=await resolve_thread_assistant_id(request, thread_id, fail_closed=True), input={"messages": [message]}, context=context, config=config, on_disconnect="continue")
|
||||
run = await create_run(thread_id, body, request, idempotency_key=f"run-input:{run_id}:{input_id}")
|
||||
await inputs.dispatched(entry["id"], run.run_id)
|
||||
# A new key is safe only when the earlier run failed before entering the graph.
|
||||
key = f"run-input-retry:{run_id}:{attempt}:{input_id}" if attempt else f"run-input:{run_id}:{input_id}"
|
||||
run = await create_run(thread_id, body, request, idempotency_key=key)
|
||||
await inputs.dispatched(input_id, run.run_id, attempt=attempt)
|
||||
return AgentRun(thread_id, run.run_id, run.status, run.assistant_id, run.stop_reason)
|
||||
|
||||
|
||||
@ -227,7 +355,18 @@ async def change_run_input(thread_id: str, run_id: str, input_id: str, request:
|
||||
raise HTTPException(403, "An unapplied input requires an explicit user retry")
|
||||
dispatched = await dispatch_one_input(thread_id, run_id, input_id, request, retry=True)
|
||||
return {"run_id": dispatched.run_id}
|
||||
await inputs.cancel(input_id)
|
||||
original = next((entry for entry in (await inputs.read())["items"] if entry["id"] == input_id), None)
|
||||
if original is not None:
|
||||
await _recover_unpublished_input(inputs, thread_id, original)
|
||||
await await_drained(_cancel_input(inputs, thread_id, user_id, input_id))
|
||||
return {"removed": True}
|
||||
except InputConflict as exc:
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
|
||||
|
||||
async def _cancel_input(inputs: RunInputs, thread_id: str, user_id: str, input_id: str):
|
||||
from app.gateway.run_input_files import discard_input_files
|
||||
|
||||
item = await inputs.cancel(input_id)
|
||||
if stage := item.get("attachment_stage"):
|
||||
await discard_input_files(thread_id, user_id, stage["id"])
|
||||
|
||||
@ -2674,6 +2674,7 @@ async def start_run(
|
||||
# Gateway-issued IDs, and old id-less run records remain comparable.
|
||||
request_input = _canonical_run_record_input(body.input, graph_input) if idempotency_key else None
|
||||
knowledge_default_request_hash = hashlib.sha256(json.dumps(request_input, sort_keys=True, ensure_ascii=False).encode()).hexdigest() if idempotency_key else None
|
||||
queued_attachments = getattr(request.state, "queued_input_attachments", None)
|
||||
if isinstance(graph_input, dict):
|
||||
graph_input = _assign_missing_run_input_message_ids(graph_input, thread_id=thread_id, idempotency_key=input_message_idempotency_key or idempotency_key)
|
||||
# deerflow_trace_id is server-issued, so the caller's value is replaced
|
||||
@ -3061,6 +3062,43 @@ async def start_run(
|
||||
raise
|
||||
|
||||
execution_context = replace(execution_context, verify_artifacts=verify_artifacts)
|
||||
if queued_attachments is not None:
|
||||
from app.gateway.run_input_files import publish_input_files
|
||||
|
||||
async def record_attachment_publication():
|
||||
try:
|
||||
await queued_attachments.source.publication_succeeded(queued_attachments.input_id, record.run_id, attempt=queued_attachments.attempt)
|
||||
except Exception:
|
||||
# Files are already published. A receipt write failure must
|
||||
# not requeue the message or prevent ordinary stage cleanup.
|
||||
logger.warning("Could not record queued attachment publication for run %s", record.run_id, exc_info=True)
|
||||
|
||||
async def publish_queued_attachments():
|
||||
# Only the admitted worker may expose this input's files to the thread.
|
||||
message = _current_human_message(graph_input)
|
||||
assert message is not None
|
||||
stage = queued_attachments.stage
|
||||
# Persist the fence before any copy. Recovery and a late
|
||||
# publisher must agree on which attempt owns this stage.
|
||||
await queued_attachments.source.begin_attachment_publication(queued_attachments.input_id, record.run_id, attempt=queued_attachments.attempt)
|
||||
try:
|
||||
files = await publish_input_files(thread_id, record.user_id, stage["id"], stage["files"], request=request, config=app_config, on_published=record_attachment_publication)
|
||||
except Exception as exc:
|
||||
# This run cannot reach the graph. Restore the input before
|
||||
# the worker reports it as finished and the queue stops polling.
|
||||
if not record.ownership_lost:
|
||||
try:
|
||||
await await_drained(queued_attachments.source.publication_failed(queued_attachments.input_id, record.run_id, attempt=queued_attachments.attempt))
|
||||
except Exception:
|
||||
logger.warning("Could not restore queued input after attachment publication failed for run %s", record.run_id, exc_info=True)
|
||||
raise RuntimeError("Could not publish queued attachments") from exc
|
||||
message.additional_kwargs["files"] = files
|
||||
# Keep the resolved attachment paths on the run record as
|
||||
# well as the graph input for clients reconnecting mid-run.
|
||||
record.kwargs["input"] = _canonical_run_record_input(body.input, graph_input)
|
||||
await run_mgr.persist_metadata(record.run_id)
|
||||
|
||||
execution_context = replace(execution_context, verify_artifacts=publish_queued_attachments)
|
||||
try:
|
||||
await run_agent(
|
||||
bridge,
|
||||
@ -3147,6 +3185,7 @@ async def start_run(
|
||||
kwargs={
|
||||
"input": run_record_input,
|
||||
**({"knowledge_default_request_hash": knowledge_default_request_hash} if accepts_knowledge_default else {}),
|
||||
**({"queued_input_request_hash": knowledge_default_request_hash, "queued_input_checks_publication": True} if queued_attachments is not None else {}),
|
||||
"config": redact_config_secrets(body.config),
|
||||
**({"conversation_references": conversation_references} if conversation_references else {}),
|
||||
},
|
||||
@ -3192,7 +3231,10 @@ async def start_run(
|
||||
# today's default; explicit scopes and recovery do not use
|
||||
# this compatibility path.
|
||||
matches_legacy_default_request = accepts_knowledge_default and "knowledge_default_request_hash" not in stored and stored_input == request_input
|
||||
matches_input = matches_default_request or matches_legacy_default_request or stored_input == body.input or stored_input == request_input or stored_input == run_record_input
|
||||
# The worker fills the actual file names after acquiring the
|
||||
# thread. Reconcile retries against the original request.
|
||||
matches_queued_input = queued_attachments is not None and knowledge_default_request_hash is not None and stored.get("queued_input_request_hash") == knowledge_default_request_hash
|
||||
matches_input = matches_queued_input or matches_default_request or matches_legacy_default_request or stored_input == body.input or stored_input == request_input or stored_input == run_record_input
|
||||
if not matches_idempotency_request or not matches_input or record.assistant_id != body.assistant_id or stored.get("conversation_references", []) != conversation_references:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
|
||||
@ -115,6 +115,16 @@ def _uploads() -> Any:
|
||||
return uploads
|
||||
|
||||
|
||||
async def prepare_published_uploads(paths: list[Path], *, sandbox: object | None = None) -> None:
|
||||
"""Make published thread files readable by mounted and remote sandboxes."""
|
||||
uploads = _uploads()
|
||||
# The Gateway and the sandbox can run under different UIDs.
|
||||
await run_file_io(uploads._make_uploaded_paths_sandbox_readable, paths)
|
||||
if sandbox is not None:
|
||||
for path in paths:
|
||||
await run_file_io(uploads._sync_upload_to_sandbox, sandbox, path, uploads.upload_virtual_path(path.name))
|
||||
|
||||
|
||||
class UnsafeFilenameError(ValueError):
|
||||
"""The display filename could not be normalized/claimed; ordinary behavior skips it."""
|
||||
|
||||
@ -152,14 +162,12 @@ class ThreadUploadIngestionService:
|
||||
self._config = app_config
|
||||
self._limits: UploadLimits | None = None
|
||||
self._uploads_dir: Path | None = None
|
||||
self._sync_to_sandbox = False
|
||||
self._sandbox_lease: SandboxRequestLease | None = None
|
||||
self._sandbox: Any = None
|
||||
self._auto_convert = False
|
||||
self._seen_filenames: set[str] = set()
|
||||
self._written_paths: list[Path] = []
|
||||
self._companion_pairs: list[tuple[Path, Path]] = []
|
||||
self._sync_targets: list[tuple[Path, str]] = []
|
||||
self._total_size = 0
|
||||
|
||||
async def __aenter__(self) -> ThreadUploadIngestionService:
|
||||
@ -198,8 +206,7 @@ class ThreadUploadIngestionService:
|
||||
listing = await run_file_io(uploads.list_files_in_dir, self._uploads_dir)
|
||||
self._seen_filenames.update(entry["filename"] for entry in listing["files"])
|
||||
sandbox_provider = uploads.get_sandbox_provider()
|
||||
self._sync_to_sandbox = not uploads._uses_thread_data_mounts(sandbox_provider)
|
||||
if self._sync_to_sandbox:
|
||||
if not uploads._uses_thread_data_mounts(sandbox_provider):
|
||||
|
||||
async def acquire_lease() -> None:
|
||||
self._sandbox_lease = await uploads.try_acquire_sandbox_for_request(
|
||||
@ -359,8 +366,6 @@ class ThreadUploadIngestionService:
|
||||
raise
|
||||
|
||||
virtual_path = uploads.upload_virtual_path(safe_filename)
|
||||
if self._sync_to_sandbox:
|
||||
self._sync_targets.append((file_path, virtual_path))
|
||||
|
||||
file_info: dict[str, Any] = {
|
||||
"filename": safe_filename,
|
||||
@ -422,8 +427,6 @@ class ThreadUploadIngestionService:
|
||||
else:
|
||||
unique_md_name, md_path = await self._link_commit_with_retry(uploads, Path(md_staged), unique_md_name)
|
||||
md_virtual_path = uploads.upload_virtual_path(md_path.name)
|
||||
if self._sync_to_sandbox:
|
||||
self._sync_targets.append((md_path, md_virtual_path))
|
||||
file_info["markdown_file"] = md_path.name
|
||||
self._companion_pairs.append((file_path, md_path))
|
||||
file_info["markdown_path"] = str(self._uploads_dir / md_path.name)
|
||||
@ -447,18 +450,7 @@ class ThreadUploadIngestionService:
|
||||
await await_drained(self._finalize())
|
||||
|
||||
async def _finalize(self) -> None:
|
||||
uploads = _uploads()
|
||||
# Uploaded files are created with 0o600 permissions (owner read/write
|
||||
# only). In Docker sandbox deployments the gateway writes as root but
|
||||
# the sandbox process runs as a non-root user (typically UID 1000).
|
||||
# Without group/other read bits the sandbox cannot access the files —
|
||||
# whether the uploads directory is bind-mounted into the container or
|
||||
# synced via sandbox.update_file. Always add group/other read bits so
|
||||
# every sandbox configuration can read the uploaded content.
|
||||
await run_file_io(uploads._make_uploaded_paths_sandbox_readable, self._written_paths)
|
||||
if self._sync_to_sandbox and self._sandbox is not None:
|
||||
for file_path, virtual_path in self._sync_targets:
|
||||
await run_file_io(uploads._sync_upload_to_sandbox, self._sandbox, file_path, virtual_path)
|
||||
await prepare_published_uploads(self._written_paths, sandbox=self._sandbox)
|
||||
# Record the final inode/version only after sandbox-readable chmod and
|
||||
# any synchronization have completed; chmod changes st_ctime_ns.
|
||||
for original, markdown in self._companion_pairs:
|
||||
|
||||
@ -306,6 +306,28 @@ the response is HTTP 504 with detail
|
||||
|
||||
### Runs
|
||||
|
||||
#### Submit an input while a Web run is active
|
||||
|
||||
`POST /api/threads/{thread_id}/runs/{run_id}/inputs` accepts JSON with
|
||||
`request_id`, `text`, `mode` (`queue` or `steer`), and optional `context`.
|
||||
To queue attachments, send multipart form data with the JSON in `input`
|
||||
and one `files` part per file. Set `mode` to `queue`. The text may be empty
|
||||
when the message includes files. Upload limits and thread write permission
|
||||
apply.
|
||||
|
||||
The input receipt and `GET /api/threads/{thread_id}/inputs` show attachment
|
||||
names and sizes. Files become readable by the Agent when the queued message's
|
||||
run starts. An available filename is preserved. If a name is taken, the
|
||||
Gateway picks an available name and remembers it for publication retries.
|
||||
An attachment input stays dispatching until the files are published. If its
|
||||
run stops before publication starts, or publication fails before the Agent
|
||||
receives the message, the same input can be removed or retried without another
|
||||
upload. An uncertain dispatch or publication outcome reuses the accepted run.
|
||||
On startup, the Gateway
|
||||
cleans up abandoned staging directories older than 24 hours.
|
||||
Remote sandboxes without thread-data mounts need Python 3 to publish queued
|
||||
attachments and reconcile partial transfers.
|
||||
|
||||
#### Create Run
|
||||
|
||||
Execute the agent with input.
|
||||
|
||||
@ -75,11 +75,21 @@ class RunRepository(RunStore):
|
||||
await session.commit()
|
||||
return copy.deepcopy(state)
|
||||
|
||||
async def list_input_runs(self, thread_id, *, user_id=None, limit=10):
|
||||
async def list_input_runs(self, thread_id, *, user_id=None, limit=10, ignore_scope_case=False):
|
||||
async with self._sf() as session:
|
||||
query = select(RunRow).where(RunRow.thread_id == thread_id, RunRow.run_inputs_json["items"][0]["id"].as_string().is_not(None))
|
||||
|
||||
def scope_filter(column, value):
|
||||
if not ignore_scope_case:
|
||||
return column == value
|
||||
# Filesystem IDs are ASCII. PostgreSQL's configured locale
|
||||
# can lowercase ASCII I differently from the filesystem.
|
||||
if session.get_bind().dialect.name == "postgresql":
|
||||
column = column.collate("C")
|
||||
return func.lower(column) == value.lower()
|
||||
|
||||
query = select(RunRow).where(scope_filter(RunRow.thread_id, thread_id), RunRow.run_inputs_json["items"][0]["id"].as_string().is_not(None))
|
||||
if user_id is not None:
|
||||
query = query.where(RunRow.user_id == user_id)
|
||||
query = query.where(scope_filter(RunRow.user_id, user_id))
|
||||
rows = await session.execute(query.order_by(RunRow.created_at.desc(), RunRow.run_id.desc()).limit(limit))
|
||||
return [self._row_to_dict(row) for row in rows.scalars()]
|
||||
|
||||
|
||||
@ -49,8 +49,19 @@ class RunInputs:
|
||||
raise InputConflict("Run input application requires its owning worker")
|
||||
return await self.store.mutate_run_inputs(self.run_id, change, user_id=self.user_id, owner_worker_id=self.worker_id if owned else None)
|
||||
|
||||
async def submit(self, request_id: str, text: str, mode: Literal["queue", "steer"], *, context: dict | None = None, source: Literal["user", "extension"] = "user") -> dict:
|
||||
if not isinstance(text, str) or not text.strip() or len(text.encode("utf-8")) > MAX_INPUT_BYTES:
|
||||
async def submit(
|
||||
self,
|
||||
request_id: str,
|
||||
text: str,
|
||||
mode: Literal["queue", "steer"],
|
||||
*,
|
||||
context: dict | None = None,
|
||||
source: Literal["user", "extension"] = "user",
|
||||
attachment_stage: dict | None = None,
|
||||
) -> dict:
|
||||
if attachment_stage and mode != "queue":
|
||||
raise InputConflict("Attachments require queue mode")
|
||||
if not isinstance(text, str) or (not text.strip() and not attachment_stage) or len(text.encode("utf-8")) > MAX_INPUT_BYTES:
|
||||
raise InputConflict("Input must contain text of at most 16 KiB")
|
||||
if mode not in ("queue", "steer") or not isinstance(request_id, str) or not 1 <= len(request_id) <= 96:
|
||||
raise InputConflict("Invalid input mode or request ID")
|
||||
@ -61,14 +72,19 @@ class RunInputs:
|
||||
if old is not None:
|
||||
if (old["text"], old["mode"], old.get("context", {}), old.get("source", "user")) != (text, mode, context, source):
|
||||
raise InputConflict("Request ID already belongs to different input")
|
||||
if (old.get("attachment_stage") or {}).get("files") != (attachment_stage or {}).get("files"):
|
||||
raise InputConflict("Request ID already belongs to different attachments")
|
||||
return
|
||||
if state["closed"] or row.get("status") not in ("pending", "running") or row.get("operation_kind", "run") != "run" or row.get("cancel_action"):
|
||||
raise InputConflict("Run is finishing or stopped; this input was not accepted")
|
||||
if attachment_stage and state.get("queue_attachments") is not True:
|
||||
raise InputConflict("This Run cannot dispatch queued attachments")
|
||||
if len(state["items"]) >= MAX_INPUTS or sum(len(x["text"].encode("utf-8")) for x in state["items"]) + len(text.encode("utf-8")) > MAX_TOTAL_BYTES:
|
||||
raise InputConflict("Too many inputs for this Run; wait for it to finish")
|
||||
state["items"].append(
|
||||
{"id": request_id, "text": text, "mode": mode, "context": context, "source": source, "status": "pending", "message_id": str(uuid5(NAMESPACE_URL, f"deerflow-input:{self.run_id}:{request_id}")), "created_at": now_iso()}
|
||||
)
|
||||
item = {"id": request_id, "text": text, "mode": mode, "context": context, "source": source, "status": "pending", "message_id": str(uuid5(NAMESPACE_URL, f"deerflow-input:{self.run_id}:{request_id}")), "created_at": now_iso()}
|
||||
if attachment_stage:
|
||||
item["attachment_stage"] = attachment_stage
|
||||
state["items"].append(item)
|
||||
|
||||
state = await self._change(change)
|
||||
return next(x for x in state["items"] if x["id"] == request_id)
|
||||
@ -103,6 +119,9 @@ class RunInputs:
|
||||
def change(state, row):
|
||||
if row.get("status") in ("pending", "running") and not row.get("cancel_action"):
|
||||
state["closed"] = False
|
||||
# Only the owning worker enables this. An older Gateway in a
|
||||
# rolling upgrade would otherwise dispatch the text alone.
|
||||
state["queue_attachments"] = True
|
||||
|
||||
await self._change(change, owned=True)
|
||||
|
||||
@ -115,12 +134,59 @@ class RunInputs:
|
||||
|
||||
await self._change(change)
|
||||
|
||||
async def dispatched(self, input_id: str, run_id: str) -> None:
|
||||
async def dispatched(self, input_id: str, run_id: str, *, attempt: int = 0) -> None:
|
||||
def change(state, row):
|
||||
item = next(x for x in state["items"] if x["id"] == input_id)
|
||||
# The worker can fail publication before admission returns its
|
||||
# receipt. A late receipt must not hide the retryable item.
|
||||
if item.get("attachment_attempt", 0) != attempt:
|
||||
return
|
||||
if item.get("run_id") not in (None, run_id):
|
||||
raise InputConflict("Queued input already belongs to another Run")
|
||||
item.update(status="applied", run_id=run_id)
|
||||
item["run_id"] = run_id
|
||||
stage = item.get("attachment_stage")
|
||||
# Keep polling admitted attachments until the worker publishes them.
|
||||
if not stage or stage.get("published") is True:
|
||||
item["status"] = "applied"
|
||||
|
||||
await self._change(change)
|
||||
|
||||
async def begin_attachment_publication(self, input_id: str, run_id: str, *, attempt: int) -> None:
|
||||
def change(state, row):
|
||||
item = next(x for x in state["items"] if x["id"] == input_id)
|
||||
stage = item.get("attachment_stage")
|
||||
if not stage or stage.get("published") is True or item["status"] not in ("dispatching", "applied"):
|
||||
raise InputConflict("Queued attachment is no longer dispatching")
|
||||
if item.get("attachment_attempt", 0) != attempt or item.get("run_id") not in (None, run_id) or stage.get("publishing_attempt") == attempt:
|
||||
raise InputConflict("Queued attachment dispatch changed")
|
||||
stage["publishing_attempt"] = attempt
|
||||
|
||||
await self._change(change)
|
||||
|
||||
async def publication_failed(self, input_id: str, run_id: str, *, attempt: int, require_unstarted: bool = False) -> dict:
|
||||
def change(state, row):
|
||||
item = next(x for x in state["items"] if x["id"] == input_id)
|
||||
stage = item.get("attachment_stage")
|
||||
if not stage or stage.get("published") is True or item["status"] not in ("dispatching", "applied"):
|
||||
return
|
||||
if item.get("attachment_attempt", 0) != attempt or item.get("run_id") not in (None, run_id):
|
||||
return
|
||||
if require_unstarted and stage.get("publishing_attempt") == attempt:
|
||||
return
|
||||
item.pop("run_id", None)
|
||||
item.update(status="not_applied", attachment_attempt=attempt + 1)
|
||||
|
||||
state = await self._change(change)
|
||||
return next(x for x in state["items"] if x["id"] == input_id)
|
||||
|
||||
async def publication_succeeded(self, input_id: str, run_id: str, *, attempt: int) -> None:
|
||||
def change(state, row):
|
||||
item = next(x for x in state["items"] if x["id"] == input_id)
|
||||
stage = item.get("attachment_stage")
|
||||
if stage and item["status"] in ("dispatching", "applied") and item.get("attachment_attempt", 0) == attempt and item.get("run_id") in (None, run_id):
|
||||
stage["published"] = True
|
||||
if item.get("run_id") == run_id:
|
||||
item["status"] = "applied"
|
||||
|
||||
await self._change(change)
|
||||
|
||||
@ -144,11 +210,12 @@ class RunInputs:
|
||||
state = await self._change(change)
|
||||
return next(x for x in state["items"] if x["id"] == input_id)
|
||||
|
||||
async def cancel(self, input_id: str) -> None:
|
||||
async def cancel(self, input_id: str) -> dict:
|
||||
def change(state, row):
|
||||
item = next((x for x in state["items"] if x["id"] == input_id), None)
|
||||
if item is None or item["status"] not in ("pending", "not_applied", "cancelled"):
|
||||
raise InputConflict("This input is already being applied")
|
||||
item["status"] = "cancelled"
|
||||
|
||||
await self._change(change)
|
||||
state = await self._change(change)
|
||||
return next(x for x in state["items"] if x["id"] == input_id)
|
||||
|
||||
@ -128,7 +128,12 @@ class RunStore(abc.ABC):
|
||||
"""
|
||||
raise NotImplementedError("Run inputs are unavailable in this store")
|
||||
|
||||
async def list_input_runs(self, thread_id, *, user_id=None, limit=10):
|
||||
async def list_input_runs(self, thread_id, *, user_id=None, limit=10, ignore_scope_case=False):
|
||||
"""List runs with input receipts, newest first. None removes the limit.
|
||||
|
||||
Filesystem reconciliation can ignore ASCII case in path identifiers to
|
||||
preserve receipts that alias the same directory on some volumes.
|
||||
"""
|
||||
raise NotImplementedError("Run inputs are unavailable in this store")
|
||||
|
||||
async def active_input_run(self, thread_id, *, user_id=None):
|
||||
|
||||
@ -38,9 +38,16 @@ class MemoryRunStore(RunStore):
|
||||
row["run_inputs"] = state
|
||||
return copy.deepcopy(state)
|
||||
|
||||
async def list_input_runs(self, thread_id, *, user_id=None, limit=10):
|
||||
rows = [x for x in await self.list_by_thread(thread_id, user_id=user_id, limit=len(self._runs_by_thread.get(thread_id, {}))) if (x.get("run_inputs") or {}).get("items")]
|
||||
return copy.deepcopy(rows[:limit])
|
||||
async def list_input_runs(self, thread_id, *, user_id=None, limit=10, ignore_scope_case=False):
|
||||
if ignore_scope_case:
|
||||
thread_id = thread_id.lower()
|
||||
owner = user_id.lower() if user_id is not None else None
|
||||
rows = [row for row in self._runs.values() if row["thread_id"].lower() == thread_id and row.get("operation_kind", "run") == "run" and (owner is None or (row.get("user_id") or "").lower() == owner)]
|
||||
rows.sort(key=lambda row: run_sort_key(row.get("created_at"), row["run_id"]), reverse=True)
|
||||
else:
|
||||
rows = await self.list_by_thread(thread_id, user_id=user_id, limit=len(self._runs_by_thread.get(thread_id, {})))
|
||||
with_inputs = [row for row in rows if (row.get("run_inputs") or {}).get("items")]
|
||||
return copy.deepcopy(with_inputs[:limit])
|
||||
|
||||
async def active_input_run(self, thread_id, *, user_id=None):
|
||||
for run_id in reversed(self._runs_by_thread.get(thread_id, {})):
|
||||
|
||||
@ -3,6 +3,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import threading
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from io import BytesIO
|
||||
from pathlib import Path, PurePosixPath
|
||||
from types import SimpleNamespace
|
||||
@ -92,6 +95,63 @@ async def test_upload_endpoint_mounted_provider_does_not_block_event_loop(tmp_pa
|
||||
assert await asyncio.to_thread(target.read_bytes) == b"hello uploads"
|
||||
|
||||
|
||||
async def test_queued_upload_storage_does_not_block_event_loop(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from app.gateway.run_input_files import discard_input_files, publish_input_files, stage_input_files
|
||||
from deerflow.config.paths import get_paths
|
||||
|
||||
_reset_paths(tmp_path, monkeypatch)
|
||||
monkeypatch.setattr(uploads, "get_sandbox_provider", lambda: _MountedProvider())
|
||||
file = UploadFile(filename="notes.txt", file=BytesIO(b"queued notes"))
|
||||
config = SimpleNamespace()
|
||||
stage_id, staged = await stage_input_files("queued-thread", "owner", [file], config)
|
||||
stage_root, uploads_dir = await asyncio.to_thread(
|
||||
lambda: (
|
||||
get_paths().thread_dir("queued-thread", user_id="owner") / ".queued-uploads",
|
||||
get_uploads_dir("queued-thread", user_id="owner"),
|
||||
)
|
||||
)
|
||||
assert not await asyncio.to_thread(uploads_dir.exists)
|
||||
files = await publish_input_files("queued-thread", "owner", stage_id, staged, request=None, config=config)
|
||||
assert await asyncio.to_thread((uploads_dir / files[0]["filename"]).read_bytes) == b"queued notes"
|
||||
await discard_input_files("queued-thread", "owner", stage_id)
|
||||
assert not await asyncio.to_thread(lambda: any(stage_root.iterdir()))
|
||||
|
||||
|
||||
async def test_startup_queued_upload_sweep_does_not_block_event_loop(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from app.gateway import run_input_cleanup
|
||||
from app.gateway.app import _run_startup_queued_upload_sweep
|
||||
from app.gateway.run_input_files import QUEUED_UPLOADS_DIR, stage_input_files
|
||||
from deerflow.config.paths import get_paths
|
||||
from deerflow.runtime.runs.store.memory import MemoryRunStore
|
||||
|
||||
_reset_paths(tmp_path, monkeypatch)
|
||||
file = UploadFile(filename="notes.txt", file=BytesIO(b"abandoned attachment"))
|
||||
stage_id, _ = await stage_input_files("queued-thread", "owner", [file], SimpleNamespace())
|
||||
stage = await asyncio.to_thread(lambda: get_paths().thread_dir("queued-thread", user_id="owner") / QUEUED_UPLOADS_DIR / stage_id)
|
||||
old = (datetime.now(UTC) - timedelta(days=7)).timestamp()
|
||||
await asyncio.to_thread(os.utime, stage, (old, old))
|
||||
|
||||
event_loop_thread = threading.get_ident()
|
||||
operations = []
|
||||
|
||||
def record_thread(operation):
|
||||
def run(*args):
|
||||
operations.append((operation.__name__, threading.get_ident()))
|
||||
return operation(*args)
|
||||
|
||||
return run
|
||||
|
||||
for operation in (run_input_cleanup._find_stale_stages, run_input_cleanup._remove_stale_stages):
|
||||
monkeypatch.setattr(run_input_cleanup, operation.__name__, record_thread(operation))
|
||||
|
||||
app = SimpleNamespace(state=SimpleNamespace(run_store=MemoryRunStore()))
|
||||
await _run_startup_queued_upload_sweep(app)
|
||||
|
||||
assert not await asyncio.to_thread(stage.exists)
|
||||
assert [name for name, _ in operations] == ["_find_stale_stages", "_remove_stale_stages"]
|
||||
assert all(thread != event_loop_thread for _, thread in operations)
|
||||
|
||||
|
||||
async def test_unsafe_filename_is_reported_as_skipped(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""A rejected filename must reach the caller in ``skipped_files`` (#7160)."""
|
||||
_reset_paths(tmp_path, monkeypatch)
|
||||
|
||||
@ -847,6 +847,445 @@ async def _wait_for_worker(client, task_id, section, field, value):
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
|
||||
async def _submit_screenshot(client, url, request_id, text, screenshot, *, mode="queue"):
|
||||
import json
|
||||
|
||||
return await client.post(
|
||||
url,
|
||||
data={"input": json.dumps({"request_id": request_id, "text": text, "mode": mode})},
|
||||
files=[("files", ("screenshot.png", screenshot, "image/png"))],
|
||||
)
|
||||
|
||||
|
||||
def _png(color):
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
output = BytesIO()
|
||||
Image.new("RGB", (1, 1), color).save(output, format="PNG")
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_queued_attachments_are_delivered_in_order_and_cancelled_bytes_are_discarded(worker_gateway, monkeypatch):
|
||||
import asyncio
|
||||
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from deerflow.config.paths import get_paths
|
||||
|
||||
client, runs, state, entered, owner = worker_gateway
|
||||
thread = await runs.create_thread(thread_id="queue-with-attachments")
|
||||
uploads = get_paths().sandbox_uploads_dir(thread, user_id=owner)
|
||||
staging = get_paths().thread_dir(thread, user_id=owner) / ".queued-uploads"
|
||||
first_png, second_png, cancelled_png = (_png(color) for color in ("red", "blue", "green"))
|
||||
observed = asyncio.Queue()
|
||||
finish_first_followup = asyncio.Event()
|
||||
|
||||
def contents(directory):
|
||||
return {path.read_bytes() for path in directory.rglob("*") if path.is_file()}
|
||||
|
||||
async def observe_uploads(prompt, runtime):
|
||||
observed.put_nowait((prompt, runtime.context["run_id"], await asyncio.to_thread(contents, uploads)))
|
||||
if prompt == "first follow-up":
|
||||
await finish_first_followup.wait()
|
||||
|
||||
state.present_worker_report = observe_uploads
|
||||
initial = await runs.start(thread_id=thread, input={"messages": [{"role": "user", "content": "wait"}]})
|
||||
inputs_url = f"/api/threads/{thread}/runs/{initial.run_id}/inputs"
|
||||
thread_inputs = f"/api/threads/{thread}/inputs"
|
||||
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
assert (await _submit_screenshot(client, inputs_url, "steer", "update now", first_png, mode="steer")).status_code == 422
|
||||
assert await asyncio.to_thread(contents, staging) == set()
|
||||
|
||||
# An older worker has no capability marker in its persisted state.
|
||||
def remove_queue_attachment_capability(inputs, _row):
|
||||
assert inputs.pop("queue_attachments") is True
|
||||
|
||||
def restore_queue_attachment_capability(inputs, _row):
|
||||
inputs["queue_attachments"] = True
|
||||
|
||||
await state.run_store.mutate_run_inputs(initial.run_id, remove_queue_attachment_capability, user_id=owner)
|
||||
assert (await _submit_screenshot(client, inputs_url, "old-worker", "old worker", first_png)).status_code == 409
|
||||
assert not await asyncio.to_thread(staging.exists)
|
||||
await state.run_store.mutate_run_inputs(initial.run_id, restore_queue_attachment_capability, user_id=owner)
|
||||
|
||||
async def fail_before_input_write(*args, **kwargs):
|
||||
assert await asyncio.to_thread(contents, staging) == {first_png}
|
||||
raise OperationalError("UPDATE runs", {}, OSError("RunStore write unavailable"))
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(state.run_store, "mutate_run_inputs", fail_before_input_write)
|
||||
with pytest.raises(OperationalError, match="RunStore write unavailable"):
|
||||
await _submit_screenshot(client, inputs_url, "failed-write", "failed write", first_png)
|
||||
assert await asyncio.to_thread(contents, staging) == set()
|
||||
|
||||
first = (await _submit_screenshot(client, inputs_url, "first", "first follow-up", first_png)).raise_for_status().json()
|
||||
repeated = (await _submit_screenshot(client, inputs_url, "first", "first follow-up", first_png)).raise_for_status().json()
|
||||
assert first == repeated
|
||||
assert first["files"] == [{"filename": "screenshot.png", "size": len(first_png)}]
|
||||
assert (await _submit_screenshot(client, inputs_url, "first", "first follow-up", second_png)).status_code == 409
|
||||
(await _submit_screenshot(client, inputs_url, "second", "second follow-up", second_png)).raise_for_status()
|
||||
(await _submit_screenshot(client, inputs_url, "cancelled", "cancel this", cancelled_png)).raise_for_status()
|
||||
entries = (await client.get(thread_inputs)).raise_for_status().json()["items"]
|
||||
assert [(entry["id"], entry["status"], entry["files"][0]["filename"]) for entry in entries] == [
|
||||
("first", "pending", "screenshot.png"),
|
||||
("second", "pending", "screenshot.png"),
|
||||
("cancelled", "pending", "screenshot.png"),
|
||||
]
|
||||
assert await asyncio.to_thread(contents, uploads) == set()
|
||||
assert cancelled_png in await asyncio.to_thread(contents, staging)
|
||||
(await client.delete(f"{inputs_url}/cancelled")).raise_for_status()
|
||||
assert cancelled_png not in await asyncio.to_thread(contents, staging)
|
||||
|
||||
state.release_worker.set()
|
||||
assert await asyncio.wait_for(observed.get(), 5) == ("wait", initial.run_id, set())
|
||||
prompt, first_run, visible = await asyncio.wait_for(observed.get(), 5)
|
||||
assert prompt == "first follow-up" and visible == {first_png}
|
||||
finish_first_followup.set()
|
||||
prompt, second_run, visible = await asyncio.wait_for(observed.get(), 5)
|
||||
assert prompt == "second follow-up" and visible == {first_png, second_png}
|
||||
assert (await runs.wait(thread_id=thread, run_id=second_run, timeout=5)).status == "success"
|
||||
|
||||
retried = (await client.post(f"{inputs_url}/first/retry")).raise_for_status().json()
|
||||
assert retried["run_id"] == first_run
|
||||
assert (await client.post(f"{inputs_url}/cancelled/retry")).status_code == 409
|
||||
records = await state.run_manager.list_by_thread(thread, user_id=owner)
|
||||
assert {record.run_id for record in records} == {initial.run_id, first_run, second_run}
|
||||
assert len([path for path in uploads.rglob("*") if path.is_file()]) == 2
|
||||
assert await asyncio.to_thread(contents, staging) == set()
|
||||
finally:
|
||||
state.release_worker.set()
|
||||
finish_first_followup.set()
|
||||
|
||||
messages = (await runs.get_state(thread_id=thread))["values"]["messages"]
|
||||
by_prompt = {message["content"]: message.get("additional_kwargs", {}) for message in messages}
|
||||
assert "files" not in by_prompt["wait"]
|
||||
(first_file,) = by_prompt["first follow-up"]["files"]
|
||||
(second_file,) = by_prompt["second follow-up"]["files"]
|
||||
assert first_file["filename"] == "screenshot.png"
|
||||
assert second_file["filename"] == "screenshot_1.png"
|
||||
root = "/mnt/user-data/uploads/"
|
||||
assert (uploads / first_file["path"].removeprefix(root)).read_bytes() == first_png
|
||||
assert (uploads / second_file["path"].removeprefix(root)).read_bytes() == second_png
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_startup_sweep_removes_published_queue_stage_after_delete_failure(worker_gateway, monkeypatch):
|
||||
import asyncio
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from app.gateway import run_input_files
|
||||
from app.gateway.run_input_cleanup import cleanup_abandoned_queued_uploads
|
||||
from deerflow.config.paths import get_paths
|
||||
|
||||
client, runs, state, entered, owner = worker_gateway
|
||||
paths = get_paths()
|
||||
thread = await runs.create_thread(thread_id="queue-published-stage")
|
||||
screenshot = _png("blue")
|
||||
staging_root = paths.thread_dir(thread, user_id=owner) / ".queued-uploads"
|
||||
initial = await runs.start(thread_id=thread, input={"messages": [{"role": "user", "content": "wait"}]})
|
||||
inputs_url = f"/api/threads/{thread}/runs/{initial.run_id}/inputs"
|
||||
remove = run_input_files.shutil.rmtree
|
||||
failed_deletions = []
|
||||
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
(await _submit_screenshot(client, inputs_url, "attachment", "read screenshot", screenshot)).raise_for_status()
|
||||
(stage,) = staging_root.iterdir()
|
||||
|
||||
def fail_stage_removal(directory, *args, **kwargs):
|
||||
if os.path.basename(directory) == stage.name:
|
||||
failed_deletions.append(directory)
|
||||
raise PermissionError("temporary staging deletion failure")
|
||||
return remove(directory, *args, **kwargs)
|
||||
|
||||
with monkeypatch.context() as publish_patch:
|
||||
publish_patch.setattr(run_input_files.shutil, "rmtree", fail_stage_removal)
|
||||
state.release_worker.set()
|
||||
source = await state.run_manager.get(initial.run_id, user_id=owner)
|
||||
await asyncio.wait_for(asyncio.shield(source.task), 5)
|
||||
finally:
|
||||
state.release_worker.set()
|
||||
|
||||
assert len(failed_deletions) == 1
|
||||
(receipt,) = (await client.get(f"/api/threads/{thread}/inputs")).raise_for_status().json()["items"]
|
||||
assert receipt["status"] == "applied"
|
||||
assert receipt["files"] == [{"filename": "screenshot.png", "size": len(screenshot)}]
|
||||
upload = paths.sandbox_uploads_dir(thread, user_id=owner) / "screenshot.png"
|
||||
assert upload.read_bytes() == screenshot
|
||||
upload.unlink()
|
||||
assert (stage / "0").read_bytes() == screenshot
|
||||
old = (datetime.now(UTC) - timedelta(days=7)).timestamp()
|
||||
os.utime(stage, (old, old))
|
||||
|
||||
assert await cleanup_abandoned_queued_uploads(state.run_store, paths) == 1
|
||||
assert not stage.exists()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_attachment_only_queue_retry_reconciles_a_lost_dispatch_receipt(worker_gateway, monkeypatch):
|
||||
import asyncio
|
||||
|
||||
from deerflow.config.paths import get_paths
|
||||
from deerflow.runtime.runs.inputs import RunInputs
|
||||
|
||||
client, runs, state, entered, owner = worker_gateway
|
||||
thread = await runs.create_thread(thread_id="queue-attachment-retry")
|
||||
screenshot = _png("purple")
|
||||
admitted = asyncio.Event()
|
||||
lost_receipt = None
|
||||
dispatched = RunInputs.dispatched
|
||||
|
||||
async def fail_first_receipt(self, input_id, run_id, *, attempt=0):
|
||||
nonlocal lost_receipt
|
||||
if input_id == "attachment" and lost_receipt is None:
|
||||
# Fail the receipt write after ordinary admission already succeeded.
|
||||
lost_receipt = run_id
|
||||
admitted.set()
|
||||
raise OSError("receipt write failed after admission")
|
||||
await dispatched(self, input_id, run_id, attempt=attempt)
|
||||
|
||||
monkeypatch.setattr(RunInputs, "dispatched", fail_first_receipt)
|
||||
initial = await runs.start(thread_id=thread, input={"messages": [{"role": "user", "content": "wait"}]})
|
||||
inputs_url = f"/api/threads/{thread}/runs/{initial.run_id}/inputs"
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
receipt = (await _submit_screenshot(client, inputs_url, "attachment", "", screenshot)).raise_for_status().json()
|
||||
assert receipt["status"] == "pending"
|
||||
finally:
|
||||
state.release_worker.set()
|
||||
|
||||
await asyncio.wait_for(admitted.wait(), 5)
|
||||
assert (await runs.wait(thread_id=thread, run_id=lost_receipt, timeout=5)).status == "success"
|
||||
before_retry = (await client.get(f"/api/threads/{thread}/inputs")).raise_for_status().json()["items"]
|
||||
assert before_retry[0]["status"] == "dispatching"
|
||||
reply = (await client.post(f"{inputs_url}/attachment/retry")).raise_for_status().json()
|
||||
assert reply == {"run_id": lost_receipt}
|
||||
after_retry = (await client.get(f"/api/threads/{thread}/inputs")).raise_for_status().json()["items"]
|
||||
assert after_retry[0]["status"] == "applied"
|
||||
records = await state.run_manager.list_by_thread(thread, user_id=owner)
|
||||
assert {record.run_id for record in records} == {initial.run_id, lost_receipt}
|
||||
uploads = get_paths().sandbox_uploads_dir(thread, user_id=owner)
|
||||
assert [path.read_bytes() for path in uploads.rglob("*") if path.is_file()] == [screenshot]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("action", ["list_then_retry", "retry", "remove"])
|
||||
async def test_queued_attachment_can_recover_when_child_stops_before_publication(worker_gateway, monkeypatch, action):
|
||||
import asyncio
|
||||
|
||||
from deerflow.config.paths import get_paths
|
||||
from deerflow.runtime import RunManager
|
||||
from deerflow.runtime.runs.inputs import RunInputs
|
||||
|
||||
client, runs, state, entered, owner = worker_gateway
|
||||
thread = await runs.create_thread(thread_id="queue-unstarted-child")
|
||||
screenshot = _png("purple")
|
||||
paths = get_paths()
|
||||
staging = paths.thread_dir(thread, user_id=owner) / ".queued-uploads"
|
||||
start_child = asyncio.Event()
|
||||
pending_child = asyncio.Event()
|
||||
receipt_written = asyncio.Event()
|
||||
first_child = None
|
||||
try_start = state.run_manager.try_start
|
||||
dispatched = RunInputs.dispatched
|
||||
initial = await runs.start(thread_id=thread, input={"messages": [{"role": "user", "content": "wait"}]})
|
||||
thread_inputs = f"/api/threads/{thread}/inputs"
|
||||
inputs_url = f"/api/threads/{thread}/runs/{initial.run_id}/inputs"
|
||||
input_url = f"{inputs_url}/attachment"
|
||||
|
||||
async def hold_first_child(run_id):
|
||||
nonlocal first_child
|
||||
if first_child is None:
|
||||
first_child = run_id
|
||||
pending_child.set()
|
||||
await start_child.wait()
|
||||
return await try_start(run_id)
|
||||
|
||||
async def observe_receipt(self, input_id, run_id, *, attempt=0):
|
||||
await dispatched(self, input_id, run_id, attempt=attempt)
|
||||
if input_id == "attachment":
|
||||
receipt_written.set()
|
||||
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
monkeypatch.setattr(state.run_manager, "try_start", hold_first_child)
|
||||
monkeypatch.setattr(RunInputs, "dispatched", observe_receipt)
|
||||
(await _submit_screenshot(client, inputs_url, "attachment", "read screenshot", screenshot)).raise_for_status()
|
||||
(stage,) = staging.iterdir()
|
||||
state.release_worker.set()
|
||||
await asyncio.wait_for(pending_child.wait(), 5)
|
||||
await asyncio.wait_for(receipt_written.wait(), 5)
|
||||
assert (await runs.get(thread_id=thread, run_id=first_child)).status == "pending"
|
||||
(receipt,) = (await client.get(thread_inputs)).raise_for_status().json()["items"]
|
||||
assert receipt["status"] == "dispatching"
|
||||
assert receipt["run_id"] == first_child
|
||||
|
||||
if action == "remove":
|
||||
# A restarted Gateway sees the durable child but has no worker for it.
|
||||
restarted = RunManager(store=state.run_store)
|
||||
recovered = await restarted.reconcile_orphaned_inflight_runs(error="Gateway restarted", stop_reason="orphan_recovered")
|
||||
assert [run.run_id for run in recovered] == [first_child]
|
||||
(await client.delete(input_url)).raise_for_status()
|
||||
assert not stage.exists()
|
||||
else:
|
||||
await runs.cancel(thread_id=thread, run_id=first_child)
|
||||
start_child.set()
|
||||
child = await state.run_manager.get(first_child, user_id=owner)
|
||||
await asyncio.wait_for(asyncio.shield(child.task), 5)
|
||||
if action == "list_then_retry":
|
||||
(receipt,) = (await client.get(thread_inputs)).raise_for_status().json()["items"]
|
||||
assert receipt["status"] == "not_applied"
|
||||
assert "run_id" not in receipt
|
||||
assert stage.is_dir()
|
||||
reply = (await client.post(f"{input_url}/retry")).raise_for_status().json()
|
||||
assert reply["run_id"] != first_child
|
||||
assert (await client.post(f"{input_url}/retry")).raise_for_status().json() == reply
|
||||
assert (await runs.wait(thread_id=thread, run_id=reply["run_id"], timeout=5)).status == "success"
|
||||
assert (paths.sandbox_uploads_dir(thread, user_id=owner) / "screenshot.png").read_bytes() == screenshot
|
||||
assert not stage.exists()
|
||||
finally:
|
||||
state.release_worker.set()
|
||||
start_child.set()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("action", ["retry", "remove"])
|
||||
async def test_queued_attachment_publication_failure_leaves_input_actionable(worker_gateway, monkeypatch, action):
|
||||
import asyncio
|
||||
|
||||
from app.gateway import run_input_files
|
||||
from deerflow.config.paths import get_paths
|
||||
|
||||
client, runs, state, entered, owner = worker_gateway
|
||||
thread = await runs.create_thread(thread_id="queue-attachment-publish-error")
|
||||
screenshot = _png("orange")
|
||||
uploads = get_paths().sandbox_uploads_dir(thread, user_id=owner)
|
||||
uploads.mkdir(parents=True, exist_ok=True)
|
||||
existing_screenshot = uploads / "screenshot.png"
|
||||
original = _png("white")
|
||||
existing_screenshot.write_bytes(original)
|
||||
staging_root = get_paths().thread_dir(thread, user_id=owner) / ".queued-uploads"
|
||||
attempts = []
|
||||
executions = []
|
||||
retry_entered = asyncio.Event()
|
||||
finish_retry = asyncio.Event()
|
||||
hold_retry = False
|
||||
prepare_uploads = run_input_files.prepare_published_uploads
|
||||
|
||||
async def fail_first_prepare(paths, **kwargs):
|
||||
attempts.append([path.name for path in paths])
|
||||
if len(attempts) == 1:
|
||||
raise OSError("transient queued attachment I/O failure")
|
||||
await prepare_uploads(paths, **kwargs)
|
||||
|
||||
async def observe_run(prompt, runtime):
|
||||
executions.append((prompt, runtime.context["run_id"]))
|
||||
if hold_retry and prompt == "analyze screenshot":
|
||||
retry_entered.set()
|
||||
await finish_retry.wait()
|
||||
|
||||
monkeypatch.setattr(run_input_files, "prepare_published_uploads", fail_first_prepare)
|
||||
state.present_worker_report = observe_run
|
||||
initial = await runs.start(thread_id=thread, input={"messages": [{"role": "user", "content": "wait"}]})
|
||||
inputs_url = f"/api/threads/{thread}/runs/{initial.run_id}/inputs"
|
||||
input_url = f"{inputs_url}/attachment"
|
||||
thread_inputs_url = f"/api/threads/{thread}/inputs"
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
(await _submit_screenshot(client, inputs_url, "attachment", "analyze screenshot", screenshot)).raise_for_status()
|
||||
(stage,) = staging_root.iterdir()
|
||||
finally:
|
||||
state.release_worker.set()
|
||||
|
||||
source = await state.run_manager.get(initial.run_id, user_id=owner)
|
||||
await asyncio.wait_for(asyncio.shield(source.task), 5)
|
||||
([destination],) = attempts
|
||||
assert destination != existing_screenshot.name
|
||||
(failed,) = [record for record in await state.run_manager.list_by_thread(thread, user_id=owner) if record.run_id != initial.run_id]
|
||||
await asyncio.wait_for(asyncio.shield(failed.task), 5)
|
||||
assert failed.status == "error"
|
||||
assert executions == [("wait", initial.run_id)]
|
||||
(receipt,) = (await client.get(thread_inputs_url)).raise_for_status().json()["items"]
|
||||
assert receipt["status"] == "not_applied"
|
||||
assert any(path.read_bytes() == screenshot for path in stage.iterdir() if path.is_file())
|
||||
assert list(uploads.iterdir()) == [existing_screenshot]
|
||||
assert existing_screenshot.read_bytes() == original
|
||||
|
||||
if action == "remove":
|
||||
(await client.delete(input_url)).raise_for_status()
|
||||
assert not stage.exists()
|
||||
assert (await client.post(f"{input_url}/retry")).status_code == 409
|
||||
assert executions == [("wait", initial.run_id)]
|
||||
return
|
||||
|
||||
# A retry with an empty destination should still honor the name assigned
|
||||
# for the original collision.
|
||||
existing_screenshot.unlink()
|
||||
hold_retry = True
|
||||
try:
|
||||
reply = (await client.post(f"{input_url}/retry")).raise_for_status().json()
|
||||
await asyncio.wait_for(retry_entered.wait(), 5)
|
||||
assert reply["run_id"] != failed.run_id
|
||||
retry = await state.run_store.get(reply["run_id"], user_id=owner)
|
||||
(message,) = retry["kwargs"]["input"]["messages"]
|
||||
(file,) = message["additional_kwargs"]["files"]
|
||||
assert file["filename"] == destination
|
||||
assert file["path"] == f"/mnt/user-data/uploads/{destination}"
|
||||
assert (await client.post(f"{input_url}/retry")).raise_for_status().json() == reply
|
||||
finally:
|
||||
finish_retry.set()
|
||||
assert (await runs.wait(thread_id=thread, run_id=reply["run_id"], timeout=5)).status == "success"
|
||||
assert (await client.post(f"{input_url}/retry")).raise_for_status().json() == reply
|
||||
assert executions == [("wait", initial.run_id), ("analyze screenshot", reply["run_id"])]
|
||||
assert attempts == [[destination], [destination]]
|
||||
assert not stage.exists()
|
||||
assert len(list(uploads.iterdir())) == 1
|
||||
assert (uploads / destination).read_bytes() == screenshot
|
||||
records = await state.run_manager.list_by_thread(thread, user_id=owner)
|
||||
assert {record.run_id for record in records} == {initial.run_id, failed.run_id, reply["run_id"]}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_queued_report_keeps_its_relative_attachment_reference(worker_gateway):
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import PurePosixPath
|
||||
|
||||
from deerflow.config.paths import get_paths
|
||||
|
||||
client, runs, state, entered, owner = worker_gateway
|
||||
thread = await runs.create_thread(thread_id="queue-relative-attachments")
|
||||
uploads = get_paths().sandbox_uploads_dir(thread, user_id=owner)
|
||||
report_text = "\n"
|
||||
chart = _png("red")
|
||||
initial = await runs.start(thread_id=thread, input={"messages": [{"role": "user", "content": "wait"}]})
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
response = await client.post(
|
||||
f"/api/threads/{thread}/runs/{initial.run_id}/inputs",
|
||||
data={"input": json.dumps({"request_id": "report", "mode": "queue", "text": "review this report"})},
|
||||
files=[("files", ("report.md", report_text.encode(), "text/markdown")), ("files", ("chart.png", chart, "image/png"))],
|
||||
)
|
||||
assert response.raise_for_status().json()["status"] == "pending"
|
||||
finally:
|
||||
state.release_worker.set()
|
||||
|
||||
source = await state.run_manager.get(initial.run_id, user_id=owner)
|
||||
await asyncio.wait_for(asyncio.shield(source.task), 5)
|
||||
messages = (await runs.get_state(thread_id=thread))["values"]["messages"]
|
||||
report_message = next(message for message in messages if message["content"] == "review this report")
|
||||
files = {item["filename"]: PurePosixPath(item["path"]) for item in report_message["additional_kwargs"]["files"]}
|
||||
assert set(files) == {"report.md", "chart.png"}
|
||||
assert files["report.md"].parent / "chart.png" == files["chart.png"]
|
||||
assert (uploads / files["report.md"].name).read_text(encoding="utf-8") == report_text
|
||||
assert (uploads / files["chart.png"].name).read_bytes() == chart
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("followup_report", [None, b"revised report"], ids=["text-followup", "same-name-file"])
|
||||
async def test_managed_worker_routes_followups_and_retains_the_producing_runs_file(worker_gateway, followup_report):
|
||||
|
||||
@ -30,6 +30,8 @@ used by ``make dev``, and the Kubernetes/Helm ConfigMap template.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import pytest
|
||||
from support.nginx_conf import NGINX_CONFIGS
|
||||
from support.nginx_conf import extract_location_block as _extract_location_block
|
||||
@ -102,6 +104,33 @@ def test_uploads_route_still_has_its_own_body_size_settings(path):
|
||||
assert "proxy_request_buffering off;" in block
|
||||
|
||||
|
||||
def _matching_thread_location(content: str, request_path: str) -> str:
|
||||
for pattern in re.findall(r"^\s*location ~ (\S+) \{", content, re.M):
|
||||
if re.match(pattern, request_path):
|
||||
return _extract_location_block(content, f"~ {pattern}")
|
||||
raise AssertionError(f"no regex location matched {request_path}")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", NGINX_CONFIGS)
|
||||
def test_run_input_submission_allows_multipart_framing(path):
|
||||
content = _read(path)
|
||||
block = _matching_thread_location(content, "/api/threads/t/runs/r/inputs")
|
||||
|
||||
assert _parse_body_size_bytes(block) == 101 * 1024**2
|
||||
assert "proxy_request_buffering off;" in block
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", NGINX_CONFIGS)
|
||||
def test_run_input_submission_preserves_threads_read_timeout(path):
|
||||
content = _read(path)
|
||||
block = _matching_thread_location(content, "/api/threads/t/runs/r/inputs")
|
||||
generic = _extract_location_block(content, "~ ^/api/threads")
|
||||
|
||||
assert _parse_read_timeout_seconds(block) >= _parse_read_timeout_seconds(generic)
|
||||
assert _matching_thread_location(content, "/api/threads/t/runs/r/inputs/i/retry") == generic
|
||||
assert _matching_thread_location(content, "/api/threads/t/runs/r/inputs/i") == generic
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", NGINX_CONFIGS)
|
||||
def test_threads_route_outlasts_blocking_gateway_calls(path):
|
||||
"""The browser calls ``/api/threads/*`` directly, not through
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
"""Run inputs are durable, owner-scoped and cannot race terminal admission."""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
@ -82,6 +84,102 @@ async def input_store(request, tmp_path):
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_startup_sweep_keeps_inflight_and_retryable_queued_uploads(input_store, tmp_path, monkeypatch):
|
||||
from app.gateway import app as gateway_app
|
||||
from app.gateway import run_input_files
|
||||
from app.gateway.run_inputs import _cancel_input
|
||||
from deerflow.config import paths as paths_module
|
||||
from deerflow.config.paths import Paths
|
||||
|
||||
paths = Paths(tmp_path)
|
||||
monkeypatch.setattr(paths_module, "_paths", paths)
|
||||
old = (datetime.now(UTC) - timedelta(days=7)).timestamp()
|
||||
|
||||
def stage(thread_id, staging_id, *, owner=USER_ID, age=old):
|
||||
directory = paths.thread_dir(thread_id, user_id=owner) / ".queued-uploads" / staging_id
|
||||
directory.mkdir(parents=True)
|
||||
(directory / "0").write_bytes(b"staged bytes")
|
||||
os.utime(directory, (age, age))
|
||||
return directory
|
||||
|
||||
retryable = stage("thread", "a" * 32)
|
||||
inputs = RunInputs(input_store, "run", USER_ID, "worker")
|
||||
await inputs.reopen()
|
||||
await inputs.submit("retry", "Retry this upload", "queue", attachment_stage={"id": retryable.name, "files": []})
|
||||
admitted = stage("thread", "9" * 32)
|
||||
await inputs.submit("admitted", "Still awaiting publication", "queue", attachment_stage={"id": admitted.name, "files": []})
|
||||
cancelled = stage("thread", "f" * 32)
|
||||
await inputs.submit("cancel", "Remove this upload", "queue", attachment_stage={"id": cancelled.name, "files": []})
|
||||
remove_stage = Mock(side_effect=PermissionError("temporary staging deletion failure"))
|
||||
with monkeypatch.context() as cancel_patch:
|
||||
cancel_patch.setattr(run_input_files.shutil, "rmtree", remove_stage)
|
||||
await _cancel_input(inputs, "thread", USER_ID, "cancel")
|
||||
remove_stage.assert_called_once()
|
||||
assert cancelled.is_dir()
|
||||
assert (await inputs.read())["items"][-1]["status"] == "cancelled"
|
||||
assert await input_store.update_status("run", "error", stop_reason="error")
|
||||
await inputs.claim("admitted", retry=True)
|
||||
await inputs.dispatched("admitted", "admitted-run")
|
||||
# The cleanup must see the old receipt even beyond the API history limit.
|
||||
for index in range(11):
|
||||
run_id = f"later-{index}"
|
||||
await input_store.put(run_id, thread_id="thread", user_id=USER_ID, status="running")
|
||||
await RunInputs(input_store, run_id, USER_ID).submit(f"input-{index}", "later text", "queue")
|
||||
assert await input_store.update_run_completion(run_id, status="success")
|
||||
|
||||
await input_store.put("peer", thread_id="Peer-Thread", user_id=USER_ID, status="running")
|
||||
inflight = stage("peer-thread", "b" * 32)
|
||||
orphan = stage("thread", "c" * 32)
|
||||
fresh = stage("thread", "d" * 32, age=datetime.now(UTC).timestamp())
|
||||
different_owner = stage("thread", retryable.name, owner="other-owner")
|
||||
other_path = stage("thread", "other-directory")
|
||||
await input_store.put("alias", thread_id="Case-Alias", user_id="Alias-Owner", status="running", owner_worker_id="worker")
|
||||
alias = stage("case-alias", "e" * 32, owner="alias-owner")
|
||||
alias_inputs = RunInputs(input_store, "alias", "Alias-Owner", "worker")
|
||||
await alias_inputs.reopen()
|
||||
await alias_inputs.submit("aliased", "Keep this upload", "queue", attachment_stage={"id": alias.name, "files": []})
|
||||
assert await input_store.update_status("alias", "error", stop_reason="error")
|
||||
|
||||
app = SimpleNamespace(state=SimpleNamespace(run_store=input_store))
|
||||
await gateway_app._run_startup_storage_sweeps(app, SimpleNamespace())
|
||||
|
||||
assert not orphan.exists()
|
||||
assert not different_owner.exists()
|
||||
assert not cancelled.exists()
|
||||
for kept in (admitted, retryable, inflight, fresh, other_path, alias):
|
||||
assert (kept / "0").read_bytes() == b"staged bytes"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_startup_sweep_keeps_replacement_at_a_discovered_stage_path(tmp_path, monkeypatch):
|
||||
from app.gateway.run_input_cleanup import cleanup_abandoned_queued_uploads
|
||||
from deerflow.config.paths import Paths
|
||||
|
||||
paths = Paths(tmp_path)
|
||||
stage = paths.thread_dir("thread", user_id=USER_ID) / ".queued-uploads" / ("a" * 32)
|
||||
stage.mkdir(parents=True)
|
||||
old = (datetime.now(UTC) - timedelta(days=7)).timestamp()
|
||||
os.utime(stage, (old, old))
|
||||
store = MemoryRunStore()
|
||||
lookup = store.list_input_runs
|
||||
replaced = False
|
||||
|
||||
async def replace_during_lookup(*args, **kwargs):
|
||||
nonlocal replaced
|
||||
stage.rename(stage.with_name("moved-stage"))
|
||||
stage.mkdir()
|
||||
(stage / "0").write_bytes(b"replacement")
|
||||
os.utime(stage, (old, old))
|
||||
replaced = True
|
||||
return await lookup(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(store, "list_input_runs", replace_during_lookup)
|
||||
assert await cleanup_abandoned_queued_uploads(store, paths) == 0
|
||||
assert replaced
|
||||
assert (stage / "0").read_bytes() == b"replacement"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inputs_preserve_mode_and_retries_without_overwriting_history(input_store):
|
||||
inputs = RunInputs(input_store, "run", USER_ID, "worker")
|
||||
@ -213,6 +311,43 @@ async def test_dispatch_and_remove_serialize_and_recovery_retains_the_same_key(i
|
||||
assert (await inputs.claim("q", retry=True))["run_id"] == "next-run"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_attachment_publication_failure_ignores_a_late_dispatch_receipt(input_store):
|
||||
inputs = RunInputs(input_store, "run", USER_ID, "worker")
|
||||
await inputs.reopen()
|
||||
await inputs.submit("q", "Read this attachment", "queue", attachment_stage={"id": "a" * 32, "files": []})
|
||||
await input_store.update_status("run", "success")
|
||||
await inputs.claim("q")
|
||||
|
||||
await inputs.publication_failed("q", "failed-run", attempt=0)
|
||||
await inputs.dispatched("q", "failed-run")
|
||||
item = (await inputs.read())["items"][0]
|
||||
assert item["status"] == "not_applied"
|
||||
assert "run_id" not in item
|
||||
with pytest.raises(InputConflict):
|
||||
await inputs.begin_attachment_publication("q", "failed-run", attempt=0)
|
||||
|
||||
retry = await inputs.claim("q", retry=True)
|
||||
assert retry["attachment_attempt"] == 1
|
||||
await inputs.dispatched("q", "next-run", attempt=1)
|
||||
await inputs.publication_succeeded("q", "failed-run", attempt=0)
|
||||
await inputs.publication_failed("q", "failed-run", attempt=0)
|
||||
retry = await inputs.claim("q", retry=True)
|
||||
assert retry["run_id"] == "next-run"
|
||||
assert "published" not in retry["attachment_stage"]
|
||||
|
||||
await inputs.begin_attachment_publication("q", "next-run", attempt=1)
|
||||
uncertain = await inputs.publication_failed("q", "next-run", attempt=1, require_unstarted=True)
|
||||
assert uncertain["status"] == "dispatching"
|
||||
assert uncertain["run_id"] == "next-run"
|
||||
|
||||
await inputs.publication_succeeded("q", "next-run", attempt=1)
|
||||
await inputs.publication_failed("q", "next-run", attempt=1)
|
||||
retry = await inputs.claim("q", retry=True)
|
||||
assert retry["run_id"] == "next-run"
|
||||
assert retry["attachment_stage"]["published"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("cancel_at", ["before_snapshot", "while_waiting", "before_claim"])
|
||||
async def test_queue_dispatch_skips_cancelled_input_and_runs_its_successor(input_store, cancel_at, caplog):
|
||||
|
||||
@ -1,7 +1,11 @@
|
||||
import asyncio
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from datetime import timedelta
|
||||
@ -15,11 +19,13 @@ from _router_auth_helpers import call_unwrapped, make_authed_test_app
|
||||
from fastapi import HTTPException, UploadFile
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.gateway import upload_ingestion
|
||||
from app.gateway import run_input_files, upload_ingestion
|
||||
from app.gateway.auth.models import User
|
||||
from app.gateway.deps import get_config
|
||||
from app.gateway.routers import uploads
|
||||
from deerflow.config.paths import Paths
|
||||
from deerflow.sandbox.lease import get_sandbox_lease_manager
|
||||
from deerflow.sandbox.sandbox import CommandOutput
|
||||
from deerflow.uploads.companions import resolve_companion
|
||||
from deerflow.uploads.manager import cleanup_stale_upload_staging_files
|
||||
|
||||
@ -45,6 +51,23 @@ def _mounted_provider() -> MagicMock:
|
||||
return provider
|
||||
|
||||
|
||||
def _remote_upload_sandbox(root: Path) -> MagicMock:
|
||||
sandbox = MagicMock()
|
||||
remote_uploads = root / "uploads"
|
||||
remote_uploads.mkdir(parents=True)
|
||||
sandbox.artifact_root = root.as_posix()
|
||||
sandbox.update_file.side_effect = lambda path, content: (remote_uploads / PurePosixPath(path).name).write_bytes(content)
|
||||
|
||||
def execute(command, *, timeout):
|
||||
interpreter, *args = shlex.split(command)
|
||||
assert interpreter == "python3"
|
||||
result = subprocess.run([sys.executable, *args], check=False, capture_output=True, text=True, timeout=timeout)
|
||||
return CommandOutput(result.stdout + result.stderr, result.returncode)
|
||||
|
||||
sandbox.execute_command.side_effect = execute
|
||||
return sandbox
|
||||
|
||||
|
||||
def _symlink_to_or_skip(link_path: Path, target_path: Path) -> None:
|
||||
try:
|
||||
link_path.symlink_to(target_path)
|
||||
@ -82,6 +105,179 @@ def test_upload_files_writes_thread_storage_and_skips_local_sandbox_sync(tmp_pat
|
||||
provider.release.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(("mounted", "release_error"), [(True, None), (False, None), (False, OSError("lease close failed"))])
|
||||
async def test_queued_upload_companion_stays_valid_after_staging_removal(tmp_path, monkeypatch, mounted, release_error):
|
||||
paths = Paths(tmp_path)
|
||||
monkeypatch.setattr("deerflow.config.paths._paths", paths)
|
||||
provider = _mounted_provider()
|
||||
provider.uses_thread_data_mounts = mounted
|
||||
monkeypatch.setattr(uploads, "get_sandbox_provider", lambda: provider)
|
||||
remote = tmp_path / "remote"
|
||||
sandbox = MagicMock() if mounted else _remote_upload_sandbox(remote)
|
||||
release = AsyncMock(side_effect=release_error)
|
||||
acquire = AsyncMock(return_value=SimpleNamespace(sandbox=sandbox, denied=False, release=release))
|
||||
monkeypatch.setattr(uploads, "try_acquire_sandbox_for_request", acquire)
|
||||
config = SimpleNamespace(uploads={"auto_convert_documents": True})
|
||||
thread_id, user_id = "thread-queue", "user-queue"
|
||||
destination = paths.sandbox_uploads_dir(thread_id, user_id=user_id)
|
||||
attachments = [
|
||||
UploadFile(filename="report.pdf", file=BytesIO(b"%PDF queued upload")),
|
||||
UploadFile(filename="report.md", file=BytesIO(b"# User's notes\n")),
|
||||
]
|
||||
stage_id, files = await run_input_files.stage_input_files(thread_id, user_id, attachments, config)
|
||||
|
||||
async def convert(source, output_path):
|
||||
assert source.suffix == ".pdf"
|
||||
assert source.read_bytes() == b"%PDF queued upload"
|
||||
assert not destination.exists()
|
||||
output_path.write_text("# Converted\n", encoding="utf-8")
|
||||
return output_path
|
||||
|
||||
monkeypatch.setattr(uploads, "convert_file_to_markdown", convert)
|
||||
metadata = await run_input_files.publish_input_files(thread_id, user_id, stage_id, files, request=MagicMock(), config=config)
|
||||
assert [item["filename"] for item in metadata] == ["report.pdf", "report.md"]
|
||||
original = destination / metadata[0]["filename"]
|
||||
assert (destination / "report.md").read_bytes() == b"# User's notes\n"
|
||||
companion = resolve_companion(original)
|
||||
assert companion is not None
|
||||
assert companion.name == "report_1.md"
|
||||
assert companion.read_text(encoding="utf-8") == "# Converted\n"
|
||||
assert list((paths.thread_dir(thread_id, user_id=user_id) / ".queued-uploads").iterdir()) == []
|
||||
if mounted:
|
||||
acquire.assert_not_awaited()
|
||||
sandbox.update_file.assert_not_called()
|
||||
else:
|
||||
acquire.assert_awaited_once()
|
||||
assert sandbox.update_file.call_count == 3
|
||||
assert {path.name: path.read_bytes() for path in (remote / "uploads").iterdir()} == {
|
||||
original.name: b"%PDF queued upload",
|
||||
"report.md": b"# User's notes\n",
|
||||
companion.name: b"# Converted\n",
|
||||
}
|
||||
release.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("failure", ["probe", "copy", "promotion", "lost_ack", "cleanup_unreachable"])
|
||||
async def test_failed_queued_upload_cleans_remote_copies_before_pooling(tmp_path, monkeypatch, failure):
|
||||
paths = Paths(tmp_path)
|
||||
monkeypatch.setattr("deerflow.config.paths._paths", paths)
|
||||
provider = MagicMock()
|
||||
provider.uses_thread_data_mounts = False
|
||||
remote = tmp_path / "remote"
|
||||
sandbox = _remote_upload_sandbox(remote)
|
||||
provider.get.return_value = sandbox
|
||||
monkeypatch.setattr(uploads, "get_sandbox_provider", lambda: provider)
|
||||
config = SimpleNamespace()
|
||||
thread_id, user_id = "thread-queue", "user-queue"
|
||||
destination = paths.sandbox_uploads_dir(thread_id, user_id=user_id)
|
||||
|
||||
async def acquire(*_args, **_kwargs):
|
||||
# Upload-based providers can bootstrap from the host's uploads on acquire.
|
||||
assert not destination.exists()
|
||||
return "remote"
|
||||
|
||||
provider.acquire_async = AsyncMock(side_effect=acquire)
|
||||
attachments = [
|
||||
UploadFile(filename="first 'image'.png", file=BytesIO(b"first attachment")),
|
||||
UploadFile(filename="second.png", file=BytesIO(b"second attachment")),
|
||||
]
|
||||
stage_id, files = await run_input_files.stage_input_files(thread_id, user_id, attachments, config)
|
||||
|
||||
existing = {"older.png": b"earlier upload", "first 'image'.png": b"remote-only file with the same name"}
|
||||
remote_uploads = remote / "uploads"
|
||||
for filename, content in existing.items():
|
||||
(remote_uploads / filename).write_bytes(content)
|
||||
if failure == "promotion":
|
||||
(remote_uploads / "second.png").mkdir()
|
||||
parked = []
|
||||
|
||||
def copy(path, content):
|
||||
resolved = remote_uploads / PurePosixPath(path).name
|
||||
resolved.write_bytes(content)
|
||||
if failure in {"copy", "cleanup_unreachable"} and content == b"second attachment":
|
||||
resolved.write_bytes(b"partial copy")
|
||||
raise OSError("temporary remote transfer failure")
|
||||
|
||||
execute = sandbox.execute_command.side_effect
|
||||
|
||||
def run_command(command, *, timeout):
|
||||
action, *_ = json.loads(shlex.split(command)[-1])
|
||||
if action == "probe":
|
||||
return "Error: python3 not found" if failure == "probe" else execute(command, timeout=timeout)
|
||||
if failure == "cleanup_unreachable":
|
||||
raise OSError("remote cleanup transport unavailable")
|
||||
output = execute(command, timeout=timeout)
|
||||
if action == "promote":
|
||||
if failure == "lost_ack":
|
||||
assert output.exit_code == 0
|
||||
assert (remote_uploads / "first 'image'.png").read_bytes() == b"first attachment"
|
||||
assert execute(command, timeout=timeout).exit_code == 0
|
||||
return "Error: lost remote promotion acknowledgement"
|
||||
if failure == "promotion":
|
||||
assert output.exit_code == 1
|
||||
assert (remote_uploads / "first 'image'.png").read_bytes() == existing["first 'image'.png"]
|
||||
return output
|
||||
|
||||
sandbox.update_file.side_effect = copy
|
||||
sandbox.execute_command.side_effect = run_command
|
||||
provider.release.side_effect = lambda _sandbox_id: parked.append({path.name: path.read_bytes() for path in remote_uploads.iterdir() if path.is_file()})
|
||||
expected_error = {
|
||||
"probe": "does not support queued upload publication with Python 3",
|
||||
"copy": "temporary remote transfer failure",
|
||||
"cleanup_unreachable": "temporary remote transfer failure",
|
||||
}.get(failure, "reconciliation was not acknowledged")
|
||||
with pytest.raises(OSError, match=expected_error):
|
||||
await run_input_files.publish_input_files(thread_id, user_id, stage_id, files, request=None, config=config)
|
||||
|
||||
assert sandbox.update_file.call_count == (0 if failure == "probe" else 2)
|
||||
(pooled_files,) = parked
|
||||
if failure == "cleanup_unreachable":
|
||||
assert sandbox.execute_command.call_count == 3
|
||||
staged = {name: data for name, data in pooled_files.items() if name.startswith(".upload-") and name.endswith(".part")}
|
||||
assert sorted(staged.values()) == [b"first attachment", b"partial copy"]
|
||||
assert {name: data for name, data in pooled_files.items() if name not in staged} == existing
|
||||
else:
|
||||
assert pooled_files == existing
|
||||
assert list(destination.iterdir()) == []
|
||||
stage = paths.thread_dir(thread_id, user_id=user_id) / ".queued-uploads" / stage_id
|
||||
assert [(stage / str(index)).read_bytes() for index in range(2)] == [b"first attachment", b"second attachment"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_queued_upload_retry_preserves_a_file_that_claimed_its_destination(tmp_path, monkeypatch):
|
||||
paths = Paths(tmp_path)
|
||||
monkeypatch.setattr("deerflow.config.paths._paths", paths)
|
||||
monkeypatch.setattr(uploads, "get_sandbox_provider", _mounted_provider)
|
||||
config = SimpleNamespace()
|
||||
thread_id, user_id = "thread-queue", "user-queue"
|
||||
destination = paths.sandbox_uploads_dir(thread_id, user_id=user_id)
|
||||
file = UploadFile(filename="chart.png", file=BytesIO(b"queued image"))
|
||||
stage_id, files = await run_input_files.stage_input_files(thread_id, user_id, [file], config)
|
||||
|
||||
async def fail_during_preparation(published_paths):
|
||||
assert published_paths == [destination / "chart.png"]
|
||||
published_paths[0].unlink()
|
||||
published_paths[0].write_bytes(b"another upload")
|
||||
raise OSError("temporary file preparation failure")
|
||||
|
||||
monkeypatch.setattr(run_input_files, "prepare_published_uploads", fail_during_preparation)
|
||||
|
||||
with pytest.raises(OSError, match="temporary file preparation failure"):
|
||||
await run_input_files.publish_input_files(thread_id, user_id, stage_id, files, request=MagicMock(), config=config)
|
||||
|
||||
original = destination / "chart.png"
|
||||
assert original.read_bytes() == b"another upload"
|
||||
monkeypatch.setattr(run_input_files, "prepare_published_uploads", upload_ingestion.prepare_published_uploads)
|
||||
|
||||
metadata = await run_input_files.publish_input_files(thread_id, user_id, stage_id, files, request=MagicMock(), config=config)
|
||||
|
||||
assert metadata[0]["filename"] == "chart_1.png"
|
||||
assert original.read_bytes() == b"another upload"
|
||||
assert (destination / "chart_1.png").read_bytes() == b"queued image"
|
||||
|
||||
|
||||
def test_upload_and_list_response_models_expose_size_as_int(tmp_path):
|
||||
thread_uploads_dir = tmp_path / "uploads"
|
||||
thread_uploads_dir.mkdir(parents=True)
|
||||
|
||||
@ -189,6 +189,19 @@ data:
|
||||
proxy_request_buffering off;
|
||||
}
|
||||
|
||||
# Allow multipart framing beyond the 100 MiB of queued attachments.
|
||||
location ~ ^/api/threads/[^/]+/runs/[^/]+/inputs$ {
|
||||
proxy_pass http://gateway_upstream;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $forwarded_proto;
|
||||
client_max_body_size 101M;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 600s;
|
||||
}
|
||||
|
||||
# Project documents — multipart upload plus the promote/attach/content/
|
||||
# delete routes. Without its own location the upload fell through to
|
||||
# /api/ and nginx's 1m default returned 413 before Gateway saw it,
|
||||
|
||||
@ -212,7 +212,7 @@ http {
|
||||
|
||||
}
|
||||
|
||||
# Custom API: Uploads endpoint
|
||||
# Thread uploads
|
||||
location ~ ^/api/threads/[^/]+/uploads {
|
||||
proxy_pass http://$gateway_upstream;
|
||||
proxy_http_version 1.1;
|
||||
@ -230,6 +230,20 @@ http {
|
||||
# Disable response buffering to avoid permission errors
|
||||
}
|
||||
|
||||
# Allow multipart framing beyond the 100 MiB of queued attachments.
|
||||
location ~ ^/api/threads/[^/]+/runs/[^/]+/inputs$ {
|
||||
proxy_pass http://$gateway_upstream;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $forwarded_proto;
|
||||
|
||||
client_max_body_size 101M;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 600s;
|
||||
}
|
||||
|
||||
# Custom API: Project documents (multipart upload, promote-from-thread,
|
||||
# attach-to-thread, content download, delete). Without its own location
|
||||
# the upload fell through to /api/ and nginx's 1m default rejected
|
||||
|
||||
@ -224,7 +224,7 @@ http {
|
||||
proxy_cache off;
|
||||
}
|
||||
|
||||
# Custom API: Uploads endpoint
|
||||
# Thread uploads
|
||||
location ~ ^/api/threads/[^/]+/uploads {
|
||||
proxy_pass http://gateway;
|
||||
proxy_http_version 1.1;
|
||||
@ -244,6 +244,23 @@ http {
|
||||
proxy_cache off;
|
||||
}
|
||||
|
||||
# Allow multipart framing beyond the 100 MiB of queued attachments.
|
||||
location ~ ^/api/threads/[^/]+/runs/[^/]+/inputs$ {
|
||||
proxy_pass http://gateway;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
client_max_body_size 101M;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 600s;
|
||||
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
}
|
||||
|
||||
# Custom API: Project documents (multipart upload, promote-from-thread,
|
||||
# attach-to-thread, content download, delete). Without its own location
|
||||
# the upload fell through to /api/ and nginx's 1m default rejected
|
||||
|
||||
@ -306,6 +306,12 @@ rolling upgrade, route keyed runs with ID-less input and their retries to
|
||||
upgraded workers until all Gateway workers are upgraded; older workers may
|
||||
reject those retries with 409. See the [run API contract](../../backend/docs/API.md#create-run).
|
||||
|
||||
During a rolling upgrade, route multipart Queue submissions and their retry
|
||||
and remove requests to upgraded Gateways. Only a run owned by a worker that
|
||||
supports queued attachments can accept them. Older Gateways handle queue items
|
||||
as plain text, so finish or remove items with attachments before rolling back.
|
||||
See [queued input](../../backend/docs/API.md#submit-an-input-while-a-web-run-is-active).
|
||||
|
||||
### Redis checkpoint history cache upgrade
|
||||
|
||||
The v2 cache rebuilds histories under a new default prefix. Deleting or pruning
|
||||
|
||||
@ -36,13 +36,17 @@ Signed-in users' notification toggle, default model, conversation mode, and reas
|
||||
In a new chat, the submitted question stays above its streamed reasoning and
|
||||
tool steps while the server creates the conversation and confirms the message.
|
||||
|
||||
While a Web task is running, choose **Queue** to send text for the next turn or
|
||||
**Steer** to update the current work. Native subagents pause at a safe boundary
|
||||
While a Web task is running, choose **Queue** to send a message for the next turn or
|
||||
**Steer** to update the current work with text. A queued Web chat message can include
|
||||
uploaded files. The queue shows their names and makes them available when that
|
||||
message's run starts, keeping the original names when available. If publication
|
||||
fails, **Send again** reuses the staged files. Removing the message discards them.
|
||||
Managed worker updates accept text only. Native subagents pause at a safe boundary
|
||||
while the main Agent handles the update; active tool calls finish first. Stop
|
||||
keeps the Goal, while explicitly replacing the work can clear it. Unapplied
|
||||
messages survive database-backed Gateway restarts and require **Send again**;
|
||||
interrupted child side effects are not replayed automatically. Existing execution
|
||||
limits still apply. Busy input currently accepts text only.
|
||||
limits still apply.
|
||||
If a run rejects an update because it has finished, retrying the retained draft
|
||||
during the next run targets that run. Uncertain network failures retain the
|
||||
original submission identity so retries can reconcile the same accepted input.
|
||||
|
||||
@ -420,7 +420,11 @@ export function InputBox({
|
||||
options?: InputBoxSubmitOptions,
|
||||
) => void | Promise<void>;
|
||||
onStop?: () => void;
|
||||
onBusySubmit?: (text: string, mode: RunInputMode) => Promise<unknown>;
|
||||
onBusySubmit?: (
|
||||
text: string,
|
||||
mode: RunInputMode,
|
||||
files: File[],
|
||||
) => Promise<unknown>;
|
||||
/**
|
||||
* Whether the caller's role holds `runs:cancel` (RFC #4063 Phase 4).
|
||||
* Defaults to true so callers that don't resolve permissions (pre-Phase-4
|
||||
@ -1668,22 +1672,42 @@ export function InputBox({
|
||||
if (runInputInFlight.current)
|
||||
return Promise.reject(new Error("input-in-flight"));
|
||||
if (
|
||||
!message.text.trim() ||
|
||||
message.files.length ||
|
||||
projectAttachments.length ||
|
||||
conversationReferences.length ||
|
||||
inlineRefs.length ||
|
||||
(sidecar?.conversationQuotes.length ?? 0) ||
|
||||
message.text.trimStart().startsWith("/")
|
||||
) {
|
||||
toast.info(t.inputBox.runInputUnsupported);
|
||||
return Promise.reject(new Error("busy-input-unsupported"));
|
||||
}
|
||||
if (
|
||||
runInputMode === "steer" &&
|
||||
(!message.text.trim() || message.files.length)
|
||||
) {
|
||||
toast.info(t.inputBox.runInputTextOnly);
|
||||
return Promise.reject(new Error("text-input-required"));
|
||||
}
|
||||
const files = message.files.flatMap(({ file }) =>
|
||||
file instanceof File ? [file] : [],
|
||||
);
|
||||
if (files.length !== message.files.length) {
|
||||
toast.error(t.uploads.notReady);
|
||||
return Promise.reject(new Error("Attachments not ready."));
|
||||
}
|
||||
if (!files.length && !message.text.trim()) {
|
||||
return Promise.reject(new Error("empty-input"));
|
||||
}
|
||||
const { violations } = validateUploadLimits([], files, uploadLimits);
|
||||
if (violations.length) {
|
||||
reportUploadLimitViolations(violations);
|
||||
return Promise.reject(new Error("Attachment limits exceeded."));
|
||||
}
|
||||
abortVoiceInput();
|
||||
runInputInFlight.current = true;
|
||||
setRunInputSending(true);
|
||||
try {
|
||||
await onBusySubmit(message.text, runInputMode);
|
||||
await onBusySubmit(message.text, runInputMode, files);
|
||||
return;
|
||||
} finally {
|
||||
runInputInFlight.current = false;
|
||||
@ -1806,13 +1830,17 @@ export function InputBox({
|
||||
projectAttachments.length,
|
||||
conversationReferences.length,
|
||||
inlineRefs.length,
|
||||
reportUploadLimitViolations,
|
||||
sidecar?.conversationQuotes.length,
|
||||
status,
|
||||
submitThreadMessage,
|
||||
t.inputBox.goalTooLong,
|
||||
t.inputBox.pleaseWaitStreaming,
|
||||
t.inputBox.runInputTextOnly,
|
||||
t.inputBox.runInputUnsupported,
|
||||
t.inputBox.startTurnUnavailable,
|
||||
t.uploads.notReady,
|
||||
uploadLimits,
|
||||
],
|
||||
);
|
||||
|
||||
@ -3580,7 +3608,10 @@ export function InputBox({
|
||||
variant="outline"
|
||||
status={runInputSending ? "submitted" : "ready"}
|
||||
disabled={
|
||||
composerLocked || voiceListening || !textInput.value.trim()
|
||||
composerLocked ||
|
||||
voiceListening ||
|
||||
(!textInput.value.trim() &&
|
||||
(runInputMode !== "queue" || !attachmentParts.length))
|
||||
}
|
||||
/>
|
||||
</>
|
||||
|
||||
@ -14,6 +14,9 @@ import {
|
||||
type RunInput,
|
||||
} from "@/core/threads/run-inputs";
|
||||
|
||||
import { FileName } from "./file-name";
|
||||
import { FileTypeIcon } from "./file-type-icon";
|
||||
|
||||
export function ThreadRunInputs({
|
||||
threadId,
|
||||
isRunning,
|
||||
@ -84,9 +87,26 @@ export function ThreadRunInputs({
|
||||
? t.inputBox.runInputQueued
|
||||
: t.inputBox.runInputSteering}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate" title={input.text}>
|
||||
{input.text}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
{input.text && (
|
||||
<p className="truncate" title={input.text}>
|
||||
{input.text}
|
||||
</p>
|
||||
)}
|
||||
{!!input.files?.length && (
|
||||
<ul className="flex flex-wrap gap-1">
|
||||
{input.files.map((file, index) => (
|
||||
<li
|
||||
key={`${file.filename}:${index}`}
|
||||
className="flex max-w-full min-w-0 items-center gap-1 rounded-md border px-1 py-0.5"
|
||||
>
|
||||
<FileTypeIcon filename={file.filename} compact />
|
||||
<FileName filename={file.filename} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
{!isRunning && canCreate && (
|
||||
<Button
|
||||
size="icon-sm"
|
||||
|
||||
@ -812,7 +812,9 @@ export const enUS: Translations = {
|
||||
steerModeHelp: "Adjust the current task at the next available point",
|
||||
runInputSend: "Send update",
|
||||
runInputTextOnly:
|
||||
"Send plain text while a task is running. Attachments and slash commands can be sent when it finishes.",
|
||||
"Use plain text to steer. Choose Queue to send attachments.",
|
||||
runInputUnsupported:
|
||||
"Send references and slash commands after the current task finishes.",
|
||||
runInputUnavailable:
|
||||
"The message was not confirmed. Check the task status and try again; your draft is kept.",
|
||||
stopRun: "Stop current task",
|
||||
|
||||
@ -662,6 +662,7 @@ export interface Translations {
|
||||
steerModeHelp: string;
|
||||
runInputSend: string;
|
||||
runInputTextOnly: string;
|
||||
runInputUnsupported: string;
|
||||
runInputUnavailable: string;
|
||||
stopRun: string;
|
||||
runInputQueued: string;
|
||||
|
||||
@ -762,8 +762,8 @@ export const zhCN: Translations = {
|
||||
queueModeHelp: "当前任务结束后再执行",
|
||||
steerModeHelp: "在下一处可处理的位置调整当前任务",
|
||||
runInputSend: "发送补充消息",
|
||||
runInputTextOnly:
|
||||
"运行中请发送纯文字,附件和斜杠命令请等当前任务结束后发送。",
|
||||
runInputTextOnly: "调整当前任务时请发送纯文字。发送附件请选择排队执行。",
|
||||
runInputUnsupported: "请等当前任务结束后再发送引用和斜杠命令。",
|
||||
runInputUnavailable:
|
||||
"尚未确认消息是否送达,请检查任务状态后重试,输入内容已保留。",
|
||||
stopRun: "停止当前任务",
|
||||
|
||||
@ -2675,6 +2675,7 @@ export function useThreadStream({
|
||||
runId: string;
|
||||
text: string;
|
||||
mode: RunInputMode;
|
||||
files: File[];
|
||||
id: string;
|
||||
context?: Record<string, unknown>;
|
||||
} | null>(null);
|
||||
@ -2687,7 +2688,7 @@ export function useThreadStream({
|
||||
[onStreamThreadId, runInputAccount],
|
||||
);
|
||||
const sendInput = useCallback(
|
||||
async (text: string, mode: RunInputMode) => {
|
||||
async (text: string, mode: RunInputMode, files: File[] = []) => {
|
||||
const targetThread = onStreamThreadId;
|
||||
const runId = inputQuery.data?.active_run_id;
|
||||
if (!targetThread || !runId)
|
||||
@ -2696,13 +2697,16 @@ export function useThreadStream({
|
||||
const attempt =
|
||||
previous?.threadId === targetThread &&
|
||||
previous.text === text &&
|
||||
previous.mode === mode
|
||||
previous.mode === mode &&
|
||||
previous.files.length === files.length &&
|
||||
previous.files.every((file, index) => file === files[index])
|
||||
? previous
|
||||
: {
|
||||
threadId: targetThread,
|
||||
runId,
|
||||
text,
|
||||
mode,
|
||||
files,
|
||||
id: uuid(),
|
||||
context:
|
||||
mode === "queue"
|
||||
@ -2725,6 +2729,7 @@ export function useThreadStream({
|
||||
text,
|
||||
mode,
|
||||
context: attempt.context,
|
||||
files: attempt.files,
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (controller.signal.aborted)
|
||||
|
||||
@ -10,6 +10,9 @@ export const runInputSchema = z.object({
|
||||
target_run_id: z.string(),
|
||||
message_id: z.string(),
|
||||
text: z.string(),
|
||||
files: z
|
||||
.array(z.object({ filename: z.string(), size: z.number() }))
|
||||
.optional(),
|
||||
mode: z.enum(["queue", "steer"]),
|
||||
status: z.enum([
|
||||
"pending",
|
||||
@ -60,6 +63,7 @@ export async function submitRunInput({
|
||||
text,
|
||||
mode,
|
||||
context,
|
||||
files = [],
|
||||
signal,
|
||||
}: {
|
||||
threadId: string;
|
||||
@ -68,19 +72,32 @@ export async function submitRunInput({
|
||||
text: string;
|
||||
mode: RunInputMode;
|
||||
context?: Record<string, unknown>;
|
||||
files?: File[];
|
||||
signal?: AbortSignal;
|
||||
}) {
|
||||
const input = JSON.stringify({
|
||||
request_id: requestId,
|
||||
text,
|
||||
mode,
|
||||
context: context ?? {},
|
||||
});
|
||||
let body: BodyInit = input;
|
||||
if (files.length) {
|
||||
const form = new FormData();
|
||||
form.set("input", input);
|
||||
for (const file of files) {
|
||||
form.append("files", file);
|
||||
}
|
||||
body = form;
|
||||
}
|
||||
const response = await fetch(
|
||||
`${getBackendBaseURL()}/api/threads/${encodeURIComponent(threadId)}/runs/${encodeURIComponent(runId)}/inputs`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
request_id: requestId,
|
||||
text,
|
||||
mode,
|
||||
context: context ?? {},
|
||||
}),
|
||||
headers: files.length
|
||||
? undefined
|
||||
: { "Content-Type": "application/json" },
|
||||
body,
|
||||
signal,
|
||||
},
|
||||
);
|
||||
|
||||
@ -12,10 +12,26 @@ type SubmittedInput = {
|
||||
mode: "queue" | "steer";
|
||||
};
|
||||
|
||||
for (const mode of ["queue", "steer"] as const) {
|
||||
test(`${mode} retries a rejected draft against the new active run`, async ({
|
||||
for (const scenario of [
|
||||
"queue",
|
||||
"steer",
|
||||
"queue with an attachment",
|
||||
] as const) {
|
||||
test(`${scenario} retries a rejected draft against the new active run`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const mode = scenario === "steer" ? "steer" : "queue";
|
||||
const screenshot =
|
||||
scenario === "queue with an attachment"
|
||||
? {
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
buffer: Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aXioAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
),
|
||||
}
|
||||
: undefined;
|
||||
let activeRunId = RUN_A;
|
||||
let acceptedInput: Record<string, unknown> | undefined;
|
||||
const submissions: Array<SubmittedInput & { runId: string }> = [];
|
||||
@ -81,11 +97,27 @@ for (const mode of ["queue", "steer"] as const) {
|
||||
);
|
||||
await page.route(
|
||||
`**/api/threads/${MOCK_THREAD_ID}/runs/*/inputs`,
|
||||
(route) => {
|
||||
async (route) => {
|
||||
const runId = new URL(route.request().url()).pathname
|
||||
.split("/")
|
||||
.at(-2)!;
|
||||
const body = route.request().postDataJSON() as SubmittedInput;
|
||||
const request = route.request();
|
||||
let body: SubmittedInput;
|
||||
if (screenshot) {
|
||||
const form = await new Response(
|
||||
new Uint8Array(request.postDataBuffer()!),
|
||||
{ headers: { "Content-Type": request.headers()["content-type"]! } },
|
||||
).formData();
|
||||
body = JSON.parse(form.get("input") as string) as SubmittedInput;
|
||||
const files = form.getAll("files") as File[];
|
||||
expect(files).toHaveLength(1);
|
||||
expect(files[0]!.name).toBe(screenshot.name);
|
||||
expect(Buffer.from(await files[0]!.arrayBuffer())).toEqual(
|
||||
screenshot.buffer,
|
||||
);
|
||||
} else {
|
||||
body = request.postDataJSON() as SubmittedInput;
|
||||
}
|
||||
submissions.push({ ...body, runId });
|
||||
if (runId === RUN_A) {
|
||||
return route.fulfill({
|
||||
@ -102,6 +134,13 @@ for (const mode of ["queue", "steer"] as const) {
|
||||
message_id: "human-update",
|
||||
text: body.text,
|
||||
mode: body.mode,
|
||||
...(screenshot
|
||||
? {
|
||||
files: [
|
||||
{ filename: screenshot.name, size: screenshot.buffer.length },
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
status: "pending",
|
||||
created_at: "2026-01-01T00:00:01Z",
|
||||
};
|
||||
@ -127,6 +166,20 @@ for (const mode of ["queue", "steer"] as const) {
|
||||
const textarea = page.getByPlaceholder(/how can i assist you/i);
|
||||
const send = page.getByRole("button", { name: "Send update" });
|
||||
await textarea.fill(INPUT_TEXT);
|
||||
if (screenshot) {
|
||||
await page.locator('input[type="file"]').setInputFiles(screenshot);
|
||||
await page.getByRole("button", { name: "Send while working" }).click();
|
||||
await page.getByRole("menuitem", { name: /^Steer/ }).click();
|
||||
await send.click();
|
||||
await expect(
|
||||
page.getByText(
|
||||
"Use plain text to steer. Choose Queue to send attachments.",
|
||||
),
|
||||
).toBeVisible();
|
||||
expect(submissions).toHaveLength(0);
|
||||
await page.getByRole("button", { name: "Send while working" }).click();
|
||||
await page.getByRole("menuitem", { name: /^Queue/ }).click();
|
||||
}
|
||||
if (mode === "steer") {
|
||||
await page.getByRole("button", { name: "Send while working" }).click();
|
||||
await page.getByRole("menuitem", { name: /^Steer/ }).click();
|
||||
@ -138,6 +191,13 @@ for (const mode of ["queue", "steer"] as const) {
|
||||
),
|
||||
).toBeVisible();
|
||||
await expect(textarea).toHaveValue(INPUT_TEXT);
|
||||
if (screenshot) {
|
||||
await expect(
|
||||
page.getByRole("button", {
|
||||
name: `Remove attachment: ${screenshot.name}`,
|
||||
}),
|
||||
).toBeVisible();
|
||||
}
|
||||
expect(submissions).toHaveLength(1);
|
||||
expect(submissions[0]).toMatchObject({
|
||||
runId: RUN_A,
|
||||
@ -160,6 +220,11 @@ for (const mode of ["queue", "steer"] as const) {
|
||||
await expect(
|
||||
page.getByTestId("run-inputs").getByText(INPUT_TEXT),
|
||||
).toBeVisible();
|
||||
if (screenshot) {
|
||||
await expect(
|
||||
page.getByTestId("run-inputs").getByTitle(screenshot.name),
|
||||
).toBeVisible();
|
||||
}
|
||||
} finally {
|
||||
await Promise.all([...streams.keys()].map(finishStream));
|
||||
}
|
||||
|
||||
@ -51,7 +51,11 @@ function renderComposer({
|
||||
}: {
|
||||
canStopStreaming?: boolean;
|
||||
onStop: () => void;
|
||||
onBusySubmit?: (text: string, mode: "queue" | "steer") => Promise<unknown>;
|
||||
onBusySubmit?: (
|
||||
text: string,
|
||||
mode: "queue" | "steer",
|
||||
files: File[],
|
||||
) => Promise<unknown>;
|
||||
canCreateRuns?: boolean;
|
||||
}) {
|
||||
const queryClient = new QueryClient({
|
||||
@ -97,6 +101,43 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("InputBox stop gating (runs:cancel)", () => {
|
||||
it("queues a file-only draft and keeps the file if the send fails", async () => {
|
||||
rs.spyOn(URL, "createObjectURL").mockReturnValue("blob:attachment");
|
||||
rs.spyOn(URL, "revokeObjectURL").mockImplementation(() => undefined);
|
||||
const onBusySubmit = rs
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error("offline"))
|
||||
.mockResolvedValueOnce({});
|
||||
const { container } = renderComposer({ onStop: rs.fn(), onBusySubmit });
|
||||
const file = new File(["test"], "screenshot.png", { type: "image/png" });
|
||||
fireEvent.change(container.querySelector('input[type="file"]')!, {
|
||||
target: { files: [file] },
|
||||
});
|
||||
|
||||
const send = screen.getByRole("button", { name: "Send update" });
|
||||
expect(send).toHaveProperty("disabled", false);
|
||||
fireEvent.click(send);
|
||||
await waitFor(() =>
|
||||
expect(onBusySubmit).toHaveBeenNthCalledWith(1, "", "queue", [file]),
|
||||
);
|
||||
await waitFor(() => expect(send).toHaveProperty("disabled", false));
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Remove attachment: screenshot.png" }),
|
||||
).toBeTruthy();
|
||||
|
||||
fireEvent.click(send);
|
||||
await waitFor(() =>
|
||||
expect(onBusySubmit).toHaveBeenNthCalledWith(2, "", "queue", [file]),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.queryByRole("button", {
|
||||
name: "Remove attachment: screenshot.png",
|
||||
}),
|
||||
).toBeNull(),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps update sending separate from Stop and preserves a rejected draft", async () => {
|
||||
const onStop = rs.fn();
|
||||
const onBusySubmit = rs
|
||||
@ -108,7 +149,7 @@ describe("InputBox stop gating (runs:cancel)", () => {
|
||||
fireEvent.change(input, { target: { value: "Include 2025" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send update" }));
|
||||
await waitFor(() =>
|
||||
expect(onBusySubmit).toHaveBeenCalledWith("Include 2025", "queue"),
|
||||
expect(onBusySubmit).toHaveBeenCalledWith("Include 2025", "queue", []),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
|
||||
@ -44,6 +44,7 @@ type SubmittedInput = {
|
||||
mode: RunInputMode;
|
||||
context: Record<string, unknown>;
|
||||
};
|
||||
files?: File[];
|
||||
};
|
||||
|
||||
const queryClients: QueryClient[] = [];
|
||||
@ -64,7 +65,7 @@ function jsonResponse(body: unknown, status = 200) {
|
||||
});
|
||||
}
|
||||
|
||||
function receiptFor({ runId, body }: SubmittedInput): RunInput {
|
||||
function receiptFor({ runId, body, files }: SubmittedInput): RunInput {
|
||||
return {
|
||||
id: body.request_id,
|
||||
target_run_id: runId,
|
||||
@ -73,6 +74,9 @@ function receiptFor({ runId, body }: SubmittedInput): RunInput {
|
||||
mode: body.mode,
|
||||
status: "pending",
|
||||
created_at: "2026-11-02T00:00:00Z",
|
||||
...(files?.length
|
||||
? { files: files.map(({ name: filename, size }) => ({ filename, size })) }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
@ -185,12 +189,15 @@ beforeEach(() => {
|
||||
);
|
||||
if (match && init?.method === "POST") {
|
||||
expect(init.credentials).toBe("include");
|
||||
if (typeof init.body !== "string") {
|
||||
throw new Error("Expected a JSON run-input request body");
|
||||
}
|
||||
const form = init.body instanceof FormData ? init.body : undefined;
|
||||
const input = form ? form.get("input") : init.body;
|
||||
if (typeof input !== "string") throw new Error("Missing run input");
|
||||
if (form)
|
||||
expect(new Headers(init.headers).get("Content-Type")).toBeNull();
|
||||
const submission: SubmittedInput = {
|
||||
runId: match[1]!,
|
||||
body: JSON.parse(init.body) as SubmittedInput["body"],
|
||||
body: JSON.parse(input) as SubmittedInput["body"],
|
||||
...(form ? { files: form.getAll("files") as File[] } : {}),
|
||||
};
|
||||
submittedInputs.push(submission);
|
||||
const receipt = receiptFor(submission);
|
||||
@ -309,3 +316,55 @@ test("recovers an accepted input when the POST response was lost", async () => {
|
||||
expect(submittedInputs).toHaveLength(1);
|
||||
expect(receipts[0]?.id).toBe(submittedInputs[0]?.body.request_id);
|
||||
});
|
||||
|
||||
test("keeps the attachment and request ID after a lost queue submission", async () => {
|
||||
firstPostFailure = "network";
|
||||
const { result, queryClient } = await renderThread();
|
||||
const screenshot = new File(["image"], "screenshot.png", {
|
||||
type: "image/png",
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await expect(
|
||||
result.current.sendInput("See screenshot", "queue", [screenshot]),
|
||||
).rejects.toThrow("Failed to fetch");
|
||||
});
|
||||
await advanceToNextRun(queryClient);
|
||||
await act(async () => {
|
||||
await expect(
|
||||
result.current.sendInput("See screenshot", "queue", [screenshot]),
|
||||
).resolves.toMatchObject({
|
||||
target_run_id: "run-1",
|
||||
files: [{ filename: screenshot.name, size: screenshot.size }],
|
||||
});
|
||||
});
|
||||
|
||||
expect(submittedInputs).toHaveLength(2);
|
||||
expect(submittedInputs[0]?.files).toEqual([screenshot]);
|
||||
expect(submittedInputs[1]).toEqual(submittedInputs[0]);
|
||||
});
|
||||
|
||||
test("uses a fresh request ID when the attachment changes", async () => {
|
||||
firstPostFailure = "network";
|
||||
const { result, queryClient } = await renderThread();
|
||||
const first = new File(["one"], "screenshot.png", { type: "image/png" });
|
||||
const replacement = new File(["two"], "screenshot.png", {
|
||||
type: "image/png",
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await expect(
|
||||
result.current.sendInput("", "queue", [first]),
|
||||
).rejects.toThrow("Failed to fetch");
|
||||
});
|
||||
await advanceToNextRun(queryClient);
|
||||
await act(async () => {
|
||||
await result.current.sendInput("", "queue", [replacement]);
|
||||
});
|
||||
|
||||
expect(submittedInputs[1]?.files).toEqual([replacement]);
|
||||
expect(submittedInputs[1]?.body.request_id).not.toBe(
|
||||
submittedInputs[0]?.body.request_id,
|
||||
);
|
||||
expect(submittedInputs[1]?.runId).toBe("run-2");
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user