From 9e85b2f3671aedfd9502c9859e0b707fe6ca87c5 Mon Sep 17 00:00:00 2001 From: kongxin Date: Sat, 21 Nov 2026 00:46:09 -0800 Subject: [PATCH] fix(sharing): keep imported share history out of the importer's memory (#8422) * fix(sharing): keep imported share history out of the importer's memory Share import now marks every copied message with a server-owned deerflow_imported_history key. Memory capture skips marked messages after each run and in the pre-compaction flush, before any backend sees them, so the sharer's statements no longer become facts about the visitor. The Gateway strips the key from client input. * fix(sharing): mark the copied history of copies imported before marks Run admission now marks a share copy made before imported messages were marked, next to the existing history-seed shim. Only messages from the copy's root checkpoint, which the import wrote, are marked, so the owner's own turns stay eligible for memory. Busy or paused threads are left for a later run, and a metadata failure never blocks the run. The share-import metadata keys are now server-reserved. --- backend/app/gateway/routers/threads.py | 4 +- backend/app/gateway/services.py | 8 +- backend/app/gateway/share_fork.py | 86 +++++++++- .../agents/memory/summarization_hook.py | 9 +- .../agents/middlewares/memory_middleware.py | 9 +- .../harness/deerflow/utils/messages.py | 18 +++ backend/tests/test_gateway_services.py | 13 ++ backend/tests/test_memory_middleware.py | 47 ++++++ backend/tests/test_shares_router.py | 147 ++++++++++++++++++ docs/guide/sharing.md | 6 + 10 files changed, 334 insertions(+), 13 deletions(-) diff --git a/backend/app/gateway/routers/threads.py b/backend/app/gateway/routers/threads.py index bab50c4c1d..f32d9a1398 100644 --- a/backend/app/gateway/routers/threads.py +++ b/backend/app/gateway/routers/threads.py @@ -57,6 +57,7 @@ from app.gateway.services import ( reserve_checkpoint_write, strip_server_owned_state_metadata, ) +from app.gateway.share_fork import SHARE_IMPORT_COMPLETE_KEY, SHARE_IMPORT_HISTORY_MARKED_KEY from app.gateway.utils import sanitize_log_param from deerflow.agents.human_input import extract_unanswered_human_input_request from deerflow.agents.thread_state import THREAD_STATE_REDUCER_FIELDS @@ -127,7 +128,8 @@ def _optional_run_event_store(request: Request) -> Any: # 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}) +# The share-import keys decide whether run admission rewrites a copy's history. +_SERVER_RESERVED_METADATA_KEYS: frozenset[str] = frozenset({"owner_id", "user_id", THREAD_PROJECT_METADATA_KEY, DEERFLOW_ORIGIN_KEY, SHARE_IMPORT_COMPLETE_KEY, SHARE_IMPORT_HISTORY_MARKED_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 diff --git a/backend/app/gateway/services.py b/backend/app/gateway/services.py index f53ad7c18a..ec61cd12c9 100644 --- a/backend/app/gateway/services.py +++ b/backend/app/gateway/services.py @@ -117,7 +117,7 @@ from deerflow.trace_context import DEERFLOW_TRACE_METADATA_KEY, ensure_trace_con from deerflow.utils.assembly_io import run_assembly from deerflow.utils.file_io import await_drained from deerflow.utils.goal_objective import normalize_goal_objective -from deerflow.utils.messages import ORIGINAL_USER_CONTENT_KEY, UNTRUSTED_INPUT_KEY +from deerflow.utils.messages import IMPORTED_HISTORY_KEY, ORIGINAL_USER_CONTENT_KEY, UNTRUSTED_INPUT_KEY from deerflow.utils.thread_id import validate_thread_id logger = logging.getLogger(__name__) @@ -206,6 +206,9 @@ _SERVER_OWNED_MESSAGE_METADATA_KEYS = ( SUBAGENT_RECEIPT_VERDICT_KEY, SUBAGENT_ACCEPTANCE_VERDICT_KEY, UNTRUSTED_INPUT_KEY, + # Only a share import marks history as someone else's; what a + # caller sends is its own and stays eligible for memory. + IMPORTED_HISTORY_KEY, "run_input_id", "run_input_source", "origin_task_id", @@ -3073,6 +3076,9 @@ async def start_run( thread_id=thread_id, assistant_id=body.assistant_id, ) + from app.gateway.share_fork import ensure_share_import_history_marked + + await ensure_share_import_history_marked(request, thread_id, threads=run_ctx.thread_store, metadata_timeout=_THREAD_METADATA_SETUP_TIMEOUT_SECONDS) # A strict caller may have observed the thread before a # concurrent delete removed it while checkpoint preparation # yielded. Recheck immediately before durable admission. The diff --git a/backend/app/gateway/share_fork.py b/backend/app/gateway/share_fork.py index 817a6e0846..9d57cd218c 100644 --- a/backend/app/gateway/share_fork.py +++ b/backend/app/gateway/share_fork.py @@ -1,5 +1,7 @@ """Import a share into a fresh owner-scoped default-agent conversation.""" +import asyncio +import logging import os import uuid from contextlib import asynccontextmanager @@ -11,18 +13,30 @@ from langgraph.types import Overwrite from app.gateway.deps import get_checkpointer, get_run_event_store, get_run_manager, get_thread_store from app.gateway.extension_artifacts import snapshot_sandbox from app.gateway.history_seed import reserve_history_seed, write_history_seed +from app.gateway.internal_auth import get_trusted_internal_owner_user_id from app.gateway.persistent_writes import run_drained_write from app.gateway.services import build_checkpoint_state_mutation_accessor from app.gateway.share_snapshot import MAX_SHARE_FILE_BYTES, OUTPUT_PREFIX, artifact_path +from app.gateway.utils import sanitize_log_param from deerflow.config.paths import get_paths +from deerflow.persistence.thread_meta import ThreadMetaStore from deerflow.persistence.thread_shares.sql import ThreadShareRepository -from deerflow.runtime import ThreadOperationKind +from deerflow.runtime import ConflictError, ThreadOperationKind from deerflow.runtime.events.store.db import DbRunEventStore from deerflow.runtime.goal import goal_thread_lock from deerflow.runtime.journal import build_branch_history_seed_events from deerflow.runtime.user_context import get_effective_user_id from deerflow.sandbox.artifact_snapshot import publish_snapshot from deerflow.utils.file_io import run_file_io +from deerflow.utils.messages import IMPORTED_HISTORY_KEY + +logger = logging.getLogger(__name__) + +#: Thread metadata, written only by this module (the thread routes strip +#: client copies): the copy's history is fully imported, and its copied +#: messages carry :data:`IMPORTED_HISTORY_KEY`. +SHARE_IMPORT_COMPLETE_KEY = "share_import_complete" +SHARE_IMPORT_HISTORY_MARKED_KEY = "share_import_history_marked" def _write_fork_files(owner: str, thread_id: str, artifacts: list[dict]) -> None: @@ -80,7 +94,7 @@ async def fork_share(request: Request, repo: ThreadShareRepository, token: str, async with goal_thread_lock(thread_id): existing = await threads.get(thread_id, user_id=owner) if existing is not None: - if existing.get("metadata", {}).get("share_import_complete") is True: + if existing.get("metadata", {}).get(SHARE_IMPORT_COMPLETE_KEY) is True: return {"thread_id": thread_id} raise HTTPException(409, "The previous import did not finish; create a new copy") artifacts = [] @@ -91,13 +105,14 @@ async def fork_share(request: Request, repo: ThreadShareRepository, token: str, artifacts.append(artifact) # Tool results become ordinary historical assistant text. The new thread # inherits no tool execution, system prompt, Agent, project or auth grants. + # The import mark keeps the copied turns out of the visitor's memory. messages = [] for item in share["snapshot"]["messages"]: content = item["content"] if item["type"] == "tool": content = f"{item['name']}:\n{content}" cls = HumanMessage if item["type"] == "human" else AIMessage - messages.append(cls(content=content, id=str(uuid.uuid4()))) + messages.append(cls(content=content, id=str(uuid.uuid4()), additional_kwargs={IMPORTED_HISTORY_KEY: "share"})) title = str(share["snapshot"]["title"])[:256] # Recheck after loading all bytes, before creating any new workspace state. if await repo.get_public(token) is None: @@ -105,7 +120,7 @@ async def fork_share(request: Request, repo: ThreadShareRepository, token: str, async with _reserve_import(request, thread_id, owner) as reservation: existing = await threads.get(thread_id, user_id=owner) if existing is not None: - if existing.get("metadata", {}).get("share_import_complete") is True: + if existing.get("metadata", {}).get(SHARE_IMPORT_COMPLETE_KEY) is True: return {"thread_id": thread_id} raise HTTPException(409, "The previous import did not finish; create a new copy") created = False @@ -122,7 +137,7 @@ async def fork_share(request: Request, repo: ThreadShareRepository, token: str, await accessor.aupdate(config, {"messages": Overwrite(messages), "title": title, "artifacts": Overwrite([OUTPUT_PREFIX + a["path"] for a in artifacts])}, as_node="branch") events = build_branch_history_seed_events(messages, thread_id=thread_id, run_id_prefix=f"branch-seed-{thread_id}", parent_thread_id=thread_id) await write_history_seed(request, events, reservation=reservation, seed_kind="branch", thread=record) - await threads.update_metadata(thread_id, {"share_import_complete": True}, user_id=owner) + await threads.update_metadata(thread_id, {SHARE_IMPORT_COMPLETE_KEY: True, SHARE_IMPORT_HISTORY_MARKED_KEY: True}, user_id=owner) except Exception: if created: # Keep admission until rollback finishes, so a failed import @@ -133,3 +148,64 @@ async def fork_share(request: Request, repo: ThreadShareRepository, token: str, await threads.delete(thread_id, user_id=owner) raise return {"thread_id": thread_id} + + +async def _imported_message_ids(request: Request, accessor, config: dict) -> set[str] | None: + """IDs of the history the import wrote as the thread's root checkpoint. + + ``None`` when the root is gone or unreadable: guessing from a later + checkpoint would mark the owner's own turns as someone else's. + """ + tuples = [item async for item in get_checkpointer(request).alist(config)] + if not tuples or tuples[-1].parent_config is not None: + return None + root_id = tuples[-1].config["configurable"]["checkpoint_id"] + snapshot = await accessor.aget({**config, "configurable": {**config["configurable"], "checkpoint_id": root_id}}) + messages = snapshot.values.get("messages") if isinstance(snapshot.values, dict) else None + ids = {message.id for message in messages or () if getattr(message, "id", None)} + return ids or None + + +async def ensure_share_import_history_marked(request: Request, thread_id: str, *, threads: ThreadMetaStore | None, metadata_timeout: float) -> None: + """Mark the copied history of a share copy imported before marks existed. + + Migration shim, run before admission like ``ensure_checkpoint_history_seeded``: + without it, such a copy's history reaches memory extraction on the owner's + next run, also through the pre-compaction flush, which ignores extraction + watermarks. Remove it once those copies are no longer an upgrade source. + A busy or paused thread is left for a later run, because a checkpoint + write would race the active run or replace the pending interrupt. The + shim is best effort: a failure is logged and never blocks the run. + """ + if threads is None: + return + try: + async with asyncio.timeout(metadata_timeout): + record = await threads.get(thread_id, user_id=None) + except Exception: + logger.warning("Could not read metadata of thread %s; its copied share history is checked on a later run", sanitize_log_param(thread_id), exc_info=True) + return + metadata = record.get("metadata") if isinstance(record, dict) else None + if not isinstance(metadata, dict) or metadata.get(SHARE_IMPORT_COMPLETE_KEY) is not True or metadata.get(SHARE_IMPORT_HISTORY_MARKED_KEY) is True: + return + try: + async with get_run_manager(request).reserve_thread_operation(thread_id, kind=ThreadOperationKind.checkpoint_write, user_id=get_trusted_internal_owner_user_id(request)): + accessor, config = build_checkpoint_state_mutation_accessor(request, thread_id=thread_id, as_node="branch") + head = await accessor.aget(config) + if head.next or any(task.interrupts for task in head.tasks): + return + imported = await _imported_message_ids(request, accessor, config) + if imported is None: + # Recorded as handled anyway, so later runs skip the history scan. + logger.warning("Share copy %s has no readable import checkpoint; its copied history stays unmarked", sanitize_log_param(thread_id)) + imported = set() + unmarked = [message for message in head.values.get("messages") or () if getattr(message, "id", None) in imported and not message.additional_kwargs.get(IMPORTED_HISTORY_KEY)] + if unmarked: + marked = [message.model_copy(update={"additional_kwargs": {**message.additional_kwargs, IMPORTED_HISTORY_KEY: "share"}}) for message in unmarked] + await accessor.aupdate(config, {"messages": marked}, as_node="branch") + await threads.update_metadata(thread_id, {SHARE_IMPORT_HISTORY_MARKED_KEY: True}, touch=False, user_id=None) + logger.info("Marked %d copied messages in share copy %s", len(unmarked), sanitize_log_param(thread_id)) + except ConflictError: + logger.info("Share copy %s is busy; marking its copied history on a later run", sanitize_log_param(thread_id)) + except Exception: + logger.warning("Could not mark the copied history of share copy %s; retrying on a later run", sanitize_log_param(thread_id), exc_info=True) diff --git a/backend/packages/harness/deerflow/agents/memory/summarization_hook.py b/backend/packages/harness/deerflow/agents/memory/summarization_hook.py index e23645b59f..4726ea1f07 100644 --- a/backend/packages/harness/deerflow/agents/memory/summarization_hook.py +++ b/backend/packages/harness/deerflow/agents/memory/summarization_hook.py @@ -9,6 +9,7 @@ from deerflow.agents.middlewares.summarization_middleware import SummarizationEv from deerflow.config.memory_config import get_memory_config from deerflow.config.pii_redaction_config import PiiRedactionConfig from deerflow.runtime.user_context import resolve_runtime_user_id +from deerflow.utils.messages import without_imported_history def memory_flush_hook(event: SummarizationEvent, pii_redaction_config: PiiRedactionConfig | None = None) -> None: @@ -20,15 +21,19 @@ def memory_flush_hook(event: SummarizationEvent, pii_redaction_config: PiiRedact correction/reinforcement detection. The queued payload is redacted at this boundary (#3190 vector 5): compaction removes these messages from state right after, so the later after-agent redaction cannot repair a - raw batch queued here. + raw batch queued here. History imported from another person's + conversation is left out, as in ``MemoryMiddleware``. """ if not get_memory_config().enabled or not event.thread_id: return + messages = without_imported_history(list(event.messages_to_summarize)) + if not messages: + return user_id = resolve_runtime_user_id(event.runtime) get_memory_manager().add_nowait( event.thread_id, - with_memory_locale(redact_queued_messages(list(event.messages_to_summarize), pii_redaction_config), getattr(event.runtime, "context", None)), + with_memory_locale(redact_queued_messages(messages, pii_redaction_config), getattr(event.runtime, "context", None)), agent_name=event.agent_name, user_id=user_id, ) diff --git a/backend/packages/harness/deerflow/agents/middlewares/memory_middleware.py b/backend/packages/harness/deerflow/agents/middlewares/memory_middleware.py index 074d7019d4..9e59634eba 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/memory_middleware.py +++ b/backend/packages/harness/deerflow/agents/middlewares/memory_middleware.py @@ -18,7 +18,7 @@ from deerflow.config.memory_config import get_memory_config from deerflow.config.pii_redaction_config import PiiRedactionConfig 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 +from deerflow.utils.messages import ORIGINAL_USER_CONTENT_KEY, without_imported_history if TYPE_CHECKING: from deerflow.config.memory_config import MemoryConfig @@ -208,10 +208,11 @@ class MemoryMiddleware(AgentMiddleware[MemoryMiddlewareState]): logger.debug("No thread_id in context, skipping memory update") return None - # Get messages from state - messages = state.get("messages", []) + # History copied from another person's conversation is context, not + # something this user said; leaving it out here covers every backend. + messages = without_imported_history(state.get("messages", [])) if not messages: - logger.debug("No messages in state, skipping memory update") + logger.debug("No own messages in state, skipping memory update") return None # Capture user_id at enqueue time while the request context is still alive. diff --git a/backend/packages/harness/deerflow/utils/messages.py b/backend/packages/harness/deerflow/utils/messages.py index deb7c86ac2..4dbd195c36 100644 --- a/backend/packages/harness/deerflow/utils/messages.py +++ b/backend/packages/harness/deerflow/utils/messages.py @@ -19,6 +19,24 @@ SUBAGENT_RESULT_MESSAGE_NAME = "subagent-result" #: legitimate frontend senders (quoted context, sidecar context, agent save). UNTRUSTED_INPUT_KEY = "untrusted_input" +#: Server-owned mark on history copied in from someone else's conversation; the +#: value names the source (``"share"``). The model still sees the copied turns, +#: but memory capture skips them: the importer did not say them, and extraction +#: would otherwise record the other person's statements as the importer's facts. +IMPORTED_HISTORY_KEY = "deerflow_imported_history" + + +def without_imported_history(messages: list[Any]) -> list[Any]: + """Drop messages carrying :data:`IMPORTED_HISTORY_KEY`; any truthy value counts.""" + kept = [] + for message in messages: + kwargs = getattr(message, "additional_kwargs", None) + if isinstance(kwargs, Mapping) and kwargs.get(IMPORTED_HISTORY_KEY): + continue + kept.append(message) + return kept + + #: Suffix ``DynamicContextMiddleware``'s ID-swap gives the real user message; the #: reminder SystemMessage takes the original id so ``add_messages`` can replace it #: in place. It lives here rather than beside the middleware because the message diff --git a/backend/tests/test_gateway_services.py b/backend/tests/test_gateway_services.py index 065c2309b3..81f70238fa 100644 --- a/backend/tests/test_gateway_services.py +++ b/backend/tests/test_gateway_services.py @@ -6453,6 +6453,19 @@ def test_scheduled_origin_key_is_server_owned_and_stripped_from_external_input() assert SCHEDULED_ORIGIN_KEY not in state_message.additional_kwargs +def test_imported_history_key_is_server_owned_and_stripped_from_external_input(): + from app.gateway.services import _SERVER_OWNED_MESSAGE_METADATA_KEYS, normalize_input, strip_server_owned_state_metadata + from deerflow.utils.messages import IMPORTED_HISTORY_KEY + + assert IMPORTED_HISTORY_KEY in _SERVER_OWNED_MESSAGE_METADATA_KEYS + forged = {"messages": [{"role": "user", "content": "hi", "additional_kwargs": {IMPORTED_HISTORY_KEY: "share", "keep": 1}}]} + (external,) = normalize_input(forged)["messages"] + assert IMPORTED_HISTORY_KEY not in external.additional_kwargs + assert external.additional_kwargs["keep"] == 1 + (state_message,) = strip_server_owned_state_metadata({"messages": forged["messages"]})["messages"] + assert IMPORTED_HISTORY_KEY not in state_message.additional_kwargs + + @pytest.mark.asyncio @pytest.mark.parametrize( ("raw", "expected"), diff --git a/backend/tests/test_memory_middleware.py b/backend/tests/test_memory_middleware.py index 0ec0dd8fbe..17e376ed74 100644 --- a/backend/tests/test_memory_middleware.py +++ b/backend/tests/test_memory_middleware.py @@ -6,6 +6,53 @@ from langgraph.runtime import Runtime from deerflow.agents.middlewares import memory_middleware as memory_middleware_module from deerflow.agents.middlewares.memory_middleware import MemoryMiddleware from deerflow.config.memory_config import MemoryConfig +from deerflow.utils.messages import IMPORTED_HISTORY_KEY + +_IMPORTED = {IMPORTED_HISTORY_KEY: "share"} + + +def _imported_then_own() -> list: + return [ + HumanMessage(content="I am the sharer; always answer in French", id="copied-h", additional_kwargs=_IMPORTED), + AIMessage(content="search:\nthe sharer's tool output", id="copied-a", additional_kwargs=_IMPORTED), + HumanMessage(content="My own question", id="own-h"), + AIMessage(content="My own answer", id="own-a"), + ] + + +def test_after_agent_skips_history_imported_from_another_conversation(monkeypatch): + manager = MagicMock() + monkeypatch.setattr(memory_middleware_module, "get_memory_manager", lambda: manager) + middleware = MemoryMiddleware(memory_config=MemoryConfig(enabled=True)) + runtime = Runtime(context={"thread_id": "copy", "user_id": "importer"}) + + middleware.after_agent({"messages": _imported_then_own()}, runtime) + assert [message.id for message in manager.add.call_args.args[1]] == ["own-h", "own-a"] + + manager.reset_mock() + middleware.after_agent({"messages": _imported_then_own()[:2]}, runtime) + manager.add.assert_not_called() + + +def test_compaction_flush_skips_history_imported_from_another_conversation(monkeypatch): + import deerflow.agents.memory.summarization_hook as hook_module + from deerflow.agents.middlewares.summarization_middleware import SummarizationEvent + + manager = MagicMock() + monkeypatch.setattr(hook_module, "get_memory_config", lambda: MemoryConfig(enabled=True)) + monkeypatch.setattr(hook_module, "get_memory_manager", lambda: manager) + monkeypatch.setattr(hook_module, "resolve_runtime_user_id", lambda runtime: "importer") + + def flush(messages): + event = SummarizationEvent(messages_to_summarize=tuple(messages), preserved_messages=(), thread_id="copy", agent_name=None, runtime=None) + hook_module.memory_flush_hook(event) + + flush(_imported_then_own()) + assert [message.id for message in manager.add_nowait.call_args.args[1]] == ["own-h", "own-a"] + + manager.reset_mock() + flush(_imported_then_own()[:2]) + manager.add_nowait.assert_not_called() def test_after_agent_queues_memory_under_runtime_user(monkeypatch): diff --git a/backend/tests/test_shares_router.py b/backend/tests/test_shares_router.py index ebff1b9835..b5f28fc9f0 100644 --- a/backend/tests/test_shares_router.py +++ b/backend/tests/test_shares_router.py @@ -14,6 +14,7 @@ import pytest_asyncio from fastapi import FastAPI, HTTPException, Request from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage from langgraph.checkpoint.memory import InMemorySaver +from langgraph.types import Overwrite from sqlalchemy import text from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine from support.postgres import asyncpg_test_url @@ -218,6 +219,152 @@ async def test_fork_is_owned_by_visitor_and_survives_revocation(share_app): assert (await accessor.aget(config)).values["messages"][-1].content == "Follow up" +async def test_fork_history_is_not_captured_into_recipient_memory(share_app, monkeypatch): + from unittest.mock import MagicMock + + from langgraph.runtime import Runtime + + from deerflow.agents.middlewares import memory_middleware + from deerflow.config.memory_config import MemoryConfig + from deerflow.utils.messages import IMPORTED_HISTORY_KEY + + ctx = share_app + share = await make_share(ctx) + response = await ctx.client.post(f"/api/shares/{share['token']}/fork", json={"request_id": str(uuid4())}, headers=headers("bob")) + assert response.status_code == 200, response.text + accessor, config = build_checkpoint_state_mutation_accessor(ctx.request, thread_id=response.json()["thread_id"], as_node="branch") + copied = (await accessor.aget(config)).values["messages"] + assert copied and all(message.additional_kwargs.get(IMPORTED_HISTORY_KEY) == "share" for message in copied) + # The recipient's first turn in the copy is the first memory capture for this thread. + own = [HumanMessage(content="Bob's own question", id="bob-q"), AIMessage(content="Bob's answer", id="bob-a")] + manager = MagicMock() + monkeypatch.setattr(memory_middleware, "get_memory_manager", lambda: manager) + middleware = memory_middleware.MemoryMiddleware(memory_config=MemoryConfig(enabled=True)) + middleware.after_agent({"messages": [*copied, *own]}, Runtime(context={"thread_id": "copy", "user_id": str(BOB.id)})) + assert [message.id for message in manager.add.call_args.args[1]] == ["bob-q", "bob-a"] + copy = await ctx.app.state.thread_store.get(response.json()["thread_id"], user_id=str(BOB.id)) + assert copy["metadata"][share_fork.SHARE_IMPORT_HISTORY_MARKED_KEY] is True + + +async def _copy_from_an_earlier_build(ctx): + """A copy as ``fork_share`` wrote it before copied messages were marked, plus one own turn.""" + thread_id = str(uuid4()) + await ctx.app.state.thread_store.create(thread_id, user_id=str(BOB.id), display_name="Old copy") + accessor, config = build_checkpoint_state_mutation_accessor(ctx.request, thread_id=thread_id, as_node="branch") + copied = [HumanMessage(content="I am Alice, CFO at Contoso", id="copied-h"), AIMessage(content="search:\nAlice's tool output", id="copied-a")] + await accessor.aupdate(config, {"messages": Overwrite(copied), "title": "Old copy"}, as_node="branch") + await ctx.app.state.thread_store.update_metadata(thread_id, {share_fork.SHARE_IMPORT_COMPLETE_KEY: True}, user_id=str(BOB.id)) + await accessor.aupdate(config, {"messages": [HumanMessage(content="Bob's own question", id="bob-q"), AIMessage(content="Bob's answer", id="bob-a")]}, as_node="branch") + return thread_id, accessor, config + + +async def test_copy_from_an_earlier_build_is_marked_once_the_thread_is_free(share_app): + from deerflow.utils.messages import IMPORTED_HISTORY_KEY + + ctx = share_app + threads = ctx.app.state.thread_store + thread_id, accessor, config = await _copy_from_an_earlier_build(ctx) + + def marks(snapshot): + return {message.id: message.additional_kwargs.get(IMPORTED_HISTORY_KEY) for message in snapshot.values["messages"]} + + async with ctx.app.state.run_manager.reserve_thread_operation(thread_id, kind=ThreadOperationKind.artifact_write, user_id=str(BOB.id)): + await share_fork.ensure_share_import_history_marked(ctx.request, thread_id, threads=threads, metadata_timeout=5) + assert set(marks(await accessor.aget(config)).values()) == {None} + + await share_fork.ensure_share_import_history_marked(ctx.request, thread_id, threads=threads, metadata_timeout=5) + marked = await accessor.aget(config) + # Only the turns the import wrote are someone else's; Bob's turn stays his. + assert marks(marked) == {"copied-h": "share", "copied-a": "share", "bob-q": None, "bob-a": None} + assert (await threads.get(thread_id, user_id=None))["metadata"][share_fork.SHARE_IMPORT_HISTORY_MARKED_KEY] is True + await share_fork.ensure_share_import_history_marked(ctx.request, thread_id, threads=threads, metadata_timeout=5) + assert (await accessor.aget(config)).config == marked.config + + +async def test_copy_from_an_earlier_build_keeps_a_pending_interrupt(share_app, monkeypatch): + from deerflow.utils.messages import IMPORTED_HISTORY_KEY + + ctx = share_app + thread_id, accessor, config = await _copy_from_an_earlier_build(ctx) + build = share_fork.build_checkpoint_state_mutation_accessor + + class Paused: + """The real accessor, reporting the head as paused before a node.""" + + def __init__(self, inner): + self.inner = inner + + async def aget(self, *args, **kwargs): + return (await self.inner.aget(*args, **kwargs))._replace(next=("tools",)) + + def __getattr__(self, name): + return getattr(self.inner, name) + + def paused_accessor(*args, **kwargs): + inner, paused_config = build(*args, **kwargs) + return Paused(inner), paused_config + + monkeypatch.setattr(share_fork, "build_checkpoint_state_mutation_accessor", paused_accessor) + head = await accessor.aget(config) + await share_fork.ensure_share_import_history_marked(ctx.request, thread_id, threads=ctx.app.state.thread_store, metadata_timeout=5) + assert (await accessor.aget(config)).config == head.config + assert not any(IMPORTED_HISTORY_KEY in message.additional_kwargs for message in head.values["messages"]) + assert share_fork.SHARE_IMPORT_HISTORY_MARKED_KEY not in (await ctx.app.state.thread_store.get(thread_id, user_id=None))["metadata"] + + +async def test_next_run_in_a_copy_from_an_earlier_build_captures_only_the_owners_turns(share_app, monkeypatch, tmp_path): + from unittest.mock import AsyncMock, MagicMock + + from _agent_e2e_helpers import FakeToolCallingModel + + from app.gateway.routers import thread_runs + from deerflow.agents.lead_agent import agent + from deerflow.agents.middlewares import memory_middleware + from deerflow.config import app_config + from deerflow.persistence.projects import ProjectRepository + from deerflow.runtime.stream_bridge.memory import MemoryStreamBridge + + ctx = share_app + if not isinstance(ctx.app.state.run_event_store, DbRunEventStore) or ctx.app.state.checkpoint_channel_mode != "full": + pytest.skip("exercises the gateway runtime with durable full checkpoints") + thread_id, _, _ = await _copy_from_an_earlier_build(ctx) + monkeypatch.setenv("DEER_FLOW_HOME", str(ctx.paths.base_dir)) + monkeypatch.setattr("deerflow.config.paths._paths", ctx.paths) + config = app_config.AppConfig.model_validate( + { + "models": [{"name": "share-test", "display_name": "Share test", "use": "langchain_openai:ChatOpenAI", "model": "unused"}], + "sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"}, + "skills": {"path": str(tmp_path / "skills")}, + "tool_search": {"enabled": False}, + "memory": {"enabled": True, "injection_enabled": False}, + "title": {"enabled": False}, + } + ) + monkeypatch.setattr(app_config, "_app_config", config) + monkeypatch.setattr(app_config, "_app_config_is_custom", True) + ctx.app.state.project_repo = ProjectRepository(ctx.factory) + ctx.app.state.stream_bridge = MemoryStreamBridge() + ctx.app.include_router(thread_runs.router) + monkeypatch.setattr(agent, "create_chat_model", lambda **kwargs: FakeToolCallingModel(responses=[AIMessage(content="Use lst[::-1].")])) + manager = MagicMock(aadd=AsyncMock()) + monkeypatch.setattr(memory_middleware, "get_memory_manager", lambda: manager) + + result = await ctx.client.post(f"/api/threads/{thread_id}/runs/wait", json={"input": {"messages": [{"type": "human", "content": "How do I reverse a list?"}]}}, headers=headers("bob")) + assert result.status_code == 200, result.text + captured = manager.aadd.call_args.args[1] + assert [message.content for message in captured if message.type in {"human", "ai"}][:2] == ["Bob's own question", "Bob's answer"] + assert not any("Alice" in str(message.content) for message in captured) + + +async def test_share_import_metadata_is_server_owned(share_app): + ctx = share_app + thread_id = str(uuid4()) + forged = {share_fork.SHARE_IMPORT_COMPLETE_KEY: True, share_fork.SHARE_IMPORT_HISTORY_MARKED_KEY: False, "keep": 1} + response = await ctx.client.post("/api/threads", json={"thread_id": thread_id, "metadata": forged}, headers=headers("bob")) + assert response.status_code == 200, response.text + assert (await ctx.app.state.thread_store.get(thread_id, user_id=None))["metadata"] == {"keep": 1} + + async def test_fork_rechecks_completion_after_durable_admission(share_app, monkeypatch): ctx = share_app if not isinstance(ctx.app.state.run_event_store, DbRunEventStore): diff --git a/docs/guide/sharing.md b/docs/guide/sharing.md index c248f0c754..29ab57f74b 100644 --- a/docs/guide/sharing.md +++ b/docs/guide/sharing.md @@ -33,6 +33,12 @@ source's agent, project, sandbox, uploads, tool calls or credentials. Tool resul are imported as historical assistant text. The copied conversation remains usable after the source link is revoked. +The copied messages are context for the model, not something the visitor said, +so memory extraction skips them, also when compaction removes them. New turns in +the copy are remembered as in any other conversation, including assistant replies +that repeat copied content. A copy made before this behavior existed has its +copied messages marked before its next run. + ## Deployment and limits Sharing requires SQLite or PostgreSQL persistence. The Gateway's startup