DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(partners): show which chat a partner conversation came from
Bingxi Zhao (Frank)abd7fbcdcea8
diff --git a/deeptutor/services/partners/runtime.py b/deeptutor/services/partners/runtime.pyindex 6dbb364ef..b117ecece 100644--- a/deeptutor/services/partners/runtime.py+++ b/deeptutor/services/partners/runtime.py@@ -47,7 +47,7 @@ from deeptutor.services.partners.interaction import ()from deeptutor.services.partners.links import linked_user_idfrom deeptutor.services.partners.scope import partner_user-from deeptutor.services.partners.sessions import PartnerSessionStore+from deeptutor.services.partners.sessions import PartnerSessionStore, conversation_scopefrom deeptutor.services.partners.workspace import ensure_partner_workspace, read_soullogger = logging.getLogger(__name__)@@ -301,14 +301,22 @@ class PartnerRunner:if options.persist:activity_id = str((msg.metadata or {}).get("_web_activity_id") or "").strip()activity_meta = {"activity_id": activity_id} if activity_id else None+ inbound_meta = msg.metadata or {}store.append(session_key,"user",msg.content,channel=msg.channel,sender_id=msg.sender_id,+ chat_id=msg.chat_id,+ scope=conversation_scope(+ msg.channel,+ str(+ inbound_meta.get("chat_type") or inbound_meta.get("channel_type") or ""+ ),+ ),metadata=activity_meta,- attachments=list((msg.metadata or {}).get("_attachment_records") or []),+ attachments=list(inbound_meta.get("_attachment_records") or []),)if final:store.append(diff --git a/deeptutor/services/partners/sessions.py b/deeptutor/services/partners/sessions.pyindex 75360c850..24eb65d7d 100644--- a/deeptutor/services/partners/sessions.py+++ b/deeptutor/services/partners/sessions.py@@ -25,6 +25,27 @@ _HISTORY_MAX_CHARS = 24_000_ARCHIVE_PREFIX = "_archived_"+# Each chat platform names its own conversation kinds, and the channels+# already carry that word inbound: Feishu sends ``chat_type`` ("group" /+# "p2p"), Slack and Mattermost send ``channel_type`` ("im"; "D" / "O" / "P" /+# "G"). This is the one place those vocabularies become the two words a+# reader of the conversation list cares about. A value not listed here — a+# channel that says nothing, or says something new — yields "", and the list+# stays silent rather than guessing.+_CONVERSATION_SCOPES: dict[str, dict[str, str]] = {+ "feishu": {"group": "group", "p2p": "direct"},+ "slack": {"im": "direct", "channel": "group", "group": "group", "mpim": "group"},+ "mattermost": {"d": "direct", "o": "group", "p": "group", "g": "group"},+}+++def conversation_scope(channel: str, chat_type: str) -> str:+ """Whether a conversation is a ``group`` chat, a ``direct`` one, or unknown."""+ return _CONVERSATION_SCOPES.get(channel.strip().lower(), {}).get(+ str(chat_type or "").strip().lower(), ""+ )++class PartnerSessionStore:"""Append-only JSONL persistence for one partner's conversations."""@@ -144,6 +165,8 @@ class PartnerSessionStore:*,channel: str = "",sender_id: str = "",+ chat_id: str = "",+ scope: str = "",metadata: dict[str, Any] | None = None,attachments: list[dict[str, Any]] | None = None,events: list[dict[str, Any]] | None = None,@@ -157,6 +180,14 @@ class PartnerSessionStore:record["channel"] = channelif sender_id:record["sender_id"] = sender_id+ # Which conversation on the platform this turn came from. Written here+ # because the channel knows it authoritatively at delivery time and+ # nothing downstream can recover it: the conversation list showed every+ # Feishu group exactly like a DM (#1229).+ if chat_id:+ record["chat_id"] = chat_id+ if scope:+ record["scope"] = scopeif metadata:record["metadata"] = metadataif attachments:@@ -288,8 +319,25 @@ class PartnerSessionStore:"updated_at": datetime.fromtimestamp(path.stat().st_mtime).isoformat(),"last_message": str(last.get("content", ""))[:200],"archived": archived,+ **self._origin(records),}+ @staticmethod+ def _origin(records: list[dict[str, Any]]) -> dict[str, str]:+ """Where this conversation happens, from the first turn that recorded it.++ Sessions that predate the origin being written carry none, so the keys+ are omitted rather than emitted empty — the list then renders exactly+ as it did before instead of labelling everything "unknown".+ """+ for record in records:+ chat_id = str(record.get("chat_id") or "")+ if not chat_id:+ continue+ scope = str(record.get("scope") or "")+ return {"chat_id": chat_id, **({"scope": scope} if scope else {})}+ return {}+@staticmethoddef _derive_title(records: list[dict[str, Any]]) -> str:"""A short, human label for a session — its opening user message.diff --git a/tests/services/partners/test_partner_runtime.py b/tests/services/partners/test_partner_runtime.pyindex f6fc5f744..c2b340001 100644--- a/tests/services/partners/test_partner_runtime.py+++ b/tests/services/partners/test_partner_runtime.py@@ -98,6 +98,73 @@ class TestTurnExecution:{"role": "assistant", "content": "The answer is 4."},]+ @pytest.mark.asyncio+ async def test_a_group_conversation_records_where_it_happened(+ self, partners_root, fake_orchestrator+ ):+ """#1229: one partner serving three subject groups looked like three DMs.++ Feishu states the kind of chat on the inbound event, so the turn that+ is being written is the only moment the origin is known for certain.+ The conversation list reads it back from there.+ """+ fake_orchestrator.script = finish("noted")+ runner = _runner(partners_root)+ group = InboundMessage(+ channel="feishu",+ sender_id="ou_student",+ chat_id="oc_math_group",+ content="老师这题怎么做",+ metadata={"chat_type": "group"},+ )++ await runner.process_message(group)++ summary = next(+ row+ for row in _shared_store().list_sessions()+ if row["session_key"] == "feishu_oc_math_group"+ )+ assert summary["chat_id"] == "oc_math_group"+ assert summary["scope"] == "group"++ @pytest.mark.asyncio+ async def test_a_direct_message_is_marked_as_one(self, partners_root, fake_orchestrator):+ fake_orchestrator.script = finish("noted")+ runner = _runner(partners_root)+ direct = InboundMessage(+ channel="feishu",+ sender_id="ou_parent",+ chat_id="ou_parent",+ content="他最近怎么样",+ metadata={"chat_type": "p2p"},+ )++ await runner.process_message(direct)++ summary = next(+ row+ for row in _shared_store().list_sessions()+ if row["session_key"] == "feishu_ou_parent"+ )+ assert summary["scope"] == "direct"++ @pytest.mark.asyncio+ async def test_a_channel_that_says_nothing_is_left_unlabelled(+ self, partners_root, fake_orchestrator+ ):+ """A conversation list that guesses is worse than one that stays quiet."""+ fake_orchestrator.script = finish("noted")+ runner = _runner(partners_root)++ await runner.process_message(_msg("hello"))++ summary = next(+ row for row in _shared_store().list_sessions() if row["session_key"] == "telegram_42"+ )+ assert summary["chat_id"] == "42"+ assert "scope" not in summary+@pytest.mark.asyncioasync def test_narration_streams_as_progress_outbound(self, partners_root, fake_orchestrator):fake_orchestrator.script = narration_round("c1", "exploring…") + finish("done")diff --git a/web/components/partners/PartnerArchives.tsx b/web/components/partners/PartnerArchives.tsxindex 33050ecc1..423c84120 100644--- a/web/components/partners/PartnerArchives.tsx+++ b/web/components/partners/PartnerArchives.tsx@@ -5,6 +5,8 @@ import {Archive,Clock3,MessageSquareText,+ User,+ Users,RefreshCw,RotateCcw,Trash2,@@ -220,9 +222,29 @@ export default function PartnerArchives({{session.last_message}</p>) : null}- <div className="mt-1 flex items-center gap-1 text-[10.5px] text-[var(--muted-foreground)]">- <Clock3 className="h-3 w-3" />- {formatTime(session.updated_at)}+ <div className="mt-1 flex items-center gap-2 text-[10.5px] text-[var(--muted-foreground)]">+ <span className="flex items-center gap-1">+ <Clock3 className="h-3 w-3" />+ {formatTime(session.updated_at)}+ </span>+ {/* Which conversation on the platform this came from. One+ partner commonly serves several study groups plus DMs, and+ without this every one of them reads as a private chat+ (#1229). Sessions recorded before the origin was stored+ carry none, and simply show nothing extra. */}+ {session.chat_id ? (+ <span+ className="flex min-w-0 items-center gap-1"+ title={session.chat_id}+ >+ {session.scope === "group" ? (+ <Users className="h-3 w-3 shrink-0" />+ ) : session.scope === "direct" ? (+ <User className="h-3 w-3 shrink-0" />+ ) : null}+ <span className="truncate">{session.chat_id}</span>+ </span>+ ) : null}</div></button>))}diff --git a/web/contracts/generated/api.ts b/web/contracts/generated/api.tsindex 9abb3d082..d72678dfe 100644--- a/web/contracts/generated/api.ts+++ b/web/contracts/generated/api.ts@@ -2300,6 +2300,38 @@ export interface paths {readonly patch?: never;readonly trace?: never;};+ readonly "/api/knowledge-bases/delete": {+ readonly parameters: {+ readonly query?: never;+ readonly header?: never;+ readonly path?: never;+ readonly cookie?: never;+ };+ readonly get?: never;+ readonly put?: never;+ /**+ * Delete Knowledge Base By Name+ * @description Delete a knowledge base named in the body rather than in the path.+ *+ * The path route below cannot reach every registered name. A name is a+ * ``kb_config.json`` key, and until the ``register_*`` methods validated it+ * the connect-* endpoints wrote whatever the user typed — including a ``/``.+ * uvicorn percent-decodes the path before routing, so ``%2F`` becomes a real+ * separator and ``{kb_name}`` (compiled to ``[^/]+``) cannot span it: every+ * per-KB route 404s and the KB is visible in the list but unreachable.+ *+ * A body is never split into path segments, so this reaches those entries.+ * Widening the path route to ``{kb_name:path}`` would not do — it is+ * declared ahead of the DELETE routes for linked folders, GitHub sources and+ * web sources, and a greedy converter would silently swallow all three.+ */+ readonly post: operations["delete_knowledge_base_by_name_api_knowledge_bases_delete_post"];+ readonly delete?: never;+ readonly options?: never;+ readonly head?: never;+ readonly patch?: never;+ readonly trace?: never;+ };readonly "/api/knowledge-bases/health": {readonly parameters: {readonly query?: never;@@ -7126,6 +7158,33 @@ export interface paths {readonly patch?: never;readonly trace?: never;};+ readonly "/api/settings/providers/openai-codex/oauth/complete": {+ readonly parameters: {+ readonly query?: never;+ readonly header?: never;+ readonly path?: never;+ readonly cookie?: never;+ };+ readonly get?: never;+ readonly put?: never;+ /**+ * Complete Openai Codex Oauth+ * @description Finish a waiting Codex login from a callback address the user pasted.+ *+ * The provider redirects the browser to a loopback listener. In Docker that+ * listener lives in the container and the published ports do not include it,+ * so the browser shows a failed page while the sign-in waits forever+ * (#1252). This is the way back in without a tunnel: the address is parsed+ * for its OAuth result and discarded, and the exchange is the same one the+ * listener would have driven.+ */+ readonly post: operations["complete_openai_codex_oauth_api_settings_providers_openai_codex_oauth_complete_post"];+ readonly delete?: never;+ readonly options?: never;+ readonly head?: never;+ readonly patch?: never;+ readonly trace?: never;+ };readonly "/api/settings/providers/openai-codex/oauth/logout": {readonly parameters: {readonly query?: never;@@ -9665,6 +9724,11 @@ export interface components {/** Trace Count */readonly trace_count: number;};+ /** CodexOAuthCallbackPayload */+ readonly CodexOAuthCallbackPayload: {+ /** Callback Url */+ readonly callback_url: string;+ };/** CodexReasoningEffortUpdate */readonly CodexReasoningEffortUpdate: {/** Model */@@ -10162,6 +10226,11 @@ export interface components {/** Page Id */readonly page_id: string;};+ /** DeleteKnowledgeBaseRequest */+ readonly DeleteKnowledgeBaseRequest: {+ /** Name */+ readonly name: string;+ };/*** DeviceCredentialCreateRequest* @description Admin payload for issuing a local ordinary-user device credential.@@ -13536,6 +13605,8 @@ export type SchemaChatResponseTimeoutUpdate =components["schemas"]["ChatResponseTimeoutUpdate"];export type SchemaChatStarterSettingsUpdate =components["schemas"]["ChatStarterSettingsUpdate"];+export type SchemaCodexOAuthCallbackPayload =+ components["schemas"]["CodexOAuthCallbackPayload"];export type SchemaCodexReasoningEffortUpdate =components["schemas"]["CodexReasoningEffortUpdate"];export type SchemaCompilePageRequest =@@ -13593,6 +13664,8 @@ export type SchemaDeeptutorApiRoutersVideoLearningProgressRequest =components["schemas"]["deeptutor__api__routers__video_learning__ProgressRequest"];export type SchemaDeleteBlockRequest =components["schemas"]["DeleteBlockRequest"];+export type SchemaDeleteKnowledgeBaseRequest =+ components["schemas"]["DeleteKnowledgeBaseRequest"];export type SchemaDeviceCredentialCreateRequest =components["schemas"]["DeviceCredentialCreateRequest"];export type SchemaDeviceInfo = components["schemas"]["DeviceInfo"];@@ -18794,6 +18867,43 @@ export interface operations {};};};+ readonly delete_knowledge_base_by_name_api_knowledge_bases_delete_post: {+ readonly parameters: {+ readonly query?: never;+ readonly header?: {+ readonly Authorization?: string | null;+ };+ readonly path?: never;+ readonly cookie?: {+ readonly dt_token?: string | null;+ };+ };+ readonly requestBody: {+ readonly content: {+ readonly "application/json": components["schemas"]["DeleteKnowledgeBaseRequest"];+ };+ };+ readonly responses: {+ /** @description Successful Response */+ readonly 200: {+ headers: {+ readonly [name: string]: unknown;+ };+ content: {+ readonly "application/json": unknown;+ };+ };+ /** @description Validation Error */+ readonly 422: {+ headers: {+ readonly [name: string]: unknown;+ };+ content: {+ readonly "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };readonly health_check_api_knowledge_bases_health_get: {readonly parameters: {readonly query?: never;@@ -30100,6 +30210,45 @@ export interface operations {};};};+ readonly complete_openai_codex_oauth_api_settings_providers_openai_codex_oauth_complete_post: {+ readonly parameters: {+ readonly query?: never;+ readonly header?: {+ readonly Authorization?: string | null;+ };+ readonly path?: never;+ readonly cookie?: {+ readonly dt_token?: string | null;+ };+ };+ readonly requestBody: {+ readonly content: {+ readonly "application/json": components["schemas"]["CodexOAuthCallbackPayload"];+ };+ };+ readonly responses: {+ /** @description Successful Response */+ readonly 200: {+ headers: {+ readonly [name: string]: unknown;+ };+ content: {+ readonly "application/json": {+ readonly [key: string]: unknown;+ };+ };+ };+ /** @description Validation Error */+ readonly 422: {+ headers: {+ readonly [name: string]: unknown;+ };+ content: {+ readonly "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };readonly logout_openai_codex_oauth_api_settings_providers_openai_codex_oauth_logout_post: {readonly parameters: {readonly query?: never;diff --git a/web/contracts/schema/openapi.json b/web/contracts/schema/openapi.jsonindex 05c5efeff..c103168fc 100644--- a/web/contracts/schema/openapi.json+++ b/web/contracts/schema/openapi.json@@ -1526,6 +1526,19 @@"title": "ChatStarterSettingsUpdate","type": "object"},+ "CodexOAuthCallbackPayload": {+ "properties": {+ "callback_url": {+ "title": "Callback Url",+ "type": "string"+ }+ },+ "required": [+ "callback_url"+ ],+ "title": "CodexOAuthCallbackPayload",+ "type": "object"+ },"CodexReasoningEffortUpdate": {"properties": {"model": {@@ -2654,6 +2667,19 @@"title": "DeleteBlockRequest","type": "object"},+ "DeleteKnowledgeBaseRequest": {+ "properties": {+ "name": {+ "title": "Name",+ "type": "string"+ }+ },+ "required": [+ "name"+ ],+ "title": "DeleteKnowledgeBaseRequest",+ "type": "object"+ },"DeviceCredentialCreateRequest": {"description": "Admin payload for issuing a local ordinary-user device credential.","properties": {@@ -17772,6 +17798,80 @@]}},+ "/api/knowledge-bases/delete": {+ "post": {+ "description": "Delete a knowledge base named in the body rather than in the path.\n\nThe path route below cannot reach every registered name. A name is a\n``kb_config.json`` key, and until the ``register_*`` methods validated it\nthe connect-* endpoints wrote whatever the user typed — including a ``/``.\nuvicorn percent-decodes the path before routing, so ``%2F`` becomes a real\nseparator and ``{kb_name}`` (compiled to ``[^/]+``) cannot span it: every\nper-KB route 404s and the KB is visible in the list but unreachable.\n\nA body is never split into path segments, so this reaches those entries.\nWidening the path route to ``{kb_name:path}`` would not do — it is\ndeclared ahead of the DELETE routes for linked folders, GitHub sources and\nweb sources, and a greedy converter would silently swallow all three.",+ "operationId": "delete_knowledge_base_by_name_api_knowledge_bases_delete_post",+ "parameters": [+ {+ "in": "header",+ "name": "Authorization",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Authorization"+ }+ },+ {+ "in": "cookie",+ "name": "dt_token",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Dt Token"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DeleteKnowledgeBaseRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {}+ }+ },+ "description": "Successful Response"+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ },+ "description": "Validation Error"+ }+ },+ "summary": "Delete Knowledge Base By Name",+ "tags": [+ "knowledge-bases"+ ]+ }+ },"/api/knowledge-bases/health": {"get": {"description": "Health check endpoint",@@ -43740,6 +43840,84 @@]}},+ "/api/settings/providers/openai-codex/oauth/complete": {+ "post": {+ "description": "Finish a waiting Codex login from a callback address the user pasted.\n\nThe provider redirects the browser to a loopback listener. In Docker that\nlistener lives in the container and the published ports do not include it,\nso the browser shows a failed page while the sign-in waits forever\n(#1252). This is the way back in without a tunnel: the address is parsed\nfor its OAuth result and discarded, and the exchange is the same one the\nlistener would have driven.",+ "operationId": "complete_openai_codex_oauth_api_settings_providers_openai_codex_oauth_complete_post",+ "parameters": [+ {+ "in": "header",+ "name": "Authorization",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Authorization"+ }+ },+ {+ "in": "cookie",+ "name": "dt_token",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Dt Token"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodexOAuthCallbackPayload"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "additionalProperties": true,+ "title": "Response Complete Openai Codex Oauth Api Settings Providers Openai Codex Oauth Complete Post",+ "type": "object"+ }+ }+ },+ "description": "Successful Response"+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ },+ "description": "Validation Error"+ }+ },+ "summary": "Complete Openai Codex Oauth",+ "tags": [+ "settings"+ ]+ }+ },"/api/settings/providers/openai-codex/oauth/logout": {"post": {"operationId": "logout_openai_codex_oauth_api_settings_providers_openai_codex_oauth_logout_post",diff --git a/web/lib/partners-api.ts b/web/lib/partners-api.tsindex 352eb16f3..998d461fc 100644--- a/web/lib/partners-api.ts+++ b/web/lib/partners-api.ts@@ -85,6 +85,10 @@ export interface PartnerSessionInfo {updated_at: string;last_message: string;archived?: boolean;+ /** The platform conversation this session belongs to, when the channel said. */+ chat_id?: string;+ /** "group" or "direct"; absent when the channel does not distinguish them. */+ scope?: string;}export interface PartnerCommandInfo {