๐คฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
โจ feat(agent): attribute agent โ agent messages to the sending agent (#20548)
Arvin Xu26cb71424f02
diff --git a/apps/cli/src/commands/agent/run.ts b/apps/cli/src/commands/agent/run.tsindex 42e9759e8e3..1fb9d330c38 100644--- a/apps/cli/src/commands/agent/run.ts+++ b/apps/cli/src/commands/agent/run.ts@@ -155,6 +155,15 @@ Exit codes:if (options.autoStart === false) input.autoStart = false;if (options.tool?.length) input.selectedToolIds = options.tool;if (options.skill?.length) input.selectedSkillIds = options.skill;+ // When another agent launched this command, its environment carries the+ // operation the launcher's run belongs to (LOBEHUB_OPERATION_ID) โ but+ // deliberately not its agent id or its topic, which device-dispatched+ // runs strip. Forward the operation so the target's conversation+ // attributes the turn to the launching agent; the server reads the topic+ // and agent from that operation row. A person running `lh` from a+ // terminal has no ambient operation, and nothing is stamped.+ const sourceOperationId = process.env.LOBEHUB_OPERATION_ID;+ if (sourceOperationId) input.sourceOperationId = sourceOperationId;// commander's --no-headless sets `headless` to false. Anything else// (undefined, true) โ headless mode is on and tool calls auto-execute.if (options.headless !== false) {diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 284fcfe2bfa..9d655aa9fcf 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -1350,6 +1350,16 @@ const ExecAgentSchema = zmessage: 'The bot trigger is reserved for authenticated server-side bot ingress',}).optional(),+ /**+ * The operation the launching agent's run belongs to, when another agent+ * started this run (agent โ agent: a sibling agent calling `lh agent run`).+ * The launcher's own agent id is deliberately not sent โ device-dispatched+ * runs strip it โ and neither is its topic: the server reads both from this+ * operation row (ownership-scoped, the caller's own) and stamps+ * `metadata.agentSender` on the created user message. An unknown, foreign,+ * or topic-less operation simply resolves to nothing.+ */+ sourceOperationId: z.string().optional(),/*** User intervention configuration for tool approvals.* Pass `{ approvalMode: 'headless' }` from headless clients (CLI, cron, bots)@@ -2662,6 +2672,7 @@ export const aiAgentRouter = router({selectedSkillIds,selectedToolIds,slug,+ sourceOperationId: input.sourceOperationId,steer,trigger: trigger ?? RequestTrigger.Chat,userAgent: ctx.userAgent ?? undefined,diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.tsindex 7f9610e16aa..bdf001f4fe6 100644--- a/apps/server/src/routers/lambda/message.ts+++ b/apps/server/src/routers/lambda/message.ts@@ -1,6 +1,7 @@import { projectToolViewModels } from '@lobechat/tool-view-model';import {CreateNewMessageParamsSchema,+ omitServerOwnedMessageMetadata,UpdateMessageParamsSchema,UpdateMessagePluginSchema,UpdateMessageRAGParamsSchema,@@ -170,7 +171,18 @@ export const messageRouter = router({).mutation(async ({ input, ctx }) => {const operations: MessageBatchOperation[] = await Promise.all(- input.operations.map(async (operation): Promise<MessageBatchOperation> => {+ input.operations.map(async (rawOperation): Promise<MessageBatchOperation> => {+ // Creates are passthrough, so a client could carry server-owned metadata.+ const operation =+ rawOperation.type === 'createMessage'+ ? {+ ...rawOperation,+ message: {+ ...rawOperation.message,+ metadata: omitServerOwnedMessageMetadata(rawOperation.message.metadata),+ },+ }+ : rawOperation;if (operation.type !== 'createMessage' ||operation.message.agentId ||@@ -354,8 +366,13 @@ export const messageRouter = router({await assertCreatorTopicTargets(guardCtx(ctx), [input.topicId]);}- // Create message with the resolved agentId- return ctx.messageService.createMessage({ ...input, agentId } as any);+ // Create message with the resolved agentId. The input is passthrough, so+ // server-owned metadata a client slipped in is dropped here.+ return ctx.messageService.createMessage({+ ...input,+ agentId,+ metadata: omitServerOwnedMessageMetadata(input.metadata),+ } as any);}),/**@@ -908,7 +925,7 @@ export const messageRouter = router({ctx.workspaceId ?? undefined,);- return ctx.messageService.updateMetadata(id, value, resolved);+ return ctx.messageService.updateMetadata(id, omitServerOwnedMessageMetadata(value), resolved);}),updatePluginError: messageProcedurediff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 5b0eda6ea4f..df1a7801942 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -3,6 +3,7 @@ import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';import type { SandboxStorageClaim } from '@lobechat/builtin-tool-cloud-sandbox';import type { LobeChatDatabase } from '@lobechat/database';import type {+ AgentSenderMetadata,ExecAgentResult,ExecGroupAgentParams,ExecGroupAgentResult,@@ -25,6 +26,7 @@ import {import { AgentModel } from '@/database/models/agent';import { AgentOperationModel } from '@/database/models/agentOperation';import { AgentShareModel } from '@/database/models/agentShare';+import { ChatGroupModel } from '@/database/models/chatGroup';import { ConnectorModel } from '@/database/models/connector';import { ConnectorToolModel } from '@/database/models/connectorTool';import { DeviceModel } from '@/database/models/device';@@ -84,6 +86,7 @@ import { startOperation } from './pipeline/startOperation';import { resolveNewTopicSnapshot, setupTurn } from './pipeline/turnSetup';import { createRunFacts, type RunFacts } from './runFacts';import { applyShareGateToAgentConfig } from './shareGate';+import { resolveAgentSenderFromOperation } from './sourceAttribution';import type { SubAgentLlmRelayRequest } from './subAgentLlmRelay';import { closeSubAgentLlmRelay, openSubAgentLlmRelay } from './subAgentLlmRelay';import type { SubAgentRunDeps } from './subAgentRuns';@@ -1215,6 +1218,14 @@ export class AiAgentService {);if (reusedContinuation) return reusedContinuation;+ // Agent โ agent attribution: resolve the launching run's agent into a+ // display snapshot once, before the turn rows exist, so the persisted user+ // message carries a self-contained sender block.+ const agentSender = await this.resolveSourceAgentSnapshot(+ resolvedAgentId,+ params.sourceOperationId,+ );+// Stage 3 + shared turn setup โ topic creation/reuse (with the pinned// model), device-access policy, hetero detection, attachment ingestion, and// the persisted user/assistant rows (see `pipeline/turnSetup`).@@ -1229,6 +1240,7 @@ export class AiAgentService {},{agentConfig,+ agentSender,agentSlug,appContext,assistantAgentId,@@ -1682,6 +1694,28 @@ export class AiAgentService {};}+ /**+ * Snapshot the agent that launched an agent โ agent run (`metadata.agentSender`)+ * from the caller's own operation row; `resolveAgentSenderFromOperation` owns the+ * trust and shareability rules.+ */+ private resolveSourceAgentSnapshot = (+ destinationAgentId: string,+ sourceOperationId?: string,+ ): Promise<AgentSenderMetadata | undefined> =>+ resolveAgentSenderFromOperation(sourceOperationId, {+ destinationAgentId,+ findAgentDisplayFields: (agentId) => this.agentModel.getAgentDisplayFields(agentId),+ findAgentVisibility: (agentId) => this.agentModel.getAgentVisibility(agentId),+ findChatGroupVisibility: async (chatGroupId) =>+ (await new ChatGroupModel(this.db, this.userId, this.workspaceId).findById(chatGroupId))+ ?.visibility ?? null,+ findOperation: (operationId) => this.agentOperationModel.findById(operationId),+ findTopic: (topicId) => this.topicModel.findById(topicId),+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+/*** `AgentRuntimeDelegate.verifyShareRunStillAuthorized` implementation โ see* `AgentShareModel.isRunStillAuthorized`'s JSDoc for what "authorized" meansdiff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.tsindex 4ec30e835c6..7d26919ca29 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -2,6 +2,7 @@ import { isHeterogeneousAgentModelId, LOADING_FLAT } from '@lobechat/const';import type { LobeChatDatabase } from '@lobechat/database';import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';import type {+ AgentSenderMetadata,ChatAudioItem,ChatFileItem,ChatTopicMetadata,@@ -331,6 +332,12 @@ const resolveRunAttachments = async (export interface TurnSetupInput {agentConfig: AgentConfigWithId;+ /**+ * Sending agent of an agent โ agent turn, resolved to a snapshot before this+ * stage runs. Stamped onto the user message as `metadata.agentSender` so the+ * receiving topic attributes the turn to that agent, not the human owner.+ */+ agentSender?: AgentSenderMetadata;agentSlug?: string | null;appContext?: InternalExecAgentParams['appContext'];assistantAgentId: string;@@ -396,6 +403,7 @@ export interface TurnSetupResult {requestedDeviceId?: string;requestTriggerMetadata: {agentDispatch?: { kind: 'callAgent'; visibility: 'internal' };+ agentSender?: AgentSenderMetadata;steer?: true;trigger?: RequestTrigger;};@@ -430,6 +438,7 @@ export const setupTurn = async (const {agentConfig,agentSlug,+ agentSender,appContext,assistantAgentId,attachedFileIds,@@ -858,6 +867,7 @@ export const setupTurn = async (// โโ Shared turn setup (runs for BOTH hetero and normal agents) โโโโโโโโโโconst requestTriggerMetadata = buildUserTurnMetadata({+ agentSender,appContext,botSender,externalOrigin,diff --git a/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts b/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.tsindex e7f324c7b3b..84b48d95457 100644--- a/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts+++ b/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts@@ -1,8 +1,10 @@+import type { AgentSenderMetadata } from '@lobechat/types';import { RequestTrigger } from '@lobechat/types';import type { InternalExecAgentParams } from '../types';export interface UserTurnMetadataInput {+ agentSender?: AgentSenderMetadata;appContext?: InternalExecAgentParams['appContext'];botSender?: InternalExecAgentParams['botSender'];externalOrigin?: InternalExecAgentParams['externalOrigin'];@@ -17,6 +19,7 @@ export interface UserTurnMetadataInput {* ordinary chat turn stores no more than `trigger`.*/export const buildUserTurnMetadata = ({+ agentSender,appContext,botSender,externalOrigin,@@ -30,6 +33,10 @@ export const buildUserTurnMetadata = ({...(appContext?.conversationAgentId && appContext.scope === 'sub_agent'? { agentDispatch: { kind: 'callAgent' as const, visibility: 'internal' as const } }: undefined),+ // An agent โ agent turn (a sibling agent calling `lh agent run`). The row is+ // persisted in THIS topic under the human owner, so keep the sending agent+ // alongside โ the UI shows it as the author and links back to its topic.+ ...(agentSender ? { agentSender } : undefined),// Bot-channel turns are inserted under the OWNER's userId; keep the real// platform author alongside so the UI can attribute the bubble correctly....(botSender ? { botSender } : undefined),diff --git a/apps/server/src/services/aiAgent/sourceAttribution.test.ts b/apps/server/src/services/aiAgent/sourceAttribution.test.tsnew file mode 100644index 00000000000..abbbb9a9d3c--- /dev/null+++ b/apps/server/src/services/aiAgent/sourceAttribution.test.ts@@ -0,0 +1,392 @@+import type { AgentOperationStatus } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { resolveAgentSenderFromOperation } from './sourceAttribution';++const CALLER = 'user-1';++const buildDeps = (overrides?: {+ agentDisplay?: unknown;+ /**+ * Visibility per agent id โ a scalar for "everything is the same", a record+ * when the source and the destination differ.+ */+ agentVisibility?: 'private' | 'public' | Record<string, 'private' | 'public' | null>;+ /** Visibility per chat group id. */+ groupVisibility?: Record<string, 'private' | 'public' | null>;+ operation?:+ | null+ | undefined+ | {+ agentId?: null | string;+ chatGroupId?: null | string;+ status?: AgentOperationStatus;+ threadId?: null | string;+ topicId?: null | string;+ userId: string;+ workspaceId?: null | string;+ };+ topic?:+ | null+ | undefined+ | { agentId?: null | string; title?: null | string; workspaceId?: null | string };+ workspaceId?: string;+}) => ({+ destinationAgentId: 'agt-destination',+ findAgentDisplayFields: vi.fn().mockResolvedValue(overrides?.agentDisplay ?? undefined),+ findAgentVisibility: vi.fn().mockImplementation(async (agentId: string) => {+ const visibility = overrides?.agentVisibility;+ if (!visibility) return null;+ return typeof visibility === 'string' ? visibility : (visibility[agentId] ?? null);+ }),+ findChatGroupVisibility: vi+ .fn()+ .mockImplementation(+ async (chatGroupId: string) => overrides?.groupVisibility?.[chatGroupId] ?? null,+ ),+ findOperation: vi.fn().mockResolvedValue(+ overrides?.operation === undefined || overrides.operation === null+ ? null+ : // Default to an in-flight run so each case states only what it exercises.+ { status: 'running', ...overrides.operation },+ ),+ findTopic: vi.fn().mockResolvedValue(overrides?.topic === undefined ? null : overrides.topic),+ userId: CALLER,+ workspaceId: overrides?.workspaceId,+});++describe('resolveAgentSenderFromOperation', () => {+ it('stamps nothing without an operation id, and never reads the models', async () => {+ const deps = buildDeps();++ await expect(resolveAgentSenderFromOperation(undefined, deps)).resolves.toBeUndefined();+ expect(deps.findOperation).not.toHaveBeenCalled();+ expect(deps.findTopic).not.toHaveBeenCalled();+ });++ it('stamps nothing for an operation it cannot resolve', async () => {+ const deps = buildDeps({ operation: null });++ await expect(resolveAgentSenderFromOperation('op-unknown', deps)).resolves.toBeUndefined();+ expect(deps.findTopic).not.toHaveBeenCalled();+ });++ /**+ * The trust rule. `AgentOperationModel.findById` is workspace-scoped, so in a+ * workspace it also resolves a sibling member's operation โ the row's own+ * `userId` is what keeps a member from rendering arbitrary text as another+ * member's agent.+ */+ it("stamps nothing for a sibling member's operation in the same workspace", async () => {+ const deps = buildDeps({+ operation: { topicId: 'tpc-victim', userId: 'user-2' },+ topic: { agentId: 'agt-victim', title: 'Victim topic' },+ });++ await expect(resolveAgentSenderFromOperation('op-sibling', deps)).resolves.toBeUndefined();+ expect(deps.findTopic).not.toHaveBeenCalled();+ expect(deps.findAgentDisplayFields).not.toHaveBeenCalled();+ });++ it('stamps nothing when the operation has no topic', async () => {+ const deps = buildDeps({ operation: { topicId: null, userId: CALLER } });++ await expect(resolveAgentSenderFromOperation('op-no-topic', deps)).resolves.toBeUndefined();+ expect(deps.findTopic).not.toHaveBeenCalled();+ });++ it('stamps nothing when the topic is gone or has no owning agent', async () => {+ const missing = buildDeps({ operation: { topicId: 'tpc-1', userId: CALLER }, topic: null });+ await expect(resolveAgentSenderFromOperation('op-1', missing)).resolves.toBeUndefined();++ const orphans = buildDeps({+ operation: { topicId: 'tpc-1', userId: CALLER },+ topic: { agentId: null, title: 'Orphan topic' },+ });+ await expect(resolveAgentSenderFromOperation('op-1', orphans)).resolves.toBeUndefined();+ });++ /**+ * `LOBEHUB_OPERATION_ID` is an ambient env var: a shell, or a long-lived child+ * process, keeps it after its run finishes, and the public API can replay any+ * prior id. A settled run must therefore stop granting authorship.+ */+ it('carries the group and thread the launching turn actually ran in', async () => {+ const deps = buildDeps({+ operation: {+ agentId: 'agt-coco',+ chatGroupId: 'grp_1',+ threadId: 'thd_1',+ topicId: 'tpc-source',+ userId: CALLER,+ },+ topic: { agentId: 'agt-coco', title: 'Source' },+ });++ const result = await resolveAgentSenderFromOperation('op-1', deps);++ // The link is built from these: without them a group source opens the+ // supervisor's conversation and a thread source opens the main transcript.+ expect(result).toMatchObject({ chatGroupId: 'grp_1', threadId: 'thd_1' });+ });++ /**+ * A group topic may carry no owning agent (legacy or API-created rows) while+ * the operation still names the agent that ran โ the group route needs no topic+ * agent, so refusing outright would drop those launches.+ */+ it('attributes a group topic that carries no owning agent', async () => {+ const deps = buildDeps({+ operation: {+ agentId: 'agt-coco',+ chatGroupId: 'grp_1',+ topicId: 'tpc-group',+ userId: CALLER,+ },+ topic: { agentId: null, title: 'Group topic' },+ });++ await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toMatchObject({+ agentId: 'agt-coco',+ chatGroupId: 'grp_1',+ topicId: 'tpc-group',+ topicTitle: 'Group topic',+ });+ });++ it('still refuses a one-to-one topic that resolves no owning agent', async () => {+ // The agent route would be invalid, so there is no destination to offer.+ const deps = buildDeps({+ operation: { agentId: 'agt-coco', topicId: 'tpc-1', userId: CALLER },+ topic: { agentId: null, title: 'Orphan' },+ });++ await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toBeUndefined();+ });++ it('keeps the origin when the destination is personal', async () => {+ const deps = buildDeps({+ operation: { agentId: 'agt-coco', topicId: 'tpc-1', userId: CALLER },+ topic: { agentId: 'agt-coco', title: 'Private topic' },+ });++ await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toMatchObject({+ topicId: 'tpc-1',+ topicTitle: 'Private topic',+ });+ });++ it('keeps the origin when a shared destination can read the source too', async () => {+ const deps = buildDeps({+ agentVisibility: { 'agt-coco': 'public', 'agt-destination': 'public' },+ operation: { agentId: 'agt-coco', topicId: 'tpc-1', userId: CALLER, workspaceId: 'ws_1' },+ topic: { agentId: 'agt-coco', title: 'Shared topic', workspaceId: 'ws_1' },+ workspaceId: 'ws_1',+ });++ await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toMatchObject({+ topicId: 'tpc-1',+ topicTitle: 'Shared topic',+ });+ });++ /**+ * The leak this guards: a workspace-shared agent's bubble is readable by every+ * member, and a topic's name is frequently derived from the user's own prompt โ+ * so a private source must not be named there. The authorship stays.+ */+ it('drops the origin when a shared destination cannot read the private source', async () => {+ const deps = buildDeps({+ agentVisibility: { 'agt-coco': 'private', 'agt-destination': 'public' },+ operation: { agentId: 'agt-coco', topicId: 'tpc-1', userId: CALLER, workspaceId: 'ws_1' },+ topic: { agentId: 'agt-coco', title: 'Private prompt title', workspaceId: 'ws_1' },+ workspaceId: 'ws_1',+ });++ const result = await resolveAgentSenderFromOperation('op-1', deps);++ expect(result).toMatchObject({ agentId: 'agt-coco' });+ expect(result?.topicId).toBeUndefined();+ expect(result?.topicTitle).toBeUndefined();+ });++ /**+ * The executing agent is not who can read the source: a public `callSubAgent`+ * child runs on its private parent's topic, and the link opens the parent's+ * conversation โ so the parent's visibility decides.+ */+ it("drops the origin when a public child runs on a private parent's topic", async () => {+ const deps = buildDeps({+ agentVisibility: {+ 'agt-child': 'public',+ 'agt-destination': 'public',+ 'agt-parent': 'private',+ },+ operation: { agentId: 'agt-child', topicId: 'tpc-1', userId: CALLER, workspaceId: 'ws_1' },+ topic: { agentId: 'agt-parent', title: 'Private parent topic', workspaceId: 'ws_1' },+ workspaceId: 'ws_1',+ });++ const result = await resolveAgentSenderFromOperation('op-1', deps);++ expect(result).toMatchObject({ agentId: 'agt-child' });+ expect(result?.topicId).toBeUndefined();+ expect(result?.topicTitle).toBeUndefined();+ });++ it('drops the origin when a public member runs inside a private group', async () => {+ const deps = buildDeps({+ agentVisibility: 'public',+ groupVisibility: { 'grp-1': 'private' },+ operation: {+ agentId: 'agt-coco',+ chatGroupId: 'grp-1',+ topicId: 'tpc-1',+ userId: CALLER,+ workspaceId: 'ws_1',+ },+ topic: { agentId: 'agt-coco', title: 'Private group topic', workspaceId: 'ws_1' },+ workspaceId: 'ws_1',+ });++ const result = await resolveAgentSenderFromOperation('op-1', deps);++ expect(result).toMatchObject({ agentId: 'agt-coco', chatGroupId: 'grp-1' });+ expect(result?.topicId).toBeUndefined();+ expect(result?.topicTitle).toBeUndefined();+ });++ it('keeps the origin of a public group even when its topic has no owning agent', async () => {+ const deps = buildDeps({+ agentVisibility: { 'agt-destination': 'public' },+ groupVisibility: { 'grp-1': 'public' },+ operation: {+ agentId: 'agt-coco',+ chatGroupId: 'grp-1',+ topicId: 'tpc-1',+ userId: CALLER,+ workspaceId: 'ws_1',+ },+ topic: { agentId: null, title: 'Group topic', workspaceId: 'ws_1' },+ workspaceId: 'ws_1',+ });++ await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toMatchObject({+ topicId: 'tpc-1',+ topicTitle: 'Group topic',+ });+ expect(deps.findChatGroupVisibility).toHaveBeenCalledWith('grp-1');+ });++ it("drops the origin when the source lives outside the destination's workspace", async () => {+ const deps = buildDeps({+ agentVisibility: 'public',+ operation: { agentId: 'agt-coco', topicId: 'tpc-1', userId: CALLER, workspaceId: null },+ topic: { agentId: 'agt-coco', title: 'Personal topic', workspaceId: null },+ workspaceId: 'ws_1',+ });++ await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toMatchObject({+ agentId: 'agt-coco',+ topicId: undefined,+ topicTitle: undefined,+ });+ });++ it('stamps nothing for an operation that has already settled', async () => {+ for (const status of ['abandoned', 'done', 'error', 'interrupted'] as const) {+ const deps = buildDeps({+ operation: { agentId: 'agt-coco', status, topicId: 'tpc-source', userId: CALLER },+ topic: { agentId: 'agt-coco', title: 'Source' },+ });++ await expect(resolveAgentSenderFromOperation('op-settled', deps)).resolves.toBeUndefined();+ expect(deps.findTopic).not.toHaveBeenCalled();+ }+ });++ it('still attributes an operation that is only waiting', async () => {+ for (const status of ['idle', 'waiting_for_human', 'waiting_for_async_tool'] as const) {+ const deps = buildDeps({+ operation: { agentId: 'agt-coco', status, topicId: 'tpc-source', userId: CALLER },+ topic: { agentId: 'agt-coco', title: 'Source' },+ });++ await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toMatchObject({+ agentId: 'agt-coco',+ });+ }+ });++ it("reads the topic and agent from the caller's own operation row", async () => {+ const deps = buildDeps({+ agentDisplay: { avatar: '๐ถ', name: 'Coco', title: 'Product Assistant' },+ operation: { agentId: 'agt-coco', topicId: 'tpc-source', userId: CALLER },+ topic: { agentId: 'agt-coco', title: 'ๅธฎๆ่ฏไผฐๆฌๅจๅๅธ็้ฃ้ฉ' },+ });++ await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toEqual({+ agentId: 'agt-coco',+ avatar: '๐ถ',+ name: 'Coco',+ title: 'Product Assistant',+ topicAgentId: 'agt-coco',+ topicId: 'tpc-source',+ topicTitle: 'ๅธฎๆ่ฏไผฐๆฌๅจๅๅธ็้ฃ้ฉ',+ });+ expect(deps.findTopic).toHaveBeenCalledWith('tpc-source');+ });++ /**+ * A heterogeneous `callSubAgent` child executes in an isolation thread on its+ * SPAWNER's topic, so the operation's agent and the topic's owner differ. The+ * child sent the turn; the parent owns the conversation the link points at.+ */+ it("attributes a sub-agent child, and links back to the topic's own agent", async () => {+ const deps = buildDeps({+ agentDisplay: { avatar: '๐ค', name: 'Release Bot', title: 'Release Bot' },+ operation: { agentId: 'agt-child', topicId: 'tpc-parent', userId: CALLER },+ topic: { agentId: 'agt-parent', title: 'Parent thread' },+ });++ await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toEqual({+ agentId: 'agt-child',+ avatar: '๐ค',+ name: 'Release Bot',+ title: 'Release Bot',+ topicAgentId: 'agt-parent',+ topicId: 'tpc-parent',+ topicTitle: 'Parent thread',+ });+ expect(deps.findAgentDisplayFields).toHaveBeenCalledWith('agt-child');+ });++ it("falls back to the topic's owner when the operation names no agent", async () => {+ const deps = buildDeps({+ operation: { agentId: null, topicId: 'tpc-source', userId: CALLER },+ topic: { agentId: 'agt-coco', title: 'Source' },+ });++ await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toEqual({+ agentId: 'agt-coco',+ topicAgentId: 'agt-coco',+ topicId: 'tpc-source',+ topicTitle: 'Source',+ });+ });++ it('degrades to the bare ids when the sender config cannot be read', async () => {+ const deps = buildDeps({+ operation: { agentId: 'agt-coco', topicId: 'tpc-source', userId: CALLER },+ topic: { agentId: 'agt-coco', title: 'Source' },+ });+ deps.findAgentDisplayFields.mockRejectedValue(new Error('agent deleted'));++ await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toEqual({+ agentId: 'agt-coco',+ topicAgentId: 'agt-coco',+ topicId: 'tpc-source',+ topicTitle: 'Source',+ });+ });+});diff --git a/apps/server/src/services/aiAgent/sourceAttribution.ts b/apps/server/src/services/aiAgent/sourceAttribution.tsnew file mode 100644index 00000000000..6851ec31ed3--- /dev/null+++ b/apps/server/src/services/aiAgent/sourceAttribution.ts@@ -0,0 +1,176 @@+import type { AgentOperationStatus, AgentSenderMetadata } from '@lobechat/types';+import { isAgentOperationInFlight } from '@lobechat/types';+import debug from 'debug';++const log = debug('lobe-server:ai-agent-source-attribution');++/** The slice of an `agent_operations` row this decision reads. */+export interface SourceOperationRow {+ /** The agent that RAN the operation โ the sender, which is not always the topic's owner. */+ agentId?: null | string;+ /** Set when the turn ran in a group conversation rather than a one-to-one topic. */+ chatGroupId?: null | string;+ status?: AgentOperationStatus | null;+ /** Set when the turn ran inside a thread; the link reopens it. */+ threadId?: null | string;+ topicId?: null | string;+ userId: string;+ workspaceId?: null | string;+}++/** The slice of a `topics` row this decision reads. */+export interface SourceTopicRow {+ agentId?: null | string;+ title?: null | string;+ workspaceId?: null | string;+}++/** The slice of the sending agent's row that is snapshotted for display. */+export interface SourceAgentDisplayRow {+ avatar?: null | string;+ name?: null | string;+ title?: null | string;+}++export interface SourceAttributionDeps {+ /** The agent whose conversation will host the message. */+ destinationAgentId: string;+ findAgentDisplayFields: (agentId: string) => Promise<SourceAgentDisplayRow | null | undefined>;+ findAgentVisibility: (agentId: string) => Promise<'private' | 'public' | null>;+ findChatGroupVisibility: (chatGroupId: string) => Promise<'private' | 'public' | null>;+ findOperation: (operationId: string) => Promise<null | SourceOperationRow | undefined>;+ findTopic: (topicId: string) => Promise<null | SourceTopicRow | undefined>;+ /** The authenticated caller โ attribution may only rest on THEIR OWN work. */+ userId: string;+ /** The caller's active workspace; undefined in personal scope. */+ workspaceId?: string;+}++/**+ * Whether the source conversation may be named (and linked) in the destination+ * bubble.+ *+ * A workspace-shared agent's conversation is readable by every member; a private+ * one only by its owner, who is the caller. So the origin is snapshotted only+ * when the same people can open it โ otherwise a private topic's name, which is+ * frequently derived from the user's own prompt, lands in a conversation other+ * members read. The authorship itself is never dropped; the inaccessible origin+ * is.+ */+const isSourceShareableWithDestination = async (+ deps: Pick<+ SourceAttributionDeps,+ 'destinationAgentId' | 'findAgentVisibility' | 'findChatGroupVisibility' | 'workspaceId'+ >,+ source: { chatGroupId?: string; sourceWorkspaceId: null | string; topicAgentId?: string },+): Promise<boolean> => {+ const destinationVisibility = await deps.findAgentVisibility(deps.destinationAgentId);+ const sharedDestination = Boolean(deps.workspaceId) && destinationVisibility === 'public';+ // Personal scope: the bubble is readable by the caller alone, who ran the source.+ if (!sharedDestination) return true;+ if (source.sourceWorkspaceId !== deps.workspaceId) return false;++ // Who can read the source is decided by the conversation the link opens, not+ // by the agent that ran: a group route is the group's, an agent route is the+ // topic owner's. A public `callSubAgent` child on a private parent's topic, or+ // a public member inside a private group, must not make that origin shareable.+ let sourceVisibility: 'private' | 'public' | null = null;+ if (source.chatGroupId) {+ sourceVisibility = await deps.findChatGroupVisibility(source.chatGroupId);+ } else if (source.topicAgentId) {+ sourceVisibility = await deps.findAgentVisibility(source.topicAgentId);+ }++ return sourceVisibility === 'public';+};++/**+ * Resolve the agent that launched an agent โ agent run into the snapshot the UI+ * renders as the message author (`metadata.agentSender`).+ *+ * The caller names only the **operation** its launcher's run belongs to+ * (the ambient `LOBEHUB_OPERATION_ID`), never a topic and never an agent: both+ * are read from the operation row **the server wrote itself**, so a caller+ * cannot point the attribution at a conversation it had nothing to do with.+ *+ * The author is the operation's agent, and the topic's owner is carried+ * alongside it for the jump-back link โ the two differ for a heterogeneous+ * `callSubAgent` child, which runs on its spawner's topic.+ *+ * The row must belong to the caller, and must still be in flight. `findById` is+ * workspace-scoped, so in a workspace it also returns a *sibling member's*+ * operation โ without the ownership check, any member holding `message:create`+ * could render arbitrary text as another member's agent. Ownership alone is not+ * enough either: the operation id travels as an ambient env var and can be+ * replayed, so a settled run must stop granting attribution.+ *+ * Attribution is display-only, so an unknown operation, a missing topic, or a+ * since-deleted agent degrades to "no attribution" rather than failing a run+ * that is otherwise perfectly valid.+ */+export const resolveAgentSenderFromOperation = async (+ sourceOperationId: string | undefined,+ deps: SourceAttributionDeps,+): Promise<AgentSenderMetadata | undefined> => {+ if (!sourceOperationId) return undefined;++ const operation = await deps.findOperation(sourceOperationId);+ if (!operation || operation.userId !== deps.userId || !operation.topicId) return undefined;+ // The claim has to be CURRENT, not merely owned. `LOBEHUB_OPERATION_ID` is an+ // env var: a shell or a long-lived child process keeps it after its run+ // finishes, so without this a later human-issued `lh agent run` โ or a replay+ // of any prior operation id through the public API โ would still render as+ // authored by that run's agent.+ if (!operation.status || !isAgentOperationInFlight(operation.status)) return undefined;++ const topic = await deps.findTopic(operation.topicId);+ // A group topic may legitimately have no owning agent (legacy or API-created+ // rows) while the operation still names the agent that ran. The group route+ // needs no topic agent, so only a one-to-one topic has to resolve one.+ if (!operation.chatGroupId && !topic?.agentId) return undefined;++ // The AUTHOR is whoever ran the operation, which is not always the topic's+ // owner: a heterogeneous `callSubAgent` child executes in an isolation thread+ // on its SPAWNER's topic, so the child sends while the topic belongs to the+ // parent. The topic's owner is kept separately, because the jump-back link has+ // to target the conversation the topic actually lives in.+ const senderAgentId = operation.agentId ?? topic?.agentId;+ if (!senderAgentId) return undefined;++ // The source may be private while the destination is workspace-shared: the+ // topic's name is often prompt-derived, so snapshotting it into a bubble every+ // member can read would leak the source to people who cannot open it. Keep the+ // authorship, drop the origin they have no access to.+ const shareable = await isSourceShareableWithDestination(deps, {+ chatGroupId: operation.chatGroupId ?? undefined,+ sourceWorkspaceId: topic?.workspaceId ?? operation.workspaceId ?? null,+ topicAgentId: topic?.agentId ?? undefined,+ });++ const base: AgentSenderMetadata = {+ agentId: senderAgentId,+ // Group and thread are where the turn actually happened: without them the+ // jump-back opens the agent's own topic instead of the group, or the topic's+ // main transcript instead of the thread.+ chatGroupId: operation.chatGroupId ?? undefined,+ threadId: operation.threadId ?? undefined,+ topicAgentId: topic?.agentId ?? undefined,+ topicId: shareable ? operation.topicId : undefined,+ topicTitle: shareable ? (topic?.title ?? undefined) : undefined,+ };++ try {+ const config = await deps.findAgentDisplayFields(senderAgentId);+ if (!config) return base;++ return {+ ...base,+ avatar: config.avatar ?? undefined,+ name: config.name ?? undefined,+ title: config.title ?? undefined,+ };+ } catch (error) {+ log('failed to resolve source agent %s: %O', senderAgentId, error);+ return base;+ }+};diff --git a/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts b/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.tsindex 06eb917bde3..2d72db98c17 100644--- a/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts@@ -69,6 +69,29 @@ describe('preprocessLhCommand', () => {);});+ it('should hand the run its own operation id, so a sandbox dispatch can be attributed', async () => {+ const result = await preprocessLhCommand(+ 'lh agent run -a agt_123 -p hi',+ 'user-1',+ 'workspace-1',+ false,+ 'op-1',+ );++ expect(result.command).toBe(+ wrap(+ 'lh agent run -a agt_123 -p hi',+ " LOBEHUB_WORKSPACE_ID='workspace-1' LOBEHUB_OPERATION_ID='op-1'",+ ),+ );+ });++ it('should omit the operation id when the caller has no run context', async () => {+ const result = await preprocessLhCommand('lh topic list', 'user-1');++ expect(result.command).not.toContain('LOBEHUB_OPERATION_ID');+ });+it('should emit the JWT once regardless of how many lh calls the script makes', async () => {const cmd = 'lh topic list --page 1 && lh topic list --page 2 && echo "done"';const result = await preprocessLhCommand(cmd, 'user-1');diff --git a/apps/server/src/services/toolExecution/preprocessLhCommand.ts b/apps/server/src/services/toolExecution/preprocessLhCommand.tsindex 35601f4b9a3..604a5b5198d 100644--- a/apps/server/src/services/toolExecution/preprocessLhCommand.ts+++ b/apps/server/src/services/toolExecution/preprocessLhCommand.ts@@ -192,6 +192,14 @@ export const preprocessLhCommand = async (* remembering to keep re-checking it.*/shareVisitorBlocked = false,+ /**+ * The run this command belongs to (`context.operationId`). Every other runtime+ * hands its process its own `LOBEHUB_OPERATION_ID`; without it here, an agent+ * running in the sandbox that reaches another agent through `lh agent run`+ * cannot be attributed as the sender, and the feature silently works only on+ * the device and heterogeneous runtimes.+ */+ operationId?: string,): Promise<PreprocessResult> => {if (!isLhCommand(command)) {return { command, isLhCommand: false, skipSkillLookup: false };@@ -223,6 +231,7 @@ export const preprocessLhCommand = async (`LOBEHUB_JWT=${shellSingleQuote(jwt)}`,`LOBEHUB_SERVER=${shellSingleQuote(serverUrl)}`,...(workspaceId ? [`LOBEHUB_WORKSPACE_ID=${shellSingleQuote(workspaceId)}`] : []),+ ...(operationId ? [`LOBEHUB_OPERATION_ID=${shellSingleQuote(operationId)}`] : []),].join(' ');const dir = `"$${LH_SHIM_DIR_VAR}"`;diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.tsindex 95d259d4632..03ebb4c3407 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts@@ -82,7 +82,11 @@ describe('cloudSandboxRuntime', () => {});const { cloudSandboxRuntime } = await import('../cloudSandbox');- const runtime = await cloudSandboxRuntime.factory(buildContext({ workspaceId: 'ws-42' }));+ const runtime = await cloudSandboxRuntime.factory(+ // The run's own id travels too, so an `lh agent run` from here can be+ // attributed to the agent that launched it.+ buildContext({ operationId: 'op-x', workspaceId: 'ws-42' }),+ );await runtime.runCommand({ command: 'lh agent edit agt_1 -t x', description: 'edit self' });@@ -91,6 +95,7 @@ describe('cloudSandboxRuntime', () => {'user-1','ws-42',false,+ 'op-x',);expect(mocks.sandboxService.callTool).toHaveBeenCalledWith('runCommand',@@ -176,7 +181,13 @@ describe('cloudSandboxRuntime', () => {const command = "echo 'the lh CLI is unavailable here'";await runtime.runCommand({ command, description: 'echo' });- expect(mocks.preprocessLhCommand).toHaveBeenCalledWith(command, 'user-1', undefined, true);+ expect(mocks.preprocessLhCommand).toHaveBeenCalledWith(+ command,+ 'user-1',+ undefined,+ true,+ undefined,+ );expect(mocks.sandboxService.callTool).toHaveBeenCalledWith('runCommand',expect.objectContaining({ command }),@@ -196,7 +207,13 @@ describe('cloudSandboxRuntime', () => {await runtime.runCommand({ command: 'ls -la', description: 'list files' });- expect(mocks.preprocessLhCommand).toHaveBeenCalledWith('ls -la', 'user-1', undefined, true);+ expect(mocks.preprocessLhCommand).toHaveBeenCalledWith(+ 'ls -la',+ 'user-1',+ undefined,+ true,+ undefined,+ );expect(mocks.sandboxService.callTool).toHaveBeenCalledWith('runCommand',expect.objectContaining({ command: 'ls -la' }),diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.tsindex 94954323424..bf2eeb0736c 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts@@ -419,6 +419,8 @@ describe('skillsRuntime', () => {'user-1','workspace-1',false,+ // These runtimes carry no run context, so there is no operation to forward.+ undefined,);expect(mocks.sandboxService.callTool).toHaveBeenCalledWith('runCommand', {command: 'LOBEHUB_WORKSPACE_ID=workspace-1 npx -y @lobehub/cli agent edit agt_123',@@ -453,6 +455,8 @@ describe('skillsRuntime', () => {'user-1','workspace-1',false,+ // These runtimes carry no run context, so there is no operation to forward.+ undefined,);});@@ -460,6 +464,38 @@ describe('skillsRuntime', () => {// execScript too; on Cloud, where gateway mode routes through this runtime// instead, `lh` inside execScript reached the sandbox raw โ no CLI, no// credentials, no workspace scope.+ it('forwards the run operation id so a sandbox dispatch can be attributed', async () => {+ mocks.preprocessLhCommand.mockResolvedValueOnce({+ command: 'lh agent run -a agt_123',+ isLhCommand: true,+ skipSkillLookup: true,+ });++ const { skillsRuntime } = await import('../skills');+ const runtime = await skillsRuntime.factory({+ operationId: 'op-abc',+ serverDB: {} as never,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ workspaceId: 'workspace-1',+ });++ await runtime.execScript({+ activatedSkills: [],+ command: 'lh agent run -a agt_123',+ description: 'Delegate',+ });++ expect(mocks.preprocessLhCommand).toHaveBeenCalledWith(+ 'lh agent run -a agt_123',+ 'user-1',+ 'workspace-1',+ false,+ 'op-abc',+ );+ });+it('preprocesses lh commands passed to execScript, not just runCommand', async () => {mocks.preprocessLhCommand.mockResolvedValueOnce({command:@@ -488,6 +524,9 @@ describe('skillsRuntime', () => {'user-1','workspace-1',false,+ // No run context here, so there is no operation for a dispatch to be+ // attributed to.+ undefined,);expect(mocks.sandboxService.callTool).toHaveBeenCalledWith('execScript',diff --git a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.tsindex 81e2c90474d..ae55249273a 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts@@ -41,6 +41,8 @@ const SHELL_TOOL_NAMES = new Set(['execScript', 'runCommand']);const withLhPreprocessing = (service: ISandboxService,resolve: {+ /** This run's operation, so an `lh agent run` from here is attributed to its agent. */+ operationId: string | undefined;userId: string;/** Raw context workspace id, log-only โ cheap to read, unlike {@link resolveContentWorkspaceId}. */workspaceIdHint: string | undefined;@@ -86,6 +88,7 @@ const withLhPreprocessing = (resolve.userId,workspaceId,resolve.isShareVisitor,+ resolve.operationId,);if (result.error) {@@ -173,6 +176,7 @@ export const cloudSandboxRuntime: ServerRuntimeRegistration = {return new CloudSandboxExecutionRuntime(withLhPreprocessing(sandboxService, {isShareVisitor: Boolean(context.agentShareVisitor),+ operationId: context.operationId,userId: context.userId,workspaceId: async () => workspaceId,workspaceIdHint: workspaceId,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.tsindex 51c65c97f09..e291b920f22 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts@@ -149,6 +149,12 @@ class SkillServerRuntimeService implements SkillRuntimeService {private fileModel: FileModel;private serverDB: LobeChatDatabase;private topicId?: string;+ /**+ * The run this runtime belongs to. Handed to `preprocessLhCommand` so a+ * sandbox `lh agent run` carries `LOBEHUB_OPERATION_ID`, exactly as the device+ * and heterogeneous runtimes do.+ */+ private operationId?: string;private userId: string;private workspaceId?: string;private sandboxCwd?: string;@@ -180,6 +186,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {*/isSkillGranted?: (identifier: string) => boolean;marketService: MarketService;+ operationId?: string;resourceService: SkillResourceService;/*** Persistence for this run, resolved once by the factory. Every sandbox@@ -209,6 +216,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {this.fileModel = options.fileModel;this.serverDB = options.serverDB;this.topicId = options.topicId;+ this.operationId = options.operationId;this.userId = options.userId;this.workspaceId = options.workspaceId;this.sandboxCwd = options.sandboxCwd;@@ -293,6 +301,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {this.userId,workspaceId,this.shareVisitorBlocked,+ this.operationId,);return { command: result.command, error: result.error };@@ -943,6 +952,10 @@ export const skillsRuntime: ServerRuntimeRegistration = {fileService,isSkillGranted,marketService,+ // The run this runtime belongs to, so an `lh agent run` it preprocesses in+ // the cloud sandbox can be attributed to the agent that launched it โ the+ // device branch below carries the same id for its own routing.+ operationId: context.operationId,resourceService,sandboxCwd: sandbox.cwd,sandboxInstanceId: sandbox.environment,diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 00e7a2cdae0..ab09642c0fc 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -44,6 +44,7 @@"agentProfile.runtime": "Runs on {{name}}","agentProfile.skills_one": "{{count}} skill","agentProfile.skills_other": "{{count}} skills",+ "agentSender.sourceTopic": "Source topic","agentSignal.receipts.agentSignalLabel": "Agent Signal","agentSignal.receipts.memory.detail": "Saved this for future replies","agentSignal.receipts.memory.openInMemory": "Open in Memory",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 4486c213a86..d7ba395078a 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -44,6 +44,7 @@"agentProfile.runtime": "่ฟ่กๆถ๏ผ{{name}}","agentProfile.skills_one": "{{count}} ้กนๆ่ฝ","agentProfile.skills_other": "{{count}} ้กนๆ่ฝ",+ "agentSender.sourceTopic": "ๆบ่ฏ้ข","agentSignal.receipts.agentSignalLabel": "ไปฃ็ไฟกๅท","agentSignal.receipts.memory.detail": "ๅทฒไฟๅญไปฅไพๆชๆฅๅๅคไฝฟ็จ","agentSignal.receipts.memory.openInMemory": "ๅจ่ฎฐๅฟไธญๆๅผ",diff --git a/packages/database/src/models/__tests__/agent.getDisplayFields.test.ts b/packages/database/src/models/__tests__/agent.getDisplayFields.test.tsnew file mode 100644index 00000000000..d3aca43adcf--- /dev/null+++ b/packages/database/src/models/__tests__/agent.getDisplayFields.test.ts@@ -0,0 +1,63 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { agents, users } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { AgentModel } from '../agent';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'display-fields-user-id';+const userId2 = 'display-fields-user-id-2';++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: userId2 }]);+});++afterEach(async () => {+ await serverDB.delete(users);+});++describe('AgentModel.getAgentDisplayFields', () => {+ it('projects only the three display fields', async () => {+ await serverDB.insert(agents).values({+ avatar: '๐ถ',+ description: 'Should not be returned',+ id: 'agent-display',+ name: 'Coco',+ slug: 'agent-display',+ title: 'Product Assistant',+ userId,+ });++ const model = new AgentModel(serverDB, userId);+ const result = await model.getAgentDisplayFields('agent-display');++ // The point of the projection: a sender label must not drag the agent's+ // knowledge and file contents through `getAgentConfigById`.+ expect(result).toEqual({ avatar: '๐ถ', name: 'Coco', title: 'Product Assistant' });+ });++ it('returns null for a missing agent', async () => {+ const model = new AgentModel(serverDB, userId);++ await expect(model.getAgentDisplayFields('agent-nope')).resolves.toBeNull();+ });++ it("returns null for an agent outside the caller's scope", async () => {+ await serverDB.insert(agents).values({+ avatar: '๐ป',+ id: 'agent-other',+ name: 'Other',+ slug: 'agent-other',+ title: 'Other',+ userId: userId2,+ });++ const model = new AgentModel(serverDB, userId);++ await expect(model.getAgentDisplayFields('agent-other')).resolves.toBeNull();+ });+});diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex 9023d9cc27e..c3a2dc7cb8b 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -563,6 +563,28 @@ export class AgentModel {return this.enrichAgentWithKnowledge(agent);};+ /**+ * The three fields a sender-identity snapshot needs, projected and scoped by+ * the model's ownership filter, or `null` when the agent is missing or not+ * visible to the current caller.+ *+ * Deliberately not {@link getAgentConfigById}: that one enriches the agent+ * with its assigned knowledge and loads every enabled file's row and content,+ * which is a lot of I/O to render a label. Callers that only display who an+ * agent is โ attribution, receipts โ should use this.+ */+ getAgentDisplayFields = async (+ id: string,+ ): Promise<{ avatar: null | string; name: null | string; title: null | string } | null> => {+ const rows = await this.db+ .select({ avatar: agents.avatar, name: agents.name, title: agents.title })+ .from(agents)+ .where(and(eq(agents.id, id), this.ownership()))+ .limit(1);++ return rows[0] ?? null;+ };+/*** Returns the agent's visibility, scoped by the model's ownership filter, or* `null` when the agent is missing or not visible to the current caller.diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 62bfd53297c..48b2794d1e4 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -245,6 +245,7 @@ export default {'agentProfile.runtime': 'Runs on {{name}}','agentProfile.skills_one': '{{count}} skill','agentProfile.skills_other': '{{count}} skills',+ 'agentSender.sourceTopic': 'Source topic','agentSignal.receipts.agentSignalLabel': 'Agent Signal','agentSignal.receipts.memory.detail': 'Saved this for future replies','agentSignal.receipts.memory.openInMemory': 'Open in Memory',diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex aea83d11e32..67cadf1cf3f 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -368,6 +368,20 @@ export interface ExecAgentParams {replacesOperationId?: string;/** The agent slug to run (either agentId or slug is required) */slug?: string;+ /**+ * The operation the launcher's run belongs to, when another agent started this+ * run. Every runtime hands its process its own `LOBEHUB_OPERATION_ID` but+ * deliberately strips the launcher's agent id (device-dispatched runs), so the+ * operation is the one identifier that survives every path. The server reads+ * the topic and the agent from that operation row โ its own record, and one+ * that must belong to the caller โ and stamps `metadata.agentSender` on the+ * created user message.+ *+ * Deliberately not a topic id: a topic is a bare client claim no server row+ * can vouch for, whereas the operation's topic and agent are written by the+ * server itself.+ */+ sourceOperationId?: string;/*** User agent of the originating request, captured server-side for run* attribution. Propagated into the run's `state.metadata` and downstreamdiff --git a/packages/types/src/aiChat.test.ts b/packages/types/src/aiChat.test.tsindex 0c4dfc702ac..cadb300aea5 100644--- a/packages/types/src/aiChat.test.ts+++ b/packages/types/src/aiChat.test.ts@@ -61,4 +61,17 @@ describe('AiSendMessageServerSchema', () => {expect(parse({ newTopic: { id: 'msg_aBc123XyZ890' } }).success).toBe(false);});});++ it('should drop client-supplied agentSender from every message it creates', () => {+ const forged = { agentSender: { agentId: 'agt_victim' }, collapsed: true };+ const parsed = AiSendMessageServerSchema.parse({+ newAssistantMessage: { metadata: forged, model: 'gpt-4o', provider: 'openai' },+ newUserMessage: { content: 'hello', metadata: forged },+ preloadMessages: [{ content: 'earlier', metadata: forged, role: 'assistant' }],+ });++ expect(parsed.newUserMessage.metadata).toEqual({ collapsed: true });+ expect(parsed.newAssistantMessage.metadata).toEqual({ collapsed: true });+ expect(parsed.preloadMessages?.[0].metadata).toEqual({ collapsed: true });+ });});diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.tsindex f7965e1c0e4..f1fcac1305b 100644--- a/packages/types/src/aiChat.ts+++ b/packages/types/src/aiChat.ts@@ -3,7 +3,11 @@ import { z } from 'zod';import { type ClientAllocatableEntity, entityIdPattern } from './entityId';import type { UIChatMessage } from './message';import type { MessageMetadata } from './message/common';-import { ChatToolPayloadSchema, MessageMetadataSchema } from './message/common';+import {+ ChatToolPayloadSchema,+ ClientMessageMetadataSchema,+ omitServerOwnedMessageMetadata,+} from './message/common';import type { ContextSelection, CreateMessageParams, PageSelection } from './message/ui/params';import { ContextSelectionSchema, PageSelectionSchema } from './message/ui/params';import type { OpenAIChatMessage } from './openai/chat';@@ -137,7 +141,7 @@ export const CreateThreadWithMessageSchema = z.object({const SendPreloadMessageSchema = z.object({content: z.string(),- metadata: MessageMetadataSchema.optional(),+ metadata: ClientMessageMetadataSchema.optional(),plugin: z.object({apiName: z.string(),@@ -172,7 +176,10 @@ export const AiSendMessageServerSchema = z.object({newAssistantMessage: z.object({agentId: z.string().optional(),id: clientEntityId('messages'),- metadata: z.record(z.string(), z.unknown()).optional(),+ metadata: z+ .record(z.string(), z.unknown())+ .optional()+ .transform(omitServerOwnedMessageMetadata),model: z.string().optional(),provider: z.string().optional(),}),@@ -195,7 +202,7 @@ export const AiSendMessageServerSchema = z.object({editorData: z.record(z.string(), z.unknown()).optional(),files: z.array(z.string()).optional(),id: clientEntityId('messages'),- metadata: MessageMetadataSchema.optional(),+ metadata: ClientMessageMetadataSchema.optional(),pageSelections: z.array(PageSelectionSchema).optional(),parentId: z.string().optional(),}),diff --git a/packages/types/src/message/common/metadata.test.ts b/packages/types/src/message/common/metadata.test.tsindex ccec3217140..5cabb7f15ea 100644--- a/packages/types/src/message/common/metadata.test.ts+++ b/packages/types/src/message/common/metadata.test.ts@@ -1,7 +1,12 @@import { describe, expect, it } from 'vitest';import { RequestTrigger } from '../../agentRuntime';-import { MessageMetadataSchema } from './metadata';+import { UpdateMessageParamsSchema } from '../db/params';+import {+ ClientMessageMetadataSchema,+ MessageMetadataSchema,+ omitServerOwnedMessageMetadata,+} from './metadata';describe('MessageMetadataSchema', () => {it('preserves the native Codex turn separately from message item provenance', () => {@@ -62,4 +67,61 @@ describe('MessageMetadataSchema', () => {heterogeneousToolStateSeq: 4,});});++ it('preserves the agent sender block so an agent โ agent turn keeps its author', () => {+ const parsed = MessageMetadataSchema.parse({+ agentSender: {+ agentId: 'agt_coco',+ avatar: 'https://a.com/coco.png',+ name: 'Coco',+ title: 'Product Agent',+ topicId: 'tpc_source',+ topicTitle: 'Release risk review',+ },+ unknown: 'stripped',+ });++ expect(parsed).toEqual({+ agentSender: {+ agentId: 'agt_coco',+ avatar: 'https://a.com/coco.png',+ name: 'Coco',+ title: 'Product Agent',+ topicId: 'tpc_source',+ topicTitle: 'Release risk review',+ },+ });+ });+});++/**+ * `agentSender` renders a message as another agent's, so only the server may+ * write it โ a client must not be able to forge it through a message write.+ */+describe('client-writable message metadata', () => {+ const forged = { agentId: 'agt_victim', name: 'Victim Agent' };++ it('drops agentSender from client metadata and keeps the rest', () => {+ expect(ClientMessageMetadataSchema.parse({ agentSender: forged, collapsed: true })).toEqual({+ collapsed: true,+ });+ });++ it('drops agentSender from a message.update payload', () => {+ const parsed = UpdateMessageParamsSchema.parse({+ content: 'edited',+ metadata: { agentSender: forged, collapsed: true },+ });++ expect(parsed.metadata).toEqual({ collapsed: true });+ });++ it('drops agentSender from untyped metadata without touching other keys', () => {+ expect(omitServerOwnedMessageMetadata({ agentSender: forged, custom: 1 })).toEqual({+ custom: 1,+ });+ expect(omitServerOwnedMessageMetadata(undefined)).toBeUndefined();+ const clean = { custom: 1 };+ expect(omitServerOwnedMessageMetadata(clean)).toBe(clean);+ });});diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.tsindex 9fd1788e1c9..056c4712c87 100644--- a/packages/types/src/message/common/metadata.ts+++ b/packages/types/src/message/common/metadata.ts@@ -203,6 +203,70 @@ export interface AgentDispatchMetadata {visibility: 'internal';}+/**+ * The agent that authored a user turn on another agent's behalf (agent โ agent+ * dispatch: a sibling agent calling `lh agent run`). Such rows are persisted+ * inside the RECEIVING agent's conversation, where the joined `sender` is the+ * human owner โ so without this block the bubble reads as if the user typed it+ * themselves. The server reads it from the OPERATION that launched the run, and+ * the UI shows it as the author, using `topicAgentId` + `topicId` to jump back+ * to where the run was launched.+ */+export interface AgentSenderMetadata {+ /**+ * The agent that ran the launching turn โ the AUTHOR of this message. Taken+ * from the operation's own agent, which is not always the topic's owner: a+ * heterogeneous `callSubAgent` child executes in an isolation thread **on its+ * spawner's topic**, so the child sends while the topic belongs to the parent.+ */+ agentId: string;+ /** Sending agent's avatar at send time; snapshotted so a later delete can't blank the bubble. */+ avatar?: string;+ /**+ * The group conversation the launching turn ran in, when it ran in one rather+ * than in a one-to-one topic. A group's turns are routed under+ * `/group/<chatGroupId>/<topicId>`; the agent route would open the supervisor's+ * own conversation instead of the group the turn actually came from.+ */+ chatGroupId?: string;+ /** Sending agent's personal name at send time; resolve the label with `agentDisplayName`. */+ name?: string;+ /**+ * The thread the launching turn ran in, reopened with `?portalThread=<id>`.+ * Without it the link lands on the topic's main transcript, which is not where+ * the turn happened.+ */+ threadId?: string;+ /** Sending agent's role title at send time; the fallback label when it has no name. */+ title?: string;+ /**+ * The agent that OWNS `topicId`, when it is not `agentId`. The jump-back link+ * targets `/agent/<topicAgentId>/<topicId>` โ only the topic's own agent has+ * that conversation, so a sub-agent sender must not become the link's segment.+ */+ topicAgentId?: string;+ /** The topic the run was launched from, for jumping back. */+ topicId?: string;+ /**+ * The source topic's own name at send time. Snapshotted rather than looked up+ * because the source topic belongs to ANOTHER agent's conversation, so the+ * receiving side's topic list does not carry it.+ */+ topicTitle?: string;+}++export const AgentSenderMetadataSchema = z.object({+ agentId: z.string(),+ avatar: z.string().optional(),+ chatGroupId: z.string().optional(),+ name: z.string().optional(),+ threadId: z.string().optional(),+ title: z.string().optional(),+ topicAgentId: z.string().optional(),+ topicId: z.string().optional(),+ topicTitle: z.string().optional(),+});+/*** Where a server-injected user turn came from when no human typed it: a* provider event (GitHub CI failure, review feedback, โฆ) that woke the@@ -260,6 +324,7 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSchebotSender: BotSenderMetadataSchema.optional(),externalOrigin: ExternalOriginMetadataSchema.optional(),agentDispatch: AgentDispatchMetadataSchema.optional(),+ agentSender: AgentSenderMetadataSchema.optional(),collapsed: z.boolean().optional(),contextSelections: z.array(ContextSelectionSchema).optional(),// Hetero-agent (Claude Code) per-message provenance. Listed here so zod does@@ -307,6 +372,21 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceScheusage: ModelUsageSchema.optional(),});+/**+ * `agentSender` is written only by the server, from a verified source operation+ * (see `resolveAgentSenderFromOperation`), and the renderer trusts it over the+ * persisted human sender. A client-supplied copy would let any caller make a+ * message read as another agent's, so client-writable inputs drop it.+ */+export const ClientMessageMetadataSchema = MessageMetadataSchema.omit({ agentSender: true });++/** Drops server-owned blocks from metadata a client sent untyped (passthrough / record inputs). */+export const omitServerOwnedMessageMetadata = <T>(metadata: T): T => {+ if (!metadata || typeof metadata !== 'object' || !('agentSender' in metadata)) return metadata;+ const { agentSender: _agentSender, ...rest } = metadata as Record<string, unknown>;+ return rest as T;+};+export interface ModelUsage extends ModelTokensUsage {/*** dollar@@ -361,6 +441,10 @@ export interface MessageMetadata {* Renderers consume this marker instead of inferring intent from the message tree.*/agentDispatch?: AgentDispatchMetadata;+ /**+ * Sending agent of an agent โ agent turn; see `AgentSenderMetadata`.+ */+ agentSender?: AgentSenderMetadata;/*** Real platform author of a bot-channel user message; see `BotSenderMetadata`.*/diff --git a/packages/types/src/message/db/params.ts b/packages/types/src/message/db/params.tsindex cdfd9f40676..237b76bc878 100644--- a/packages/types/src/message/db/params.ts+++ b/packages/types/src/message/db/params.ts@@ -15,7 +15,7 @@ import {ChatImageItemSchema,ChatMessageErrorSchema,ChatToolPayloadSchema,- MessageMetadataSchema,+ ClientMessageMetadataSchema,MessageToolCallSchema,ModelReasoningSchema,ModelUsageSchema,@@ -150,7 +150,7 @@ export const UpdateMessageParamsSchema = zeditorData: z.record(z.string(), z.any()).nullish(),error: ChatMessageErrorSchema.nullish(),imageList: z.array(ChatImageItemSchema).optional(),- metadata: MessageMetadataSchema.optional(),+ metadata: ClientMessageMetadataSchema.optional(),model: z.string().optional(),observationId: z.string().optional(),provider: z.string().optional(),diff --git a/src/features/Conversation/ChatItem/ChatItem.tsx b/src/features/Conversation/ChatItem/ChatItem.tsxindex 1c5a3dbf48e..2e8b72a1835 100644--- a/src/features/Conversation/ChatItem/ChatItem.tsx+++ b/src/features/Conversation/ChatItem/ChatItem.tsx@@ -83,6 +83,12 @@ const ChatItem = memo<ChatItemProps>(className={'message-header'}direction={isUser ? 'horizontal-reverse' : 'horizontal'}gap={8}+ // The row wraps nothing, so without a cap it is sized by its content and+ // simply overflows its lane โ on a narrow viewport that is a header+ // wider than the conversation pane (the source-topic link, a long agent+ // name). Capped, the shrinkable addons yield to the space actually+ // available and truncate instead.+ style={{ maxInlineSize: '100%', minInlineSize: 0 }}>{showAvatar &&(customAvatarRender ? customAvatarRender(avatar, avatarContent) : avatarContent)}diff --git a/src/features/Conversation/Messages/CompressedGroup/CompressedMessageItem.tsx b/src/features/Conversation/Messages/CompressedGroup/CompressedMessageItem.tsxindex 2ef61a413bd..e535f6a304b 100644--- a/src/features/Conversation/Messages/CompressedGroup/CompressedMessageItem.tsx+++ b/src/features/Conversation/Messages/CompressedGroup/CompressedMessageItem.tsx@@ -14,7 +14,7 @@ import { useAgentMeta } from '../../hooks';import ContentBlock from '../AssistantGroup/components/ContentBlock';import Group from '../AssistantGroup/components/Group';import UserMessageContent from '../User/components/MessageContent';-import { getBotSender, resolveSenderIdentity } from '../User/resolveSenderIdentity';+import { resolveSenderIdentity } from '../User/resolveSenderIdentity';import { resolveCompressedMessageView } from './resolveCompressedMessageView';interface CompressedMessageItemProps {@@ -36,10 +36,13 @@ const CompressedMessageItem = memo<CompressedMessageItemProps>(({ message }) =>// Render user messageif (view === 'user') {// A shared (workspace) topic's compressed history may hold messages from- // other members โ render the sender's identity, not the viewer's.+ // other members โ render the sender's identity, not the viewer's. The+ // resolver reads the server-written blocks off the row itself, so this path+ // cannot drop one of them (an agent โ agent turn used to revert to the human+ // owner here).const { avatar, title } = resolveSenderIdentity({- botSender: getBotSender(message),currentUserId,+ message,selfAvatar: userAvatar,sender,unknownLabel: t('sender.unknownMember'),diff --git a/src/features/Conversation/Messages/User/components/AgentSenderSourceLink.tsx b/src/features/Conversation/Messages/User/components/AgentSenderSourceLink.tsxnew file mode 100644index 00000000000..8a5b6bd2715--- /dev/null+++ b/src/features/Conversation/Messages/User/components/AgentSenderSourceLink.tsx@@ -0,0 +1,110 @@+'use client';++import { createStaticStyles, Icon, Tooltip } from '@lobehub/ui';+import { Link2 } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { buildOperationSourcePath } from '@/features/Portal/Thread/sharePath';+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';++const styles = createStaticStyles(({ css, cssVar }) => ({+ link: css`+ display: inline-flex;++ /* Shrinkable, not fixed: the header is a non-wrapping flex row, so on a+ phone-width viewport the cap below plus the author name and avatar would+ overflow the row โ the inner ellipsis can only truncate a link that is+ allowed to shrink past its content. */+ flex: 0 1 auto;+ gap: 3px;+ align-items: center;++ min-inline-size: 0;+ max-inline-size: 320px;++ font-size: 12px;+ color: ${cssVar.colorTextTertiary};++ &:hover {+ color: ${cssVar.colorTextSecondary};+ }+ `,+ label: css`+ overflow: hidden;+ min-inline-size: 0;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));++interface AgentSenderSourceLinkProps {+ /**+ * The group conversation the turn ran in, when it ran in one. A group's turns+ * live under `/group/<chatGroupId>/<topicId>`; the agent route would open the+ * supervisor's own conversation instead.+ */+ chatGroupId?: string;+ /** The thread the turn ran in, reopened via `?portalThread=<threadId>`. */+ threadId?: string;+ /**+ * The agent that OWNS the source topic โ the link's `/agent/<id>/` segment when+ * the turn ran in a one-to-one topic. Not necessarily the sending agent: a+ * heterogeneous `callSubAgent` child runs on its spawner's topic, and only the+ * topic's own agent holds that conversation.+ */+ topicAgentId: string;+ /** The source topic id. */+ topicId: string;+ /**+ * The source topic's own name. Shown as the link label; the generic caption is+ * only the fallback for a topic that has none.+ */+ topicTitle?: string | null;+}++/**+ * Jump-back to the conversation an agent โ agent turn was launched from. Sits+ * before the sending agent's name so the authorship and its origin read as one+ * cluster.+ *+ * Labels itself with the topic's OWN name rather than a generic "source topic"+ * caption: the name is what tells a reader *which* conversation this came from,+ * and repeating a caption on every such message is chrome. The caption appears+ * on hover โ and is the label for an untitled topic โ so the affordance still+ * explains itself without occupying the row.+ *+ * The destination is the conversation the turn actually ran in, not merely its+ * topic: the group it belonged to, and the thread, when it ran in one.+ */+const AgentSenderSourceLink = memo<AgentSenderSourceLinkProps>(+ ({ chatGroupId, threadId, topicAgentId, topicId, topicTitle }) => {+ const { t } = useTranslation('chat');+ const caption = t('agentSender.sourceTopic');+ const name = topicTitle?.trim();++ const href = buildOperationSourcePath({+ agentId: topicAgentId,+ chatGroupId,+ threadId,+ topicId,+ });+ if (!href) return null;++ return (+ <Tooltip title={caption}>+ {/* `WorkspaceLink`, not the bare router `Link`: these routes are mirrored+ under `/:workspaceSlug`, so an unprefixed href would drop a workspace+ reader into their personal route and the source would not load. */}+ <WorkspaceLink className={styles.link} to={href}>+ <Icon icon={Link2} size={12} />+ <span className={styles.label}>{name || caption}</span>+ </WorkspaceLink>+ </Tooltip>+ );+ },+);++AgentSenderSourceLink.displayName = 'AgentSenderSourceLink';++export default AgentSenderSourceLink;diff --git a/src/features/Conversation/Messages/User/index.tsx b/src/features/Conversation/Messages/User/index.tsxindex 13714e741c1..46918e47561 100644--- a/src/features/Conversation/Messages/User/index.tsx+++ b/src/features/Conversation/Messages/User/index.tsx@@ -23,10 +23,11 @@ import {useSetMessageItemActionTypeContext,} from '../Contexts/message-action-context';import Actions from './Actions';+import AgentSenderSourceLink from './components/AgentSenderSourceLink';import UserMessageContent from './components/MessageContent';import { ScmEventAvatar, ScmEventSenderTitle } from './components/ScmEventSender';import { UserMessageExtra } from './Extra';-import { getBotSender, resolveSenderIdentity } from './resolveSenderIdentity';+import { getAgentSender, getBotSender, resolveSenderIdentity } from './resolveSenderIdentity';import ScheduledRunFooter from './ScheduledRunFooter';interface UserMessageProps {@@ -39,6 +40,10 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual)!;const { content, createdAt, error, role, extra, targetId, sender, metadata } = item;const botSender = getBotSender(item);+ // An agent โ agent turn (a sibling agent's `lh agent run`): the row belongs to+ // the receiving agent's topic, so the sending agent โ not the human owner โ+ // is who the bubble must be attributed to.+ const agentSender = getAgentSender(item);// A wake-up message from the SCM integration is authored by the pull// request, so GitHub takes the sender slot instead of the card's header.const scmSource = useMemo(() => getScmEventSource(content), [content]);@@ -54,12 +59,12 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {// hidden-avatar behavior. Self identity applies only to the viewer's own// rows โ see resolveSenderIdentity.// A bot-channel row is authored by someone else even in personal mode, so- // its sender is always shown.- const showSender = Boolean(activeWorkspaceId) || !!botSender || !!scmSource;+ // its sender is always shown. Same for an agent โ agent turn.+ const showSender = Boolean(activeWorkspaceId) || !!botSender || !!scmSource || !!agentSender;const currentUserId = useUserStore(userProfileSelectors.userId);const { avatar, title } = resolveSenderIdentity({- botSender,currentUserId,+ message: item,selfAvatar,selfTitle,sender,@@ -121,7 +126,6 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {showAvatar={showSender}showTitle={showSender && !scmSource}time={createdAt}- titleAddon={dmIndicator}actionAddon={commentCount > 0 && commentTopicId ? (<MessageCommentBadge count={commentCount} messageId={id} topicId={commentTopicId} />@@ -135,6 +139,27 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {</>) : undefined}+ titleAddon={+ // The row is `row-reverse` (right-aligned), so `headerAddon` renders on+ // the far side of the author name. The source link belongs on the near+ // side instead: the author name stays next to its own avatar, and the+ // topic it came from reads as a leading qualifier rather than splitting+ // the name from its avatar.+ dmIndicator || agentSender?.topicId ? (+ <>+ {dmIndicator}+ {agentSender?.topicId && (+ <AgentSenderSourceLink+ chatGroupId={agentSender.chatGroupId}+ threadId={agentSender.threadId}+ topicAgentId={agentSender.topicAgentId ?? agentSender.agentId}+ topicId={agentSender.topicId}+ topicTitle={agentSender.topicTitle}+ />+ )}+ </>+ ) : undefined+ }onDoubleClick={onDoubleClick}onMouseEnter={onMouseEnter}>diff --git a/src/features/Conversation/Messages/User/resolveSenderIdentity.test.ts b/src/features/Conversation/Messages/User/resolveSenderIdentity.test.tsindex 89bd73a82f4..1410d3d1e73 100644--- a/src/features/Conversation/Messages/User/resolveSenderIdentity.test.ts+++ b/src/features/Conversation/Messages/User/resolveSenderIdentity.test.ts@@ -1,10 +1,11 @@import { RequestTrigger } from '@lobechat/types';import { describe, expect, it } from 'vitest';-import { getBotSender, resolveSenderIdentity } from './resolveSenderIdentity';+import { getAgentSender, getBotSender, resolveSenderIdentity } from './resolveSenderIdentity';const viewer = {currentUserId: 'user-viewer',+ message: {} as Parameters<typeof resolveSenderIdentity>[0]['message'],selfAvatar: 'https://a.com/viewer.png',selfTitle: 'Viewer',unknownLabel: 'Member',@@ -83,7 +84,7 @@ describe('resolveSenderIdentity', () => {it('prefers the bot-channel sender over the owner account', () => {const result = resolveSenderIdentity({...viewer,- botSender: { fullName: 'ๆๅฝฌ', id: 'ou_1', platform: 'feishu' },+ message: { metadata: { botSender: { fullName: 'ๆๅฝฌ', id: 'ou_1', platform: 'feishu' } } },sender: { avatar: 'owner.png', fullName: 'Lin', id: 'user-viewer', username: null },});expect(result).toEqual({ avatar: undefined, isOwn: false, title: 'ๆๅฝฌ' });@@ -93,13 +94,92 @@ describe('resolveSenderIdentity', () => {expect(resolveSenderIdentity({...viewer,- botSender: { id: '1', platform: 'discord', username: 'john', avatar: 'https://x/a.png' },+ message: {+ metadata: {+ botSender: {+ avatar: 'https://x/a.png',+ id: '1',+ platform: 'discord',+ username: 'john',+ },+ },+ },}),).toEqual({ avatar: 'https://x/a.png', isOwn: false, title: 'john' });expect(- resolveSenderIdentity({ ...viewer, botSender: { id: '1', platform: 'discord' } }).title,+ resolveSenderIdentity({+ ...viewer,+ message: { metadata: { botSender: { id: '1', platform: 'discord' } } },+ }).title,).toBe(viewer.unknownLabel);});++ it('reads a legacy inline speaker tag off the row as well', () => {+ const result = resolveSenderIdentity({+ ...viewer,+ message: {+ content: '<speaker id="legacy" nickname="Old" />\nhi',+ metadata: { trigger: RequestTrigger.Bot },+ },+ });++ expect(result).toEqual({ avatar: undefined, isOwn: false, title: 'Old' });+ });++ /**+ * The regression the identity must keep reading from the ROW: the compressed+ * group re-renders user rows through a second path, so a resolver that takes+ * the blocks as separate arguments lets that path silently drop one and revert+ * an agent โ agent turn to the human owner.+ */+ it('attributes an agent โ agent turn to the sending agent, not the human owner', () => {+ const result = resolveSenderIdentity({+ ...viewer,+ message: {+ metadata: {+ agentSender: {+ agentId: 'agt_coco',+ avatar: 'https://a.com/coco.png',+ name: 'Coco',+ title: 'Product Agent',+ topicId: 'tpc_source',+ },+ },+ },+ // The row is persisted under the human owner; that must not win.+ sender: { avatar: 'owner.png', fullName: 'Lin', id: 'user-viewer', username: null },+ });++ expect(result).toEqual({ avatar: 'https://a.com/coco.png', isOwn: false, title: 'Coco' });+ });++ it('falls back to the sending agent role when it has no personal name', () => {+ const result = resolveSenderIdentity({+ ...viewer,+ message: { metadata: { agentSender: { agentId: 'agt_three', title: 'LobeHub ๆถๆๅทฅ็จๅธ' } } },+ });++ expect(result).toEqual({ avatar: undefined, isOwn: false, title: 'LobeHub ๆถๆๅทฅ็จๅธ' });+ });++ it('still labels a sending agent that was deleted after the turn, leaving only its id', () => {+ const result = resolveSenderIdentity({+ ...viewer,+ message: { metadata: { agentSender: { agentId: 'agt_gone' } } },+ });++ expect(result).toEqual({ avatar: undefined, isOwn: false, title: viewer.unknownLabel });+ });+});++describe('getAgentSender', () => {+ it('reads the server-written block off the message metadata', () => {+ const agentSender = { agentId: 'agt-coco', name: 'Coco', topicId: 'tpc-source' };++ expect(getAgentSender({ metadata: { agentSender } })).toEqual(agentSender);+ expect(getAgentSender({ metadata: null })).toBeUndefined();+ expect(getAgentSender({})).toBeUndefined();+ });});describe('getBotSender', () => {diff --git a/src/features/Conversation/Messages/User/resolveSenderIdentity.ts b/src/features/Conversation/Messages/User/resolveSenderIdentity.tsindex 446e75f294c..7b67df79c3e 100644--- a/src/features/Conversation/Messages/User/resolveSenderIdentity.ts+++ b/src/features/Conversation/Messages/User/resolveSenderIdentity.ts@@ -1,15 +1,54 @@-import { type BotSenderMetadata, type MessageSender, RequestTrigger } from '@lobechat/types';+import {+ agentDisplayName,+ type AgentSenderMetadata,+ type BotSenderMetadata,+ type MessageSender,+ RequestTrigger,+} from '@lobechat/types';import { parseSpeakerTag } from '@/store/chat/utils/parseSpeakerTag';+/** The shape of a user row this resolver needs โ the server-written blocks live on it. */+export interface SenderIdentitySource {+ content?: null | string;+ metadata?: null | {+ agentSender?: AgentSenderMetadata | null;+ botSender?: BotSenderMetadata | null;+ trigger?: RequestTrigger;+ };+}++/**+ * Agent sender for a user message: the structured block the server wrote for an+ * agent โ agent turn. Every render path that can show such a row must read it+ * through here โ a path that resolves the sender without it falls back to the+ * human owner the row was persisted under, i.e. it misattributes the message.+ */+export const getAgentSender = (message: {+ metadata?: { agentSender?: AgentSenderMetadata | null } | null;+}): AgentSenderMetadata | undefined => message.metadata?.agentSender ?? undefined;++/**+ * Bot-channel sender for a user message: the structured block written by the+ * server, falling back to the `<speaker>` tag older rows still carry inline.+ */+export const getBotSender = (message: {+ content?: string | null;+ metadata?: { botSender?: BotSenderMetadata | null; trigger?: RequestTrigger } | null;+}): BotSenderMetadata | undefined =>+ message.metadata?.botSender ??+ (message.metadata?.trigger === RequestTrigger.Bot ? parseSpeakerTag(message.content) : undefined);+interface ResolveSenderIdentityOptions {+ /** Viewer's user id, used to detect their own messages. */+ currentUserId?: null | string;/**- * Real platform author of a bot-channel message. Wins over `sender`, which- * for such rows is the bot OWNER's account rather than who actually typed.+ * The user row being rendered. The server-written sender blocks are read off+ * it here rather than passed in, so a renderer cannot resolve an identity+ * while silently dropping one of them โ the compressed group re-renders user+ * rows through a second path that has to agree with this one.*/- botSender?: BotSenderMetadata | null;- /** Viewer's user id, used to detect their own messages. */- currentUserId?: string | null;+ message: SenderIdentitySource;/** Viewer's avatar, applied only to their own messages. */selfAvatar: string;/** Viewer's display name, applied only to their own messages. */@@ -29,13 +68,26 @@ interface ResolveSenderIdentityOptions {* misattribute their messages to whoever is looking.*/export const resolveSenderIdentity = ({- botSender,currentUserId,+ message,selfAvatar,selfTitle,sender,unknownLabel,}: ResolveSenderIdentityOptions) => {+ const agentSender = getAgentSender(message);+ const botSender = getBotSender(message);++ // Another agent sent this turn. It is never the viewer's own message, and the+ // label follows the product-wide agent naming rule (personal name over role).+ if (agentSender) {+ return {+ avatar: agentSender.avatar || undefined,+ isOwn: false,+ title: agentDisplayName(agentSender) || unknownLabel,+ };+ }+if (botSender) {return {avatar: botSender.avatar || undefined,@@ -54,14 +106,3 @@ export const resolveSenderIdentity = ({return { avatar, isOwn, title };};--/**- * Bot-channel sender for a user message: the structured block written by the- * server, falling back to the `<speaker>` tag older rows still carry inline.- */-export const getBotSender = (message: {- content?: string | null;- metadata?: { botSender?: BotSenderMetadata | null; trigger?: RequestTrigger } | null;-}): BotSenderMetadata | undefined =>- message.metadata?.botSender ??- (message.metadata?.trigger === RequestTrigger.Bot ? parseSpeakerTag(message.content) : undefined);diff --git a/src/features/Portal/Thread/sharePath.test.ts b/src/features/Portal/Thread/sharePath.test.tsindex c25a81bf73c..9c4a425eff5 100644--- a/src/features/Portal/Thread/sharePath.test.ts+++ b/src/features/Portal/Thread/sharePath.test.ts@@ -1,6 +1,53 @@import { describe, expect, it } from 'vitest';-import { buildThreadSharePath, PORTAL_THREAD_QUERY_KEY } from './sharePath';+import {+ buildOperationSourcePath,+ buildThreadSharePath,+ PORTAL_THREAD_QUERY_KEY,+} from './sharePath';++describe('buildOperationSourcePath', () => {+ it('points at the agent topic when the turn ran in a one-to-one conversation', () => {+ expect(buildOperationSourcePath({ agentId: 'agt_1', topicId: 'tpc_1' })).toBe(+ '/agent/agt_1/tpc_1',+ );+ });++ it('reopens the thread the turn ran in', () => {+ expect(+ buildOperationSourcePath({ agentId: 'agt_1', threadId: 'thd_1', topicId: 'tpc_1' }),+ ).toBe('/agent/agt_1/tpc_1?portalThread=thd_1');+ });++ /**+ * A group's turns live under the group route; routing them through the agent+ * would open the supervisor's own conversation instead of the group the turn+ * actually came from.+ */+ it('points at the group conversation, with or without a thread', () => {+ expect(+ buildOperationSourcePath({+ agentId: 'agt_supervisor',+ chatGroupId: 'grp_1',+ topicId: 'tpc_1',+ }),+ ).toBe('/group/grp_1/tpc_1');++ expect(+ buildOperationSourcePath({+ agentId: 'agt_supervisor',+ chatGroupId: 'grp_1',+ threadId: 'thd_1',+ topicId: 'tpc_1',+ }),+ ).toBe('/group/grp_1/tpc_1?portalThread=thd_1');+ });++ it('has no path without a topic', () => {+ expect(buildOperationSourcePath({ agentId: 'a', topicId: undefined })).toBeUndefined();+ expect(buildOperationSourcePath({ topicId: 't' })).toBeUndefined();+ });+});describe('buildThreadSharePath', () => {it('points at the topic and reopens the thread in the side panel', () => {diff --git a/src/features/Portal/Thread/sharePath.ts b/src/features/Portal/Thread/sharePath.tsindex 3f99709a753..fda6bf15036 100644--- a/src/features/Portal/Thread/sharePath.ts+++ b/src/features/Portal/Thread/sharePath.ts@@ -4,31 +4,60 @@ import { AGENT_CHAT_TOPIC_URL, GROUP_CHAT_TOPIC_URL } from '@lobechat/const';export const PORTAL_THREAD_QUERY_KEY = 'portalThread';/**- * Route that reopens a thread in the side panel of its topic:- * `/agent/<agentId>/<topicId>?portalThread=<threadId>`, or- * `/group/<groupId>/<topicId>?portalThread=<threadId>` inside a group, where- * `agentId` is the supervisor and would open a different conversation.+ * Route back to where a run actually happened: the group conversation it belongs+ * to (`/group/<chatGroupId>/<topicId>`) or its agent topic, with the thread+ * reopened (`?portalThread=<threadId>`) when it ran inside one.+ *+ * A group's turns and an agent's turns are different conversations โ routing a+ * group turn through the agent route opens the supervisor's own transcript, and+ * dropping the thread lands on the topic's main one.*/-export const buildThreadSharePath = ({+export const buildOperationSourcePath = ({agentId,- groupId,+ chatGroupId,threadId,topicId,}: {- agentId?: string | null;- groupId?: string | null;- threadId?: string | null;- topicId?: string | null;+ agentId?: null | string;+ chatGroupId?: null | string;+ threadId?: null | string;+ topicId?: null | string;}): string | undefined => {- if (!topicId || !threadId) return;+ if (!topicId) return;- const topicPath = groupId- ? GROUP_CHAT_TOPIC_URL(groupId, topicId)+ const topicPath = chatGroupId+ ? GROUP_CHAT_TOPIC_URL(chatGroupId, topicId): agentId? AGENT_CHAT_TOPIC_URL(agentId, topicId): undefined;if (!topicPath) return;+ if (!threadId) return topicPath;const query = new URLSearchParams({ [PORTAL_THREAD_QUERY_KEY]: threadId });return `${topicPath}?${query.toString()}`;};++/**+ * Route that reopens a thread in the side panel of its topic:+ * `/agent/<agentId>/<topicId>?portalThread=<threadId>`, or+ * `/group/<groupId>/<topicId>?portalThread=<threadId>` inside a group, where+ * `agentId` is the supervisor and would open a different conversation.+ *+ * Returns nothing without a thread โ callers share a *thread*, so a topic-only+ * destination is not one; `buildOperationSourcePath` is the one that also takes+ * the plain topic.+ */+export const buildThreadSharePath = (options: {+ agentId?: null | string;+ groupId?: null | string;+ threadId?: null | string;+ topicId?: null | string;+}): string | undefined =>+ options.threadId+ ? buildOperationSourcePath({+ agentId: options.agentId,+ chatGroupId: options.groupId,+ threadId: options.threadId,+ topicId: options.topicId,+ })+ : undefined;