Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
5d051c6
feat(threads): add incognito threads hidden from lists, search and di…
Loveca Nov 15, 2026
2784e40
feat(threads): expire incognito threads with a tombstone-first sweep
Loveca Nov 15, 2026
fdbb4fd
fix(incognito): keep thread config reads off the loop and complete th…
Loveca Nov 16, 2026
778caf1
feat(agents): skip memory and blob writes for incognito runs
Loveca Nov 16, 2026
8a9ddca
feat(features): expose incognito chat availability and idle lifetime
Loveca Nov 16, 2026
baf8911
feat(frontend): add incognito chat entry and exit flow
Loveca Nov 16, 2026
34578e5
fix(incognito): propagate the marker into subagents and purge batch rows
Loveca Nov 16, 2026
49723aa
fix(incognito): bind no scheduler capability on incognito threads
Loveca Nov 16, 2026
5fa0f90
feat(incognito): close the side-chat entry in incognito chats
Loveca Nov 16, 2026
89725aa
feat(incognito): offer no branch action in an incognito chat
Loveca Nov 16, 2026
8f09e3d
docs(incognito): document the API contract and the storage boundary
Loveca Nov 16, 2026
28ef859
feat(incognito): rebuild the surface around the approved design
Loveca Nov 16, 2026
0140379
fix(incognito): close the live-test gaps in the temporary-chat boundary
Loveca Nov 16, 2026
2b6c6f5
fix(incognito): close the remaining boundary gaps from review
Loveca Nov 17, 2026
a055c9b
fix(incognito): bound the lifetime config and spell the idle window
Loveca Nov 17, 2026
923103a
fix(incognito): scope the Chinese term rule to Chinese replies
Loveca Nov 17, 2026
593f18d
fix(incognito): register the incognito prompt tag in the input denylist
Loveca Nov 21, 2026
ba109a2
fix(config): bound the incognito end grace period
LuisQin01 Nov 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
24 changes: 24 additions & 0 deletions backend/app/gateway/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
8 changes: 5 additions & 3 deletions backend/app/gateway/conversation_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
91 changes: 84 additions & 7 deletions backend/app/gateway/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand All @@ -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)

Expand Down Expand Up @@ -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,
Expand All @@ -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,
),
)

Expand Down
106 changes: 106 additions & 0 deletions backend/app/gateway/incognito.py
Original file line number Diff line number Diff line change
@@ -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)
14 changes: 14 additions & 0 deletions backend/app/gateway/routers/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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)

Expand Down Expand Up @@ -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,
),
)


Expand Down
Loading