mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-09-21 12:06:18 +00:00
* feat(projects): project workspaces with scoped chats and thread membership
Backend:
- projects table model and migration; fail-closed ProjectRepository with
ownership checks, CRUD/archive/restore/delete router, and atomic thread
move between projects
- threads_meta.project_id column exposed as reserved deerflow_project_id
metadata; project-aware thread create/search with pagination bounds and
membership echoed in create responses
- first-run admission assigns the project only at genuine first run, seeded
at write time and dropped when invalid; serialized against project
deletion and thread assignment
- branch creation inherits the source thread's project membership (an
archived/deleted project degrades the branch to unassigned instead of
failing the request)
Frontend:
- projects data layer, thread move API, and sidebar projects section with
flat/grouped modes, archived-project threads, and stable virtual-list
offsets
- project detail page with project-scoped new chat
(/workspace/chats/new?project=) and paginated thread list
- move-to-project thread menu, new-project dialog, archived-project gates
- project-scoped new chats pre-create the thread with membership before the
first submit or /goal set, so runs never proceed outside the project
- goal-set preparation is fenced against conversation switches: a stale
continuation is dropped instead of saving the goal or launching the
abandoned submission on the newly opened conversation
- project thread lists join thread lifecycle invalidations (stop, pin) so
an open project page never keeps stale titles, recency, or pagination
* fix(chats): keep archive undo toast when the sidebar row unmounts
The archive success toast was fired from per-mutate callbacks passed to
mutation.mutate. React Query drops those handlers when the observer
component unmounts before the mutation settles; archiving the open chat
removes its sidebar row mid-flight, so the undo toast never appeared and
the e2e archive-undo test timed out waiting for it.
Move the success/error handlers to the mutation level (useArchiveThread
options, same pattern as useMoveThreadToProject) where callbacks are
delivered even after the originating row unmounts.
* fix(projects): pin project thread listing contract and exclude archived chats
GET /api/projects/{id}/threads returned the thread store row verbatim
(list[dict], no response_model): user_id/assistant_id leaked, any future
ThreadMetaRow column would auto-leak, and the OpenAPI schema was empty.
Return a narrow ProjectThreadResponse (the exact fields ProjectThread
declares) with the same metadata secret redaction the surrounding thread
endpoints get from _MetadataRedactingResponse.
The listing also ran search() without the archived filter, so a retired
chat rendered as a normal row on the project page while the sidebar hid
it. Search archived=False to mirror the sidebar's archived:false lists;
restore stays on the global Archived tab.
Both regressions pinned by new router tests: wire-shape allowlist and
archived-member exclusion.
* docs(migrations): record the 0019/0020 chain against the bootstrap reservation
The tree now chains 0018 -> 0019_projects -> 0020_threads_meta_project_id,
so migrations/AGENTS.md was stale twice over: the revision index stopped at
0018 and the rolling-forward section still claimed the tree 'deliberately
remains at 0018'.
Document the new head and record the intentional numeric-prefix reuse of
0019: 0019_projects is in-chain while 0019_thread_incarnations stays the
reserved, allowlisted out-of-tree rollout id. The owning rollout revision
must re-parent onto this tree's head when it merges so alembic never sees
two heads off 0018; bootstrap.py now cross-references that note next to
_FORWARD_COMPATIBLE_REVISION.
* fix(chats): invalidate project thread lists on archive/restore
useArchiveThread refreshed the infinite sidebar cache, threads/search and
the per-thread metadata cache but not the project-scoped list
([...PROJECTS_QUERY_KEY, 'threads', id]) this PR adds — the one thread
mutation not wired to that key, after usePinThread, useRenameThread,
useDeleteThread, useMoveThreadToProject and invalidateStoppedThreadCaches.
An archive from a sidebar row while a project page is open therefore left
the archived chat rendered as a normal row until remount (and undo left it
missing). Invalidate the prefix in the mutation-level success handler.
Regression test asserts the project-list prefix is invalidated on success.
* fix(projects): fetch project discovery only in grouped sidebar mode
RecentChatList mounted two useProjects queries per sidebar render, but
knownProjectIds is consumed only by the grouped-mode exclusion filter; in
the default flat mode every page load paid two GET /api/projects?status=
round trips for data nothing read. Gate both queries on grouped mode —
GroupedProjectList fetches the same keys when the toggle is on and
TanStack dedupes the observers.
Also set retry: false on useProject: a deleted or foreign project 404s
deterministically, and the page renders a dedicated not-found state for
it, so the default 1s/2s/4s retry backoff kept deep links in 'loading'
for ~7s before that state appeared. Matches useThreadMetadata /
useThreadTokenUsage.
* fix(threads): fail closed on project-scoped create in memory mode
MemoryThreadMetaStore.create accepted project_id and silently ignored it,
making memory mode the one membership path that fails open: POST
/api/threads with a project id returned 200 and the run started
unassigned, violating the invariant that a run never proceeds outside the
selected project (the SQL store raises ProjectNotAssignableError inside
the insert transaction for the same request).
Raise ProjectNotAssignableError whenever project_id is present so the
router's existing 404 mapping applies, the frontend keeps the composer
text for a retry, and memory mode behaves exactly like SQL mode.
set_project already reports rejection; create now matches it.
Store-level test (raises, nothing persisted, project filter stays empty,
unscoped creates still work) plus a router-level test asserting the 404
and that no row is left behind.
* fix(projects): window the project page thread list
ProjectThreadsSection rendered every loaded page as a plain Link row, so a
long-lived project accumulated unbounded DOM on the page's scroll surface:
each load-more appended another 100 rows and every formatTimeAgo tick
re-rendered the whole list.
Reuse VirtualThreadList (now generic over any row shape with a
thread_id), pointing its scroll parent at this page's ScrollArea viewport
via the shared [data-slot="scroll-area-viewport"] selector used by
/workspace/chats; under the 60-row threshold it falls back to the plain
render, so small projects are unchanged.
* fix(projects): restore row dividers and pin them with a render test
The row class template literal concatenated transition-colors directly
with the conditional border-b token, so non-final rows rendered the
invalid class 'transition-colorsborder-b' and lost both the divider and
the transition. Compose the row classes with cn() and a boolean guard
instead.
The section moved out of page.tsx into a testable component so the row
markup finally has coverage: a DOM test asserts every row except the
final data row carries border-b (index-based, not last: — correct under
virtualization where the last mounted row is not the last data row), and
the untitled fallback plus load-more button render for a partial page.
* fix(projects): validate forward schemas and fence membership reads
221 lines
9.2 KiB
Python
221 lines
9.2 KiB
Python
"""In-memory ThreadMetaStore backed by LangGraph BaseStore.
|
|
|
|
Used when database.backend=memory. Delegates to the LangGraph Store's
|
|
``("threads",)`` namespace — the same namespace used by the Gateway
|
|
router for thread records.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
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, _ProjectFilterUnset
|
|
from deerflow.runtime.user_context import AUTO, _AutoSentinel, resolve_user_id
|
|
from deerflow.utils.time import coerce_iso, now_iso
|
|
|
|
THREADS_NS: tuple[str, ...] = ("threads",)
|
|
SEARCH_PAGE_SIZE = 500
|
|
|
|
|
|
class MemoryThreadMetaStore(ThreadMetaStore):
|
|
def __init__(self, store: BaseStore) -> None:
|
|
self._store = store
|
|
|
|
async def _get_owned_record(
|
|
self,
|
|
thread_id: str,
|
|
user_id: str | None | _AutoSentinel,
|
|
method_name: str,
|
|
) -> dict | None:
|
|
"""Fetch a record and verify ownership. Returns a mutable copy, or None."""
|
|
resolved = resolve_user_id(user_id, method_name=method_name)
|
|
item = await self._store.aget(THREADS_NS, thread_id)
|
|
if item is None:
|
|
return None
|
|
record = dict(item.value)
|
|
if resolved is not None and record.get("user_id") != resolved:
|
|
return None
|
|
return record
|
|
|
|
async def create(
|
|
self,
|
|
thread_id: str,
|
|
*,
|
|
assistant_id: str | None = None,
|
|
user_id: str | None | _AutoSentinel = AUTO,
|
|
display_name: str | None = None,
|
|
metadata: dict | None = None,
|
|
project_id: str | 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
|
|
# create carrying ``project_id`` raises ``ProjectNotAssignableError``
|
|
# (the router maps it to 404) instead of silently persisting an
|
|
# unassigned thread that a run would then proceed under. Mirrors
|
|
# ``set_project`` below, which already reports rejection.
|
|
if project_id is not None:
|
|
from deerflow.persistence.projects import ProjectNotAssignableError
|
|
|
|
raise ProjectNotAssignableError(project_id)
|
|
resolved_user_id = resolve_user_id(user_id, method_name="MemoryThreadMetaStore.create")
|
|
now = now_iso()
|
|
record: dict[str, Any] = {
|
|
"thread_id": thread_id,
|
|
"assistant_id": assistant_id,
|
|
"user_id": resolved_user_id,
|
|
"display_name": display_name,
|
|
"status": "idle",
|
|
"metadata": metadata or {},
|
|
"values": {},
|
|
"created_at": now,
|
|
"updated_at": now,
|
|
}
|
|
await self._store.aput(THREADS_NS, thread_id, record)
|
|
return record
|
|
|
|
async def set_project(self, thread_id: str, project_id: str | None, *, user_id: str | None | _AutoSentinel = AUTO) -> bool:
|
|
# Memory mode has no projects backend in Phase 1: membership moves
|
|
# are unsupported and always report rejection.
|
|
return False
|
|
|
|
async def get(self, thread_id: str, *, user_id: str | None | _AutoSentinel = AUTO) -> dict | None:
|
|
return await self._get_owned_record(thread_id, user_id, "MemoryThreadMetaStore.get")
|
|
|
|
async def search(
|
|
self,
|
|
*,
|
|
metadata: dict[str, Any] | None = None,
|
|
status: str | None = None,
|
|
archived: bool | None = None,
|
|
project_id: str | None | _ProjectFilterUnset = PROJECT_FILTER_UNSET,
|
|
limit: int = 100,
|
|
offset: int = 0,
|
|
user_id: str | None | _AutoSentinel = AUTO,
|
|
) -> list[dict[str, Any]]:
|
|
"""Search threads by materializing matches, then sorting in Python.
|
|
|
|
The memory backend loads all matching rows in chunks before slicing so
|
|
it can mirror SQL's pinned-first ordering. Use the SQL store for
|
|
scalable paginated I/O.
|
|
"""
|
|
resolved_user_id = resolve_user_id(user_id, method_name="MemoryThreadMetaStore.search")
|
|
if not isinstance(project_id, _ProjectFilterUnset) and project_id is not None:
|
|
# Memory mode has no projects backend: no thread can be a member.
|
|
return []
|
|
filter_dict: dict[str, Any] = {}
|
|
if status:
|
|
filter_dict["status"] = status
|
|
if resolved_user_id is not None:
|
|
filter_dict["user_id"] = resolved_user_id
|
|
|
|
items = []
|
|
search_offset = 0
|
|
while True:
|
|
page = await self._store.asearch(
|
|
THREADS_NS,
|
|
filter=filter_dict or None,
|
|
limit=SEARCH_PAGE_SIZE,
|
|
offset=search_offset,
|
|
)
|
|
if not page:
|
|
break
|
|
items.extend(page)
|
|
if len(page) < SEARCH_PAGE_SIZE:
|
|
break
|
|
search_offset += len(page)
|
|
|
|
records = [self._item_to_dict(item) for item in items]
|
|
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:
|
|
records = [record for record in records if ((record.get("metadata") or {}).get(THREAD_ARCHIVED_METADATA_KEY) is True) == archived]
|
|
records.sort(key=self._sort_key, reverse=True)
|
|
return records[offset : offset + limit]
|
|
|
|
async def check_access(self, thread_id: str, user_id: str, *, require_existing: bool = False) -> bool:
|
|
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")
|
|
if record_user_id is None:
|
|
return True
|
|
return record_user_id == user_id
|
|
|
|
async def update_display_name(
|
|
self,
|
|
thread_id: str,
|
|
display_name: str,
|
|
*,
|
|
remove_metadata_keys: tuple[str, ...] = (),
|
|
user_id: str | None | _AutoSentinel = AUTO,
|
|
) -> None:
|
|
record = await self._get_owned_record(thread_id, user_id, "MemoryThreadMetaStore.update_display_name")
|
|
if record is None:
|
|
return
|
|
record["display_name"] = display_name
|
|
metadata = dict(record.get("metadata") or {})
|
|
for key in remove_metadata_keys:
|
|
metadata.pop(key, None)
|
|
record["metadata"] = metadata
|
|
record["updated_at"] = now_iso()
|
|
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:
|
|
record = await self._get_owned_record(thread_id, user_id, "MemoryThreadMetaStore.update_status")
|
|
if record is None:
|
|
return
|
|
record["status"] = status
|
|
record["updated_at"] = now_iso()
|
|
await self._store.aput(THREADS_NS, thread_id, record)
|
|
|
|
async def update_metadata(self, thread_id: str, metadata: dict, *, touch: bool = True, user_id: str | None | _AutoSentinel = AUTO) -> None:
|
|
record = await self._get_owned_record(thread_id, user_id, "MemoryThreadMetaStore.update_metadata")
|
|
if record is None:
|
|
return
|
|
merged = dict(record.get("metadata") or {})
|
|
merged.update(metadata)
|
|
record["metadata"] = merged
|
|
if touch:
|
|
record["updated_at"] = now_iso()
|
|
await self._store.aput(THREADS_NS, thread_id, record)
|
|
|
|
async def update_owner(self, thread_id: str, owner_user_id: str, *, user_id: str | None | _AutoSentinel = AUTO) -> None:
|
|
record = await self._get_owned_record(thread_id, user_id, "MemoryThreadMetaStore.update_owner")
|
|
if record is None:
|
|
return
|
|
record["user_id"] = owner_user_id
|
|
record["updated_at"] = now_iso()
|
|
await self._store.aput(THREADS_NS, thread_id, record)
|
|
|
|
async def delete(self, thread_id: str, *, user_id: str | None | _AutoSentinel = AUTO) -> None:
|
|
record = await self._get_owned_record(thread_id, user_id, "MemoryThreadMetaStore.delete")
|
|
if record is None:
|
|
return
|
|
await self._store.adelete(THREADS_NS, thread_id)
|
|
|
|
@staticmethod
|
|
def _item_to_dict(item) -> dict[str, Any]:
|
|
"""Convert a Store SearchItem to the dict format expected by callers."""
|
|
val = item.value
|
|
return {
|
|
"thread_id": item.key,
|
|
"assistant_id": val.get("assistant_id"),
|
|
"user_id": val.get("user_id"),
|
|
"display_name": val.get("display_name"),
|
|
"status": val.get("status", "idle"),
|
|
"metadata": val.get("metadata", {}),
|
|
# ``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", "")),
|
|
"updated_at": coerce_iso(val.get("updated_at", "")),
|
|
}
|
|
|
|
@staticmethod
|
|
def _sort_key(record: dict[str, Any]) -> tuple[bool, str, str]:
|
|
metadata = record.get("metadata")
|
|
pinned = isinstance(metadata, dict) and metadata.get(THREAD_PINNED_METADATA_KEY) is True
|
|
return (pinned, str(record.get("updated_at") or ""), str(record.get("thread_id") or ""))
|