Skip to content

Build and run agents you can see, understand and trust.

refactor(app): a session's origin is one tagged union (#2536)

DavdGao0b2c47a63430
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index 83b4a5f6b..b3be4719f 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -111,7 +111,20 @@ export interface AgentSchemaV2Response {
// ─── Session ──────────────────────────────────────────────────────────────────
-export type SessionSource = 'user' | 'schedule' | 'channel';
+/** How a session came to exist — fixed when it is created. */
+export type SessionOrigin =
+ | { type: 'user' }
+ | { type: 'schedule'; schedule_id: string }
+ | {
+ type: 'channel';
+ channel_id: string;
+ chat_id: string;
+ chat_name: string | null;
+ }
+ | { type: 'team' };
+
+/** The tag of a {@link SessionOrigin}. */
+export type SessionSourceKind = SessionOrigin['type'];
export interface SessionConfig {
name: string;
@@ -139,9 +152,7 @@ export type AgentState = Record<string, unknown>;
export interface SessionRecord extends RecordBase {
user_id: string;
agent_id: string;
- source: SessionSource;
- source_schedule_id: string | null;
- source_channel_id: string | null;
+ origin: SessionOrigin;
/**
* The team this session participates in, if any. Set when the
* session is the leader of a team (the session that called
diff --git a/examples/web_ui/frontend/src/pages/chat/index.tsx b/examples/web_ui/frontend/src/pages/chat/index.tsx
index c5a302301..045fc22e7 100644
--- a/examples/web_ui/frontend/src/pages/chat/index.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/index.tsx
@@ -10,12 +10,13 @@ import {
Plus,
Settings2,
Trash2,
+ Users,
} from 'lucide-react';
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { ChatViewport } from './ChatViewport';
-import type { SessionRecord, SessionSource } from '@/api';
+import type { SessionRecord, SessionSourceKind } from '@/api';
import { AgentDialog } from '@/components/dialog/AgentDialog';
import { DeleteDialog } from '@/components/dialog/DeleteDialog';
import { EditAgentDialog } from '@/components/dialog/EditAgentDialog';
@@ -77,10 +78,11 @@ import { useTranslation } from '@/i18n/useI18n.ts';
* @returns The chat page JSX.
*/
// Icon per session origin, shown only when a sidebar mixes sources.
-const SOURCE_ICON: Record<SessionSource, LucideIcon> = {
+const SOURCE_ICON: Record<SessionSourceKind, LucideIcon> = {
user: BotMessageSquare,
schedule: CalendarClock,
channel: Cable,
+ team: Users,
};
/** localStorage keys holding the last (agent, session) the user viewed. */
@@ -120,7 +122,7 @@ const ChatPageInner = () => {
const currentView = sessions.find((v) => v.session.id === urlSessionId) ?? null;
// Show a per-origin icon only when sessions actually mix sources —
// a uniform list needs no disambiguation.
- const showSourceIcons = new Set(sessions.map((v) => v.session.source)).size > 1;
+ const showSourceIcons = new Set(sessions.map((v) => v.session.origin.type)).size > 1;
// "Inner focus" — when the URL carries a third `:memberId` segment
// the user is drilling into a team member's chat. The main sidebar
@@ -334,7 +336,7 @@ const ChatPageInner = () => {
{todaySessions.map((view) => {
const session = view.session;
const SourceIcon =
- SOURCE_ICON[session.source] ??
+ SOURCE_ICON[session.origin.type] ??
BotMessageSquare;
return (
<SidebarMenuItem key={session.id}>
@@ -426,7 +428,7 @@ const ChatPageInner = () => {
{earlierSessions.map((view) => {
const session = view.session;
const SourceIcon =
- SOURCE_ICON[session.source] ??
+ SOURCE_ICON[session.origin.type] ??
BotMessageSquare;
return (
<SidebarMenuItem key={session.id}>
diff --git a/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py b/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py
index 8ff3639e7..7648f52a8 100644
--- a/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py
+++ b/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py
@@ -23,7 +23,7 @@ from ...storage import (
ScheduleRecord,
ChatModelConfig,
SessionConfig,
- SessionSource,
+ ScheduleOrigin,
)
if TYPE_CHECKING:
@@ -236,8 +236,7 @@ class SchedulerManager:
config=session_config,
state=state,
session_id=stateful_session_id,
- source=SessionSource.SCHEDULE,
- source_schedule_id=record.id,
+ origin=ScheduleOrigin(schedule_id=record.id),
)
else:
logger.info(
@@ -272,8 +271,7 @@ class SchedulerManager:
chat_model_config=record.data.chat_model_config,
),
state=state,
- source=SessionSource.SCHEDULE,
- source_schedule_id=record.id,
+ origin=ScheduleOrigin(schedule_id=record.id),
)
logger.info(
diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.py
index 85a619082..cf060a3ba 100644
--- a/src/agentscope/app/_service/_chat.py
+++ b/src/agentscope/app/_service/_chat.py
@@ -36,7 +36,7 @@ from ..storage import (
AgentRecord,
SessionNaming,
SessionRecord,
- SessionSource,
+ ChannelOrigin,
)
from ..storage._utils import _resolve_team_leader
from .._manager import BackgroundTaskManager, SchedulerManager
@@ -898,9 +898,9 @@ class ChatService:
# -------------------------------------------------------------
channel = (
await self._channel_clients.get(
- session_record.source_channel_id,
+ session_record.origin.channel_id,
)
- if session_record.source_channel_id
+ if isinstance(session_record.origin, ChannelOrigin)
and self._channel_clients is not None
else None
)
@@ -1066,10 +1066,10 @@ class ChatService:
# Channel-bound sessions: tell the agent which chat it serves.
if channel is not None:
tools = ", ".join(t.name for t in channel_tools)
- chat_id = session_record.source_chat_id or ""
+ chat_id = session_record.origin.chat_id
kind = await channel.chat_kind(chat_id)
name = (
- session_record.source_chat_name
+ session_record.origin.chat_name
or await channel.chat_name(chat_id)
)
where = f' named "{name}"' if name else ""
@@ -1147,15 +1147,13 @@ class ChatService:
# channel's connection. Covers scheduled / background wakes,
# not just inbound channel messages.
if (
- session_record.source == SessionSource.CHANNEL
- and session_record.source_channel_id
- and session_record.source_chat_id
+ isinstance(session_record.origin, ChannelOrigin)
and self._channel_clients is not None
):
await self._channel_clients.deliver(
session_id=session_id,
- channel_id=session_record.source_channel_id,
- chat_id=session_record.source_chat_id,
+ channel_id=session_record.origin.channel_id,
+ chat_id=session_record.origin.chat_id,
agent_id=agent_id,
)
reply_msg: Msg | None = None
diff --git a/src/agentscope/app/_tool/_agent_create.py b/src/agentscope/app/_tool/_agent_create.py
index 98f83edab..9a25bfc7f 100644
--- a/src/agentscope/app/_tool/_agent_create.py
+++ b/src/agentscope/app/_tool/_agent_create.py
@@ -11,7 +11,13 @@ from pydantic import Field
from ._team_tool_base import _TeamToolBase
from .._types import SubAgentTemplate
from .._bus_ops import deliver_to_inbox
-from ..storage import AgentData, AgentRecord, SessionConfig, TeamMember
+from ..storage import (
+ AgentData,
+ AgentRecord,
+ SessionConfig,
+ TeamMember,
+ TeamOrigin,
+)
from ..storage._utils import _ensure_team_members, _resolve_team_leader
from ...message import HintBlock, TextBlock, ToolResultState
from ...permission import PermissionContext
@@ -448,6 +454,7 @@ optional):
),
),
state=worker_state,
+ origin=TeamOrigin(),
)
await self._storage.set_session_team_id(
self._user_id,
diff --git a/src/agentscope/app/_tool/_agent_invite.py b/src/agentscope/app/_tool/_agent_invite.py
index 3691da8f1..251d9f636 100644
--- a/src/agentscope/app/_tool/_agent_invite.py
+++ b/src/agentscope/app/_tool/_agent_invite.py
@@ -25,7 +25,7 @@ from pydantic import Field
from ._constants import HANDLE_LEN
from ._team_tool_base import _TeamToolBase
from .._bus_ops import deliver_to_inbox
-from ..storage import SessionConfig, TeamMember
+from ..storage import SessionConfig, TeamMember, TeamOrigin
from ..storage._utils import _ensure_team_members, _resolve_team_leader
from ...message import HintBlock, TextBlock, ToolResultState
from ...state import AgentState
@@ -391,6 +391,7 @@ class AgentInvite(_TeamToolBase):
fallback_chat_model_config=borrowed_fallback_model,
),
state=worker_state,
+ origin=TeamOrigin(),
)
await self._storage.set_session_team_id(
self._user_id,
diff --git a/src/agentscope/app/channel/_gateway.py b/src/agentscope/app/channel/_gateway.py
index f9567970a..fa651ddb9 100644
--- a/src/agentscope/app/channel/_gateway.py
+++ b/src/agentscope/app/channel/_gateway.py
@@ -29,7 +29,7 @@ from ..storage import (
ChatModelConfig,
SessionConfig,
SessionScope,
- SessionSource,
+ ChannelOrigin,
StorageBase,
)
from ..workspace_manager import WorkspaceManagerBase
@@ -132,7 +132,12 @@ class ChannelGateway:
event.channel_id,
):
target = (session.agent_id, session.id)
- if target == guess or session.source_chat_id != event.chat_id:
+ chat_id = (
+ session.origin.chat_id
+ if isinstance(session.origin, ChannelOrigin)
+ else None
+ )
+ if target == guess or chat_id != event.chat_id:
continue
if await self._resume(record.user_id, target, event):
return
@@ -315,10 +320,11 @@ class ChannelGateway:
config=session_config,
state=initial_state,
session_id=session_id,
- source=SessionSource.CHANNEL,
- source_chat_id=event.chat_id,
- source_chat_name=event.chat_name or None,
- source_channel_id=record.id,
+ origin=ChannelOrigin(
+ channel_id=record.id,
+ chat_id=event.chat_id,
+ chat_name=event.chat_name or None,
+ ),
)
@staticmethod
diff --git a/src/agentscope/app/storage/__init__.py b/src/agentscope/app/storage/__init__.py
index b5b73c7c1..b1b8c76e8 100644
--- a/src/agentscope/app/storage/__init__.py
+++ b/src/agentscope/app/storage/__init__.py
@@ -22,12 +22,17 @@ from ._model import (
MCPRecord,
ScheduleData,
ScheduleRecord,
- ScheduleSource,
+ ScheduleOrigin,
SessionConfig,
SessionNaming,
SessionKnowledgeConfig,
SessionRecord,
+ SessionOrigin,
SessionSource,
+ UserOrigin,
+ ScheduleSource,
+ ChannelOrigin,
+ TeamOrigin,
SkillRecord,
ChatModelConfig,
TTSModelConfig,
@@ -91,7 +96,12 @@ __all__ = [
"SessionNaming",
"SessionKnowledgeConfig",
"SessionRecord",
+ "SessionOrigin",
"SessionSource",
+ "UserOrigin",
+ "ScheduleOrigin",
+ "ChannelOrigin",
+ "TeamOrigin",
"SkillRecord",
"ChatModelConfig",
"TTSModelConfig",
diff --git a/src/agentscope/app/storage/_base.py b/src/agentscope/app/storage/_base.py
index 3bc13af76..760a6b158 100644
--- a/src/agentscope/app/storage/_base.py
+++ b/src/agentscope/app/storage/_base.py
@@ -17,7 +17,7 @@ from ._model import (
ScheduleRecord,
SessionRecord,
SessionConfig,
- SessionSource,
+ SessionOrigin,
SkillRecord,
TeamRecord,
)
@@ -370,7 +370,8 @@ class StorageBase(ABC):
config: SessionConfig,
state: AgentState | None = None,
session_id: str | None = None,
- source: SessionSource = SessionSource.USER,
+ origin: SessionOrigin | None = None,
+ source: str | None = None,
source_schedule_id: str | None = None,
source_chat_id: str | None = None,
source_chat_name: str | None = None,
@@ -389,16 +390,14 @@ class StorageBase(ABC):
session_id (`str | None`, optional): If provided, update the
existing session with this id. If ``None``, create a new
session.
- source (`SessionSource`, optional): The source that created this
- session. Defaults to ``SessionSource.USER``.
- source_schedule_id (`str | None`, optional): The schedule that
- created this session. When set, the session is indexed under
- the schedule for execution history queries.
- source_chat_id (`str | None`, optional): The platform chat this
- session serves.
- source_chat_name (`str | None`, optional): That chat's title, as
- supplied by the inbound message.
- source_channel_id (`str | None`, optional): The owning channel.
+ origin (`SessionOrigin | None`, optional): How the session came
+ to exist — a :class:`ScheduleOrigin` also indexes it under
+ its schedule. Defaults to :class:`UserOrigin`.
+ source / source_schedule_id / source_chat_id /
+ source_chat_name / source_channel_id: **Deprecated** —
+ the flat shape ``origin`` replaced. Passing any of them
+ still builds the matching origin, so callers written
+ against the old signature keep working.
Returns:
`SessionRecord`: The created or updated record.
diff --git a/src/agentscope/app/storage/_model/__init__.py b/src/agentscope/app/storage/_model/__init__.py
index 823ed44c0..6d4227fb9 100644
--- a/src/agentscope/app/storage/_model/__init__.py
+++ b/src/agentscope/app/storage/_model/__init__.py
@@ -30,7 +30,12 @@ from ._session import (
ChatModelConfig,
TTSModelConfig,
EmbeddingModelConfig,
+ SessionOrigin,
SessionSource,
+ UserOrigin,
+ ScheduleOrigin,
+ ChannelOrigin,
+ TeamOrigin,
)
from ._skill import SkillRecord
from ._team import TeamRecord, TeamData, TeamMember
@@ -54,12 +59,17 @@ __all__ = [
"MCPRecord",
"ScheduleData",
"ScheduleRecord",
- "ScheduleSource",
+ "ScheduleOrigin",
"SessionConfig",
"SessionNaming",
"SessionKnowledgeConfig",
"SessionRecord",
+ "SessionOrigin",
"SessionSource",
+ "UserOrigin",
+ "ScheduleSource",
+ "ChannelOrigin",
+ "TeamOrigin",
"SkillRecord",
"ChatModelConfig",
"TTSModelConfig",
diff --git a/src/agentscope/app/storage/_model/_session.py b/src/agentscope/app/storage/_model/_session.py
index 78ba2ffc0..76192e219 100644
--- a/src/agentscope/app/storage/_model/_session.py
+++ b/src/agentscope/app/storage/_model/_session.py
@@ -1,22 +1,89 @@
# -*- coding: utf-8 -*-
"""The session data class for storage."""
+import warnings
from datetime import datetime
from enum import Enum
+from typing import Annotated, Any, Literal, Union
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, model_validator
+from typing_extensions import deprecated
from ._base import _RecordBase
from ....state import AgentState
class SessionSource(str, Enum):
- """The source that created the session."""
+ """The kinds a session's source used to come in.
+
+ Superseded by :data:`SessionOrigin`, whose tag carries the same
+ values. Kept importable, and comparable to
+ :attr:`SessionRecord.source`, so integrations pinned to the old name
+ keep working while they move.
+ """
USER = "user"
SCHEDULE = "schedule"
CHANNEL = "channel"
+class UserOrigin(BaseModel):
+ """A session a person opened themselves."""
+
+ type: Literal["user"] = "user"
+
+
+class ScheduleOrigin(BaseModel):
+ """A session a schedule opened on its due date."""
+
+ type: Literal["schedule"] = "schedule"
+
+ schedule_id: str
+ """The schedule that created it."""
+
+
+class ChannelOrigin(BaseModel):
+ """A session an inbound platform message opened."""
+
+ type: Literal["channel"] = "channel"
+
+ channel_id: str
+ """The owning channel. Lets the output forwarder locate the channel
+ adapter and its presentation settings on a background or scheduled
+ wake, where no inbound message is available to supply it."""
+
+ chat_id: str
+ """The platform chat this session maps to, so agent output can be
+ delivered back to the right place."""
+
+ chat_name: str | None = None
+ """That chat's title when the platform supplied one. Recorded
+ because the name arrives with the inbound message: a node that never
+ holds the connection cannot look it up."""
+
+
+class TeamOrigin(BaseModel):
+ """A session a team minted for one of its members.
+
+ Carries no team id on purpose. Which team a session belongs to is
+ :attr:`SessionRecord.team_id`, which every reader already uses and
+ which a session can also lose — this only records that a team is why
+ the session exists at all, which nothing could tell before.
+ """
+
+ type: Literal["team"] = "team"
+
+
+# How a session came to exist. Fixed when the session is created and
+# never rewritten, which is what separates it from
+# ``SessionRecord.team_id``: team membership is granted by a tool call
+# inside an existing session and can be revoked, so it is a field of its
+# own rather than a member of this union.
+SessionOrigin = Annotated[
+ Union[UserOrigin, ScheduleOrigin, ChannelOrigin, TeamOrigin],
+ Field(discriminator="type"),
+]
+
+
class ChatModelConfig(BaseModel):
"""The model configuration class."""
@@ -211,27 +278,17 @@ class SessionRecord(_RecordBase):
agent_id: str
"""The agent id."""
- source: SessionSource = SessionSource.USER
- """The source that created this session."""
-
- source_schedule_id: str | None = None
- """The source schedule Id."""
+ origin: SessionOrigin = Field(default_factory=UserOrigin)
+ """How this session came to exist.
- source_chat_id: str | None = None
- """For channel-created sessions, the platform chat this session maps
- to. Recorded so agent output can be delivered back to the right chat
- even on a background / scheduled wake, where no inbound message is
- available to supply it."""
+ A tagged union rather than a bare kind plus a row of nullable ids:
+ once the tag says ``channel`` the channel and chat ids are there,
+ and no reader has to ask whether the combination makes sense.
- source_chat_name: str | None = None
- """For channel-created sessions, that chat's title when the platform
- supplied one. Recorded because the name arrives with the inbound
- message: a node that never holds the connection cannot look it up."""
-
- source_channel_id: str | None = None
- """For channel-created sessions, the owning channel id. Lets the
- output forwarder locate the channel adapter + presentation settings
- on a background / scheduled wake."""
+ Named apart from the old ``source`` so that name could stay behind as
+ a deprecated property — a rename in place would have turned every
+ ``record.source == "user"`` into a silently false comparison.
+ """
team_id: str | None = None
"""The team this session participates in, if any.
@@ -244,5 +301,140 @@ class SessionRecord(_RecordBase):
config: SessionConfig
"""Session configuration (workspace, name, model)."""
+ @model_validator(mode="before")
+ @classmethod
+ def _fold_legacy_source(cls, data: Any) -> Any:
+ """Read rows written before :data:`SessionOrigin` existed.
+
+ Those carry a bare ``source`` string beside a set of nullable
+ ``source_*`` ids. Nothing migrates them in the database; they are
+ folded here and written back in the new shape on the next save.
+ """
+ if not isinstance(data, dict):
+ return data
+ if data.get("origin") is not None:
+ return data
+
+ data = dict(data)
+ kind = data.pop("source", None) or "user"
+ if not isinstance(kind, str):
+ # Built the old way but with a new value — ``source=`` was
+ # the field's name for long enough that callers still reach
+ # for it, and silently dropping one would leave the session
+ # claiming a user opened it.
+ data["origin"] = kind
+ return data
+ schedule_id = data.get("source_schedule_id")
+ channel_id = data.get("source_channel_id")
+ chat_id = data.get("source_chat_id")
+ # A tag carries its ids, so a legacy row missing them cannot be
+ # given one — manufacturing a blank id would let it past every
+ # guard the old nullable fields made callers write, and it would
+ # be indexed under the empty string as well.
+ if kind == "schedule" and schedule_id:
+ data["origin"] = {
+ "type": "schedule",
+ "schedule_id": schedule_id,
+ }
+ elif kind == "channel" and channel_id and chat_id:
+ data["origin"] = {
+ "type": "channel",
+ "channel_id": channel_id,
+ "chat_id": chat_id,
+ "chat_name": data.get("source_chat_name"),
+ }
+ elif kind in ("user", "team"):
+ data["origin"] = {"type": kind}
+ else:
+ data["origin"] = {"type": "user"}
+ for legacy in (
+ "source_schedule_id",
+ "source_channel_id",
+ "source_chat_id",
+ "source_chat_name",
+ ):
+ data.pop(legacy, None)
+ return data
+
+ @property
+ @deprecated("Use ``origin.type`` instead.")
+ def source(self) -> str:
+ """The origin's tag, under the name it used to have."""
+ return self.origin.type
+
+ @property
+ @deprecated("Use ``origin.schedule_id`` on a ``ScheduleOrigin``.")
+ def source_schedule_id(self) -> str | None:
+ """The schedule that created this session, if one did."""
+ return (
+ self.origin.schedule_id
+ if isinstance(self.origin, ScheduleOrigin)
+ else None
+ )
+
+ @property
+ @deprecated("Use ``origin.channel_id`` on a ``ChannelOrigin``.")
+ def source_channel_id(self) -> str | None:
+ """The owning channel, if an inbound message created this."""
+ return (
+ self.origin.channel_id
+ if isinstance(self.origin, ChannelOrigin)
+ else None
+ )
+
+ @property
+ @deprecated("Use ``origin.chat_id`` on a ``ChannelOrigin``.")
+ def source_chat_id(self) -> str | None:
+ """The platform chat this session serves, if any."""
+ return (
+ self.origin.chat_id
+ if isinstance(self.origin, ChannelOrigin)
+ else None
+ )
+
+ @property
+ @deprecated("Use ``origin.chat_name`` on a ``ChannelOrigin``.")
+ def source_chat_name(self) -> str | None:
+ """That chat's title, when the platform supplied one."""
+ return (
+ self.origin.chat_name
+ if isinstance(self.origin, ChannelOrigin)
+ else None
+ )
+
state: AgentState = Field(default_factory=AgentState)
"""Mutable runtime state, updated after each chat turn."""
+
+
+def _origin_kwargs(
+ origin: SessionOrigin | None,
+ source: str | None,
+ schedule_id: str | None,
+ channel_id: str | None,
+ chat_id: str | None,
+ chat_name: str | None,
+) -> dict:
+ """Build the ``SessionRecord`` keyword that says where a session came
+ from, accepting either the union or the flat arguments it replaced.
+
+ The flat ones are folded by the record's own legacy validator rather
+ than here, so both entry points agree on what an incomplete set
+ means.
+ """
+ if origin is not None:
+ return {"origin": origin}
+ if not any((source, schedule_id, channel_id, chat_id, chat_name)):
+ return {"origin": UserOrigin()}
+ warnings.warn(
+ "The flat source arguments are deprecated; pass ``origin`` with "
+ "a SessionOrigin instead.",
+ DeprecationWarning,
+ stacklevel=3,
+ )
+ return {
+ "source": source or "user",
+ "source_schedule_id": schedule_id,
+ "source_channel_id": channel_id,
+ "source_chat_id": chat_id,
+ "source_chat_name": chat_name,
+ }
diff --git a/src/agentscope/app/storage/_redis_storage.py b/src/agentscope/app/storage/_redis_storage.py
index d91276ce7..4115fadb1 100644
--- a/src/agentscope/app/storage/_redis_storage.py
+++ b/src/agentscope/app/storage/_redis_storage.py
@@ -9,6 +9,7 @@ from typing import Any, TYPE_CHECKING, Self
from pydantic import BaseModel
from ._base import StorageBase
+from ._model._session import _origin_kwargs
from ._model import (
AgentRecord,
ChannelRecord,
@@ -20,7 +21,9 @@ from ._model import (
ScheduleRecord,
SessionRecord,
SessionConfig,
- SessionSource,
+ ChannelOrigin,
+ ScheduleOrigin,
+ SessionOrigin,
SkillRecord,
TeamRecord,
)
@@ -872,7 +875,8 @@ class RedisStorage(StorageBase):
config: SessionConfig,
state: AgentState | None = None,
session_id: str | None = None,
- source: SessionSource = SessionSource.USER,
+ origin: SessionOrigin | None = None,
+ source: str | None = None,
source_schedule_id: str | None = None,
source_chat_id: str | None = None,
source_chat_name: str | None = None,
@@ -907,11 +911,14 @@ class RedisStorage(StorageBase):
user_id=user_id,
agent_id=agent_id,
config=config,
- source=source,
- source_schedule_id=source_schedule_id,
- source_chat_id=source_chat_id,
- source_chat_name=source_chat_name,
- source_channel_id=source_channel_id,
+ **_origin_kwargs(
+ origin,
+ source,
+ source_schedule_id,
+ source_channel_id,
+ source_chat_id,
+ source_chat_name,
+ ),
state=state if state is not None else AgentState(),
**new_id_kwargs,
)
@@ -928,19 +935,19 @@ class RedisStorage(StorageBase):
await self._set_with_ttl(key, record.model_dump_json())
await self._client.sadd(index_key, record.id)
- if source_schedule_id:
+ if isinstance(record.origin, ScheduleOrigin):
schedule_session_key = self._key(
self.key_config.schedule_session_index,
user_id=user_id,
- schedule_id=source_schedule_id,
+ schedule_id=record.origin.schedule_id,
)
await self._client.sadd(schedule_session_key, record.id)
- if source_channel_id:
+ if isinstance(record.origin, ChannelOrigin):
channel_session_key = self._key(
self.key_config.channel_session_index,
user_id=user_id,
- channel_id=source_channel_id,
+ channel_id=record.origin.channel_id,
)
await self._client.sadd(channel_session_key, record.id)
@@ -1099,19 +1106,19 @@ class RedisStorage(StorageBase):
await self._client.srem(index_key, session_id)
await self._client.delete(msg_key)
- if record.source_schedule_id:
+ if isinstance(record.origin, ScheduleOrigin):
schedule_session_key = self._key(
self.key_config.schedule_session_index,
user_id=user_id,
- schedule_id=record.source_schedule_id,
+ schedule_id=record.origin.schedule_id,
)
await self._client.srem(schedule_session_key, session_id)
- if record.source_channel_id:
+ if isinstance(record.origin, ChannelOrigin):
channel_session_key = self._key(
self.key_config.channel_session_index,
user_id=user_id,
- channel_id=record.source_channel_id,
+ channel_id=record.origin.channel_id,
)
await self._client.srem(channel_session_key, session_id)
diff --git a/src/agentscope/app/storage/_sql/_mappers.py b/src/agentscope/app/storage/_sql/_mappers.py
index bea8dac4a..6322c4f74 100644
--- a/src/agentscope/app/storage/_sql/_mappers.py
+++ b/src/agentscope/app/storage/_sql/_mappers.py
@@ -3,6 +3,12 @@
Round-trip contract (the "no duplication" invariant enforced here):
+Fields nested inside a record can also back a column, through
+``_index_paths``. Those are **copies** rather than the field's only
+home: the value stays in ``payload`` as well, because splitting a
+nested object across two places would leave neither half readable on
+its own. They exist to be queried and indexed, never to be read back.
+
- On write (``_from_record``) the record is dumped once with
``model_dump(mode="json")``, the envelope keys (``id`` /
``created_at`` / ``updated_at``) and every field listed in the
@@ -28,6 +34,17 @@ if TYPE_CHECKING:
R = TypeVar("R", bound=_RecordBase)
+
+def _walk(dump: dict, path: str) -> object | None:
+ """Follow a dotted path through a dumped record, or answer ``None``."""
+ cur: object = dump
+ for part in path.split("."):
+ if not isinstance(cur, dict):
+ return None
+ cur = cur.get(part)
+ return cur
+
+
# Envelope fields promoted by :class:`_JsonRecordMixin`; also popped
# from every record dump before it hits ``payload``.
_ENVELOPE_FIELDS = ("id", "created_at", "updated_at")
@@ -61,6 +78,8 @@ def _from_record(
column_values: dict = {}
for field in row_cls.get_indexed_fields():
column_values[field] = dump.pop(field, None)
+ for column, path in row_cls.get_index_paths().items():
+ column_values[column] = _walk(dump, path)
return row_cls(
id=record.id,
created_at=record.created_at,
@@ -97,4 +116,16 @@ def _to_record(
obj["updated_at"] = row.updated_at
for field in row.__class__.get_indexed_fields():
obj[field] = getattr(row, field)
+ paths = row.__class__.get_index_paths()
+ # Index columns are copies, so a row that already carries the nested
+ # value needs nothing. A row written before the nesting existed does
+ # not have it at all — there the columns ARE the values, restored
+ # under their old flat names for the record's own legacy validator
+ # to fold. Legacy-ness is decided once, from the payload as it
+ # arrived: deciding per column would let the first restored column
+ # make the rest look present.
+ roots = {p.split(".", 1)[0] for p in paths.values()}
+ if roots and not roots & obj.keys():
+ for column in paths:
+ obj[column] = getattr(row, column)
return record_cls.model_validate(obj)
diff --git a/src/agentscope/app/storage/_sql/_storage.py b/src/agentscope/app/storage/_sql/_storage.py
index e3e2cf276..a9697e096 100644
--- a/src/agentscope/app/storage/_sql/_storage.py
+++ b/src/agentscope/app/storage/_sql/_storage.py
@@ -20,6 +20,7 @@ from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any, Self
from .._base import StorageBase
+from .._model._session import _origin_kwargs
from .._model import (
AgentRecord,
ChannelRecord,
@@ -31,7 +32,7 @@ from .._model import (
ScheduleRecord,
SessionRecord,
SessionConfig,
- SessionSource,
+ SessionOrigin,
SkillRecord,
TeamRecord,
)
@@ -377,6 +378,7 @@ class AsyncSQLAlchemyStorage(StorageBase):
record.created_at = _to_naive_utc(record.created_at)
new_row = _from_record(row_cls, record)
indexed = tuple(row_cls.get_indexed_fields())
+ indexed += tuple(row_cls.get_index_paths())
values = {
col: getattr(new_row, col)
for col in ("id", "created_at", "updated_at", "payload") + indexed
@@ -1058,7 +1060,8 @@ class AsyncSQLAlchemyStorage(StorageBase):
config: SessionConfig,
state: AgentState | None = None,
session_id: str | None = None,
- source: SessionSource = SessionSource.USER,
+ origin: SessionOrigin | None = None,
+ source: str | None = None,
source_schedule_id: str | None = None,
source_chat_id: str | None = None,
source_chat_name: str | None = None,
@@ -1081,11 +1084,14 @@ class AsyncSQLAlchemyStorage(StorageBase):
user_id=user_id,
agent_id=agent_id,
config=config,
- source=source,
- source_schedule_id=source_schedule_id,
- source_chat_id=source_chat_id,
- source_chat_name=source_chat_name,
- source_channel_id=source_channel_id,
+ **_origin_kwargs(
+ origin,
+ source,
+ source_schedule_id,
+ source_channel_id,
+ source_chat_id,
+ source_chat_name,
+ ),
state=state if state is not None else AgentState(),
**new_id_kwargs,
)
@@ -1231,10 +1237,12 @@ class AsyncSQLAlchemyStorage(StorageBase):
) -> list[SessionRecord]:
"""Sessions derived from *channel_id* — newest first.
- ``source_channel_id`` lives in the JSON payload (not a promoted
- column), so it is matched inside the payload.
+ The channel id lives in the JSON payload rather than a column,
+ and in two shapes: nested under ``source`` since that became a
+ tagged union, flat for rows written before. Both are matched, so
+ no backfill is needed.
"""
- from sqlalchemy import select
+ from sqlalchemy import or_, select
async with self._session() as sess:
rows = (
@@ -1243,8 +1251,16 @@ class AsyncSQLAlchemyStorage(StorageBase):
select(SessionRow)
.where(
SessionRow.user_id == user_id,
- SessionRow.payload["source_channel_id"].as_string()
- == channel_id,
+ or_(
+ SessionRow.payload["origin"][
+ "channel_id"
+ ].as_string()
+ == channel_id,
+ SessionRow.payload[
+ "source_channel_id"
+ ].as_string()
+ == channel_id,
+ ),
)
.order_by(SessionRow.created_at.desc()),
)
diff --git a/src/agentscope/app/storage/_sql/_tables.py b/src/agentscope/app/storage/_sql/_tables.py
index d7b4e09b3..21c943b99 100644
--- a/src/agentscope/app/storage/_sql/_tables.py
+++ b/src/agentscope/app/storage/_sql/_tables.py
@@ -92,6 +92,12 @@ class _JsonRecordMixin(_Base):
# Populated by subclasses; see class docstring.
_record_cls: ClassVar[type]
_indexed_fields: ClassVar[tuple[str, ...]] = ()
+ _index_paths: ClassVar[dict[str, str]] = {}
+
+ @classmethod
+ def get_index_paths(cls) -> dict[str, str]:
+ """Return ``column -> dotted path`` for columns fed from nesting."""
+ return cls._index_paths
@classmethod
def get_indexed_fields(cls) -> tuple[str, ...]:
@@ -170,11 +176,17 @@ class SessionRow(_JsonRecordMixin):
_indexed_fields = (
"user_id",
"agent_id",
- "source",
- "source_schedule_id",
"team_id",
)
+ # Fed from inside ``source``, which is a tagged union rather than a
+ # flat field. Same column names and same indexes as before the
+ # nesting, so no migration is needed.
+ _index_paths: ClassVar[dict[str, str]] = {
+ "source": "origin.type",
+ "source_schedule_id": "origin.schedule_id",
+ }
+
class ScheduleRow(_JsonRecordMixin):
"""One row per :class:`~agentscope.app.storage.ScheduleRecord`."""
diff --git a/tests/channel_gateway_test.py b/tests/channel_gateway_test.py
index 29a4430ae..2dc6b620a 100644
--- a/tests/channel_gateway_test.py
+++ b/tests/channel_gateway_test.py
@@ -27,6 +27,7 @@ from agentscope.app.storage import (
ChannelBinding,
ChannelRecord,
RoutingConfig,
+ ChannelOrigin,
SessionConfig,
SessionRecord,
SessionScope,
@@ -446,7 +447,10 @@ class _AwaitingStorage:
id=self._session_id,
user_id=self._record.user_id,
agent_id="agent-x",
- source_chat_id="group:cid-1",
+ origin=ChannelOrigin(
+ channel_id="chan-1",
+ chat_id="group:cid-1",
+ ),
config=SessionConfig(workspace_id="ws-1"),
),
]
@@ -512,14 +516,27 @@ class ChatNameRecordingTest(IsolatedAsyncioTestCase):
async def test_chat_title_is_recorded_on_the_session(self) -> None:
upsert = await self._upsert("产品群")
- self.assertEqual(upsert["source_chat_id"], "group:cid-1")
- self.assertEqual(upsert["source_chat_name"], "产品群")
+ self.assertEqual(
+ upsert["origin"],
+ ChannelOrigin(
+ channel_id="chan-1",
+ chat_id="group:cid-1",
+ chat_name="产品群",
+ ),
+ )
async def test_a_nameless_chat_records_no_title(self) -> None:
"""A private chat has no title, and "" is not one."""
upsert = await self._upsert("")
- self.assertIsNone(upsert["source_chat_name"])
+ self.assertEqual(
+ upsert["origin"],
+ ChannelOrigin(
+ channel_id="chan-1",
+ chat_id="group:cid-1",
+ chat_name=None,
+ ),
+ )
class DecisionRoutingTest(IsolatedAsyncioTestCase):
diff --git a/tests/service_chat_channel_delivery_test.py b/tests/service_chat_channel_delivery_test.py
index 73f6d48be..3f8137c70 100644
--- a/tests/service_chat_channel_delivery_test.py
+++ b/tests/service_chat_channel_delivery_test.py
@@ -39,7 +39,9 @@ from agentscope.app.storage import (
SessionConfig,
SessionRecord,
SessionSettings,
- SessionSource,
+ ChannelOrigin,
+ SessionOrigin,
+ UserOrigin,
)
@@ -144,7 +146,7 @@ class ChannelDeliveryFromTheRunTest(IsolatedAsyncioTestCase):
"""Isolate the instances each test observes."""
_RecordingChannel.instances.clear()
- def _fixture(self, source: SessionSource) -> tuple:
+ def _fixture(self, source: SessionOrigin) -> tuple:
"""Build a session of ``source`` plus its agent and channel."""
user_id = "user-1"
agent = AgentRecord(
@@ -160,13 +162,7 @@ class ChannelDeliveryFromTheRunTest(IsolatedAsyncioTestCase):
id="session-1",
user_id=user_id,
agent_id=agent.id,
- source=source,
- source_channel_id=(
- "chan-1" if source is SessionSource.CHANNEL else None
- ),
- source_chat_id=(
- "chat-1" if source is SessionSource.CHANNEL else None
- ),
+ origin=source,
config=SessionConfig(
workspace_id="ws-1",
chat_model_config=ChatModelConfig(
@@ -189,7 +185,7 @@ class ChannelDeliveryFromTheRunTest(IsolatedAsyncioTestCase):
)
return user_id, agent, session, channel
- async def _run(self, source: SessionSource) -> ChannelClients:
+ async def _run(self, source: SessionOrigin) -> ChannelClients:
"""Drive one run to completion and return the channel runtime."""
user_id, agent, session, channel = self._fixture(source)
storage = _Storage(session, agent, channel)
@@ -267,7 +263,9 @@ class ChannelDeliveryFromTheRunTest(IsolatedAsyncioTestCase):
) -> None:
"""The run finishes before the channel starts reading, so the
delivery has to replay the log rather than miss the reply."""
- clients = await self._run(SessionSource.CHANNEL)
+ clients = await self._run(
+ ChannelOrigin(channel_id="chan-1", chat_id="chat-1"),
+ )
try:
self.assertEqual(len(_RecordingChannel.instances), 1)
channel = _RecordingChannel.instances[0]
@@ -296,7 +294,7 @@ class ChannelDeliveryFromTheRunTest(IsolatedAsyncioTestCase):
async def test_a_web_session_delivers_nothing(self) -> None:
"""Only a channel-originated run has a chat to reply into."""
- clients = await self._run(SessionSource.USER)
+ clients = await self._run(UserOrigin())
try:
self.assertListEqual(_RecordingChannel.instances, [])
finally:
diff --git a/tests/service_scheduler_test.py b/tests/service_scheduler_test.py
index f75dd1863..ca90ab8cc 100644
--- a/tests/service_scheduler_test.py
+++ b/tests/service_scheduler_test.py
@@ -38,7 +38,7 @@ from agentscope.app.storage import (
RedisStorage,
ScheduleData,
ScheduleRecord,
- SessionSource,
+ ScheduleOrigin,
)
from agentscope.app.workspace_manager import LocalWorkspaceManager
from agentscope.permission import PermissionMode
@@ -150,14 +150,8 @@ class TestSchedulerFireDelivery(_SchedulerFireTestBase):
self.assertEqual(len(sessions), 1)
session = sessions[0]
self.assertEqual(
- {
- "source": session.source,
- "source_schedule_id": session.source_schedule_id,
- },
- {
- "source": SessionSource.SCHEDULE,
- "source_schedule_id": record.id,
- },
+ session.origin,
+ ScheduleOrigin(schedule_id=record.id),
)
# Inbox has the wrapped HintBlock.
diff --git a/tests/service_team_tools_test.py b/tests/service_team_tools_test.py
index a6a156a87..f71eb9337 100644
--- a/tests/service_team_tools_test.py
+++ b/tests/service_team_tools_test.py
@@ -33,6 +33,8 @@ from agentscope.app._tool import (
from agentscope.app._types import SubAgentTemplate
from agentscope.app.message_bus import RedisMessageBus
from agentscope.app.storage import (
+ TeamOrigin,
+ UserOrigin,
AgentData,
AgentRecord,
RedisStorage,
@@ -301,6 +303,10 @@ class TestAgentCreate(_TeamToolsTestBase):
)
self.assertEqual(len(worker_sessions), 1)
self.assertEqual(worker_sessions[0].team_id, sess.team_id)
+ # The team minted this session, and the record says so — the
+ # leader's own session stays user-sourced.
+ self.assertEqual(worker_sessions[0].origin, TeamOrigin())
+ self.assertEqual(sess.origin, UserOrigin())
# The initial prompt is in the worker's inbox as a HintBlock
# wrapped in a <team-message> tag.
@@ -1449,6 +1455,7 @@ class TestAgentInviteSuccess(_AgentInviteTestBase):
)
self.assertEqual(borrowed.config.workspace_id, "ws-monday")
self.assertEqual(borrowed.team_id, team.id)
+ self.assertEqual(borrowed.origin, TeamOrigin())
# Borrowed session starts with a fresh PermissionContext —
# no leader / Monday state carried over.
diff --git a/tests/service_workspace_files_test.py b/tests/service_workspace_files_test.py
index a485928f1..b501a9d5a 100644
--- a/tests/service_workspace_files_test.py
+++ b/tests/service_workspace_files_test.py
@@ -26,7 +26,7 @@ from agentscope.app.storage import (
AgentRecord,
SessionConfig,
SessionRecord,
- SessionSource,
+ UserOrigin,
)
from agentscope.agent import ContextConfig, ReActConfig
from agentscope.state import AgentState
@@ -213,7 +213,7 @@ def _make_session(
user_id=user_id,
agent_id=agent_id,
id=session_id,
- source=SessionSource.USER,
+ origin=UserOrigin(),
state=AgentState(),
config=SessionConfig(
workspace_id=workspace_id,
diff --git a/tests/service_workspace_status_test.py b/tests/service_workspace_status_test.py
index 61a68de78..aba6d119f 100644
--- a/tests/service_workspace_status_test.py
+++ b/tests/service_workspace_status_test.py
@@ -24,7 +24,7 @@ from agentscope.app.storage import (
AgentRecord,
SessionConfig,
SessionRecord,
- SessionSource,
+ UserOrigin,
)
from agentscope.state import AgentState
from agentscope.tool import ExecResult
@@ -118,7 +118,7 @@ def _make_session(cwd: str | None = None) -> SessionRecord:
user_id="u",
agent_id="a",
id="s",
- source=SessionSource.USER,
+ origin=UserOrigin(),
state=AgentState(),
config=SessionConfig(workspace_id="ws-1", name="t", cwd=cwd),
agent_snapshot=AgentRecord(
diff --git a/tests/storage_redis_test.py b/tests/storage_redis_test.py
index d0f558acb..faeb85d8f 100644
--- a/tests/storage_redis_test.py
+++ b/tests/storage_redis_test.py
@@ -14,7 +14,8 @@ from agentscope.app.storage import (
ChatModelConfig,
ScheduleRecord,
ScheduleData,
- SessionSource,
+ ChannelOrigin,
+ ScheduleOrigin,
TeamData,
TeamRecord,
)
@@ -655,8 +656,7 @@ class TestScheduleSession(IsolatedAsyncioTestCase):
self.user_id,
self.agent_id,
make_session_config(),
- source=SessionSource.SCHEDULE,
- source_schedule_id=schedule.id,
+ origin=ScheduleOrigin(schedule_id=schedule.id),
)
results = await self.storage.list_sessions_by_schedule(
@@ -665,7 +665,10 @@ class TestScheduleSession(IsolatedAsyncioTestCase):
)
self.assertEqual(len(results), 1)
self.assertEqual(results[0].id, session.id)
- self.assertEqual(results[0].source_schedule_id, schedule.id)
+ self.assertEqual(
+ results[0].origin,
+ ScheduleOrigin(schedule_id=schedule.id),
+ )
async def test_list_sessions_by_schedule_empty(self) -> None:
"""Returns empty list when no sessions exist for a schedule."""
@@ -685,8 +688,7 @@ class TestScheduleSession(IsolatedAsyncioTestCase):
self.user_id,
self.agent_id,
make_session_config(),
- source=SessionSource.SCHEDULE,
- source_schedule_id=schedule.id,
+ origin=ScheduleOrigin(schedule_id=schedule.id),
)
agent_sessions = await self.storage.list_sessions(
@@ -705,15 +707,13 @@ class TestScheduleSession(IsolatedAsyncioTestCase):
self.user_id,
self.agent_id,
make_session_config(),
- source=SessionSource.SCHEDULE,
- source_schedule_id=schedule.id,
+ origin=ScheduleOrigin(schedule_id=schedule.id),
)
await self.storage.upsert_session(
self.user_id,
self.agent_id,
make_session_config(),
- source=SessionSource.SCHEDULE,
- source_schedule_id=schedule.id,
+ origin=ScheduleOrigin(schedule_id=schedule.id),
)
await self.storage.delete_schedule(self.user_id, schedule.id)
@@ -739,8 +739,7 @@ class TestScheduleSession(IsolatedAsyncioTestCase):
self.user_id,
self.agent_id,
make_session_config(),
- source=SessionSource.SCHEDULE,
- source_schedule_id=schedule.id,
+ origin=ScheduleOrigin(schedule_id=schedule.id),
)
await self.storage.delete_session(
@@ -1518,3 +1517,75 @@ class TestSkill(IsolatedAsyncioTestCase):
len(await self.storage.list_skills(self.user_id)),
1,
)
+
+
+class TestChannelSessionIndex(IsolatedAsyncioTestCase):
+ """The channel index, which the tagged union now drives.
+
+ It used to be written from a nullable ``source_channel_id``; it is
+ now written from a ``ChannelOrigin``, and the schedule path's
+ coverage says nothing about it.
+ """
+
+ async def asyncSetUp(self) -> None:
+ """Set up test fixtures."""
+ self.storage = make_storage()
+ self.user_id = "user-1"
+ self.agent_id = "agent-1"
+
+ async def test_a_channel_session_is_indexed_and_unindexed(self) -> None:
+ """It is found by its channel, and gone once the session is."""
+ session = await self.storage.upsert_session(
+ self.user_id,
+ self.agent_id,
+ make_session_config(),
+ origin=ChannelOrigin(
+ channel_id="chan-1",
+ chat_id="chat-1",
+ chat_name="产品群",
+ ),
+ )
+
+ found = await self.storage.list_sessions_by_channel(
+ self.user_id,
+ "chan-1",
+ )
+ self.assertEqual(len(found), 1)
+ self.assertEqual(found[0].id, session.id)
+ self.assertEqual(
+ found[0].origin,
+ ChannelOrigin(
+ channel_id="chan-1",
+ chat_id="chat-1",
+ chat_name="产品群",
+ ),
+ )
+
+ await self.storage.delete_session(
+ self.user_id,
+ self.agent_id,
+ session.id,
+ )
+
+ self.assertEqual(
+ await self.storage.list_sessions_by_channel(
+ self.user_id,
+ "chan-1",
+ ),
+ [],
+ )
+
+ async def test_a_session_from_elsewhere_is_not_indexed(self) -> None:
+ """Only a ChannelOrigin goes into the channel index."""
+ await self.storage.upsert_session(
+ self.user_id,
+ self.agent_id,
+ make_session_config(),
+ )
+ self.assertEqual(
+ await self.storage.list_sessions_by_channel(
+ self.user_id,
+ "chan-1",
+ ),
+ [],
+ )
diff --git a/tests/storage_sql_test.py b/tests/storage_sql_test.py
index 624ce1c81..0d2224fce 100644
--- a/tests/storage_sql_test.py
+++ b/tests/storage_sql_test.py
@@ -20,6 +20,8 @@ from sqlalchemy.dialects import mysql
from utils import AnyString
+from agentscope.app.storage._sql._mappers import _to_record
+from agentscope.app.storage._sql._tables import SessionRow
from agentscope.app.storage import (
AgentData,
AgentRecord,
@@ -37,7 +39,10 @@ from agentscope.app.storage import (
ScheduleRecord,
SessionConfig,
SessionSettings,
- SessionSource,
+ ChannelOrigin,
+ UserOrigin,
+ ScheduleOrigin,
+ SessionRecord,
SkillRecord,
AsyncSQLAlchemyStorage,
TeamData,
@@ -323,10 +328,9 @@ class AsyncSQLAlchemyStorageTest(IsolatedAsyncioTestCase):
user_id="user-1",
agent_id=agent.id,
config=_session_config(),
- source=SessionSource.SCHEDULE,
- source_schedule_id="sch-1",
+ origin=ScheduleOrigin(schedule_id="sch-1"),
)
- self.assertEqual(session.source, SessionSource.SCHEDULE)
+ self.assertEqual(session.origin, ScheduleOrigin(schedule_id="sch-1"))
# Update (same session_id) — config swap
new_config = _session_config()
@@ -1197,3 +1201,165 @@ class LegacyRecordShapeTest(IsolatedAsyncioTestCase):
MCPRecord.model_validate(payload).name,
"deepwiki",
)
+
+
+class SessionOriginLegacyTest(IsolatedAsyncioTestCase):
+ """Rows written before :data:`SessionOrigin` existed still read back.
+
+ Those carry a bare ``source`` string, and — this is the part a
+ round-trip through the new code never exercises — their ids live in
+ promoted columns rather than in the payload.
+ """
+
+ def _legacy_row(self, **columns: object) -> SessionRow:
+ """A row in the shape the old mapper wrote."""
+ now = datetime.now()
+ return SessionRow(
+ id="sess-legacy",
+ created_at=now,
+ updated_at=now,
+ user_id="user-1",
+ agent_id="agent-1",
+ team_id=None,
+ payload={"config": {"name": "n", "workspace_id": "ws-1"}},
+ **columns,
+ )
+
+ async def test_legacy_schedule_row_keeps_its_schedule_id(self) -> None:
+ """The id is in a column, not the payload, and must survive."""
+ record = _to_record(
+ self._legacy_row(source="schedule", source_schedule_id="sch-1"),
+ SessionRecord,
+ )
+ self.assertEqual(record.origin, ScheduleOrigin(schedule_id="sch-1"))
+
+ async def test_legacy_channel_row_keeps_its_ids(self) -> None:
+ """Channel ids were in the payload already, flat rather than nested."""
+ row = self._legacy_row(source="channel", source_schedule_id=None)
+ row.payload = {
+ **row.payload,
+ "source_channel_id": "chan-1",
+ "source_chat_id": "chat-1",
+ "source_chat_name": "产品群",
+ }
+ self.assertEqual(
+ _to_record(row, SessionRecord).origin,
+ ChannelOrigin(
+ channel_id="chan-1",
+ chat_id="chat-1",
+ chat_name="产品群",
+ ),
+ )
+
+ async def test_legacy_user_row_reads_as_user(self) -> None:
+ """The plain case, where every id column is empty."""
+ record = _to_record(
+ self._legacy_row(source="user", source_schedule_id=None),
+ SessionRecord,
+ )
+ self.assertEqual(record.origin, UserOrigin())
+
+ async def test_an_origin_without_its_ids_is_not_that_origin(self) -> None:
+ """A tag carries its ids, so a row missing them cannot claim one.
+
+ The old shape let ``source`` say ``channel`` while the ids were
+ ``None``, and every caller wrote a truthiness guard because of
+ it. Manufacturing blank ids would walk such a row straight past
+ those guards — and index it under the empty string.
+ """
+ self.assertEqual(
+ _to_record(
+ self._legacy_row(source="schedule", source_schedule_id=None),
+ SessionRecord,
+ ).origin,
+ UserOrigin(),
+ )
+ self.assertEqual(
+ _to_record(
+ self._legacy_row(source="channel", source_schedule_id=None),
+ SessionRecord,
+ ).origin,
+ UserOrigin(),
+ )
+
+
+class ChannelSessionLookupTest(IsolatedAsyncioTestCase):
+ """``list_sessions_by_channel`` reads both payload shapes.
+
+ The nested one is what the union writes; the flat one is every row
+ written before it. Matching both is what lets this ship without a
+ backfill, and it is dialect-sensitive JSON access, so it is worth
+ running rather than reasoning about.
+ """
+
+ async def asyncSetUp(self) -> None:
+ """Open a storage on an in-memory database."""
+ self._stack = AsyncExitStack()
+ self.storage = await self._stack.enter_async_context(
+ AsyncSQLAlchemyStorage(url="sqlite+aiosqlite:///:memory:"),
+ )
+
+ async def asyncTearDown(self) -> None:
+ """Close it."""
+ await self._stack.aclose()
+
+ async def test_both_shapes_come_back(self) -> None:
+ """One session written each way, both found by their channel."""
+ await self.storage.upsert_session(
+ user_id="user-1",
+ agent_id="agent-1",
+ config=SessionConfig(workspace_id="ws-1"),
+ origin=ChannelOrigin(channel_id="chan-1", chat_id="chat-new"),
+ )
+ # A row as the old code wrote it: no ``origin``, ids flat in the
+ # payload. Written through the row layer so the record's own
+ # validator cannot normalise it on the way in.
+ now = datetime.now()
+ # pylint: disable=protected-access
+ async with self.storage._session() as sess:
+ sess.add(
+ SessionRow(
+ id="sess-legacy",
+ created_at=now,
+ updated_at=now,
+ user_id="user-1",
+ agent_id="agent-1",
+ team_id=None,
+ source="channel",
+ source_schedule_id=None,
+ payload={
+ "config": {"workspace_id": "ws-1"},
+ "source_channel_id": "chan-1",
+ "source_chat_id": "chat-old",
+ },
+ ),
+ )
+ await sess.commit()
+
+ found = await self.storage.list_sessions_by_channel("user-1", "chan-1")
+
+ self.assertListEqual(
+ sorted(_.origin.chat_id for _ in found),
+ ["chat-new", "chat-old"],
+ )
+
+ async def test_a_legacy_call_still_builds_the_right_origin(self) -> None:
+ """The flat arguments ``upsert_session`` used to take still work."""
+ with self.assertWarns(DeprecationWarning):
+ record = await self.storage.upsert_session(
+ user_id="user-1",
+ agent_id="agent-1",
+ config=SessionConfig(workspace_id="ws-1"),
+ source="channel",
+ source_channel_id="chan-1",
+ source_chat_id="chat-1",
+ source_chat_name="产品群",
+ )
+ self.assertEqual(
+ record.origin,
+ ChannelOrigin(
+ channel_id="chan-1",
+ chat_id="chat-1",
+ chat_name="产品群",
+ ),
+ )