diff --git a/README.md b/README.md index 6e0075c77dc..89457a7efef 100644 --- a/README.md +++ b/README.md @@ -123,6 +123,7 @@ Each guide is the full reference for its topic. Open the one you need. | Feishu, Slack, Telegram, Discord, DingTalk and other IM channels | [IM Channels](docs/guide/im-channels.md) | | File attachments, downloads and Office previews | [File Previews](docs/guide/file-previews.md) | | Token usage dashboard, workspace, chat archive | [Workspace UI](docs/guide/workspace.md) | +| Incognito chats | [Incognito Chats](docs/guide/incognito-chats.md) | | Terminal workbench | [Terminal Workbench (TUI)](docs/guide/tui.md) | | Personal access tokens, stream actions, embedded Python client | [API Access and Python Client](docs/guide/api-and-client.md) | | Trace correlation, LangSmith, Langfuse, Monocle | [Tracing and Observability](docs/guide/observability.md) | diff --git a/backend/app/gateway/app.py b/backend/app/gateway/app.py index 835ebb0c679..18173ad06b1 100644 --- a/backend/app/gateway/app.py +++ b/backend/app/gateway/app.py @@ -400,6 +400,21 @@ async def _shutdown_startup_trash_sweep(app: FastAPI) -> None: logger.exception("Startup trash sweep failed during shutdown") +async def _shutdown_incognito_sweep(app: FastAPI) -> None: + """Stop the incognito lifetime sweep before the runtime is torn down. + + A purge interrupted mid-flight leaves its tombstone and past deadline in + place, so the next Gateway start retries it; cancellation never resurrects + a thread or leaves one readable. + """ + task = getattr(app.state, "incognito_sweep_task", None) + if task is None or task.done(): + return + task.cancel() + with suppress(asyncio.CancelledError): + await task + + async def _shutdown_scheduled_task_service(app: FastAPI) -> None: """Bound scheduler stop so a stuck poll cannot block Gateway exit. @@ -760,6 +775,14 @@ async def _gateway_lifespan(app: FastAPI) -> AsyncGenerator[None, None]: # 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)) + # Incognito lifetime: tombstone then purge each thread whose deadline + # passed. Started regardless of ``incognito.enabled`` — the switch only + # stops new incognito threads, and threads created before an operator + # flipped it must still disappear on schedule. + from app.gateway.incognito import run_incognito_sweep_loop + + app.state.incognito_sweep_task = asyncio.create_task(run_incognito_sweep_loop(app)) + # Best-effort per-document summary generation. # Workers start only when projects.summaries_enabled is true; the # write routes' enqueue is a no-op otherwise. Needs the session @@ -947,6 +970,7 @@ async def _gateway_lifespan(app: FastAPI) -> AsyncGenerator[None, None]: yield await _shutdown_startup_trash_sweep(app) + await _shutdown_incognito_sweep(app) try: from deerflow.projects.summaries import get_summary_generator, reset_summary_generator diff --git a/backend/app/gateway/conversation_access.py b/backend/app/gateway/conversation_access.py index 7aadc333b05..7aec87340de 100644 --- a/backend/app/gateway/conversation_access.py +++ b/backend/app/gateway/conversation_access.py @@ -241,15 +241,17 @@ def json_room(thread_id: str) -> int | None: async def owned_scan(thread_id: str, **scan: Any) -> tuple[list[dict], bool] | None: """Scan the visible rows of an owned source; ``None`` when it is unavailable.""" try: - # Strict ownership deliberately excludes legacy shared/unowned rows. + # Strict ownership deliberately excludes legacy shared/unowned rows, + # and an incognito source is never referencable: its transcript must + # not be copied into another thread's context. source = await thread_store.get(thread_id, user_id=user_id) - if source is None or source.get("user_id") != user_id: + if source is None or source.get("user_id") != user_id or source.get("incognito") is True: return None rows, has_more = await read_visible_message_page(event_store=event_store, run_manager=run_manager, thread_id=thread_id, user_id=user_id, **scan) # Recheck ownership after storage yields (including deletion during # a read); a stale local event feed must not reopen a deleted source. source = await thread_store.get(thread_id, user_id=user_id) - if source is None or source.get("user_id") != user_id: + if source is None or source.get("user_id") != user_id or source.get("incognito") is True: return None except Exception: logger.warning("Unable to read referenced conversation history", exc_info=True) diff --git a/backend/app/gateway/deps.py b/backend/app/gateway/deps.py index 989d4cee387..9a6b4d91f6c 100644 --- a/backend/app/gateway/deps.py +++ b/backend/app/gateway/deps.py @@ -23,6 +23,7 @@ import tempfile from collections.abc import AsyncGenerator, Callable from contextlib import AsyncExitStack, asynccontextmanager +from datetime import timedelta from pathlib import Path from typing import TYPE_CHECKING, Any, TypeVar, cast @@ -36,7 +37,9 @@ from deerflow.config.credentials_key import CREDENTIALS_KEY_ENV_VAR, CREDENTIALS_KEY_FILENAME, GENERATE_KEY_COMMAND, CredentialsKeyError, parse_credentials_keys from deerflow.config.deployment_config import multi_instance_declaration from deerflow.persistence.feedback import FeedbackRepository -from deerflow.runtime import ORPHAN_RECOVERY_STOP_REASON, STARTUP_ORPHAN_RECOVERY_ERROR, RunContext, RunManager, StreamBridge +from deerflow.persistence.thread_meta import is_incognito_expired +from deerflow.runtime import ORPHAN_RECOVERY_STOP_REASON, STARTUP_ORPHAN_RECOVERY_ERROR, RunAdmissionRejected, RunContext, RunManager, StreamBridge +from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY from deerflow.runtime.events.store.base import RunEventStore from deerflow.runtime.runs.store.base import RunStore from deerflow.utils.file_io import await_drained @@ -1236,10 +1239,67 @@ def get_subagent_batch_service(request: Request): return val -def _run_admission_hook(*, checkpointer: Any): - """Prune metadata leaves inside the run's durable admission fence.""" +def _run_admission_hook(*, checkpointer: Any, thread_store: Any | None = None, app_config: Any | None = None): + """Re-verify the incognito verdict, then prune metadata leaves and renew. + + ``start_run`` pins the verdict before durable admission, but the row can + change before the worker starts: another Gateway process may sweep an + expired thread or delete it. A pinned ``True`` is therefore rechecked + against the live row, and an unreadable store raises + :class:`RunAdmissionRejected` instead of silently running as an ordinary + conversation and writing memory or shared blobs. A caller that reaches the + worker without the pre-check (an embedded host) gets its first read here. + """ async def handle(record: Any, config: dict[str, Any]) -> None: + context = config.get("context") + if not isinstance(context, dict): + context = None + verdict = context.get(INCOGNITO_CONTEXT_KEY) if context is not None else None + if thread_store is not None and app_config is not None and (verdict is None or verdict is True): + try: + thread = await thread_store.get(record.thread_id, user_id=None) + except Exception as exc: + logger.warning( + "Incognito admission lookup failed for thread %s (fatal)", + record.thread_id, + exc_info=True, + ) + raise RunAdmissionRejected("Unable to verify the thread's incognito state") from exc + if verdict is None: + if thread is not None and thread.get("incognito") is True: + if is_incognito_expired(thread): + raise RunAdmissionRejected("This incognito thread has expired") + verdict = True + else: + verdict = False + if context is None: + context = {} + config["context"] = context + context[INCOGNITO_CONTEXT_KEY] = verdict + elif thread is None or thread.get("incognito") is not True: + # The pinned verdict is a hint, not proof. If the row is gone + # (another process deleted it) or was recreated as an ordinary + # thread, fail closed rather than start an incognito run whose + # policy no longer matches the stored thread. + raise RunAdmissionRejected("This incognito thread is no longer available") + elif is_incognito_expired(thread): + # The sweep writes the tombstone before purging; a run that was + # admitted before the race must not execute afterwards and + # recreate content that no later sweep will select. + raise RunAdmissionRejected("This incognito thread has expired") + if verdict is True: + # Renewal is activity, not the verdict: a failed renewal keeps + # the old deadline and never turns the run ordinary. + try: + await thread_store.renew_incognito( + record.thread_id, + idle_ttl=timedelta(seconds=app_config.incognito.idle_ttl_seconds), + max_lifetime=timedelta(seconds=app_config.incognito.max_lifetime_seconds), + user_id=None, + ) + except Exception: + logger.warning("Incognito admission renewal failed for thread %s (non-fatal)", record.thread_id, exc_info=True) try: from app.gateway.checkpoint_retention import enforce_completed_run_retention @@ -1272,7 +1332,7 @@ def _selected_checkpoint_ids(config: dict[str, Any]) -> frozenset[str]: return frozenset(selected) -def _run_completion_hook(*, scheduled_task_service: Any | None, batch_continuations: Any | None = None): +def _run_completion_hook(*, scheduled_task_service: Any | None, batch_continuations: Any | None = None, thread_store: Any | None = None, app_config: Any | None = None): """Notify the scheduler after ordinary run finalization.""" async def handle(record: Any) -> None: @@ -1284,6 +1344,19 @@ async def handle(record: Any) -> None: await scheduled_task_service.handle_run_completion(record) except Exception: logger.warning("Scheduled task completion hook failed for run %s (non-fatal)", record.run_id, exc_info=True) + # Finishing a turn is activity: an incognito thread's idle deadline is + # measured from it. The store no-ops for every other thread and for an + # incognito thread the owner already ended. + if thread_store is not None and app_config is not None and getattr(record, "thread_id", None): + try: + await thread_store.renew_incognito( + record.thread_id, + idle_ttl=timedelta(seconds=app_config.incognito.idle_ttl_seconds), + max_lifetime=timedelta(seconds=app_config.incognito.max_lifetime_seconds), + user_id=getattr(record, "user_id", None), + ) + except Exception: + logger.warning("Incognito renewal failed for thread %s (non-fatal)", record.thread_id, exc_info=True) if batch_continuations is not None: await batch_continuations.source_finished(record) @@ -1314,6 +1387,8 @@ def get_run_context(request: Request) -> RunContext: agent_runs = get_agent_runs(request) checkpointer = get_checkpointer(request) scheduled_task_service = getattr(request.app.state, "scheduled_task_service", None) + thread_store = get_thread_store(request) + app_config = get_config() return RunContext( agent_runs=agent_runs, checkpointer=checkpointer, @@ -1322,15 +1397,17 @@ def get_run_context(request: Request) -> RunContext: run_events_config=getattr(request.app.state, "run_events_config", None), checkpoint_channel_mode=getattr(request.app.state, "checkpoint_channel_mode", "full"), checkpoint_snapshot_frequency=getattr(request.app.state, "checkpoint_snapshot_frequency", None), - thread_store=get_thread_store(request), + thread_store=thread_store, mcp_task_repo=getattr(request.app.state, "mcp_task_repo", None), approval_store=getattr(request.app.state, "approval_store", None), - app_config=get_config(), + app_config=app_config, extensions=getattr(request.app.state, "extensions", None), - on_run_admitted=_run_admission_hook(checkpointer=checkpointer), + on_run_admitted=_run_admission_hook(checkpointer=checkpointer, thread_store=thread_store, app_config=app_config), on_run_completed=_run_completion_hook( scheduled_task_service=scheduled_task_service, batch_continuations=getattr(request.app.state, "batch_continuations", None), + thread_store=thread_store, + app_config=app_config, ), ) diff --git a/backend/app/gateway/incognito.py b/backend/app/gateway/incognito.py new file mode 100644 index 00000000000..9b28a458f1e --- /dev/null +++ b/backend/app/gateway/incognito.py @@ -0,0 +1,106 @@ +"""Incognito thread lifetime: the background expiry sweep. + +The Gateway starts :func:`run_incognito_sweep_loop` beside the other lifespan +background tasks. It polls the thread store for incognito rows whose deadline +passed and deletes their data through the same orchestration as +``DELETE /api/threads/{thread_id}``, under the same durable reservation, so a +sweep can never race an in-flight run. + +Ordering matters: the store tombstone (``status="expired"``, content cleared) +is written before any delete, so a purge that fails halfway still leaves the +thread unreadable; and the row's ``expires_at`` is cleared only after every +store has been cleaned, which is what makes a failed purge retry on the next +pass. The row itself is never deleted: the thread id must not be reusable as +an ordinary thread, and read routes must report it as gone rather than as an +empty 200. +""" + +from __future__ import annotations + +import asyncio +import logging +from datetime import datetime +from typing import Any + +from app.gateway.utils import sanitize_log_param +from deerflow.runtime import ThreadOperationKind +from deerflow.runtime.goal import goal_thread_lock +from deerflow.runtime.runs.manager import ConflictError + +logger = logging.getLogger(__name__) + +# Fallback poll cadence when the live config cannot be read (a broken +# config.yaml must not turn the sweep into a busy loop). +_SWEEP_RETRY_SECONDS = 60 + + +async def sweep_expired_incognito_threads(app: Any, *, now: datetime | None = None, batch_size: int = 100) -> int: + """Purge one batch of expired incognito threads; return how many finished. + + A thread with work in flight is skipped: its reservation refuses the + delete, its data stays intact, and the next sweep retries it. A batch + entry whose deadline was renewed after the due list was read is skipped + too, and every other failure leaves the tombstone in place and is retried + the same way. + """ + store = getattr(app.state, "thread_store", None) + run_manager = getattr(app.state, "run_manager", None) + if store is None or run_manager is None: + return 0 + + due = await store.list_due_incognito(now=now, limit=batch_size) + purged = 0 + for record in due: + thread_id = record.get("thread_id") + if not isinstance(thread_id, str) or not thread_id: + continue + user_id = record.get("user_id") + try: + async with goal_thread_lock(thread_id): + async with run_manager.reserve_thread_operation(thread_id, kind=ThreadOperationKind.delete, user_id=user_id): + # The due list is a snapshot; a run admission or completion + # may have renewed the deadline since it was read. The + # store rechecks under its row lock and reports whether the + # row is still due, so a renewed thread is left alone. + if not await store.begin_incognito_expiry(thread_id): + continue + # Imported lazily: the delete core lives with the threads + # router, and importing that module here would pull the + # whole router graph into app startup before it is needed. + from app.gateway.routers.threads import purge_thread_data + + await purge_thread_data(thread_id, app_state=app.state, user_id=user_id, delete_meta_row=False, require_complete=True) + await store.finish_incognito_expiry(thread_id) + purged += 1 + except ConflictError: + logger.info("Incognito thread %s has work in flight; expiry deferred to the next sweep", sanitize_log_param(thread_id)) + except Exception: + logger.warning("Failed to purge expired incognito thread %s; retrying on the next sweep", sanitize_log_param(thread_id), exc_info=True) + return purged + + +async def run_incognito_sweep_loop(app: Any) -> None: + """Sweep until cancelled; the lifespan owns the task and its shutdown. + + Runs even when ``incognito.enabled`` is false: the switch stops clients + from creating new incognito threads, but threads created before the + operator flipped it must still be deleted on schedule. + """ + from deerflow.config import get_app_config + + while True: + try: + settings = (await asyncio.to_thread(get_app_config)).incognito + except Exception: + logger.warning("Incognito sweep could not read config.yaml; retrying in %ss", _SWEEP_RETRY_SECONDS, exc_info=True) + await asyncio.sleep(_SWEEP_RETRY_SECONDS) + continue + try: + purged = await sweep_expired_incognito_threads(app, batch_size=settings.sweep_batch_size) + if purged: + logger.info("Incognito lifetime sweep purged %d thread(s)", purged) + except asyncio.CancelledError: + raise + except Exception: + logger.warning("Incognito lifetime sweep failed", exc_info=True) + await asyncio.sleep(settings.sweep_interval_seconds) diff --git a/backend/app/gateway/routers/features.py b/backend/app/gateway/routers/features.py index 25e1b0cb300..1af65406ab2 100644 --- a/backend/app/gateway/routers/features.py +++ b/backend/app/gateway/routers/features.py @@ -84,6 +84,13 @@ class ThreadActivityFeature(BaseModel): available: bool = Field(..., description="Whether GET /api/thread-activity, POST /api/threads/{thread_id}/read and the thread search `unread` field work (SQL persistence)") +class IncognitoFeature(BaseModel): + """Availability and lifetime of incognito (temporary) chats.""" + + enabled: bool = Field(..., description="Whether authenticated browser clients can create incognito chats") + idle_ttl_seconds: int = Field(..., description="Idle window after the last activity before an incognito chat is deleted") + + class ToolApprovalFeature(BaseModel): enabled: bool = False default_mode: Literal["ask", "auto", "full"] = "ask" @@ -101,6 +108,7 @@ class FeaturesResponse(BaseModel): knowledge_base: KnowledgeBaseFeature scheduled_tasks: ScheduledTasksFeature thread_activity: ThreadActivityFeature + incognito: IncognitoFeature run_inputs: bool = False tool_approval: ToolApprovalFeature = Field(default_factory=ToolApprovalFeature) @@ -147,6 +155,12 @@ async def list_features(request: Request, config: AppConfig = Depends(get_config scheduled_tasks=_scheduled_tasks_feature(request, config), # Startup-scoped: the read repository exists only with SQL persistence. thread_activity=ThreadActivityFeature(available=thread_activity_available(request.app.state)), + # Read through ``get_config`` so the entry point and the lifetime + # notice follow config.yaml without a restart, like the other flags. + incognito=IncognitoFeature( + enabled=config.incognito.enabled, + idle_ttl_seconds=config.incognito.idle_ttl_seconds, + ), ) diff --git a/backend/app/gateway/routers/shares.py b/backend/app/gateway/routers/shares.py index a611b0c8fc7..155332db022 100644 --- a/backend/app/gateway/routers/shares.py +++ b/backend/app/gateway/routers/shares.py @@ -49,6 +49,13 @@ def share_repository() -> ThreadShareRepository: @require_permission("runs", "read") async def create_share(thread_id: ThreadId, body: ShareCreateRequest, request: Request): async def create(): + from app.gateway.deps import get_thread_store + + thread = await get_thread_store(request).get(thread_id) + if thread is not None and thread.get("incognito") is True: + # A share is a frozen copy readable without the owner's session; + # it would outlive the incognito thread and defeat its deletion. + raise HTTPException(409, "An incognito thread cannot be shared") repo = share_repository() async with reserve_checkpoint_write(request, thread_id, user_id=get_effective_user_id()): if await repo.count_active(thread_id, get_effective_user_id()) >= 10: diff --git a/backend/app/gateway/routers/thread_activity.py b/backend/app/gateway/routers/thread_activity.py index 61d2be0f661..20dc0f61942 100644 --- a/backend/app/gateway/routers/thread_activity.py +++ b/backend/app/gateway/routers/thread_activity.py @@ -112,9 +112,26 @@ async def list_thread_activity( latest.pop(thread_id, None) latest[thread_id] = ThreadActivityItem(thread_id=thread_id, origin_kind=origin_kind, status=str(row.get("status") or "")) + threads = list(latest.values()) + # An incognito thread must never appear on an activity surface. It cannot + # be a server-originated run's target today (it is not a valid scheduled + # task reuse target, and IM/extension callers cannot create one), so this + # is defense in depth. A store failure keeps the page: the feed is + # owner-scoped and only prompts a sidebar refetch, whose own list excludes + # incognito threads. + thread_store = getattr(state, "thread_store", None) + incognito_ids = getattr(thread_store, "incognito_ids", None) + if threads and callable(incognito_ids): + try: + hidden = await incognito_ids([item.thread_id for item in threads], user_id=user_id) + except Exception: + hidden = set() + if hidden: + threads = [item for item in threads if item.thread_id not in hidden] + return ThreadActivityResponse( cursor=next_cursor, - threads=list(latest.values()), + threads=threads, truncated=truncated, read_version=await read_repo.read_version(user_id=user_id), ) diff --git a/backend/app/gateway/routers/threads.py b/backend/app/gateway/routers/threads.py index 16b79b2a592..4a73f743824 100644 --- a/backend/app/gateway/routers/threads.py +++ b/backend/app/gateway/routers/threads.py @@ -17,15 +17,18 @@ import logging import shutil import uuid +from datetime import UTC, datetime, timedelta from pathlib import Path +from types import SimpleNamespace from typing import Any -from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request +from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request, Response from langgraph.checkpoint.base import empty_checkpoint from langgraph.types import Overwrite from pydantic import BaseModel, ConfigDict, Field, field_validator from sqlalchemy.exc import IntegrityError +from app.gateway.auth_disabled import AUTH_SOURCE_AUTH_DISABLED, AUTH_SOURCE_SESSION from app.gateway.authz import _is_internal_caller, authorize_model_use, require_permission from app.gateway.checkpoint_lineage import ( CheckpointLineageError, @@ -38,7 +41,7 @@ resolve_history_versions, resolve_stamp_candidate_versions, ) -from app.gateway.deps import get_checkpointer, get_config, get_current_user_from_request, get_run_event_store, get_run_manager, get_run_store +from app.gateway.deps import get_checkpointer, get_config, get_current_user_from_request, get_run_event_store, get_run_manager from app.gateway.history_seed import reserve_history_seed, write_history_seed from app.gateway.hitl_approval import find_pending_interrupts from app.gateway.internal_auth import get_trusted_internal_owner_user_id @@ -57,7 +60,17 @@ from deerflow.config.app_config import AppConfig from deerflow.config.paths import Paths, get_paths from deerflow.config.summarization_config import ContextSize -from deerflow.persistence.thread_meta import PROJECT_FILTER_UNSET, THREAD_ARCHIVED_METADATA_KEY, THREAD_PINNED_METADATA_KEY, THREAD_PROJECT_METADATA_KEY, ThreadOwnershipConflictError +from deerflow.persistence.thread_meta import ( + PROJECT_FILTER_UNSET, + THREAD_ARCHIVED_METADATA_KEY, + THREAD_INCOGNITO_ENDED_METADATA_KEY, + THREAD_PINNED_METADATA_KEY, + THREAD_PROJECT_METADATA_KEY, + ThreadCreateConflictError, + ThreadOwnershipConflictError, + incognito_deadline, + is_incognito_expired, +) from deerflow.runtime import ThreadOperationKind, serialize_channel_values_for_api from deerflow.runtime.checkpoint_mode import CheckpointModeMismatchError, CheckpointModeReconfigurationError from deerflow.runtime.checkpoint_state import graph_reducer_channels, graph_state_schema, graph_writable_channels @@ -138,7 +151,7 @@ def _checkpoint_mode_http_error(exc: Exception, thread_id: str) -> HTTPException # the auth contextvar; this list closes the metadata-blob echo gap. # ``deerflow_origin`` marks a thread the server created for a schedule or an # extension; only the server sets it (``create_thread`` below, run admission). -_SERVER_RESERVED_METADATA_KEYS: frozenset[str] = frozenset({"owner_id", "user_id", THREAD_PROJECT_METADATA_KEY, DEERFLOW_ORIGIN_KEY}) +_SERVER_RESERVED_METADATA_KEYS: frozenset[str] = frozenset({"owner_id", "user_id", THREAD_PROJECT_METADATA_KEY, DEERFLOW_ORIGIN_KEY, THREAD_INCOGNITO_ENDED_METADATA_KEY}) # Checkpoint metadata the server writes and later reads back as trusted: # LangGraph's lineage keys and delta counters (``step`` drives the next turn, # ``parents`` the history walk, and ``counters_since_delta_snapshot`` is read @@ -499,6 +512,7 @@ class ThreadResponse(_MetadataRedactingResponse): values: dict[str, Any] = Field(default_factory=dict, description="Current state channel values") interrupts: dict[str, Any] = Field(default_factory=dict, description="Pending interrupts") unread: bool | None = Field(default=None, description="Thread search only: a server-originated run of the caller changed since the caller last opened the thread; null when unknown") + incognito: bool = Field(default=False, description="Temporary chat: hidden from every list, search, project and share surface and deleted on expiry") class ThreadReadResponse(BaseModel): @@ -515,6 +529,7 @@ class ThreadCreateRequest(BaseModel): assistant_id: str | None = Field(default=None, description="Associate thread with an assistant") metadata: dict[str, Any] = Field(default_factory=dict, description="Initial metadata") project_id: str | None = Field(default=None, description="Assign the new thread to this project (validated server-side)") + incognito: bool = Field(default=False, description="Create a temporary chat: hidden from every list, search, project and share surface and deleted on expiry") _strip_reserved = field_validator("metadata")(classmethod(lambda cls, v: _strip_reserved_metadata(v))) @@ -792,10 +807,28 @@ async def delete_thread_data(thread_id: str, request: Request) -> ThreadDeleteRe Cleans DeerFlow-managed thread directories, removes checkpoint data, and removes the thread_meta row from the configured ThreadMetaStore (sqlite or memory). + + An incognito thread is refused: this best-effort path would delete its + tombstone (making the id reusable) and would not retry a partial purge. + Ending it through ``POST /api/threads/{thread_id}/incognito/end`` keeps + the tombstone and routes deletion through the sweep's checked purge. """ run_manager = get_run_manager(request) try: async with goal_thread_lock(thread_id): + thread_store = getattr(request.app.state, "thread_store", None) + if thread_store is not None: + # The permission decorator already authorized this caller, so + # read the row unscoped: an unowned legacy row must not skip + # the guard merely because it has no owner to match. + record = await thread_store.get(thread_id, user_id=None) + if record is not None and record.get("incognito") is True: + if is_incognito_expired(record): + raise HTTPException(status_code=410, detail="This incognito thread has expired") + raise HTTPException( + status_code=409, + detail=f"Incognito chats cannot be deleted directly. End the chat with POST /api/threads/{thread_id}/incognito/end.", + ) async with run_manager.reserve_thread_operation( thread_id, kind=ThreadOperationKind.delete, @@ -829,19 +862,73 @@ def _event_delete_owner_kwargs(delete_by_thread: Any, user_id: str) -> dict[str, async def _delete_thread_data_with_reservation(thread_id: str, request: Request) -> ThreadDeleteResponse: """Delete a thread while its durable exclusive reservation is held.""" + return await purge_thread_data(thread_id, app_state=request.app.state, user_id=get_effective_user_id()) + + +class ThreadPurgeIncomplete(RuntimeError): + """A purge step failed while the caller required complete deletion. + + The interactive delete route is best-effort: it already returned control + to the user, so a failed auxiliary cleanup is logged and the thread row is + gone. The incognito sweep cannot treat content deletion that way — a + thread whose runs or events survived must stay on the retry list — so it + raises this after every step has been attempted. + """ + + +async def purge_thread_data( + thread_id: str, + *, + app_state: Any, + user_id: str | None, + delete_meta_row: bool = True, + require_complete: bool = False, +) -> ThreadDeleteResponse: + """Delete a thread's data while its durable exclusive reservation is held. + + ``app_state`` rather than a Request lets the incognito sweep reuse this + orchestration; every accessor below reads ``app.state`` and nothing else + from the request. ``delete_meta_row=False`` keeps the row for the sweep's + tombstone, which must survive the purge. + + ``require_complete`` turns the content stores below (runs, run events, + feedback, scheduled-task events, MCP tasks, read markers) into a checked + contract: every step is still attempted, but any failure raises + :class:`ThreadPurgeIncomplete` at the end. A configured store that is + absent on this deployment is skipped, not counted as a failure. Browser + and MCP sessions are runtime resources rather than stored content, so + their teardown stays best-effort and is not retried. The incognito sweep + uses this so a partial purge keeps its retry marker; the delete route + keeps the best-effort behavior. + """ from app.gateway.deps import get_thread_store + request = SimpleNamespace(app=SimpleNamespace(state=app_state)) # One owner identity for every cleanup step below: the filesystem bucket, the # persisted runs/events/feedback and the thread_meta row all belong to the # same owner, so they must not resolve their scope independently. - user_id = get_effective_user_id() run_manager = get_run_manager(request) batch_repo = getattr(request.app.state, "subagent_batch_repo", None) approval_store = getattr(request.app.state, "approval_store", None) + # Declared before the first optional store so a failing step is recorded + # and the purge continues: the strict caller raises only after every step + # has been attempted. + purge_failures: list[str] = [] if approval_store is not None: await await_drained(approval_store.delete_thread(thread_id, user_id=user_id)) if batch_repo is not None: - await batch_repo.suppress_thread_continuations(thread_id) + try: + await batch_repo.suppress_thread_continuations(thread_id) + # Suppression only fences in-flight continuations; the durable batch + # rows (each item's prompt text, the execution_spec) stay readable. + # Remove them so a swept incognito thread and a user delete both leave + # nothing behind. Batch rows are owner-scoped, so this needs a resolved + # user_id; a None owner (migration/CLI purge) skips it. + if user_id is not None: + await batch_repo.delete_by_thread(thread_id, user_id=user_id) + except Exception: + purge_failures.append("subagent batches") + logger.debug("Could not delete subagent batch rows for thread %s (not critical)", sanitize_log_param(thread_id)) # Legacy IDs may predate the canonical filesystem-safe contract. They can # still be removed from metadata/checkpoint stores, but must never be @@ -874,12 +961,13 @@ async def _delete_thread_data_with_reservation(thread_id: str, request: Request) # are deleted, so the durable thread-operation reservation protecting this # very request survives until ``reserve_thread_operation`` exits. Third-party # RunStore implementations that predate the capability are skipped. - try: - delete_runs = getattr(get_run_store(request), "delete_by_thread", None) - if delete_runs is not None: + delete_runs = getattr(getattr(request.app.state, "run_store", None), "delete_by_thread", None) + if delete_runs is not None: + try: await delete_runs(thread_id, user_id=user_id) - except Exception: - logger.debug("Could not delete run records for thread %s (not critical)", sanitize_log_param(thread_id)) + except Exception: + purge_failures.append("runs") + logger.debug("Could not delete run records for thread %s (not critical)", sanitize_log_param(thread_id)) # Drop this worker's in-memory copies too. ``RunManager.get()`` and # ``list_by_thread()`` answer from the process-local registry before the @@ -896,11 +984,13 @@ async def _delete_thread_data_with_reservation(thread_id: str, request: Request) # thread's feed readable again through GET /threads/{id}/messages. A legacy # store that predates the owner-scoped signature is still called, with the # old contract. - try: - delete_events = get_run_event_store(request).delete_by_thread - await delete_events(thread_id, **_event_delete_owner_kwargs(delete_events, user_id)) - except Exception: - logger.debug("Could not delete run events for thread %s (not critical)", sanitize_log_param(thread_id)) + delete_events = getattr(getattr(request.app.state, "run_event_store", None), "delete_by_thread", None) + if delete_events is not None: + try: + await delete_events(thread_id, **_event_delete_owner_kwargs(delete_events, user_id)) + except Exception: + purge_failures.append("run events") + logger.debug("Could not delete run events for thread %s (not critical)", sanitize_log_param(thread_id)) # Remove persisted feedback best-effort. This cleans existing rows; fencing # already-admitted writes across thread deletion is a separate lifecycle @@ -911,15 +1001,31 @@ async def _delete_thread_data_with_reservation(thread_id: str, request: Request) if feedback_repo is not None: await feedback_repo.delete_by_thread(thread_id, user_id=user_id) except Exception: + purge_failures.append("feedback") logger.debug("Could not delete feedback for thread %s (not critical)", sanitize_log_param(thread_id)) - # Remove thread_meta row (best-effort) — required for sqlite backend - # so the deleted thread no longer appears in /threads/search. + # Remove tracked MCP tasks (best-effort). Their rows hold the remote task's + # result and input payloads, and the poller can keep a row readable long + # after the conversation is gone. Skipped on the memory backend, which has + # no MCP task repository. try: - thread_store = get_thread_store(request) - await thread_store.delete(thread_id, user_id=user_id) + mcp_task_repo = getattr(request.app.state, "mcp_task_repo", None) + if mcp_task_repo is not None: + await mcp_task_repo.delete_by_thread(thread_id, user_id=user_id) except Exception: - logger.debug("Could not delete thread_meta for %s (not critical)", sanitize_log_param(thread_id)) + purge_failures.append("MCP tasks") + logger.debug("Could not delete MCP tasks for thread %s (not critical)", sanitize_log_param(thread_id)) + + # Remove thread_meta row (best-effort) — required for sqlite backend + # so the deleted thread no longer appears in /threads/search. The + # incognito sweep keeps the row as its tombstone. + if delete_meta_row: + try: + thread_store = get_thread_store(request) + await thread_store.delete(thread_id, user_id=user_id) + except Exception: + purge_failures.append("thread metadata") + logger.debug("Could not delete thread_meta for %s (not critical)", sanitize_log_param(thread_id)) # Remove the chat's scheduled-task lifecycle lines (best-effort). They are # display-only history of this chat; the tasks themselves are untouched. @@ -933,15 +1039,18 @@ async def _delete_thread_data_with_reservation(thread_id: str, request: Request) if task_event_repo is not None: await task_event_repo.delete_by_thread(thread_id, user_id=user_id) except Exception: + purge_failures.append("scheduled task events") logger.debug("Could not delete scheduled task events for thread %s (not critical)", sanitize_log_param(thread_id)) # Remove every user's read marker for the thread (best-effort): the thread - # is gone, so its unread state is meaningless for all of them. + # is gone, so its unread state is meaningless for all of them. The row is + # persisted content, so a failure is part of the checked contract. try: thread_read_repo = getattr(request.app.state, "thread_read_repo", None) if thread_read_repo is not None: await thread_read_repo.delete_by_thread(thread_id) except Exception: + purge_failures.append("read markers") logger.debug("Could not delete read markers for thread %s (not critical)", sanitize_log_param(thread_id)) # Tear down any live browser session (best-effort). Sessions are keyed only @@ -972,6 +1081,11 @@ async def _delete_thread_data_with_reservation(thread_id: str, request: Request) except Exception: logger.debug("Could not close MCP sessions for %s (not critical)", sanitize_log_param(thread_id)) + if require_complete and purge_failures: + # The caller (the incognito sweep) holds the row open for a retry, so + # report which stores survived instead of pretending the purge is done. + raise ThreadPurgeIncomplete(f"Purge for thread {thread_id} left data in: {', '.join(purge_failures)}") + return response @@ -1002,7 +1116,69 @@ def _existing_thread_response(thread_id: str, record: dict) -> ThreadResponse: created_at=coerce_iso(record.get("created_at", "")), updated_at=coerce_iso(record.get("updated_at", "")), metadata=record.get("metadata", {}), + incognito=record.get("incognito") is True, + ) + + +def _existing_thread_or_conflict(thread_id: str, record: dict, *, incognito: bool) -> ThreadResponse: + """Idempotent create keeps the stored visibility; it never converts a thread.""" + if is_incognito_expired(record): + # The tombstone row still owns the id: answering with it would hand + # back a dead thread, and creating it anew would resurrect it. + raise HTTPException(status_code=410, detail="This incognito thread has expired") + if (record.get("incognito") is True) != incognito: + raise HTTPException(status_code=409, detail="Thread already exists with a different visibility mode") + return _existing_thread_response(thread_id, record) + + +_INCOGNITO_CREATE_SOURCES = frozenset({AUTH_SOURCE_SESSION, AUTH_SOURCE_AUTH_DISABLED}) + + +def _require_incognito_creation_allowed(request: Request, *, enabled: bool) -> None: + """Incognito threads belong to a browser session, not to IM or extensions. + + The restriction is server-enforced: a PAT, an internal caller or an + extension-launched request cannot mint a thread that the owner's other + surfaces will never see. + """ + if not enabled: + raise HTTPException(status_code=403, detail="Incognito threads are disabled by the operator") + if getattr(request.state, "run_origin", None) is not None: + raise HTTPException(status_code=403, detail="Incognito threads can only be created from a browser session") + if getattr(request.state, "auth_source", None) not in _INCOGNITO_CREATE_SOURCES: + raise HTTPException(status_code=403, detail="Incognito threads can only be created from a browser session") + + +@router.post("/{thread_id}/incognito/end", status_code=204) +@require_permission("threads", "write", owner_check=True, require_existing=True) +async def end_incognito_thread(thread_id: ThreadId, request: Request) -> Response: + """End an incognito thread: its data is purged after the grace period. + + The browser exits locally without waiting for this call, so it is + best-effort; a failed request still ends the thread through the idle TTL. + During the grace window in-flight work may finish, but further activity no + longer renews the deadline. + """ + from app.gateway.deps import get_thread_store + + thread_store = get_thread_store(request) + record = await thread_store.get(thread_id) + if record is None: + raise HTTPException(status_code=404, detail=f"Thread {thread_id} not found") + if record.get("incognito") is not True: + raise HTTPException(status_code=409, detail="Thread is not an incognito thread") + if is_incognito_expired(record): + raise HTTPException(status_code=410, detail="This incognito thread has expired") + # Reading config touches the filesystem; keep it off the event loop. + app_config = await asyncio.to_thread(get_config) + ended = await thread_store.end_incognito( + thread_id, + grace=timedelta(seconds=app_config.incognito.end_grace_seconds), + max_lifetime=timedelta(seconds=app_config.incognito.max_lifetime_seconds), ) + if not ended: + raise HTTPException(status_code=410, detail="This incognito thread has expired") + return Response(status_code=204) @router.post("", response_model=ThreadResponse) @@ -1026,20 +1202,47 @@ async def _create_thread_locked(body: ThreadCreateRequest, request: Request, thr checkpointer = get_checkpointer(request) thread_store = get_thread_store(request) now = now_iso() + expires_at: datetime | None = None + # The LangGraph SDK creates the thread lazily on the first submit and only + # forwards ``metadata``; the browser marks that implicit create there. Read + # the marker as the same creation intent as the top-level field, so the + # SDK's ensure-create stays idempotent with the REST pre-create instead of + # returning 409 on the visibility mismatch. + incognito = body.incognito or body.metadata.get("incognito") is True + if incognito: + # Only incognito creation needs the configuration, and the read touches + # the filesystem: keep ordinary creates free of it and the incognito + # read off the event loop. + app_config = await asyncio.to_thread(get_config) + _require_incognito_creation_allowed(request, enabled=app_config.incognito.enabled) + if body.project_id is not None: + raise HTTPException(status_code=400, detail="An incognito thread cannot belong to a project") + # Creation is the first deadline write, so it goes through the same + # ceiling as renewal and end; the store stamps created_at a moment + # later, which only makes the cap looser by that margin. + created_at = datetime.now(UTC) + expires_at = incognito_deadline( + now=created_at, + created_at=created_at, + window=timedelta(seconds=app_config.incognito.idle_ttl_seconds), + max_lifetime=timedelta(seconds=app_config.incognito.max_lifetime_seconds), + ) thread_owner_user_id = get_trusted_internal_owner_user_id(request) thread_owner_kwargs = {"user_id": thread_owner_user_id} if thread_owner_user_id else {} # ``body.metadata`` is already stripped of server-reserved keys by # ``ThreadCreateRequest._strip_reserved`` — see the model definition. # A server-side caller (an extension handle) marks the thread it creates; - # request.state is never HTTP input. - metadata = dict(body.metadata) + # request.state is never HTTP input. The incognito marker above is a + # creation hint only — the column is the single source of truth, so it is + # not stored again in metadata. + metadata = {key: value for key, value in body.metadata.items() if key != "incognito"} if (origin := admit_origin(getattr(request.state, "run_origin", None))) is not None: metadata[DEERFLOW_ORIGIN_KEY] = origin # Idempotency: return existing record when already present existing_record = await _resolve_existing_thread(thread_store, thread_id, thread_owner_user_id, thread_owner_kwargs) if existing_record is not None: - return _existing_thread_response(thread_id, existing_record) + return _existing_thread_or_conflict(thread_id, existing_record, incognito=incognito) # Write thread_meta so the thread appears in /threads/search immediately from deerflow.persistence.projects import ProjectNotAssignableError @@ -1051,6 +1254,8 @@ async def _create_thread_locked(body: ThreadCreateRequest, request: Request, thr **thread_owner_kwargs, metadata=metadata, project_id=body.project_id, + incognito=incognito, + expires_at=expires_at, ) except ProjectNotAssignableError: # Fail closed: missing, foreign, or archived projects are @@ -1059,18 +1264,19 @@ async def _create_thread_locked(body: ThreadCreateRequest, request: Request, thr except ThreadOwnershipConflictError: # Do not reveal that a caller-chosen id belongs to another user. raise HTTPException(status_code=404, detail="Thread not found") from None - except IntegrityError: + except (IntegrityError, ThreadCreateConflictError): # The idempotency read above and this insert are not atomic: a # another worker's request for the same thread_id can commit in between, so # the SQL-backed store rejects ours on the duplicate primary key. # Honour the documented idempotency contract by resolving the # now-existing record — running the same owner reconciliation the fast # path does — instead of surfacing the conflict as a 500. Same-process - # HTTP creates share the lifecycle lock; the memory store retains its - # historical overwrite behavior for direct callers. + # HTTP creates share the lifecycle lock. ThreadCreateConflictError is + # the memory store's equivalent: it refuses to overwrite an incognito + # row (live or tombstoned) instead of silently replacing it. existing_record = await _resolve_existing_thread(thread_store, thread_id, thread_owner_user_id, thread_owner_kwargs) if existing_record is not None: - return _existing_thread_response(thread_id, existing_record) + return _existing_thread_or_conflict(thread_id, existing_record, incognito=incognito) # The same-owner reconciliation above found nothing, yet the insert hit # a duplicate primary key — so the surviving row belongs to *another* # user. That is the ownership-conflict case, which the route already @@ -1145,6 +1351,10 @@ async def _branch_thread_with_reservation( source_record = await thread_store.get(thread_id) if source_record is None: raise HTTPException(status_code=404, detail=f"Thread {thread_id} not found") + if source_record.get("incognito") is True: + # A branch is a new ordinary thread carrying this conversation's + # content; allowing it would turn a temporary chat into a lasting one. + raise HTTPException(status_code=409, detail="An incognito thread cannot be branched") source_metadata = source_record.get("metadata") or {} if source_metadata.get(_SIDECAR_METADATA_KEY) is True: @@ -1392,6 +1602,7 @@ async def search_threads(body: ThreadSearchRequest, request: Request) -> list[Th values={"title": r["display_name"]} if r.get("display_name") else {}, interrupts={}, unread=(r["thread_id"] in unread_ids) if unread_ids is not None else None, + incognito=r.get("incognito") is True, ) for r in rows ] @@ -1461,6 +1672,7 @@ async def patch_thread(thread_id: ThreadId, body: ThreadPatchRequest, request: R created_at=coerce_iso(record.get("created_at", "")), updated_at=coerce_iso(record.get("updated_at", "")), metadata=record.get("metadata", {}), + incognito=record.get("incognito") is True, ) @@ -1478,6 +1690,13 @@ async def move_thread(thread_id: ThreadId, body: ThreadMoveRequest, request: Req from app.gateway.deps import get_thread_store thread_store = get_thread_store(request) + existing = await thread_store.get(thread_id) + if existing is None: + raise HTTPException(status_code=404, detail="Thread or project not found") + if existing.get("incognito") is True: + # Project membership is a listing surface; an incognito thread must + # never enter one. + raise HTTPException(status_code=409, detail="An incognito thread cannot be moved into a project") moved = await thread_store.set_project(thread_id, body.project_id) if not moved: raise HTTPException(status_code=404, detail="Thread or project not found") @@ -1488,6 +1707,7 @@ async def move_thread(thread_id: ThreadId, body: ThreadMoveRequest, request: Req created_at=coerce_iso(record.get("created_at", "")), updated_at=coerce_iso(record.get("updated_at", "")), metadata=record.get("metadata", {}), + incognito=record.get("incognito") is True, ) @@ -1540,6 +1760,7 @@ async def get_thread(thread_id: ThreadId, request: Request) -> ThreadResponse: created_at=coerce_iso(record.get("created_at", "")), updated_at=coerce_iso(record.get("updated_at", "")), metadata=record.get("metadata", {}), + incognito=record.get("incognito") is True, values=serialize_channel_values_for_api(snapshot.values), interrupts={task_id: [serialize_lc_object(interrupt) for interrupt in interrupts] for task_id, interrupts in (await find_pending_interrupts(request, thread_id, accessor=accessor, read_config=config, snapshot=snapshot)).items()}, ) diff --git a/backend/app/gateway/scheduled_task_access.py b/backend/app/gateway/scheduled_task_access.py index 56fb7e0e8ba..422ff4a76d4 100644 --- a/backend/app/gateway/scheduled_task_access.py +++ b/backend/app/gateway/scheduled_task_access.py @@ -254,6 +254,11 @@ async def _require(self, permissions: frozenset[str], *, check_origin: bool = Tr origin = await self._thread_store.get(self._origin_thread_id, user_id=self._owner_id) if self._origin_thread_id else None if origin is None or origin.get("user_id") != self._owner_id: raise scheduler_error(404, "conversation_not_found", "Originating conversation not found") + if origin.get("incognito") is True: + # Defense in depth: capability binding already withholds the + # capability for an incognito origin, so this only fires when a + # thread flipped after the grant was minted. + raise scheduler_error(422, "incognito_thread_not_schedulable", "An incognito thread cannot be managed by a scheduled task") async def _task(self, task_id: Any) -> dict[str, Any]: """A task this conversation may manage: created here, or one whose run this conversation is.""" @@ -552,7 +557,10 @@ async def prepare_scheduler_capability( if mode is RunInteractionMode.INTERACTIVE: origin_thread_id = thread_id origin = await threads.get(origin_thread_id, user_id=owner_id) - if origin is None or origin.get("user_id") != owner_id: + # A capability minted for an incognito conversation would let a run + # whose chat is being purged keep writing listable task rows, so the + # grant is withheld here as well as at the conversation layer. + if origin is None or origin.get("user_id") != owner_id or origin.get("incognito") is True: return None elif mode is RunInteractionMode.SCHEDULED and source == AUTH_SOURCE_INTERNAL and isinstance(scheduled_task_runtime, Mapping): task_id = scheduled_task_runtime.get("task_id") diff --git a/backend/app/gateway/scheduled_task_errors.py b/backend/app/gateway/scheduled_task_errors.py index 5ed09c700bb..f3edab96d6f 100644 --- a/backend/app/gateway/scheduled_task_errors.py +++ b/backend/app/gateway/scheduled_task_errors.py @@ -28,6 +28,7 @@ "once_time_passed", "invalid_context_mode", "reuse_thread_requires_thread", + "incognito_thread_not_schedulable", "thread_not_found", "invalid_assistant", "unknown_assistant", diff --git a/backend/app/gateway/scheduled_task_validation.py b/backend/app/gateway/scheduled_task_validation.py index ec15bbeaf0d..854ad9a4c28 100644 --- a/backend/app/gateway/scheduled_task_validation.py +++ b/backend/app/gateway/scheduled_task_validation.py @@ -224,6 +224,11 @@ async def validate_scheduled_task_create( raise scheduler_error(422, "reuse_thread_requires_thread", "reuse_thread requires thread_id") if not await thread_store.check_access(body.thread_id, user_id, require_existing=True): raise scheduler_error(404, "thread_not_found", "Thread not found") + thread = await thread_store.get(body.thread_id, user_id=user_id) + if thread is not None and thread.get("incognito") is True: + # A scheduled task outlives the thread and would pin its transcript + # in a durable, listable surface. + raise scheduler_error(422, "incognito_thread_not_schedulable", "An incognito thread cannot be reused by a scheduled task") if body.schedule_type not in SCHEDULE_TYPES: raise scheduler_error(422, "invalid_schedule_type", "Unsupported schedule_type") schedule_spec, upcoming = await asyncio.to_thread(_validate_schedule, body.schedule_type, body.schedule_spec, body.timezone, scheduler_config=scheduler_config, now=reference) @@ -348,6 +353,13 @@ async def validate_scheduled_task_update( raise scheduler_error(422, "reuse_thread_requires_thread", "reuse_thread requires thread_id") if not await thread_store.check_access(str(effective_thread_id), user_id, require_existing=True): raise scheduler_error(404, "thread_not_found", "Thread not found") + thread = await thread_store.get(str(effective_thread_id), user_id=user_id) + if thread is not None and thread.get("incognito") is True: + # Same rule as create: a task that outlives the thread would pin + # its transcript in a durable, listable surface. A PATCH can move + # a task onto such a thread just as a create can, so the check + # runs on the effective thread, not only on a field the request set. + raise scheduler_error(422, "incognito_thread_not_schedulable", "An incognito thread cannot be reused by a scheduled task") elif effective_context_mode == "fresh_thread_per_run": updates["thread_id"] = None if "timezone" in updates: diff --git a/backend/app/gateway/search_corpus.py b/backend/app/gateway/search_corpus.py index 3eaa1af7d91..1529b7c28a9 100644 --- a/backend/app/gateway/search_corpus.py +++ b/backend/app/gateway/search_corpus.py @@ -69,7 +69,7 @@ def project_thread(row) -> SearchThread: async def thread(self, thread_id: str) -> SearchThread | None: row = await self.thread_store.get(thread_id, user_id=self.user_id) - if row is None or (row.get("metadata") or {}).get("deerflow_sidecar") is True: + if row is None or row.get("incognito") is True or (row.get("metadata") or {}).get("deerflow_sidecar") is True: return None return self.project_thread(row) @@ -85,7 +85,7 @@ async def seed_legacy_history(self, thread: SearchThread) -> None: async def owns(self, thread: SearchThread) -> bool: row = await self.thread_store.get(thread.thread_id, user_id=self.user_id) - return bool(row and str(row.get("incarnation") or row.get("created_at") or "") == thread.incarnation and (row.get("metadata") or {}).get("deerflow_sidecar") is not True) + return bool(row and row.get("incognito") is not True and str(row.get("incarnation") or row.get("created_at") or "") == thread.incarnation and (row.get("metadata") or {}).get("deerflow_sidecar") is not True) async def revision(self, thread: SearchThread) -> str | None: if not await self.owns(thread): @@ -126,7 +126,7 @@ async def _page(self, thread_id: str, *, limit: int, before_seq=None, after_seq= async def around(self, thread_id: str, message_id: str, *, limit: int = 20, seq: int | None = None) -> dict | None: row = await self.thread_store.get(thread_id, user_id=self.user_id) - if row is None or (row.get("metadata") or {}).get("deerflow_sidecar") is True: + if row is None or row.get("incognito") is True or (row.get("metadata") or {}).get("deerflow_sidecar") is True: return None await self.seed_legacy_history(self.project_thread(row)) # Walk backward from the head so later versions win even when they diff --git a/backend/app/gateway/services.py b/backend/app/gateway/services.py index a6f859485b4..0d055e710cc 100644 --- a/backend/app/gateway/services.py +++ b/backend/app/gateway/services.py @@ -62,6 +62,7 @@ THREAD_INCARNATION_METADATA_GUARD_KEY, is_valid_thread_incarnation, ) +from deerflow.persistence.thread_meta import is_incognito_expired from deerflow.projects.context import PROJECT_CONTEXT_MESSAGE_MARKER, resolve_project_context from deerflow.runtime import ( END_SENTINEL, @@ -92,7 +93,7 @@ ) from deerflow.runtime.checkpoint_state import graph_state_schema from deerflow.runtime.client_context import sanitize_client_context -from deerflow.runtime.context_keys import AGENT_AUTH_CONTEXT_KEY, PROJECT_CONTEXT_KEY +from deerflow.runtime.context_keys import AGENT_AUTH_CONTEXT_KEY, INCOGNITO_CONTEXT_KEY, PROJECT_CONTEXT_KEY from deerflow.runtime.events.message_identity import MESSAGE_SEQ_KEY from deerflow.runtime.goal import goal_thread_lock from deerflow.runtime.journal import build_checkpoint_history_seed_events @@ -1153,6 +1154,9 @@ async def _discard_failed_resume_admission(request: Request, run_mgr: RunManager # never survive in either run-config section. PROJECT_CONTEXT_KEY, AGENT_AUTH_CONTEXT_KEY, + # Server-stamped only: a client-supplied flag must never let a + # normal run opt out of durable writes. + INCOGNITO_CONTEXT_KEY, KNOWLEDGE_SCOPE_KEY, KNOWLEDGE_SCOPE_RUNTIME_KEY, } @@ -2785,6 +2789,40 @@ async def scheduled_reader(*args, **kwargs): if project_context is not None: config["context"][PROJECT_CONTEXT_KEY] = project_context + async def admission_thread_verdict() -> bool | None: + """Read the thread's incognito verdict, or ``None`` when no row exists. + + A store failure is fatal: the run cannot choose its persistence + policy on a guess, because the ordinary path writes user-level + memory and shared blobs. Called under the goal lock so the sweep + and the delete route cannot change the row between this read and + durable admission. + """ + try: + thread = await run_ctx.thread_store.get(thread_id, user_id=None) + except Exception as exc: + logger.warning( + "Unable to read thread state for %s at run admission (fatal)", + sanitize_log_param(thread_id), + exc_info=True, + ) + raise HTTPException(status_code=503, detail="Unable to verify thread state") from exc + if thread is None: + return None + if thread.get("incognito") is not True: + return False + if is_incognito_expired(thread): + raise HTTPException(status_code=404, detail=f"Thread {thread_id} not found") + return True + + # The incognito verdict is pinned here, under the same goal lock the + # delete route and the lifetime sweep take, before this run can write + # anything (checkpoint seeding included). A tombstone or a deadline + # that passed while the request waited means the owner's thread is + # already gone; admitting it would create data no later sweep can + # reach. The admission hook renews the deadline once the run holds its + # durable reservation and no longer has to discover the verdict. + async def run_after_metadata(record: RunRecord) -> None: metadata_task = asyncio.create_task( _ensure_thread_metadata( @@ -2893,23 +2931,51 @@ async def run_after_metadata(record: RunRecord) -> None: human_text = original elif isinstance(original, list): human_text = "\n".join(block["text"] for block in original if isinstance(block, dict) and block.get("type") == "text" and isinstance(block.get("text"), str)) + # An incognito thread binds no scheduler capability. A scheduled + # task is a durable user-level object — its prompt and schedule + # outlive the conversation and surface on the tasks page — so + # creating one would break the "nothing persists" promise. With no + # capability bound, schedule_task returns its existing 503 + # scheduler_tools_disabled and the model tells the user it cannot + # create tasks in this conversation. The pre-admission read is the + # primary verdict; ``metadata_record`` is the fresher thread_store + # row and can also confirm an ordinary thread whose row was created + # after admission. When neither source knows (metadata setup timed + # out on a thread that did not exist yet), fail closed: a durable + # task is worse than a missing convenience tool. + pre_admission_verdict = (config.get("context") or {}).get(INCOGNITO_CONTEXT_KEY) + if pre_admission_verdict is True or (metadata_record is not None and metadata_record.get("incognito") is True): + thread_is_incognito = True + thread_incognito_known = True + elif metadata_record is not None or pre_admission_verdict is False: + thread_is_incognito = False + thread_incognito_known = True + else: + thread_is_incognito = False + thread_incognito_known = False scheduler_capability = None if scheduler_tools_enabled(getattr(run_ctx, "app_config", None)): - client_timezone = await _client_timezone_from_context(body.context) - try: - scheduler_capability = await prepare_scheduler_capability( - request, - user=internal_owner_user or user, - thread_id=thread_id, - run_id=record.run_id, - assistant_id=scope_assistant_id, - original_user_text=human_text, - interaction_policy=resolve_run_interaction_policy(config), - scheduled_task_runtime=scheduled_task_runtime, - client_timezone=client_timezone, + if thread_incognito_known and not thread_is_incognito: + client_timezone = await _client_timezone_from_context(body.context) + try: + scheduler_capability = await prepare_scheduler_capability( + request, + user=internal_owner_user or user, + thread_id=thread_id, + run_id=record.run_id, + assistant_id=scope_assistant_id, + original_user_text=human_text, + interaction_policy=resolve_run_interaction_policy(config), + scheduled_task_runtime=scheduled_task_runtime, + client_timezone=client_timezone, + ) + except Exception: + logger.warning("Scheduler tool capability is unavailable for this run", exc_info=True) + elif not thread_incognito_known: + logger.warning( + "Scheduler capability withheld for %s: thread incognito state is unknown", + sanitize_log_param(thread_id), ) - except Exception: - logger.warning("Scheduler tool capability is unavailable for this run", exc_info=True) execution_context = replace(run_ctx, scheduler_capability=scheduler_capability) if scheduler_capability is not None else run_ctx artifact_imports = getattr(request.state, "extension_artifact_imports", None) artifact_lifetime = None @@ -2959,17 +3025,30 @@ async def verify_artifacts(): try: async with goal_thread_lock(thread_id): + # Recheck access and the thread's lifecycle under the same lock + # the delete route and the sweep take. A strict caller may have + # observed the thread before a concurrent delete removed it; + # the incognito read additionally refuses a tombstone or a + # deadline that passed while this request waited. Both happen + # before checkpoint-history seeding, which can write events. + if require_existing_thread and not await thread_access_allowed(): + raise HTTPException(status_code=404, detail=f"Thread {thread_id} not found") + incognito_verdict = await admission_thread_verdict() + if require_existing_thread and incognito_verdict is None: + raise HTTPException(status_code=404, detail=f"Thread {thread_id} not found") + if incognito_verdict is not None: + config.setdefault("context", {})[INCOGNITO_CONTEXT_KEY] = incognito_verdict await ensure_checkpoint_history_seeded( request, thread_id=thread_id, assistant_id=body.assistant_id, ) - # A strict caller may have observed the thread before a - # concurrent delete removed it while checkpoint preparation - # yielded. Recheck immediately before durable admission. The - # delete route holds a durable thread-operation reservation, - # so after this point either the run or the delete wins; they - # cannot both succeed across Gateway workers. + # Seeding yields and can write events. A strict caller may have + # observed the thread before a concurrent delete removed it in + # that window; recheck so the delete and the run cannot both + # succeed. The delete route holds a durable reservation, so + # after this point the run's own admission decides the winner + # across Gateway workers. if require_existing_thread and not await thread_access_allowed(): raise HTTPException(status_code=404, detail=f"Thread {thread_id} not found") admission_run_id = str(uuid.uuid4()) diff --git a/backend/docs/API.md b/backend/docs/API.md index b8aa5221866..77110f4bcfd 100644 --- a/backend/docs/API.md +++ b/backend/docs/API.md @@ -1493,9 +1493,104 @@ DELETE /api/threads/{thread_id} this response until the durable delete reservation is released or reconciled. In a single-worker deployment with ownership heartbeats disabled, a stranded reservation is reconciled at Gateway startup. +- `409` for an incognito thread (`Incognito chats cannot be deleted directly.`): + this route removes the metadata row, which would make the thread ID reusable, + and its purge is best-effort. Use `POST /api/threads/{thread_id}/incognito/end` + instead. An already-expired incognito thread answers `410`. Deleting a thread also removes every user's read marker for it. +### Incognito Threads + +An incognito chat is a temporary thread that never enters a listing surface, +search, project, share or the activity feed. The user-facing behavior is in +[Incognito Chats](../../docs/guide/incognito-chats.md); this section is the +wire contract. + +#### Create an Incognito Thread + +```http +POST /api/threads +Content-Type: application/json + +{ + "thread_id": "abc123", + "incognito": true +} +``` + +The response carries `"incognito": true`. Creation is server-restricted to an +authenticated browser session (or the auth-disabled local mode): a personal +access token, an internal/IM caller and an extension-launched request get +`403`, and `incognito.enabled: false` answers `403` for every caller. An +incognito thread cannot carry `project_id` (`400`). Repeating the create is +idempotent while the stored mode matches; a stored mode that differs answers +`409` (`Thread already exists with a different visibility mode`), and an +expired tombstone answers `410` (`This incognito thread has expired`). + +`metadata: {"incognito": true}` is accepted as the same creation intent as the +top-level field. The LangGraph SDK creates a thread implicitly on the first +submit and can only forward metadata, so the browser uses this marker to make +that implicit create match the incognito pre-create instead of conflicting +with it. The marker is a hint, not stored metadata; the response column is the +single source of truth. + +#### End an Incognito Thread + +```http +POST /api/threads/{thread_id}/incognito/end +``` + +Answers `204`. The Gateway schedules deletion after +`incognito.end_grace_seconds` in the background, capped by +`created_at + incognito.max_lifetime_seconds`, and the deadline no longer +moves. Repeating the request is idempotent and answers `204` again without +pushing the deadline out. `409` when the thread is not incognito. Once the +thread has expired it is no longer visible to its owner, so the route answers +`404` like any read; a deadline that passes mid-request answers `410`. + +**Lifetime.** `expires_at` moves forward on run admission and run completion +but never past `created_at + incognito.max_lifetime_seconds`. A deadline that +has already passed is final: a run finishing after it cannot push it out again, +and a tombstone is not revived by late status or title writes from a run that +was finalizing elsewhere. The worker also rechecks the thread row immediately +before the agent starts, so a run admitted concurrently with the sweep fails +instead of executing against purged data. An expired thread answers `404` on +read routes; the tombstone row keeps its ID from being reused. A run submitted +to an expired incognito thread is rejected with `404` before admission. If the +thread store cannot be read at that point, admission fails with `503` instead +of proceeding as an ordinary run, because the ordinary path would write +user-level memory and shared blobs. + +The sweep rechecks each deadline under the row lock before it tombstones a +thread, so a run that renewed a thread after the batch was read is left alone. +The sweep purges the thread directory, checkpoints, run and event records, +feedback, scheduled-task lines, tracked MCP task records, read markers, durable +subagent-batch rows and browser/MCP sessions through the same orchestration as +a user delete. A failed content step (runs, events, feedback, scheduled-task +lines, MCP tasks, read markers and batch rows) keeps `expires_at` set so the +next pass retries, and `expires_at` is cleared only after all of them succeed. +Browser and MCP sessions are runtime resources, so their teardown is +best-effort and is not retried. + +**REST backstops.** An incognito thread cannot be branched (`409`), moved into +a project (`409`), shared (`409`), deleted through `DELETE /api/threads/{id}` +(`409`, use the end route), or used as the `reuse_thread` target of a +scheduled task on create or update (`422`, error code +`incognito_thread_not_schedulable`). A chat run in an incognito thread binds no +scheduler capability, so `schedule_task` answers its existing +`scheduler_tools_disabled` `503` and the model tells the user it cannot create +tasks in this conversation. + +**Feature flag.** `GET /api/features` includes: + +```json +{ "incognito": { "enabled": true, "idle_ttl_seconds": 86400 } } +``` + +`enabled` gates the entry point; `idle_ttl_seconds` is the live idle window the +chat displays. + ### Thread Origin, Activity and Unread State Runs the server starts for a user (a schedule, an IM channel, a GitHub agent, diff --git a/backend/packages/harness/deerflow/agents/incognito_prompt.py b/backend/packages/harness/deerflow/agents/incognito_prompt.py new file mode 100644 index 00000000000..a9a26df6109 --- /dev/null +++ b/backend/packages/harness/deerflow/agents/incognito_prompt.py @@ -0,0 +1,92 @@ +"""System-prompt text for incognito runs. + +The block states the storage invariant instead of enumerating every closed +feature. A capability list would drift from the binding layer that actually +enforces it, and a feature that does not exist yet needs no rendering branch. +A change that makes an explicit exception to "nothing persistent leaves this +chat" changes the wording here, in one place, and nowhere else. +""" + +from typing import Literal + +IncognitoAudience = Literal["lead", "subagent"] + +_LEAD_INCOGNITO_SECTION = """ +This conversation is an incognito chat. It is temporary: neither it nor +anything derived from it can be made persistent from within the conversation. +It is deleted after a period of inactivity or when the user ends it. While it +runs, its messages and files live in storage scoped to this one thread and are +deleted with it; nothing from it appears in the chat list, archive, projects, +search, activity or shares. +If you reply in Chinese, call this mode 无痕模式 (the chat itself 无痕对话), +exactly as written; do not substitute other Chinese terms. +Do not use these Chinese terms in a reply in another language. + +You cannot add, update or delete memories in this chat. If existing memory +about the user is provided to you, or a memory search tool is available, you +may use it, but treat it as read-only. Do not call a memory write tool in this +chat, even when the user explicitly asks; explain the limitation instead. +Never say or imply that you saved, recorded, remembered or updated something +in the user's memory or profile, and never promise to remember it for a future +conversation. Working notes such as `task_note`, when available, are notes for +this conversation only; a "saved" result does not mean long-term memory. If the +user asks you to remember something, say this is an incognito chat so you +cannot write it to memory, and offer to do it in a normal chat. + +Do not create durable objects from this chat. For example, scheduled tasks, +branches, shares, project membership, side chats, durable subagent batches +(`batch_task`), and creating or editing skills or agent definitions are +unavailable here. If the user asks for one, explain briefly that an incognito +chat cannot create it and suggest a normal chat or the relevant page. If a tool +reports that it is unavailable in incognito chats, do not retry it and do not +look for a workaround. + +Everything that does not create a durable object still works: thread files and +uploads, artifacts, working notes, history search and read, web search, MCP +tools and subagents. Thread-scoped state lives only in this chat and is deleted +with it; tool outputs and viewed images stay in the thread workspace instead of +shared blob storage. + +A subagent you start runs under the same boundary. Do not ask it to save memory, +create durable objects or write skills, and do not trust a report that claims +something was persisted. Its results return to this chat and are deleted with +it. + +The promise covers DeerFlow's own storage: this chat leaves no conversation +content in the surfaces above. It does not cover third parties. Content still +goes to the configured model provider, search services and MCP servers, and a +tool that writes to an external service leaves a trace there that ending the +chat does not remove. Connecting an MCP server can also store its OAuth +credential at the deployment level; that credential belongs to the connection, +not this conversation. If the user asks whether something is "really gone", +draw this line instead of saying nothing was stored. + +The interface already shows these notices. Do not repeat them unless the user +asks or the limitation matters to the answer. +""" + +_SUBAGENT_INCOGNITO_SECTION = """ +You are running inside an incognito chat. The conversation is temporary: it is +deleted after a period of inactivity or when the user ends it, and nothing from +it may persist in DeerFlow outside this thread. + +- You cannot add, update or delete memories in this chat. If memory about the + user is provided or searchable, you may use it read-only. Do not call a + memory write tool, even when the task asks for it, and never claim that you + saved, recorded or remembered anything. Working notes such as `task_note` + are notes for this conversation, not long-term memory. +- Do not create durable objects: no scheduled tasks, shares, branches, project + membership, skill creation or edits, agent definition updates, or anything + else that would outlive the chat outside its thread. If a tool reports that + it is unavailable in incognito chats, do not retry it or work around it. +- Working files, artifacts, notes and tool results stay in the thread workspace + and are deleted with the chat. Search and MCP calls still happen externally; + their side effects are not undone when the chat ends. +- In your report, do not claim that anything was persisted beyond this + conversation. Return your results to the lead agent. +""" + + +def build_incognito_section(audience: IncognitoAudience = "lead") -> str: + """Return the incognito system-prompt block for the lead or a subagent.""" + return _SUBAGENT_INCOGNITO_SECTION if audience == "subagent" else _LEAD_INCOGNITO_SECTION diff --git a/backend/packages/harness/deerflow/agents/lead_agent/agent.py b/backend/packages/harness/deerflow/agents/lead_agent/agent.py index 208f233819a..38c01c0be55 100644 --- a/backend/packages/harness/deerflow/agents/lead_agent/agent.py +++ b/backend/packages/harness/deerflow/agents/lead_agent/agent.py @@ -990,12 +990,16 @@ def _complete_assembly( def _assemble_lead_agent(config: RunnableConfig, *, app_config: AppConfig) -> LeadAgentAssembly: # Lazy import to avoid circular dependency + from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY from deerflow.tools import get_available_tools from deerflow.tools.builtins import setup_agent, update_agent from deerflow.tools.builtins.tool_search import assemble_deferred_tools, build_mcp_routing_middleware, get_mcp_routing_hints_prompt_section from deerflow.tools.conversation import CONVERSATION_READER_CONTEXT_KEY cfg = _get_runtime_config(config) + # Admission pins the server-owned marker from the stored thread, so this + # run's prompt states the temporary-chat boundary exactly when it applies. + incognito = cfg.get(INCOGNITO_CONTEXT_KEY) is True resolved_app_config = app_config mode = (config.get("configurable", {}) or {}).get( INTERNAL_CHECKPOINT_MODE_KEY, @@ -1209,7 +1213,11 @@ def _assemble_lead_agent(config: RunnableConfig, *, app_config: AppConfig) -> Le skill_authorization=skill_authorization, ) chat_model = create_chat_model(name=model_name, thinking_enabled=thinking_enabled, app_config=resolved_app_config, attach_tracing=False) - raw_tools = get_available_tools(model_name=model_name, subagent_enabled=subagent_enabled, app_config=resolved_app_config, chat_model=chat_model) + [setup_agent] + # Agent creation is durable by definition: it writes a per-user agent + # record and SOUL.md outside the chat. An incognito run must not leave + # that behind, so the bootstrap flow does not expose the tool at all. + bootstrap_tools = get_available_tools(model_name=model_name, subagent_enabled=subagent_enabled, app_config=resolved_app_config, chat_model=chat_model, incognito=incognito) + raw_tools = bootstrap_tools if incognito else [*bootstrap_tools, setup_agent] configured_tools = raw_tools configured_tools = [tool for tool in configured_tools if tool.name not in interaction_policy.disabled_tool_names] authorization_candidates = [*configured_tools] @@ -1286,6 +1294,7 @@ def _assemble_lead_agent(config: RunnableConfig, *, app_config: AppConfig) -> Le subagent_execution_capacity=subagent_execution_capacity, interaction_policy=interaction_policy, memory_enabled=memory_enabled, + incognito=incognito, bash_available=has_bash_tool(authorized_tools), ) bound_middlewares = normalize_middleware_state_schemas(middlewares, mode) @@ -1358,7 +1367,9 @@ def _assemble_lead_agent(config: RunnableConfig, *, app_config: AppConfig) -> Le # leave it unset, so ``update_agent`` remains available there. channel_name = cfg.get("channel_name") is_webhook_channel = channel_name in _WEBHOOK_CHANNELS - extra_tools = [update_agent] if agent_name and not is_webhook_channel else [] + # An incognito run must not mutate the persisted agent either: the change + # outlives the chat and is visible in every later ordinary conversation. + extra_tools = [update_agent] if agent_name and not is_webhook_channel and not incognito else [] # Resolve the model once so tool guidance uses the same effective settings. chat_model = create_chat_model(name=model_name, thinking_enabled=thinking_enabled, reasoning_effort=reasoning_effort, app_config=resolved_app_config, attach_tracing=False, model_overrides=agent_model_overrides) raw_tools = get_available_tools( @@ -1366,6 +1377,7 @@ def _assemble_lead_agent(config: RunnableConfig, *, app_config: AppConfig) -> Le groups=agent_config.tool_groups if agent_config else None, mcp_plugins=getattr(agent_config, "mcp_plugins", None), subagent_enabled=subagent_enabled, + incognito=incognito, include_conversation_reader=callable(cfg.get(CONVERSATION_READER_CONTEXT_KEY)) and not bool(cfg.get("is_subagent")), **({"scheduler_capability": scheduler_capability} if scheduler_capability is not None else {}), app_config=resolved_app_config, @@ -1443,6 +1455,7 @@ def _assemble_lead_agent(config: RunnableConfig, *, app_config: AppConfig) -> Le subagent_execution_capacity=subagent_execution_capacity, interaction_policy=interaction_policy, memory_enabled=memory_enabled, + incognito=incognito, bash_available=has_bash_tool(authorized_tools), ) bound_middlewares = normalize_middleware_state_schemas(middlewares, mode) diff --git a/backend/packages/harness/deerflow/agents/lead_agent/prompt.py b/backend/packages/harness/deerflow/agents/lead_agent/prompt.py index 4394b3dd00e..16a637a8e9b 100644 --- a/backend/packages/harness/deerflow/agents/lead_agent/prompt.py +++ b/backend/packages/harness/deerflow/agents/lead_agent/prompt.py @@ -10,6 +10,7 @@ from functools import lru_cache from typing import TYPE_CHECKING, Any +from deerflow.agents.incognito_prompt import build_incognito_section from deerflow.agents.interaction_policy import RunInteractionPolicy from deerflow.config.agents_config import load_agent_soul from deerflow.config.shared_reset_marker import SharedResetChange, SharedResetMarker, SharedResetMarkerTracker, resolve_shared_config_path @@ -713,7 +714,7 @@ def _build_subagent_section( {skills_section} {memory_tool_section} - +{incognito_section} {deferred_tools_section} @@ -1147,6 +1148,7 @@ def apply_prompt_template( memory_enabled: bool = True, interaction_policy: RunInteractionPolicy | None = None, bash_available: bool = True, + incognito: bool = False, ) -> str: interaction_policy = interaction_policy or RunInteractionPolicy.interactive() # Include subagent section only if enabled (from runtime parameter) @@ -1171,7 +1173,9 @@ def apply_prompt_template( total, app_config=app_config, allowed_subagents=allowed_subagents, - batch_enabled=is_subagent_batch_runtime_available(), + # Durable batch tools are withheld in incognito runs, so the prompt + # must not advertise a mode the run cannot dispatch. + batch_enabled=is_subagent_batch_runtime_available() and not incognito, lead_bash_available=bash_available, ) else: @@ -1228,6 +1232,9 @@ def apply_prompt_template( ) memory_tool_section = _build_memory_tool_section(app_config=app_config, memory_enabled=memory_enabled) + # The incognito block follows the memory guidance so its write restriction + # overrides the tool-mode instructions above it instead of being overridden. + incognito_section = build_incognito_section("lead") if incognito else "" # Script guidance only helps when a tool can run the script. Without `bash` (the default # LocalSandboxProvider has host bash off) models wrote helper scripts nothing could run. @@ -1254,6 +1261,7 @@ def apply_prompt_template( mcp_routing_hints_section=mcp_routing_hints_section, subagent_section=subagent_section, memory_tool_section=memory_tool_section, + incognito_section=incognito_section, subagent_reminder=subagent_reminder, skill_first_reminder=skill_first_reminder, subagent_thinking=subagent_thinking, diff --git a/backend/packages/harness/deerflow/agents/memory/summarization_hook.py b/backend/packages/harness/deerflow/agents/memory/summarization_hook.py index e23645b59ff..49eab4e35f4 100644 --- a/backend/packages/harness/deerflow/agents/memory/summarization_hook.py +++ b/backend/packages/harness/deerflow/agents/memory/summarization_hook.py @@ -8,6 +8,7 @@ from deerflow.agents.middlewares.summarization_middleware import SummarizationEvent from deerflow.config.memory_config import get_memory_config from deerflow.config.pii_redaction_config import PiiRedactionConfig +from deerflow.runtime.context_keys import is_incognito_runtime from deerflow.runtime.user_context import resolve_runtime_user_id @@ -24,6 +25,8 @@ def memory_flush_hook(event: SummarizationEvent, pii_redaction_config: PiiRedact """ if not get_memory_config().enabled or not event.thread_id: return + if is_incognito_runtime(event.runtime): + return user_id = resolve_runtime_user_id(event.runtime) get_memory_manager().add_nowait( diff --git a/backend/packages/harness/deerflow/agents/memory/tools.py b/backend/packages/harness/deerflow/agents/memory/tools.py index d8dcf24e002..f9aeabb1255 100644 --- a/backend/packages/harness/deerflow/agents/memory/tools.py +++ b/backend/packages/harness/deerflow/agents/memory/tools.py @@ -22,11 +22,14 @@ from langchain.tools import tool from deerflow.agents.memory.manager import get_memory_manager +from deerflow.runtime.context_keys import is_incognito_runtime from deerflow.runtime.user_context import resolve_runtime_user_id from deerflow.tools.types import Runtime logger = logging.getLogger(__name__) +_INCOGNITO_WRITE_ERROR = "Memory writes are disabled in incognito chats" + def _resolve_scope(runtime: Runtime | None = None) -> tuple[str | None, str]: """Resolve agent_name and user_id for tool handler scope. @@ -142,6 +145,8 @@ def memory_add_tool( JSON string with "fact_id" and "status": "added". On duplicate content, returns "error" with explanation. """ + if is_incognito_runtime(runtime): + return json.dumps({"error": _INCOGNITO_WRITE_ERROR}) agent_name, user_id = _resolve_scope(runtime) try: normalized_content = content.strip() @@ -214,6 +219,8 @@ def memory_update_tool( JSON string with "fact_id" and "status": "updated". On invalid fact_id, returns "error" with explanation. """ + if is_incognito_runtime(runtime): + return json.dumps({"error": _INCOGNITO_WRITE_ERROR}) agent_name, user_id = _resolve_scope(runtime) try: manager = get_memory_manager() @@ -252,6 +259,8 @@ def memory_delete_tool(runtime: Runtime, fact_id: str) -> str: JSON string with "fact_id" and "status": "deleted". On invalid fact_id, returns "error" with explanation. """ + if is_incognito_runtime(runtime): + return json.dumps({"error": _INCOGNITO_WRITE_ERROR}) agent_name, user_id = _resolve_scope(runtime) try: manager = get_memory_manager() diff --git a/backend/packages/harness/deerflow/agents/middlewares/input_sanitization_middleware.py b/backend/packages/harness/deerflow/agents/middlewares/input_sanitization_middleware.py index fa3b3400613..9243521da67 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/input_sanitization_middleware.py +++ b/backend/packages/harness/deerflow/agents/middlewares/input_sanitization_middleware.py @@ -127,6 +127,11 @@ "client_context", # Run-scoped language preference emitted by DynamicContextMiddleware. "response_language_preference", + # Incognito chat section emitted by agents/incognito_prompt.py into the + # lead-agent and every subagent system prompt. It declares the run's + # storage boundary, so forging it in untrusted input could impersonate + # the framework's persistence restrictions. + "incognito_mode", # Common prompt-injection tag patterns "system", "instruction", diff --git a/backend/packages/harness/deerflow/agents/middlewares/memory_middleware.py b/backend/packages/harness/deerflow/agents/middlewares/memory_middleware.py index 074d7019d46..f35fe33cd24 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/memory_middleware.py +++ b/backend/packages/harness/deerflow/agents/middlewares/memory_middleware.py @@ -16,6 +16,7 @@ from deerflow.agents.middlewares.pii_redaction_middleware import _make_redactor, _redact_content, _Redactor from deerflow.config.memory_config import get_memory_config from deerflow.config.pii_redaction_config import PiiRedactionConfig +from deerflow.runtime.context_keys import is_incognito_runtime from deerflow.runtime.user_context import resolve_runtime_user_id from deerflow.trace_context import DEERFLOW_TRACE_METADATA_KEY, resolve_trace_id from deerflow.utils.messages import ORIGINAL_USER_CONTENT_KEY @@ -198,6 +199,9 @@ def _resolve_add_args(self, state: MemoryMiddlewareState, runtime: Runtime) -> t config = self._memory_config or get_memory_config() if not config.enabled: return None + if is_incognito_runtime(runtime): + logger.debug("Incognito run, skipping memory update") + return None # Get thread ID from runtime context first, then fall back to LangGraph's configurable metadata thread_id = runtime.context.get("thread_id") if runtime.context else None diff --git a/backend/packages/harness/deerflow/agents/middlewares/tool_output_budget_middleware.py b/backend/packages/harness/deerflow/agents/middlewares/tool_output_budget_middleware.py index 493dd93e7de..f4ed5e64ba1 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/tool_output_budget_middleware.py +++ b/backend/packages/harness/deerflow/agents/middlewares/tool_output_budget_middleware.py @@ -53,6 +53,7 @@ from deerflow.config.summarization_config import DEFAULT_SKILL_FILE_READ_TOOL_NAMES from deerflow.config.tool_output_config import ToolOutputConfig from deerflow.constants import DEFAULT_SKILLS_CONTAINER_PATH, WRITE_ELISION_PLACEHOLDER_TEMPLATE +from deerflow.runtime.context_keys import is_incognito_runtime from deerflow.sandbox.lease import run_sync_lifecycle_operation from deerflow.sandbox.sandbox_provider import get_sandbox_provider from deerflow.storage import BlobRef, BlobStoreError, get_blob_store_if_enabled @@ -538,11 +539,14 @@ def _budget_content( config: ToolOutputConfig, sandbox: Sandbox | None = None, thread_id: str | None = None, + persist_blobs: bool = True, ) -> _BudgetedContent | None: """Apply budget to *content* and name the applied transform. Returns the replacement, transform kind, and optional durable blob - metadata, or ``None`` if no change was needed. + metadata, or ``None`` if no change was needed. ``persist_blobs`` is False + for incognito runs: the output still externalizes into the thread's own + outputs directory, but no copy enters the shared blob store. """ threshold = config.tool_overrides.get(tool_name, config.externalize_min_chars) if threshold <= 0 and config.fallback_max_chars <= 0: @@ -587,7 +591,7 @@ def _budget_content( host_outputs_path = outputs_path if host_outputs_path is not None: - blob_store = get_blob_store_if_enabled() + blob_store = get_blob_store_if_enabled() if persist_blobs else None try: blob_bytes = content.encode("utf-8") if blob_store is not None else None except UnicodeEncodeError: @@ -695,6 +699,8 @@ def _patch_tool_message( outputs_path: str | None, sandbox: Sandbox | None = None, thread_id: str | None = None, + *, + persist_blobs: bool = True, ) -> ToolMessage: """Apply budget to a single ToolMessage. Returns the original if unchanged.""" tool_name = msg.name or "unknown" @@ -713,6 +719,7 @@ def _patch_tool_message( config=config, sandbox=sandbox, thread_id=thread_id, + persist_blobs=persist_blobs, ) update: dict[str, Any] = {} trigger = _effective_trigger(tool_name, config) @@ -793,10 +800,12 @@ def _patch_result( outputs_path: str | None, sandbox: Sandbox | None = None, thread_id: str | None = None, + *, + persist_blobs: bool = True, ) -> ToolMessage | Command: """Apply budget to a tool call result (ToolMessage or Command).""" if isinstance(result, ToolMessage): - return _patch_tool_message(result, config, outputs_path, sandbox, thread_id) + return _patch_tool_message(result, config, outputs_path, sandbox, thread_id, persist_blobs=persist_blobs) update = getattr(result, "update", None) if not isinstance(update, dict): @@ -804,7 +813,7 @@ def _patch_result( messages = update.get("messages") if isinstance(messages, ToolMessage): - patched = _patch_tool_message(messages, config, outputs_path, sandbox, thread_id) + patched = _patch_tool_message(messages, config, outputs_path, sandbox, thread_id, persist_blobs=persist_blobs) return result if patched is messages else dc_replace(result, update={**update, "messages": patched}) if not isinstance(messages, (list, tuple)): return result @@ -813,7 +822,7 @@ def _patch_result( changed = False for msg in messages: if isinstance(msg, ToolMessage): - patched = _patch_tool_message(msg, config, outputs_path, sandbox, thread_id) + patched = _patch_tool_message(msg, config, outputs_path, sandbox, thread_id, persist_blobs=persist_blobs) if patched is not msg: changed = True new_messages.append(patched) @@ -1202,6 +1211,7 @@ def wrap_tool_call( outputs_path, sandbox, _resolve_thread_id(request), + persist_blobs=not is_incognito_runtime(getattr(request, "runtime", None)), ) return _record_visible_skill_usage(result, request, skill_read_tool_names=self._skill_read_tool_names, skills_root=self._skills_root) @@ -1225,6 +1235,7 @@ async def awrap_tool_call( outputs_path, sandbox, _resolve_thread_id(request), + persist_blobs=not is_incognito_runtime(getattr(request, "runtime", None)), ) return _record_visible_skill_usage(result, request, skill_read_tool_names=self._skill_read_tool_names, skills_root=self._skills_root) diff --git a/backend/packages/harness/deerflow/config/app_config.py b/backend/packages/harness/deerflow/config/app_config.py index 631b6582a73..4fef522a882 100644 --- a/backend/packages/harness/deerflow/config/app_config.py +++ b/backend/packages/harness/deerflow/config/app_config.py @@ -29,6 +29,7 @@ from deerflow.config.guardrails_config import GuardrailsConfig, load_guardrails_config_from_dict from deerflow.config.harness_guard_config import HarnessGuardConfig from deerflow.config.hitl_approval_config import HitlApprovalConfig +from deerflow.config.incognito_config import IncognitoThreadsConfig from deerflow.config.input_polish_config import InputPolishConfig from deerflow.config.knowledge_base_config import KnowledgeBaseConfig from deerflow.config.loop_detection_config import LoopDetectionConfig @@ -342,6 +343,7 @@ def _unique_mcp_agent_grants(cls, bindings: dict[str, McpAgentCredentialBinding] read_before_write: ReadBeforeWriteConfig = Field(default_factory=ReadBeforeWriteConfig, description="Read-before-write file gate middleware configuration") harness_guard: HarnessGuardConfig = Field(default_factory=HarnessGuardConfig, description="HarnessGuard tool-loop interceptor middleware configuration") projects: ProjectsConfig = Field(default_factory=ProjectsConfig, description="User projects configuration (instructions injection, shelf index, trash retention)") + incognito: IncognitoThreadsConfig = Field(default_factory=IncognitoThreadsConfig, description="Incognito (temporary) chat threads lifetime and sweep configuration") pii_redaction: PiiRedactionConfig = Field(default_factory=PiiRedactionConfig, description="PII redaction middleware configuration (issue #3190)") safety_finish_reason: SafetyFinishReasonConfig = Field(default_factory=SafetyFinishReasonConfig, description="Provider safety-filter finish_reason interception middleware configuration") auth: AuthAppConfig = Field(default_factory=AuthAppConfig, description="Authentication configuration (local + OIDC SSO)") diff --git a/backend/packages/harness/deerflow/config/incognito_config.py b/backend/packages/harness/deerflow/config/incognito_config.py new file mode 100644 index 00000000000..ab73968df8c --- /dev/null +++ b/backend/packages/harness/deerflow/config/incognito_config.py @@ -0,0 +1,74 @@ +"""Configuration for incognito (temporary) chat threads.""" + +from __future__ import annotations + +from pydantic import BaseModel, Field, model_validator + +_MAX_LIFETIME_SECONDS = 365 * 24 * 60 * 60 + + +class IncognitoThreadsConfig(BaseModel): + """Lifetime and sweep settings for incognito threads. + + An incognito thread is invisible to every list, search, project and share + surface; it exists only for its owner until the lifetime sweep deletes it. + ``expires_at`` is renewed on activity to ``min(now + idle_ttl_seconds, + created_at + max_lifetime_seconds)``, so an idle thread disappears after + the idle window and a long-lived one still disappears after the absolute + maximum. Creation and an explicit end use the same ceiling, and the idle + window may not exceed it; setting both equal means the absolute lifetime + alone decides. + + The idle floor is one hour because renewal happens on runs only: typing, + reading or leaving the window open is not activity, and a window shorter + than a single run would expire the chat right after the answer. The + end grace has the same one-year upper bound as the absolute lifetime + because the Gateway adds the grace to the current time before applying + the lifetime cap. + """ + + enabled: bool = Field( + default=True, + description="Operator switch. When disabled, clients cannot create incognito threads.", + ) + idle_ttl_seconds: int = Field( + default=24 * 60 * 60, + ge=60 * 60, + description="Idle window after the last run before an incognito thread is deleted.", + ) + end_grace_seconds: int = Field( + default=60 * 60, + ge=0, + le=_MAX_LIFETIME_SECONDS, + description="Grace period after an explicit end before the thread and its data are purged.", + ) + max_lifetime_seconds: int = Field( + default=7 * 24 * 60 * 60, + ge=60 * 60, + le=_MAX_LIFETIME_SECONDS, + description="Absolute lifetime ceiling measured from creation, regardless of activity.", + ) + sweep_interval_seconds: int = Field( + default=60, + ge=5, + le=3600, + description="How often the Gateway scans for expired incognito threads.", + ) + sweep_batch_size: int = Field( + default=100, + ge=1, + le=1000, + description="Maximum expired incognito threads deleted per sweep batch.", + ) + + @model_validator(mode="after") + def _idle_window_fits_within_lifetime(self) -> IncognitoThreadsConfig: + """Reject an idle window longer than the absolute lifetime. + + The pair would contradict itself: creation would schedule a deadline + past the ceiling and the first activity renewal would pin it back, so + ``idle_ttl_seconds`` would silently do nothing. + """ + if self.idle_ttl_seconds > self.max_lifetime_seconds: + raise ValueError(f"incognito.idle_ttl_seconds ({self.idle_ttl_seconds}) must not exceed incognito.max_lifetime_seconds ({self.max_lifetime_seconds})") + return self diff --git a/backend/packages/harness/deerflow/persistence/mcp_tasks/sql.py b/backend/packages/harness/deerflow/persistence/mcp_tasks/sql.py index ff2ad188bd3..f42cf9cbedc 100644 --- a/backend/packages/harness/deerflow/persistence/mcp_tasks/sql.py +++ b/backend/packages/harness/deerflow/persistence/mcp_tasks/sql.py @@ -6,7 +6,7 @@ from datetime import UTC, datetime, timedelta from typing import Any, Literal -from sqlalchemy import and_, case, or_, select, text, update +from sqlalchemy import and_, case, delete, or_, select, text, update from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker @@ -297,6 +297,23 @@ async def list_by_thread( result = await session.execute(stmt) return [self._row_to_dict(row) for row in result.scalars()] + async def delete_by_thread(self, thread_id: str, *, user_id: str | None) -> int: + """Delete every tracked MCP task for a thread; return the row count. + + Thread lifecycle cleanup is not incarnation-scoped: a purge must also + remove rows left by an earlier incarnation, or their result payloads + (the tool output the user asked to forget) outlive the thread. A + ``None`` owner purges the thread across owners, as the migration and + CLI callers require; an explicit owner scopes the delete to that user. + """ + stmt = delete(McpTaskRow).where(McpTaskRow.thread_id == thread_id) + if user_id is not None: + stmt = stmt.where(McpTaskRow.user_id == user_id) + async with self._sf() as session: + result = await session.execute(stmt) + await session.commit() + return int(result.rowcount or 0) + async def claim_due_tasks( self, *, diff --git a/backend/packages/harness/deerflow/persistence/migrations/versions/0056_incognito_threads.py b/backend/packages/harness/deerflow/persistence/migrations/versions/0056_incognito_threads.py new file mode 100644 index 00000000000..61a1ca36f52 --- /dev/null +++ b/backend/packages/harness/deerflow/persistence/migrations/versions/0056_incognito_threads.py @@ -0,0 +1,47 @@ +"""Add incognito markers to ``threads_meta``. + +``incognito`` marks a thread that must never surface in a thread list, search +result, project, archive view or share. ``expires_at`` is the deadline the +incognito lifetime sweep compares against the database clock. + +Both columns are nullable with no server default: a binary sharing the database +during a rolling upgrade keeps inserting and reading rows, and NULL reads as +"not incognito". The composite index backs the sweep's +``incognito = true AND expires_at <= now`` predicate. +""" + +import sqlalchemy as sa +from alembic import op + +revision = "0056_incognito_threads" +down_revision = "0055_thread_shares" +branch_labels = None +depends_on = None + +_TABLE = "threads_meta" +_INDEX = "ix_threads_meta_incognito_expires_at" + + +def _has_index() -> bool: + inspector = sa.inspect(op.get_bind()) + if _TABLE not in inspector.get_table_names(): + return False + return _INDEX in {index["name"] for index in inspector.get_indexes(_TABLE)} + + +def upgrade(): + from deerflow.persistence.migrations._helpers import safe_add_column + + safe_add_column(_TABLE, sa.Column("incognito", sa.Boolean(), nullable=True)) + safe_add_column(_TABLE, sa.Column("expires_at", sa.DateTime(timezone=True), nullable=True)) + if not _has_index(): + op.create_index(_INDEX, _TABLE, ["incognito", "expires_at"]) + + +def downgrade(): + from deerflow.persistence.migrations._helpers import safe_drop_column + + if _has_index(): + op.drop_index(_INDEX, table_name=_TABLE) + safe_drop_column(_TABLE, "expires_at") + safe_drop_column(_TABLE, "incognito") diff --git a/backend/packages/harness/deerflow/persistence/subagent_batches/sql.py b/backend/packages/harness/deerflow/persistence/subagent_batches/sql.py index 791563ada0e..8f2592979b6 100644 --- a/backend/packages/harness/deerflow/persistence/subagent_batches/sql.py +++ b/backend/packages/harness/deerflow/persistence/subagent_batches/sql.py @@ -5,7 +5,7 @@ from datetime import UTC, datetime, timedelta from typing import Any -from sqlalchemy import func, or_, select, update +from sqlalchemy import delete, func, or_, select, update from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker from sqlalchemy.orm import aliased, defer @@ -399,6 +399,36 @@ async def suppress_thread_continuations(self, thread_id: str, *, goal_created_at ) await session.commit() + async def delete_by_thread(self, thread_id: str, *, user_id: str) -> int: + """Delete every batch row of one thread; return the batch count removed. + + Called by ``purge_thread_data`` after ``suppress_thread_continuations`` + has fenced in-flight continuations. Suppression only flips + ``continuation_status``; the rows — including each item's ``prompt`` + text and the batch ``execution_spec`` — stay readable. An incognito + thread is swept and a user delete must leave nothing behind, so the rows + go too. ``user_id`` scopes the delete to the owner (the same convention + the feedback and task-event repos follow): batches belong to one user, + and purge always knows the owner. + + Rows are removed dependency-first (dependencies → items → batches) + rather than relying on the ``ondelete=CASCADE`` foreign keys, so the + result is identical on a backend where cascade is not enforced. + """ + async with self._sf() as session: + batch_ids = list((await session.scalars(select(SubagentBatchRow.id).where(SubagentBatchRow.thread_id == thread_id, SubagentBatchRow.user_id == user_id))).all()) + if not batch_ids: + return 0 + item_ids = select(SubagentBatchItemRow.id).where(SubagentBatchItemRow.batch_id.in_(batch_ids)) + await session.execute(delete(SubagentBatchDependencyRow).where(or_(SubagentBatchDependencyRow.item_id.in_(item_ids), SubagentBatchDependencyRow.prerequisite_id.in_(item_ids)))) + await session.execute(delete(SubagentBatchItemRow).where(SubagentBatchItemRow.batch_id.in_(batch_ids))) + await session.execute(delete(SubagentBatchRow).where(SubagentBatchRow.id.in_(batch_ids))) + # Drop the continuation fence rows too; they are keyed by batch id + # and would otherwise outlive the batches they guarded. + await session.execute(delete(ExtensionExecutionLeaseRow).where(ExtensionExecutionLeaseRow.namespace == BATCH_CONTINUATION_NAMESPACE, ExtensionExecutionLeaseRow.resource_id.in_(batch_ids))) + await session.commit() + return len(batch_ids) + async def latest_run_state(self, thread_id: str, *, user_id: str) -> dict | None: async with self._sf() as session: row = ( diff --git a/backend/packages/harness/deerflow/persistence/thread_meta/__init__.py b/backend/packages/harness/deerflow/persistence/thread_meta/__init__.py index ef45175250a..7c367546128 100644 --- a/backend/packages/harness/deerflow/persistence/thread_meta/__init__.py +++ b/backend/packages/harness/deerflow/persistence/thread_meta/__init__.py @@ -4,7 +4,20 @@ from typing import TYPE_CHECKING -from deerflow.persistence.thread_meta.base import PROJECT_FILTER_UNSET, THREAD_ARCHIVED_METADATA_KEY, THREAD_PINNED_METADATA_KEY, THREAD_PROJECT_METADATA_KEY, InvalidMetadataFilterError, ThreadMetaStore, ThreadOwnershipConflictError +from deerflow.persistence.thread_meta.base import ( + PROJECT_FILTER_UNSET, + THREAD_ARCHIVED_METADATA_KEY, + THREAD_INCOGNITO_ENDED_METADATA_KEY, + THREAD_INCOGNITO_EXPIRED_STATUS, + THREAD_PINNED_METADATA_KEY, + THREAD_PROJECT_METADATA_KEY, + InvalidMetadataFilterError, + ThreadCreateConflictError, + ThreadMetaStore, + ThreadOwnershipConflictError, + incognito_deadline, + is_incognito_expired, +) from deerflow.persistence.thread_meta.memory import MemoryThreadMetaStore from deerflow.persistence.thread_meta.model import ThreadMetaRow from deerflow.persistence.thread_meta.sql import ThreadMetaRepository @@ -17,6 +30,8 @@ "InvalidMetadataFilterError", "MemoryThreadMetaStore", "PROJECT_FILTER_UNSET", + "THREAD_INCOGNITO_ENDED_METADATA_KEY", + "THREAD_INCOGNITO_EXPIRED_STATUS", "THREAD_PINNED_METADATA_KEY", "THREAD_ARCHIVED_METADATA_KEY", "THREAD_PINNED_METADATA_KEY", @@ -24,7 +39,10 @@ "ThreadMetaRepository", "ThreadMetaRow", "ThreadMetaStore", + "ThreadCreateConflictError", "ThreadOwnershipConflictError", + "incognito_deadline", + "is_incognito_expired", "make_thread_store", ] diff --git a/backend/packages/harness/deerflow/persistence/thread_meta/base.py b/backend/packages/harness/deerflow/persistence/thread_meta/base.py index cc68650fc16..e2e21e0acd9 100644 --- a/backend/packages/harness/deerflow/persistence/thread_meta/base.py +++ b/backend/packages/harness/deerflow/persistence/thread_meta/base.py @@ -15,6 +15,8 @@ from __future__ import annotations import abc +from collections.abc import Mapping, Sequence +from datetime import UTC, datetime, timedelta from typing import Any, ClassVar, Final from deerflow.runtime.user_context import AUTO, _AutoSentinel @@ -25,6 +27,66 @@ THREAD_PINNED_METADATA_KEY = "deerflow_pinned" THREAD_ARCHIVED_METADATA_KEY = "deerflow_archived" +# Server-only metadata key: set when the owner explicitly ends an incognito +# thread, so the activity renewal that run completion performs cannot extend a +# thread the user has already closed. Clients cannot write it (the Gateway +# strips server-reserved keys from every request body). +THREAD_INCOGNITO_ENDED_METADATA_KEY = "deerflow_incognito_ended" + +# ``status`` value of an incognito row whose data has been (or is being) +# purged. The row itself stays as a tombstone: deleting it would let the same +# thread id be created again as an ordinary thread, and read routes would +# answer a 200 with empty content instead of reporting the thread as gone. +THREAD_INCOGNITO_EXPIRED_STATUS = "expired" + + +def _as_utc(value: object) -> datetime | None: + """Parse a stored timestamp (datetime or ISO string) as UTC.""" + if isinstance(value, datetime): + return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC) + if isinstance(value, str) and value: + try: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError: + return None + return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC) + return None + + +def is_incognito_expired(record: Mapping[str, Any], *, now: datetime | None = None) -> bool: + """Return whether *record* is an incognito thread past its lifetime. + + Two states count as expired: the tombstone the sweep writes before it + purges data (``status == "expired"``), and a live row whose ``expires_at`` + deadline already passed but which the sweep has not reached yet. From the + owner's point of view an incognito thread disappears the moment its + deadline passes, not at the next sweep. + """ + if record.get("incognito") is not True: + return False + if record.get("status") == THREAD_INCOGNITO_EXPIRED_STATUS: + return True + deadline = _as_utc(record.get("expires_at")) + return deadline is not None and deadline <= (now or datetime.now(UTC)) + + +def incognito_deadline( + *, + now: datetime, + created_at: datetime, + window: timedelta, + max_lifetime: timedelta, +) -> datetime: + """Return the earlier of a renewal window and the absolute lifetime. + + ``window`` is the idle window on an activity renewal and the end grace + period when the owner ends the chat. Every write that moves + ``expires_at`` goes through this function, so ``max_lifetime`` is a true + ceiling rather than a rule only renewals respect. + """ + return min(now + window, created_at + max_lifetime) + + # Cross-component metadata key. Keep in sync with # ``frontend/src/core/threads/utils.ts`` and # ``frontend/tests/e2e/utils/mock-api.ts``. @@ -56,6 +118,18 @@ class ThreadOwnershipConflictError(Exception): """Raised when create would overwrite a thread owned by another user.""" +class ThreadCreateConflictError(Exception): + """Raised when create would overwrite a row the caller must not replace. + + The memory store historically overwrote a duplicate id, while the SQL + store's primary key rejects the insert. An incognito row is the one record + that must survive external writes: overwriting a tombstone would let the + id be reused, and overwriting a live incognito row would silently convert + or extend it. A store raises this instead, and the Gateway resolves the + existing row through its idempotent-create path (410 expired, 409 mode + mismatch, or the existing row itself).""" + + class ThreadMetaStore(abc.ABC): @abc.abstractmethod async def create( @@ -67,10 +141,18 @@ async def create( display_name: str | None = None, metadata: dict | None = None, project_id: str | None = None, + incognito: bool = False, + expires_at: datetime | None = None, ) -> dict: """Create a thread row; when ``project_id`` is set, validate the project inside the insert transaction and raise - ``ProjectNotAssignableError`` on failure (no partial row).""" + ``ProjectNotAssignableError`` on failure (no partial row). + + ``incognito`` marks a thread that must never appear in a thread list, + search result, project, archive view or share; ``expires_at`` is the + absolute deadline its lifetime sweep uses. Ordinary mutators never + touch either field: only the lifecycle methods below move the deadline + and the tombstone.""" @abc.abstractmethod async def claim_unowned(self, thread_id: str, owner: str) -> bool: @@ -107,6 +189,9 @@ async def search( ) -> list[dict[str, Any]]: """Search threads. + Incognito threads are never returned, regardless of filters: the only + way to reach one is by its exact thread id through :meth:`get`. + ``archived=None`` includes all threads; False includes legacy rows without a true archive flag. Filtering precedes pagination. @@ -125,10 +210,24 @@ async def update_display_name( remove_metadata_keys: tuple[str, ...] = (), user_id: str | None | _AutoSentinel = AUTO, ) -> None: + """Update the display name and remove caller-selected stale metadata. + + Must be a no-op for an incognito tombstone (``status="expired"``): run + finalization on another worker can reach it after the sweep purged the + thread, and writing the title back would leave content on a row that + reads no longer resolve. + """ pass @abc.abstractmethod async def update_status(self, thread_id: str, status: str, *, user_id: str | None | _AutoSentinel = AUTO) -> None: + """Update the run status. + + Like :meth:`update_display_name`, this must never overwrite an + incognito tombstone. A resurrected row would resolve for its owner + again while ``expires_at`` is already cleared, so the sweep would never + select it for deletion. + """ pass @abc.abstractmethod @@ -163,3 +262,87 @@ async def check_access(self, thread_id: str, user_id: str, *, require_existing: @abc.abstractmethod async def delete(self, thread_id: str, *, user_id: str | None | _AutoSentinel = AUTO) -> None: pass + + # ------------------------------------------------------------------ + # Incognito lifetime + # + # These have no-op defaults rather than ``@abc.abstractmethod`` so a + # third-party store written before incognito existed keeps instantiating. + # Such a store simply never expires a thread; both stores shipped with + # DeerFlow implement the full lifecycle. + # ------------------------------------------------------------------ + + async def incognito_ids(self, thread_ids: Sequence[str], *, user_id: str | None | _AutoSentinel = AUTO) -> set[str]: + """Return the subset of ``thread_ids`` that name incognito threads. + + The run-activity feed must never list an incognito thread, and it + holds a page of ids rather than records; this lets it filter them in + one call. Missing and foreign rows are not returned. The base + implementation performs one owner-scoped :meth:`get` per id; the SQL + store overrides it with a single query. + """ + found: set[str] = set() + for thread_id in thread_ids: + record = await self.get(thread_id, user_id=user_id) + if record is not None and record.get("incognito") is True: + found.add(thread_id) + return found + + async def list_due_incognito(self, *, now: datetime | None = None, limit: int = 100) -> list[dict[str, Any]]: + """Return incognito rows whose deadline passed, oldest deadline first. + + The lifetime sweep calls this with no owner scope: expiry is a + server-side lifecycle, not a user action. + """ + return [] + + async def renew_incognito( + self, + thread_id: str, + *, + idle_ttl: timedelta, + max_lifetime: timedelta, + now: datetime | None = None, + user_id: str | None | _AutoSentinel = AUTO, + ) -> bool: + """Push the deadline to ``min(now + idle_ttl, created_at + max_lifetime)``. + + Called on run admission and run completion, i.e. exactly when the + thread is active. Moving to an earlier deadline is allowed (the + absolute ceiling wins) but never extends a thread beyond it. Returns + ``False`` for missing/non-incognito/tombstoned rows, for a row whose + deadline already passed (expiry is not undone by activity, even before + the sweep reaches it), and for a thread the owner already ended, whose + grace deadline must not grow back into a full idle window. + """ + return False + + async def end_incognito(self, thread_id: str, *, grace: timedelta, max_lifetime: timedelta, now: datetime | None = None, user_id: str | None | _AutoSentinel = AUTO) -> bool: + """Schedule an owner-requested end: deadline ``min(now + grace, created_at + max_lifetime)``. + + Records the end in metadata so activity renewal stops. Returns + ``False`` for missing/non-incognito/tombstoned rows or a foreign owner. + """ + return False + + async def begin_incognito_expiry(self, thread_id: str, *, now: datetime | None = None) -> bool: + """Write the tombstone before any data is purged. + + Clears the thread's content from the row (display name, metadata, + project membership) and marks it ``expired`` so reads stop resolving + it even if the purge below fails halfway. Returns ``False`` when the + row is missing, not incognito, or its deadline is still in the future; + the sweep's due list is a snapshot, so a concurrent renewal must win + over a stale batch entry. An already-tombstoned row whose deadline is + past returns ``True`` again so a failed purge retries. + """ + return False + + async def finish_incognito_expiry(self, thread_id: str) -> None: + """Mark a tombstoned row as purged by clearing ``expires_at``. + + The sweep selects rows by a non-NULL past ``expires_at``, so this is + what stops a completed purge from being retried. It runs only after + every other store has been cleaned. + """ + return None diff --git a/backend/packages/harness/deerflow/persistence/thread_meta/memory.py b/backend/packages/harness/deerflow/persistence/thread_meta/memory.py index a79da62ba6f..fdbb4ff2c00 100644 --- a/backend/packages/harness/deerflow/persistence/thread_meta/memory.py +++ b/backend/packages/harness/deerflow/persistence/thread_meta/memory.py @@ -8,12 +8,25 @@ from __future__ import annotations import uuid +from datetime import UTC, datetime, timedelta from typing import Any from langgraph.store.base import BaseStore from deerflow.persistence.json_compat import json_value_matches -from deerflow.persistence.thread_meta.base import PROJECT_FILTER_UNSET, THREAD_ARCHIVED_METADATA_KEY, THREAD_PINNED_METADATA_KEY, ThreadMetaStore, ThreadOwnershipConflictError, _ProjectFilterUnset +from deerflow.persistence.thread_meta.base import ( + PROJECT_FILTER_UNSET, + THREAD_ARCHIVED_METADATA_KEY, + THREAD_INCOGNITO_ENDED_METADATA_KEY, + THREAD_INCOGNITO_EXPIRED_STATUS, + THREAD_PINNED_METADATA_KEY, + ThreadCreateConflictError, + ThreadMetaStore, + ThreadOwnershipConflictError, + _as_utc, + _ProjectFilterUnset, + incognito_deadline, +) from deerflow.runtime.keyed_lock import AsyncKeyedLockTable from deerflow.runtime.user_context import AUTO, _AutoSentinel, resolve_user_id from deerflow.utils.time import coerce_iso, now_iso @@ -52,6 +65,8 @@ async def create( display_name: str | None = None, metadata: dict | None = None, project_id: str | None = None, + incognito: bool = False, + expires_at: datetime | None = None, ) -> dict: # Memory mode has no projects backend in Phase 1. Fail closed exactly # like the SQL store does for a missing/foreign/archived project: a @@ -68,6 +83,13 @@ async def create( existing = await self._store.aget(THREADS_NS, thread_id) if existing is not None and resolved_user_id is not None and existing.value.get("user_id") != resolved_user_id: raise ThreadOwnershipConflictError(thread_id) + # The SQL store rejects this id at the primary key; the memory + # store used to overwrite it. An incognito row must survive every + # create: a tombstone keeps its id from being reused, and a live + # row must not be converted or have its deadline reset. Raise so + # the Gateway resolves the existing row (410/409/idempotent 200). + if existing is not None and existing.value.get("incognito") is True: + raise ThreadCreateConflictError(thread_id) now = now_iso() record: dict[str, Any] = { "thread_id": thread_id, @@ -78,6 +100,8 @@ async def create( "status": "idle", "metadata": metadata or {}, "values": {}, + "incognito": incognito, + "expires_at": coerce_iso(expires_at) if expires_at is not None else None, "created_at": now, "updated_at": now, } @@ -146,7 +170,7 @@ async def search( break search_offset += len(page) - records = [self._item_to_dict(item) for item in items] + records = [record for record in (self._item_to_dict(item) for item in items) if record.get("incognito") is not True] if metadata: records = [record for record in records if isinstance(record.get("metadata"), dict) and all(json_value_matches(record["metadata"], key, value) for key, value in metadata.items())] if archived is not None: @@ -161,7 +185,14 @@ async def check_access(self, thread_id: str, user_id: str, *, require_existing: item = await self._store.aget(THREADS_NS, thread_id) if item is None: return not require_existing - record_user_id = item.value.get("user_id") + value = item.value + # An expired incognito thread resolves for nobody: the owner's view of + # it ends when its deadline passes, even before the sweep purges data. + if value.get("incognito") is True: + deadline = _as_utc(value.get("expires_at")) + if value.get("status") == THREAD_INCOGNITO_EXPIRED_STATUS or (deadline is not None and deadline <= datetime.now(UTC)): + return False + record_user_id = value.get("user_id") if record_user_id is None: return True return record_user_id == user_id @@ -178,6 +209,10 @@ async def update_display_name( record = await self._get_owned_record(thread_id, user_id, "MemoryThreadMetaStore.update_display_name") if record is None: return + if record.get("incognito") is True and record.get("status") == THREAD_INCOGNITO_EXPIRED_STATUS: + # A tombstone is terminal: run finalization must not write the + # title back onto a thread the sweep has purged. + return record["display_name"] = display_name metadata = dict(record.get("metadata") or {}) for key in remove_metadata_keys: @@ -187,10 +222,15 @@ async def update_display_name( await self._store.aput(THREADS_NS, thread_id, record) async def update_status(self, thread_id: str, status: str, *, user_id: str | None | _AutoSentinel = AUTO) -> None: + """Update the run status without ever reviving an incognito tombstone.""" async with self._thread_locks.hold(thread_id): record = await self._get_owned_record(thread_id, user_id, "MemoryThreadMetaStore.update_status") if record is None: return + if record.get("incognito") is True and record.get("status") == THREAD_INCOGNITO_EXPIRED_STATUS: + # The sweep's tombstone is authoritative; a run finalizing + # after it must not turn the row back into a live thread. + return record["status"] = status record["updated_at"] = now_iso() await self._store.aput(THREADS_NS, thread_id, record) @@ -223,6 +263,122 @@ async def delete(self, thread_id: str, *, user_id: str | None | _AutoSentinel = return await self._store.adelete(THREADS_NS, thread_id) + # ------------------------------------------------------------------ + # Incognito lifetime + # ------------------------------------------------------------------ + + async def _all_records(self) -> list[dict[str, Any]]: + """Page the whole thread namespace; the sweep runs unscoped.""" + records: list[dict[str, Any]] = [] + offset = 0 + while True: + page = await self._store.asearch(THREADS_NS, limit=SEARCH_PAGE_SIZE, offset=offset) + if not page: + break + records.extend(self._item_to_dict(item) for item in page) + if len(page) < SEARCH_PAGE_SIZE: + break + offset += len(page) + return records + + async def list_due_incognito(self, *, now: datetime | None = None, limit: int = 100) -> list[dict[str, Any]]: + moment = now or datetime.now(UTC) + due = [] + for record in await self._all_records(): + if record.get("incognito") is not True: + continue + deadline = _as_utc(record.get("expires_at")) + if deadline is not None and deadline <= moment: + due.append(record) + due.sort(key=lambda record: str(record.get("expires_at") or "")) + return due[:limit] + + async def renew_incognito( + self, + thread_id: str, + *, + idle_ttl: timedelta, + max_lifetime: timedelta, + now: datetime | None = None, + user_id: str | None | _AutoSentinel = AUTO, + ) -> bool: + moment = now or datetime.now(UTC) + async with self._thread_locks.hold(thread_id): + record = await self._get_owned_record(thread_id, user_id, "MemoryThreadMetaStore.renew_incognito") + if record is None or record.get("incognito") is not True or record.get("status") == THREAD_INCOGNITO_EXPIRED_STATUS: + return False + if (record.get("metadata") or {}).get(THREAD_INCOGNITO_ENDED_METADATA_KEY) is True: + return False + deadline = _as_utc(record.get("expires_at")) + if deadline is not None and deadline <= moment: + # Expiry is not reversible by activity: a run finishing before + # the sweep reaches an already-gone thread must not extend it. + return False + created = _as_utc(record.get("created_at")) or moment + record["expires_at"] = coerce_iso( + incognito_deadline( + now=moment, + created_at=created, + window=idle_ttl, + max_lifetime=max_lifetime, + ) + ) + await self._store.aput(THREADS_NS, thread_id, record) + return True + + async def end_incognito(self, thread_id: str, *, grace: timedelta, max_lifetime: timedelta, now: datetime | None = None, user_id: str | None | _AutoSentinel = AUTO) -> bool: + moment = now or datetime.now(UTC) + async with self._thread_locks.hold(thread_id): + record = await self._get_owned_record(thread_id, user_id, "MemoryThreadMetaStore.end_incognito") + if record is None or record.get("incognito") is not True or record.get("status") == THREAD_INCOGNITO_EXPIRED_STATUS: + return False + metadata = dict(record.get("metadata") or {}) + if metadata.get(THREAD_INCOGNITO_ENDED_METADATA_KEY) is True: + # Ending is idempotent: a repeated request must not keep + # pushing the purge deadline out while the user waits for the + # thread to disappear. + return True + metadata[THREAD_INCOGNITO_ENDED_METADATA_KEY] = True + record["metadata"] = metadata + record["expires_at"] = coerce_iso( + incognito_deadline( + now=moment, + created_at=_as_utc(record.get("created_at")) or moment, + window=grace, + max_lifetime=max_lifetime, + ) + ) + await self._store.aput(THREADS_NS, thread_id, record) + return True + + async def begin_incognito_expiry(self, thread_id: str, *, now: datetime | None = None) -> bool: + moment = now or datetime.now(UTC) + async with self._thread_locks.hold(thread_id): + item = await self._store.aget(THREADS_NS, thread_id) + if item is None or item.value.get("incognito") is not True: + return False + # The due list is a snapshot: a run completion may have renewed the + # deadline in between. Recheck under the thread lock so the renewal + # wins; only an actually-due row is tombstoned. + deadline = _as_utc(item.value.get("expires_at")) + if deadline is None or deadline > moment: + return False + record = dict(item.value) + record["status"] = THREAD_INCOGNITO_EXPIRED_STATUS + record["display_name"] = None + record["metadata"] = {} + await self._store.aput(THREADS_NS, thread_id, record) + return True + + async def finish_incognito_expiry(self, thread_id: str) -> None: + async with self._thread_locks.hold(thread_id): + item = await self._store.aget(THREADS_NS, thread_id) + if item is None: + return + record = dict(item.value) + record["expires_at"] = None + await self._store.aput(THREADS_NS, thread_id, record) + @staticmethod def _item_to_dict(item) -> dict[str, Any]: """Convert a Store SearchItem to the dict format expected by callers.""" @@ -235,6 +391,8 @@ def _item_to_dict(item) -> dict[str, Any]: "display_name": val.get("display_name"), "status": val.get("status", "idle"), "metadata": val.get("metadata", {}), + "incognito": val.get("incognito") is True, + "expires_at": val.get("expires_at"), # ``coerce_iso`` heals legacy unix-second values written by # earlier Gateway versions that called ``str(time.time())``. "created_at": coerce_iso(val.get("created_at", "")), diff --git a/backend/packages/harness/deerflow/persistence/thread_meta/model.py b/backend/packages/harness/deerflow/persistence/thread_meta/model.py index 5f95aea3d7f..16f0c85f190 100644 --- a/backend/packages/harness/deerflow/persistence/thread_meta/model.py +++ b/backend/packages/harness/deerflow/persistence/thread_meta/model.py @@ -4,7 +4,7 @@ from datetime import UTC, datetime -from sqlalchemy import JSON, DateTime, String +from sqlalchemy import JSON, Boolean, DateTime, Index, String from sqlalchemy.orm import Mapped, mapped_column from deerflow.persistence.base import Base @@ -12,6 +12,7 @@ class ThreadMetaRow(Base): __tablename__ = "threads_meta" + __table_args__ = (Index("ix_threads_meta_incognito_expires_at", "incognito", "expires_at"),) thread_id: Mapped[str] = mapped_column(String(64), primary_key=True) incarnation: Mapped[str | None] = mapped_column(String(32), nullable=True) @@ -21,5 +22,11 @@ class ThreadMetaRow(Base): display_name: Mapped[str | None] = mapped_column(String(256)) status: Mapped[str] = mapped_column(String(20), default="idle") metadata_json: Mapped[dict] = mapped_column(JSON, default=dict) + # Nullable with no server default so a binary sharing the database during a + # rolling upgrade keeps inserting rows; NULL reads as "not incognito". + incognito: Mapped[bool | None] = mapped_column(Boolean, nullable=True) + # Absolute deadline of the incognito thread's current lifetime. The TTL + # sweep compares it against the database clock; NULL on ordinary threads. + expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC)) updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC)) diff --git a/backend/packages/harness/deerflow/persistence/thread_meta/sql.py b/backend/packages/harness/deerflow/persistence/thread_meta/sql.py index 013b0c74f84..daef703d934 100644 --- a/backend/packages/harness/deerflow/persistence/thread_meta/sql.py +++ b/backend/packages/harness/deerflow/persistence/thread_meta/sql.py @@ -4,7 +4,7 @@ import logging import uuid -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from typing import Any from sqlalchemy import case, column, select, table, text, update @@ -12,7 +12,19 @@ from sqlalchemy.orm.attributes import flag_modified from deerflow.persistence.json_compat import json_match -from deerflow.persistence.thread_meta.base import PROJECT_FILTER_UNSET, THREAD_ARCHIVED_METADATA_KEY, THREAD_PINNED_METADATA_KEY, THREAD_PROJECT_METADATA_KEY, InvalidMetadataFilterError, ThreadMetaStore, _ProjectFilterUnset +from deerflow.persistence.thread_meta.base import ( + PROJECT_FILTER_UNSET, + THREAD_ARCHIVED_METADATA_KEY, + THREAD_INCOGNITO_ENDED_METADATA_KEY, + THREAD_INCOGNITO_EXPIRED_STATUS, + THREAD_PINNED_METADATA_KEY, + THREAD_PROJECT_METADATA_KEY, + InvalidMetadataFilterError, + ThreadMetaStore, + _as_utc, + _ProjectFilterUnset, + incognito_deadline, +) from deerflow.persistence.thread_meta.model import ThreadMetaRow from deerflow.runtime.user_context import AUTO, _AutoSentinel, resolve_user_id from deerflow.utils.time import coerce_iso @@ -31,12 +43,14 @@ def _row_to_dict(row: ThreadMetaRow) -> dict[str, Any]: project_id = d.pop("project_id", None) if project_id is not None: d["metadata"][THREAD_PROJECT_METADATA_KEY] = project_id - for key in ("created_at", "updated_at"): + for key in ("created_at", "updated_at", "expires_at"): val = d.get(key) if isinstance(val, datetime): # SQLite drops tzinfo despite ``DateTime(timezone=True)``; # ``coerce_iso`` normalizes naive values as UTC so the wire format always carries tz. d[key] = coerce_iso(val) + # Normalize the nullable column for callers: pre-migration rows read NULL. + d["incognito"] = d.get("incognito") is True return d async def create( @@ -48,6 +62,8 @@ async def create( display_name: str | None = None, metadata: dict | None = None, project_id: str | None = None, + incognito: bool = False, + expires_at: datetime | None = None, ) -> dict: # Auto-resolve user_id from contextvar when AUTO; explicit None # creates an orphan row (used by migration scripts). @@ -86,6 +102,8 @@ async def create( status="idle", metadata_json=metadata or {}, project_id=project_id, + incognito=incognito, + expires_at=expires_at, created_at=now, updated_at=now, ) @@ -181,6 +199,20 @@ async def get( return None return self._row_to_dict(row) + async def incognito_ids(self, thread_ids, *, user_id: str | None | _AutoSentinel = AUTO) -> set[str]: + """Return the incognito subset of ``thread_ids`` in one query.""" + if not thread_ids: + return set() + resolved_user_id = resolve_user_id(user_id, method_name="ThreadMetaRepository.incognito_ids") + stmt = select(ThreadMetaRow.thread_id).where( + ThreadMetaRow.thread_id.in_(thread_ids), + ThreadMetaRow.incognito.is_(True), + ) + if resolved_user_id is not None: + stmt = stmt.where(ThreadMetaRow.user_id == resolved_user_id) + async with self._sf() as session: + return set((await session.scalars(stmt)).all()) + async def check_access(self, thread_id: str, user_id: str, *, require_existing: bool = False) -> bool: """Check if ``user_id`` has access to ``thread_id``. @@ -207,6 +239,11 @@ async def check_access(self, thread_id: str, user_id: str, *, require_existing: row = await session.get(ThreadMetaRow, thread_id) if row is None: return not require_existing + # An expired incognito thread resolves for nobody: the owner's + # view of it ends when its deadline passes, even before the sweep + # has purged its data. + if row.incognito is True and (row.status == THREAD_INCOGNITO_EXPIRED_STATUS or (deadline := _as_utc(row.expires_at)) is not None and deadline <= datetime.now(UTC)): + return False if row.user_id is None: return True return row.user_id == user_id @@ -238,6 +275,9 @@ async def search( ThreadMetaRow.updated_at.desc(), ThreadMetaRow.thread_id.desc(), ) + # Incognito threads never surface in a list or search result. ``isnot`` + # (not ``== False``) keeps pre-migration NULL rows visible. + stmt = stmt.where(ThreadMetaRow.incognito.isnot(True)) if resolved_user_id is not None: stmt = stmt.where(ThreadMetaRow.user_id == resolved_user_id) if status: @@ -321,6 +361,13 @@ async def update_display_name( row = result.scalar_one_or_none() if row is None or (resolved_user_id is not None and row.user_id != resolved_user_id): return + if row.incognito is True and row.status == THREAD_INCOGNITO_EXPIRED_STATUS: + # A tombstone is terminal. Run finalization on another Gateway + # process can reach here after the sweep has purged the thread; + # writing the title back would leave content on a row reads no + # longer resolve. + await session.rollback() + return row.display_name = display_name metadata = dict(row.metadata_json or {}) for key in remove_metadata_keys: @@ -336,11 +383,24 @@ async def update_status( *, user_id: str | None | _AutoSentinel = AUTO, ) -> None: + """Update the run status without ever reviving an incognito tombstone. + + A run finishes after another Gateway process swept its thread; the + tombstone is the authoritative state, so the row is left untouched. + The predicate is part of the UPDATE so the check is atomic with it. + """ resolved_user_id = resolve_user_id(user_id, method_name="ThreadMetaRepository.update_status") async with self._sf() as session: if not await self._check_ownership(session, thread_id, resolved_user_id): return - await session.execute(update(ThreadMetaRow).where(ThreadMetaRow.thread_id == thread_id).values(status=status, updated_at=datetime.now(UTC))) + await session.execute( + update(ThreadMetaRow) + .where( + ThreadMetaRow.thread_id == thread_id, + ~((ThreadMetaRow.incognito.is_(True)) & (ThreadMetaRow.status == THREAD_INCOGNITO_EXPIRED_STATUS)), + ) + .values(status=status, updated_at=datetime.now(UTC)) + ) await session.commit() async def update_metadata( @@ -429,3 +489,133 @@ async def delete( return await session.delete(row) await session.commit() + + async def _locked_row(self, session: AsyncSession, thread_id: str) -> ThreadMetaRow | None: + """Fetch a row under the write lock this repository uses elsewhere.""" + if session.get_bind().dialect.name == "sqlite": + await session.execute(text("BEGIN IMMEDIATE")) + return await session.get(ThreadMetaRow, thread_id) + return (await session.execute(select(ThreadMetaRow).where(ThreadMetaRow.thread_id == thread_id).with_for_update())).scalar_one_or_none() + + # ------------------------------------------------------------------ + # Incognito lifetime + # ------------------------------------------------------------------ + + async def list_due_incognito(self, *, now: datetime | None = None, limit: int = 100) -> list[dict[str, Any]]: + """Return incognito rows past their deadline, oldest deadline first. + + ``expires_at`` doubles as the purge-retry marker: the sweep clears it + only after every other store has been cleaned, so a row it failed to + purge is selected again on the next pass. + """ + deadline = now or datetime.now(UTC) + stmt = ( + select(ThreadMetaRow) + .where( + ThreadMetaRow.incognito.is_(True), + ThreadMetaRow.expires_at.isnot(None), + ThreadMetaRow.expires_at <= deadline, + ) + .order_by(ThreadMetaRow.expires_at) + .limit(limit) + ) + async with self._sf() as session: + result = await session.execute(stmt) + return [self._row_to_dict(row) for row in result.scalars()] + + async def renew_incognito( + self, + thread_id: str, + *, + idle_ttl: timedelta, + max_lifetime: timedelta, + now: datetime | None = None, + user_id: str | None | _AutoSentinel = AUTO, + ) -> bool: + resolved_user_id = resolve_user_id(user_id, method_name="ThreadMetaRepository.renew_incognito") + moment = now or datetime.now(UTC) + async with self._sf() as session: + row = await self._locked_row(session, thread_id) + if row is None or row.incognito is not True or row.status == THREAD_INCOGNITO_EXPIRED_STATUS: + await session.rollback() + return False + if resolved_user_id is not None and row.user_id != resolved_user_id: + await session.rollback() + return False + if (row.metadata_json or {}).get(THREAD_INCOGNITO_ENDED_METADATA_KEY) is True: + await session.rollback() + return False + deadline = _as_utc(row.expires_at) + if deadline is not None and deadline <= moment: + # Expiry is not reversible by activity: once the deadline has + # passed the thread is gone to its owner, so a run finishing + # before the sweep reaches it must not push the deadline out + # and pull it back from the due list. + await session.rollback() + return False + created = _as_utc(row.created_at) or moment + # The absolute ceiling wins even when it shortens the deadline. + row.expires_at = incognito_deadline( + now=moment, + created_at=created, + window=idle_ttl, + max_lifetime=max_lifetime, + ) + await session.commit() + return True + + async def end_incognito(self, thread_id: str, *, grace: timedelta, max_lifetime: timedelta, now: datetime | None = None, user_id: str | None | _AutoSentinel = AUTO) -> bool: + resolved_user_id = resolve_user_id(user_id, method_name="ThreadMetaRepository.end_incognito") + moment = now or datetime.now(UTC) + async with self._sf() as session: + row = await self._locked_row(session, thread_id) + if row is None or row.incognito is not True or row.status == THREAD_INCOGNITO_EXPIRED_STATUS: + await session.rollback() + return False + if resolved_user_id is not None and row.user_id != resolved_user_id: + await session.rollback() + return False + metadata = dict(row.metadata_json or {}) + if metadata.get(THREAD_INCOGNITO_ENDED_METADATA_KEY) is True: + # Ending is idempotent: a repeated request must not keep + # pushing the purge deadline out while the user waits for the + # thread to disappear. + await session.rollback() + return True + metadata[THREAD_INCOGNITO_ENDED_METADATA_KEY] = True + row.metadata_json = metadata + row.expires_at = incognito_deadline( + now=moment, + created_at=_as_utc(row.created_at) or moment, + window=grace, + max_lifetime=max_lifetime, + ) + await session.commit() + return True + + async def begin_incognito_expiry(self, thread_id: str, *, now: datetime | None = None) -> bool: + moment = now or datetime.now(UTC) + async with self._sf() as session: + row = await self._locked_row(session, thread_id) + deadline = _as_utc(row.expires_at) if row is not None else None + # The due list is a snapshot: a run completion may have renewed the + # deadline in between. Recheck under the row lock so the renewal + # wins; only an actually-due row is tombstoned. + if row is None or row.incognito is not True or deadline is None or deadline > moment: + await session.rollback() + return False + row.status = THREAD_INCOGNITO_EXPIRED_STATUS + row.display_name = None + row.metadata_json = {} + row.project_id = None + await session.commit() + return True + + async def finish_incognito_expiry(self, thread_id: str) -> None: + async with self._sf() as session: + row = await self._locked_row(session, thread_id) + if row is None: + await session.rollback() + return + row.expires_at = None + await session.commit() diff --git a/backend/packages/harness/deerflow/runtime/__init__.py b/backend/packages/harness/deerflow/runtime/__init__.py index 56bcf3b439b..78193f8b783 100644 --- a/backend/packages/harness/deerflow/runtime/__init__.py +++ b/backend/packages/harness/deerflow/runtime/__init__.py @@ -13,6 +13,7 @@ CancelOutcome, ConflictError, DisconnectMode, + RunAdmissionRejected, RunContext, RunIdempotencyKeyMismatch, RunIdempotencyUnsupported, @@ -45,6 +46,7 @@ "ConflictError", "DisconnectMode", "ORPHAN_RECOVERY_STOP_REASON", + "RunAdmissionRejected", "RunContext", "RunIdempotencyKeyMismatch", "RunIdempotencyUnsupported", diff --git a/backend/packages/harness/deerflow/runtime/context_keys.py b/backend/packages/harness/deerflow/runtime/context_keys.py index f7fb781b4ad..e730578f76b 100644 --- a/backend/packages/harness/deerflow/runtime/context_keys.py +++ b/backend/packages/harness/deerflow/runtime/context_keys.py @@ -19,6 +19,23 @@ PROJECT_CONTEXT_KEY: Final[str] = "__deerflow_project_context" AGENT_AUTH_CONTEXT_KEY: Final[str] = "__deerflow_mcp_agent_authority" +# Server-owned marker for a run whose thread is incognito. Middlewares and +# tools read it to skip durable writes (memory, blob storage); clients can +# never supply it, so a normal run cannot opt itself out of persistence. +INCOGNITO_CONTEXT_KEY: Final[str] = "__deerflow_incognito" + + +def is_incognito_runtime(runtime: object) -> bool: + """Return whether *runtime* belongs to an incognito thread. + + The marker is server-owned: Gateway admission pins it from the stored + thread, and the run worker hoists it into the runtime context, so a client + cannot mark or unmark a run. Anything other than the exact boolean ``True`` + means an ordinary run. + """ + context = getattr(runtime, "context", None) + return isinstance(context, Mapping) and context.get(INCOGNITO_CONTEXT_KEY) is True + def checkpoint_agent_binding_metadata(metadata: object) -> dict[str, str]: """Copy a checkpoint's server-authored agent binding for a state rewrite. diff --git a/backend/packages/harness/deerflow/runtime/runs/__init__.py b/backend/packages/harness/deerflow/runtime/runs/__init__.py index 31070021253..fa45c27c951 100644 --- a/backend/packages/harness/deerflow/runtime/runs/__init__.py +++ b/backend/packages/harness/deerflow/runtime/runs/__init__.py @@ -1,5 +1,6 @@ """Run lifecycle management for LangGraph Platform API compatibility.""" +from .admission import RunAdmissionRejected from .manager import ORPHAN_RECOVERY_STOP_REASON, STARTUP_ORPHAN_RECOVERY_ERROR, CancelOutcome, ConflictError, RunIdempotencyKeyMismatch, RunIdempotencyUnsupported, RunManager, RunRecord, UnsupportedStrategyError from .schemas import DisconnectMode, RunStatus, ThreadOperationKind from .worker import RunContext, run_agent @@ -9,6 +10,7 @@ "ConflictError", "DisconnectMode", "ORPHAN_RECOVERY_STOP_REASON", + "RunAdmissionRejected", "RunContext", "RunIdempotencyKeyMismatch", "RunIdempotencyUnsupported", diff --git a/backend/packages/harness/deerflow/runtime/runs/admission.py b/backend/packages/harness/deerflow/runtime/runs/admission.py new file mode 100644 index 00000000000..6a7deb556dc --- /dev/null +++ b/backend/packages/harness/deerflow/runtime/runs/admission.py @@ -0,0 +1,16 @@ +"""Fatal outcomes a host admission hook can report. + +``RunContext.on_run_admitted`` is deliberately best-effort for bookkeeping: a +host hook must not strand an admitted run on a transient cleanup failure. One +class of hook work is not bookkeeping, though: deciding whether the run may +write to durable storage at all. When the host cannot establish that verdict, +continuing would silently run under the wrong persistence policy. Raising +:class:`RunAdmissionRejected` tells the worker to fail the run instead of +swallowing the hook error. +""" + +from __future__ import annotations + + +class RunAdmissionRejected(RuntimeError): + """A host admission precondition could not be verified; the run must fail.""" diff --git a/backend/packages/harness/deerflow/runtime/runs/worker.py b/backend/packages/harness/deerflow/runtime/runs/worker.py index b28599e0e1d..fc7ff4e7da8 100644 --- a/backend/packages/harness/deerflow/runtime/runs/worker.py +++ b/backend/packages/harness/deerflow/runtime/runs/worker.py @@ -66,6 +66,7 @@ CHECKPOINT_AGENT_NAME_METADATA_KEY, CURRENT_RUN_PRE_EXISTING_MESSAGE_IDS_KEY, DEFAULT_AGENT_NAME_METADATA_VALUE, + INCOGNITO_CONTEXT_KEY, PROJECT_CONTEXT_KEY, checkpoint_agent_binding_metadata, ) @@ -98,6 +99,7 @@ from deerflow.runtime.goal_progress import observe_goal_operations from deerflow.runtime.keyed_lock import AsyncKeyedLockTable from deerflow.runtime.run_origin import origin_kind_of +from deerflow.runtime.runs.admission import RunAdmissionRejected from deerflow.runtime.runs.schemas import GOAL_RUN_HARD_STOP_REASONS from deerflow.runtime.runs.stream_cleanup import close_agent_stream from deerflow.runtime.serialization import serialize @@ -640,6 +642,9 @@ def finish(self) -> list[Any]: # admission (spec §7.1); a caller-supplied value in # ``config['context']`` must never be merged (§12). PROJECT_CONTEXT_KEY, + # Admission stamps this only for an incognito thread; a caller + # must never opt a normal run out of durable writes. + INCOGNITO_CONTEXT_KEY, KNOWLEDGE_SCOPE_RUNTIME_KEY, } ) @@ -709,21 +714,26 @@ def _build_runtime_context( return runtime_ctx -def _pin_admission_project_context(config: dict, runtime_context: dict[str, Any]) -> None: - """Re-inject the admission-pinned project snapshot into the runtime context. +def _pin_admission_server_context(config: dict, runtime_context: dict[str, Any]) -> None: + """Re-inject admission-pinned server context into the runtime context. The Gateway resolves and stamps ``config['context'][PROJECT_CONTEXT_KEY]`` - after stripping client-supplied values at admission (``build_run_config`` - drops ``__``-prefixed context keys; the services pop-set covers both - sections), so a value surviving to this point is server-authoritative. + and ``config['context'][INCOGNITO_CONTEXT_KEY]`` after stripping + client-supplied values at admission (``build_run_config`` drops + ``__``-prefixed context keys; the services pop-set covers both sections), + so a value surviving to this point is server-authoritative. ``_build_runtime_context`` refuses server-owned keys from the caller merge, and ``_install_runtime_context`` treats the runtime context as the authoritative view — hoisting here is what lets middleware and tools read - exactly the snapshot admission pinned. + exactly what admission pinned. """ caller_context = config.get("context") - if isinstance(caller_context, dict) and PROJECT_CONTEXT_KEY in caller_context: + if not isinstance(caller_context, dict): + return + if PROJECT_CONTEXT_KEY in caller_context: runtime_context[PROJECT_CONTEXT_KEY] = caller_context[PROJECT_CONTEXT_KEY] + if caller_context.get(INCOGNITO_CONTEXT_KEY) is True: + runtime_context[INCOGNITO_CONTEXT_KEY] = True @dataclass(frozen=True) @@ -749,7 +759,9 @@ class RunContext: # this process" (embedded/tests) and resolves to the config default. checkpoint_snapshot_frequency: int | None = None # Called after durable same-thread admission is active and before the first - # checkpoint read. Failures are isolated from the run outcome. + # checkpoint read. Ordinary failures are isolated from the run outcome; + # raising ``RunAdmissionRejected`` fails the run because a host + # precondition (for example the incognito verdict) could not be verified. on_run_admitted: Any | None = field(default=None) on_run_completed: Any | None = field(default=None) # The host binds this capability to one run's authenticated reader and references. @@ -1260,6 +1272,13 @@ async def _finish_cancellation( if ctx.on_run_admitted is not None: try: await ctx.on_run_admitted(record, config) + except RunAdmissionRejected: + # The host could not establish a precondition that protects + # durable storage. The outer handler marks the run failed; + # continuing would run the agent under the wrong persistence + # policy (for example as an ordinary run on an incognito + # thread, writing memory and shared blobs). + raise except Exception: logger.warning("Run admission hook failed for %s (non-fatal)", run_id, exc_info=True) @@ -1407,7 +1426,7 @@ async def _finish_cancellation( checkpoint_metadata = {} config["metadata"] = checkpoint_metadata checkpoint_metadata[CHECKPOINT_AGENT_NAME_METADATA_KEY] = DEFAULT_AGENT_NAME_METADATA_VALUE if checkpoint_agent_name is None else checkpoint_agent_name - _pin_admission_project_context(config, runtime_ctx) + _pin_admission_server_context(config, runtime_ctx) if knowledge_scope is not None: runtime_ctx[KNOWLEDGE_SCOPE_RUNTIME_KEY] = execution_scope(knowledge_scope) deerflow_trace_id = _bind_trace_id(config, runtime_ctx) diff --git a/backend/packages/harness/deerflow/subagents/batch_service.py b/backend/packages/harness/deerflow/subagents/batch_service.py index 554ccbef763..2ce643d094d 100644 --- a/backend/packages/harness/deerflow/subagents/batch_service.py +++ b/backend/packages/harness/deerflow/subagents/batch_service.py @@ -14,6 +14,7 @@ from deerflow.config.subagent_runtime_config import SubagentRuntimeConfig from deerflow.extensions import LoadedExtensions, get_loaded_extensions from deerflow.mcp_scope import THREAD_INCARNATION_CONTEXT_KEY +from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY from deerflow.subagents.batch_acceptance import check_batch_acceptance from deerflow.subagents.batch_lease import BatchItemLease from deerflow.subagents.batch_runtime import BatchSubmitRequest @@ -519,6 +520,10 @@ async def _execute_leased_item(self, item: dict[str, Any], lease: BatchItemLease executor_kwargs["agent_mcp_authority"] = restore_agent_authority(batch["user_id"], spec["mcp_agent_auth"]) if THREAD_INCARNATION_CONTEXT_KEY in spec: executor_kwargs[THREAD_INCARNATION_CONTEXT_KEY] = spec[THREAD_INCARNATION_CONTEXT_KEY] + # Rebuild the incognito verdict from the durable spec so a worker on + # any process skips the shared blob writes the lead's gates skip. + if spec.get(INCOGNITO_CONTEXT_KEY) is True: + executor_kwargs["incognito"] = True executor = SubagentExecutor( config=config, tools=tools, diff --git a/backend/packages/harness/deerflow/subagents/executor.py b/backend/packages/harness/deerflow/subagents/executor.py index 04e6af7958a..5afd921ed71 100644 --- a/backend/packages/harness/deerflow/subagents/executor.py +++ b/backend/packages/harness/deerflow/subagents/executor.py @@ -26,6 +26,7 @@ from langchain_core.runnables.config import var_child_runnable_config from langgraph.errors import GraphRecursionError +from deerflow.agents.incognito_prompt import build_incognito_section from deerflow.agents.middlewares.audit_context import ( LOOP_DETECTION_RECORDER_CONTEXT_KEY, TOOL_PROGRESS_RECORDER_CONTEXT_KEY, @@ -960,6 +961,7 @@ def __init__( thread_incarnation: str | None | object = _THREAD_INCARNATION_UNSET, input_gate: Any | None = None, agent_mcp_authority: Any | None = None, + incognito: bool = False, ): """Initialize the executor. @@ -1043,6 +1045,12 @@ def __init__( self.agent_mcp_authority = agent_mcp_authority self.thread_id = thread_id self.thread_incarnation = thread_incarnation + # Server-owned incognito marker captured from the parent runtime context. + # Propagated into the subagent's own runtime context so the shared + # L4 durable-write gates (blob externalization, view_image) read the + # same verdict inside the delegated loop. A client cannot set this: the + # parent context key is admission-pinned and stripped from caller input. + self.incognito = incognito is True # Generate trace_id if not provided (for top-level calls) self.trace_id = trace_id or str(uuid.uuid4())[:8] self.user_id = user_id @@ -1637,6 +1645,10 @@ async def _build_initial_state(self, task: str) -> tuple[dict[str, Any], list[Ba system_parts: list[str] = [] if self.config.system_prompt: system_parts.append(self.config.system_prompt) + if self.incognito: + # Framework policy follows a custom subagent prompt so the + # temporary-chat boundary never depends on its author repeating it. + system_parts.append(build_incognito_section("subagent")) if self.context_snapshot is not None: system_parts.append(SNAPSHOT_SYSTEM_NOTE) # RFC #4651 PR3: every subagent — built-in or custom — gets the same @@ -1927,6 +1939,10 @@ def current_bash_executions() -> list[dict[str, Any]] | None: context["thread_id"] = self.thread_id if self.thread_incarnation is not _THREAD_INCARNATION_UNSET: context[THREAD_INCARNATION_CONTEXT_KEY] = self.thread_incarnation + if self.incognito: + from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY + + context[INCOGNITO_CONTEXT_KEY] = True if self.app_config is not None: context["app_config"] = self.app_config # Propagate guardrail attribution so delegated tool calls are diff --git a/backend/packages/harness/deerflow/tools/builtins/batch_task_tool.py b/backend/packages/harness/deerflow/tools/builtins/batch_task_tool.py index 4495c8b7836..d7777ba4dca 100644 --- a/backend/packages/harness/deerflow/tools/builtins/batch_task_tool.py +++ b/backend/packages/harness/deerflow/tools/builtins/batch_task_tool.py @@ -25,6 +25,7 @@ THREAD_INCARNATION_METADATA_GUARD_KEY, runtime_thread_incarnation, ) +from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY, is_incognito_runtime from deerflow.runtime.user_context import resolve_runtime_user_id from deerflow.subagents.batch_runtime import ( BatchItemInput, @@ -196,6 +197,15 @@ async def batch_task( An active Goal resumes only from external waiting and within its existing limits. """ submitter = _batch_submitter() + # Defence in depth: the lead-agent assembly already withholds the batch + # tools in incognito runs. Durable rows store each item's prompt and + # execution spec and outlive the chat, so a re-attached copy must refuse. + if is_incognito_runtime(runtime): + return _result( + tool_call_id, + content="Error: batch_task is unavailable in an incognito chat. Durable batch rows outlive the conversation; use the ordinary task tool for subagents here.", + error=True, + ) if submitter is None: return _result( tool_call_id, @@ -264,6 +274,11 @@ async def batch_task( } if THREAD_INCARNATION_CONTEXT_KEY in context: execution_spec[THREAD_INCARNATION_CONTEXT_KEY] = context[THREAD_INCARNATION_CONTEXT_KEY] + # The admission-pinned incognito marker rides the durable spec so a batch + # worker on another process still builds its executor without durable + # writes. Strict ``is True`` mirrors the task tool's propagation. + if context.get(INCOGNITO_CONTEXT_KEY) is True: + execution_spec[INCOGNITO_CONTEXT_KEY] = True if KNOWLEDGE_SCOPE_RUNTIME_KEY in context: execution_spec["knowledge_scope"] = execution_scope(context[KNOWLEDGE_SCOPE_RUNTIME_KEY]) from deerflow.mcp.agent_auth import export_agent_authority, runtime_agent_authority diff --git a/backend/packages/harness/deerflow/tools/builtins/setup_agent_tool.py b/backend/packages/harness/deerflow/tools/builtins/setup_agent_tool.py index 3297a4378e5..629b24ea527 100644 --- a/backend/packages/harness/deerflow/tools/builtins/setup_agent_tool.py +++ b/backend/packages/harness/deerflow/tools/builtins/setup_agent_tool.py @@ -12,6 +12,7 @@ from deerflow.config.paths import get_paths from deerflow.knowledge_scope import canonicalize_knowledge_scope from deerflow.persistence.agents import get_agent_store +from deerflow.runtime.context_keys import is_incognito_runtime from deerflow.runtime.user_context import resolve_runtime_user_id from deerflow.tools.types import Runtime from deerflow.utils.atomic_write import cleanup_failed_atomic_write @@ -69,6 +70,22 @@ def setup_agent( skills: Optional list of skill names this agent should use. None means use all enabled skills, empty list means no skills. """ + # Defence in depth — the lead-agent factory already withholds this tool + # from incognito runs. Creating an agent writes a durable per-user record + # and SOUL.md, so a re-attached tool must still refuse inside the chat. + if is_incognito_runtime(runtime): + return Command( + update={ + "messages": [ + ToolMessage( + content="Error: setup_agent is unavailable in an incognito chat. Creating an agent persists data outside this conversation and would outlive it.", + tool_call_id=runtime.tool_call_id, + status="error", + ) + ] + } + ) + # Reject empty / whitespace-only soul before touching the filesystem. # Without this guard the tool would happily persist an empty SOUL.md and # still report success, which caused the frontend to enter the "agent diff --git a/backend/packages/harness/deerflow/tools/builtins/task_tool.py b/backend/packages/harness/deerflow/tools/builtins/task_tool.py index 41cea9019cd..0681984087d 100644 --- a/backend/packages/harness/deerflow/tools/builtins/task_tool.py +++ b/backend/packages/harness/deerflow/tools/builtins/task_tool.py @@ -30,6 +30,7 @@ runtime_thread_incarnation, ) from deerflow.models.selection import authorize_selected_model +from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY from deerflow.runtime.user_context import resolve_runtime_user_id from deerflow.sandbox.security import LOCAL_BASH_SUBAGENT_DISABLED_MESSAGE, is_host_bash_allowed from deerflow.subagents import SubagentExecutor, get_available_subagent_names, get_subagent_config @@ -1147,6 +1148,13 @@ async def task_tool( # inventing a legacy scope for missing context or re-reading thread state. if THREAD_INCARNATION_CONTEXT_KEY in parent_context: executor_kwargs["thread_incarnation"] = parent_context[THREAD_INCARNATION_CONTEXT_KEY] + # Propagate the admission-pinned incognito marker so the delegated loop's + # shared durable-write gates (blob externalization, view_image) read the + # same verdict as the lead. Strict ``is True``: the parent key is + # server-owned and stripped from caller input, so any other value is an + # ordinary run. + if parent_context.get(INCOGNITO_CONTEXT_KEY) is True: + executor_kwargs["incognito"] = True if context_snapshot is not None: executor_kwargs["context_snapshot"] = context_snapshot middleware_recorder = None diff --git a/backend/packages/harness/deerflow/tools/builtins/update_agent_tool.py b/backend/packages/harness/deerflow/tools/builtins/update_agent_tool.py index 9e94e4fb318..de887894b0b 100644 --- a/backend/packages/harness/deerflow/tools/builtins/update_agent_tool.py +++ b/backend/packages/harness/deerflow/tools/builtins/update_agent_tool.py @@ -39,6 +39,7 @@ from deerflow.config.paths import get_paths from deerflow.persistence.agents import get_agent_store from deerflow.persistence.agents.file import FileAgentStore +from deerflow.runtime.context_keys import is_incognito_runtime from deerflow.runtime.user_context import resolve_runtime_user_id from deerflow.tools.types import Runtime @@ -119,6 +120,12 @@ def update_agent( def _err(message: str) -> Command: return Command(update={"messages": [ToolMessage(content=f"Error: {message}", tool_call_id=tool_call_id, status="error")]}) + # Defence in depth — the lead-agent factory already withholds this tool + # from incognito runs. The write is durable and visible in every later + # ordinary conversation, so a re-attached tool must refuse on its own. + if is_incognito_runtime(runtime): + return _err("update_agent is unavailable in an incognito chat. Agent changes persist outside this conversation and would outlive it.") + # Defence in depth — the lead-agent factory already withholds this # tool from webhook-channel runs (see ``_WEBHOOK_CHANNELS`` in # ``deerflow.agents.lead_agent.agent``). The same channel set is diff --git a/backend/packages/harness/deerflow/tools/builtins/view_image_tool.py b/backend/packages/harness/deerflow/tools/builtins/view_image_tool.py index 1f98653ee0f..1a501aee829 100644 --- a/backend/packages/harness/deerflow/tools/builtins/view_image_tool.py +++ b/backend/packages/harness/deerflow/tools/builtins/view_image_tool.py @@ -297,30 +297,34 @@ def _view_image_authorized(runtime: Runtime, image_path: str, tool_call_id: str) "actual_path": str(actual_path), "sha256": hashlib.sha256(image_data).hexdigest(), } + from deerflow.runtime.context_keys import is_incognito_runtime from deerflow.storage import get_blob_store_if_enabled - try: - blob_store = get_blob_store_if_enabled() - if blob_store is not None: - blob_ref = blob_store.put_bytes( - image_data, - kind="viewed-image", - content_type=mime_type, - thread_id=_get_thread_id(runtime), + # Incognito runs keep the image inside their own thread storage; the + # middleware resolves it from actual_path instead of a shared blob. + if not is_incognito_runtime(runtime): + try: + blob_store = get_blob_store_if_enabled() + if blob_store is not None: + blob_ref = blob_store.put_bytes( + image_data, + kind="viewed-image", + content_type=mime_type, + thread_id=_get_thread_id(runtime), + ) + image_metadata["blob_ref"] = blob_ref.model_dump(mode="json", exclude_none=True) + except Exception: + logger.warning("Failed to persist viewed image in shared blob storage", exc_info=True) + return Command( + update={ + "messages": [ + ToolMessage( + "Error: Failed to persist image in shared blob storage", + tool_call_id=tool_call_id, + ) + ] + }, ) - image_metadata["blob_ref"] = blob_ref.model_dump(mode="json", exclude_none=True) - except Exception: - logger.warning("Failed to persist viewed image in shared blob storage", exc_info=True) - return Command( - update={ - "messages": [ - ToolMessage( - "Error: Failed to persist image in shared blob storage", - tool_call_id=tool_call_id, - ) - ] - }, - ) if read_source_sandbox_id is not None: image_metadata["source_sandbox_id"] = read_source_sandbox_id new_viewed_images = {image_path: image_metadata} diff --git a/backend/packages/harness/deerflow/tools/tools.py b/backend/packages/harness/deerflow/tools/tools.py index ca2dc273585..f03607b3336 100644 --- a/backend/packages/harness/deerflow/tools/tools.py +++ b/backend/packages/harness/deerflow/tools/tools.py @@ -173,6 +173,7 @@ def get_available_tools( app_config: AppConfig | None = None, extensions=None, chat_model: BaseChatModel | None = None, + incognito: bool = False, ) -> list[BaseTool]: """Get all available tools from config. @@ -197,6 +198,10 @@ def get_available_tools( scheduler_capability: Current-run host grant for conversation schedule management or own-schedule stopping. Omitted for embedded, bootstrap and subagent assembly. + incognito: Whether the run belongs to an incognito thread. Durable + batch tools stay off there: their rows store each item's prompt and + execution spec, so they are a durable object derived from the + conversation. Returns: List of available tools. @@ -255,7 +260,11 @@ def get_available_tools( # Add subagent tools only if enabled via runtime parameter if subagent_enabled: builtin_tools.extend(SUBAGENT_TOOLS) - if is_subagent_batch_runtime_available(): + # Durable batch rows store each item's prompt and execution spec, so + # they are a durable object derived from the conversation. An incognito + # run keeps the in-process task tool but never the batch tools; the + # tool itself refuses as well, for re-attached copies. + if not incognito and is_subagent_batch_runtime_available(): from deerflow.subagents.batch_runtime import get_subagent_batch_submitter from deerflow.tools.builtins.batch_task_tool import bind_batch_tools diff --git a/backend/tests/_router_auth_helpers.py b/backend/tests/_router_auth_helpers.py index b3c8dfcd45c..c43f769d4d7 100644 --- a/backend/tests/_router_auth_helpers.py +++ b/backend/tests/_router_auth_helpers.py @@ -75,14 +75,23 @@ class _StubAuthMiddleware(BaseHTTPMiddleware): authenticated context and skips its own re-authentication path. """ - def __init__(self, app: ASGIApp, user_factory: Callable[[], User], bind_current_user: bool = False) -> None: + def __init__(self, app: ASGIApp, user_factory: Callable[[], User], bind_current_user: bool = False, auth_source: str | None = None) -> None: super().__init__(app) self._user_factory = user_factory self._bind_current_user = bind_current_user + self._auth_source = auth_source async def dispatch(self, request: Request, call_next: Callable) -> Response: user = self._user_factory() request.state.user = user + # Production always stamps an auth source. Only stamp it when a test + # explicitly opts in: get_current_user_from_request treats a stamped + # session as an identified owner, which turns on per-user run/event + # filters. Legacy fixtures persist rows with user_id=None, so leaving + # the default unstamped preserves their no-filter behavior. Tests that + # gate on the auth source (e.g. incognito creation) pass it explicitly. + if self._auth_source is not None: + request.state.auth_source = self._auth_source request.state.auth = AuthContext(user=user, permissions=list(_STUB_PERMISSIONS)) if not self._bind_current_user: return await call_next(request) @@ -98,6 +107,7 @@ def make_authed_test_app( user_factory: Callable[[], User] | None = None, owner_check_passes: bool = True, bind_current_user: bool = False, + auth_source: str | None = None, ) -> FastAPI: """Build a FastAPI test app with stub auth + permissive thread_store. @@ -111,6 +121,10 @@ def make_authed_test_app( permission failures surface correctly. bind_current_user: Also bind the stub user to the request's user context when a test needs to assert owner-scoped behavior. + auth_source: When set, stamp ``request.state.auth_source`` with this + value. Leave unset for the legacy fixtures that persist rows with + ``user_id=None``; a stamped session activates per-user run/event + filters for those rows. Source-gated routes pass it explicitly. Returns: A ``FastAPI`` app with the stub middleware installed and @@ -119,10 +133,13 @@ def make_authed_test_app( """ factory = user_factory or _make_stub_user app = FastAPI() - app.add_middleware(_StubAuthMiddleware, user_factory=factory, bind_current_user=bind_current_user) + app.add_middleware(_StubAuthMiddleware, user_factory=factory, bind_current_user=bind_current_user, auth_source=auth_source) repo = MagicMock() repo.check_access = AsyncMock(return_value=owner_check_passes) + # Routes that read the row themselves (the delete guard) see a missing one; + # a MagicMock attribute is not awaitable. + repo.get = AsyncMock(return_value=None) app.state.thread_store = repo return app diff --git a/backend/tests/test_agent_assembly_descriptor.py b/backend/tests/test_agent_assembly_descriptor.py index 17165e1ed50..724a5fd4de8 100644 --- a/backend/tests/test_agent_assembly_descriptor.py +++ b/backend/tests/test_agent_assembly_descriptor.py @@ -244,6 +244,32 @@ def test_assemble_returns_both_the_graph_and_a_descriptor(self, monkeypatch): assert assembly.effective_model == assembly.descriptor.effective_model assert assembly.descriptor.fingerprint + def test_assemble_passes_the_admission_pinned_incognito_marker_to_the_prompt(self, monkeypatch): + from deerflow.agents.lead_agent import agent as lead_agent_module + from deerflow.agents.lead_agent.agent import assemble_lead_agent + from deerflow.extensions import bind_agent_build_extensions + from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY + + self._isolate_from_the_ambient_config(monkeypatch) + prompt_calls = [] + + def render_prompt(**kwargs): + prompt_calls.append(kwargs) + return "prompt" + + monkeypatch.setattr(lead_agent_module, "apply_prompt_template", render_prompt) + with bind_agent_build_extensions(self._extensions_with_an_agent_assembly_observer()): + assemble_lead_agent( + { + "configurable": {"thread_id": "t-incognito"}, + "context": {INCOGNITO_CONTEXT_KEY: True}, + } + ) + assemble_lead_agent({"configurable": {"thread_id": "t-ordinary"}}) + + assert prompt_calls[0]["incognito"] is True + assert prompt_calls[1]["incognito"] is False + def test_descriptor_hashes_the_same_scoped_prompt_passed_to_the_graph(self, monkeypatch): from deerflow_extension_api import canonical_hash diff --git a/backend/tests/test_batch_dependencies.py b/backend/tests/test_batch_dependencies.py index 98f9f52520b..18203c394d5 100644 --- a/backend/tests/test_batch_dependencies.py +++ b/backend/tests/test_batch_dependencies.py @@ -148,3 +148,66 @@ async def test_capped_attempt_can_retry_before_releasing_its_dependent(repo): ready = await claim(repo) assert [item["item_key"] for item in ready] == ["b"] assert ready[0]["attempt"] == 1 + + +async def _count_dependency_rows() -> int: + """Read the raw dependency edges; no public projection exposes them.""" + from sqlalchemy import func, select + + from deerflow.persistence.subagent_batches.model import SubagentBatchDependencyRow + + session_factory = get_session_factory() + async with session_factory() as session: + return int(await session.scalar(select(func.count()).select_from(SubagentBatchDependencyRow)) or 0) + + +@pytest.mark.asyncio +async def test_delete_by_thread_removes_batches_items_and_dependencies(repo): + """Purge must leave nothing behind: batch, item prompt text, and dependency edges. + + ``suppress_thread_continuations`` only fences in-flight continuations; the + durable rows stay readable. An incognito sweep and a user delete both call + this to remove them. Rows go dependency-first so the result does not rely on + ``ondelete=CASCADE`` being enforced by the backend, and a sibling thread's + batch under the same owner is untouched. + """ + await create( + repo, + [ + {"key": "a", "prompt": "Read sales"}, + {"key": "b", "prompt": "Combine A", "depends_on": ["a"]}, + ], + batch_id="batch-target", + submission_key="run:call-target", + thread_id="thread-secret", + ) + await create( + repo, + [{"key": "x", "prompt": "Keep me"}], + batch_id="batch-sibling", + submission_key="run:call-sibling", + thread_id="thread-keep", + ) + assert await _count_dependency_rows() == 1 + + removed = await repo.delete_by_thread("thread-secret", user_id="owner") + + assert removed == 1 + assert await repo.get_batch("batch-target", user_id="owner") is None + assert await _count_dependency_rows() == 0 + # The sibling thread under the same owner is untouched. + assert (await repo.get_batch("batch-sibling", user_id="owner"))["id"] == "batch-sibling" + assert len(await repo.list_items("batch-sibling", user_id="owner")) == 1 + + +@pytest.mark.asyncio +async def test_delete_by_thread_is_scoped_to_the_owner(repo): + """A delete never crosses owners: it scopes by ``user_id`` like the other repos.""" + await create(repo, [{"key": "a", "prompt": "Owner one"}], batch_id="batch-one", submission_key="run:one", user_id="owner", thread_id="shared-thread") + await create(repo, [{"key": "b", "prompt": "Owner two"}], batch_id="batch-two", submission_key="run:two", user_id="other", thread_id="shared-thread") + + removed = await repo.delete_by_thread("shared-thread", user_id="owner") + + assert removed == 1 + assert await repo.get_batch("batch-one", user_id="owner") is None + assert (await repo.get_batch("batch-two", user_id="other"))["id"] == "batch-two" diff --git a/backend/tests/test_batch_result_reader.py b/backend/tests/test_batch_result_reader.py index a571f18d7ca..c72199586b6 100644 --- a/backend/tests/test_batch_result_reader.py +++ b/backend/tests/test_batch_result_reader.py @@ -418,6 +418,12 @@ async def test_gateway_tool_assembly_gating_and_config_binding(env, monkeypatch) raw = await tools["read_batch_result"].coroutine(runtime=runtime(), batch_id=batch) assert json.loads(raw)["status"] == "ok" and len(raw) <= 500 assert "read_batch_result" not in {t.name for t in get_available_tools(app_config=config, subagent_enabled=False)} + # An incognito run keeps the in-process task tool but never the durable + # batch family: those rows store prompts and execution specs and would + # outlive the chat. + incognito_names = {t.name for t in get_available_tools(app_config=config, subagent_enabled=True, incognito=True)} + assert incognito_names.isdisjoint({"batch_task", "batch_status", "cancel_batch", "read_batch_result"}) + assert "task" in incognito_names set_subagent_batch_submitter(None) assert json.loads(await tools["read_batch_result"].coroutine(runtime=runtime(), batch_id=batch)) == {"status": "unavailable"} assert "read_batch_result" not in {t.name for t in get_available_tools(app_config=config, subagent_enabled=True)} diff --git a/backend/tests/test_batch_service_incognito.py b/backend/tests/test_batch_service_incognito.py new file mode 100644 index 00000000000..fce7b335c4f --- /dev/null +++ b/backend/tests/test_batch_service_incognito.py @@ -0,0 +1,91 @@ +"""The batch worker rebuilds the incognito verdict from the durable spec. + +Incognito runs no longer bind the durable batch tools, so this path now serves +rows created before that change (and any re-attached caller). It stays because +those rows must not lose their blob-write protection when a worker replays +them: a batch item can execute on another process after a restart, where the +only record of the parent run is the stored ``execution_spec``. Reconstructing +the executor's ``incognito`` flag from that spec matches the in-process +task-tool propagation those rows were created with. +""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from test_extension_task_store_runtime import _subagent_env as _subagent_env + +from deerflow.config.subagent_batches_config import SubagentBatchesConfig +from deerflow.config.subagent_runtime_config import SubagentRuntimeConfig +from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY +from deerflow.subagents import batch_service as service_module +from deerflow.tools import tools as assembly + + +@pytest.mark.asyncio +@pytest.mark.parametrize("incognito", [True, False]) +async def test_batch_worker_rebuilds_incognito_marker_from_spec(monkeypatch, _subagent_env, incognito): + captured = {} + repo = SimpleNamespace( + renew_item_lease=AsyncMock(return_value={"valid": True}), + finalize_item=AsyncMock(return_value=True), + ) + config = SimpleNamespace( + tools=[], + models=[], + acp_agents={}, + get_model_config=lambda name: None, + authorization=SimpleNamespace(enabled=False), + tool_search=SimpleNamespace(enabled=False), + ) + service = service_module.SubagentBatchService( + repository=repo, + config=SubagentBatchesConfig(), + runtime_config=SubagentRuntimeConfig(), + app_config=config, + ) + spec = { + "subagent_config": {"name": "researcher", "description": "d", "system_prompt": "p"}, + "parent_model": "model-a", + "mcp_plugins": [], + "tool_groups": [], + } + if incognito: + spec[INCOGNITO_CONTEXT_KEY] = True + item = { + "id": "item-1", + "item_key": "key-1", + "prompt": "research one source", + "batch": {"id": "batch-1", "thread_id": "thread-1", "user_id": "user-1", "run_id": None, "execution_spec": spec}, + } + + monkeypatch.setattr(assembly, "BUILTIN_TOOLS", []) + monkeypatch.setattr(assembly, "is_host_bash_allowed", lambda config: False) + monkeypatch.setattr(assembly, "is_mcp_task_runtime_available", lambda: False) + monkeypatch.setattr("deerflow.mcp.cache.get_cached_mcp_tools", lambda: []) + monkeypatch.setattr(service_module, "resolve_subagent_model_name", lambda *args, **kwargs: "model-a") + + class CaptureExecutor: + def __init__(self, **kwargs): + captured["executor_kwargs"] = kwargs + + def execute_async(self, prompt, task_id=None): + return "exec-1" + + monkeypatch.setattr(service_module, "SubagentExecutor", CaptureExecutor) + monkeypatch.setattr(service_module, "SubagentStatus", _subagent_env.SubagentStatus) + monkeypatch.setattr( + service_module, + "get_background_task_result", + lambda _: SimpleNamespace(status=service_module.SubagentStatus.COMPLETED, result="done", error=None, stop_reason=None, token_usage_records=None), + ) + monkeypatch.setattr(service_module, "cleanup_background_task", lambda _: None) + + await service._execute_item(item, lease_owner="claim-1") + + assert repo.finalize_item.await_args.kwargs["succeeded"] + forwarded = captured["executor_kwargs"].get("incognito") + if incognito: + assert forwarded is True + else: + assert forwarded is None diff --git a/backend/tests/test_batch_task_tool.py b/backend/tests/test_batch_task_tool.py index 0319167482b..efa76c713e5 100644 --- a/backend/tests/test_batch_task_tool.py +++ b/backend/tests/test_batch_task_tool.py @@ -120,6 +120,49 @@ async def test_batch_task_is_explicit_idempotent_submission( assert "running independently" in message.content +@pytest.mark.asyncio +@pytest.mark.parametrize("marker", [True, "true", 1, None]) +async def test_batch_task_refuses_incognito_and_records_only_an_exact_true_marker( + monkeypatch, + marker, +) -> None: + """A re-attached batch tool refuses an incognito run. + + New incognito runs never bind the batch tools. If one is reached anyway, + the exact boolean ``True`` must refuse before anything is submitted. Any + other marker value is ordinary, and the durable execution_spec records + nothing (legacy rows keep their own marker for cross-process replay). + """ + from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY + + submitter = AsyncMock() + submitter.submit.return_value = {"id": "subagent-batch-1", "status": "queued", "total_items": 1} + monkeypatch.setattr(tool_module, "get_subagent_batch_submitter", lambda: submitter) + monkeypatch.setattr(tool_module, "get_available_subagent_names", lambda **_kwargs: ["general-purpose"]) + monkeypatch.setattr(tool_module, "get_subagent_config", lambda *_args, **_kwargs: SubagentConfig(name="general-purpose", description="General purpose")) + + runtime = _runtime() + runtime.context[INCOGNITO_CONTEXT_KEY] = marker + + command = await tool_module.batch_task.coroutine( + runtime=runtime, + title="Research", + items=[BatchTaskItem(key="record-1", prompt="Process one")], + subagent_type="general-purpose", + tool_call_id="call-1", + ) + + if marker is True: + message = _message(command) + assert message.status == "error" + assert "incognito" in message.content + submitter.submit.assert_not_awaited() + return + + request = submitter.submit.await_args.args[0] + assert request.execution_spec.get(INCOGNITO_CONTEXT_KEY) is None + + @pytest.mark.asyncio async def test_batch_task_rejects_stale_standalone_thread_incarnation( monkeypatch, diff --git a/backend/tests/test_checkpoint_retention_service.py b/backend/tests/test_checkpoint_retention_service.py index dbaada4ab2f..c1b4ee0981d 100644 --- a/backend/tests/test_checkpoint_retention_service.py +++ b/backend/tests/test_checkpoint_retention_service.py @@ -1004,6 +1004,12 @@ class Scheduler: async def handle_run_completion(self, record: Any) -> None: completed.append(record) + class EmptyThreadStore: + # The admission hook reads the row to pin the incognito verdict; a + # missing row means an ordinary (or not-yet-created) thread. + async def get(self, thread_id: str, *, user_id: str | None = None) -> None: + return None + request = SimpleNamespace( app=SimpleNamespace( state=SimpleNamespace( @@ -1012,7 +1018,7 @@ async def handle_run_completion(self, record: Any) -> None: checkpointer=wrapped, store=object(), run_event_store=object(), - thread_store=object(), + thread_store=EmptyThreadStore(), ) ) ) diff --git a/backend/tests/test_conversation_access.py b/backend/tests/test_conversation_access.py index 260d46a6de5..55fcf6ec272 100644 --- a/backend/tests/test_conversation_access.py +++ b/backend/tests/test_conversation_access.py @@ -279,3 +279,16 @@ async def fake_run_agent(*args, **kwargs): finally: reset_current_user(user_token) reset_app_config() + + +def test_incognito_source_is_never_readable_through_a_reference(): + async def exercise(): + prepare, events, threads, _, _ = _setup() + await threads.create("secret", user_id="alice", incognito=True) + events.list_messages = AsyncMock(side_effect=AssertionError("content was accessed")) + reader, _ = prepare(["secret"]) + result = json.loads(await reader(thread_id="secret", cursor=None, limit=10)) + assert result["status"] == "unavailable" + events.list_messages.assert_not_awaited() + + asyncio.run(exercise()) diff --git a/backend/tests/test_extension_task_store_runtime.py b/backend/tests/test_extension_task_store_runtime.py index 09a8de34a0c..e7f24fc408b 100644 --- a/backend/tests/test_extension_task_store_runtime.py +++ b/backend/tests/test_extension_task_store_runtime.py @@ -146,6 +146,7 @@ def _subagent_env(): # mock; otherwise isolated execution depends on earlier test collection. import importlib + importlib.import_module("deerflow.agents.incognito_prompt") importlib.import_module("deerflow.agents.middlewares.audit_context") importlib.import_module("deerflow.authz.principal") original_modules = {name: sys.modules.get(name) for name in _MOCKED_SUBAGENT_MODULES} diff --git a/backend/tests/test_features_router.py b/backend/tests/test_features_router.py index 5a16688be19..5a5ff7e11ef 100644 --- a/backend/tests/test_features_router.py +++ b/backend/tests/test_features_router.py @@ -38,6 +38,8 @@ def _app_with_config( scheduler_running: bool = False, scheduler_tool_enabled: bool = False, channel_connections_enabled: bool | None = None, + incognito_enabled: bool = True, + incognito_idle_ttl_seconds: int = 24 * 60 * 60, ) -> FastAPI: app = FastAPI() app.state.scheduled_task_repo = object() if scheduled_task_repo_available else None @@ -62,6 +64,7 @@ def _app_with_config( scope_selection_enabled=scope_selection_enabled, ), scheduler=SimpleNamespace(enabled=scheduler_running, tool_enabled=scheduler_tool_enabled, min_once_delay_seconds=60), + incognito=SimpleNamespace(enabled=incognito_enabled, idle_ttl_seconds=incognito_idle_ttl_seconds), ) if channel_connections_enabled is not None: fake_config.channel_connections = SimpleNamespace(enabled=channel_connections_enabled) @@ -93,6 +96,7 @@ def test_features_reports_agents_api_enabled() -> None: }, "scheduled_tasks": {"available": False, "running": False, "tool_enabled": False, "min_interval_seconds": 60, "group_notifications": False}, "thread_activity": {"available": False}, + "incognito": {"enabled": True, "idle_ttl_seconds": 86400}, } @@ -118,6 +122,7 @@ def test_features_reports_agents_api_disabled() -> None: }, "scheduled_tasks": {"available": False, "running": False, "tool_enabled": False, "min_interval_seconds": 60, "group_notifications": False}, "thread_activity": {"available": False}, + "incognito": {"enabled": True, "idle_ttl_seconds": 86400}, } @@ -303,3 +308,15 @@ def test_features_reports_thread_activity_only_with_sql_persistence(run_store, r response = client.get("/api/features") assert response.status_code == 200 assert response.json()["thread_activity"] == {"available": available} + + +def test_features_reports_incognito_availability_and_idle_lifetime() -> None: + app = _app_with_config( + agents_api_enabled=True, + incognito_enabled=False, + incognito_idle_ttl_seconds=3600, + ) + with TestClient(app) as client: + response = client.get("/api/features") + assert response.status_code == 200 + assert response.json()["incognito"] == {"enabled": False, "idle_ttl_seconds": 3600} diff --git a/backend/tests/test_gateway_services.py b/backend/tests/test_gateway_services.py index 1eb0dc521d2..6e2f103a869 100644 --- a/backend/tests/test_gateway_services.py +++ b/backend/tests/test_gateway_services.py @@ -2636,8 +2636,15 @@ async def test_pending_cancel_bypasses_thread_metadata_and_logs_failure(_stub_ap from deerflow.runtime.runs.store.memory import MemoryRunStore metadata_started = asyncio.Event() - - async def get_thread(_thread_id): + reads = 0 + + async def get_thread(_thread_id, *, user_id=None): + nonlocal reads + reads += 1 + if reads == 1: + # Admission verdict read: no metadata row exists yet, so the run + # is admitted without waiting for the (hanging) metadata store. + return None metadata_started.set() try: await asyncio.Event().wait() @@ -2686,8 +2693,14 @@ async def test_thread_metadata_timeout_logs_and_run_still_starts(_stub_app_confi metadata_started = asyncio.Event() run_agent_called = asyncio.Event() + reads = 0 - async def get_thread(_thread_id): + async def get_thread(_thread_id, *, user_id=None): + nonlocal reads + reads += 1 + if reads == 1: + # Admission verdict read: no metadata row exists yet. + return None metadata_started.set() await asyncio.Event().wait() @@ -4296,14 +4309,9 @@ def test_start_run_project_resolution_failure_degrades_to_unassigned(_stub_app_c async def _scenario(): request, _run_store, _thread_store = _make_start_run_persistence_context() - class _BoomThreadStore: - async def get(self, thread_id, **kwargs): - raise RuntimeError("database is down") - - async def check_access(self, thread_id, user_id, **kwargs): - return True - - request.app.state.thread_store = _BoomThreadStore() + # Project resolution fails because no project repository is configured. + # An unreadable *thread* store would now fail admission fatally (503), + # so the resolution seam is the project side, not the thread read. request.state = SimpleNamespace(auth_source="session", user=SimpleNamespace(id="u1", system_role="user")) body = SimpleNamespace( assistant_id="lead_agent", @@ -6361,6 +6369,205 @@ async def fake_run_agent(*_args, **kwargs): assert "client_timezone" not in config.get("configurable", {}) +@pytest.mark.asyncio +@pytest.mark.parametrize("incognito", [False, True]) +async def test_incognito_threads_bind_no_scheduler_capability(_stub_app_config, incognito): + """A scheduled task outlives the conversation, so incognito binds no capability. + + Binding the capability is what makes ``schedule_task`` callable at all; + without it the tool reports ``scheduler_tools_disabled`` and never reaches + persistence. The verdict comes from the thread row ``start_run`` reads + under the goal lock, so this adds no second interpretation of the thread. An + ordinary thread keeps the capability. + """ + from unittest.mock import AsyncMock, patch + + from langgraph.store.memory import InMemoryStore + + from app.gateway.routers.thread_runs import RunCreateRequest + from app.gateway.services import start_run + from deerflow.persistence.thread_meta.memory import MemoryThreadMetaStore + from deerflow.runtime import RunManager + from deerflow.runtime.runs.store.memory import MemoryRunStore + + thread_store = MemoryThreadMetaStore(InMemoryStore()) + await thread_store.create("thread-incognito", incognito=True) + await thread_store.create("thread-ordinary") + request = _make_start_run_request(RunManager(store=MemoryRunStore()), thread_store=thread_store) + body = RunCreateRequest(input={"messages": [{"role": "user", "content": "Every weekday at 9, check the list"}]}) + capability = object() + prepare = AsyncMock(return_value=capability) + captured: dict[str, object] = {} + + async def fake_run_agent(*_args, **kwargs): + captured["ctx"] = kwargs["ctx"] + + with ( + patch("app.gateway.services.resolve_agent_factory", return_value=object()), + patch("app.gateway.services.run_agent", side_effect=fake_run_agent), + patch("app.gateway.services.scheduler_tools_enabled", return_value=True), + patch("app.gateway.scheduled_task_access.prepare_scheduler_capability", new=prepare), + ): + record = await start_run(body, "thread-incognito" if incognito else "thread-ordinary", request) + await record.task + + if incognito: + prepare.assert_not_awaited() + assert captured["ctx"].scheduler_capability is None + else: + prepare.assert_awaited_once() + assert captured["ctx"].scheduler_capability is capability + + +@pytest.mark.asyncio +async def test_scheduler_capability_is_withheld_when_thread_state_is_unknown(_stub_app_config): + """A durable task is worse than a missing tool when the verdict is absent.""" + from unittest.mock import AsyncMock, patch + + from langgraph.store.memory import InMemoryStore + + from app.gateway.services import start_run + from deerflow.persistence.thread_meta.memory import MemoryThreadMetaStore + from deerflow.runtime import RunManager + from deerflow.runtime.runs.store.memory import MemoryRunStore + + class _SlowCreateStore(MemoryThreadMetaStore): + async def create(self, *_args, **_kwargs): + await asyncio.Event().wait() + + # No row exists at admission (a brand-new interactive thread), so the + # pre-admission verdict is unknown; the metadata setup then times out. + thread_store = _SlowCreateStore(InMemoryStore()) + request = _make_start_run_request(RunManager(store=MemoryRunStore()), thread_store=thread_store) + body = _run_create_request() + prepare = AsyncMock(return_value=object()) + captured: dict[str, object] = {} + + async def fake_run_agent(*_args, **kwargs): + captured["ctx"] = kwargs["ctx"] + + with ( + patch("app.gateway.services.resolve_agent_factory", return_value=object()), + patch("app.gateway.services.run_agent", side_effect=fake_run_agent), + patch("app.gateway.services.scheduler_tools_enabled", return_value=True), + patch("app.gateway.services._THREAD_METADATA_SETUP_TIMEOUT_SECONDS", 0.05), + patch("app.gateway.scheduled_task_access.prepare_scheduler_capability", new=prepare), + ): + record = await start_run(body, "thread-state-unknown", request) + await record.task + + prepare.assert_not_awaited() + assert captured["ctx"].scheduler_capability is None + + +@pytest.mark.asyncio +async def test_start_run_rejects_an_expired_incognito_thread_before_admission(_stub_app_config): + """A run admitted to a tombstoned thread would write data no sweep can reach.""" + from datetime import UTC, datetime, timedelta + from unittest.mock import patch + + from fastapi import HTTPException + from langgraph.store.memory import InMemoryStore + + from app.gateway.services import start_run + from deerflow.persistence.thread_meta.memory import MemoryThreadMetaStore + from deerflow.runtime import RunManager + from deerflow.runtime.runs.store.memory import MemoryRunStore + + thread_store = MemoryThreadMetaStore(InMemoryStore()) + await thread_store.create("thread-expired", incognito=True, expires_at=datetime.now(UTC) - timedelta(minutes=1)) + request = _make_start_run_request(RunManager(store=MemoryRunStore()), thread_store=thread_store) + body = _run_create_request() + started = False + + async def fake_run_agent(*_args, **_kwargs): + nonlocal started + started = True + + with ( + patch("app.gateway.services.resolve_agent_factory", return_value=object()), + patch("app.gateway.services.run_agent", side_effect=fake_run_agent), + ): + with pytest.raises(HTTPException) as caught: + await start_run(body, "thread-expired", request) + + assert caught.value.status_code == 404 + assert not started + + +@pytest.mark.asyncio +async def test_start_run_fails_closed_when_the_thread_verdict_cannot_be_read(_stub_app_config): + """Choosing a persistence policy on an unreadable store would leak writes.""" + from unittest.mock import patch + + from fastapi import HTTPException + + from app.gateway.services import start_run + from deerflow.runtime import RunManager + from deerflow.runtime.runs.store.memory import MemoryRunStore + + class _BrokenStore: + async def get(self, *_args, **_kwargs): + raise RuntimeError("thread store down") + + async def check_access(self, *_args, **_kwargs): + return True + + request = _make_start_run_request(RunManager(store=MemoryRunStore()), thread_store=_BrokenStore()) + body = _run_create_request() + started = False + + async def fake_run_agent(*_args, **_kwargs): + nonlocal started + started = True + + with ( + patch("app.gateway.services.resolve_agent_factory", return_value=object()), + patch("app.gateway.services.run_agent", side_effect=fake_run_agent), + ): + with pytest.raises(HTTPException) as caught: + await start_run(body, "thread-unreadable", request) + + assert caught.value.status_code == 503 + assert not started + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("thread_id", "incognito", "expected"), [("thread-live-secret", True, True), ("thread-live-plain", False, False)]) +async def test_start_run_pins_the_incognito_verdict_before_admission(_stub_app_config, thread_id, incognito, expected): + from unittest.mock import AsyncMock, patch + + from langgraph.store.memory import InMemoryStore + + from app.gateway.services import start_run + from deerflow.persistence.thread_meta.memory import MemoryThreadMetaStore + from deerflow.runtime import RunManager + from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY + from deerflow.runtime.runs.store.memory import MemoryRunStore + + thread_store = MemoryThreadMetaStore(InMemoryStore()) + await thread_store.create(thread_id, incognito=incognito) + request = _make_start_run_request(RunManager(store=MemoryRunStore()), thread_store=thread_store) + body = _run_create_request() + captured: dict[str, object] = {} + + async def fake_run_agent(*_args, **kwargs): + captured["config"] = kwargs["config"] + + with ( + patch("app.gateway.services.resolve_agent_factory", return_value=object()), + patch("app.gateway.services.run_agent", side_effect=fake_run_agent), + patch("app.gateway.services.scheduler_tools_enabled", return_value=True), + patch("app.gateway.scheduled_task_access.prepare_scheduler_capability", new=AsyncMock(return_value=None)), + ): + record = await start_run(body, thread_id, request) + await record.task + + # The verdict reaches the worker before durable admission; the hook no + # longer has to discover it, and a later metadata timeout cannot erase it. + assert captured["config"]["context"][INCOGNITO_CONTEXT_KEY] is expected + + @pytest.mark.asyncio @pytest.mark.parametrize("carrier", ["context", "config.context", "config.configurable", "both-config-sections"]) async def test_start_run_forwards_sanitized_client_context_to_runtime_context_only(_stub_app_config, carrier): diff --git a/backend/tests/test_incognito_config.py b/backend/tests/test_incognito_config.py new file mode 100644 index 00000000000..c9fc5653946 --- /dev/null +++ b/backend/tests/test_incognito_config.py @@ -0,0 +1,66 @@ +"""Incognito config bounds and the idle-window / absolute-lifetime relationship.""" + +import pytest +from pydantic import ValidationError + +from deerflow.config.incognito_config import IncognitoThreadsConfig + + +def test_idle_window_beyond_the_absolute_lifetime_is_rejected() -> None: + # A longer idle window would never take effect: the first activity pins + # the deadline back to the ceiling, so the pair is a configuration error. + with pytest.raises(ValidationError, match="must not exceed"): + IncognitoThreadsConfig( + idle_ttl_seconds=8 * 24 * 60 * 60, + max_lifetime_seconds=7 * 24 * 60 * 60, + ) + + +def test_idle_window_equal_to_the_absolute_lifetime_is_allowed() -> None: + config = IncognitoThreadsConfig(idle_ttl_seconds=3600, max_lifetime_seconds=3600) + + assert config.idle_ttl_seconds == 3600 + assert config.max_lifetime_seconds == 3600 + + +def test_defaults_satisfy_the_relationship() -> None: + config = IncognitoThreadsConfig() + + assert config.idle_ttl_seconds < config.max_lifetime_seconds + + +def test_idle_window_below_one_hour_is_rejected() -> None: + # Renewal happens on runs only, so a shorter window can expire a chat + # while the user is still writing, or right after a long run finishes. + with pytest.raises(ValidationError, match="greater than or equal to 3600"): + IncognitoThreadsConfig(idle_ttl_seconds=3599) + + +def test_lifetime_above_one_year_is_rejected() -> None: + # Larger values overflow the datetime arithmetic that sets the deadline. + with pytest.raises(ValidationError, match="less than or equal to 31536000"): + IncognitoThreadsConfig(max_lifetime_seconds=365 * 24 * 60 * 60 + 1) + + +def test_boundary_values_are_accepted() -> None: + shortest = IncognitoThreadsConfig(idle_ttl_seconds=3600, max_lifetime_seconds=3600, end_grace_seconds=0) + longest = IncognitoThreadsConfig( + idle_ttl_seconds=365 * 24 * 60 * 60, + max_lifetime_seconds=365 * 24 * 60 * 60, + end_grace_seconds=365 * 24 * 60 * 60, + ) + + assert shortest.idle_ttl_seconds == 3600 + assert shortest.end_grace_seconds == 0 + assert longest.max_lifetime_seconds == 31536000 + assert longest.end_grace_seconds == 31536000 + + +@pytest.mark.parametrize("seconds", [31536001, 10_000 * 365 * 24 * 60 * 60], ids=["one-second-over", "datetime-overflow"]) +def test_end_grace_above_one_year_is_rejected(seconds: int) -> None: + with pytest.raises(ValidationError) as exc_info: + IncognitoThreadsConfig(end_grace_seconds=seconds) + + error = exc_info.value.errors()[0] + assert error["loc"] == ("end_grace_seconds",) + assert error["type"] == "less_than_equal" diff --git a/backend/tests/test_incognito_durable_writes.py b/backend/tests/test_incognito_durable_writes.py new file mode 100644 index 00000000000..01638b6a9b9 --- /dev/null +++ b/backend/tests/test_incognito_durable_writes.py @@ -0,0 +1,190 @@ +"""Incognito runs skip every durable write the agent normally performs. + +The marker is pinned at admission and hoisted into the runtime context (see +``test_incognito_run_context.py``); these tests drive each write surface with +that context and assert the memory backend and the shared blob store stay +untouched. Thread-scoped files (workspace, uploads, outputs) still work and +are purged with the thread by the lifecycle sweep. +""" + +from __future__ import annotations + +import asyncio +import base64 +import importlib +import json +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +from langchain_core.messages import AIMessage, HumanMessage, ToolMessage +from langgraph.runtime import Runtime + +from deerflow.agents.memory import summarization_hook +from deerflow.agents.memory.tools import memory_add_tool, memory_delete_tool, memory_update_tool +from deerflow.agents.middlewares import memory_middleware as memory_middleware_module +from deerflow.agents.middlewares.memory_middleware import MemoryMiddleware +from deerflow.agents.middlewares.summarization_middleware import SummarizationEvent +from deerflow.config.memory_config import MemoryConfig +from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY, is_incognito_runtime + +# Minimal 1x1 PNG, the same fixture the view_image tests use. +PNG_BYTES = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==") + + +def _runtime(**context) -> Runtime: + return Runtime(context={"thread_id": "secret", "user_id": "alice", **context}) + + +def _incognito_runtime() -> Runtime: + return _runtime(**{INCOGNITO_CONTEXT_KEY: True}) + + +def test_only_the_server_boolean_marks_a_run_incognito(): + assert is_incognito_runtime(_incognito_runtime()) + assert not is_incognito_runtime(_runtime()) + # A persisted string or another truthy value is not the marker. + assert not is_incognito_runtime(_runtime(**{INCOGNITO_CONTEXT_KEY: "true"})) + assert not is_incognito_runtime(_runtime(**{INCOGNITO_CONTEXT_KEY: 1})) + assert not is_incognito_runtime(SimpleNamespace(context=None)) + assert not is_incognito_runtime(None) + + +def test_memory_middleware_skips_incognito_capture(monkeypatch): + manager = MagicMock() + monkeypatch.setattr(memory_middleware_module, "get_memory_manager", lambda: manager) + middleware = MemoryMiddleware(memory_config=MemoryConfig(enabled=True)) + state = {"messages": [HumanMessage("secret"), AIMessage("ok")]} + + assert middleware.after_agent(state, _incognito_runtime()) is None + assert asyncio.run(middleware.aafter_agent(state, _incognito_runtime())) is None + + manager.add.assert_not_called() + manager.aadd.assert_not_called() + + +def test_compaction_flush_skips_incognito(monkeypatch): + manager = MagicMock() + monkeypatch.setattr(summarization_hook, "get_memory_manager", lambda: manager) + monkeypatch.setattr(summarization_hook, "get_memory_config", lambda: SimpleNamespace(enabled=True)) + event = SummarizationEvent( + messages_to_summarize=(HumanMessage("secret"),), + preserved_messages=(), + thread_id="secret", + agent_name=None, + runtime=_incognito_runtime(), + ) + + summarization_hook.memory_flush_hook(event) + + manager.add_nowait.assert_not_called() + + +def test_memory_write_tools_refuse_incognito(monkeypatch): + manager = MagicMock() + monkeypatch.setattr("deerflow.agents.memory.tools.get_memory_manager", lambda: manager) + runtime = _incognito_runtime() + + results = [ + memory_add_tool.func(runtime, "secret preference"), + memory_update_tool.func(runtime, "fact-1", content="secret"), + memory_delete_tool.func(runtime, "fact-1"), + ] + + for result in results: + assert "incognito" in json.loads(result)["error"].lower() + assert manager.mock_calls == [] + + +def test_tool_output_blobs_are_skipped_for_incognito(tmp_path: Path, monkeypatch): + from deerflow.agents.middlewares import tool_output_budget_middleware as budget + + store = MagicMock() + monkeypatch.setattr(budget, "get_blob_store_if_enabled", lambda: store) + config = budget.ToolOutputConfig(externalize_min_chars=100, fallback_max_chars=50) + message = ToolMessage(content="x" * 500, name="web_fetch", tool_call_id="tc-1") + + patched = budget._patch_tool_message(message, config, str(tmp_path), persist_blobs=False) + + assert patched is not message + store.put_bytes.assert_not_called() + # The full output still externalizes into the thread's own outputs tree. + assert any(path.is_file() for path in tmp_path.rglob("*")) + + budget._patch_tool_message(message, config, str(tmp_path)) + store.put_bytes.assert_called_once() + + +def test_tool_output_wrapper_reads_the_incognito_marker(tmp_path: Path, monkeypatch): + from langchain.agents.middleware import ToolCallRequest + + from deerflow.agents.middlewares.tool_output_budget_middleware import ToolOutputBudgetMiddleware, ToolOutputConfig + + store = MagicMock() + monkeypatch.setattr("deerflow.agents.middlewares.tool_output_budget_middleware.get_blob_store_if_enabled", lambda: store) + middleware = ToolOutputBudgetMiddleware(ToolOutputConfig(externalize_min_chars=100, fallback_max_chars=50)) + message = ToolMessage(content="x" * 500, name="web_fetch", tool_call_id="tc-1") + + def call(marker: dict) -> ToolMessage: + request = ToolCallRequest( + tool_call={"name": "web_fetch", "args": {}, "id": "tc-1", "type": "tool_call"}, + tool=None, + state={}, + runtime=SimpleNamespace( + context={"thread_id": "secret", **marker}, + state={"thread_data": {"outputs_path": str(tmp_path)}}, + config={}, + ), + ) + return middleware.wrap_tool_call(request, lambda _request: message) + + patched = call({INCOGNITO_CONTEXT_KEY: True}) + assert patched is not message + store.put_bytes.assert_not_called() + + call({}) + store.put_bytes.assert_called_once() + + +def _thread_data(tmp_path: Path) -> dict[str, str]: + user_data = tmp_path / "threads" / "thread-1" / "user-data" + paths = { + "workspace_path": user_data / "workspace", + "uploads_path": user_data / "uploads", + "outputs_path": user_data / "outputs", + } + for path in paths.values(): + path.mkdir(parents=True) + return {name: str(path) for name, path in paths.items()} + + +def _view_runtime(thread_data: dict[str, str], **context) -> SimpleNamespace: + return SimpleNamespace(state={"thread_data": thread_data}, context={"thread_id": "thread-1", **context}, config={}) + + +@pytest.mark.parametrize("incognito", [True, False]) +def test_view_image_writes_a_blob_only_for_ordinary_runs(tmp_path: Path, monkeypatch, incognito: bool) -> None: + module = importlib.import_module("deerflow.tools.builtins.view_image_tool") + + thread_data = _thread_data(tmp_path) + image_path = Path(thread_data["uploads_path"]) / "sample.png" + image_path.write_bytes(PNG_BYTES) + store = MagicMock() + monkeypatch.setattr("deerflow.storage.get_blob_store_if_enabled", lambda: store) + context = {INCOGNITO_CONTEXT_KEY: True} if incognito else {} + + result = module.view_image_tool.func( + runtime=_view_runtime(thread_data, **context), + image_path="/mnt/user-data/uploads/sample.png", + tool_call_id="tc-view", + ) + + assert result.update["messages"][0].content == "Successfully read image" + viewed = result.update["viewed_images"]["/mnt/user-data/uploads/sample.png"] + if incognito: + assert "blob_ref" not in viewed + store.put_bytes.assert_not_called() + else: + assert "blob_ref" in viewed + store.put_bytes.assert_called_once() diff --git a/backend/tests/test_incognito_lifecycle.py b/backend/tests/test_incognito_lifecycle.py new file mode 100644 index 00000000000..be4bc728531 --- /dev/null +++ b/backend/tests/test_incognito_lifecycle.py @@ -0,0 +1,647 @@ +"""Incognito lifetime: deadline renewal, explicit end, tombstones and the sweep. + +The visibility contract lives in ``test_incognito_threads_router.py``; these +tests cover the clock: an active thread keeps moving its deadline, an ended +one does not grow back, and an expired one becomes an unreadable tombstone +whose data the sweep purges without ever deleting the row. +""" + +from __future__ import annotations + +from contextlib import asynccontextmanager, contextmanager +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace +from unittest.mock import AsyncMock, patch + +import pytest +from langgraph.store.memory import InMemoryStore +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +from deerflow.persistence.thread_meta.base import ( + THREAD_INCOGNITO_ENDED_METADATA_KEY, + THREAD_INCOGNITO_EXPIRED_STATUS, + incognito_deadline, + is_incognito_expired, +) +from deerflow.persistence.thread_meta.memory import MemoryThreadMetaStore +from deerflow.persistence.thread_meta.model import ThreadMetaRow +from deerflow.persistence.thread_meta.sql import ThreadMetaRepository + + +@pytest.fixture(params=["memory", "sqlite"]) +async def store(request, tmp_path): + if request.param == "memory": + yield MemoryThreadMetaStore(InMemoryStore()) + return + engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'incognito.db'}") + async with engine.begin() as connection: + await connection.run_sync(ThreadMetaRow.metadata.create_all) + yield ThreadMetaRepository(async_sessionmaker(engine, expire_on_commit=False)) + await engine.dispose() + + +async def _incognito(store, *, thread_id="secret", user_id="alice", expires_in=3600.0): + return await store.create( + thread_id, + user_id=user_id, + display_name="private notes", + metadata={"deerflow_pinned": True}, + incognito=True, + expires_at=datetime.now(UTC) + timedelta(seconds=expires_in), + ) + + +@pytest.mark.anyio +async def test_renewal_moves_the_idle_deadline_but_never_past_the_creation_ceiling(store): + await _incognito(store) + + assert await store.renew_incognito("secret", idle_ttl=timedelta(hours=2), max_lifetime=timedelta(days=30), user_id="alice") + renewed = await store.get("secret", user_id="alice") + deadline = datetime.fromisoformat(renewed["expires_at"]) + assert timedelta(hours=1, minutes=55) < deadline - datetime.now(UTC) <= timedelta(hours=2) + + # The absolute ceiling wins even when it shortens the window. + assert await store.renew_incognito("secret", idle_ttl=timedelta(days=2), max_lifetime=timedelta(minutes=30), user_id="alice") + capped = await store.get("secret", user_id="alice") + assert datetime.fromisoformat(capped["expires_at"]) - datetime.now(UTC) <= timedelta(minutes=31) + + +def test_deadline_helper_caps_every_window_at_the_creation_ceiling(): + created = datetime(2026, 1, 1, tzinfo=UTC) + + # A window shorter than the ceiling wins unchanged. + assert incognito_deadline( + now=created + timedelta(minutes=10), + created_at=created, + window=timedelta(minutes=5), + max_lifetime=timedelta(days=1), + ) == created + timedelta(minutes=15) + # Idle and grace windows both stop at the ceiling. + for window in (timedelta(days=2), timedelta(days=30)): + assert incognito_deadline( + now=created + timedelta(hours=23), + created_at=created, + window=window, + max_lifetime=timedelta(days=1), + ) == created + timedelta(days=1) + + +@pytest.mark.anyio +async def test_end_schedules_grace_only_up_to_the_creation_ceiling(store): + await _incognito(store) + + assert await store.end_incognito( + "secret", + grace=timedelta(days=30), + max_lifetime=timedelta(minutes=30), + user_id="alice", + ) + ended = await store.get("secret", user_id="alice") + created = datetime.fromisoformat(ended["created_at"]) + assert datetime.fromisoformat(ended["expires_at"]) == created + timedelta(minutes=30) + + +@pytest.mark.anyio +async def test_renewal_skips_ordinary_ended_and_tombstoned_threads(store): + await store.create("plain", user_id="alice") + assert not await store.renew_incognito("plain", idle_ttl=timedelta(hours=1), max_lifetime=timedelta(days=7), user_id="alice") + + await _incognito(store) + assert await store.end_incognito("secret", grace=timedelta(minutes=5), max_lifetime=timedelta(days=7), user_id="alice") + ended = await store.get("secret", user_id="alice") + assert ended["metadata"][THREAD_INCOGNITO_ENDED_METADATA_KEY] is True + # An end must not be undone by activity finishing inside the grace window. + assert not await store.renew_incognito("secret", idle_ttl=timedelta(hours=24), max_lifetime=timedelta(days=7), user_id="alice") + assert (await store.get("secret", user_id="alice"))["expires_at"] == ended["expires_at"] + + # The tombstone write only happens for a due row, so pass a moment past + # the end grace window. + assert await store.begin_incognito_expiry("secret", now=datetime.now(UTC) + timedelta(minutes=10)) + assert not await store.renew_incognito("secret", idle_ttl=timedelta(hours=1), max_lifetime=timedelta(days=7), user_id="alice") + + +@pytest.mark.anyio +async def test_owner_end_requires_the_incognito_owner(store): + await _incognito(store) + + assert not await store.end_incognito("secret", grace=timedelta(minutes=5), max_lifetime=timedelta(days=7), user_id="bob") + assert not await store.end_incognito("missing", grace=timedelta(minutes=5), max_lifetime=timedelta(days=7), user_id="alice") + + +@pytest.mark.anyio +async def test_tombstone_clears_content_and_makes_the_thread_unreadable(store): + await _incognito(store) + + assert await store.begin_incognito_expiry("secret", now=datetime.now(UTC) + timedelta(hours=2)) + tombstone = await store.get("secret", user_id="alice") + assert tombstone is not None + assert tombstone["status"] == THREAD_INCOGNITO_EXPIRED_STATUS + assert tombstone["display_name"] is None + assert tombstone["metadata"] == {} + assert tombstone["incognito"] is True + assert is_incognito_expired(tombstone) + assert not await store.check_access("secret", "alice", require_existing=True) + # The row still owns the id, which is what stops resurrection. + assert await store.get("secret", user_id="alice") is not None + + await store.finish_incognito_expiry("secret") + assert (await store.get("secret", user_id="alice"))["expires_at"] is None + assert is_incognito_expired(await store.get("secret", user_id="alice")) + + +@pytest.mark.anyio +async def test_due_list_holds_only_incognito_deadlines(store): + await _incognito(store, thread_id="due", expires_in=-60) + await _incognito(store, thread_id="later", expires_in=3600) + await store.create("plain", user_id="alice", expires_at=datetime.now(UTC) - timedelta(hours=1)) + await _incognito(store, thread_id="purged", expires_in=-60) + await store.begin_incognito_expiry("purged") + await store.finish_incognito_expiry("purged") + + due = await store.list_due_incognito(limit=10) + assert [row["thread_id"] for row in due] == ["due"] + assert due[0]["user_id"] == "alice" + + +@pytest.mark.anyio +async def test_expired_deadline_hides_the_thread_before_the_sweep_runs(store): + await _incognito(store, expires_in=-1) + + assert not await store.check_access("secret", "alice") + assert is_incognito_expired(await store.get("secret", user_id="alice")) + + +@pytest.mark.anyio +async def test_renewal_refuses_a_deadline_that_already_passed(store): + await _incognito(store, expires_in=-60) + before = await store.get("secret", user_id="alice") + + assert not await store.renew_incognito("secret", idle_ttl=timedelta(hours=2), max_lifetime=timedelta(days=7), user_id="alice") + + unchanged = await store.get("secret", user_id="alice") + assert unchanged["expires_at"] == before["expires_at"] + # Only the sweep writes the tombstone, but activity must not pull an + # already-expired row back from the due list. + assert unchanged["status"] == "idle" + assert is_incognito_expired(unchanged) + + +@pytest.mark.anyio +async def test_tombstone_survives_late_status_and_title_writes(store): + await _incognito(store) + assert await store.begin_incognito_expiry("secret", now=datetime.now(UTC) + timedelta(hours=2)) + + # A run finalizing on another worker writes its title and status back after + # the sweep. Those writes must not revive the tombstone, or reads resolve + # again while ``expires_at`` is cleared and the sweep never returns. + await store.update_display_name("secret", "leaked title") + await store.update_status("secret", "running") + await store.update_status("secret", "idle") + + record = await store.get("secret", user_id="alice") + assert record["status"] == THREAD_INCOGNITO_EXPIRED_STATUS + assert record["display_name"] is None + assert is_incognito_expired(record) + + +@pytest.mark.anyio +async def test_begin_expiry_skips_a_row_renewed_after_the_due_snapshot(store): + # The sweep's due list is a snapshot. Model the stale entry by renewing the + # row before the tombstone write: the store must recheck the live deadline + # instead of trusting the batch. + await _incognito(store, expires_in=5) + assert await store.renew_incognito("secret", idle_ttl=timedelta(hours=2), max_lifetime=timedelta(days=7), user_id="alice") + assert not await store.begin_incognito_expiry("secret") + record = await store.get("secret", user_id="alice") + assert record["status"] == "idle" + assert record["display_name"] == "private notes" + + # Once the renewed deadline passes, the same row is eligible again. + assert await store.begin_incognito_expiry("secret", now=datetime.now(UTC) + timedelta(hours=3)) + assert (await store.get("secret", user_id="alice"))["status"] == THREAD_INCOGNITO_EXPIRED_STATUS + + +@pytest.mark.anyio +async def test_end_incognito_is_idempotent_and_keeps_the_first_deadline(store): + await _incognito(store) + moment = datetime.now(UTC) + + assert await store.end_incognito("secret", grace=timedelta(minutes=5), max_lifetime=timedelta(days=7), now=moment, user_id="alice") + first = await store.get("secret", user_id="alice") + # A repeated end (the caller retried or closed the tab twice) must not push + # the purge deadline out again. + assert await store.end_incognito("secret", grace=timedelta(minutes=5), max_lifetime=timedelta(days=7), now=moment + timedelta(minutes=3), user_id="alice") + second = await store.get("secret", user_id="alice") + assert second["expires_at"] == first["expires_at"] + + +@pytest.mark.anyio +async def test_sweep_tombstones_purges_and_keeps_the_row(tmp_path): + from app.gateway import incognito as incognito_module + from app.gateway.routers import threads as thread_routes + + store = MemoryThreadMetaStore(InMemoryStore()) + await _incognito(store, expires_in=-60) + await _incognito(store, thread_id="later", expires_in=3600) + + reserved: list[tuple[str, dict]] = [] + + class _RunManager: + @asynccontextmanager + async def reserve_thread_operation(self, thread_id, **kwargs): + reserved.append((thread_id, kwargs)) + yield + + async def discard_thread_runs(self, thread_id): + return None + + app = SimpleNamespace( + state=SimpleNamespace( + thread_store=store, + run_manager=_RunManager(), + checkpointer=None, + run_store=None, + run_event_store=None, + mcp_task_repo=SimpleNamespace(delete_by_thread=AsyncMock()), + ) + ) + + with ( + patch.object(thread_routes, "_delete_thread_data", lambda *args, **kwargs: thread_routes.ThreadDeleteResponse(success=True, message="ok")), + patch("deerflow.community.browser_automation.get_browser_session_manager", return_value=SimpleNamespace(close_session=_noop)), + patch("deerflow.mcp.session_pool.get_session_pool", return_value=SimpleNamespace(close_thread_scope=_noop)), + ): + purged = await incognito_module.sweep_expired_incognito_threads(app, batch_size=10) + + assert purged == 1 + # MCP task rows hold remote result payloads, so the purge removes them too. + app.state.mcp_task_repo.delete_by_thread.assert_awaited_once_with("secret", user_id="alice") + assert [thread_id for thread_id, _ in reserved] == ["secret"] + tombstone = await store.get("secret", user_id="alice") + assert tombstone["status"] == THREAD_INCOGNITO_EXPIRED_STATUS + assert tombstone["display_name"] is None + assert tombstone["expires_at"] is None + assert (await store.get("later", user_id="alice"))["status"] == "idle" + + +@pytest.mark.anyio +async def test_sweep_defers_a_thread_whose_run_is_in_flight(): + from app.gateway import incognito as incognito_module + + store = MemoryThreadMetaStore(InMemoryStore()) + await _incognito(store, expires_in=-60) + + class _BusyRunManager: + @asynccontextmanager + async def reserve_thread_operation(self, thread_id, **kwargs): + from deerflow.runtime.runs.manager import ConflictError + + raise ConflictError() + yield # pragma: no cover + + app = SimpleNamespace(state=SimpleNamespace(thread_store=store, run_manager=_BusyRunManager(), checkpointer=None)) + + assert await incognito_module.sweep_expired_incognito_threads(app, batch_size=10) == 0 + record = await store.get("secret", user_id="alice") + assert record["status"] == "idle" + assert record["display_name"] == "private notes" + + +async def _noop(*args, **kwargs): + return None + + +class _RecordingRunManager: + def __init__(self): + self.reserved: list[tuple[str, dict]] = [] + + @asynccontextmanager + async def reserve_thread_operation(self, thread_id, **kwargs): + self.reserved.append((thread_id, kwargs)) + yield + + async def discard_thread_runs(self, thread_id): + return None + + +@contextmanager +def _sweep_patches(thread_routes): + with ( + patch.object(thread_routes, "_delete_thread_data", lambda *args, **kwargs: thread_routes.ThreadDeleteResponse(success=True, message="ok")), + patch("deerflow.community.browser_automation.get_browser_session_manager", return_value=SimpleNamespace(close_session=_noop)), + patch("deerflow.mcp.session_pool.get_session_pool", return_value=SimpleNamespace(close_thread_scope=_noop)), + ): + yield + + +@pytest.mark.anyio +async def test_sweep_skips_a_row_renewed_after_the_due_list_was_read(): + from app.gateway import incognito as incognito_module + + class _RacyStore(MemoryThreadMetaStore): + """Hand the sweep a stale due entry, then renew the live row.""" + + async def list_due_incognito(self, *, now=None, limit=100): + stale = await self.get("secret", user_id=None) + assert await self.renew_incognito("secret", idle_ttl=timedelta(hours=2), max_lifetime=timedelta(days=7), user_id="alice") + return [stale] + + store = _RacyStore(InMemoryStore()) + await _incognito(store, expires_in=5) + app = SimpleNamespace(state=SimpleNamespace(thread_store=store, run_manager=_RecordingRunManager(), checkpointer=None)) + + assert await incognito_module.sweep_expired_incognito_threads(app, batch_size=10) == 0 + record = await store.get("secret", user_id="alice") + assert record["status"] == "idle" + assert record["display_name"] == "private notes" + assert record["expires_at"] is not None + + +@pytest.mark.anyio +async def test_failed_purge_keeps_the_retry_marker_and_succeeds_on_the_next_sweep(): + from app.gateway import incognito as incognito_module + from app.gateway.routers import threads as thread_routes + + class _FailingRunStore: + async def delete_by_thread(self, thread_id, *, user_id): + raise RuntimeError("run store unavailable") + + class _WorkingRunStore: + async def delete_by_thread(self, thread_id, *, user_id): + return 0 + + store = MemoryThreadMetaStore(InMemoryStore()) + await _incognito(store, expires_in=-60) + state = SimpleNamespace(thread_store=store, run_manager=_RecordingRunManager(), checkpointer=None, run_store=_FailingRunStore(), run_event_store=None) + + with _sweep_patches(thread_routes): + # The tombstone is written, but the failed run deletion raises so the + # sweep does not clear ``expires_at``. + assert await incognito_module.sweep_expired_incognito_threads(SimpleNamespace(state=state), batch_size=10) == 0 + tombstone = await store.get("secret", user_id="alice") + assert tombstone["status"] == THREAD_INCOGNITO_EXPIRED_STATUS + assert tombstone["expires_at"] is not None + + state.run_store = _WorkingRunStore() + assert await incognito_module.sweep_expired_incognito_threads(SimpleNamespace(state=state), batch_size=10) == 1 + + finished = await store.get("secret", user_id="alice") + assert finished["expires_at"] is None + + +@pytest.mark.anyio +async def test_sweep_treats_a_failed_batch_cleanup_as_incomplete(): + from app.gateway import incognito as incognito_module + from app.gateway.routers import threads as thread_routes + + class _FailingBatchRepo: + async def suppress_thread_continuations(self, thread_id): + raise RuntimeError("batch store unavailable") + + async def delete_by_thread(self, thread_id, *, user_id): + raise AssertionError("suppression failed first") + + store = MemoryThreadMetaStore(InMemoryStore()) + await _incognito(store, expires_in=-60) + state = SimpleNamespace( + thread_store=store, + run_manager=_RecordingRunManager(), + checkpointer=None, + subagent_batch_repo=_FailingBatchRepo(), + ) + + with _sweep_patches(thread_routes): + # A failing batch repository must not abort the purge halfway through: + # the tombstone is written, the remaining stores are still attempted, + # and the strict contract keeps the retry marker. + assert await incognito_module.sweep_expired_incognito_threads(SimpleNamespace(state=state), batch_size=10) == 0 + + tombstone = await store.get("secret", user_id="alice") + assert tombstone["status"] == THREAD_INCOGNITO_EXPIRED_STATUS + assert tombstone["expires_at"] is not None + + +@pytest.mark.anyio +async def test_sweep_treats_a_failed_read_marker_cleanup_as_incomplete(): + from app.gateway import incognito as incognito_module + from app.gateway.routers import threads as thread_routes + + class _FailingReadRepo: + async def delete_by_thread(self, thread_id): + raise RuntimeError("read store unavailable") + + store = MemoryThreadMetaStore(InMemoryStore()) + await _incognito(store, expires_in=-60) + state = SimpleNamespace( + thread_store=store, + run_manager=_RecordingRunManager(), + checkpointer=None, + thread_read_repo=_FailingReadRepo(), + ) + + with _sweep_patches(thread_routes): + # Read markers are persisted content, so their failure is part of the + # strict contract: the row keeps its retry marker. + assert await incognito_module.sweep_expired_incognito_threads(SimpleNamespace(state=state), batch_size=10) == 0 + + tombstone = await store.get("secret", user_id="alice") + assert tombstone["status"] == THREAD_INCOGNITO_EXPIRED_STATUS + assert tombstone["expires_at"] is not None + + +@pytest.mark.anyio +async def test_best_effort_purge_survives_a_failed_batch_cleanup(): + from app.gateway.routers import threads as thread_routes + + class _FailingBatchRepo: + async def suppress_thread_continuations(self, thread_id): + raise RuntimeError("batch store unavailable") + + async def delete_by_thread(self, thread_id, *, user_id): + raise AssertionError("suppression failed first") + + state = SimpleNamespace( + run_manager=_RecordingRunManager(), + checkpointer=None, + subagent_batch_repo=_FailingBatchRepo(), + ) + + with _sweep_patches(thread_routes): + # The interactive delete route is best-effort: a broken auxiliary store + # must not turn the user's DELETE into a 500. + response = await thread_routes.purge_thread_data("secret", app_state=state, user_id="alice", delete_meta_row=False) + + assert response.success + + +def test_run_admission_pins_incognito_and_renews_the_deadline(): + import asyncio + + from app.gateway.deps import _run_admission_hook + from deerflow.config.incognito_config import IncognitoThreadsConfig + from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY + + async def scenario(): + store = MemoryThreadMetaStore(InMemoryStore()) + await _incognito(store, expires_in=60) + await store.create("plain", user_id="alice") + hook = _run_admission_hook( + checkpointer=object(), + thread_store=store, + app_config=SimpleNamespace(incognito=IncognitoThreadsConfig(idle_ttl_seconds=3600, max_lifetime_seconds=7 * 24 * 3600)), + ) + secret_config: dict = {} + plain_config: dict = {} + await hook(SimpleNamespace(run_id="r1", thread_id="secret"), secret_config) + await hook(SimpleNamespace(run_id="r2", thread_id="plain"), plain_config) + assert secret_config["context"][INCOGNITO_CONTEXT_KEY] is True + # An ordinary thread is pinned as False, not left absent: the verdict + # is established at admission so no later step has to guess it. + assert plain_config["context"][INCOGNITO_CONTEXT_KEY] is False + assert datetime.fromisoformat((await store.get("secret", user_id="alice"))["expires_at"]) - datetime.now(UTC) > timedelta(minutes=50) + + asyncio.run(scenario()) + + +def test_run_admission_fails_closed_when_the_thread_store_is_unreadable(): + import asyncio + + from app.gateway.deps import _run_admission_hook + from deerflow.config.incognito_config import IncognitoThreadsConfig + from deerflow.runtime.runs import RunAdmissionRejected + + class _BrokenStore: + async def get(self, *args, **kwargs): + raise RuntimeError("thread store down") + + async def renew_incognito(self, *args, **kwargs): + raise RuntimeError("thread store down") + + async def scenario(): + hook = _run_admission_hook( + checkpointer=object(), + thread_store=_BrokenStore(), + app_config=SimpleNamespace(incognito=IncognitoThreadsConfig(idle_ttl_seconds=3600, max_lifetime_seconds=7 * 24 * 3600)), + ) + # Without a pinned verdict the run cannot know which persistence + # policy applies. Guessing "ordinary" would write memory and shared + # blobs for an incognito thread, so admission fails instead. + with pytest.raises(RunAdmissionRejected): + await hook(SimpleNamespace(run_id="r1", thread_id="secret"), {}) + + asyncio.run(scenario()) + + +def test_run_admission_rejects_a_run_on_an_expired_thread(): + import asyncio + + from app.gateway.deps import _run_admission_hook + from deerflow.config.incognito_config import IncognitoThreadsConfig + from deerflow.runtime.runs import RunAdmissionRejected + + async def scenario(): + store = MemoryThreadMetaStore(InMemoryStore()) + await _incognito(store, expires_in=-60) + hook = _run_admission_hook( + checkpointer=object(), + thread_store=store, + app_config=SimpleNamespace(incognito=IncognitoThreadsConfig(idle_ttl_seconds=3600, max_lifetime_seconds=7 * 24 * 3600)), + ) + with pytest.raises(RunAdmissionRejected): + await hook(SimpleNamespace(run_id="r1", thread_id="secret"), {}) + + asyncio.run(scenario()) + + +def test_run_admission_rechecks_a_pinned_verdict_against_the_live_row(): + import asyncio + + from app.gateway.deps import _run_admission_hook + from deerflow.config.incognito_config import IncognitoThreadsConfig + from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY + from deerflow.runtime.runs import RunAdmissionRejected + + async def scenario(): + store = MemoryThreadMetaStore(InMemoryStore()) + hook = _run_admission_hook( + checkpointer=object(), + thread_store=store, + app_config=SimpleNamespace(incognito=IncognitoThreadsConfig(idle_ttl_seconds=3600, max_lifetime_seconds=7 * 24 * 3600)), + ) + # The pinned verdict is only a hint: another process may have swept or + # deleted the thread since start_run read it. + with pytest.raises(RunAdmissionRejected): + await hook(SimpleNamespace(run_id="r1", thread_id="secret"), {"context": {INCOGNITO_CONTEXT_KEY: True}}) + + await _incognito(store, expires_in=60) + await store.begin_incognito_expiry("secret", now=datetime.now(UTC) + timedelta(hours=2)) + with pytest.raises(RunAdmissionRejected): + await hook(SimpleNamespace(run_id="r2", thread_id="secret"), {"context": {INCOGNITO_CONTEXT_KEY: True}}) + + # A row recreated as an ordinary thread no longer matches the pinned + # policy; starting an incognito run on it would be a guess. + await store.create("ordinary", user_id="alice") + with pytest.raises(RunAdmissionRejected): + await hook(SimpleNamespace(run_id="r3", thread_id="ordinary"), {"context": {INCOGNITO_CONTEXT_KEY: True}}) + + asyncio.run(scenario()) + + +def test_run_admission_renewal_failure_never_flips_the_verdict(): + import asyncio + + from app.gateway.deps import _run_admission_hook + from deerflow.config.incognito_config import IncognitoThreadsConfig + from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY + + class _RenewFailsStore: + async def get(self, *args, **kwargs): + # A live incognito row: the hook rechecks the pinned verdict against + # the store before it renews. + return { + "thread_id": "secret", + "incognito": True, + "status": "idle", + "expires_at": (datetime.now(UTC) + timedelta(hours=1)).isoformat(), + } + + async def renew_incognito(self, *args, **kwargs): + raise RuntimeError("renewal failed") + + async def scenario(): + hook = _run_admission_hook( + checkpointer=object(), + thread_store=_RenewFailsStore(), + app_config=SimpleNamespace(incognito=IncognitoThreadsConfig(idle_ttl_seconds=3600, max_lifetime_seconds=7 * 24 * 3600)), + ) + config: dict = {"context": {INCOGNITO_CONTEXT_KEY: True}} + # Renewal is activity bookkeeping: its failure keeps the old deadline + # but must not turn an incognito run into an ordinary one. + await hook(SimpleNamespace(run_id="r1", thread_id="secret"), config) + assert config["context"][INCOGNITO_CONTEXT_KEY] is True + + asyncio.run(scenario()) + + +def test_run_completion_renews_an_incognito_thread_only(): + import asyncio + + from app.gateway.deps import _run_completion_hook + from deerflow.config.incognito_config import IncognitoThreadsConfig + + async def scenario(): + store = MemoryThreadMetaStore(InMemoryStore()) + await _incognito(store, expires_in=60) + await store.create("plain", user_id="alice") + hook = _run_completion_hook( + scheduled_task_service=None, + thread_store=store, + app_config=SimpleNamespace(incognito=IncognitoThreadsConfig(idle_ttl_seconds=3600, max_lifetime_seconds=7 * 24 * 3600)), + ) + await hook(SimpleNamespace(run_id="r1", thread_id="secret", user_id="alice")) + await hook(SimpleNamespace(run_id="r2", thread_id="plain", user_id="alice")) + renewed = await store.get("secret", user_id="alice") + assert datetime.fromisoformat(renewed["expires_at"]) - datetime.now(UTC) > timedelta(minutes=50) + assert (await store.get("plain", user_id="alice"))["expires_at"] is None + + asyncio.run(scenario()) diff --git a/backend/tests/test_incognito_run_context.py b/backend/tests/test_incognito_run_context.py new file mode 100644 index 00000000000..096bdf8eba2 --- /dev/null +++ b/backend/tests/test_incognito_run_context.py @@ -0,0 +1,26 @@ +"""The incognito marker is server-owned and survives admission to the runtime context.""" + +from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY +from deerflow.runtime.runs.worker import _build_runtime_context, _pin_admission_server_context + + +def test_caller_cannot_opt_a_run_out_of_durable_writes(): + runtime = _build_runtime_context("thread", "run", {INCOGNITO_CONTEXT_KEY: True}) + + assert INCOGNITO_CONTEXT_KEY not in runtime + + +def test_admission_pinned_incognito_is_hoisted_into_the_runtime_context(): + runtime: dict = {} + + _pin_admission_server_context({"context": {INCOGNITO_CONTEXT_KEY: True}}, runtime) + + assert runtime[INCOGNITO_CONTEXT_KEY] is True + + +def test_non_incognito_context_is_not_hoisted(): + runtime: dict = {} + + _pin_admission_server_context({"context": {}}, runtime) + + assert INCOGNITO_CONTEXT_KEY not in runtime diff --git a/backend/tests/test_incognito_threads_router.py b/backend/tests/test_incognito_threads_router.py new file mode 100644 index 00000000000..c2f3a2df279 --- /dev/null +++ b/backend/tests/test_incognito_threads_router.py @@ -0,0 +1,215 @@ +"""Incognito thread visibility at the HTTP boundary. + +The store-level contract lives in ``test_thread_meta_repo.py`` and +``test_memory_thread_meta_isolation.py``; these tests cover the router: +creation gating, the response flag, and the surfaces that must refuse an +incognito thread (project move, branch, share). +""" + +from types import SimpleNamespace +from uuid import uuid4 + +import pytest +from _router_auth_helpers import make_authed_test_app +from fastapi.testclient import TestClient +from langgraph.checkpoint.memory import InMemorySaver +from langgraph.store.memory import InMemoryStore +from test_threads_router import _PermissiveThreadMetaStore, _ThreadTestRunManager + +from app.gateway.auth_disabled import AUTH_SOURCE_PAT, AUTH_SOURCE_SESSION +from app.gateway.routers import shares, threads +from deerflow.config.incognito_config import IncognitoThreadsConfig +from deerflow.persistence.thread_meta.base import THREAD_INCOGNITO_ENDED_METADATA_KEY +from deerflow.persistence.thread_meta.memory import THREADS_NS + + +def _config(**overrides) -> SimpleNamespace: + return SimpleNamespace(incognito=IncognitoThreadsConfig(**overrides)) + + +@pytest.fixture(autouse=True) +def _router_config(monkeypatch): + # The worktree has no config.yaml and these routes only read the + # incognito block. + monkeypatch.setattr(threads, "get_config", lambda: _config()) + + +def _build_app(*, auth_source: str = AUTH_SOURCE_SESSION): + app = make_authed_test_app(auth_source=auth_source) + app.state.store = InMemoryStore() + app.state.checkpointer = InMemorySaver() + app.state.run_manager = _ThreadTestRunManager() + app.state.thread_store = _PermissiveThreadMetaStore(app.state.store) + app.include_router(threads.router) + app.include_router(shares.router) + return app + + +def _create(client: TestClient, *, incognito: bool = False, **body) -> str: + thread_id = body.pop("thread_id", uuid4().hex) + response = client.post("/api/threads", json={"thread_id": thread_id, "incognito": incognito, **body}) + assert response.status_code == 200, response.text + return thread_id + + +def test_incognito_thread_is_hidden_from_search_but_readable_by_id(monkeypatch): + class _Accessor: + async def aget(self, config): + return SimpleNamespace(config={}, values={}, metadata={}, created_at="", tasks=[], next=[]) + + async def _fake_accessor(request, **kwargs): + return _Accessor(), {"configurable": {"thread_id": kwargs["thread_id"]}} + + monkeypatch.setattr(threads, "abuild_checkpoint_state_accessor", _fake_accessor) + + client = TestClient(_build_app()) + secret_id = _create(client, incognito=True) + visible_id = _create(client) + + listed = client.post("/api/threads/search", json={}) + assert [thread["thread_id"] for thread in listed.json()] == [visible_id] + + fetched = client.get(f"/api/threads/{secret_id}") + assert fetched.status_code == 200 + assert fetched.json()["incognito"] is True + + ordinary = client.get(f"/api/threads/{visible_id}") + assert ordinary.json()["incognito"] is False + + +def test_incognito_create_rejects_project_membership(): + client = TestClient(_build_app()) + response = client.post("/api/threads", json={"thread_id": uuid4().hex, "incognito": True, "project_id": "p1"}) + + assert response.status_code == 400 + assert "project" in response.json()["detail"].lower() + + +def test_incognito_create_requires_a_browser_session(): + client = TestClient(_build_app(auth_source=AUTH_SOURCE_PAT)) + response = client.post("/api/threads", json={"thread_id": uuid4().hex, "incognito": True}) + + assert response.status_code == 403 + + +def test_incognito_create_respects_the_operator_switch(monkeypatch): + monkeypatch.setattr(threads, "get_config", lambda: _config(enabled=False)) + client = TestClient(_build_app()) + response = client.post("/api/threads", json={"thread_id": uuid4().hex, "incognito": True}) + + assert response.status_code == 403 + + +def test_idempotent_create_never_converts_visibility(): + client = TestClient(_build_app()) + ordinary_id = _create(client) + incognito_id = _create(client, incognito=True) + + promote = client.post("/api/threads", json={"thread_id": ordinary_id, "incognito": True}) + demote = client.post("/api/threads", json={"thread_id": incognito_id}) + + assert promote.status_code == 409 + assert demote.status_code == 409 + + +def test_metadata_marker_seeds_an_incognito_thread_for_the_sdk_create(): + """The LangGraph SDK's implicit create can only carry metadata. + + On the first submit the SDK creates the thread itself and forwards the + submit metadata; the browser marks an incognito send there. The Gateway + must read that marker as the creation intent, otherwise the SDK's create + sees a visibility mismatch against the REST pre-create and answers 409. + """ + client = TestClient(_build_app()) + thread_id = uuid4().hex + body = {"thread_id": thread_id, "metadata": {"incognito": True}} + + created = client.post("/api/threads", json=body) + + assert created.status_code == 200, created.text + assert created.json()["incognito"] is True + # The column is the single source of truth; the hint is not re-stored. + assert "incognito" not in created.json()["metadata"] + assert [thread["thread_id"] for thread in client.post("/api/threads/search", json={}).json()] == [] + + # The SDK repeats its ensure-create while the chat is still lazy. + again = client.post("/api/threads", json=body) + assert again.status_code == 200 + + +def test_metadata_marker_never_converts_an_ordinary_thread(): + client = TestClient(_build_app()) + ordinary_id = _create(client) + + response = client.post("/api/threads", json={"thread_id": ordinary_id, "metadata": {"incognito": True}}) + + assert response.status_code == 409 + + +def test_move_rejects_incognito_thread(): + client = TestClient(_build_app()) + thread_id = _create(client, incognito=True) + + response = client.post(f"/api/threads/{thread_id}/move", json={"project_id": None}) + + assert response.status_code == 409 + + +def test_branch_rejects_incognito_thread(): + client = TestClient(_build_app()) + thread_id = _create(client, incognito=True) + + response = client.post(f"/api/threads/{thread_id}/branches", json={"message_id": "assistant-1"}) + + assert response.status_code == 409 + + +def test_share_rejects_incognito_thread(): + client = TestClient(_build_app()) + thread_id = _create(client, incognito=True) + + response = client.post(f"/api/threads/{thread_id}/shares", json={"expires_in_seconds": 3600}) + + assert response.status_code == 409 + + +def test_end_endpoint_schedules_the_grace_deadline(): + app = _build_app() + client = TestClient(app) + thread_id = _create(client, incognito=True) + + response = client.post(f"/api/threads/{thread_id}/incognito/end") + + assert response.status_code == 204, response.text + record = app.state.store.get(THREADS_NS, thread_id).value + assert record["metadata"][THREAD_INCOGNITO_ENDED_METADATA_KEY] is True + assert record["expires_at"] is not None + + +def test_end_endpoint_rejects_an_ordinary_thread(): + app = _build_app() + client = TestClient(app) + thread_id = _create(client) + + response = client.post(f"/api/threads/{thread_id}/incognito/end") + + assert response.status_code == 409 + + +def test_expired_incognito_thread_is_gone_and_cannot_be_recreated(): + app = _build_app() + client = TestClient(app) + thread_id = _create(client, incognito=True) + # The tombstone the sweep writes before purging data. + record = dict(app.state.store.get(THREADS_NS, thread_id).value) + record["status"] = "expired" + record["display_name"] = None + app.state.store.put(THREADS_NS, thread_id, record) + + assert client.get(f"/api/threads/{thread_id}").status_code == 404 + assert client.post(f"/api/threads/{thread_id}/incognito/end").status_code == 404 + # The id stays owned by the tombstone: idempotent create must not + # resurrect the thread as an ordinary one. + recreated = client.post("/api/threads", json={"thread_id": thread_id}) + assert recreated.status_code == 410 + assert client.post("/api/threads", json={"thread_id": thread_id, "incognito": True}).status_code == 410 diff --git a/backend/tests/test_lead_agent_model_resolution.py b/backend/tests/test_lead_agent_model_resolution.py index 82e67f3d1b9..5a0ddf93982 100644 --- a/backend/tests/test_lead_agent_model_resolution.py +++ b/backend/tests/test_lead_agent_model_resolution.py @@ -677,7 +677,7 @@ def _fake_create_chat_model(*, name, thinking_enabled, reasoning_effort=None, ap "reasoning_effort": "high", "app_config": app_config, } - get_available_tools.assert_called_once_with(model_name="context-model", groups=None, subagent_enabled=True, mcp_plugins=None, include_conversation_reader=False, app_config=app_config, chat_model=result["model"]) + get_available_tools.assert_called_once_with(model_name="context-model", groups=None, subagent_enabled=True, incognito=False, mcp_plugins=None, include_conversation_reader=False, app_config=app_config, chat_model=result["model"]) assert result["model"] is not None @@ -729,6 +729,51 @@ def _capture_prompt_policy(**kwargs): assert captured_prompt_policy["policy"].mode.value == "scheduled" +def test_make_lead_agent_withholds_setup_agent_in_an_incognito_bootstrap_run(monkeypatch): + """Agent creation is durable, so an incognito bootstrap run cannot offer it.""" + from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY + + app_config = _make_app_config([_make_model("safe-model", supports_thinking=False)]) + + import deerflow.tools as tools_module + + def _named_tool(name: str): + tool = MagicMock() + tool.name = name + return tool + + captured_kwargs: dict = {} + + def _assemble(**kwargs): + captured_kwargs.update(kwargs) + return [_named_tool("bash")] + + monkeypatch.setattr(lead_agent_module, "get_app_config", lambda: app_config) + monkeypatch.setattr(tools_module, "get_available_tools", _assemble) + monkeypatch.setattr(lead_agent_module, "build_middlewares", create_autospec(lead_agent_module.build_middlewares, return_value=[])) + monkeypatch.setattr(lead_agent_module, "apply_prompt_template", lambda **kwargs: "prompt") + monkeypatch.setattr(lead_agent_module, "create_chat_model", lambda **kwargs: object()) + monkeypatch.setattr(lead_agent_module, "create_agent", lambda **kwargs: kwargs) + + result = lead_agent_module.make_lead_agent( + { + "context": { + "model_name": "safe-model", + "thinking_enabled": False, + "subagent_enabled": False, + "non_interactive": True, + "is_bootstrap": True, + INCOGNITO_CONTEXT_KEY: True, + } + } + ) + + assert [tool.name for tool in result["tools"]] == ["bash"] + # The durable-batch gate lives inside tool assembly, so the flag has to + # reach it from the bootstrap path too. + assert captured_kwargs["incognito"] is True + + def test_make_lead_agent_rejects_invalid_bootstrap_agent_name(monkeypatch): app_config = _make_app_config([_make_model("safe-model", supports_thinking=False)]) @@ -1525,6 +1570,7 @@ def test_empty_allowed_subagents_disables_requested_delegation(monkeypatch, mcp_ groups=None, mcp_plugins=mcp_plugins, subagent_enabled=False, + incognito=False, include_conversation_reader=False, app_config=app_config, chat_model=ANY, diff --git a/backend/tests/test_lead_agent_prompt.py b/backend/tests/test_lead_agent_prompt.py index 7425da6a844..d583dd23836 100644 --- a/backend/tests/test_lead_agent_prompt.py +++ b/backend/tests/test_lead_agent_prompt.py @@ -193,6 +193,59 @@ def test_apply_prompt_template_includes_memory_tool_guidance_only_in_tool_mode(m assert "" not in middleware_prompt +def test_apply_prompt_template_states_the_incognito_boundary_only_when_flagged(monkeypatch): + config = SimpleNamespace( + sandbox=SimpleNamespace(mounts=[]), + skills=SimpleNamespace(container_path="/mnt/skills", use="deerflow.skills.storage.local_skill_storage:LocalSkillStorage", get_skills_path=lambda: Path("/tmp/skills")), + skill_evolution=SimpleNamespace(enabled=False), + tool_search=SimpleNamespace(enabled=False), + memory=SimpleNamespace(enabled=True, mode="tool", injection_enabled=False), + acp_agents={}, + ) + monkeypatch.setattr(prompt_module, "get_or_new_skill_storage", lambda app_config=None: SimpleNamespace(load_skills=lambda enabled_only=True: [])) + monkeypatch.setattr(prompt_module, "get_or_new_user_skill_storage", lambda user_id, app_config=None: SimpleNamespace(load_skills=lambda *, enabled_only: [])) + monkeypatch.setattr(prompt_module, "get_deferred_tools_prompt_section", lambda **kwargs: "") + monkeypatch.setattr(prompt_module, "_build_acp_section", lambda **kwargs: "") + monkeypatch.setattr(prompt_module, "get_agent_soul", lambda agent_name=None, **kwargs: "") + + incognito_prompt = prompt_module.apply_prompt_template(app_config=config, incognito=True) + ordinary_prompt = prompt_module.apply_prompt_template(app_config=config) + + assert "" in incognito_prompt + assert "can be made persistent from within the conversation" in incognito_prompt + assert "无痕模式" in incognito_prompt + assert "You cannot add, update or delete memories" in incognito_prompt + assert "Do not call a memory write tool" in incognito_prompt + assert "`task_note`" in incognito_prompt + # The write restriction must land after the tool-mode instructions it + # qualifies, so the model reads it as an override rather than a preamble. + assert incognito_prompt.index("") < incognito_prompt.index("") + assert "" not in ordinary_prompt + + +def test_incognito_sections_keep_lead_and_subagent_copy_distinct(): + from deerflow.agents.incognito_prompt import build_incognito_section + + lead = build_incognito_section("lead") + subagent = build_incognito_section("subagent") + + assert "" in lead + assert "" in subagent + assert "The interface already shows these notices" in lead + assert "The interface already shows these notices" not in subagent + assert "无痕模式" in lead + assert "无痕模式" not in subagent + # The Chinese name is a term-selection rule, not an explanation to hand + # the user: it must not describe the interface language or enumerate + # wrong translations, which invites further glosses. + assert "exactly as written; do not substitute other Chinese terms" in lead + assert "Do not use these Chinese terms in a reply in another language" in lead + assert "Chinese interface" not in lead + assert "隐身" not in lead + assert "Return your results to the lead agent" in subagent + assert "Return your results to the lead agent" not in lead + + def test_apply_prompt_template_threads_explicit_app_config_without_global_config(monkeypatch): mounts = [SimpleNamespace(container_path="/home/user/shared", read_only=False)] explicit_config = SimpleNamespace( diff --git a/backend/tests/test_lead_agent_skills.py b/backend/tests/test_lead_agent_skills.py index 0857b566577..a5d6b6756fc 100644 --- a/backend/tests/test_lead_agent_skills.py +++ b/backend/tests/test_lead_agent_skills.py @@ -553,6 +553,68 @@ def test_make_lead_agent_drops_update_agent_on_github_channel(monkeypatch): assert "read_file" in tool_names +def test_make_lead_agent_drops_update_agent_in_an_incognito_run(monkeypatch): + """An incognito run must not mutate the agent for every later chat.""" + from unittest.mock import MagicMock + + from deerflow.agents.lead_agent import agent as lead_agent_module + from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY + + monkeypatch.setattr(lead_agent_module, "_resolve_model_name", lambda x=None, **kwargs: "default-model") + monkeypatch.setattr(lead_agent_module, "create_chat_model", lambda **kwargs: "model") + monkeypatch.setattr(lead_agent_module, "build_middlewares", lambda *args, **kwargs: []) + monkeypatch.setattr(lead_agent_module, "apply_prompt_template", lambda **kwargs: "mock_prompt") + monkeypatch.setattr(lead_agent_module, "create_agent", lambda **kwargs: kwargs) + monkeypatch.setattr(lead_agent_module, "load_agent_config", lambda x, *, user_id=None: AgentConfig(name="test", skills=None)) + monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None: [_make_skill("legacy", None)]) + monkeypatch.setattr("deerflow.tools.get_available_tools", lambda **kwargs: [NamedTool("bash")]) + + mock_app_config = MagicMock() + mock_app_config.database.checkpoint_delta.snapshot_frequency = 10 + mock_app_config.get_model_config.return_value = SimpleNamespace(supports_thinking=False, supports_vision=False) + monkeypatch.setattr(lead_agent_module, "get_app_config", lambda: mock_app_config) + + kwargs_incognito = lead_agent_module.make_lead_agent({"configurable": {"agent_name": "test"}, "context": {INCOGNITO_CONTEXT_KEY: True}}) + tool_names = [t.name for t in kwargs_incognito["tools"]] + assert "update_agent" not in tool_names + assert "bash" in tool_names + + +def test_make_lead_agent_passes_the_incognito_flag_to_tool_assembly(monkeypatch): + """Durable batch tools are gated inside assembly, so the flag must reach it.""" + from unittest.mock import MagicMock + + from deerflow.agents.lead_agent import agent as lead_agent_module + from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY + + captured: dict = {} + + def _assemble(**kwargs): + captured.update(kwargs) + return [NamedTool("bash")] + + monkeypatch.setattr(lead_agent_module, "_resolve_model_name", lambda x=None, **kwargs: "default-model") + monkeypatch.setattr(lead_agent_module, "create_chat_model", lambda **kwargs: "model") + monkeypatch.setattr(lead_agent_module, "build_middlewares", lambda *args, **kwargs: []) + monkeypatch.setattr(lead_agent_module, "apply_prompt_template", lambda **kwargs: "mock_prompt") + monkeypatch.setattr(lead_agent_module, "create_agent", lambda **kwargs: kwargs) + monkeypatch.setattr(lead_agent_module, "load_agent_config", lambda x, *, user_id=None: AgentConfig(name="test", skills=None)) + monkeypatch.setattr(lead_agent_module, "_load_enabled_available_skills", lambda available_skills, *, app_config, user_id=None: [_make_skill("legacy", None)]) + monkeypatch.setattr("deerflow.tools.get_available_tools", _assemble) + + mock_app_config = MagicMock() + mock_app_config.database.checkpoint_delta.snapshot_frequency = 10 + mock_app_config.get_model_config.return_value = SimpleNamespace(supports_thinking=False, supports_vision=False) + monkeypatch.setattr(lead_agent_module, "get_app_config", lambda: mock_app_config) + + lead_agent_module.make_lead_agent({"configurable": {"agent_name": "test"}, "context": {INCOGNITO_CONTEXT_KEY: True}}) + assert captured["incognito"] is True + + captured.clear() + lead_agent_module.make_lead_agent({"configurable": {"agent_name": "test"}}) + assert captured["incognito"] is False + + def test_make_lead_agent_keeps_update_agent_on_non_webhook_channels(monkeypatch): """Direct invocation and non-webhook channels still get ``update_agent``. diff --git a/backend/tests/test_mcp_task_repository.py b/backend/tests/test_mcp_task_repository.py index b31bdc9e7ce..c4e921933c6 100644 --- a/backend/tests/test_mcp_task_repository.py +++ b/backend/tests/test_mcp_task_repository.py @@ -7,7 +7,7 @@ import pytest import pytest_asyncio -from sqlalchemy import event +from sqlalchemy import event, select from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession @@ -45,14 +45,15 @@ async def _create_working_task( task_id: str, now: datetime, user_id: str = "user-1", + thread_id: str = "thread-1", remote_task_id: str | None = None, thread_incarnation: str | None = None, ) -> dict: async with repo._sf() as session: - if await session.get(ThreadMetaRow, "thread-1") is None: + if await session.get(ThreadMetaRow, thread_id) is None: session.add( ThreadMetaRow( - thread_id="thread-1", + thread_id=thread_id, incarnation=None, user_id=user_id, metadata_json={}, @@ -64,7 +65,7 @@ async def _create_working_task( return await repo.create( task_id=task_id, user_id=user_id, - thread_id="thread-1", + thread_id=thread_id, expected_thread_incarnation=thread_incarnation, run_id="run-1", tool_call_id="call-1", @@ -124,6 +125,40 @@ async def execute(session, statement, *args, **kwargs): await asyncio.gather(task, return_exceptions=True) +@pytest.mark.asyncio +async def test_delete_by_thread_removes_every_incarnation_and_reports_count(tmp_path): + repo = await _make_repo(tmp_path) + now = datetime.now(UTC) + await _create_working_task(repo, task_id="task-a1", now=now, thread_id="thread-a") + await _create_working_task(repo, task_id="task-a2", now=now, thread_id="thread-a") + await _create_working_task(repo, task_id="task-other", now=now, thread_id="thread-b") + + # Thread cleanup is not incarnation-scoped: every task row for the thread + # goes, or its result payload would outlive the conversation. + assert await repo.delete_by_thread("thread-a", user_id="user-1") == 2 + async with repo._sf() as session: + remaining = (await session.execute(select(McpTaskRow.id).order_by(McpTaskRow.id))).scalars().all() + assert remaining == ["task-other"] + + +@pytest.mark.asyncio +async def test_delete_by_thread_is_owner_scoped_on_a_legacy_shared_thread(tmp_path): + repo = await _make_repo(tmp_path) + now = datetime.now(UTC) + # A legacy thread row with no owner matches every user's incarnation lock, + # so two users' tasks can share one thread id. + async with repo._sf() as session: + session.add(ThreadMetaRow(thread_id="shared", incarnation=None, user_id=None, metadata_json={}, created_at=now, updated_at=now)) + await session.commit() + await _create_working_task(repo, task_id="alice-task", now=now, user_id="alice", thread_id="shared") + await _create_working_task(repo, task_id="bob-task", now=now, user_id="bob", thread_id="shared") + + assert await repo.delete_by_thread("shared", user_id="alice") == 1 + async with repo._sf() as session: + remaining = (await session.execute(select(McpTaskRow.id))).scalars().all() + assert remaining == ["bob-task"] + + @pytest.mark.asyncio @pytest.mark.parametrize("operation", ["release_claim", "apply_snapshot", "apply_cancel_snapshot"]) async def test_interleaved_reclaim_fences_inflight_poll_and_cancel_mutations(tmp_path, monkeypatch, operation): diff --git a/backend/tests/test_memory_thread_meta_isolation.py b/backend/tests/test_memory_thread_meta_isolation.py index b5a2b5b725c..5b44f66ba61 100644 --- a/backend/tests/test_memory_thread_meta_isolation.py +++ b/backend/tests/test_memory_thread_meta_isolation.py @@ -13,7 +13,7 @@ from langgraph.store.memory import InMemoryStore from deerflow.persistence.projects import ProjectNotAssignableError -from deerflow.persistence.thread_meta import ThreadOwnershipConflictError +from deerflow.persistence.thread_meta import THREAD_INCOGNITO_EXPIRED_STATUS, ThreadCreateConflictError, ThreadOwnershipConflictError from deerflow.persistence.thread_meta.memory import MemoryThreadMetaStore from deerflow.runtime.user_context import reset_current_user, set_current_user @@ -96,6 +96,39 @@ async def test_duplicate_create_rejects_different_owner_without_overwrite(store) assert fetched == original +@pytest.mark.anyio +@pytest.mark.no_auto_user +async def test_create_refuses_to_overwrite_a_live_incognito_row(store): + with _as_user(USER_A): + original = await store.create("incognito-duplicate", incognito=True, metadata={"keep": True}) + with pytest.raises(ThreadCreateConflictError): + await store.create("incognito-duplicate", display_name="replacement") + fetched = await store.get("incognito-duplicate") + + assert fetched is not None + assert fetched["incognito"] is True + assert fetched["display_name"] == original["display_name"] + assert fetched["metadata"] == {"keep": True} + assert fetched["created_at"] == original["created_at"] + + +@pytest.mark.anyio +@pytest.mark.no_auto_user +async def test_create_refuses_to_overwrite_an_incognito_tombstone(store): + """The SQL store rejects this id at the primary key; memory must not revive it.""" + with _as_user(USER_A): + await store.create("incognito-tombstone", incognito=True) + await store.update_status("incognito-tombstone", THREAD_INCOGNITO_EXPIRED_STATUS) + with pytest.raises(ThreadCreateConflictError): + await store.create("incognito-tombstone", display_name="replacement") + fetched = await store.get("incognito-tombstone") + + assert fetched is not None + assert fetched["incognito"] is True + assert fetched["status"] == THREAD_INCOGNITO_EXPIRED_STATUS + assert fetched["display_name"] is None + + @pytest.mark.anyio @pytest.mark.no_auto_user async def test_concurrent_create_allows_one_owner_and_rejects_the_other(store): @@ -437,3 +470,37 @@ async def test_create_with_project_id_fails_closed(store): # Membership moves report rejection (never a silent unassign). assert await store.set_project("t-plain", "p1") is False + + +@pytest.mark.anyio +@pytest.mark.no_auto_user +async def test_incognito_threads_are_hidden_from_search(store): + from datetime import UTC, datetime, timedelta + + with _as_user(USER_A): + await store.create("visible", display_name="visible") + await store.create("secret", display_name="secret", incognito=True, expires_at=datetime.now(UTC) + timedelta(hours=2)) + + assert [r["thread_id"] for r in await store.search()] == ["visible"] + assert [r["thread_id"] for r in await store.search(query="visible")] == ["visible"] + assert [r["thread_id"] for r in await store.search(query="secret")] == [] + + fetched = await store.get("secret") + assert fetched is not None + assert fetched["incognito"] is True + assert fetched["expires_at"] is not None + + +@pytest.mark.anyio +@pytest.mark.no_auto_user +async def test_legacy_memory_record_without_incognito_flag_stays_listed(store): + with _as_user(USER_A): + await store.create("legacy") + + # Records written before the flag existed simply omit the key. + item = await store._store.aget(("threads",), "legacy") + record = dict(item.value) + record.pop("incognito", None) + await store._store.aput(("threads",), "legacy", record) + + assert [r["thread_id"] for r in await store.search()] == ["legacy"] diff --git a/backend/tests/test_migration_0047_mcp_oauth_tokens.py b/backend/tests/test_migration_0047_mcp_oauth_tokens.py index 551239a4147..799b0528aea 100644 --- a/backend/tests/test_migration_0047_mcp_oauth_tokens.py +++ b/backend/tests/test_migration_0047_mcp_oauth_tokens.py @@ -44,9 +44,10 @@ async def test_0047_remains_in_the_single_migration_chain(): - assert bootstrap._get_head_revision() == "0055_thread_shares" + assert bootstrap._get_head_revision() == "0056_incognito_threads" script = ScriptDirectory(str(bootstrap._MIGRATIONS_DIR)) - assert script.get_heads() == ["0055_thread_shares"] + assert script.get_heads() == ["0056_incognito_threads"] + assert script.get_revision("0056_incognito_threads").down_revision == "0055_thread_shares" assert script.get_revision("0055_thread_shares").down_revision == "0054_project_memory" assert script.get_revision("0054_project_memory").down_revision == "0053_tool_approvals" assert script.get_revision("0053_tool_approvals").down_revision == "0052_batch_continuation" diff --git a/backend/tests/test_migration_0056_incognito_threads.py b/backend/tests/test_migration_0056_incognito_threads.py new file mode 100644 index 00000000000..c5726c2a890 --- /dev/null +++ b/backend/tests/test_migration_0056_incognito_threads.py @@ -0,0 +1,82 @@ +"""Migration and ORM shapes agree; ordinary rows survive the incognito columns.""" + +import asyncio +import os +import uuid +from datetime import UTC, datetime, timedelta + +import pytest +from alembic import command +from alembic.autogenerate import compare_metadata +from alembic.migration import MigrationContext +from sqlalchemy import inspect, text +from sqlalchemy.ext.asyncio import create_async_engine +from support.postgres import asyncpg_test_url + +from deerflow.persistence import bootstrap +from deerflow.persistence.base import Base +from deerflow.persistence.postgres_schema import build_asyncpg_connect_args +from deerflow.persistence.thread_meta.model import ThreadMetaRow + + +def _columns(sync_conn) -> set[str]: + return {column["name"] for column in inspect(sync_conn).get_columns("threads_meta")} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("backend", ["sqlite", "postgres"]) +async def test_incognito_upgrade_downgrade_and_schema(tmp_path, backend): + schema = None + if backend == "sqlite": + engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'migration.db'}") + else: + uri = os.environ.get("TEST_POSTGRES_URI") + if not uri: + pytest.skip("requires TEST_POSTGRES_URI") + schema = "incognito_migration_" + uuid.uuid4().hex + engine = create_async_engine(asyncpg_test_url(uri), connect_args=build_asyncpg_connect_args(schema)) + config = bootstrap._get_alembic_config(engine, postgres_schema=schema or "") + try: + if schema: + async with engine.begin() as conn: + await conn.execute(text(f'CREATE SCHEMA "{schema}"')) + await asyncio.to_thread(command.upgrade, config, "0055_thread_shares") + async with engine.begin() as conn: + await conn.execute( + ThreadMetaRow.__table__.insert().values(thread_id="existing", user_id="alice", display_name="Existing conversation", status="idle", metadata_json={}, created_at=datetime.now(UTC), updated_at=datetime.now(UTC)) + ) + + await asyncio.to_thread(command.upgrade, config, "0056_incognito_threads") + + async with engine.begin() as conn: + legacy = (await conn.execute(text("SELECT incognito, expires_at FROM threads_meta WHERE thread_id='existing'"))).one() + assert legacy == (None, None) + expires_at = datetime.now(UTC).replace(microsecond=0) + timedelta(hours=2) + await conn.execute(ThreadMetaRow.__table__.insert().values(thread_id="secret", user_id="alice", status="idle", metadata_json={}, incognito=True, expires_at=expires_at, created_at=datetime.now(UTC), updated_at=datetime.now(UTC))) + secret = (await conn.execute(text("SELECT incognito, expires_at FROM threads_meta WHERE thread_id='secret'"))).one() + assert secret[0] in (True, 1) + assert secret[1] is not None + + async with engine.connect() as conn: + + def schema_diff(sync): + context = MigrationContext.configure(sync, opts={"compare_type": True}) + return compare_metadata(context, Base.metadata) + + assert await conn.run_sync(schema_diff) == [] + + await asyncio.to_thread(command.downgrade, config, "0055_thread_shares") + async with engine.connect() as conn: + columns = await conn.run_sync(_columns) + assert "incognito" not in columns + assert "expires_at" not in columns + assert (await conn.execute(text("SELECT display_name FROM threads_meta WHERE thread_id='existing'"))).scalar_one() == "Existing conversation" + + await asyncio.to_thread(command.upgrade, config, "0056_incognito_threads") + async with engine.connect() as conn: + assert {"incognito", "expires_at"} <= await conn.run_sync(_columns) + finally: + if schema: + async with engine.begin() as conn: + await conn.execute(text(f'DROP SCHEMA IF EXISTS "{schema}" CASCADE')) + await engine.dispose() diff --git a/backend/tests/test_run_worker_rollback.py b/backend/tests/test_run_worker_rollback.py index 95c1173058f..2bdf92c2381 100644 --- a/backend/tests/test_run_worker_rollback.py +++ b/backend/tests/test_run_worker_rollback.py @@ -162,6 +162,70 @@ async def astream(self, graph_input, config=None, stream_mode=None, subgraphs=Fa assert record.status == RunStatus.success +@pytest.mark.anyio +async def test_admission_rejection_fails_the_run_before_the_agent_starts(): + """A host that cannot establish a durable-storage precondition aborts the run.""" + from deerflow.runtime.runs import RunAdmissionRejected + + manager = RunManager() + record = await manager.create("thread-admission-reject") + agent_started = asyncio.Event() + + class EmptyAgent: + async def astream(self, graph_input, config=None, stream_mode=None, subgraphs=False): + del graph_input, config, stream_mode, subgraphs + agent_started.set() + yield {"messages": []} + + async def reject_admission(_record, _config) -> None: + raise RunAdmissionRejected("incognito verdict unavailable") + + await run_agent( + _lease_test_bridge(), + manager, + record, + ctx=RunContext(checkpointer=None, on_run_admitted=reject_admission), + agent_factory=lambda **_kwargs: EmptyAgent(), + graph_input={}, + config={}, + ) + + assert record.status == RunStatus.error + assert "incognito verdict unavailable" in (record.error or "") + assert not agent_started.is_set() + + +@pytest.mark.anyio +async def test_ordinary_admission_hook_failure_stays_non_fatal(): + """Bookkeeping failures (cleanup, renewal) must not strand an admitted run.""" + manager = RunManager() + record = await manager.create("thread-admission-warning") + ran = False + + class EmptyAgent: + async def astream(self, graph_input, config=None, stream_mode=None, subgraphs=False): + del graph_input, config, stream_mode, subgraphs + nonlocal ran + ran = True + yield {"messages": []} + + async def failing_admission(_record, _config) -> None: + raise RuntimeError("cleanup failed") + + await run_agent( + _lease_test_bridge(), + manager, + record, + ctx=RunContext(checkpointer=None, on_run_admitted=failing_admission), + agent_factory=lambda **_kwargs: EmptyAgent(), + graph_input={}, + config={}, + ) + + assert record.status == RunStatus.success + assert ran + + @pytest.mark.anyio async def test_run_agent_releases_execution_lease_when_graph_raises(): provider = MagicMock() @@ -777,17 +841,17 @@ def test_install_runtime_context_preserves_the_pinned_project_context(): def test_pin_admission_project_context_hoists_only_the_stamped_value(): from deerflow.runtime.context_keys import PROJECT_CONTEXT_KEY - from deerflow.runtime.runs.worker import _pin_admission_project_context + from deerflow.runtime.runs.worker import _pin_admission_server_context stamped = {"project_id": "p-1", "name": "Roadmap", "instructions": "x"} runtime_ctx = {"thread_id": "record-thread", "run_id": "run-1"} - _pin_admission_project_context({"context": {PROJECT_CONTEXT_KEY: stamped}}, runtime_ctx) + _pin_admission_server_context({"context": {PROJECT_CONTEXT_KEY: stamped}}, runtime_ctx) assert runtime_ctx[PROJECT_CONTEXT_KEY] is stamped empty = {"thread_id": "record-thread", "run_id": "run-1"} - _pin_admission_project_context({"context": {}}, empty) - _pin_admission_project_context({}, empty) - _pin_admission_project_context({"context": "not-a-mapping"}, empty) + _pin_admission_server_context({"context": {}}, empty) + _pin_admission_server_context({}, empty) + _pin_admission_server_context({"context": "not-a-mapping"}, empty) assert PROJECT_CONTEXT_KEY not in empty diff --git a/backend/tests/test_scheduled_task_router_behavior.py b/backend/tests/test_scheduled_task_router_behavior.py index 5f3cf60d586..3178ef38f26 100644 --- a/backend/tests/test_scheduled_task_router_behavior.py +++ b/backend/tests/test_scheduled_task_router_behavior.py @@ -200,7 +200,7 @@ async def test_create_scheduled_task_uses_repo(): ) user = SimpleNamespace(id="user-1") - thread_store = SimpleNamespace(check_access=AsyncMock(return_value=True)) + thread_store = SimpleNamespace(check_access=AsyncMock(return_value=True), get=AsyncMock(return_value={"incognito": False})) config = _Config() old_repo = scheduled_tasks.get_scheduled_task_repo @@ -245,7 +245,7 @@ async def test_create_fresh_thread_task_does_not_require_thread_id(): ) user = SimpleNamespace(id="user-1") - thread_store = SimpleNamespace(check_access=AsyncMock(return_value=True)) + thread_store = SimpleNamespace(check_access=AsyncMock(return_value=True), get=AsyncMock(return_value={"incognito": False})) config = _Config() old_repo = scheduled_tasks.get_scheduled_task_repo @@ -378,7 +378,7 @@ async def test_update_scheduled_task_writes_repo(): request = SimpleNamespace() user = SimpleNamespace(id="user-1") config = _Config() - thread_store = SimpleNamespace(check_access=AsyncMock(return_value=True)) + thread_store = SimpleNamespace(check_access=AsyncMock(return_value=True), get=AsyncMock(return_value={"incognito": False})) old_repo = scheduled_tasks.get_scheduled_task_repo old_thread_store = scheduled_tasks.get_thread_store @@ -445,7 +445,7 @@ async def get_active_run_status(self, task_id: str): next_run_at=None, ) scheduled_tasks.get_scheduled_task_repo = lambda _request: repo - scheduled_tasks.get_thread_store = lambda _request: SimpleNamespace(check_access=AsyncMock(return_value=True)) + scheduled_tasks.get_thread_store = lambda _request: SimpleNamespace(check_access=AsyncMock(return_value=True), get=AsyncMock(return_value={"incognito": False})) scheduled_tasks.get_config = lambda: _Config() scheduled_tasks.get_optional_user_from_request = AsyncMock(return_value=SimpleNamespace(id="user-1")) @@ -517,7 +517,7 @@ async def test_update_interval_task_metadata_through_the_sql_repository(tmp_path ) assert isinstance(task["next_run_at"], str) # the serialized form the router reuses scheduled_tasks.get_scheduled_task_repo = lambda _request: repo - scheduled_tasks.get_thread_store = lambda _request: SimpleNamespace(check_access=AsyncMock(return_value=True)) + scheduled_tasks.get_thread_store = lambda _request: SimpleNamespace(check_access=AsyncMock(return_value=True), get=AsyncMock(return_value={"incognito": False})) scheduled_tasks.get_config = lambda: _Config() scheduled_tasks.get_optional_user_from_request = AsyncMock(return_value=SimpleNamespace(id="user-1")) @@ -764,7 +764,7 @@ async def test_update_rejects_running_task(): request = SimpleNamespace() user = SimpleNamespace(id="user-1") config = _Config() - thread_store = SimpleNamespace(check_access=AsyncMock(return_value=True)) + thread_store = SimpleNamespace(check_access=AsyncMock(return_value=True), get=AsyncMock(return_value={"incognito": False})) old_repo = scheduled_tasks.get_scheduled_task_repo old_thread_store = scheduled_tasks.get_thread_store @@ -955,7 +955,7 @@ async def test_create_once_task_enforces_minimum_delay(): timezone="UTC", ) user = SimpleNamespace(id="user-1") - thread_store = SimpleNamespace(check_access=AsyncMock(return_value=True)) + thread_store = SimpleNamespace(check_access=AsyncMock(return_value=True), get=AsyncMock(return_value={"incognito": False})) config = _Config(min_once_delay_seconds=60) old_repo = scheduled_tasks.get_scheduled_task_repo @@ -1045,7 +1045,7 @@ def _interval_create_request(**overrides): async def _call_create(body, repo=None, config=None): repo = repo or _Repo() user = SimpleNamespace(id="user-1") - thread_store = SimpleNamespace(check_access=AsyncMock(return_value=True)) + thread_store = SimpleNamespace(check_access=AsyncMock(return_value=True), get=AsyncMock(return_value={"incognito": False})) old_repo = scheduled_tasks.get_scheduled_task_repo old_thread_store = scheduled_tasks.get_thread_store old_config = scheduled_tasks.get_config @@ -1498,6 +1498,7 @@ async def mark_session_source(request, call_next): app.state.scheduled_task_repo = repo app.state.scheduled_task_run_repo = run_repo + app.state.thread_store.get = AsyncMock(return_value={"incognito": False}) app.state.scheduled_task_service = ScheduledTaskService(task_repo=repo, task_run_repo=run_repo, launch_run=launch, poll_interval_seconds=60, lease_seconds=120, max_concurrent_runs=3) app.include_router(scheduled_tasks.router) monkeypatch.setattr(scheduled_tasks, "get_config", lambda: _Config()) diff --git a/backend/tests/test_scheduled_task_wall_times.py b/backend/tests/test_scheduled_task_wall_times.py index cbc631d55df..d82991ffb20 100644 --- a/backend/tests/test_scheduled_task_wall_times.py +++ b/backend/tests/test_scheduled_task_wall_times.py @@ -1,6 +1,7 @@ """HTTP and conversation admission must not silently move nonexistent local times.""" from datetime import UTC, datetime +from types import SimpleNamespace from unittest.mock import AsyncMock from zoneinfo import ZoneInfo @@ -72,6 +73,31 @@ async def test_shared_admission_rejects_nonexistent_wall_time(timezone, wall_tim assert timezone in caught.value.detail["message"] +@pytest.mark.asyncio +async def test_update_rejects_moving_a_task_onto_an_incognito_thread(): + thread_store = SimpleNamespace( + check_access=AsyncMock(return_value=True), + get=AsyncMock(return_value={"thread_id": "secret", "user_id": "owner", "incognito": True}), + ) + body = ScheduledTaskUpdateRequest(context_mode="reuse_thread", thread_id="secret") + + # A PATCH can move a task onto another conversation just as create can + # mint one on it, so it must apply the same incognito rule. + with pytest.raises(HTTPException) as caught: + await validate_scheduled_task_update( + _existing("UTC"), + body.model_dump(exclude_unset=True), + user_id="owner", + thread_store=thread_store, + scheduler_config=SchedulerConfig(), + assistant_resolver=AsyncMock(), + used=0, + now=NOW, + ) + assert caught.value.status_code == 422 + assert caught.value.detail["code"] == "incognito_thread_not_schedulable" + + @pytest.mark.parametrize(("timezone", "wall_time"), GAPS) def test_resume_rejects_nonexistent_end_at(timezone, wall_time): with pytest.raises(HTTPException) as caught: diff --git a/backend/tests/test_scheduler_capability_access.py b/backend/tests/test_scheduler_capability_access.py index aa7e603becb..699b0ff7d28 100644 --- a/backend/tests/test_scheduler_capability_access.py +++ b/backend/tests/test_scheduler_capability_access.py @@ -134,6 +134,26 @@ async def test_noninteractive_runs_without_private_occurrence_authority_get_no_g assert await prepare() is None +@pytest.mark.asyncio +async def test_incognito_origin_withholds_the_gateway_grant(monkeypatch): + prepare, _, _, _, threads, *_ = _setup(monkeypatch) + threads.get.return_value = {"user_id": "alice", "incognito": True} + # A task minted in an incognito chat would keep writing listable rows for + # a conversation that is about to be purged. + assert await prepare() is None + + +@pytest.mark.asyncio +async def test_existing_grant_rejects_an_origin_that_became_incognito(monkeypatch): + prepare, repo, _, _, threads, *_ = _setup(monkeypatch) + capability = await prepare() + threads.get.return_value = {"user_id": "alice", "incognito": True} + result = await capability.manage(action="list", request={}) + assert result["status_code"] == 422 + assert result["code"] == "incognito_thread_not_schedulable" + repo.list_manageable_from_thread.assert_not_awaited() + + @pytest.mark.asyncio async def test_session_principal_and_permission_ceiling_cannot_be_widened(monkeypatch): prepare, repo, _, _, _, _, resolve, request = _setup(monkeypatch, permissions=("threads:read",)) diff --git a/backend/tests/test_setup_agent_tool.py b/backend/tests/test_setup_agent_tool.py index 180d937f86b..dac23c4cc4e 100644 --- a/backend/tests/test_setup_agent_tool.py +++ b/backend/tests/test_setup_agent_tool.py @@ -11,6 +11,7 @@ import pytest +from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY from deerflow.tools.builtins.setup_agent_tool import setup_agent # --- Helpers --- @@ -49,6 +50,20 @@ def _call_setup_agent(tmp_path: Path, soul: str, description: str, agent_name: s # --- Agent name validation tests --- +def test_setup_agent_refuses_in_an_incognito_chat(tmp_path, monkeypatch): + monkeypatch.setenv("DEER_FLOW_HOME", str(tmp_path)) + runtime = _DummyRuntime(context={"agent_name": "test-agent", INCOGNITO_CONTEXT_KEY: True}, tool_call_id="tool-1") + + result = setup_agent.func(soul="test soul", description="desc", runtime=runtime) + + messages = result.update["messages"] + assert len(messages) == 1 + assert messages[0].status == "error" + assert "incognito" in messages[0].content + # Agent creation persists outside the chat, so nothing may be written. + assert not (tmp_path / "users" / "test-user-autouse" / "agents").exists() + + def test_setup_agent_rejects_invalid_agent_name_before_writing(tmp_path, monkeypatch): monkeypatch.setenv("DEER_FLOW_HOME", str(tmp_path)) outside_dir = tmp_path.parent / "outside-target" diff --git a/backend/tests/test_subagent_executor.py b/backend/tests/test_subagent_executor.py index 92570ce1c2c..1bf98b8709a 100644 --- a/backend/tests/test_subagent_executor.py +++ b/backend/tests/test_subagent_executor.py @@ -156,6 +156,7 @@ def _setup_executor_classes(): original_executor = sys.modules.get("deerflow.subagents.executor") original_audit_context = sys.modules.get("deerflow.agents.middlewares.audit_context") original_tool_declarations = sys.modules.get("deerflow.agents.middlewares.tool_declarations") + original_incognito_prompt = sys.modules.get("deerflow.agents.incognito_prompt") original_tool_search = sys.modules.get("deerflow.tools.builtins.tool_search") original_sandbox_provider = sys.modules.get("deerflow.sandbox.sandbox_provider") original_sandbox_overwrite = sys.modules.get("deerflow.sandbox.overwrite") @@ -166,6 +167,7 @@ def _setup_executor_classes(): # sys.modules makes this fixture independent of test collection order. audit_context_module = importlib.import_module("deerflow.agents.middlewares.audit_context") tool_declarations_module = importlib.import_module("deerflow.agents.middlewares.tool_declarations") + incognito_prompt_module = importlib.import_module("deerflow.agents.incognito_prompt") tool_search_module = importlib.import_module("deerflow.tools.builtins.tool_search") sandbox_provider_module = importlib.import_module("deerflow.sandbox.sandbox_provider") sandbox_overwrite_module = importlib.import_module("deerflow.sandbox.overwrite") @@ -187,6 +189,7 @@ def _setup_executor_classes(): sys.modules["deerflow.skills.storage"] = storage_module sys.modules["deerflow.agents.middlewares.audit_context"] = audit_context_module sys.modules["deerflow.agents.middlewares.tool_declarations"] = tool_declarations_module + sys.modules["deerflow.agents.incognito_prompt"] = incognito_prompt_module sys.modules["deerflow.tools.builtins.tool_search"] = tool_search_module sys.modules["deerflow.sandbox.sandbox_provider"] = sandbox_provider_module sys.modules["deerflow.sandbox.overwrite"] = sandbox_overwrite_module @@ -243,6 +246,10 @@ def _setup_executor_classes(): sys.modules["deerflow.agents.middlewares.tool_declarations"] = original_tool_declarations else: sys.modules.pop("deerflow.agents.middlewares.tool_declarations", None) + if original_incognito_prompt is not None: + sys.modules["deerflow.agents.incognito_prompt"] = original_incognito_prompt + else: + sys.modules.pop("deerflow.agents.incognito_prompt", None) if original_tool_search is not None: sys.modules["deerflow.tools.builtins.tool_search"] = original_tool_search else: @@ -1000,6 +1007,36 @@ async def test_build_initial_state_no_skills_only_system_prompt( assert base_config.system_prompt in messages[0].content assert isinstance(messages[1], HumanMessage) + @pytest.mark.anyio + async def test_build_initial_state_states_the_incognito_boundary_only_when_flagged( + self, + classes, + base_config, + monkeypatch: pytest.MonkeyPatch, + ): + """A delegated incognito run carries the same temporary-chat rules.""" + monkeypatch.setattr( + sys.modules["deerflow.skills.storage"], + "get_or_new_user_skill_storage", + lambda user_id, *, app_config=None: SimpleNamespace(load_skills=lambda *, enabled_only: []), + ) + SubagentExecutor = classes["SubagentExecutor"] + + incognito_executor = SubagentExecutor(config=base_config, tools=[], thread_id="test-thread", incognito=True) + ordinary_executor = SubagentExecutor(config=base_config, tools=[], thread_id="test-thread") + + incognito_state, _final_tools, _deferred_setup = await incognito_executor._build_initial_state("Do the task") + ordinary_state, _final_tools, _deferred_setup = await ordinary_executor._build_initial_state("Do the task") + + incognito_system = incognito_state["messages"][0].content + ordinary_system = ordinary_state["messages"][0].content + assert "" in incognito_system + assert "You cannot add, update or delete memories" in incognito_system + assert "memory write tool" in incognito_system + assert "even when the task asks for it" in incognito_system + assert "Return your results to the lead agent" in incognito_system + assert "" not in ordinary_system + @pytest.mark.anyio async def test_prompt_overlay_surrounds_complete_system_message(self, classes): from langchain_core.messages import SystemMessage @@ -1824,6 +1861,42 @@ async def aclose(self): assert result.completed_at is not None assert stream.closed is True + @pytest.mark.anyio + @pytest.mark.parametrize("incognito", [True, False]) + async def test_aexecute_propagates_the_incognito_marker_into_child_context(self, classes, base_config, mock_agent, msg, incognito): + """An incognito parent hands the marker to the delegated loop. + + The shared durable-write gates (blob externalization, view_image) read + ``is_incognito_runtime(runtime)`` off the child's own runtime context. + Without propagation they fail open inside the subagent, so an incognito + research run would leave oversized tool output and viewed images in the + content-addressed blob store that thread purge never deletes. + """ + from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY + + SubagentExecutor = classes["SubagentExecutor"] + + final_state = {"messages": [msg.human("Do something"), msg.ai("done", "msg-1")]} + captured: dict = {} + + def capture_astream(*args, **kwargs): + captured["context"] = kwargs.get("context") + return async_iterator([final_state]) + + mock_agent.astream = capture_astream + + executor_kwargs = {"config": base_config, "tools": [], "thread_id": "test-thread"} + if incognito: + executor_kwargs["incognito"] = True + executor = SubagentExecutor(**executor_kwargs) + + with patch.object(executor, "_create_agent", return_value=mock_agent): + await executor._aexecute("Do something") + + context = captured["context"] + assert context is not None + assert (context.get(INCOGNITO_CONTEXT_KEY) is True) == incognito + @pytest.mark.anyio async def test_aexecute_marks_capacity_rejection_as_admission_failure(self, classes, base_config): SubagentExecutor = classes["SubagentExecutor"] diff --git a/backend/tests/test_subagent_routing_prompt.py b/backend/tests/test_subagent_routing_prompt.py index 4064ba72d28..8610206a048 100644 --- a/backend/tests/test_subagent_routing_prompt.py +++ b/backend/tests/test_subagent_routing_prompt.py @@ -35,6 +35,20 @@ def test_durable_batch_guidance_allows_only_explicit_prerequisites(monkeypatch) assert "depends_on" not in prompt_module._build_subagent_section(3, batch_enabled=False) +def test_incognito_prompt_hides_durable_batch_guidance(monkeypatch) -> None: + """Incognito runs do not bind the batch tools, so the prompt must not advertise them.""" + import deerflow.subagents.batch_runtime as batch_runtime + + monkeypatch.setattr(batch_runtime, "is_subagent_batch_runtime_available", lambda: True) + monkeypatch.setattr(prompt_module, "get_available_subagent_names", lambda: ["general-purpose"]) + + ordinary = prompt_module.apply_prompt_template(subagent_enabled=True) + incognito = prompt_module.apply_prompt_template(subagent_enabled=True, incognito=True) + + assert "Explicit durable batch mode" in ordinary + assert "Explicit durable batch mode" not in incognito + + def test_hard_vetoes_apply_to_parallel_dispatch_not_single_agent_chains(monkeypatch) -> None: section = _build_section(monkeypatch) diff --git a/backend/tests/test_task_tool_core_logic.py b/backend/tests/test_task_tool_core_logic.py index 14c4d39eb66..80c71d7ae2e 100644 --- a/backend/tests/test_task_tool_core_logic.py +++ b/backend/tests/test_task_tool_core_logic.py @@ -447,6 +447,51 @@ def execute_async(self, prompt, task_id=None): assert assemble_tools.call_args.kwargs["extensions"] is loaded +@pytest.mark.parametrize("marker", [True, "true", 1, None]) +def test_task_tool_forwards_only_the_server_incognito_marker_to_executor(monkeypatch, marker): + """Delegation carries the admission-pinned incognito marker, nothing looser. + + The executor rebuilds its own runtime context from this kwarg, so the shared + L4 durable-write gates inside the subagent see the same verdict as the lead. + Only the exact boolean ``True`` propagates: a persisted string or another + truthy value would let a caller opt a normal run out of durable writes. + """ + from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY + + runtime = _make_runtime() + runtime.context[INCOGNITO_CONTEXT_KEY] = marker + captured = {} + + class DummyExecutor: + def __init__(self, **kwargs): + captured["executor_kwargs"] = kwargs + + def execute_async(self, prompt, task_id=None): + return task_id or "generated-task-id" + + monkeypatch.setattr(task_tool_module, "SubagentStatus", FakeSubagentStatus) + monkeypatch.setattr(task_tool_module, "SubagentExecutor", DummyExecutor) + monkeypatch.setattr(task_tool_module, "get_subagent_config", lambda _name, **_kwargs: _make_subagent_config()) + monkeypatch.setattr( + task_tool_module, + "get_background_task_result", + lambda _: _make_result(FakeSubagentStatus.COMPLETED, result="done"), + ) + monkeypatch.setattr(task_tool_module, "get_stream_writer", lambda: lambda _event: None) + monkeypatch.setattr(task_tool_module.asyncio, "sleep", _no_sleep) + monkeypatch.setattr("deerflow.tools.get_available_tools", MagicMock(return_value=[])) + + _run_task_tool(runtime=runtime, description="test", prompt="p", subagent_type="general-purpose", tool_call_id="tc-incognito") + + # Only the server boolean reaches the executor; every other value leaves + # the kwarg absent, so the child builds an ordinary (durable) context. + forwarded = captured["executor_kwargs"].get("incognito") + if marker is True: + assert forwarded is True + else: + assert forwarded is None + + def test_task_tool_installs_and_closes_narrow_middleware_recorder(monkeypatch): journal = MagicMock() runtime = _make_runtime() diff --git a/backend/tests/test_thread_activity_router.py b/backend/tests/test_thread_activity_router.py index 504b67a0d8d..dc6c7c11b37 100644 --- a/backend/tests/test_thread_activity_router.py +++ b/backend/tests/test_thread_activity_router.py @@ -8,6 +8,7 @@ from __future__ import annotations from contextlib import asynccontextmanager +from datetime import UTC, datetime, timedelta from uuid import UUID import httpx @@ -21,6 +22,8 @@ from deerflow.persistence.base import Base from deerflow.persistence.run import RunRepository from deerflow.persistence.run.model import RunChangeClockRow, RunRow +from deerflow.persistence.thread_meta import ThreadMetaRepository +from deerflow.persistence.thread_meta.model import ThreadMetaRow from deerflow.persistence.thread_reads import ThreadReadMarkerRow, ThreadReadRepository, ThreadReadVersionRow from deerflow.runtime.run_origin import DEERFLOW_ORIGIN_KEY, make_origin from deerflow.runtime.runs.store.memory import MemoryRunStore @@ -36,18 +39,19 @@ async def repositories(tmp_path): engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'activity.db'}") try: async with engine.begin() as conn: - await conn.run_sync(lambda sync: Base.metadata.create_all(sync, tables=[m.__table__ for m in (RunRow, RunChangeClockRow, ThreadReadMarkerRow, ThreadReadVersionRow)])) + await conn.run_sync(lambda sync: Base.metadata.create_all(sync, tables=[m.__table__ for m in (RunRow, RunChangeClockRow, ThreadReadMarkerRow, ThreadReadVersionRow, ThreadMetaRow)])) sf = async_sessionmaker(engine, expire_on_commit=False) - yield RunRepository(sf), ThreadReadRepository(sf) + yield RunRepository(sf), ThreadReadRepository(sf), ThreadMetaRepository(sf) finally: await engine.dispose() @asynccontextmanager -async def client_for(run_store, read_repo, *, user=_ALICE): +async def client_for(run_store, read_repo, metas, *, user=_ALICE): app = make_authed_test_app(user_factory=lambda: user, bind_current_user=True) app.state.run_store = run_store app.state.thread_read_repo = read_repo + app.state.thread_store = metas app.include_router(thread_activity.router) app.include_router(threads.router) async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://activity.test") as client: @@ -69,7 +73,7 @@ async def poll(client, cursor=None, **params): @pytest.mark.asyncio async def test_first_poll_only_seeds_at_the_callers_head(tmp_path): - async with repositories(tmp_path) as (runs, reads), client_for(runs, reads) as client: + async with repositories(tmp_path) as (runs, reads, metas), client_for(runs, reads, metas) as client: await put_run(runs, "run-1", "sched", origin="schedule") seeded = await poll(client) assert seeded["threads"] == [] @@ -84,7 +88,7 @@ async def test_first_poll_only_seeds_at_the_callers_head(tmp_path): @pytest.mark.asyncio async def test_user_without_runs_seeds_at_zero_and_sees_the_first_scheduled_run(tmp_path): - async with repositories(tmp_path) as (runs, reads), client_for(runs, reads) as client: + async with repositories(tmp_path) as (runs, reads, metas), client_for(runs, reads, metas) as client: seeded = await poll(client) assert seeded["cursor"] == "0:" await put_run(runs, "run-1", "sched", origin="schedule", status="running") @@ -94,7 +98,7 @@ async def test_user_without_runs_seeds_at_zero_and_sees_the_first_scheduled_run( @pytest.mark.asyncio async def test_cursor_advances_to_the_last_returned_row_without_skips_or_repeats(tmp_path): - async with repositories(tmp_path) as (runs, reads), client_for(runs, reads) as client: + async with repositories(tmp_path) as (runs, reads, metas), client_for(runs, reads, metas) as client: cursor = (await poll(client))["cursor"] for index in range(5): await put_run(runs, f"run-{index}", f"thread-{index}", origin="schedule") @@ -115,7 +119,7 @@ async def test_cursor_advances_to_the_last_returned_row_without_skips_or_repeats @pytest.mark.asyncio async def test_interactive_changes_advance_the_cursor_but_are_not_returned(tmp_path): - async with repositories(tmp_path) as (runs, reads), client_for(runs, reads) as client: + async with repositories(tmp_path) as (runs, reads, metas), client_for(runs, reads, metas) as client: cursor = (await poll(client))["cursor"] await put_run(runs, "chat-1", "chat", status="pending") await put_run(runs, "chat-1", "chat", status="running") @@ -129,7 +133,7 @@ async def test_interactive_changes_advance_the_cursor_but_are_not_returned(tmp_p @pytest.mark.asyncio async def test_new_server_runs_are_listed_once_per_thread_with_latest_status(tmp_path): - async with repositories(tmp_path) as (runs, reads), client_for(runs, reads) as client: + async with repositories(tmp_path) as (runs, reads, metas), client_for(runs, reads, metas) as client: cursor = (await poll(client))["cursor"] await put_run(runs, "run-s", "sched", origin="schedule", status="running") await put_run(runs, "run-im", "im", origin="im_channel", status="running") @@ -141,15 +145,28 @@ async def test_new_server_runs_are_listed_once_per_thread_with_latest_status(tmp ] +@pytest.mark.asyncio +async def test_incognito_threads_are_not_listed(tmp_path): + """The feed's only reach is an exact id; an incognito id must never surface.""" + async with repositories(tmp_path) as (runs, reads, metas), client_for(runs, reads, metas) as client: + cursor = (await poll(client))["cursor"] + await metas.create("secret", user_id=ALICE, incognito=True, expires_at=datetime.now(UTC) + timedelta(hours=1)) + await put_run(runs, "run-secret", "secret", origin="schedule") + await put_run(runs, "run-open", "open", origin="schedule") + page = await poll(client, cursor) + assert [item["thread_id"] for item in page["threads"]] == ["open"] + assert page["cursor"] != cursor + + @pytest.mark.asyncio async def test_other_users_runs_never_appear_even_with_their_cursor(tmp_path): - async with repositories(tmp_path) as (runs, reads): - async with client_for(runs, reads, user=_BOB) as bob: + async with repositories(tmp_path) as (runs, reads, metas): + async with client_for(runs, reads, metas, user=_BOB) as bob: bob_cursor = (await poll(bob))["cursor"] await put_run(runs, "run-bob", "bob-thread", user_id=BOB, origin="schedule") # Bob's run in a thread shared with Alice. await put_run(runs, "run-bob-shared", "shared", user_id=BOB, origin="im_channel") - async with client_for(runs, reads) as alice: + async with client_for(runs, reads, metas) as alice: assert (await poll(alice, bob_cursor))["threads"] == [] assert (await poll(alice, "0:"))["threads"] == [] assert (await poll(alice))["cursor"] == "0:" @@ -158,7 +175,7 @@ async def test_other_users_runs_never_appear_even_with_their_cursor(tmp_path): @pytest.mark.asyncio @pytest.mark.parametrize("cursor", ["", "abc", "12", "-1:run", "1:run:x", "01:run", "1: run", "9" * 20 + ":r", f"{2**63}:r", "1:" + "r" * 65, "1:" + "r" * 200]) async def test_malformed_cursor_is_rejected(tmp_path, cursor): - async with repositories(tmp_path) as (runs, reads), client_for(runs, reads) as client: + async with repositories(tmp_path) as (runs, reads, metas), client_for(runs, reads, metas) as client: response = await client.get("/api/thread-activity", params={"cursor": cursor}) assert response.status_code == 422 assert response.json()["detail"]["code"] == "invalid_cursor" @@ -166,7 +183,7 @@ async def test_malformed_cursor_is_rejected(tmp_path, cursor): @pytest.mark.asyncio async def test_largest_change_seq_is_a_valid_cursor(tmp_path): - async with repositories(tmp_path) as (runs, reads), client_for(runs, reads) as client: + async with repositories(tmp_path) as (runs, reads, metas), client_for(runs, reads, metas) as client: cursor = f"{2**63 - 1}:r" page = await poll(client, cursor) assert page["threads"] == [] and page["cursor"] == cursor @@ -174,8 +191,9 @@ async def test_largest_change_seq_is_a_valid_cursor(tmp_path): @pytest.mark.asyncio async def test_read_version_moves_only_when_a_read_clears_something(tmp_path): - async with repositories(tmp_path) as (runs, reads), client_for(runs, reads) as client: + async with repositories(tmp_path) as (runs, reads, metas), client_for(runs, reads, metas) as client: await put_run(runs, "run-1", "sched", origin="schedule") + await metas.create("sched", user_id=ALICE) cursor = (await poll(client))["cursor"] cleared = await client.post("/api/threads/sched/read") @@ -216,6 +234,7 @@ def _feature_config(): subagent_runtime=SimpleNamespace(max_running=3), knowledge_base=SimpleNamespace(enabled=False, scope_selection_enabled=False), scheduler=SimpleNamespace(enabled=False, tool_enabled=False, min_once_delay_seconds=60), + incognito=SimpleNamespace(enabled=True, idle_ttl_seconds=86400), ) config.get_tool_config = lambda _name: None return config diff --git a/backend/tests/test_thread_create_idempotency.py b/backend/tests/test_thread_create_idempotency.py index d44b94e8822..7998f19121e 100644 --- a/backend/tests/test_thread_create_idempotency.py +++ b/backend/tests/test_thread_create_idempotency.py @@ -140,6 +140,47 @@ async def aput(self, config, checkpoint, metadata, versions): assert not goal._goal_locks._entries_by_loop +@pytest.mark.anyio +async def test_create_racing_an_incognito_tombstone_answers_410(thread_store, monkeypatch): + """A create that loses the idempotency read to an incognito row must not revive it. + + The memory store used to overwrite the row while the SQL store rejected + the insert at the primary key; both now resolve through the route's + idempotent-create recovery to the same 410. + """ + from datetime import UTC, datetime, timedelta + + await thread_store.create( + "expired-create", + user_id=str(USER.id), + incognito=True, + expires_at=datetime.now(UTC) - timedelta(seconds=1), + ) + original_get = thread_store.get + reads = 0 + + async def observed_get(thread_id, **kwargs): + nonlocal reads + if thread_id == "expired-create": + reads += 1 + if reads == 1: + # The racing request read the id before this row existed. + return None + return await original_get(thread_id, **kwargs) + + monkeypatch.setattr(thread_store, "get", observed_get) + app = app_for(thread_store, InMemorySaver()) + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: + response = await client.post("/api/threads", json={"thread_id": "expired-create"}) + + assert response.status_code == 410, response.text + assert response.json()["detail"] == "This incognito thread has expired" + row = await original_get("expired-create", user_id=str(USER.id)) + assert row is not None + assert row["incognito"] is True + assert row["metadata"] == {} + + @pytest.mark.anyio async def test_cancelled_waiter_keeps_other_threads_available(thread_store, monkeypatch): attempted = asyncio.Event() diff --git a/backend/tests/test_thread_meta_repo.py b/backend/tests/test_thread_meta_repo.py index 2e619dd3cc0..794febe0fce 100644 --- a/backend/tests/test_thread_meta_repo.py +++ b/backend/tests/test_thread_meta_repo.py @@ -2,6 +2,7 @@ import asyncio import logging +from datetime import UTC, datetime, timedelta import pytest from sqlalchemy.exc import IntegrityError @@ -340,6 +341,54 @@ async def test_search_without_metadata_still_works(self, repo): results = await repo.search(limit=10) assert len(results) == 2 + @pytest.mark.anyio + async def test_create_incognito_persists_flag_and_expiry(self, repo): + expires = datetime.now(UTC) + timedelta(hours=2) + + record = await repo.create("secret", incognito=True, expires_at=expires) + assert record["incognito"] is True + assert datetime.fromisoformat(record["expires_at"]) == expires + + fetched = await repo.get("secret") + assert fetched is not None + assert fetched["incognito"] is True + assert datetime.fromisoformat(fetched["expires_at"]) == expires + + @pytest.mark.anyio + async def test_search_excludes_incognito_threads(self, repo): + await repo.create("visible", display_name="visible") + await repo.create("secret", display_name="secret", incognito=True) + + results = await repo.search(limit=10) + + assert [row["thread_id"] for row in results] == ["visible"] + + @pytest.mark.anyio + async def test_search_query_does_not_expose_incognito_titles(self, repo): + await repo.create("visible", display_name="shared title") + await repo.create("secret", display_name="shared title", incognito=True) + + results = await repo.search(query="shared", limit=10) + + assert [row["thread_id"] for row in results] == ["visible"] + + @pytest.mark.anyio + async def test_search_legacy_row_without_incognito_flag_stays_listed(self, repo): + from sqlalchemy import update + + from deerflow.persistence.engine import get_session_factory + from deerflow.persistence.thread_meta.model import ThreadMetaRow + + await repo.create("legacy") + async with get_session_factory()() as session: + # Pre-migration rows read NULL for the new column. + await session.execute(update(ThreadMetaRow).where(ThreadMetaRow.thread_id == "legacy").values(incognito=None)) + await session.commit() + + results = await repo.search(limit=10) + + assert [row["thread_id"] for row in results] == ["legacy"] + @pytest.mark.anyio async def test_search_metadata_missing_key_no_match(self, repo): """Rows without the requested metadata key should not match.""" diff --git a/backend/tests/test_threads_router.py b/backend/tests/test_threads_router.py index c26c82c5838..0f9e2f487dc 100644 --- a/backend/tests/test_threads_router.py +++ b/backend/tests/test_threads_router.py @@ -3,6 +3,7 @@ import re import threading from contextlib import asynccontextmanager +from datetime import UTC, datetime from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock, patch @@ -31,6 +32,7 @@ ThreadMetaRepository, ThreadOwnershipConflictError, ) +from deerflow.persistence.thread_meta.base import THREAD_INCOGNITO_EXPIRED_STATUS, _as_utc from deerflow.persistence.thread_meta.memory import THREADS_NS, MemoryThreadMetaStore from deerflow.runtime import ConflictError, ThreadOperationKind from deerflow.runtime.checkpoint_mode import CheckpointModeMismatchError, CheckpointModeReconfigurationError @@ -64,10 +66,17 @@ async def check_access(self, thread_id, user_id, *, require_existing=False): # item = await self._store.aget(THREADS_NS, thread_id) if item is None: return not require_existing + # Keep the production expiry rule: an expired incognito thread is + # unreadable even for its owner. + value = item.value + if value.get("incognito") is True: + deadline = _as_utc(value.get("expires_at")) + if value.get("status") == THREAD_INCOGNITO_EXPIRED_STATUS or (deadline is not None and deadline <= datetime.now(UTC)): + return False return True - async def create(self, thread_id, *, assistant_id=None, user_id=None, display_name=None, metadata=None, project_id=None): # type: ignore[override] - return await super().create(thread_id, assistant_id=assistant_id, user_id=None, display_name=display_name, metadata=metadata, project_id=project_id) + async def create(self, thread_id, *, assistant_id=None, user_id=None, display_name=None, metadata=None, project_id=None, incognito=False, expires_at=None): # type: ignore[override] + return await super().create(thread_id, assistant_id=assistant_id, user_id=None, display_name=display_name, metadata=metadata, project_id=project_id, incognito=incognito, expires_at=expires_at) async def search(self, *, metadata=None, status=None, limit=100, offset=0, user_id=None, archived=None, project_id=PROJECT_FILTER_UNSET): # type: ignore[override] return await super().search(metadata=metadata, status=status, limit=limit, offset=offset, user_id=None, archived=archived, project_id=project_id) @@ -502,6 +511,32 @@ def test_delete_thread_route_cleans_thread_directory(tmp_path): assert not thread_dir.exists() +def test_delete_thread_route_refuses_an_incognito_thread() -> None: + """The best-effort delete would drop the tombstone and make the id reusable.""" + app, store, _checkpointer = _build_thread_app() + + async def _seed(): + await store.aput( + THREADS_NS, + "thread-incognito", + { + "thread_id": "thread-incognito", + "status": "idle", + "incognito": True, + "expires_at": "2099-01-01T00:00:00+00:00", + "metadata": {}, + }, + ) + + asyncio.run(_seed()) + with TestClient(app) as client: + response = client.delete("/api/threads/thread-incognito") + + assert response.status_code == 409 + assert "incognito/end" in response.json()["detail"] + assert asyncio.run(store.aget(THREADS_NS, "thread-incognito")) is not None + + def test_delete_thread_route_closes_browser_session(tmp_path): """Deleting a thread tears down its live browser session so a later caller who reuses the id cannot inherit the retained page/cookies.""" @@ -579,12 +614,14 @@ def test_delete_thread_route_isolates_failing_mcp_cleanup(tmp_path): pool.close_thread_scope.assert_awaited_once() -def _persistence_cleanup_app(tmp_path, *, run_store, event_store, feedback_repo): +def _persistence_cleanup_app(tmp_path, *, run_store, event_store, feedback_repo, batch_repo=None): app = make_authed_test_app() app.state.run_manager = _ThreadTestRunManager() app.state.run_store = run_store app.state.run_event_store = event_store app.state.feedback_repo = feedback_repo + if batch_repo is not None: + app.state.subagent_batch_repo = batch_repo app.include_router(threads.router) return app @@ -715,6 +752,45 @@ def test_delete_thread_route_cleans_persisted_records(tmp_path): feedback_repo.delete_by_thread.assert_awaited_once_with("thread-cleanup", user_id=user_id) +def test_delete_thread_route_removes_durable_batch_rows(tmp_path): + """Purge fences continuations, then deletes the durable batch rows. + + ``suppress_thread_continuations`` only flips the continuation status; the + batch/item rows — including each item's prompt text — stay readable. A user + delete (and the incognito sweep that reuses this orchestration) must remove + them, scoped to the owner. + """ + from deerflow.runtime.user_context import get_effective_user_id + + paths = Paths(tmp_path) + user_id = get_effective_user_id() + run_store = MagicMock() + run_store.delete_by_thread = AsyncMock(return_value=0) + event_store = MagicMock() + event_store.delete_by_thread = AsyncMock(return_value=0) + feedback_repo = MagicMock() + feedback_repo.delete_by_thread = AsyncMock(return_value=0) + batch_repo = MagicMock() + batch_repo.suppress_thread_continuations = AsyncMock(return_value=None) + batch_repo.delete_by_thread = AsyncMock(return_value=1) + + app = _persistence_cleanup_app( + tmp_path, + run_store=run_store, + event_store=event_store, + feedback_repo=feedback_repo, + batch_repo=batch_repo, + ) + + with patch("app.gateway.routers.threads.get_paths", return_value=paths): + with TestClient(app) as client: + response = client.delete("/api/threads/thread-cleanup") + + assert response.status_code == 200 + batch_repo.suppress_thread_continuations.assert_awaited_once_with("thread-cleanup") + batch_repo.delete_by_thread.assert_awaited_once_with("thread-cleanup", user_id=user_id) + + def test_delete_thread_route_isolates_failing_persistence_cleanup(tmp_path): """One failing store must not stop the remaining cleanup attempts.""" paths = Paths(tmp_path) @@ -1137,7 +1213,7 @@ def __init__(self, backing): super().__init__(backing) self._raised = False - async def create(self, thread_id, *, assistant_id=None, user_id=None, display_name=None, metadata=None, project_id=None): # type: ignore[override] + async def create(self, thread_id, *, assistant_id=None, user_id=None, display_name=None, metadata=None, project_id=None, incognito=False, expires_at=None): # type: ignore[override] if not self._raised: self._raised = True await super().create( @@ -1199,7 +1275,7 @@ class _RacingOwnerStore(MemoryThreadMetaStore): """Our insert loses to a competing create that already wrote an unscoped row, exactly the interleaving the recovery path exists for.""" - async def create(self, thread_id, *, assistant_id=None, user_id=None, display_name=None, metadata=None, project_id=None): # type: ignore[override] + async def create(self, thread_id, *, assistant_id=None, user_id=None, display_name=None, metadata=None, project_id=None, incognito=False, expires_at=None): # type: ignore[override] # The competing request commits its (owner-less) row here, then our # insert loses the primary-key race. await super().create(thread_id, user_id=None, metadata=metadata, project_id=project_id) @@ -1314,7 +1390,7 @@ def __init__(self): self._create_lock = asyncio.Lock() self._legacy_row_committed = asyncio.Event() - async def create(self, thread_id, *, assistant_id=None, user_id=None, display_name=None, metadata=None, project_id=None): # type: ignore[override] + async def create(self, thread_id, *, assistant_id=None, user_id=None, display_name=None, metadata=None, project_id=None, incognito=False, expires_at=None): # type: ignore[override] async with self._create_lock: self._create_arrivals += 1 if self._create_arrivals == 2: @@ -1391,7 +1467,7 @@ def test_create_thread_does_not_swallow_non_integrity_errors() -> None: app, store, _checkpointer = _build_thread_app() class _BrokenAfterWriteStore(_PermissiveThreadMetaStore): - async def create(self, thread_id, *, assistant_id=None, user_id=None, display_name=None, metadata=None): # type: ignore[override] + async def create(self, thread_id, *, assistant_id=None, user_id=None, display_name=None, metadata=None, incognito=False, expires_at=None): # type: ignore[override] # A row exists after this call, but the insert failed for a reason # unrelated to the idempotency race. await super().create(thread_id, metadata=metadata) @@ -1420,7 +1496,7 @@ def test_create_thread_keeps_real_integrity_failure_as_500() -> None: app, store, _checkpointer = _build_thread_app() class _IntegrityFailureNoSurvivingRowStore(_PermissiveThreadMetaStore): - async def create(self, thread_id, *, assistant_id=None, user_id=None, display_name=None, metadata=None, project_id=None): # type: ignore[override] + async def create(self, thread_id, *, assistant_id=None, user_id=None, display_name=None, metadata=None, project_id=None, incognito=False, expires_at=None): # type: ignore[override] raise IntegrityError( "INSERT INTO threads_meta", {}, diff --git a/backend/tests/test_update_agent_tool.py b/backend/tests/test_update_agent_tool.py index 80fd42ffcc9..9ec65c1758a 100644 --- a/backend/tests/test_update_agent_tool.py +++ b/backend/tests/test_update_agent_tool.py @@ -18,6 +18,7 @@ from langchain.tools import ToolRuntime from deerflow.config.agents_config import AgentConfig +from deerflow.runtime.context_keys import INCOGNITO_CONTEXT_KEY from deerflow.tools.builtins.update_agent_tool import update_agent DEFAULT_USER = "test-user-autouse" # matches the autouse fixture in tests/conftest.py @@ -116,6 +117,21 @@ def test_update_agent_rejects_invalid_agent_name(patched_paths): assert "Invalid agent name" in msg.content +def test_update_agent_refuses_in_an_incognito_chat(tmp_path, patched_paths): + _seed_agent(tmp_path) + runtime = _runtime(agent_name="test-agent") + runtime.context[INCOGNITO_CONTEXT_KEY] = True + + result = update_agent.func(runtime=runtime, soul="new soul") + + msg = result.update["messages"][0] + assert msg.status == "error" + assert "incognito" in msg.content + # The seeded agent is untouched: the change would have persisted outside + # the chat and stayed visible in every later conversation. + assert (_user_agent_dir(tmp_path) / "SOUL.md").read_text(encoding="utf-8") == "old soul" + + def test_update_agent_rejects_unknown_agent(tmp_path, patched_paths): result = update_agent.func(runtime=_runtime(agent_name="ghost"), soul="x") diff --git a/backend/tests/test_workspace_search.py b/backend/tests/test_workspace_search.py index e79c6360fd8..2e5cc3cdd0a 100644 --- a/backend/tests/test_workspace_search.py +++ b/backend/tests/test_workspace_search.py @@ -341,3 +341,27 @@ async def test_route_filters_and_permission_boundary(monkeypatch, index): assert (await client.get("/api/threads/project/messages/around?message_id=m")).status_code == 403 monkeypatch.setattr(auth_helpers, "_STUB_PERMISSIONS", []) assert (await client.post("/api/search", json={"query": "报告"})).status_code == 403 + + +@pytest.mark.anyio +async def test_search_corpus_never_exposes_an_incognito_thread(threads): + from deerflow_extension_api.search import SearchThread + + from app.gateway.search_corpus import GatewaySearchCorpus + + events = MemoryRunEventStore() + manager = AsyncMock() + manager.list_successful_regenerate_sources.return_value = set() + manager.list_edit_replay_visibility.return_value = EditReplayVisibility() + await threads.create("secret", user_id="alice", display_name="secret", incognito=True) + await events.put(thread_id="secret", run_id="r", event_type="message", category="message", content={"id": "a", "type": "ai", "content": "secret answer"}) + corpus = GatewaySearchCorpus(threads, events, manager, "alice") + + assert await corpus.threads() == () + assert await corpus.thread("secret") is None + assert await corpus.around("secret", "a") is None + + row = await threads.get("secret", user_id="alice") + forged = SearchThread(thread_id="secret", incarnation=row["incarnation"], title="secret", updated_at=row["updated_at"], agent_name=None, project_id=None, archived=False) + assert await corpus.owns(forged) is False + assert (await corpus.messages(forged, before_seq=None)).items == () diff --git a/config.example.yaml b/config.example.yaml index 5b787da857f..af74bd59318 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -3789,3 +3789,53 @@ authorization: # # also match a host-owned table name. # config: # label: example # extension-private values, if any + +# ============================================================================ +# Incognito (Temporary) Chats +# ============================================================================ +# An incognito thread is invisible to every list, search result, project, +# share and archive surface. Its owner can still reach it by exact thread id +# while it is alive. The Gateway deletes the thread, its checkpoint history +# and its per-thread files after the idle window or the absolute lifetime, +# whichever comes first; an explicit end shortens the idle window to the +# grace period. +# +# Every window is in seconds, and an out-of-range value fails validation when +# the Gateway starts instead of being clamped. idle_ttl_seconds must be between +# one hour (3600) and max_lifetime_seconds; max_lifetime_seconds must be +# between one hour and one year (31536000), a cap that keeps the deadline +# arithmetic inside datetime's range. end_grace_seconds accepts 0 through 31536000. +# sweep_interval_seconds must be between 5 and 3600, and sweep_batch_size +# between 1 and 1000. Setting idle_ttl_seconds equal to max_lifetime_seconds is +# allowed: the absolute lifetime alone then decides when the chat goes. +# +# incognito: +# enabled: true +# +# # Idle timeout, minimum one hour. A run starting or finishing renews the +# # deadline; leaving the window open, typing or scrolling is not activity +# # and renews nothing. Example: a user sends a message and never ends the +# # chat, so it expires 24 hours after that message and the next sweep +# # removes it. +# idle_ttl_seconds: 86400 +# +# # Grace period after the user ends the chat from the incognito header. +# # Ending does not delete immediately; it shortens the deadline to this +# # window, never past max_lifetime_seconds. Example: a chat ended at 10:00 +# # is removed by the first sweep after 11:00. +# end_grace_seconds: 3600 +# +# # Absolute ceiling measured from creation, at most one year. Activity +# # renews the idle deadline and an explicit end schedules its grace period, +# # but neither can pass this one. Example: a user who keeps chatting every +# # few minutes still loses the chat 7 days after creating it. +# max_lifetime_seconds: 604800 +# +# # How often the background sweep scans for expired chats. It delays the +# # purge but never extends a deadline. Example: a 24-hour idle window is +# # removed within about one interval after it expires. +# sweep_interval_seconds: 60 +# +# # Expired chats removed per sweep pass; a backlog drains over several +# # passes instead of one. +# sweep_batch_size: 100 diff --git a/contracts/scheduled_task_errors_contract.json b/contracts/scheduled_task_errors_contract.json index d17f344df4c..d819091bfa5 100644 --- a/contracts/scheduled_task_errors_contract.json +++ b/contracts/scheduled_task_errors_contract.json @@ -13,6 +13,7 @@ "once_time_passed", "invalid_context_mode", "reuse_thread_requires_thread", + "incognito_thread_not_schedulable", "thread_not_found", "invalid_assistant", "unknown_assistant", diff --git a/docs/guide/incognito-chats.md b/docs/guide/incognito-chats.md new file mode 100644 index 00000000000..a0834f68b2b --- /dev/null +++ b/docs/guide/incognito-chats.md @@ -0,0 +1,168 @@ +# Incognito chats + +An incognito chat is a temporary conversation for material you do not want in +your ordinary workspace. It never appears in the chat list, archive, project, +share, activity or search surfaces, and it is not usable as a conversation +reference or as the reuse target of a scheduled task. It also cannot create a +scheduled task, branch into a new chat or open a side chat, because each of +those would copy the conversation into a durable object. While it is alive, +only its owner can open it by its exact thread URL; there is no sidebar entry. + +Incognito is a DeerFlow storage boundary, not a promise about third parties. +Conversation content still goes to the model provider and any tools or +connectors you use, whose data handling is outside DeerFlow's control. DeerFlow +is self-hosted and does not train models on your conversations. + +## Start and end + +Start an incognito chat from the ghost icon at the top right of a blank new +chat, or open `/workspace/chats/new?incognito=true`. A saved conversation does +not offer the icon: an ordinary chat and an incognito chat cannot be converted +into one another. The workspace sidebar is removed and the chat takes the whole +window: a dark top bar around a framed conversation area, a dashed composer +border and two notices. The first says the chat does not enter history, memory +or search and gives the idle lifetime from the live configuration; the second +names the third-party boundary below. + +Use the **×** control in the top bar to end the chat. The browser leaves immediately; the +Gateway then schedules a short deletion grace in the background. If that +request fails, the idle lifetime still ends the chat. An ended chat cannot be +reopened from a list, and its deadline no longer grows when a run finishes. +Ending it again does not move the deadline either, so a repeated close cannot +keep the chat around. The ordinary thread-delete API refuses an incognito +thread and points at the end endpoint, because it would remove the tombstone +and make the thread ID reusable. + +The first version allows incognito creation only from an authenticated browser +session. Personal access tokens, IM channels, extensions and scheduled runs +cannot create one. An operator can disable new incognito chats with +`incognito.enabled: false`; existing incognito chats still expire on schedule. + +## What the chat does not offer + +These entry points are closed because each one produces a durable object from +the conversation: + +- **Scheduled tasks.** A task's prompt and schedule outlive the chat and appear + on the tasks page, so a run in an incognito chat binds no scheduler + capability. The model can still explain a schedule, but it cannot create one: + `schedule_task` reports that tasks are unavailable here. The API also rejects + naming an incognito thread as a task's reuse target, whether the task is + created or edited. +- **Durable subagent batches.** A durable batch stores each item's prompt and + execution spec in the database so it can resume after a restart, which makes + it a persistent copy of the conversation. The `batch_task` tool family is not + offered in an incognito chat, and `batch_task` refuses if reached anyway. + Ordinary subagents still work through the in-process `task` tool. +- **Agent creation and edits.** Creating an agent, or changing a custom + agent's persona, skills or model, writes outside the chat and stays visible + in every later conversation. `setup_agent` and `update_agent` are withheld in + an incognito run, and both tools refuse if reached anyway. +- **Side chat.** A side chat is its own persistent thread, so the header + trigger, the panel and the "Ask in side chat" toolbar action are absent. + "Add to conversation" still works, because a quote only rides the next + message and is deleted with the thread. +- **Branch.** A branch copies the conversation into a new persistent thread, + so the branch action is not offered; the API rejects a branch of an + incognito thread as well. + +## What the run does not write + +Runs in an incognito chat do not write long-term memory or the shared blob +store. Passive memory capture, the compaction flush and the memory tools' +write operations are skipped; large tool outputs and viewed images stay in the +thread's own workspace instead of entering shared blob storage. Reading +memory that already exists (injection and search) still works. Subagents stay +available and inherit the same rule, so a delegated run neither writes blobs +nor leaves durable batch rows behind. Everything the chat does write stays +inside its thread directory and is removed by the same expiry sweep. + +## What the assistant is told + +The system prompt states the storage boundary rather than a list of individual +features. It tells the assistant that the conversation is temporary and that +neither it nor anything derived from it can be made persistent from within the +chat, so the rule still covers a capability that is added later. It also states +that memory writes are unavailable and that the assistant must never claim to +have saved or remembered something; a working note such as `task_note` is a +note for this conversation, not long-term memory. + +Delegated work inherits the same rule. The lead is told not to ask a subagent +to persist anything and not to trust a report that claims it did; each +subagent's own system prompt carries the boundary as well. + +The prompt keeps the third-party edge explicit: content still goes to the +model, search and MCP services, and an external write is not undone when the +chat ends. The interface notices are shown once; the assistant is told not to +repeat them unless the limitation matters to the answer. + +## What stays outside the boundary + +The promise covers DeerFlow's own storage: an incognito chat leaves no +conversation content in lists, memory, shared blobs or another thread. Three +edges are worth knowing: + +- **External side effects are not recallable.** Searches, fetched pages, tool + and MCP calls, and anything a connector writes happen outside DeerFlow. + Ending the chat deletes its local trace, not what a third party already saw + or stored. +- **MCP OAuth credentials belong to the connection.** Connecting or refreshing + an MCP server's OAuth token writes that credential to the deployment's MCP + credential store, because credentials are shared by every chat rather than + owned by one conversation. Disconnect the server in MCP settings if you want + no trace of the connection. +- **Memory retrieval bookkeeping.** With DeerMem's hybrid eviction policy, a + memory search records usage metadata (access heat and last-accessed time) for + the facts it returned in a user-level sidecar. That sidecar stores no + conversation text. + +## Lifetime and deletion + +The deadline shown in `expires_at` moves forward on run admission and run +completion, but never past the absolute maximum measured from creation. An +explicit end replaces it with the grace period under the same ceiling, so no +path schedules a purge beyond the maximum. A deadline that has already passed +is final: a run finishing after it cannot push it out again, and a run that +races the sweep is stopped before its agent starts rather than allowed to write +into a purged thread. The defaults are: + +| Setting | Default | Meaning | +| ---------------------------------- | ------- | ----------------------------------- | +| `incognito.idle_ttl_seconds` | 86400 | idle window after the last activity | +| `incognito.end_grace_seconds` | 3600 | grace after an explicit end | +| `incognito.max_lifetime_seconds` | 604800 | absolute lifetime from creation | +| `incognito.sweep_interval_seconds` | 60 | Gateway scan cadence | +| `incognito.sweep_batch_size` | 100 | maximum threads purged per pass | + +Every window is in seconds. `idle_ttl_seconds` must be between one hour and +`max_lifetime_seconds`; `max_lifetime_seconds` must be between one hour and one +year, a cap that keeps the deadline arithmetic inside `datetime`'s range. The +one-hour idle floor exists because renewal happens on runs only: typing, +reading or leaving the window open does not count, so a shorter window can +expire the chat while it is still in use or right after a long run finishes. +`end_grace_seconds` accepts 0 through 31536000 seconds (365 days). The thread's +absolute lifetime still caps its deletion deadline. The sweep settings are bounded +(`sweep_interval_seconds` 5 to 3600, `sweep_batch_size` 1 to 1000). An idle +window equal to the absolute lifetime is allowed: the lifetime alone then +decides when the chat goes. An out-of-range or contradictory value fails +configuration validation, so the Gateway does not start rather than running +with a silently adjusted lifetime. The chat notice spells the live idle window +in hours up to 72 hours, and days (plus hours) above that, marking a window the +units cannot express exactly with "about". + +The Gateway's background sweep writes a tombstone first +(`status="expired"`, with the row's title, metadata and project membership +cleared), then removes the thread directory, checkpoints, run and event +records, feedback, scheduled-task lines, tracked MCP task records, read +markers and browser/MCP sessions through the same orchestration as an ordinary +thread deletion. The tombstone row is retained so the thread ID cannot be +reused and read routes answer `404` instead of an empty `200`. The sweep +rechecks the deadline under the row lock, so a chat renewed after the batch was +read is skipped rather than deleted. A purge interrupted by a crash or a +work-in-flight conflict keeps its retry marker and is retried on the next pass; +the marker is cleared only after the checked stores (runs, events, feedback, +scheduled-task lines, MCP tasks, read markers and durable batch rows) have been +cleaned. Browser and MCP sessions are runtime resources rather than stored +content, so their teardown is best-effort and is not retried. See +[configuration](configuration.md) and the commented `incognito:` block in +`config.example.yaml` for the operator settings. diff --git a/frontend/DESIGN.md b/frontend/DESIGN.md index 8f8c8c08cba..17c7b4368ad 100644 --- a/frontend/DESIGN.md +++ b/frontend/DESIGN.md @@ -49,6 +49,11 @@ Rules: opacity modifiers (`bg-secondary/60`), so they follow the theme. - Theme switching is `next-themes` with `attribute="class"` and system default. Every new color must work in both modes; check both before shipping. +- The incognito chat surface uses the `--incognito*` tokens for its top bar and + surrounding frame, which stay dark in both themes because the temporary-chat + mode is meant to read as distinct, not as another raised card. Its + conversation area uses `--incognito-surface`: paper in light mode, and in + dark mode one step lighter than the fixed surround so the frame still reads. ## Typography diff --git a/frontend/src/app/workspace/workspace-content.tsx b/frontend/src/app/workspace/workspace-content.tsx index b60f9202e71..f36fe8850ec 100644 --- a/frontend/src/app/workspace/workspace-content.tsx +++ b/frontend/src/app/workspace/workspace-content.tsx @@ -5,6 +5,7 @@ import { QueryClientProvider } from "@/components/query-client-provider"; import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"; import { CommandPalette } from "@/components/workspace/command-palette"; import { GatewayOfflineBanner } from "@/components/workspace/gateway-offline-banner"; +import { IncognitoModeProvider } from "@/components/workspace/incognito-mode-context"; import { ModelLoadErrorBanner } from "@/components/workspace/model-load-error-banner"; import { SettingsDialogHost } from "@/components/workspace/settings"; import { WorkspaceSettingsDeepLink } from "@/components/workspace/workspace-settings-deep-link"; @@ -37,12 +38,14 @@ export async function WorkspaceContent({ - - - - - {children} - + + + + + + {children} + + diff --git a/frontend/src/components/workspace/chats/chat-page.tsx b/frontend/src/components/workspace/chats/chat-page.tsx index 822a9c118bb..f09dff8012e 100644 --- a/frontend/src/components/workspace/chats/chat-page.tsx +++ b/frontend/src/components/workspace/chats/chat-page.tsx @@ -13,6 +13,7 @@ import { BrowserTrigger } from "@/components/workspace/browser-view"; import { ContextUsageBadge } from "@/components/workspace/context-usage-badge"; import { ExportTrigger } from "@/components/workspace/export-trigger"; import { GoalStatus } from "@/components/workspace/goal-status"; +import { usePublishIncognitoMode } from "@/components/workspace/incognito-mode-context"; import { InputBox, type InputBoxSubmitOptions, @@ -42,6 +43,7 @@ import { useAuth } from "@/core/auth/AuthProvider"; import { hasPermission, PERMISSIONS } from "@/core/auth/permissions"; import { useBrowserControlEnabled, + useIncognitoFeature, useKnowledgeBaseEnabled, } from "@/core/features"; import { useI18n } from "@/core/i18n/hooks"; @@ -68,7 +70,7 @@ import { useThreadScheduledTaskEvents } from "@/core/scheduled-tasks/events"; import { useScheduleToolResultRefresh } from "@/core/scheduled-tasks/hooks"; import { useLocalSettings, useThreadSettings } from "@/core/settings"; import { resolveThreadContext, selectThreadModel } from "@/core/settings/store"; -import { createThread } from "@/core/threads/api"; +import { createThread, endIncognitoThread } from "@/core/threads/api"; import { useBranchThread, INFINITE_THREADS_QUERY_KEY_PREFIX, @@ -85,6 +87,13 @@ import { env } from "@/env"; import { cn } from "@/lib/utils"; import { ChatBox } from "./chat-box"; +import { shouldRequestIncognitoEnd } from "./incognito-end"; +import { IncognitoEntry } from "./incognito-entry"; +import { + IncognitoNotices, + IncognitoShell, + IncognitoTitle, +} from "./incognito-frame"; import { useSpecificChatMode } from "./use-chat-mode"; import { useMarkOpenThreadRead } from "./use-mark-open-thread-read"; import { useThreadChat } from "./use-thread-chat"; @@ -106,7 +115,17 @@ export default function ChatPage() { // meaningful while the thread is still lazy (`isNewThread`); once // materialized the URL is replaced with the thread route and the param is // gone. Invalid ids are dropped by backend admission. - const projectParam = isNewThread ? searchParams.get("project") : null; + // + // Incognito new chat: `/workspace/chats/new?incognito=true` needs the same + // pre-create for a different reason — run admission only pins the marker on + // a row that already exists, so the first run would otherwise write memory + // and shared blobs as an ordinary chat. An incognito thread never belongs to + // a project, so the incognito entry point wins over a hand-written project + // param. + const incognitoParam = + isNewThread && searchParams.get("incognito") === "true"; + const projectParam = + isNewThread && !incognitoParam ? searchParams.get("project") : null; // `isNewThread` tracks whether the backend has the thread yet — gates the // SDK's history fetch (see issue #2746). `isWelcomeMode` is the visual // welcome layout (centered input, hero, quick actions); we flip it to false @@ -124,6 +143,9 @@ export default function ChatPage() { useEffect(() => setModelChoiceSummary(""), [threadId, user?.id]); const [localSettings, setLocalSettings] = useLocalSettings(); const { enabled: browserControlEnabled } = useBrowserControlEnabled(); + // The frame's lifetime notice follows the live configuration; `null` until + // `/api/features` answers, so the UI never states a duration it did not read. + const { idleTtlSeconds: incognitoIdleTtlSeconds } = useIncognitoFeature(); const { tokenUsageEnabled } = useModels(); const threadTokenUsage = useThreadTokenUsage( isNewThread || isMock ? undefined : threadId, @@ -133,6 +155,15 @@ export default function ChatPage() { enabled: !isNewThread && !isMock, isMock, }); + // The URL carries the mode while the thread is lazy; afterwards the row is + // authoritative. The pre-create seeds the metadata cache, so the frame does + // not blink away between the first run starting and the refetch. + const isIncognito = isNewThread + ? incognitoParam + : threadMetadata.data?.incognito === true; + // An incognito chat owns the whole window: the workspace shell unmounts the + // sidebar while this surface renders. + usePublishIncognitoMode(isIncognito); // A saved thread that exists on the server is being read while open: // clears its unread dot (sidebar and chats list) on every device. const markThreadRead = useMarkOpenThreadRead(threadId, { @@ -283,40 +314,62 @@ export default function ChatPage() { ]); // Born assigned: pre-create the thread row with its project so the sidebar - // lists it under the project immediately. Idempotent server-side on + // lists it under the project immediately, or with its incognito marker so + // run admission can pin it on the very first turn. Idempotent server-side on // `thread_id`, so retrying the same first message (same `threadId` while - // `isNewThread`) reuses the existing row instead of double-creating. This - // is the sole membership channel — run requests never carry the project - // key. + // `isNewThread`) reuses the existing row instead of double-creating. Project + // membership is the sole membership channel — run requests never carry the + // project key. // // Also runs before InputBox issues a `/goal ` PUT (via // `onPrepareThread`): the goal endpoint materializes a missing thread row // itself, and an unassigned row would make this later idempotent create a - // membership no-op. - const ensureProjectThread = useCallback(async () => { - if (!projectParam) { + // membership no-op. The same pre-create keeps that materialized row from + // being an ordinary chat when the user is in an incognito entry. + + // The id of the thread row this page has created on the server. `isNewThread` + // flips only when the first run starts, but the project/incognito pre-create + // (and the goal endpoint) materialize the row earlier. The incognito × must + // end that row even while `isNewThread` is still true. + const createdThreadRowIdRef = useRef(null); + + const ensureThreadRow = useCallback(async () => { + if (!projectParam && !incognitoParam) { return; } try { - const created = await createThread(threadId, projectParam); - // Keep confirmed membership available while the first metadata read is pending - // or fails after the composer materializes this new project thread. + const created = await createThread( + threadId, + projectParam ?? undefined, + incognitoParam, + ); + createdThreadRowIdRef.current = threadId; + // Keep confirmed membership/visibility available while the first + // metadata read is pending or fails after the composer materializes + // this new thread. queryClient.setQueryData( ["thread", "metadata", threadId, false], created, ); - void queryClient.invalidateQueries({ - queryKey: INFINITE_THREADS_QUERY_KEY_PREFIX, - }); + if (!incognitoParam) { + void queryClient.invalidateQueries({ + queryKey: INFINITE_THREADS_QUERY_KEY_PREFIX, + }); + } } catch (error) { // Any failure (e.g. the project was deleted/archived between page load - // and submit): do NOT submit unassigned. Reject so PromptInput keeps - // the composer's text for a retry; the send in-flight guard is never - // engaged on this path, so retrying works immediately. - toast.error(t.projects.projectUnavailable); + // and submit, or an operator disabled incognito chats): do NOT submit in + // the wrong mode. Reject so PromptInput keeps the composer's text for a + // retry; the send in-flight guard is never engaged on this path, so + // retrying works immediately. + toast.error( + incognitoParam + ? t.incognito.createFailed + : t.projects.projectUnavailable, + ); throw error; } - }, [threadId, projectParam, queryClient, t]); + }, [threadId, projectParam, incognitoParam, queryClient, t]); // Submission fence. The cleanup runs when `threadId` changes (conversation // switch on a persisted page — sidebar navigation keeps this component @@ -359,7 +412,7 @@ export default function ChatPage() { runModelContext.model_selection_requested = choice.model_name; } } - await ensureProjectThread(); + await ensureThreadRow(); // Conversation switched (or the page unmounted) while the project // pre-create was pending: drop the submission. Reject silently — the // user has already moved on, so a toast would land on the new @@ -374,7 +427,10 @@ export default function ChatPage() { isNewThread && !projectParam ) { - await createThread(threadId); + // Idempotent with the incognito pre-create above; the mode must match + // the existing row or the server answers 409. + await createThread(threadId, undefined, incognitoParam); + createdThreadRowIdRef.current = threadId; if (submissionEpochRef.current !== submissionEpoch) throw new Error("thread-submission-stale"); } @@ -462,6 +518,10 @@ export default function ChatPage() { ...scopedOptions?.additionalKwargs, ...modelInput.additionalKwargs, }, + // Only the first send of a lazy new chat can trigger the SDK's + // implicit thread create; mark it so the create matches the row the + // pre-create made (an incognito row otherwise conflicts with 409). + incognito: isNewThread && isIncognito, }; const sendPromise = sendMessage( threadId, @@ -478,12 +538,14 @@ export default function ChatPage() { currentKnowledgeScopeSnapshot, sendMessage, threadId, - ensureProjectThread, + ensureThreadRow, prepareModelControl, settings.context.mode, locale, isNewThread, projectParam, + incognitoParam, + isIncognito, setThreadId, setIsNewThread, ], @@ -525,6 +587,31 @@ export default function ChatPage() { const handleStop = useCallback(async () => { await thread.stop(); }, [thread]); + // End the chat and leave in the same click: the Gateway schedules the purge + // after the grace period, and a lost request still leaves the idle lifetime + // to delete the thread. The call is gated on a server row existing, not on + // `isNewThread`: the pre-create materializes the row before the first run + // flips that flag, so a lazy new chat has nothing to end while a + // pre-created one must still be ended. + const handleEndIncognito = useCallback(() => { + const endedThreadId = threadId; + if ( + shouldRequestIncognitoEnd({ + isNewThread, + isMock, + threadId: endedThreadId, + createdThreadId: createdThreadRowIdRef.current, + }) + ) { + void endIncognitoThread(endedThreadId).catch(() => { + toast.error(t.incognito.endFailed); + }); + } + queryClient.removeQueries({ + queryKey: ["thread", "metadata", endedThreadId], + }); + router.replace("/workspace/chats/new"); + }, [isMock, isNewThread, queryClient, router, t, threadId]); const handleRegenerate = useCallback( (messageId: string, supersededMessageIds: string[]) => regenerateMessage(threadId, messageId, supersededMessageIds), @@ -607,304 +694,341 @@ export default function ChatPage() { !hasOpenHumanInputCard && !hasPendingApproval; - return ( - - - -
-
- {!isMock && } -
- - {!isNewThread && - !isMock && - env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true" && ( - - )} - {affiliatedProjectId && ( - + const chatSurface = ( + +
+ {!isIncognito && ( +
+ {!isMock && } +
+ + {!isNewThread && + !isMock && + env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true" && ( + )} -
-
- {!isNewThread && - !isMock && - env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true" && ( - - )} - {!isNewThread && - !isMock && - env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true" && ( - - )} - {!isNewThread && !isMock && ( - + {affiliatedProjectId && ( + + )} +
+
+ + {!isNewThread && + !isMock && + env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true" && ( + )} - {tokenUsageEnabled ? ( - - setLocalSettings("tokenUsage", preferences) - } - /> - ) : ( - + {!isNewThread && + !isMock && + env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true" && ( + )} - - {browserEnabled && } - - - -
-
-
-
- threadMetadata.refetch()} - waitingForInputRunIds={waitingForInputRunIds} - onSubmitApproval={handleSubmitApproval} - canRegenerate={ - !isNewThread && - !isMock && - env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true" && - !isUploading && - !thread.isLoading && - !hasPendingApproval - } - onRegenerateMessage={handleRegenerate} - canEdit={editBase && !hasGoal} - editLockedByGoal={editBase && hasGoal} - onEditAndRegenerateMessage={handleEditAndRegenerate} - onSubmitHumanInput={ - isMock || env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" - ? undefined - : handleSubmitHumanInput - } - canBranch={ - !isNewThread && - !isMock && - env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true" && - !isUploading && - !thread.isLoading && - !branchThread.isPending && - !hasPendingApproval + {!isNewThread && !isMock && ( + + )} + {tokenUsageEnabled ? ( + + setLocalSettings("tokenUsage", preferences) } - onBranchTurn={handleBranchTurn} /> -
-
+ ) : ( + + )} + + {browserEnabled && } + + + +
+
+ )} +
+
+ threadMetadata.refetch()} + waitingForInputRunIds={waitingForInputRunIds} + onSubmitApproval={handleSubmitApproval} + canRegenerate={ + !isNewThread && + !isMock && + env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true" && + !isUploading && + !thread.isLoading && + !hasPendingApproval + } + onRegenerateMessage={handleRegenerate} + canEdit={editBase && !hasGoal} + editLockedByGoal={editBase && hasGoal} + onEditAndRegenerateMessage={handleEditAndRegenerate} + onSubmitHumanInput={ + isMock || env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" + ? undefined + : handleSubmitHumanInput + } + canBranch={ + !isNewThread && + !isMock && + env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true" && + !isUploading && + !thread.isLoading && + !branchThread.isPending && + !hasPendingApproval + } + // A branch copies this conversation into a new persistent + // thread, so an incognito chat offers none: no handler, no + // action. The backend rejects a branch of an incognito + // thread as well, for direct API callers. + onBranchTurn={isIncognito ? undefined : handleBranchTurn} + /> +
+
+
+ {(hasGoal || goalOutcome !== null || hasTodos) && (
- {(hasGoal || goalOutcome !== null || hasTodos) && ( -
-
- + + {hasTodos && ( +
+
+ )} + {modelControl.request && ( +
+ modelControl.choose(response)} + /> +
+ )} + {modelChoiceSummary && ( +

+ {modelChoiceSummary} +

+ )} + {isIncognito && isWelcomeMode && } + {mountedRef.current ? ( +
+ + - {hasTodos && ( -
-
- )} - {modelControl.request && ( -
- modelControl.choose(response)} - /> -
- )} - {modelChoiceSummary && ( -

- {modelChoiceSummary} -

- )} - {mountedRef.current ? ( -
- - - ) : undefined - } - autoFocus={isWelcomeMode} - status={ - thread.error - ? "error" - : thread.isLoading - ? "streaming" - : "ready" - } - context={settings.context} - extraHeader={ - isWelcomeMode && - !hasGoal && - !hasTodos && - } - disabled={ - isMock || - env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" || - isUploading || - modelControl.busy || - (!isNewThread && isHistoryLoading) || - hasPendingApproval - } - inputLocked={hasPendingApproval} - onContextChange={(context, options) => { - if (options?.automatic) - resolveThreadContext(threadId, context); - else setSettings("context", context); - }} - onGoalChange={setLocalGoal} - onPrepareThread={ensureProjectThread} - onReferenceFileAttached={() => { - if (!isNewThread) return; - history.replaceState( - null, - "", - `/workspace/chats/${threadId}`, - ); - setThreadId(threadId); - setIsNewThread(false); - }} - onSubmit={handleSubmit} - onBusySubmit={canSendInput ? sendInput : undefined} - onStop={handleStop} - canStopStreaming={canStopStreaming} - canCreateRuns={canCreateRuns} - /> -
- ) : ( - + ) : ( + -
+ )} +
-
+ + + + ); + + return ( + + + {isIncognito ? ( + + {chatSurface} + + ) : ( + chatSurface + )} ); diff --git a/frontend/src/components/workspace/chats/incognito-end.ts b/frontend/src/components/workspace/chats/incognito-end.ts new file mode 100644 index 00000000000..6e4917536be --- /dev/null +++ b/frontend/src/components/workspace/chats/incognito-end.ts @@ -0,0 +1,23 @@ +/** + * Whether closing the incognito frame must ask the Gateway to end the chat. + * + * `isNewThread` flips only when the first run starts, but a project/incognito + * pre-create (or a `/goal` command) materializes the thread row earlier. The + * decision therefore follows the row, not the flag: a lazy chat that never + * created a row has nothing to end, while a pre-created one must still be + * ended before the frame navigates away. + */ +export function shouldRequestIncognitoEnd({ + isNewThread, + isMock, + threadId, + createdThreadId, +}: { + isNewThread: boolean; + isMock: boolean; + threadId: string; + createdThreadId: string | null; +}): boolean { + if (isMock) return false; + return !isNewThread || createdThreadId === threadId; +} \ No newline at end of file diff --git a/frontend/src/components/workspace/chats/incognito-entry.tsx b/frontend/src/components/workspace/chats/incognito-entry.tsx new file mode 100644 index 00000000000..6a8c9d873a2 --- /dev/null +++ b/frontend/src/components/workspace/chats/incognito-entry.tsx @@ -0,0 +1,50 @@ +"use client"; + +import { GhostIcon } from "lucide-react"; +import Link from "next/link"; + +import { Button } from "@/components/ui/button"; +import { useIncognitoFeature } from "@/core/features/hooks"; +import { useI18n } from "@/core/i18n/hooks"; +import { env } from "@/env"; + +import { Tooltip } from "../tooltip"; + +/** + * The ghost entry to a new incognito chat, sitting in the chat header's + * top-right cluster. The sidebar carries no incognito item: the mode starts + * from the surface it applies to. + */ +export function IncognitoEntry({ isNewThread }: { isNewThread: boolean }) { + const { t } = useI18n(); + const { enabled } = useIncognitoFeature(); + // Only a blank new chat offers the entry: a saved conversation is already + // committed to its visibility, and turning it into a temporary chat is not + // something the storage boundary permits. A static demo has no Gateway, so + // the entry would lead to a dead page, and an operator can disable new + // incognito chats entirely. + if ( + !isNewThread || + !enabled || + env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" + ) { + return null; + } + return ( + + + + ); +} diff --git a/frontend/src/components/workspace/chats/incognito-frame.tsx b/frontend/src/components/workspace/chats/incognito-frame.tsx new file mode 100644 index 00000000000..c98d41960af --- /dev/null +++ b/frontend/src/components/workspace/chats/incognito-frame.tsx @@ -0,0 +1,102 @@ +"use client"; + +import { GhostIcon, XIcon } from "lucide-react"; +import type { ReactNode } from "react"; + +import { Button } from "@/components/ui/button"; +import { useI18n } from "@/core/i18n/hooks"; +import { + incognitoLifetimeLabel, + incognitoLifetimeParts, +} from "@/core/threads/incognito"; + +import { Tooltip } from "../tooltip"; + +export interface IncognitoNoticesProps { + /** + * Idle window from `/api/features`, or `null` when it could not be read. + * The UI never states a lifetime the server did not report. + */ + idleTtlSeconds: number | null; +} + +/** + * The full-width shell of an incognito chat: a dark top bar around a framed, + * lightly-filled conversation area. The workspace sidebar and the ordinary + * chat header are not part of this surface. + */ +export function IncognitoShell({ + onEnd, + children, +}: { + /** End the chat and leave; the Gateway purges it after the grace period. */ + onEnd: () => void; + children: ReactNode; +}) { + const { t } = useI18n(); + return ( +
+
+
+
+
+ {children} +
+
+
+ ); +} + +/** The centered heading of an empty incognito chat. */ +export function IncognitoTitle() { + const { t } = useI18n(); + return ( +
+ {t.incognito.title} +
+ ); +} + +/** + * What the chat never enters and when it disappears, plus the third-party + * boundary. Rendered under the composer inside the frame. + */ +export function IncognitoNotices({ idleTtlSeconds }: IncognitoNoticesProps) { + const { t } = useI18n(); + const duration = + idleTtlSeconds === null + ? null + : incognitoLifetimeLabel(incognitoLifetimeParts(idleTtlSeconds), t.incognito); + return ( +
+

+ {duration === null + ? t.incognito.noticesUnknown + : t.incognito.notices(duration)} +

+

+ {t.incognito.boundaryNotice} +

+
+ ); +} diff --git a/frontend/src/components/workspace/chats/use-thread-chat.ts b/frontend/src/components/workspace/chats/use-thread-chat.ts index c65fa001e6c..278ee9418da 100644 --- a/frontend/src/components/workspace/chats/use-thread-chat.ts +++ b/frontend/src/components/workspace/chats/use-thread-chat.ts @@ -84,31 +84,35 @@ export function useThreadChat() { }, [pathname, threadIdFromPath]); // A new-chat identity is minted for the entry scope (the new chat's - // `project` query). The sidebar "New chat" link can leave - // `/new?project=…` for plain `/new` without a pathname change, so the - // pathname sync above keeps the old identity — which may already be - // pre-created under the previous project, and whose in-flight submission - // would otherwise survive the navigation. Re-mint whenever the project - // scope changes while still on a new-chat path. + // `project` and `incognito` query). The sidebar links can move between + // `/new`, `/new?project=…` and `/new?incognito=true` without a pathname + // change, so the pathname sync above keeps the old identity — which may + // already be pre-created under the previous scope, and whose in-flight + // submission would otherwise survive the navigation. Re-mint whenever the + // entry scope changes while still on a new-chat path. const newChatScopeRef = useRef(NEW_CHAT_SCOPE_UNSET); useEffect(() => { const project = isNewPath ? searchParams.get("project") : null; + const incognito = isNewPath && searchParams.get("incognito") === "true"; + // Incognito threads never belong to a project; compose the scope so a + // switch between the two entry points always mints a fresh identity. + const scope = `${project ?? ""}\u0000${incognito ? "incognito" : ""}`; if (!isNewPath) { newChatScopeRef.current = NEW_CHAT_SCOPE_UNSET; return; } - if (newChatScopeRef.current === project) { + if (newChatScopeRef.current === scope) { return; } const previousScope = newChatScopeRef.current; - newChatScopeRef.current = project; + newChatScopeRef.current = scope; if (previousScope === NEW_CHAT_SCOPE_UNSET) { return; } - // Scope changed (project added, removed, or swapped): the old identity - // belongs to the previous scope, so allocate a fresh one. The threadId - // flip also runs every fence keyed on `threadId` (composer goal aborts, - // chat-page submission epoch). + // Scope changed (project added, removed, or swapped; incognito toggled): + // the old identity belongs to the previous scope, so allocate a fresh one. + // The threadId flip also runs every fence keyed on `threadId` (composer + // goal aborts, chat-page submission epoch). const nextThreadId = uuid(); newThreadIdRef.current = nextThreadId; setIsNewThreadState(true); diff --git a/frontend/src/components/workspace/incognito-mode-context.tsx b/frontend/src/components/workspace/incognito-mode-context.tsx new file mode 100644 index 00000000000..5c26c7ac436 --- /dev/null +++ b/frontend/src/components/workspace/incognito-mode-context.tsx @@ -0,0 +1,53 @@ +"use client"; + +import { + createContext, + useContext, + useLayoutEffect, + useMemo, + useState, + type ReactNode, +} from "react"; + +interface IncognitoModeValue { + incognito: boolean; + setIncognito: (active: boolean) => void; +} + +const IncognitoModeContext = createContext(null); + +/** + * Publishes "an incognito chat is open" from the chat page to the workspace + * shell, which then stops rendering the sidebar. The URL alone cannot tell: + * an existing incognito thread is recognized from its metadata after it loads. + */ +export function IncognitoModeProvider({ children }: { children: ReactNode }) { + const [incognito, setIncognito] = useState(false); + const value = useMemo(() => ({ incognito, setIncognito }), [incognito]); + return ( + + {children} + + ); +} + +/** Whether the workspace is showing an incognito chat; false without a provider. */ +export function useIncognitoMode() { + return useContext(IncognitoModeContext)?.incognito ?? false; +} + +/** + * Publishes the current surface's incognito state while it renders. A layout + * effect keeps the sidebar from painting even once before it is hidden, and + * unmounting the chat page releases the flag for whatever renders next. + */ +export function usePublishIncognitoMode(active: boolean) { + const setIncognito = useContext(IncognitoModeContext)?.setIncognito; + useLayoutEffect(() => { + if (!setIncognito) { + return; + } + setIncognito(active); + return () => setIncognito(false); + }, [active, setIncognito]); +} diff --git a/frontend/src/components/workspace/input-box.tsx b/frontend/src/components/workspace/input-box.tsx index 83d0ae11bcc..97948d49e20 100644 --- a/frontend/src/components/workspace/input-box.tsx +++ b/frontend/src/components/workspace/input-box.tsx @@ -354,6 +354,7 @@ export function InputBox({ canStopStreaming = true, canCreateRuns = true, inputLocked = false, + incognito = false, agentSkillNames, agentSkillsLoading = false, ...props @@ -363,6 +364,11 @@ export function InputBox({ disabled?: boolean; /** Prevent new input while retaining cancellation of a live run. */ inputLocked?: boolean; + /** + * An incognito chat keeps the composer bare: the surface's own notices + * replace the welcome suggestions and the AI disclaimer. + */ + incognito?: boolean; context: Omit< AgentThreadContext, "thread_id" | "is_plan_mode" | "thinking_enabled" | "subagent_enabled" @@ -3740,6 +3746,7 @@ export function InputBox({ )} {isWelcomeMode && + !incognito && searchParams.get("mode") !== "skill" && !showCommandSuggestions && !showMentions && ( @@ -3748,14 +3755,16 @@ export function InputBox({ )} -

- {t.inputBox.disclaimer} -

+ {!incognito && ( +

+ {t.inputBox.disclaimer} +

+ )} diff --git a/frontend/src/components/workspace/messages/message-list.tsx b/frontend/src/components/workspace/messages/message-list.tsx index 1f5541dab9c..801fd18abdb 100644 --- a/frontend/src/components/workspace/messages/message-list.tsx +++ b/frontend/src/components/workspace/messages/message-list.tsx @@ -1908,7 +1908,7 @@ export function MessageList({ {t.sidecar.addToConversation} - {!sidecarSurface && ( + {!sidecarSurface && !sidecar.disabled && ( + + + + + ); +} + +function renderProbe(disabled: boolean) { + return render( + + + , + ); +} + +beforeEach(() => { + api.findLatestSidecarThread.mockReset(); + api.findLatestSidecarThread.mockResolvedValue(null); +}); + +afterEach(cleanup); + +describe("SidecarProvider in an incognito chat", () => { + it("never queries, restores or opens a side thread", async () => { + renderProbe(true); + + expect(screen.getByTestId("disabled").textContent).toBe("true"); + await waitFor(() => + expect(api.findLatestSidecarThread).not.toHaveBeenCalled(), + ); + + fireEvent.click(screen.getByText("open-sidecar")); + fireEvent.click(screen.getByText("open-context")); + fireEvent.click(screen.getByText("open-selected-text")); + + expect(screen.getByTestId("open").textContent).toBe("false"); + expect(screen.getByTestId("sidecar-thread").textContent).toBe("null"); + }); + + it("still quotes selected text into the main composer", () => { + renderProbe(true); + + fireEvent.click(screen.getByText("quote")); + + expect(screen.getByTestId("quotes").textContent).toBe("1"); + expect(screen.getByTestId("open").textContent).toBe("false"); + }); + + it("keeps the ordinary restore and open paths when enabled", async () => { + renderProbe(false); + + expect(screen.getByTestId("disabled").textContent).toBe("false"); + await waitFor(() => + expect(api.findLatestSidecarThread).toHaveBeenCalledTimes(1), + ); + + fireEvent.click(screen.getByText("open-context")); + + expect(screen.getByTestId("open").textContent).toBe("true"); + }); +}); diff --git a/frontend/tests/unit/components/workspace/workspace-sidebar-frame.dom.test.tsx b/frontend/tests/unit/components/workspace/workspace-sidebar-frame.dom.test.tsx index 1291515de3a..b9c554bff51 100644 --- a/frontend/tests/unit/components/workspace/workspace-sidebar-frame.dom.test.tsx +++ b/frontend/tests/unit/components/workspace/workspace-sidebar-frame.dom.test.tsx @@ -22,14 +22,27 @@ import { const { mobile, navigation } = rs.hoisted(() => ({ mobile: { value: true }, - navigation: { pathname: "/workspace/chats/new" }, + navigation: { pathname: "/workspace/chats/new", search: "" }, })); rs.mock("@/hooks/use-mobile", () => ({ useIsMobile: () => mobile.value })); rs.mock("next/navigation", () => ({ usePathname: () => navigation.pathname, + useSearchParams: () => new URLSearchParams(navigation.search), +})); +rs.mock("@/core/features/hooks", () => ({ + useIncognitoFeature: () => ({ + enabled: false, + idleTtlSeconds: 86400, + isLoading: false, + }), })); rs.mock("@/core/i18n/hooks", () => ({ - useI18n: () => ({ t: { sidebar: { newChat: "New chat" } } }), + useI18n: () => ({ + t: { + sidebar: { newChat: "New chat" }, + incognito: { entry: "Incognito chat" }, + }, + }), })); rs.mock("@/env", () => ({ env: { NEXT_PUBLIC_STATIC_WEBSITE_ONLY: "false" }, @@ -82,6 +95,7 @@ afterEach(() => { cleanup(); mobile.value = true; navigation.pathname = "/workspace/chats/new"; + navigation.search = ""; document.cookie = "sidebar_state=; path=/; max-age=0"; }); diff --git a/frontend/tests/unit/components/workspace/workspace-sidebar-incognito.dom.test.tsx b/frontend/tests/unit/components/workspace/workspace-sidebar-incognito.dom.test.tsx new file mode 100644 index 00000000000..37e06501274 --- /dev/null +++ b/frontend/tests/unit/components/workspace/workspace-sidebar-incognito.dom.test.tsx @@ -0,0 +1,88 @@ +import { afterEach, describe, expect, rs, test } from "@rstest/core"; +import { cleanup, render, screen } from "@testing-library/react"; +import type { ReactNode } from "react"; + +import { + IncognitoModeProvider, + usePublishIncognitoMode, +} from "@/components/workspace/incognito-mode-context"; +import { WorkspaceSidebar } from "@/components/workspace/workspace-sidebar"; + +rs.mock("@/components/ui/sidebar", () => ({ + SidebarHeader: ({ children }: { children: ReactNode }) => ( +
{children}
+ ), + SidebarContent: ({ children }: { children: ReactNode }) => ( +
{children}
+ ), + SidebarFooter: ({ children }: { children: ReactNode }) => ( +
{children}
+ ), + SidebarRail: () => null, + useSidebar: () => ({ isMobile: false }), +})); +rs.mock("@/core/threads/activity", () => ({ + useThreadActivity: () => undefined, +})); +rs.mock("@/components/workspace/workspace-sidebar-frame", () => ({ + WorkspaceSidebarFrame: ({ children }: { children: ReactNode }) => ( +
{children}
+ ), + useWorkspaceSidebarExpanded: () => true, +})); +rs.mock("@/components/workspace/workspace-header", () => ({ + WorkspaceHeader: () => null, +})); +rs.mock("@/components/workspace/workspace-nav-chat-list", () => ({ + WorkspaceNavChatList: () => null, +})); +rs.mock("@/components/workspace/workspace-nav-menu", () => ({ + WorkspaceNavMenu: () => null, +})); +rs.mock("@/components/workspace/channels/workspace-channels-list", () => ({ + WorkspaceChannelsList: () => null, +})); +rs.mock("@/components/workspace/plugin-navigation", () => ({ + PluginNavigation: () => null, +})); +rs.mock("@/components/workspace/projects-section", () => ({ + ProjectsSection: () => null, +})); +rs.mock("@/components/workspace/recent-chat-list", () => ({ + RecentChatList: () => null, +})); +rs.mock("@/components/workspace/thread-delete-dialog", () => ({ + ThreadDeleteDialogProvider: ({ children }: { children: ReactNode }) => ( + <>{children} + ), +})); + +function Publisher({ active }: { active: boolean }) { + usePublishIncognitoMode(active); + return null; +} + +function renderSidebar(active: boolean) { + return render( + + + + , + ); +} + +afterEach(cleanup); + +describe("workspace sidebar in an incognito chat", () => { + test("is unmounted, not collapsed", () => { + renderSidebar(true); + + expect(screen.queryByTestId("workspace-sidebar")).toBeNull(); + }); + + test("stays mounted in an ordinary chat", () => { + renderSidebar(false); + + expect(screen.getByTestId("workspace-sidebar")).not.toBeNull(); + }); +}); diff --git a/frontend/tests/unit/core/features/api.test.ts b/frontend/tests/unit/core/features/api.test.ts index bf0e14b1293..abef8fdaa71 100644 --- a/frontend/tests/unit/core/features/api.test.ts +++ b/frontend/tests/unit/core/features/api.test.ts @@ -6,6 +6,7 @@ rs.mock("@/core/config", () => ({ getBackendBaseURL: () => "" })); import { fetch } from "@/core/api/fetcher"; import { fetchConversationReferencesCapability, + fetchIncognitoFeature, fetchScheduledTasksFeature, fetchSubagentBatchesCapability, } from "@/core/features/api"; @@ -157,3 +158,43 @@ describe("scheduled tasks feature", () => { }); }); }); + +describe("incognito feature", () => { + it("reads the entry switch and the idle lifetime", async () => { + mockedFetch.mockResolvedValueOnce( + jsonResponse({ + agents_api: { enabled: true }, + incognito: { enabled: true, idle_ttl_seconds: 3600 }, + }), + ); + await expect(fetchIncognitoFeature()).resolves.toEqual({ + enabled: true, + idleTtlSeconds: 3600, + }); + }); + + it("keeps the entry hidden and the lifetime unknown without the block", async () => { + mockedFetch.mockResolvedValueOnce( + jsonResponse({ agents_api: { enabled: true } }), + ); + await expect(fetchIncognitoFeature()).resolves.toEqual({ + enabled: false, + idleTtlSeconds: null, + }); + }); + + it("never states a lifetime the backend did not report as a positive integer", async () => { + for (const idle of [0, -60, 1.5, "86400", null]) { + mockedFetch.mockResolvedValueOnce( + jsonResponse({ + agents_api: { enabled: true }, + incognito: { enabled: true, idle_ttl_seconds: idle }, + }), + ); + await expect(fetchIncognitoFeature()).resolves.toEqual({ + enabled: true, + idleTtlSeconds: null, + }); + } + }); +}); diff --git a/frontend/tests/unit/core/threads/api.test.ts b/frontend/tests/unit/core/threads/api.test.ts index 84740909f43..abe5d235633 100644 --- a/frontend/tests/unit/core/threads/api.test.ts +++ b/frontend/tests/unit/core/threads/api.test.ts @@ -171,3 +171,72 @@ test("compactThreadContext surfaces an active-run conflict", async () => { "Thread has a run in flight. Compact after the run finishes.", ); }); + +test("createThread sends the incognito marker only when requested", async () => { + fetchWithAuth.mockResolvedValue({ + ok: true, + json: async () => ({ thread_id: "thread-1", incognito: true }), + }); + + const { createThread } = await import("@/core/threads/api"); + + await createThread("thread-1", undefined, true); + expect(fetchWithAuth).toHaveBeenCalledWith( + expect.stringContaining("/api/threads"), + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ thread_id: "thread-1", incognito: true }), + }, + ); + + fetchWithAuth.mockClear(); + await createThread("thread-2", "project-1"); + expect(fetchWithAuth).toHaveBeenCalledWith( + expect.stringContaining("/api/threads"), + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ thread_id: "thread-2", project_id: "project-1" }), + }, + ); +}); + +test("endIncognitoThread posts to the end route and keeps the request alive", async () => { + fetchWithAuth.mockResolvedValue({ ok: true, status: 204 }); + + const { endIncognitoThread } = await import("@/core/threads/api"); + + await expect(endIncognitoThread("thread/1")).resolves.toBeUndefined(); + expect(fetchWithAuth).toHaveBeenCalledWith( + expect.stringContaining("/api/threads/thread%2F1/incognito/end"), + { method: "POST", keepalive: true }, + ); +}); + +test("endIncognitoThread treats an already-deleted chat as done", async () => { + const { endIncognitoThread } = await import("@/core/threads/api"); + + for (const status of [404, 410]) { + fetchWithAuth.mockResolvedValue({ + ok: false, + status, + json: async () => ({ detail: "This incognito thread has expired" }), + }); + await expect(endIncognitoThread("thread-1")).resolves.toBeUndefined(); + } +}); + +test("endIncognitoThread surfaces a real failure", async () => { + fetchWithAuth.mockResolvedValue({ + ok: false, + status: 500, + json: async () => ({ detail: "Failed to end the thread" }), + }); + + const { endIncognitoThread } = await import("@/core/threads/api"); + + await expect(endIncognitoThread("thread-1")).rejects.toThrow( + "Failed to end the thread", + ); +}); diff --git a/frontend/tests/unit/core/threads/incognito.test.ts b/frontend/tests/unit/core/threads/incognito.test.ts new file mode 100644 index 00000000000..85feccb9142 --- /dev/null +++ b/frontend/tests/unit/core/threads/incognito.test.ts @@ -0,0 +1,155 @@ +import { describe, expect, test } from "@rstest/core"; + +import { enUS } from "@/core/i18n/locales/en-US"; +import { + incognitoLifetimeLabel, + incognitoLifetimeParts, +} from "@/core/threads/incognito"; + +const MINUTE = 60; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; + +describe("incognitoLifetimeParts", () => { + test("keeps windows up to 72 hours in hours", () => { + expect(incognitoLifetimeParts(HOUR)).toEqual({ + count: 1, + unit: "hours", + remainderHours: 0, + approximate: false, + }); + expect(incognitoLifetimeParts(2 * DAY)).toEqual({ + count: 48, + unit: "hours", + remainderHours: 0, + approximate: false, + }); + expect(incognitoLifetimeParts(72 * HOUR)).toEqual({ + count: 72, + unit: "hours", + remainderHours: 0, + approximate: false, + }); + }); + + test("switches to days past 72 hours", () => { + expect(incognitoLifetimeParts(73 * HOUR)).toEqual({ + count: 3, + unit: "days", + remainderHours: 1, + approximate: false, + }); + expect(incognitoLifetimeParts(7 * DAY)).toEqual({ + count: 7, + unit: "days", + remainderHours: 0, + approximate: false, + }); + expect(incognitoLifetimeParts(4 * DAY + 4 * HOUR)).toEqual({ + count: 4, + unit: "days", + remainderHours: 4, + approximate: false, + }); + }); + + test("marks a window the units cannot spell exactly", () => { + expect(incognitoLifetimeParts(90)).toEqual({ + count: 2, + unit: "minutes", + remainderHours: 0, + approximate: true, + }); + expect(incognitoLifetimeParts(90 * MINUTE)).toEqual({ + count: 2, + unit: "hours", + remainderHours: 0, + approximate: true, + }); + expect(incognitoLifetimeParts(73 * HOUR + 30 * MINUTE)).toEqual({ + count: 3, + unit: "days", + remainderHours: 2, + approximate: true, + }); + expect(incognitoLifetimeParts(4 * DAY + MINUTE)).toEqual({ + count: 4, + unit: "days", + remainderHours: 0, + approximate: true, + }); + }); + + test("picks the unit from the rounded value", () => { + // 71.5 hours rounds to 72, the last hour-counted window. + expect(incognitoLifetimeParts(71.5 * HOUR)).toEqual({ + count: 72, + unit: "hours", + remainderHours: 0, + approximate: true, + }); + // 72.5 hours rounds to 73, which reads as three days and one hour. + expect(incognitoLifetimeParts(72.5 * HOUR)).toEqual({ + count: 3, + unit: "days", + remainderHours: 1, + approximate: true, + }); + // 59.5 minutes rounds up to an hour instead of showing 60 minutes. + expect(incognitoLifetimeParts(59.5 * MINUTE)).toEqual({ + count: 1, + unit: "hours", + remainderHours: 0, + approximate: true, + }); + }); + + test("falls back to minutes and never reports zero", () => { + expect(incognitoLifetimeParts(MINUTE)).toEqual({ + count: 1, + unit: "minutes", + remainderHours: 0, + approximate: false, + }); + // The config schema enforces at least 60s; a stray small value still + // must not render "0 minutes". + expect(incognitoLifetimeParts(1)).toEqual({ + count: 1, + unit: "minutes", + remainderHours: 0, + approximate: true, + }); + expect(incognitoLifetimeParts(-5)).toEqual({ + count: 1, + unit: "minutes", + remainderHours: 0, + approximate: false, + }); + }); +}); + +describe("incognitoLifetimeLabel", () => { + test("spells exact windows without the approximate marker", () => { + expect( + incognitoLifetimeLabel(incognitoLifetimeParts(DAY), enUS.incognito), + ).toBe("24 hours"); + expect( + incognitoLifetimeLabel(incognitoLifetimeParts(73 * HOUR), enUS.incognito), + ).toBe("3 days and 1 hour"); + expect( + incognitoLifetimeLabel(incognitoLifetimeParts(7 * DAY), enUS.incognito), + ).toBe("7 days"); + }); + + test("marks what the display rounds", () => { + expect( + incognitoLifetimeLabel( + incognitoLifetimeParts(73 * HOUR + 30 * MINUTE), + enUS.incognito, + ), + ).toBe("about 3 days and 2 hours"); + expect( + incognitoLifetimeLabel(incognitoLifetimeParts(90), enUS.incognito), + ).toBe("about 2 minutes"); + }); +});