🤯 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(chat-input): @ 菜单直接提及市场中的助理与技能,直接 @ 助理时实时显示回复进度 (#22194)
Mocha1f04a92e3fc9
diff --git a/apps/server/src/routers/lambda/agent/lifecycle.createAgent.test.ts b/apps/server/src/routers/lambda/agent/lifecycle.createAgent.test.tsindex e7d380cdf38..e1f48c49bed 100644--- a/apps/server/src/routers/lambda/agent/lifecycle.createAgent.test.ts+++ b/apps/server/src/routers/lambda/agent/lifecycle.createAgent.test.ts@@ -56,6 +56,16 @@ describe('agent.createAgent direct Channel', () => {},);+ it('opens no Channel to a hidden (virtual) Agent', async () => {+ // A Market agent run from an @ mention gets a hidden copy; a direct Channel+ // to it would surface in the sidebar as an empty conversation.+ const config = { title: 'OKR 教练', virtual: true };+ await expect(caller('ws-1').createAgent({ config })).resolves.toEqual({ agentId: 'agt_new' });++ expect(mocks.createAgent).toHaveBeenCalledWith({ config });+ expect(mocks.createAgentDirectChannel).not.toHaveBeenCalled();+ });+it('opens nothing when the Agent was not created', async () => {mocks.createAgent.mockRejectedValue(new Error('A private agent cannot be created here'));diff --git a/apps/server/src/routers/lambda/agent/lifecycle.ts b/apps/server/src/routers/lambda/agent/lifecycle.tsindex 488151df5b7..4cdc1ab477d 100644--- a/apps/server/src/routers/lambda/agent/lifecycle.ts+++ b/apps/server/src/routers/lambda/agent/lifecycle.ts@@ -51,7 +51,8 @@ export const lifecycleRouter = router({return ctx.agentModel.countAgents(input);}),/**- * Create a standalone agent, with the creator's direct Channel to it while Channels are on.+ * Create a standalone agent, with the creator's direct Channel to it while Channels are on+ * (none for a hidden `virtual` agent).* Returns the created agent ID.*/createAgent: agentProcedure@@ -68,6 +69,9 @@ export const lifecycleRouter = router({.mutation(async ({ input, ctx }) => {const { localDeviceId, ...params } = input;const result = await ctx.agentService.createAgent(params);+ // A hidden (virtual) copy, such as a Market agent run from an @ mention, is+ // never a conversation of its own, so it gets no direct Channel.+ if (params.config?.virtual) return result;await createAgentDirectChannel({agentId: result.agentId,db: ctx.serverDB,@@ -156,10 +160,13 @@ export const lifecycleRouter = router({.input(z.object({forkedFromIdentifier: z.string(),+ virtual: z.boolean().optional(),}),).query(async ({ input, ctx }) => {- return ctx.agentModel.getAgentByForkedFromIdentifier(input.forkedFromIdentifier);+ return ctx.agentModel.getAgentByForkedFromIdentifier(input.forkedFromIdentifier, {+ virtual: input.virtual,+ });}),/*** Get an agent by marketIdentifierdiff --git a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.tsindex dac1bfb4764..c023263c40f 100644--- a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts@@ -831,6 +831,35 @@ describe('AiAgentService.execSubAgent', () => {mockStreamManager.closeLlmRelayChannel.mockResolvedValue(undefined);});+ it('does not link the child to a parent operation the server has no run for', async () => {+ // The gateway only authorizes a child whose recorded parent is a live+ // server run, so linking the tab's local id makes the child UNAUTHORIZED.+ mockOperationFindById.mockResolvedValue(null);+ const execAgentSpy = vi+ .spyOn(service, 'execAgent')+ .mockResolvedValue({ operationId: 'op-child', success: true } as any);++ await service.execSubAgent(params);++ expect(mockOperationFindById).toHaveBeenCalledWith('client-local-op');+ expect(execAgentSpy.mock.calls[0][0].parentOperationId).toBeUndefined();+ // Only the chat UI dispatches a sub-agent from a tab-local operation.+ expect(execAgentSpy.mock.calls[0][0].trigger).toBe('chat');+ });++ it('hands the tab the child run gateway ticket so it can stream the reply', async () => {+ vi.spyOn(service, 'execAgent').mockResolvedValue({+ assistantMessageId: 'msg-child',+ operationId: 'op-child',+ success: true,+ token: 'child-ticket',+ } as any);++ const result = await service.execSubAgent(params);++ expect(result).toMatchObject({ operationId: 'op-child', token: 'child-ticket' });+ });+it('relays the child on the channel the tab stands by on', async () => {const execAgentSpy = vi.spyOn(service, 'execAgent')diff --git a/apps/server/src/services/aiAgent/subAgentRuns.ts b/apps/server/src/services/aiAgent/subAgentRuns.tsindex 566d44cfb4e..a1333f4c26f 100644--- a/apps/server/src/services/aiAgent/subAgentRuns.ts+++ b/apps/server/src/services/aiAgent/subAgentRuns.ts@@ -9,7 +9,12 @@ import type {ThreadMetadata,UserInterventionConfig,} from '@lobechat/types';-import { isAgentOperationInFlight, ThreadStatus, ThreadType } from '@lobechat/types';+import {+ isAgentOperationInFlight,+ RequestTrigger,+ ThreadStatus,+ ThreadType,+} from '@lobechat/types';import debug from 'debug';import type { AgentOperationModel } from '@/database/models/agentOperation';@@ -314,10 +319,20 @@ export const execAgentThreadRun = async (// original entry point (chat / bot / cli / eval / …). Lookup is best-effort// — a missing parent row falls back to undefined and the column stays null.let inheritedTrigger: string | undefined;+ // A tab that dispatches a direct @mention passes its own client-local+ // operation id, which has no server row. The child must not record it as its+ // parent: gateway authorization only admits a child whose recorded parent is+ // a live server run, so the child would fail with UNAUTHORIZED.+ let recordedParentOperationId = parentOperationId;if (parentOperationId) {try {const parentOp = await deps.agentOperationModel.findById(parentOperationId);inheritedTrigger = parentOp?.trigger ?? undefined;+ if (!parentOp) {+ recordedParentOperationId = undefined;+ // Only the chat UI dispatches from a tab-local operation.+ inheritedTrigger = RequestTrigger.Chat;+ }} catch (error) {log('%s: failed to read parent operation trigger: %O', options.logScope, error);}@@ -365,7 +380,7 @@ export const execAgentThreadRun = async (localDeviceId: options.localDeviceId,// Explicit sub-agent model override resolved at the spawn site.model: options.model,- parentOperationId,+ parentOperationId: recordedParentOperationId,prompt: instruction,provider: options.provider,trigger: inheritedTrigger,@@ -453,6 +468,9 @@ export const execAgentThreadRun = async (operationId: result.operationId,success: result.success ?? false,threadId: thread.id,+ // The child's own gateway ticket: a tab that dispatched it has no server+ // run whose channel would carry the child's progress, so it subscribes here.+ ...(result.token && { token: result.token }),};};diff --git a/apps/server/src/services/skill/resource.test.ts b/apps/server/src/services/skill/resource.test.tsindex 66574fe414f..535bf53d903 100644--- a/apps/server/src/services/skill/resource.test.ts+++ b/apps/server/src/services/skill/resource.test.ts@@ -162,6 +162,52 @@ describe('SkillResourceService', () => {expect(result['lib/utils.ts'].fileHash).toHaveLength(64);});+ it('uploads resources concurrently, with a bounded number in flight', async () => {+ // A Market skill can carry hundreds of files; one upload at a time made a+ // 847-file skill take ~26s to install while the @mention send waited.+ let inFlight = 0;+ let peak = 0;+ mockUploadBuffer.mockImplementation(async () => {+ inFlight += 1;+ peak = Math.max(peak, inFlight);+ await new Promise((resolve) => setTimeout(resolve, 5));+ inFlight -= 1;+ return { key: 'mock-key' };+ });+ const service = new SkillResourceService({} as any, 'user-1');+ const resources = new Map(+ Array.from({ length: 40 }, (_, i) => [`file-${i}.md`, Buffer.from(`# ${i}`)] as const),+ );++ const result = await service.storeResources('zip-many', resources);++ expect(Object.keys(result)).toHaveLength(40);+ expect(result['file-39.md'].size).toBe(4);+ expect(peak).toBeGreaterThan(1);+ expect(peak).toBeLessThanOrEqual(16);+ mockUploadBuffer.mockResolvedValue({ key: 'mock-key' });+ });++ it('registers each distinct content once, even when several paths share it', async () => {+ // Concurrent workers registering one hash race on the global file insert+ // (check-then-insert on its primary key), failing the whole install.+ const service = new SkillResourceService({} as any, 'user-1');+ const resources = new Map([+ ['pkg/__init__.py', Buffer.from('')],+ ['pkg/sub/__init__.py', Buffer.from('')],+ ['pkg/main.py', Buffer.from('print(1)')],+ ]);++ const result = await service.storeResources('zip-dup', resources);++ const registered = mockCreateGlobalFile.mock.calls.map(([file]) => file.fileHash);+ expect(registered).toHaveLength(2);+ expect(new Set(registered).size).toBe(2);+ expect(result['pkg/__init__.py'].fileHash).toBe(result['pkg/sub/__init__.py'].fileHash);+ expect(result['pkg/sub/__init__.py'].size).toBe(0);+ expect(result['pkg/main.py'].fileHash).not.toBe(result['pkg/__init__.py'].fileHash);+ });+it('should pass correct metadata to createGlobalFile', async () => {const service = new SkillResourceService({} as any, 'user-1');const resources = new Map([['docs/guide.md', Buffer.from('# Guide')]]);diff --git a/apps/server/src/services/skill/resource.ts b/apps/server/src/services/skill/resource.tsindex 7edfdfc978a..f0eb15a2255 100644--- a/apps/server/src/services/skill/resource.ts+++ b/apps/server/src/services/skill/resource.ts@@ -7,6 +7,7 @@ import {import { getMimeType } from '@lobechat/utils';import debug from 'debug';import { sha256 } from 'js-sha256';+import pMap from 'p-map';import { FileService } from '@/server/services/file';@@ -14,6 +15,8 @@ import { SkillResourceError } from './errors';const log = debug('lobe-chat:service:skill-resource');+const STORE_RESOURCES_CONCURRENCY = 16;+function isTextMimeType(mimeType: string): boolean {if (mimeType.startsWith('text/')) return true;const textApplicationTypes = [@@ -51,13 +54,30 @@ export class SkillResourceService {log('storeResources: starting with zipHash=%s, resourceCount=%d', zipHash, resources.size);const result: Record<string, SkillResourceMeta> = {};+ // Paths with identical contents (e.g. several empty `__init__.py`) share one+ // global file; registering that hash from parallel workers would race on its+ // insert, so each distinct content is stored once, from its first path.+ const pathsByHash = new Map<string, { buffer: Buffer; paths: string[] }>();for (const [virtualPath, buffer] of resources) {- log('storeResources: storing resource path=%s, size=%d bytes', virtualPath, buffer.length);- const fileHash = await this.storeResource(zipHash, virtualPath, buffer);- result[virtualPath] = { fileHash, size: buffer.length };- log('storeResources: stored resource path=%s, fileHash=%s', virtualPath, fileHash);+ const fileHash = sha256(buffer);+ const entry = pathsByHash.get(fileHash);+ if (entry) entry.paths.push(virtualPath);+ else pathsByHash.set(fileHash, { buffer, paths: [virtualPath] });}+ // Each file is an object-storage upload plus a row insert; a Market skill can+ // carry hundreds of them, so storing them one at a time dominated install time.+ await pMap(+ pathsByHash.values(),+ async ({ buffer, paths }) => {+ log('storeResources: storing resource path=%s, size=%d bytes', paths[0], buffer.length);+ const fileHash = await this.storeResource(zipHash, paths[0], buffer);+ for (const virtualPath of paths) result[virtualPath] = { fileHash, size: buffer.length };+ log('storeResources: stored %d path(s), fileHash=%s', paths.length, fileHash);+ },+ { concurrency: STORE_RESOURCES_CONCURRENCY },+ );+log('storeResources: completed, stored %d resources', Object.keys(result).length);return result;}diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex c9be2433ba9..f9bc78480d0 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -413,6 +413,11 @@"devinInstallGuide.menuNotification.title": "Devin CLI not found","devinInstallGuide.reason": "LobeHub could not start Devin: {{message}}","devinInstallGuide.title": "Install Devin CLI",+ "directMention.progress.elapsed": "{{time}}",+ "directMention.progress.running": "Running",+ "directMention.progress.thinking": "Thinking…",+ "directMention.progress.usingTool": "Using {{name}}…",+ "directMention.progress.viewFullRecord": "View full record","dm.placeholder": "Your private messages with {{agentTitle}} will appear here.","dm.tooltip": "Send a private message","dm.visibleTo": "Visible to {{target}} only",@@ -1751,6 +1756,7 @@"mention.category.tools": "Tools","mention.category.topics": "Topics","mention.category.workspaceAgents": "Workspace",+ "mention.marketInstall.failed": "{{names}} isn’t available right now. The message was not sent; try again.","mention.title": "Mention Members","messageAction.advanced": "Advanced","messageAction.codexEdit.alreadySubmitting": "This edit is already being submitted",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 18874643a3e..be92d1daf1a 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -413,6 +413,11 @@"devinInstallGuide.menuNotification.title": "未找到 Devin CLI","devinInstallGuide.reason": "LobeHub 无法启动 Devin:{{message}}","devinInstallGuide.title": "安装 Devin CLI",+ "directMention.progress.elapsed": "已 {{time}}",+ "directMention.progress.running": "执行中",+ "directMention.progress.thinking": "正在思考…",+ "directMention.progress.usingTool": "正在使用 {{name}}…",+ "directMention.progress.viewFullRecord": "查看完整记录","dm.placeholder": "你与 {{agentTitle}} 的私信会显示在这里。","dm.tooltip": "发送私信","dm.visibleTo": "仅 {{target}} 可见",@@ -1751,6 +1756,7 @@"mention.category.tools": "工具","mention.category.topics": "话题","mention.category.workspaceAgents": "工作区",+ "mention.marketInstall.failed": "{{names}} 暂时无法使用,消息未发送,请重试。","mention.title": "提及成员","messageAction.advanced": "高级操作","messageAction.codexEdit.alreadySubmitting": "正在提交此次编辑,请稍候",diff --git a/package.json b/package.jsonindex 66dff3d714c..c17d55f544c 100644--- a/package.json+++ b/package.json@@ -328,7 +328,7 @@"@lobehub/analytics": "^1.6.4","@lobehub/charts": "^6.0.0","@lobehub/desktop-ipc-typings": "workspace:*",- "@lobehub/editor": "7.2.0",+ "@lobehub/editor": "7.2.1","@lobehub/icons": "^6.13.0","@lobehub/market-sdk": "0.46.0","@lobehub/ui": "^6.12.0",diff --git a/packages/database/src/models/__tests__/agent.forkedFromIdentifier.test.ts b/packages/database/src/models/__tests__/agent.forkedFromIdentifier.test.tsnew file mode 100644index 00000000000..4822999d0d8--- /dev/null+++ b/packages/database/src/models/__tests__/agent.forkedFromIdentifier.test.ts@@ -0,0 +1,53 @@+// @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 = 'forked-from-test-user-id';+const agentModel = new AgentModel(serverDB, userId);++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }]);+});++afterEach(async () => {+ await serverDB.delete(users);+});++describe('AgentModel.getAgentByForkedFromIdentifier with hidden copies', () => {+ it('keeps the hidden copy an @ mention runs apart from installed agents', async () => {+ const [hidden] = await serverDB+ .insert(agents)+ .values({+ userId,+ title: 'Mentioned',+ params: { forkedFromIdentifier: 'mentioned-id' },+ virtual: true,+ })+ .returning();++ expect(await agentModel.getAgentByForkedFromIdentifier('mentioned-id')).toBeNull();+ expect(await agentModel.getAgentByForkedFromIdentifier('mentioned-id', { virtual: true })).toBe(+ hidden.id,+ );+ });++ it('finds the installed agent, not the hidden copy, by default', async () => {+ const [installed] = await serverDB+ .insert(agents)+ .values([+ { userId, title: 'Hidden', params: { forkedFromIdentifier: 'both-id' }, virtual: true },+ { userId, title: 'Installed', params: { forkedFromIdentifier: 'both-id' } },+ ])+ .returning()+ .then((rows) => rows.filter((row) => !row.virtual));++ expect(await agentModel.getAgentByForkedFromIdentifier('both-id')).toBe(installed.id);+ });+});diff --git a/packages/database/src/models/agent/find.ts b/packages/database/src/models/agent/find.tsindex a88d33dcb6b..64df463ca65 100644--- a/packages/database/src/models/agent/find.ts+++ b/packages/database/src/models/agent/find.ts@@ -259,11 +259,15 @@ export const getAgentByMarketIdentifier = async (/*** Get an agent by the forkedFromIdentifier stored in params* @param forkedFromIdentifier - The source agent's market identifier+ * @param options.virtual - Look among hidden copies (a Market agent run from an+ * @ mention) instead of installed agents. An installed lookup never matches a+ * hidden copy, so mentioning an agent never counts as installing it.* @returns agent id if exists, null otherwise*/export const getAgentByForkedFromIdentifier = async (ctx: AgentModelContext,forkedFromIdentifier: string,+ { virtual = false }: { virtual?: boolean } = {},): Promise<string | null> => {const result = await ctx.db.query.agents.findFirst({columns: { id: true },@@ -271,6 +275,7 @@ export const getAgentByForkedFromIdentifier = async (where: and(ctx.ownership(),sql`${agents.params}->>'forkedFromIdentifier' = ${forkedFromIdentifier}`,+ sql`coalesce(${agents.virtual}, false) = ${virtual}`,),});return result?.id ?? null;diff --git a/packages/database/src/repositories/home/index.test.ts b/packages/database/src/repositories/home/index.test.tsindex b33f37fdb25..fe13521d176 100644--- a/packages/database/src/repositories/home/index.test.ts+++ b/packages/database/src/repositories/home/index.test.ts@@ -85,6 +85,27 @@ describe('HomeRepository', () => {});});+ it('should expose the market source an agent was forked from', async () => {+ const [forked, plain] = await serverDB+ .insert(agents)+ .values([+ {+ params: { forkedFromIdentifier: 'market-writer' },+ title: 'Forked',+ userId,+ virtual: false,+ },+ { title: 'Plain', userId, virtual: false },+ ])+ .returning();++ const result = await homeRepo.getSidebarAgentList();+ const byId = new Map(result.ungrouped.map((item) => [item.id, item]));++ expect(byId.get(forked.id)?.forkedFromIdentifier).toBe('market-writer');+ expect(byId.get(plain.id)?.forkedFromIdentifier ?? null).toBeNull();+ });+it('should fallback inbox agent meta by slug', async () => {const [agent] = await serverDB.insert(agents)diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.tsindex cc0a526c87b..1839b11d78f 100644--- a/packages/database/src/repositories/home/index.ts+++ b/packages/database/src/repositories/home/index.ts@@ -100,6 +100,7 @@ export class HomeRepository {avatar: agents.avatar,backgroundColor: agents.backgroundColor,description: agents.description,+ forkedFromIdentifier: sql<string | null>`${agents.params}->>'forkedFromIdentifier'`,id: agents.id,name: agents.name,model: agents.model,@@ -297,6 +298,7 @@ export class HomeRepository {avatar: string | null;backgroundColor: string | null;description: string | null;+ forkedFromIdentifier: string | null;id: string;name: string | null;model: string | null;@@ -354,6 +356,7 @@ export class HomeRepository {avatar: meta.avatar,backgroundColor: a.backgroundColor,description: a.description,+ forkedFromIdentifier: a.forkedFromIdentifier,groupId: a.sessionGroupId,heterogeneousType: a.agencyConfig?.heterogeneousProvider?.type ?? null,id: a.id,diff --git a/packages/database/src/repositories/topic/__tests__/create.test.ts b/packages/database/src/repositories/topic/__tests__/create.test.tsindex 75d9df6efd8..9535cfda0b0 100644--- a/packages/database/src/repositories/topic/__tests__/create.test.ts+++ b/packages/database/src/repositories/topic/__tests__/create.test.ts@@ -37,6 +37,31 @@ describe('TopicRepository - create', () => {});describe('create', () => {+ it('never moves a message that already belongs to another topic', async () => {+ // A stale client bucket once sent another conversation's message ids as+ // `topicMessageIds`; re-parenting them emptied that conversation.+ await serverDB.insert(topics).values({ id: 'existing-topic', sessionId, userId });+ await serverDB.insert(messages).values([+ { id: 'loose-message', role: 'user', userId, sessionId },+ { id: 'owned-message', role: 'user', userId, sessionId, topicId: 'existing-topic' },+ ]);++ await topicRepo.create(+ { messages: ['loose-message', 'owned-message'], sessionId, title: 'New' },+ 'fresh-topic',+ );++ const rows = await serverDB+ .select({ id: messages.id, topicId: messages.topicId })+ .from(messages)+ .where(inArray(messages.id, ['loose-message', 'owned-message']))+ .orderBy(asc(messages.id));+ expect(rows).toEqual([+ { id: 'loose-message', topicId: 'fresh-topic' },+ { id: 'owned-message', topicId: 'existing-topic' },+ ]);+ });+it('should create a new topic and associate messages', async () => {const topicData = {title: 'New Topic',diff --git a/packages/database/src/repositories/topic/create.ts b/packages/database/src/repositories/topic/create.tsindex 302f7676ab6..04f6bb98371 100644--- a/packages/database/src/repositories/topic/create.ts+++ b/packages/database/src/repositories/topic/create.ts@@ -1,5 +1,5 @@import { runTimedSinkStage as runTimedStage } from '@lobechat/utils';-import { and, inArray } from 'drizzle-orm';+import { and, inArray, isNull } from 'drizzle-orm';import pMap from 'p-map';import { type CreateTopicParams, type ModelTimingContext, TopicModel } from '../../models/topic';@@ -18,11 +18,18 @@ const reparentMessages = (scope: TopicRepositoryScope,topicId: string,messageIds: string[],+ { onlyUntopiced = false }: { onlyUntopiced?: boolean } = {},) =>db.update(messages).set({ topicId })- .where(and(messageOwnership(scope), inArray(messages.id, messageIds)));+ .where(+ and(+ messageOwnership(scope),+ inArray(messages.id, messageIds),+ onlyUntopiced ? isNull(messages.topicId) : undefined,+ ),+ );/*** Creates a topic and, when `messages` is given, re-parents those existing@@ -52,7 +59,9 @@ export const createTopic = async (await runTimedStage(timing,'db.topic.create.messages.updateTopic',- () => reparentMessages(trx, scope, topic.id, messageIds),+ // A new topic adopts the blank conversation it was started from; a+ // message already living in another topic is never moved out of it.+ () => reparentMessages(trx, scope, topic.id, messageIds, { onlyUntopiced: true }),{ messageCount: messageIds.length },);diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex e5ae6e5386a..6f9511f64d6 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1,4 +1,9 @@export default {+ 'directMention.progress.elapsed': '{{time}}',+ 'directMention.progress.running': 'Running',+ 'directMention.progress.thinking': 'Thinking…',+ 'directMention.progress.usingTool': 'Using {{name}}…',+ 'directMention.progress.viewFullRecord': 'View full record','sharePage.app.linkCopied': 'Link copied','sharePage.app.open': 'Open app','sharePage.app.help': 'Trouble opening the app?',@@ -1064,6 +1069,8 @@ export default {'mention.category.tools': 'Tools','mention.category.topics': 'Topics','mention.category.workspaceAgents': 'Workspace',+ 'mention.marketInstall.failed':+ '{{names}} isn’t available right now. The message was not sent; try again.','mention.title': 'Mention Members','messageAction.codexEdit.alreadySubmitting': 'This edit is already being submitted','messageAction.codexEdit.branchFailed':diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex e87ae7ef18d..bd241867c02 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -716,6 +716,8 @@ export interface ExecSubAgentResult {success: boolean;/** The Thread ID where the execution is isolated */threadId: string;+ /** Short-lived Gateway ticket for streaming this run (absent when withheld) */+ token?: string;}/**diff --git a/packages/types/src/home.ts b/packages/types/src/home.tsindex 47f5063c772..c9ee837012c 100644--- a/packages/types/src/home.ts+++ b/packages/types/src/home.ts@@ -56,6 +56,12 @@ export interface SidebarAgentItem {*/backgroundColor?: string | null;description?: string | null;+ /**+ * Market identifier of the community agent this agent was installed from+ * (`params.forkedFromIdentifier`). Lets pickers tell which market agents+ * the caller already has. Absent for chat groups and agents created locally.+ */+ forkedFromIdentifier?: string | null;/*** Group's own avatar (emoji or uploaded image URL)* Only present for chat groups (type === 'group')diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 3b69dd6bbc0..55f991090f6 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -67,7 +67,7 @@ overrides:'@lobehub/icons': ^6.0.0# Exact: an editor release can move its lexical version, and the root pins# lexical; lift both together.- '@lobehub/editor': 7.2.0+ '@lobehub/editor': 7.2.1'@lobehub/charts': ^6.0.0'@lobehub/fluent-emoji': ^5.0.0# Stay on the latest 1.9.x: @opentelemetry/*@2.x peers reject 1.10.0, and mixing both splits drizzle-orm into duplicate peer variants.diff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionMention.tsx b/src/features/ChatInput/InputEditor/ActionTag/ActionMention.tsxindex 446cb0ec664..a3b90f3a2e0 100644--- a/src/features/ChatInput/InputEditor/ActionTag/ActionMention.tsx+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionMention.tsx@@ -108,7 +108,7 @@ export const ActionMention = memo<ActionMentionProps>(className={cx(styles.actionTag, styles[styleKey], isClickable && styles.clickable)}onClick={handleClick}>- <Icon icon={IconComponent} size={14} />+ <Icon className={styles.actionTagIcon} icon={IconComponent} size={14} /><span className={styles.actionTagLabel}>{label}</span></span></Tooltip>diff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionTag.tsx b/src/features/ChatInput/InputEditor/ActionTag/ActionTag.tsxindex f75da51d282..f88c226352a 100644--- a/src/features/ChatInput/InputEditor/ActionTag/ActionTag.tsx+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionTag.tsx@@ -42,7 +42,7 @@ const ActionTag = memo<ActionTagProps>(({ node, editor, label }) => {}, [editor, onClick]);return (- <span ref={spanRef} style={{ verticalAlign: -3 }}>+ <span ref={spanRef}><ActionMentioncategory={node.actionCategory}clickable={!!open}diff --git a/src/features/ChatInput/InputEditor/ActionTag/style.ts b/src/features/ChatInput/InputEditor/ActionTag/style.tsindex e5433084d0c..e000a6e6482 100644--- a/src/features/ChatInput/InputEditor/ActionTag/style.ts+++ b/src/features/ChatInput/InputEditor/ActionTag/style.ts@@ -19,11 +19,16 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({display: inline-flex;gap: 4px;- align-items: center;+ /* The label sets the tag's baseline, so it sits on the surrounding text's+ baseline; an icon-first inline-flex would take the SVG's bottom edge. */+ align-items: baseline;margin-inline-end: ${TAG_MARGIN_INLINE_END}px;padding-inline: 2px;`,+ actionTagIcon: css`+ align-self: center;+ `,actionTagLabel: css`font-weight: 500;`,diff --git a/src/features/ChatInput/InputEditor/ActionTag/useInstalledSkillsAndTools.ts b/src/features/ChatInput/InputEditor/ActionTag/useInstalledSkillsAndTools.tsindex 751bc0277a6..bfd765bc69b 100644--- a/src/features/ChatInput/InputEditor/ActionTag/useInstalledSkillsAndTools.ts+++ b/src/features/ChatInput/InputEditor/ActionTag/useInstalledSkillsAndTools.ts@@ -10,107 +10,132 @@ import {pluginSelectors,} from '@/store/tool/selectors';import { connectorSelectors } from '@/store/tool/slices/connector';+import type { ToolStore } from '@/store/tool/store';import type { ActionTagData } from './types';+interface InstalledSources {+ builtinSkills: ReturnType<typeof builtinToolSelectors.installedBuiltinSkills>;+ composioServers: ReturnType<typeof composioStoreSelectors.getServers>;+ customConnectors: ReturnType<typeof connectorSelectors.customConnectors>;+ installedPlugins: ReturnType<typeof pluginSelectors.installedPluginMetaList>;+ lobehubSkillServers: ReturnType<typeof lobehubSkillStoreSelectors.getServers>;+ marketAgentSkills: ReturnType<typeof agentSkillsSelectors.getMarketAgentSkills>;+ userAgentSkills: ReturnType<typeof agentSkillsSelectors.getUserAgentSkills>;+}++const selectInstalledSources = (s: ToolStore): InstalledSources => ({+ builtinSkills: builtinToolSelectors.installedBuiltinSkills(s),+ composioServers: composioStoreSelectors.getServers(s),+ customConnectors: connectorSelectors.customConnectors(s),+ installedPlugins: pluginSelectors.installedPluginMetaList(s),+ lobehubSkillServers: lobehubSkillStoreSelectors.getServers(s),+ marketAgentSkills: agentSkillsSelectors.getMarketAgentSkills(s),+ userAgentSkills: agentSkillsSelectors.getUserAgentSkills(s),+});+/**- * Collects all installed skills and tools, returning them as ActionTagData[].* Skills: builtinSkills, lobehubSkillServers, marketAgentSkills, userAgentSkills* Tools: installedPlugins (excluding skill-type entries), composioServers*/-export const useInstalledSkillsAndTools = (): ActionTagData[] => {- const builtinSkills = useToolStore(builtinToolSelectors.installedBuiltinSkills, isEqual);- const customConnectors = useToolStore(connectorSelectors.customConnectors, isEqual);- const installedPlugins = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);- const composioServers = useToolStore(composioStoreSelectors.getServers, isEqual);- const lobehubSkillServers = useToolStore(lobehubSkillStoreSelectors.getServers, isEqual);- const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);- const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);+const buildInstalledSkillsAndTools = ({+ builtinSkills,+ composioServers,+ customConnectors,+ installedPlugins,+ lobehubSkillServers,+ marketAgentSkills,+ userAgentSkills,+}: InstalledSources): ActionTagData[] => {+ const items: ActionTagData[] = [];- return useMemo(() => {- const items: ActionTagData[] = [];+ // --- Build skill set (identifier → { label, icon }) ---+ const skillMap = new Map<string, { description?: string; icon?: string; label: string }>();- // --- Build skill set (identifier → { label, icon }) ---- const skillMap = new Map<string, { description?: string; icon?: string; label: string }>();-- for (const item of builtinSkills) {+ for (const item of builtinSkills) {+ skillMap.set(item.identifier, {+ description: item.description,+ icon: item.avatar,+ label: item.title || item.name || item.identifier,+ });+ }+ for (const item of lobehubSkillServers) {+ if (!skillMap.has(item.identifier)) {+ skillMap.set(item.identifier, { icon: item.icon, label: item.name || item.identifier });+ }+ }+ for (const item of marketAgentSkills) {+ if (!skillMap.has(item.identifier)) {skillMap.set(item.identifier, {- description: item.description,- icon: item.avatar,- label: item.title || item.name || item.identifier,+ description: item.description || item.manifest?.description,+ label: item.name || item.identifier,});}- for (const item of lobehubSkillServers) {- if (!skillMap.has(item.identifier)) {- skillMap.set(item.identifier, { icon: item.icon, label: item.name || item.identifier });- }- }- for (const item of marketAgentSkills) {- if (!skillMap.has(item.identifier)) {- skillMap.set(item.identifier, {- description: item.description || item.manifest?.description,- label: item.name || item.identifier,- });- }- }- for (const item of userAgentSkills) {- if (!skillMap.has(item.identifier)) {- skillMap.set(item.identifier, {- description: item.description || item.manifest?.description,- label: item.name || item.identifier,- });- }+ }+ for (const item of userAgentSkills) {+ if (!skillMap.has(item.identifier)) {+ skillMap.set(item.identifier, {+ description: item.description || item.manifest?.description,+ label: item.name || item.identifier,+ });}+ }- // --- Build tool set, excluding identifiers already classified as skills ---- const toolMap = new Map<string, { icon?: string; label: string }>();+ // --- Build tool set, excluding identifiers already classified as skills ---+ const toolMap = new Map<string, { icon?: string; label: string }>();- // Custom connectors (user-added MCP servers) first: they take priority over- // a legacy plugin sharing the same identifier, mirroring toolEngineering's- // connector-over-plugin rule. Only enabled connectors with synced tools are- // in the tools engine (buildClientConnectorManifests), so match that here —- // otherwise the picker would offer a mention that resolves to nothing.- for (const item of customConnectors) {- if (!item.isEnabled || (item.tools?.length ?? 0) === 0) continue;- if (skillMap.has(item.identifier)) continue;- if (!toolMap.has(item.identifier)) {- toolMap.set(item.identifier, { label: item.name || item.identifier });- }+ // Custom connectors (user-added MCP servers) first: they take priority over+ // a legacy plugin sharing the same identifier, mirroring toolEngineering's+ // connector-over-plugin rule. Only enabled connectors with synced tools are+ // in the tools engine (buildClientConnectorManifests), so match that here —+ // otherwise the picker would offer a mention that resolves to nothing.+ for (const item of customConnectors) {+ if (!item.isEnabled || (item.tools?.length ?? 0) === 0) continue;+ if (skillMap.has(item.identifier)) continue;+ if (!toolMap.has(item.identifier)) {+ toolMap.set(item.identifier, { label: item.name || item.identifier });}+ }- for (const item of installedPlugins) {- // Skip entries that are actually skills (lobehub skill, agent skill, builtin skill)- if (skillMap.has(item.identifier)) continue;- if (!toolMap.has(item.identifier)) {- toolMap.set(item.identifier, { icon: item.avatar, label: item.title || item.identifier });- }+ for (const item of installedPlugins) {+ // Skip entries that are actually skills (lobehub skill, agent skill, builtin skill)+ if (skillMap.has(item.identifier)) continue;+ if (!toolMap.has(item.identifier)) {+ toolMap.set(item.identifier, { icon: item.avatar, label: item.title || item.identifier });}- for (const item of composioServers) {- if (skillMap.has(item.identifier)) continue;- if (!toolMap.has(item.identifier)) {- toolMap.set(item.identifier, {- icon: item.icon,- label: item.label || item.identifier,- });- }+ }+ for (const item of composioServers) {+ if (skillMap.has(item.identifier)) continue;+ if (!toolMap.has(item.identifier)) {+ toolMap.set(item.identifier, {+ icon: item.icon,+ label: item.label || item.identifier,+ });}+ }- // --- Merge into output ---- for (const [id, { description, icon, label }] of skillMap) {- items.push({ category: 'skill', description, icon, label, type: id });- }- for (const [id, { icon, label }] of toolMap) {- items.push({ category: 'tool', icon, label, type: id });- }+ // --- Merge into output ---+ for (const [id, { description, icon, label }] of skillMap) {+ items.push({ category: 'skill', description, icon, label, type: id });+ }+ for (const [id, { icon, label }] of toolMap) {+ items.push({ category: 'tool', icon, label, type: id });+ }++ return items;+};++/** Identifiers of every installed skill, read straight from the tool store (no hook). */+export const getInstalledSkillIdentifiers = (): Set<string> =>+ new Set(+ buildInstalledSkillsAndTools(selectInstalledSources(useToolStore.getState()))+ .filter((item) => item.category === 'skill')+ .map((item) => item.type),+ );++/** Collects all installed skills and tools, returning them as ActionTagData[]. */+export const useInstalledSkillsAndTools = (): ActionTagData[] => {+ const sources = useToolStore(selectInstalledSources, isEqual);- return items;- }, [- builtinSkills,- customConnectors,- installedPlugins,- composioServers,- lobehubSkillServers,- marketAgentSkills,- userAgentSkills,- ]);+ return useMemo(() => buildInstalledSkillsAndTools(sources), [sources]);};diff --git a/src/features/ChatInput/InputEditor/index.test.tsx b/src/features/ChatInput/InputEditor/index.test.tsxindex da28c891c10..c02fa97701e 100644--- a/src/features/ChatInput/InputEditor/index.test.tsx+++ b/src/features/ChatInput/InputEditor/index.test.tsx@@ -268,7 +268,29 @@ vi.mock('./useLocalFileTag', () => ({searchLocalFiles: vi.fn(async () => []),}),}));-vi.mock('./useMentionCategories', () => ({ useMentionCategories: () => [] }));+vi.mock('@/services/mentionMarketInstall', () => ({+ prepareMentionedMarketAgent: vi.fn(),+ prepareMentionedMarketSkill: vi.fn(),+}));+vi.mock('./marketMentionItems', () => ({+ searchMarketForMention: vi.fn(async () => ({ agents: [], skills: [] })),+ toMarketAgentItem: vi.fn(),+ toMarketSkillItem: vi.fn(),+}));+vi.mock('./useMentionCategories', () => ({+ useMentionCategories: () => ({+ categories: [],+ market: {+ agentCategory: undefined,+ agentVisibility: 'public',+ agents: false,+ installedAgentSources: new Set(),+ installedSkills: new Set(),+ skillCategory: { icon: null, id: 'skill', label: 'Skills' },+ skills: false,+ },+ }),+}));describe('ChatInput InputEditor', () => {beforeEach(() => {diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsxindex 73ed9f7fcf5..edeb659ed73 100644--- a/src/features/ChatInput/InputEditor/index.tsx+++ b/src/features/ChatInput/InputEditor/index.tsx@@ -24,6 +24,10 @@ import { useIMECompositionEvent } from '@/hooks/useIMECompositionEvent';import { usePermission } from '@/hooks/usePermission';import { useSingleton } from '@/hooks/useSingleton';import { aiChatService } from '@/services/aiChat';+import {+ prepareMentionedMarketAgent,+ prepareMentionedMarketSkill,+} from '@/services/mentionMarketInstall';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -51,6 +55,15 @@ import {import { createInputCompletionError, isInputCompletionAbortError } from './inputCompletionError';import InputHistoryPopup, { getHistoryPreviewText } from './InputHistoryPopup';import { INSERT_LOCAL_FILE_TAG_COMMAND } from './LocalFileTag';+import { searchMarketForMention, toMarketAgentItem, toMarketSkillItem } from './marketMentionItems';+import {+ AGENT_CATEGORY_IDS,+ DEFAULT_MENTION_GROUP_LIMIT,+ limitMentionGroups,+ mergeIntoCategory,+ SEARCH_MENTION_GROUP_LIMIT,+ SKILL_PRECEDING_IDS,+} from './mentionMenuSections';import { mentionPlainClassName } from './mentionStyle';import Placeholder, { type PlaceholderVariant } from './Placeholder';import { createChatInputRichPlugins } from './plugins';@@ -140,7 +153,7 @@ const InputEditor = memo<{});// --- Category-based mention system ---- const categories = useMentionCategories();+ const { categories, market } = useMentionCategories();// Get agent's model info for vision support check and handle paste uploadconst { model, provider } = useEffectiveModel(agentId);@@ -151,9 +164,11 @@ const InputEditor = memo<{const { enableLocalFileTag, searchLocalFiles } = useLocalFileTag();const allMentionItems = useMemo(() => categories.flatMap((c) => c.items), [categories]);+ // Before the user types, agents and skills (installed first, then the+ // Market's top entries) show only a few each; typing filters all of them.const mentionSections = useMemo<ISlashSectionOption[]>(() =>- categories.map((category) => ({+ limitMentionGroups(categories, DEFAULT_MENTION_GROUP_LIMIT).map((category) => ({items: category.items,key: `mention-section-${category.id}`,label: category.label,@@ -178,30 +193,58 @@ const InputEditor = memo<{search: { leadOffset: number; matchingString: string; replaceableString: string } | null,) => {if (search?.matchingString) {- const [localFileItems, mentionItems] = await Promise.all([+ const [localFileItems, mentionItems, marketResult] = await Promise.all([searchLocalFiles(search.matchingString),Promise.resolve(fuse.search(search.matchingString).map((r) => r.item)),+ searchMarketForMention(search.matchingString, market),]);const rankByKey = new Map(mentionItems.map((item, index) => [String(item.key), index]));- const matchedSections = categories- .map((category): ISlashSectionOption => {- const items = category.items- .filter((item) => rankByKey.has(String(item.key)))- .sort(- (a, b) =>- (rankByKey.get(String(a.key)) ?? Number.MAX_SAFE_INTEGER) -- (rankByKey.get(String(b.key)) ?? Number.MAX_SAFE_INTEGER),- );-- return {- items,- key: `mention-section-${category.id}`,- label: category.label,- type: 'section',- };- })- .filter((section) => section.items.length > 0);+ let matchedCategories = categories.map((category) => ({+ ...category,+ items: category.items+ .filter((item) => rankByKey.has(String(item.key)))+ .sort(+ (a, b) =>+ (rankByKey.get(String(a.key)) ?? Number.MAX_SAFE_INTEGER) -+ (rankByKey.get(String(b.key)) ?? Number.MAX_SAFE_INTEGER),+ ),+ }));++ // Search reaches beyond the prefetched top entries; uninstalled matches+ // join the same sections as installed ones.+ if (market.agentCategory) {+ matchedCategories = mergeIntoCategory(+ matchedCategories,+ {+ ...market.agentCategory,+ items: marketResult.agents+ .filter((agent) => !market.installedAgentSources.has(agent.identifier))+ .map((agent) => toMarketAgentItem(agent, market.agentVisibility)),+ },+ AGENT_CATEGORY_IDS,+ );+ }+ matchedCategories = mergeIntoCategory(+ matchedCategories,+ {+ ...market.skillCategory,+ items: marketResult.skills+ .filter((skill) => !market.installedSkills.has(skill.identifier))+ .map(toMarketSkillItem),+ },+ SKILL_PRECEDING_IDS,+ );++ const matchedSections = limitMentionGroups(+ matchedCategories,+ SEARCH_MENTION_GROUP_LIMIT,+ ).map((category): ISlashSectionOption => ({+ items: category.items,+ key: `mention-section-${category.id}`,+ label: category.label,+ type: 'section',+ }));if (localFileItems.length > 0) {return [@@ -219,10 +262,12 @@ const InputEditor = memo<{}return mentionSections;},- [categories, fuse, mentionSections, searchLocalFiles, t],+ [categories, fuse, market, mentionSections, searchLocalFiles, t],);- const enableMention = isMentionEnabled && (allMentionItems.length > 0 || enableLocalFileTag);+ const enableMention =+ isMentionEnabled &&+ (allMentionItems.length > 0 || enableLocalFileTag || market.agents || market.skills);const heterogeneousName = heterogeneousType? (HETEROGENEOUS_TYPE_LABELS[heterogeneousType] ?? heterogeneousType): undefined;@@ -473,6 +518,7 @@ const InputEditor = memo<{type: String(option.metadata.actionType),};editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, payload);+ if (option.metadata.marketSkill) prepareMentionedMarketSkill(payload.type);} else if (option.metadata?.type === 'localFile') {editor.dispatchCommand(INSERT_LOCAL_FILE_TAG_COMMAND, {isDirectory: !!option.metadata.isDirectory,@@ -480,6 +526,14 @@ const InputEditor = memo<{path: String(option.metadata.path ?? ''),});} else {+ // Ready a Market agent (its hidden copy and Market skills) as soon as it is+ // picked; the send then only waits for what is still unfinished.+ if (typeof option.metadata?.marketIdentifier === 'string') {+ prepareMentionedMarketAgent(+ option.metadata.marketIdentifier,+ option.metadata.marketVisibility === 'private' ? 'private' : 'public',+ );+ }// Agent options carry a ReactNode label; the chip needs the plain name// kept in `metadata.label`. Other types (member) still use `label` itself.editor.dispatchCommand(INSERT_MENTION_COMMAND, {diff --git a/src/features/ChatInput/InputEditor/marketMention.test.ts b/src/features/ChatInput/InputEditor/marketMention.test.tsnew file mode 100644index 00000000000..29b42199b3a--- /dev/null+++ b/src/features/ChatInput/InputEditor/marketMention.test.ts@@ -0,0 +1,114 @@+import { describe, expect, it } from 'vitest';++import {+ applyInstalledMarketAgents,+ collectPendingMarketAgents,+ collectPendingMarketSkills,+ marketAgentMentionId,+} from './marketMention';++const mention = (label: string, metadata: Record<string, unknown>) => ({+ label,+ metadata,+ type: 'mention',+});++const skillTag = (actionType: string, actionLabel = actionType) => ({+ actionCategory: 'skill',+ actionLabel,+ actionType,+ type: 'action-tag',+});++const doc = (...children: unknown[]) => ({+ root: { children: [{ children, type: 'paragraph' }], type: 'root' },+});++const marketAgent = (identifier: string, visibility: 'private' | 'public' = 'public') =>+ mention(identifier.toUpperCase(), {+ id: marketAgentMentionId(identifier),+ label: identifier.toUpperCase(),+ marketIdentifier: identifier,+ marketVisibility: visibility,+ type: 'agent',+ });++describe('collectPendingMarketAgents', () => {+ it('returns each market agent once, ignoring installed agents and other mentions', () => {+ const editorData = doc(+ marketAgent('writer', 'private'),+ mention('Local', { id: 'agt_1', label: 'Local', type: 'agent' }),+ mention('Topic', { topicId: 'tpc_1', type: 'topic' }),+ marketAgent('writer', 'private'),+ marketAgent('coder'),+ );++ expect(collectPendingMarketAgents(editorData)).toEqual([+ { identifier: 'writer', label: 'WRITER', visibility: 'private' },+ { identifier: 'coder', label: 'CODER', visibility: 'public' },+ ]);+ });++ it('ignores a mention whose id was already resolved', () => {+ const resolved = mention('Writer', {+ id: 'agt_9',+ label: 'Writer',+ marketIdentifier: 'writer',+ type: 'agent',+ });++ expect(collectPendingMarketAgents(doc(resolved))).toEqual([]);+ });+});++describe('collectPendingMarketSkills', () => {+ it('returns skill tags that are not installed, deduped, with their display names', () => {+ const editorData = doc(+ skillTag('installed-skill'),+ skillTag('market-skill', '营销文案'),+ skillTag('market-skill', '营销文案'),+ skillTag('unlabeled-skill', ''),+ { actionCategory: 'tool', actionLabel: 'T', actionType: 'some-tool', type: 'action-tag' },+ );++ expect(collectPendingMarketSkills(editorData, new Set(['installed-skill']))).toEqual([+ { identifier: 'market-skill', label: '营销文案' },+ { identifier: 'unlabeled-skill', label: 'unlabeled-skill' },+ ]);+ });+});++describe('applyInstalledMarketAgents', () => {+ it('points the chip and the markdown at the installed agent', () => {+ const editorData = doc(marketAgent('writer'), marketAgent('coder'));+ const markdown = `<mention name="WRITER" id="${marketAgentMentionId('writer')}" /> and <mention name="CODER" id="${marketAgentMentionId('coder')}" /> hi <mention name="WRITER" id="${marketAgentMentionId('writer')}" />`;++ const result = applyInstalledMarketAgents(+ { editorData, markdown },+ new Map([+ ['writer', 'agt_w'],+ ['coder', 'agt_c'],+ ]),+ );++ expect(result.markdown).toBe(+ '<mention name="WRITER" id="agt_w" /> and <mention name="CODER" id="agt_c" /> hi <mention name="WRITER" id="agt_w" />',+ );+ const chips = (result.editorData as any).root.children[0].children;+ expect(chips[0].metadata).toEqual({ id: 'agt_w', label: 'WRITER', type: 'agent' });+ expect(chips[1].metadata).toEqual({ id: 'agt_c', label: 'CODER', type: 'agent' });+ expect(collectPendingMarketAgents(result.editorData)).toEqual([]);+ // The caller's editor JSON stays untouched.+ expect(collectPendingMarketAgents(editorData)).toHaveLength(2);+ });++ it('keeps market agents that were not installed pending', () => {+ const editorData = doc(marketAgent('writer'));+ const markdown = `<mention name="WRITER" id="${marketAgentMentionId('writer')}" />`;++ const result = applyInstalledMarketAgents({ editorData, markdown }, new Map());++ expect(result.markdown).toBe(markdown);+ expect(collectPendingMarketAgents(result.editorData)).toHaveLength(1);+ });+});diff --git a/src/features/ChatInput/InputEditor/marketMention.ts b/src/features/ChatInput/InputEditor/marketMention.tsnew file mode 100644index 00000000000..692bf3470c7--- /dev/null+++ b/src/features/ChatInput/InputEditor/marketMention.ts@@ -0,0 +1,106 @@+/**+ * Market entries offered by the @ menu are not installed yet. Their chips carry+ * a placeholder agent id (or, for skills, an identifier the local catalog does+ * not know); the composer installs them right before sending and swaps the+ * placeholders for the installed agent ids, so the runtime only ever sees+ * regular agent mentions and installed skills.+ */++const MARKET_AGENT_ID_PREFIX = 'market:';++export type MarketInstallVisibility = 'private' | 'public';++export interface PendingMarketAgent {+ identifier: string;+ label: string;+ visibility: MarketInstallVisibility;+}++export interface ComposerContent {+ editorData: Record<string, any> | undefined;+ markdown: string;+}++export const marketAgentMentionId = (identifier: string) =>+ `${MARKET_AGENT_ID_PREFIX}${identifier}`;++const isPendingMarketAgent = (metadata: Record<string, unknown> | undefined) =>+ metadata?.type === 'agent' &&+ typeof metadata.marketIdentifier === 'string' &&+ metadata.id === marketAgentMentionId(metadata.marketIdentifier);++const walk = (node: any, visit: (node: any) => void) => {+ if (!node) return;+ visit(node);+ if (Array.isArray(node.children)) for (const child of node.children) walk(child, visit);+};++export const collectPendingMarketAgents = (+ editorData: Record<string, any> | undefined,+): PendingMarketAgent[] => {+ const pending = new Map<string, PendingMarketAgent>();++ walk(editorData?.root, (node) => {+ if (node.type !== 'mention' || !isPendingMarketAgent(node.metadata)) return;+ const identifier = node.metadata.marketIdentifier as string;+ if (pending.has(identifier)) return;++ pending.set(identifier, {+ identifier,+ label: String(node.metadata.label ?? node.label ?? identifier),+ visibility: node.metadata.marketVisibility === 'private' ? 'private' : 'public',+ });+ });++ return [...pending.values()];+};++export interface PendingMarketSkill {+ identifier: string;+ /** Display name shown to the user while it is prepared or when it fails. */+ label: string;+}++/** Skill chips whose identifier is not installed locally — the menu only offers those from the market. */+export const collectPendingMarketSkills = (+ editorData: Record<string, any> | undefined,+ installedSkillIdentifiers: ReadonlySet<string>,+): PendingMarketSkill[] => {+ const pending = new Map<string, PendingMarketSkill>();++ walk(editorData?.root, (node) => {+ if (node.type !== 'action-tag' || node.actionCategory !== 'skill') return;+ const identifier = String(node.actionType ?? '');+ if (!identifier || installedSkillIdentifiers.has(identifier) || pending.has(identifier)) return;+ pending.set(identifier, { identifier, label: String(node.actionLabel || identifier) });+ });++ return [...pending.values()];+};++/** Point the chips and the serialized `<mention>` tags at the installed agents. */+export const applyInstalledMarketAgents = (+ { editorData, markdown }: ComposerContent,+ installedAgentIds: ReadonlyMap<string, string>,+): ComposerContent => {+ if (installedAgentIds.size === 0) return { editorData, markdown };++ const nextEditorData = editorData ? structuredClone(editorData) : editorData;+ walk(nextEditorData?.root, (node) => {+ if (node.type !== 'mention' || !isPendingMarketAgent(node.metadata)) return;+ const { marketIdentifier, marketVisibility: _visibility, ...rest } = node.metadata;+ const agentId = installedAgentIds.get(marketIdentifier);+ if (!agentId) return;++ node.metadata = { ...rest, id: agentId };+ });++ let nextMarkdown = markdown;+ for (const [identifier, agentId] of installedAgentIds) {+ nextMarkdown = nextMarkdown+ .split(`id="${marketAgentMentionId(identifier)}"`)+ .join(`id="${agentId}"`);+ }++ return { editorData: nextEditorData, markdown: nextMarkdown };+};diff --git a/src/features/ChatInput/InputEditor/marketMentionItems.tsx b/src/features/ChatInput/InputEditor/marketMentionItems.tsxnew file mode 100644index 00000000000..6698b1bcac3--- /dev/null+++ b/src/features/ChatInput/InputEditor/marketMentionItems.tsx@@ -0,0 +1,143 @@+import type { ISlashMenuOption } from '@lobehub/editor';+import { Avatar, cssVar, Flexbox } from '@lobehub/ui';+import type { ReactNode } from 'react';++import { discoverService } from '@/services/discover';+import { globalHelpers } from '@/store/global/helpers';+import type { DiscoverAssistantItem, DiscoverSkillItem } from '@/types/discover';++import { marketAgentMentionId, type MarketInstallVisibility } from './marketMention';+import MentionItemIcon from './MentionItemIcon';++/** Market rows fetched per list; installed ones are filtered out of it, so ask for more than shown. */+export const MARKET_MENTION_FETCH_SIZE = 12;+const SEARCH_TIMEOUT_MS = 1500;+const SEARCH_CACHE_SIZE = 50;++export const mentionLabel = (title: string, secondary?: string): ReactNode =>+ secondary ? (+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0, overflow: 'hidden' }}>+ <span style={{ flex: 'none' }}>{title}</span>+ <span+ style={{+ color: cssVar.colorTextDescription,+ fontSize: 12,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ >+ {secondary}+ </span>+ </Flexbox>+ ) : (+ title+ );++export const toMarketAgentItem = (+ agent: DiscoverAssistantItem,+ visibility: MarketInstallVisibility,+): ISlashMenuOption => {+ const title = agent.title?.trim() || agent.identifier;+ const description = agent.description?.trim();++ return {+ icon: (+ <Avatar+ avatar={typeof agent.avatar === 'string' ? agent.avatar : undefined}+ background={agent.backgroundColor ?? undefined}+ size={24}+ />+ ),+ key: `market-agent-${agent.identifier}`,+ label: mentionLabel(title, description),+ metadata: {+ id: marketAgentMentionId(agent.identifier),+ label: title,+ marketIdentifier: agent.identifier,+ marketVisibility: visibility,+ searchText: [title, description, ...(agent.tags ?? [])].filter(Boolean).join(' '),+ timestamp: 0,+ type: 'agent' as const,+ },+ };+};++export const toMarketSkillItem = (skill: DiscoverSkillItem): ISlashMenuOption => {+ const label = skill.name?.trim() || skill.identifier;++ return {+ icon: <MentionItemIcon avatar={skill.icon} category={'skill'} label={label} />,+ key: `market-skill-${skill.identifier}`,+ label,+ metadata: {+ actionCategory: 'skill',+ actionType: skill.identifier,+ description: skill.description,+ // Installed the moment it is picked, so the send does not wait for it.+ marketSkill: true,+ searchText: [label, skill.description].filter(Boolean).join(' '),+ timestamp: 0,+ type: 'skill' as const,+ },+ };+};++export interface MarketSearchResult {+ agents: DiscoverAssistantItem[];+ skills: DiscoverSkillItem[];+}++const searchCache = new Map<string, Promise<MarketSearchResult>>();++const searchMarket = (+ query: string,+ { agents, skills }: { agents: boolean; skills: boolean },+): Promise<MarketSearchResult> => {+ const key = `${globalHelpers.getCurrentLanguage()}:${agents}:${skills}:${query}`;+ const cached = searchCache.get(key);+ if (cached) return cached;++ const request = Promise.all([+ agents+ ? discoverService+ .getAssistantList({ page: 1, pageSize: MARKET_MENTION_FETCH_SIZE, q: query })+ .then((result) => result.items)+ : [],+ skills+ ? discoverService+ .getSkillList({ page: 1, pageSize: MARKET_MENTION_FETCH_SIZE, q: query })+ .then((result) => result.items)+ : [],+ ]).then(([agentItems, skillItems]) => ({ agents: agentItems, skills: skillItems }));++ searchCache.set(key, request);+ request.catch(() => searchCache.delete(key));+ if (searchCache.size > SEARCH_CACHE_SIZE) {+ searchCache.delete(searchCache.keys().next().value!);+ }+ return request;+};++const EMPTY_RESULT: MarketSearchResult = { agents: [], skills: [] };++/**+ * Market search for the @ menu. Never rejects and never holds the menu longer+ * than the timeout: a slow answer is still cached, so the next keystroke shows it.+ */+export const searchMarketForMention = (+ query: string,+ scope: { agents: boolean; skills: boolean },+): Promise<MarketSearchResult> => {+ if (!query.trim() || (!scope.agents && !scope.skills)) return Promise.resolve(EMPTY_RESULT);++ return Promise.race([+ searchMarket(query.trim(), scope).catch((error) => {+ console.warn('[mention] market search failed:', error);+ return EMPTY_RESULT;+ }),+ new Promise<MarketSearchResult>((resolve) =>+ setTimeout(() => resolve(EMPTY_RESULT), SEARCH_TIMEOUT_MS),+ ),+ ]);+};diff --git a/src/features/ChatInput/InputEditor/mentionMenuSections.test.ts b/src/features/ChatInput/InputEditor/mentionMenuSections.test.tsnew file mode 100644index 00000000000..78948346fcc--- /dev/null+++ b/src/features/ChatInput/InputEditor/mentionMenuSections.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from 'vitest';++import type { MentionCategory, MentionCategoryId } from './MentionMenu/types';+import { limitMentionGroups, mergeIntoCategory } from './mentionMenuSections';++const category = (id: MentionCategoryId, count: number): MentionCategory => ({+ icon: null,+ id,+ items: Array.from({ length: count }, (_, i) => ({ key: `${id}-${i}`, label: `${id} ${i}` })),+ label: id,+});++const keysById = (categories: MentionCategory[]) =>+ Object.fromEntries(categories.map((c) => [c.id, c.items.map((item) => item.key)]));++describe('limitMentionGroups', () => {+ it('shares one budget across the agent sections and caps skills', () => {+ const result = limitMentionGroups(+ [+ category('agent-private', 1),+ category('agent-workspace', 5),+ category('topic', 6),+ category('skill', 5),+ category('tool', 4),+ ],+ 3,+ );++ expect(keysById(result)).toEqual({+ 'agent-private': ['agent-private-0'],+ 'agent-workspace': ['agent-workspace-0', 'agent-workspace-1'],+ 'skill': ['skill-0', 'skill-1', 'skill-2'],+ 'tool': ['tool-0', 'tool-1', 'tool-2', 'tool-3'],+ 'topic': ['topic-0', 'topic-1', 'topic-2', 'topic-3', 'topic-4', 'topic-5'],+ });+ });++ it('drops a section the budget never reached instead of rendering it empty', () => {+ const result = limitMentionGroups(+ [category('agent-private', 3), category('agent-workspace', 2)],+ 3,+ );++ expect(result.map((c) => c.id)).toEqual(['agent-private']);+ });+});++describe('mergeIntoCategory', () => {+ it('appends entries to the existing section without duplicates', () => {+ const result = mergeIntoCategory(+ [category('agent', 1)],+ {+ ...category('agent', 0),+ items: [+ { key: 'agent-0', label: 'dup' },+ { key: 'remote', label: 'remote' },+ ],+ },+ [],+ );++ expect(keysById(result)).toEqual({ agent: ['agent-0', 'remote'] });+ });++ it('creates a missing section after the last listed sibling', () => {+ const result = mergeIntoCategory(+ [category('agent', 1), category('topic', 1), category('tool', 1)],+ { ...category('skill', 0), items: [{ key: 'remote', label: 'remote' }] },+ ['agent', 'member', 'topic'],+ );++ expect(result.map((c) => c.id)).toEqual(['agent', 'topic', 'skill', 'tool']);+ });+});diff --git a/src/features/ChatInput/InputEditor/mentionMenuSections.ts b/src/features/ChatInput/InputEditor/mentionMenuSections.tsnew file mode 100644index 00000000000..99135845c75--- /dev/null+++ b/src/features/ChatInput/InputEditor/mentionMenuSections.ts@@ -0,0 +1,70 @@+import type { ISlashMenuOption } from '@lobehub/editor';++import type { MentionCategory, MentionCategoryId } from './MentionMenu/types';++/** Sections an uninstalled agent may join or follow. */+export const AGENT_CATEGORY_IDS: MentionCategoryId[] = [+ 'agent',+ 'agent-private',+ 'agent-workspace',+];+/** Sections the skill section follows when it has to be created. */+export const SKILL_PRECEDING_IDS: MentionCategoryId[] = [...AGENT_CATEGORY_IDS, 'member', 'topic'];++/** Entries per group in the menu before the user types. */+export const DEFAULT_MENTION_GROUP_LIMIT = 3;+/** Entries per group once the user filters by a keyword. */+export const SEARCH_MENTION_GROUP_LIMIT = 8;++/** The agent sections (private / workspace) share one budget, filled in section order. */+const GROUP_OF: Partial<Record<MentionCategoryId, 'agent' | 'skill'>> = {+ 'agent': 'agent',+ 'agent-private': 'agent',+ 'agent-workspace': 'agent',+ 'skill': 'skill',+};++export const limitMentionGroups = (+ categories: MentionCategory[],+ limit: number,+): MentionCategory[] => {+ const remaining = { agent: limit, skill: limit };++ return categories+ .map((category) => {+ const group = GROUP_OF[category.id];+ if (!group) return category;++ const items = category.items.slice(0, Math.max(remaining[group], 0));+ remaining[group] -= items.length;+ return { ...category, items };+ })+ .filter((category) => category.items.length > 0);+};++/** Append entries to a category (created after `afterId` when missing), skipping keys already listed. */+export const mergeIntoCategory = (+ categories: MentionCategory[],+ extra: Omit<MentionCategory, 'items'> & { items: ISlashMenuOption[] },+ afterIds: MentionCategoryId[],+): MentionCategory[] => {+ if (extra.items.length === 0) return categories;++ const existing = categories.find((category) => category.id === extra.id);+ if (existing) {+ const keys = new Set(existing.items.map((item) => String(item.key)));+ const items = [...existing.items, ...extra.items.filter((item) => !keys.has(String(item.key)))];+ return categories.map((category) =>+ category === existing ? { ...category, items } : category,+ );+ }++ let insertAt = 0;+ for (let i = categories.length - 1; i >= 0; i--) {+ if (afterIds.includes(categories[i].id)) {+ insertAt = i + 1;+ break;+ }+ }+ return [...categories.slice(0, insertAt), extra, ...categories.slice(insertAt)];+};diff --git a/src/features/ChatInput/InputEditor/useMentionCategories.tsx b/src/features/ChatInput/InputEditor/useMentionCategories.tsxindex 96a7bf3928c..42d3be3efaa 100644--- a/src/features/ChatInput/InputEditor/useMentionCategories.tsx+++ b/src/features/ChatInput/InputEditor/useMentionCategories.tsx@@ -1,5 +1,5 @@import { agentDisplayName } from '@lobechat/types';-import { Avatar, cssVar, Flexbox, Icon } from '@lobehub/ui';+import { Avatar, Icon } from '@lobehub/ui';import { SkillsIcon } from '@lobehub/ui/icons';import isEqual from 'fast-deep-equal';import { Bot, Lock, MessageSquareText, Users, Wrench } from 'lucide-react';@@ -7,24 +7,56 @@ import { useMemo } from 'react';import { useTranslation } from 'react-i18next';import type { SidebarAgentItem } from '@/database/repositories/home';+import { usePermission } from '@/hooks/usePermission';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';+import { useDiscoverStore } from '@/store/discover';+import { assistantSelectors, skillSelectors } from '@/store/discover/selectors';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { useHomeStore } from '@/store/home';import { homeAgentListSelectors } from '@/store/home/selectors';+import { useToolStore } from '@/store/tool';+import { AssistantSorts, SkillSorts } from '@/types/discover';import { useAgentId } from '../hooks/useAgentId';import { useChatInputStore } from '../store';import { useInstalledSkillsAndTools } from './ActionTag/useInstalledSkillsAndTools';+import type { MarketInstallVisibility } from './marketMention';+import {+ MARKET_MENTION_FETCH_SIZE,+ mentionLabel,+ toMarketAgentItem,+ toMarketSkillItem,+} from './marketMentionItems';import MentionItemIcon from './MentionItemIcon';import type { MentionCategory } from './MentionMenu/types';+import { AGENT_CATEGORY_IDS, mergeIntoCategory, SKILL_PRECEDING_IDS } from './mentionMenuSections';const MAX_AGENT_ITEMS = 20;const MAX_TOPIC_LABEL = 50;type MenuOptionWithMetadata = { key: string; metadata?: Record<string, unknown> };-export const useMentionCategories = (): MentionCategory[] => {+/** What the menu needs to turn a Market search into installable entries. */+export interface MarketMentionScope {+ /** Section uninstalled agents join (where they land once installed); absent in group chats. */+ agentCategory?: Omit<MentionCategory, 'items'>;+ agents: boolean;+ agentVisibility: MarketInstallVisibility;+ /** Market identifiers the caller already has as a mentionable agent here. */+ installedAgentSources: ReadonlySet<string>;+ installedSkills: ReadonlySet<string>;+ /** Section uninstalled skills join. */+ skillCategory: Omit<MentionCategory, 'items'>;+ skills: boolean;+}++export interface MentionSource {+ categories: MentionCategory[];+ market: MarketMentionScope;+}++export const useMentionCategories = (): MentionSource => {const { t } = useTranslation('chat');const currentAgentId = useAgentId();const pinnedAgents = useHomeStore(homeAgentListSelectors.pinnedAgents, isEqual);@@ -45,10 +77,34 @@ export const useMentionCategories = (): MentionCategory[] => {const externalMentionItems = useChatInputStore((s) => s.mentionItems);const isGroupChat = !!externalMentionItems;+ // The installed-skill list is otherwise only fetched by skill settings pages;+ // without it here, a Market skill installed from this menu (or anywhere+ // else) would keep being offered as not installed after a reload.+ const useFetchAgentSkills = useToolStore((s) => s.useFetchAgentSkills);+ useFetchAgentSkills(true);const enabledSkills = useInstalledSkillsAndTools();+ // Market entries install on send, which creates content in the active scope.+ const { allowed: canInstall } = usePermission('create_content');+ const useAssistantList = useDiscoverStore((s) => s.useFetchAssistantList);+ const useSkillList = useDiscoverStore((s) => s.useFetchSkillList);+ const marketAgentsEnabled = canInstall && !isGroupChat;+ const { queryKey: marketAgentKey } = useAssistantList(+ { page: 1, pageSize: MARKET_MENTION_FETCH_SIZE, sort: AssistantSorts.Recommended },+ { enabled: marketAgentsEnabled },+ );+ const { queryKey: marketSkillKey } = useSkillList(+ { page: 1, pageSize: MARKET_MENTION_FETCH_SIZE, sort: SkillSorts.InstallCount },+ { enabled: canInstall },+ );+ const marketAgents = useDiscoverStore(assistantSelectors.assistantList(marketAgentKey))?.items;+ const marketSkills = useDiscoverStore(skillSelectors.skillList(marketSkillKey))?.items;+return useMemo(() => {- const categories: MentionCategory[] = [];+ let categories: MentionCategory[] = [];+ let agentCategory: Omit<MentionCategory, 'items'> | undefined;+ const installedAgentSources = new Set<string>();+ let agentVisibility: MarketInstallVisibility = 'public';const toItem = (agent: SidebarAgentItem) => {const name = agent.name?.trim();@@ -69,24 +125,7 @@ export const useMentionCategories = (): MentionCategory[] => {/>),key: `agent-${agent.id}`,- label: secondary ? (- <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0, overflow: 'hidden' }}>- <span style={{ flex: 'none' }}>{displayName}</span>- <span- style={{- color: cssVar.colorTextDescription,- fontSize: 12,- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap',- }}- >- {secondary}- </span>- </Flexbox>- ) : (- displayName- ),+ label: mentionLabel(displayName, secondary),metadata: {id: agent.id,// The rendered label is a ReactNode; keep the plain-text identity here@@ -146,6 +185,32 @@ export const useMentionCategories = (): MentionCategory[] => {// effectively invisible to the rest of the workspace and the private// invariant holds.const isCurrentContextPrivate = !!currentAgentId && privateAgentIds.has(currentAgentId);+ // A Market agent installed from here lands where it can be mentioned+ // again: private beside a private agent, shared otherwise.+ agentVisibility = isCurrentContextPrivate ? 'private' : 'public';++ // Market agents already installed and mentionable here (or the current+ // agent itself) are not offered again from the Market.+ const mentionableHere = [+ ...pinnedAgents,+ ...workspaceGroups.flatMap((g) => g.items),+ ...workspaceUngrouped,+ ...(isCurrentContextPrivate+ ? [...privatePinned, ...privateGroups.flatMap((g) => g.items), ...privateUngrouped]+ : []),+ ];+ for (const agent of mentionableHere) {+ if (agent.forkedFromIdentifier) installedAgentSources.add(agent.forkedFromIdentifier);+ }+ const currentAgent = [+ ...mentionableHere,+ ...privatePinned,+ ...privateGroups.flatMap((g) => g.items),+ ...privateUngrouped,+ ].find((agent) => agent.id === currentAgentId);+ if (currentAgent?.forkedFromIdentifier) {+ installedAgentSources.add(currentAgent.forkedFromIdentifier);+ }// Quota stays at MAX_AGENT_ITEMS total. When the user has private agents// we reserve up to half for them so they don't get drowned out by a long@@ -180,6 +245,36 @@ export const useMentionCategories = (): MentionCategory[] => {label,});}++ // Uninstalled entries sit in the same section as installed ones — where+ // they will land once installed on send — so the user never sees a+ // difference between the two.+ agentCategory = isCurrentContextPrivate+ ? {+ icon: <Icon icon={Lock} size={16} />,+ id: 'agent-private',+ label: t('mention.category.privateAgents'),+ }+ : {+ icon: <Icon icon={Bot} size={16} />,+ id: privateItems.length > 0 ? 'agent-workspace' : 'agent',+ label:+ privateItems.length > 0+ ? t('mention.category.workspaceAgents')+ : t('mention.category.agents'),+ };+ if (marketAgentsEnabled) {+ categories = mergeIntoCategory(+ categories,+ {+ ...agentCategory,+ items: (marketAgents ?? [])+ .filter((agent) => !installedAgentSources.has(agent.identifier))+ .map((agent) => toMarketAgentItem(agent, agentVisibility)),+ },+ AGENT_CATEGORY_IDS,+ );+ }}// --- Members (group chat only) ---@@ -254,6 +349,25 @@ export const useMentionCategories = (): MentionCategory[] => {});}+ const installedSkills = new Set(skillItems.map((item) => item.type));+ const skillCategory: Omit<MentionCategory, 'items'> = {+ icon: <Icon icon={SkillsIcon} size={16} />,+ id: 'skill',+ label: t('mention.category.skills'),+ };+ if (canInstall) {+ categories = mergeIntoCategory(+ categories,+ {+ ...skillCategory,+ items: (marketSkills ?? [])+ .filter((skill) => !installedSkills.has(skill.identifier))+ .map(toMarketSkillItem),+ },+ SKILL_PRECEDING_IDS,+ );+ }+// --- Tools ---const toolItems = enabledSkills.filter((s) => s.category === 'tool');if (toolItems.length > 0) {@@ -276,7 +390,18 @@ export const useMentionCategories = (): MentionCategory[] => {});}- return categories;+ return {+ categories,+ market: {+ agentCategory,+ agentVisibility,+ agents: marketAgentsEnabled,+ installedAgentSources,+ installedSkills,+ skillCategory,+ skills: canInstall,+ },+ };}, [pinnedAgents,workspaceGroups,@@ -290,6 +415,10 @@ export const useMentionCategories = (): MentionCategory[] => {isGroupChat,externalMentionItems,enabledSkills,+ canInstall,+ marketAgentsEnabled,+ marketAgents,+ marketSkills,t,]);};diff --git a/src/features/ChatInput/SendArea/SendButton.tsx b/src/features/ChatInput/SendArea/SendButton.tsxindex f9f6c24ecd5..e2b19c85ac7 100644--- a/src/features/ChatInput/SendArea/SendButton.tsx+++ b/src/features/ChatInput/SendArea/SendButton.tsx@@ -19,6 +19,8 @@ const SendButton = memo(() => {isEqual,);const [send, handleStop] = useChatInputStore((s) => [s.handleSendButton, s.handleStop]);+ // Market agents/skills picked from the @ menu install before the send commits.+ const installing = useChatInputStore((s) => s.installingMarketMentions);// Workspace viewer doesn't have `message:create` → backend would 403.// OR the permission gate into the existing disabled prop so the button@@ -39,6 +41,7 @@ const SendButton = memo(() => {<Send generating shape={shape} size={size} onStop={() => handleStop()} /><Senddisabled={disabled || !canSend}+ loading={installing}shape={shape}size={size}onClick={canSend ? () => send() : undefined}@@ -48,6 +51,7 @@ const SendButton = memo(() => {<Senddisabled={disabled || !canSend}generating={generating}+ loading={installing}menu={canSend ? (sendMenu as any) : undefined}placement={'topRight'}shape={shape}diff --git a/src/features/ChatInput/store/action.test.ts b/src/features/ChatInput/store/action.test.tsindex af4dfbbfb78..ce786c2e9e5 100644--- a/src/features/ChatInput/store/action.test.ts+++ b/src/features/ChatInput/store/action.test.ts@@ -1,8 +1,10 @@import type { IEditor } from '@lobehub/editor';import { CommonPlugin, Kernel, MarkdownPlugin } from '@lobehub/editor';+import { toast } from '@lobehub/ui';import { $createParagraphNode, $createTextNode, $getRoot, KEY_ESCAPE_COMMAND } from 'lexical';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { installMarketMentions, MarketMentionInstallError } from '@/services/mentionMarketInstall';import { useAgentStore } from '@/store/agent';import { systemAgentSelectors } from '@/store/user/selectors';@@ -10,6 +12,11 @@ import { getDraft, saveDraft } from '../draftStorage';import { getInputHistory } from '../inputHistoryStorage';import { createStore, selectors } from '.';+vi.mock('@/services/mentionMarketInstall', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ installMarketMentions: vi.fn(),+}));+describe('ChatInput store actions', () => {beforeEach(() => {localStorage.clear();@@ -170,7 +177,6 @@ describe('ChatInput store actions', () => {store.getState().handleSendButton();expect(getInputHistory()).toEqual([]);- expect(editor.getDocument).not.toHaveBeenCalled();});it('clears the input-completion ghost before sending when autocomplete is enabled', () => {@@ -322,4 +328,155 @@ describe('ChatInput store actions', () => {expect(sent).toBe(prompt);});++ describe('market entries picked from the @ menu', () => {+ const marketDoc = {+ root: {+ children: [+ {+ children: [+ {+ label: 'Writer',+ metadata: {+ id: 'market:writer',+ label: 'Writer',+ marketIdentifier: 'writer',+ marketVisibility: 'public',+ type: 'agent',+ },+ type: 'mention',+ },+ ],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ };+ const marketEditor = () => ({+ cleanDocument: vi.fn(),+ dispatchCommand: vi.fn(),+ focus: vi.fn(),+ getDocument: vi.fn((type: string) =>+ type === 'markdown' ? '<mention name="Writer" id="market:writer" /> hi' : marketDoc,+ ),+ getLexicalEditor: () => ({}),+ });++ beforeEach(() => {+ vi.mocked(installMarketMentions).mockReset();+ });++ it('installs them first and sends the installed agent id', async () => {+ vi.mocked(installMarketMentions).mockResolvedValue(new Map([['writer', 'agt_writer']]));+ const loadingToast = vi.spyOn(toast, 'loading');+ const onSend = vi.fn();+ const store = createStore({ editor: marketEditor() as unknown as IEditor, onSend });++ store.getState().handleSendButton();++ expect(installMarketMentions).toHaveBeenCalledWith({+ agents: [{ identifier: 'writer', label: 'Writer', visibility: 'public' }],+ skills: [],+ });+ expect(onSend).not.toHaveBeenCalled();+ // The send button's spinner is the only progress cue; no toast.+ expect(store.getState().installingMarketMentions).toBe(true);+ expect(loadingToast).not.toHaveBeenCalled();++ await vi.waitFor(() => expect(onSend).toHaveBeenCalledOnce());+ const { getEditorData, getMarkdownContent } = onSend.mock.calls[0][0];+ expect(getMarkdownContent()).toBe('<mention name="Writer" id="agt_writer" /> hi');+ expect(getEditorData().root.children[0].children[0].metadata).toEqual({+ id: 'agt_writer',+ label: 'Writer',+ type: 'agent',+ });+ expect(store.getState().installingMarketMentions).toBe(false);+ });++ it('sends what the composer holds once ready, even if it was edited during the install', async () => {+ // The composer stays editable while the picked agent installs; replacing+ // it must not send the new agent's unresolved Market placeholder.+ const poetDoc = structuredClone(marketDoc);+ Object.assign(poetDoc.root.children[0].children[0], {+ label: 'Poet',+ metadata: {+ id: 'market:poet',+ label: 'Poet',+ marketIdentifier: 'poet',+ marketVisibility: 'public',+ type: 'agent',+ },+ });+ let current: typeof marketDoc = marketDoc;+ const editor = {+ ...marketEditor(),+ getDocument: vi.fn((type: string) =>+ type === 'markdown'+ ? `<mention name="${current.root.children[0].children[0].label}" id="${current.root.children[0].children[0].metadata.id}" /> hi`+ : current,+ ),+ };+ vi.mocked(installMarketMentions)+ .mockImplementationOnce(async () => {+ current = poetDoc;+ return new Map([['writer', 'agt_writer']]);+ })+ .mockResolvedValueOnce(new Map([['poet', 'agt_poet']]));+ const onSend = vi.fn();+ const store = createStore({ editor: editor as unknown as IEditor, onSend });++ store.getState().handleSendButton();++ await vi.waitFor(() => expect(onSend).toHaveBeenCalledOnce());+ expect(installMarketMentions).toHaveBeenLastCalledWith({+ agents: [{ identifier: 'poet', label: 'Poet', visibility: 'public' }],+ skills: [],+ });+ expect(onSend.mock.calls[0][0].getMarkdownContent()).toBe(+ '<mention name="Poet" id="agt_poet" /> hi',+ );+ expect(store.getState().installingMarketMentions).toBe(false);+ });++ it('drops the send when the composer moved to another conversation during the install', async () => {+ // The composer store outlives a topic switch: the other conversation's+ // draft must not be sent without the user pressing Send there.+ let current: unknown = marketDoc;+ const editor = { ...marketEditor(), getDocument: vi.fn(() => current) };+ const onSend = vi.fn();+ const store = createStore({+ draftKey: 'topic-a',+ editor: editor as unknown as IEditor,+ onSend,+ });+ vi.mocked(installMarketMentions).mockImplementation(async () => {+ current = { root: { children: [{ children: [], type: 'paragraph' }], type: 'root' } };+ store.setState({ draftKey: 'topic-b' });+ return new Map([['writer', 'agt_writer']]);+ });++ store.getState().handleSendButton();+ await vi.waitFor(() => expect(store.getState().installingMarketMentions).toBe(false));++ expect(installMarketMentions).toHaveBeenCalledOnce();+ expect(onSend).not.toHaveBeenCalled();+ expect(editor.cleanDocument).not.toHaveBeenCalled();+ });++ it('keeps the message in the composer when the install fails', async () => {+ vi.mocked(installMarketMentions).mockRejectedValue(new MarketMentionInstallError(['Writer']));+ const onSend = vi.fn();+ const editor = marketEditor();+ const store = createStore({ editor: editor as unknown as IEditor, onSend });++ store.getState().handleSendButton();+ await vi.waitFor(() => expect(store.getState().installingMarketMentions).toBe(false));++ expect(onSend).not.toHaveBeenCalled();+ expect(editor.cleanDocument).not.toHaveBeenCalled();+ expect(getInputHistory()).toEqual([]);+ });+ });});diff --git a/src/features/ChatInput/store/action.ts b/src/features/ChatInput/store/action.tsindex 5c7248b2d4e..fa35cc5b786 100644--- a/src/features/ChatInput/store/action.ts+++ b/src/features/ChatInput/store/action.ts@@ -1,12 +1,21 @@+import { toast } from '@lobehub/ui';+import { t } from 'i18next';import { KEY_ESCAPE_COMMAND } from 'lexical';import { type StateCreator } from 'zustand/vanilla';+import { installMarketMentions, MarketMentionInstallError } from '@/services/mentionMarketInstall';import { useAgentStore } from '@/store/agent';import { useUserStore } from '@/store/user';import { systemAgentSelectors, userProfileSelectors } from '@/store/user/selectors';import { removeDraft } from '../draftStorage';import { readDocument, writeDocument } from '../editorDocument';+import { getInstalledSkillIdentifiers } from '../InputEditor/ActionTag/useInstalledSkillsAndTools';+import {+ applyInstalledMarketAgents,+ collectPendingMarketAgents,+ collectPendingMarketSkills,+} from '../InputEditor/marketMention';import { addInputHistory } from '../inputHistoryStorage';import { type PublicState, type State } from './initialState';import { initialState } from './initialState';@@ -63,7 +72,8 @@ export const store: CreateStore = (publicState) => (set, get) => ({const editor = get().editor;if (!editor) return;- const { resolveSendBlocked, sendButtonProps } = get();+ const { installingMarketMentions, resolveSendBlocked, sendButtonProps } = get();+ if (installingMarketMentions) return;if (resolveSendBlocked ? resolveSendBlocked() : sendButtonProps?.disabled) return;// Drop any pending AI input-completion ghost before serializing the message.@@ -78,45 +88,102 @@ export const store: CreateStore = (publicState) => (set, get) => ({editor.dispatchCommand(KEY_ESCAPE_COMMAND, new KeyboardEvent('keydown', { key: 'Escape' }));}- const onSend = get().onSend;- const historyEnabled = !!onSend && (get().feature?.inputHistory ?? true);- const historySnapshot = historyEnabled- ? {- agentId: getEffectiveAgentId(get().agentId),- json: get().getJSONState(),- markdown: get().getMarkdownContent(),- userId: userProfileSelectors.userId(useUserStore.getState()),- }- : undefined;-- // Tie the draft's fate to the composer actually being cleared: a host may- // decline the send after the fact (a rejected scheduled send keeps the text- // on screen), and the key is captured here because committing the send can- // move the conversation to a freshly created topic.- const sentDraftKey = get().draftKey;-- onSend?.({- clearContent: () => {- editor?.cleanDocument();- if (sentDraftKey) removeDraft(sentDraftKey);- },- editor: editor!,- getEditorData: get().getJSONState,- getMarkdownContent: get().getMarkdownContent,- });-- if (historySnapshot) {- addInputHistory(historySnapshot);+ const commit = (installedAgentIds: ReadonlyMap<string, string> = new Map()) => {+ // Market chips picked from the @ menu were installed just before this+ // commit: every read of the content sees the installed agent ids.+ const readContent = () =>+ applyInstalledMarketAgents(+ { editorData: get().getJSONState(), markdown: get().getMarkdownContent() },+ installedAgentIds,+ );++ const onSend = get().onSend;+ const historyEnabled = !!onSend && (get().feature?.inputHistory ?? true);+ const historySnapshot = historyEnabled+ ? (() => {+ const { editorData, markdown } = readContent();+ return {+ agentId: getEffectiveAgentId(get().agentId),+ json: editorData,+ markdown,+ userId: userProfileSelectors.userId(useUserStore.getState()),+ };+ })()+ : undefined;++ // Tie the draft's fate to the composer actually being cleared: a host may+ // decline the send after the fact (a rejected scheduled send keeps the text+ // on screen), and the key is captured here because committing the send can+ // move the conversation to a freshly created topic.+ const sentDraftKey = get().draftKey;++ onSend?.({+ clearContent: () => {+ editor?.cleanDocument();+ if (sentDraftKey) removeDraft(sentDraftKey);+ },+ editor: editor!,+ getEditorData: () => readContent().editorData,+ getMarkdownContent: () => readContent().markdown,+ });++ if (historySnapshot) {+ addInputHistory(historySnapshot);+ }++ if (get().expand) {+ set({ _savedEditorState: undefined, expand: false });+ }+ requestAnimationFrame(() => {+ requestAnimationFrame(() => {+ editor.focus();+ });+ });+ };++ // Nothing would consume the message, so there is nothing worth installing for.+ if (!get().onSend) {+ commit();+ return;}- if (get().expand) {- set({ _savedEditorState: undefined, expand: false });+ const editorData = get().getJSONState();+ const pending = {+ agents: collectPendingMarketAgents(editorData),+ skills: collectPendingMarketSkills(editorData, getInstalledSkillIdentifiers()),+ };+ if (pending.agents.length === 0 && pending.skills.length === 0) {+ commit();+ return;}- requestAnimationFrame(() => {- requestAnimationFrame(() => {- editor.focus();++ // Install what the message picked from the Market, then send. The composer+ // keeps its content until the install succeeds, so a failure loses nothing;+ // the send button's spinner is the only progress cue while it waits.+ const names = [...pending.agents, ...pending.skills].map((item) => item.label).join('、');+ const submitted = JSON.stringify(editorData);+ const submittedDraftKey = get().draftKey;+ set({ installingMarketMentions: true });+ installMarketMentions(pending)+ .then((installedAgentIds) => {+ set({ installingMarketMentions: false });+ // The composer outlives a conversation switch; the conversation it now+ // shows never asked to send, so the send is dropped.+ if (get().draftKey !== submittedDraftKey) return;+ // The composer stays editable meanwhile: an edit may pick other Market+ // entries, so send its current content through the same preparation.+ if (JSON.stringify(get().getJSONState()) !== submitted) {+ get().handleSendButton();+ return;+ }+ commit(installedAgentIds);+ })+ .catch((error) => {+ set({ installingMarketMentions: false });+ const failed =+ error instanceof MarketMentionInstallError ? error.failedNames.join('、') : names;+ toast.error(t('mention.marketInstall.failed', { names: failed, ns: 'chat' }));});- });},handleStop: () => {diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.tsindex 0bc44976dfa..75736c32f0b 100644--- a/src/features/ChatInput/store/initialState.ts+++ b/src/features/ChatInput/store/initialState.ts@@ -112,6 +112,8 @@ export interface State extends PublicState {editor?: IEditor;inputCompletionError?: InputCompletionError;inputCompletionErrorDismissed: boolean;+ /** Market agents/skills picked from the @ menu are being installed before the send commits. */+ installingMarketMentions: boolean;isContentEmpty: boolean;markdownContent: string;slashMenuRef: ChatInputProps['slashMenuRef'];@@ -123,6 +125,7 @@ export const initialState: State = {expand: false,feature: DEFAULT_CHAT_INPUT_FEATURE,inputCompletionErrorDismissed: false,+ installingMarketMentions: false,isContentEmpty: false,leftActions: [],markdownContent: '',diff --git a/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/index.tsx b/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/index.tsxnew file mode 100644index 00000000000..87e720375f5--- /dev/null+++ b/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/index.tsx@@ -0,0 +1,116 @@+'use client';++import { formatDuration } from '@lobechat/utils';+import { Block, Button, Flexbox, Tag, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { SquareArrowOutUpRightIcon } from 'lucide-react';+import { memo, useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useChatStore } from '@/store/chat';++import { contextSelectors, useConversationStore } from '../../../../store';+import { summarizeThreadProgress } from './summarize';+import { selectThreadTranscript } from './threadTranscript';++const styles = stylex.create({+ activity: {+ color: cssVar.colorTextTertiary,+ fontSize: 13,+ },+ text: {+ color: cssVar.colorText,+ },+});++const useElapsed = (startedAt: number) => {+ const [now, setNow] = useState(() => Date.now());++ useEffect(() => {+ const timer = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(timer);+ }, []);++ return Math.max(0, now - startedAt);+};++/** Header addon next to the agent's name: it is running, and for how long. */+export const DirectMentionStatus = memo<{ startedAt: number }>(({ startedAt }) => {+ const { t } = useTranslation('chat');+ const elapsed = useElapsed(startedAt);++ return (+ <Flexbox horizontal align={'center'} gap={6} style={{ whiteSpace: 'nowrap' }}>+ <Text type={'secondary'}>· {t('directMention.progress.running')}</Text>+ <Tag size={'small'}>+ {t('directMention.progress.elapsed', {+ time: formatDuration(Math.floor(elapsed / 1000) * 1000),+ })}+ </Tag>+ </Flexbox>+ );+});++DirectMentionStatus.displayName = 'DirectMentionStatus';++interface DirectMentionProgressProps {+ /** The mentioned agent, which runs the thread. */+ agentId: string;+ messageId: string;+ threadId: string;+}++/**+ * Live body for a direct @Agent reply still being written in its thread: what+ * the agent is doing and the newest line of its answer, with the way into the+ * full record.+ */+const DirectMentionProgress = memo<DirectMentionProgressProps>(+ ({ agentId, messageId, threadId }) => {+ const { t } = useTranslation('chat');+ const topicId = useConversationStore(contextSelectors.topicId);+ const openThreadInPortal = useChatStore((s) => s.openThreadInPortal);++ const messages = useChatStore(selectThreadTranscript({ agentId, threadId, topicId }));+ const { activity, text } = useMemo(+ () => summarizeThreadProgress(messages ?? [], threadId),+ [messages, threadId],+ );++ const activityLine =+ activity?.type === 'tool'+ ? t('directMention.progress.usingTool', { name: activity.name })+ : (activity?.text ?? t('directMention.progress.thinking'));++ return (+ <Flexbox gap={8}>+ <Block gap={8} paddingBlock={12} paddingInline={16} variant={'filled'}>+ <Text ellipsis {...stylex.props(styles.activity)}>+ {activityLine}+ </Text>+ {text && (+ <Text ellipsis {...stylex.props(styles.text)}>+ {text}+ </Text>+ )}+ </Block>+ <Flexbox horizontal>+ <Button+ icon={SquareArrowOutUpRightIcon}+ outdent={'start'}+ size={'small'}+ type={'text'}+ onClick={() => openThreadInPortal(threadId, messageId)}+ >+ {t('directMention.progress.viewFullRecord')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+ },+);++DirectMentionProgress.displayName = 'DirectMentionProgress';++export default DirectMentionProgress;diff --git a/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/summarize.test.ts b/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/summarize.test.tsnew file mode 100644index 00000000000..e9dba5c3bfe--- /dev/null+++ b/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/summarize.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it } from 'vitest';++import { summarizeThreadProgress } from './summarize';++const summarize = (messages: any[]) =>+ summarizeThreadProgress(+ messages.map((message) => ({ threadId: 't1', ...message })),+ 't1',+ );++describe('summarizeThreadProgress', () => {+ it('is empty before the child has replied', () => {+ expect(summarize([{ content: 'question', id: 'u1', role: 'user' }])).toEqual({});+ });++ it('shows the latest thinking while the child reasons', () => {+ expect(+ summarize([+ {+ content: '',+ id: 'a1',+ reasoning: { content: '先看需求\n正在读鉴权相关文件' },+ role: 'assistant',+ },+ ]),+ ).toEqual({ activity: { text: '正在读鉴权相关文件', type: 'thinking' } });+ });++ it('shows the tool the child is waiting on', () => {+ expect(+ summarize([+ {+ content: '',+ id: 'a1',+ role: 'assistant',+ tools: [{ apiName: 'readFile', id: 'call_1', identifier: 'local-files' }],+ },+ ]),+ ).toEqual({ activity: { name: 'readFile', type: 'tool' } });+ });++ it('pairs the thinking with the newest line of the answer being written', () => {+ expect(+ summarize([+ {+ content: '第一段\n\n准备把密码登录收成 oauth 入口',+ id: 'a1',+ reasoning: { content: '核对 session 写入点' },+ role: 'assistant',+ },+ ]),+ ).toEqual({+ activity: { text: '核对 session 写入点', type: 'thinking' },+ text: '准备把密码登录收成 oauth 入口',+ });+ });++ it('keeps the earlier answer while a finished tool step hands over to a new one', () => {+ expect(+ summarize([+ {+ content: '我先看下代码',+ id: 'a1',+ role: 'assistant',+ tools: [{ apiName: 'readFile', id: 'call_1', identifier: 'local-files' }],+ },+ { content: 'file body', id: 't1', role: 'tool', tool_call_id: 'call_1' },+ { content: '', id: 'a2', role: 'assistant' },+ ]),+ ).toEqual({ text: '我先看下代码' });+ });++ it('shows the end of a long line, where the new words are', () => {+ const line = `${'旧'.repeat(100)}最新的字`;++ const { text } = summarize([{ content: line, id: 'a1', role: 'assistant' }]);++ expect(text?.startsWith('…')).toBe(true);+ expect(text?.endsWith('最新的字')).toBe(true);+ expect(text!.length).toBeLessThanOrEqual(81);+ });++ it('ignores the conversation the thread inherits', () => {+ expect(+ summarizeThreadProgress(+ [+ { content: '之前 Lobe AI 的回答', id: 'm1', role: 'assistant' },+ {+ content: '',+ id: 'a1',+ reasoning: { content: '回看前文' },+ role: 'assistant',+ threadId: 't1',+ },+ ] as any,+ 't1',+ ),+ ).toEqual({ activity: { text: '回看前文', type: 'thinking' } });+ });+});diff --git a/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/summarize.ts b/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/summarize.tsnew file mode 100644index 00000000000..6fb2c6b5032--- /dev/null+++ b/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/summarize.ts@@ -0,0 +1,51 @@+import { LOADING_FLAT } from '@lobechat/const';+import type { UIChatMessage } from '@lobechat/types';++const MAX_LINE = 80;++export interface ThreadProgress {+ /** What the child is doing right now. */+ activity?: { text: string; type: 'thinking' } | { name: string; type: 'tool' };+ /** The newest line of the answer it is writing. */+ text?: string;+}++/** Last non-empty line, cut from the front so the newest words stay visible. */+const tailLine = (value?: string | null): string | undefined => {+ if (!value || value === LOADING_FLAT) return;+ const line = value+ .split('\n')+ .map((part) => part.trim())+ .findLast(Boolean);+ if (!line) return;++ return line.length > MAX_LINE ? `…${line.slice(-MAX_LINE)}` : line;+};++/** One-glance progress of a direct @Agent child, read from its thread transcript. */+export const summarizeThreadProgress = (+ transcript: UIChatMessage[],+ threadId: string,+): ThreadProgress => {+ // The transcript also carries the conversation the thread reads; progress is+ // the thread's own.+ const messages = transcript.filter((message) => message.threadId === threadId);+ const replies = messages.filter((message) => message.role === 'assistant');+ const current = replies.at(-1);+ if (!current) return {};++ const answeredCalls = new Set(+ messages.filter((message) => message.role === 'tool').map((message) => message.tool_call_id),+ );+ const pendingTool = current.tools?.find((tool) => !answeredCalls.has(tool.id));+ const thinking = tailLine(current.reasoning?.content);+ const text = replies.map((reply) => tailLine(reply.content)).findLast(Boolean);++ const activity: ThreadProgress['activity'] = pendingTool+ ? { name: pendingTool.apiName || pendingTool.identifier, type: 'tool' }+ : thinking+ ? { text: thinking, type: 'thinking' }+ : undefined;++ return { ...(activity && { activity }), ...(text && { text }) };+};diff --git a/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/threadTranscript.test.ts b/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/threadTranscript.test.tsnew file mode 100644index 00000000000..d55577ef22e--- /dev/null+++ b/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/threadTranscript.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';++import { messageMapKey } from '@/store/chat/utils/messageMapKey';++import { selectThreadTranscript } from './threadTranscript';++const target = { agentId: 'agt_xw', threadId: 'thd_1', topicId: 'tpc_1' };+const reply = [{ content: 'hi', id: 'm1', role: 'assistant', threadId: 'thd_1' }] as any[];++describe('selectThreadTranscript', () => {+ it('reads a thread the tab runs itself from the sub-agent scope', () => {+ const key = messageMapKey({ ...target, scope: 'sub_agent', subAgentId: target.agentId });++ expect(selectThreadTranscript(target)({ dbMessagesMap: { [key]: reply } })).toBe(reply);+ });++ it('reads a Gateway-streamed thread from the thread scope', () => {+ const key = messageMapKey({ ...target, scope: 'thread' });++ expect(selectThreadTranscript(target)({ dbMessagesMap: { [key]: reply } })).toBe(reply);+ });+});diff --git a/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/threadTranscript.ts b/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/threadTranscript.tsnew file mode 100644index 00000000000..fdf8cc49188--- /dev/null+++ b/src/features/Conversation/Messages/Assistant/components/DirectMentionProgress/threadTranscript.ts@@ -0,0 +1,21 @@+import type { UIChatMessage } from '@lobechat/types';++import { messageMapKey } from '@/store/chat/utils/messageMapKey';++interface ThreadTranscriptTarget {+ agentId: string;+ threadId: string;+ topicId?: string | null;+}++/**+ * The live transcript of a direct @Agent thread. A run this tab drives itself+ * (no Gateway) writes it under the sub-agent scope; a Gateway run streams into+ * the thread scope.+ */+export const selectThreadTranscript =+ ({ agentId, threadId, topicId }: ThreadTranscriptTarget) =>+ (state: { dbMessagesMap: Record<string, UIChatMessage[] | undefined> }) =>+ state.dbMessagesMap[+ messageMapKey({ agentId, scope: 'sub_agent', subAgentId: agentId, threadId, topicId })+ ] ?? state.dbMessagesMap[messageMapKey({ agentId, scope: 'thread', threadId, topicId })];diff --git a/src/features/Conversation/Messages/Assistant/index.tsx b/src/features/Conversation/Messages/Assistant/index.tsxindex 5a0bb4eed71..80c2fa11d30 100644--- a/src/features/Conversation/Messages/Assistant/index.tsx+++ b/src/features/Conversation/Messages/Assistant/index.tsx@@ -26,6 +26,7 @@ import {useSetMessageItemActionTypeContext,} from '../Contexts/message-action-context';import MessageWorks from '../MessageWorks';+import DirectMentionProgress, { DirectMentionStatus } from './components/DirectMentionProgress';import InterruptedHint from './components/InterruptedHint';import MessageContent from './components/MessageContent';import ThreadExecutionSummary from './components/ThreadExecutionSummary';@@ -62,6 +63,7 @@ const AssistantMessage = memo<AssistantMessageProps>(performance,usage,metadata,+ taskDetail,} = item;const avatar = useAgentMeta(agentId);@@ -120,6 +122,14 @@ const AssistantMessage = memo<AssistantMessageProps>([id, index, setMessageItemActionElementPortialContext, setMessageItemActionTypeContext],);+ // A direct @Agent reply still being written in its thread: show its live+ // progress instead of an empty bubble until the answer lands here.+ const processing = useConversationStore(messageStateSelectors.isMessageProcessing(id));+ const runningThreadId =+ processing && agentId && taskDetail?.threadId && (!content || content === LOADING_FLAT)+ ? taskDetail.threadId+ : undefined;+const hasEmptyErrorMessage = Boolean(errorContent &&error &&@@ -129,7 +139,7 @@ const AssistantMessage = memo<AssistantMessageProps>(return (<ChatItemshowTitle- aboveMessage={<ThreadExecutionSummary messageId={id} />}+ aboveMessage={runningThreadId ? undefined : <ThreadExecutionSummary messageId={id} />}// ChatItem renders this as the primary block when the message is empty,// or inside messageExtra (below the content) when the turn streamed// content before erroring — so don't gate it on empty content.@@ -140,11 +150,10 @@ const AssistantMessage = memo<AssistantMessageProps>(editing={editing}error={errorContent && error ? errorContent : undefined}id={id}- loading={generating || isCreating}+ loading={generating || isCreating || !!runningThreadId}message={message}placement={'left'}- time={createdAt}- titleAddon={<RefreshingIndicator messageId={id} />}+ time={runningThreadId ? undefined : createdAt}actionAddon={reactions.length > 0 || (commentCount > 0 && commentTopicId) ? (<>@@ -195,10 +204,25 @@ const AssistantMessage = memo<AssistantMessageProps>({footerRender}</>}+ titleAddon={+ runningThreadId ? (+ <DirectMentionStatus+ startedAt={+ taskDetail?.startedAt ? Date.parse(taskDetail.startedAt) : Number(createdAt)+ }+ />+ ) : (+ <RefreshingIndicator messageId={id} />+ )+ }onDoubleClick={onDoubleClick}onMouseEnter={onMouseEnter}>- <MessageContent {...item} />+ {runningThreadId ? (+ <DirectMentionProgress agentId={agentId!} messageId={id} threadId={runningThreadId} />+ ) : (+ <MessageContent {...item} />+ )}</ChatItem>);},diff --git a/src/services/agent.ts b/src/services/agent.tsindex 88e7dcf92b7..d8a97aa2688 100644--- a/src/services/agent.ts+++ b/src/services/agent.ts@@ -131,8 +131,14 @@ class AgentService {* Get an agent by forkedFromIdentifier stored in params* @returns agent id if exists, null otherwise*/- getAgentByForkedFromIdentifier = async (forkedFromIdentifier: string): Promise<string | null> => {- return lambdaClient.agent.getAgentByForkedFromIdentifier.query({ forkedFromIdentifier });+ getAgentByForkedFromIdentifier = async (+ forkedFromIdentifier: string,+ options?: { virtual?: boolean },+ ): Promise<string | null> => {+ return lambdaClient.agent.getAgentByForkedFromIdentifier.query({+ forkedFromIdentifier,+ ...options,+ });};/**diff --git a/src/services/installMarketplaceAgents.ts b/src/services/installMarketplaceAgents.tsindex 8f2feb096df..cee30b0a856 100644--- a/src/services/installMarketplaceAgents.ts+++ b/src/services/installMarketplaceAgents.ts@@ -1,4 +1,5 @@import type { InstallMarketplaceAgentSummary } from '@lobechat/builtin-tool-web-onboarding/agentMarketplace';+import type { DiscoverAssistantDetail } from '@lobechat/types';import { customAlphabet } from 'nanoid/non-secure';import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';@@ -12,12 +13,38 @@ import { useHomeStore } from '@/store/home';export type { InstallMarketplaceAgentSummary };-const generateMarketIdentifier = () => {+export const generateMarketIdentifier = () => {const alphabet = '0123456789abcdefghijklmnopqrstuvwxyz';const generate = customAlphabet(alphabet, 8);return generate();};+/** Local agent config for the Market agent `sourceId`. */+export const buildMarketAgentConfig = (detail: DiscoverAssistantDetail, sourceId: string) => ({+ ...detail.config,+ avatar: detail.avatar,+ backgroundColor: detail.backgroundColor,+ description: detail.description,+ editorData: detail.editorData,+ params: {+ ...detail.config.params,+ forkedFromIdentifier: sourceId,+ },+ tags: detail.tags,+ title: detail.title,+});++/** Local agent config for a Market fork of `sourceId`, as every install entry builds it. */+export const buildForkedAgentConfig = (+ detail: DiscoverAssistantDetail,+ fork: { identifier: string; name: string },+ sourceId: string,+) => ({+ ...buildMarketAgentConfig(detail, sourceId),+ marketIdentifier: fork.identifier,+ title: fork.name,+});+const getSourcePath = () => {if (typeof location === 'undefined') return 'onboarding/agent-marketplace';@@ -103,7 +130,7 @@ export const installMarketplaceAgents = async (// 3. Build batch fork input only for items with valid detailtype Prepared = {- detail: NonNullable<Awaited<ReturnType<typeof discoverService.getAssistantDetail>>>;+ detail: DiscoverAssistantDetail;newIdentifier: string;sourceId: string;};@@ -150,20 +177,7 @@ export const installMarketplaceAgents = async (}const fork = outcome.data;const result = await createAgent({- config: {- ...detail.config,- avatar: detail.avatar,- backgroundColor: detail.backgroundColor,- description: detail.description,- editorData: detail.editorData,- marketIdentifier: fork.agent.identifier,- params: {- ...detail.config.params,- forkedFromIdentifier: sourceId,- },- tags: detail.tags,- title: fork.agent.name,- },+ config: buildForkedAgentConfig(detail, fork.agent, sourceId),visibility,});diff --git a/src/services/mentionMarketInstall.test.ts b/src/services/mentionMarketInstall.test.tsnew file mode 100644index 00000000000..c3c24351547--- /dev/null+++ b/src/services/mentionMarketInstall.test.ts@@ -0,0 +1,186 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ createAgent: vi.fn(),+ ensureAgentMarketSkills: vi.fn(),+ ensureAgentMarketSkillsAndWarn: vi.fn(),+ getAgentByForkedFromIdentifier: vi.fn(),+ getAgentConfigById: vi.fn(),+ getAssistantDetail: vi.fn(),+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => 'ws_1',+}));+vi.mock('@/services/agent', () => ({+ agentService: {+ getAgentByForkedFromIdentifier: mocks.getAgentByForkedFromIdentifier,+ getAgentConfigById: mocks.getAgentConfigById,+ },+}));+vi.mock('@/services/discover', () => ({+ discoverService: { getAssistantDetail: mocks.getAssistantDetail },+}));+vi.mock('@/services/ensureAgentMarketSkills', () => ({+ ensureAgentMarketSkills: mocks.ensureAgentMarketSkills,+ ensureAgentMarketSkillsAndWarn: mocks.ensureAgentMarketSkillsAndWarn,+}));+vi.mock('@/store/agent', () => ({+ useAgentStore: { getState: () => ({ createAgent: mocks.createAgent }) },+}));++const {+ MarketMentionInstallError,+ installMarketMentions,+ prepareMentionedMarketAgent,+ prepareMentionedMarketSkill,+} = await import('./mentionMarketInstall');++const detail = {+ avatar: '🎯',+ config: { plugins: ['okr-skill'], systemRole: 'You are an OKR coach' },+ description: 'Writes OKRs',+ title: 'OKR 教练',+};++describe('installMarketMentions', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getAssistantDetail.mockResolvedValue(detail);+ mocks.createAgent.mockResolvedValue({ agentId: 'agt_hidden' });+ });++ it('readies a Market agent when its chip is picked, so the send reuses that work', async () => {+ mocks.getAgentByForkedFromIdentifier.mockResolvedValue(null);+ let finishSkills!: () => void;+ mocks.ensureAgentMarketSkillsAndWarn.mockReturnValue(+ new Promise<void>((resolve) => {+ finishSkills = resolve;+ }),+ );++ prepareMentionedMarketAgent('picked-early', 'public');+ await vi.waitFor(() => expect(mocks.createAgent).toHaveBeenCalledTimes(1));+ expect(mocks.ensureAgentMarketSkillsAndWarn).toHaveBeenCalledWith(['okr-skill']);++ const sending = installMarketMentions({+ agents: [{ identifier: 'picked-early', label: 'OKR 教练', visibility: 'public' }],+ skills: [],+ });+ finishSkills();++ expect((await sending).get('picked-early')).toBe('agt_hidden');+ expect(mocks.createAgent).toHaveBeenCalledTimes(1);+ expect(mocks.ensureAgentMarketSkillsAndWarn).toHaveBeenCalledTimes(1);+ });++ it('runs a mentioned Market agent from a hidden copy instead of installing it', async () => {+ mocks.getAgentByForkedFromIdentifier.mockResolvedValue(null);++ const installed = await installMarketMentions({+ agents: [{ identifier: 'okr-coach', label: 'OKR 教练', visibility: 'public' }],+ skills: [],+ });++ expect(installed.get('okr-coach')).toBe('agt_hidden');+ expect(mocks.getAgentByForkedFromIdentifier).toHaveBeenCalledWith('okr-coach', {+ virtual: true,+ });+ const { config, visibility } = mocks.createAgent.mock.calls[0][0];+ expect(config).toMatchObject({+ // Labelled as the Market expert, never with a drawn personal name.+ name: 'OKR 教练',+ params: { forkedFromIdentifier: 'okr-coach' },+ systemRole: 'You are an OKR coach',+ title: 'OKR 教练',+ virtual: true,+ });+ expect(config.marketIdentifier).toBeUndefined();+ expect(visibility).toBe('public');+ expect(mocks.ensureAgentMarketSkillsAndWarn).toHaveBeenCalledWith(['okr-skill']);+ });++ it('installs a picked Market skill right away, so the send reuses that install', async () => {+ let finish!: () => void;+ mocks.ensureAgentMarketSkills.mockReturnValue(+ new Promise((resolve) => {+ finish = () => resolve([{ identifier: 'big-skill', status: 'installed' }]);+ }),+ );++ prepareMentionedMarketSkill('big-skill');+ expect(mocks.ensureAgentMarketSkills).toHaveBeenCalledWith(['big-skill']);++ const sending = installMarketMentions({+ agents: [],+ skills: [{ identifier: 'big-skill', label: '大技能' }],+ });+ finish();++ await expect(sending).resolves.toEqual(new Map());+ expect(mocks.ensureAgentMarketSkills).toHaveBeenCalledTimes(1);+ });++ it('retries a skill whose early install failed and names it if it fails again', async () => {+ mocks.ensureAgentMarketSkills.mockResolvedValue([+ { identifier: 'flaky-skill', reason: 'download', status: 'failed' },+ ]);++ prepareMentionedMarketSkill('flaky-skill');+ await vi.waitFor(() => expect(mocks.ensureAgentMarketSkills).toHaveBeenCalledTimes(1));+ await Promise.resolve();++ const sending = installMarketMentions({+ agents: [],+ skills: [{ identifier: 'flaky-skill', label: '不稳定技能' }],+ });++ await expect(sending).rejects.toEqual(new MarketMentionInstallError(['不稳定技能']));+ expect(mocks.ensureAgentMarketSkills).toHaveBeenCalledTimes(2);+ });++ it('installs a skill again when it was removed after an earlier mention installed it', async () => {+ mocks.ensureAgentMarketSkills.mockResolvedValue([+ { identifier: 'removed-skill', status: 'installed' },+ ]);+ const request = { agents: [], skills: [{ identifier: 'removed-skill', label: '被删技能' }] };++ await installMarketMentions(request);+ // The user deleted it from the agent's tools; mentioning it again must+ // reinstall it rather than trust the earlier install.+ await installMarketMentions(request);++ expect(mocks.ensureAgentMarketSkills).toHaveBeenCalledTimes(2);+ });++ it('reuses the hidden copy an earlier mention created', async () => {+ mocks.getAgentByForkedFromIdentifier.mockResolvedValue('agt_earlier');++ const installed = await installMarketMentions({+ agents: [{ identifier: 'reused-coach', label: 'OKR 教练', visibility: 'private' }],+ skills: [],+ });++ expect(installed.get('reused-coach')).toBe('agt_earlier');+ expect(mocks.createAgent).not.toHaveBeenCalled();+ });++ it('makes sure a reused hidden copy still has the Market skills it depends on', async () => {+ // A dependency that failed to install when the copy was created must be+ // retried, or the agent keeps running without it.+ mocks.getAgentByForkedFromIdentifier.mockResolvedValue('agt_earlier');+ mocks.getAgentConfigById.mockResolvedValue({ plugins: ['okr-skill', 'lobe-web-browsing'] });++ await installMarketMentions({+ agents: [{ identifier: 'coach-with-skills', label: 'OKR 教练', visibility: 'private' }],+ skills: [],+ });++ expect(mocks.getAgentConfigById).toHaveBeenCalledWith('agt_earlier');+ expect(mocks.ensureAgentMarketSkillsAndWarn).toHaveBeenCalledWith([+ 'okr-skill',+ 'lobe-web-browsing',+ ]);+ expect(mocks.getAssistantDetail).not.toHaveBeenCalled();+ });+});diff --git a/src/services/mentionMarketInstall.ts b/src/services/mentionMarketInstall.tsnew file mode 100644index 00000000000..9f7421d9ef4--- /dev/null+++ b/src/services/mentionMarketInstall.ts@@ -0,0 +1,184 @@+import type { DiscoverAssistantDetail } from '@lobechat/types';++import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import type {+ MarketInstallVisibility,+ PendingMarketAgent,+ PendingMarketSkill,+} from '@/features/ChatInput/InputEditor/marketMention';+import { agentService } from '@/services/agent';+import { discoverService } from '@/services/discover';+import {+ ensureAgentMarketSkills,+ ensureAgentMarketSkillsAndWarn,+} from '@/services/ensureAgentMarketSkills';+import { buildMarketAgentConfig } from '@/services/installMarketplaceAgents';+import type { EnsureMarketSkillResult } from '@/services/skill';+import { useAgentStore } from '@/store/agent';++/**+ * Readies the Market agents and skills picked from the composer's @ menu.+ *+ * Speed matters here because the send waits for it: an agent is readied the+ * moment its chip is picked, and the agent's own Market skills are installed+ * alongside its local row instead of after it.+ */++/**+ * Share work that is still in flight, so the send reuses what picking the chip+ * started. Settled work is not kept: each later attempt checks again (cheaply —+ * an installed skill or an existing hidden copy is found without reinstalling),+ * so a failure is retried and a skill removed since is installed again.+ */+const shareInFlight = <T>(cache: Map<string, Promise<T>>, key: string, load: () => Promise<T>) => {+ const pending = cache.get(key);+ if (pending) return pending;++ const promise = load().finally(() => cache.delete(key));+ cache.set(key, promise);+ return promise;+};++const detailCache = new Map<string, Promise<DiscoverAssistantDetail>>();+const installCache = new Map<string, Promise<string>>();+const skillCache = new Map<string, Promise<void>>();++const loadAgentDetail = (identifier: string) =>+ shareInFlight(detailCache, identifier, async () => {+ const detail = await discoverService.getAssistantDetail({ identifier });+ if (!detail?.config) throw new Error(`Market agent ${identifier} is unavailable`);+ return detail as DiscoverAssistantDetail;+ });++/**+ * Mentioning a Market agent runs it without installing it: the run needs a+ * local agent row (its prompt, model and tools), so the agent gets a hidden+ * (`virtual`) copy — kept out of the agent list and not forked to the Market —+ * that later mentions reuse. Installing it stays an explicit Market action.+ */+const prepareMarketAgent = (identifier: string, visibility: MarketInstallVisibility) => {+ const workspaceId = getActiveWorkspaceId();+ const key = `${workspaceId ?? ''}:${visibility}:${identifier}`;++ return shareInFlight(installCache, key, async () => {+ const existing = await agentService.getAgentByForkedFromIdentifier(identifier, {+ virtual: true,+ });+ if (existing) {+ // A Market skill it depends on may have failed to install when the copy was+ // made; installed ones are skipped locally, so this only retries what's missing.+ const config = await agentService.getAgentConfigById(existing);+ await ensureAgentMarketSkillsAndWarn(config?.plugins);+ return existing;+ }++ const detail = await loadAgentDetail(identifier);+ const [result] = await Promise.all([+ useAgentStore.getState().createAgent({+ // Nobody adopts a hidden copy, so it keeps the Market name instead of+ // drawing a personal one: the reply is labelled — and the agent+ // introduces itself — as the expert the user picked.+ config: {+ ...buildMarketAgentConfig(detail, identifier),+ name: detail.title,+ virtual: true,+ },+ ...(workspaceId ? { visibility } : {}),+ }),+ ensureAgentMarketSkillsAndWarn(detail.config.plugins),+ ]);++ return result.agentId;+ });+};++/**+ * Start readying a Market agent the moment its chip is picked, while the user is+ * still typing: an agent with large Market skills can take many seconds to set up,+ * and the send then only awaits whatever is left. A failure is not shared, so the+ * send retries it and reports it.+ */+export const prepareMentionedMarketAgent = (+ identifier: string,+ visibility: MarketInstallVisibility,+) => {+ prepareMarketAgent(identifier, visibility).catch((error) => {+ console.error('[mention] failed to prepare market agent early', identifier, error);+ });+};++class MarketSkillPrepareError extends Error {+ constructor(readonly result: EnsureMarketSkillResult) {+ super(`Failed to install skill: ${result.identifier}`);+ this.name = 'MarketSkillPrepareError';+ }+}++/** Install a Market skill picked from the @ menu unless it is already installed. */+const prepareMarketSkill = (identifier: string) =>+ shareInFlight(skillCache, `${getActiveWorkspaceId() ?? ''}:${identifier}`, async () => {+ const [result] = await ensureAgentMarketSkills([identifier]);+ if (result?.status === 'failed' || result?.status === 'notSkill') {+ throw new MarketSkillPrepareError(result);+ }+ });++/** Start installing a Market skill the moment its chip is picked, like Market agents. */+export const prepareMentionedMarketSkill = (identifier: string) => {+ prepareMarketSkill(identifier).catch((error) => {+ console.error('[mention] failed to prepare market skill early', identifier, error);+ });+};++export class MarketMentionInstallError extends Error {+ constructor(readonly failedNames: string[]) {+ super(`Failed to install: ${failedNames.join(', ')}`);+ this.name = 'MarketMentionInstallError';+ }+}++export interface MarketMentionInstallRequest {+ agents: PendingMarketAgent[];+ skills: PendingMarketSkill[];+}++/**+ * Install everything the message references from the Market, in parallel.+ * Resolves the installed agent id of each Market agent identifier; throws+ * `MarketMentionInstallError` naming whatever could not be installed.+ */+export const installMarketMentions = async ({+ agents,+ skills,+}: MarketMentionInstallRequest): Promise<Map<string, string>> => {+ const [agentResults, skillResults] = await Promise.all([+ Promise.allSettled(+ agents.map((agent) => prepareMarketAgent(agent.identifier, agent.visibility)),+ ),+ Promise.allSettled(skills.map((skill) => prepareMarketSkill(skill.identifier))),+ ]);++ const installed = new Map<string, string>();+ const failedNames: string[] = [];++ agentResults.forEach((result, index) => {+ const agent = agents[index];+ if (result.status === 'fulfilled') installed.set(agent.identifier, result.value);+ else {+ console.error('[mention] failed to install market agent', agent.identifier, result.reason);+ failedNames.push(agent.label);+ }+ });+ skillResults.forEach((result, index) => {+ if (result.status === 'fulfilled') return;+ console.error(+ '[mention] failed to install market skill',+ skills[index].identifier,+ result.reason,+ );+ failedNames.push(skills[index].label);+ });++ if (failedNames.length > 0) throw new MarketMentionInstallError(failedNames);+ return installed;+};diff --git a/src/store/chat/agents/transports/ClientSubAgentTransport.test.ts b/src/store/chat/agents/transports/ClientSubAgentTransport.test.tsindex 2e6f455b1c4..5ba34ab6fea 100644--- a/src/store/chat/agents/transports/ClientSubAgentTransport.test.ts+++ b/src/store/chat/agents/transports/ClientSubAgentTransport.test.ts@@ -104,6 +104,27 @@ describe('ClientSubAgentTransport', () => {});});+ it('hands the accepted dispatch to the caller before waiting on the child', async () => {+ const { store } = createStore();+ vi.mocked(aiAgentService.execSubAgentTask).mockResolvedValueOnce({+ ...dispatchResult,+ token: 'child-ticket',+ });+ const onDispatched = vi.fn(() => {+ expect(aiAgentService.getSubAgentTaskStatus).not.toHaveBeenCalled();+ });+ vi.mocked(aiAgentService.getSubAgentTaskStatus).mockResolvedValueOnce({+ result: 'done',+ status: 'completed',+ });++ await new ClientSubAgentTransport(() => store, 'root-operation', {+ onDispatched,+ }).execSubAgent(params);++ expect(onDispatched).toHaveBeenCalledWith({ ...dispatchResult, token: 'child-ticket' });+ });+it('returns a terminal failure when dispatch is rejected', async () => {const { store } = createStore();vi.mocked(aiAgentService.execSubAgentTask).mockResolvedValueOnce({diff --git a/src/store/chat/agents/transports/ClientSubAgentTransport.ts b/src/store/chat/agents/transports/ClientSubAgentTransport.tsindex be75d6092e4..f65f5957d1c 100644--- a/src/store/chat/agents/transports/ClientSubAgentTransport.ts+++ b/src/store/chat/agents/transports/ClientSubAgentTransport.ts@@ -1,6 +1,10 @@import { llmRelayChannelScope } from '@lobechat/agent-gateway-client';import type { SubAgentExecutionResult, SubAgentTransport } from '@lobechat/agent-runtime';-import type { ExecSubAgentParams, ExecVirtualSubAgentParams } from '@lobechat/types';+import type {+ ExecSubAgentParams,+ ExecSubAgentResult,+ ExecVirtualSubAgentParams,+} from '@lobechat/types';import { getBusinessTrpcHeaders } from '@/business/client/trpc-headers';import type { ExecSubAgentTaskParams } from '@/services/aiAgent';@@ -39,6 +43,10 @@ export class ClientSubAgentTransport implements SubAgentTransport {constructor(private readonly get: () => ChatStore,private readonly operationId: string,+ private readonly options: {+ /** The server accepted the child; called before waiting on it. */+ onDispatched?: (dispatch: ExecSubAgentResult) => void;+ } = {},) {}execSubAgent(params: ExecSubAgentParams): Promise<SubAgentExecutionResult> {@@ -118,6 +126,8 @@ export class ClientSubAgentTransport implements SubAgentTransport {const operation = this.get().operations[this.operationId];if (!operation) throw new Error(`Operation not found: ${this.operationId}`);+ this.options.onDispatched?.(dispatchResult);+const signal = operation.abortController.signal;const timeoutMs = params.timeout ?? DEFAULT_TIMEOUT_MS;const startedAt = Date.now();diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.isolatedBlankBucket.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.isolatedBlankBucket.test.tsnew file mode 100644index 00000000000..93b4535e349--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.isolatedBlankBucket.test.ts@@ -0,0 +1,106 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { agentService } from '@/services/agent';+import { aiChatService } from '@/services/aiChat';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { getSessionStoreState } from '@/store/session';+import { useUserStore } from '@/store/user';++import { useChatStore } from '../../../../store';+import { clearBlankConversationBucket } from '../clearBlankBucket';+import { createMockAgentConfig, createMockMessage, TEST_CONTENT, TEST_IDS } from './fixtures';+import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';++vi.mock('@/services/resourcePermission', () => ({+ resourcePermissionService: { getGeneralAccess: vi.fn() },+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ session: { updateSession: { mutate: vi.fn().mockResolvedValue(undefined) } },+ },+}));++beforeEach(() => {+ resetTestEnvironment();+ setupMockSelectors();+ spyOnMessageService();+ vi.spyOn(getSessionStoreState(), 'triggerSessionUpdate').mockResolvedValue(undefined);+ vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);+ useUserStore.setState({ workspaceUserPreference: {} });++ act(() => {+ useChatStore.setState({+ executeClientAgent: vi.fn(),+ mainInputEditor: null,+ refreshMessages: vi.fn(),+ refreshTopic: vi.fn(),+ });+ });+});++afterEach(() => {+ vi.restoreAllMocks();+});++const agentId = TEST_IDS.SESSION_ID;+const blankKey = messageMapKey({ agentId, scope: 'main', topicId: null });++describe('isolated sends and the blank conversation bucket', () => {+ it('empties the blank bucket once an isolated send has created its topic', async () => {+ // The Home composer sends with `isolatedTopic` and shows the optimistic pair in+ // the agent's blank bucket. Left there, the next blank send (e.g. a direct+ // @Agent) adopted those rows as its new topic's messages, moving them out of+ // the topic they had just been created in.+ const newTopicId = TEST_IDS.NEW_TOPIC_ID;+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: true,+ messages: [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user', topicId: newTopicId }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant',+ topicId: newTopicId,+ }),+ ],+ topicId: newTopicId,+ topics: { items: [{ id: newTopicId, title: 'Server Topic' }], total: 1 },+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);+ const onTopicCreated = vi.fn();+ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ await result.current.sendMessage({+ context: { agentId, isNew: true, isolatedTopic: true, scope: 'main' },+ message: TEST_CONTENT.USER_MESSAGE,+ onTopicCreated,+ });+ });++ expect(onTopicCreated).toHaveBeenCalledWith(newTopicId);+ expect(useChatStore.getState().dbMessagesMap[blankKey] ?? []).toEqual([]);+ expect(+ useChatStore.getState().dbMessagesMap[messageMapKey({ agentId, topicId: newTopicId })],+ ).toHaveLength(2);+ });++ it('clears only the blank bucket of the conversation the send came from', () => {+ const topicKey = messageMapKey({ agentId, topicId: TEST_IDS.TOPIC_ID });+ const leftover = createMockMessage({ id: 'leftover', role: 'user' });+ const kept = createMockMessage({ id: 'kept', role: 'user', topicId: TEST_IDS.TOPIC_ID });+ act(() => {+ useChatStore.setState({+ dbMessagesMap: { [blankKey]: [leftover], [topicKey]: [kept] },+ messagesMap: { [blankKey]: [leftover], [topicKey]: [kept] },+ });+ });++ act(() => clearBlankConversationBucket(useChatStore.getState, { agentId, scope: 'main' }));++ expect(useChatStore.getState().dbMessagesMap[blankKey]).toEqual([]);+ expect(useChatStore.getState().dbMessagesMap[topicKey]).toHaveLength(1);+ });+});diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.watchSubAgentRun.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.watchSubAgentRun.test.tsnew file mode 100644index 00000000000..396a8abf5cb--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.watchSubAgentRun.test.ts@@ -0,0 +1,185 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import type * as ConstVersion from '@/const/version';+import { topicService } from '@/services/topic';++import { GatewayActionImpl } from '../transports/gateway/gateway';++vi.mock('../transports/gateway/serverSteerQueue', () => ({+ reclaimServerQueuedMessages: vi.fn().mockResolvedValue(undefined),+ restoreServerQueuedMessages: vi.fn(),+ withdrawQueuedMessage: vi.fn(),+}));++vi.mock('@/services/aiAgent', () => ({+ aiAgentService: { execAgentTask: vi.fn(), interruptTask: vi.fn(), refreshGatewayToken: vi.fn() },+}));++vi.mock('@/services/shareChat', () => ({+ shareChatService: { interruptTask: vi.fn(), refreshGatewayToken: vi.fn() },+}));++vi.mock('@/services/message', () => ({+ messageService: { getMessages: vi.fn().mockResolvedValue([]) },+}));++vi.mock('@/services/topic', () => ({+ topicService: {+ getTopicDetail: vi.fn().mockResolvedValue(null),+ settleRunningOperation: vi.fn().mockResolvedValue(undefined),+ updateTopicMetadata: vi.fn().mockResolvedValue(undefined),+ },+}));++vi.mock('@/store/file/store', () => ({+ getFileStoreState: () => ({ moveChatContextSelections: vi.fn() }),+}));++const mockUserState = vi.hoisted(() => ({+ profile: { id: 'user-viewer' },+ workspaceUserPreference: { agentDeviceOverrides: {} as Record<string, any> },+}));++vi.mock('@/store/user', () => ({ useUserStore: { getState: vi.fn(() => mockUserState) } }));++vi.mock('@/store/user/selectors', () => ({+ settingsSelectors: { defaultAgentConfig: () => ({ chatConfig: {} }) },+ toolInterventionSelectors: { allowList: () => [], approvalMode: () => 'manual' },+ userProfileSelectors: { userId: (state: typeof mockUserState) => state.profile.id },+}));++vi.mock('@/const/version', async (importOriginal) => ({+ ...(await importOriginal<typeof ConstVersion>()),+ isDesktop: false,+}));++vi.mock('@/services/electron/gatewayConnection', () => ({+ gatewayConnectionService: { getDeviceInfo: vi.fn() },+}));++vi.mock('@/store/agent', () => ({+ getAgentStoreState: () => ({ activeAgentId: undefined, agentMap: {} }),+}));++vi.mock('@/store/agent/selectors', () => ({+ agentByIdSelectors: {+ getAgencyConfigById: () => () => undefined,+ getAgentById: () => () => undefined,+ },+ agentSelectors: { currentAgentWorkingDirectory: () => () => undefined },+ chatConfigByIdSelectors: {+ getChatConfigById: () => () => ({}),+ isChatModeById: () => () => false,+ isLocalSystemEnabledById: () => () => false,+ },+}));++afterEach(() => {+ vi.clearAllMocks();+ delete (globalThis as any).window;+});++const createMockClient = () => ({ disconnect: vi.fn() });++describe('GatewayActionImpl.watchSubAgentRun', () => {+ const threadContext = {+ agentId: 'agt-expert',+ scope: 'thread' as const,+ threadId: 'thd-1',+ topicId: 'tpc-1',+ };++ function createWatchTestAction() {+ const connectToGateway = vi.fn();+ const completeOperation = vi.fn();+ const operations: Record<string, any> = {};+ const state: Record<string, any> = { gatewayConnections: {}, operations };+ const get = vi.fn(() => ({+ ...state,+ associateMessageWithOperation: vi.fn(),+ completeOperation: (id: string) => {+ completeOperation(id);+ operations[id].status = 'completed';+ },+ connectToGateway,+ startOperation: vi.fn(() => {+ operations['watch-op'] = { status: 'running' };+ return { operationId: 'watch-op' };+ }),+ })) as any;+ const set = vi.fn((updater: any) => {+ if (typeof updater === 'function') Object.assign(state, updater(state));+ else Object.assign(state, updater);+ });++ (globalThis as any).window = {+ global_serverConfigStore: {+ getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),+ },+ };++ const action = new GatewayActionImpl(set as any, get, undefined);+ return { action, completeOperation, connectToGateway, state };+ }++ const watch = (action: GatewayActionImpl) =>+ action.watchSubAgentRun({+ assistantMessageId: 'msg-child',+ context: threadContext,+ operationId: 'op-child',+ token: 'child-ticket',+ });++ it('subscribes passively to the child run with its own ticket, replaying what it missed', () => {+ const { action, connectToGateway } = createWatchTestAction();++ watch(action);++ expect(connectToGateway).toHaveBeenCalledWith(+ expect.objectContaining({+ executor: false,+ gatewayUrl: 'https://gateway.test.com',+ localOperationId: 'watch-op',+ operationId: 'op-child',+ resumeOnConnect: true,+ token: 'child-ticket',+ topicId: 'tpc-1',+ }),+ );+ });++ it('settles only its own render operation when the stream ends, never the topic', () => {+ const { action, completeOperation, connectToGateway } = createWatchTestAction();++ watch(action);+ connectToGateway.mock.calls[0][0].onSessionComplete({+ authFailed: false,+ succeeded: true,+ terminalReceived: true,+ });++ expect(completeOperation).toHaveBeenCalledWith('watch-op');+ expect(topicService.settleRunningOperation).not.toHaveBeenCalled();+ });++ it('drops the subscription and its operation when the caller stops watching', () => {+ const { action, completeOperation, state } = createWatchTestAction();+ const client = createMockClient();+ state.gatewayConnections['op-child'] = { client, status: 'connected' };++ const stop = watch(action);+ stop();++ expect(client.disconnect).toHaveBeenCalled();+ expect(completeOperation).toHaveBeenCalledWith('watch-op');+ });++ it('does nothing without a gateway', () => {+ const { action, connectToGateway } = createWatchTestAction();+ (globalThis as any).window = undefined;++ watch(action)();++ expect(connectToGateway).not.toHaveBeenCalled();+ });+});diff --git a/src/store/chat/slices/agentRun/actions/clearBlankBucket.ts b/src/store/chat/slices/agentRun/actions/clearBlankBucket.tsnew file mode 100644index 00000000000..0fb49f4289f--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/clearBlankBucket.ts@@ -0,0 +1,47 @@+import type { ConversationContext } from '@lobechat/types';++import type { ChatStore } from '@/store/chat/store';++/**+ * Empty an agent's blank (`_new`) conversation bucket once an isolated send+ * (Home composer, forwarding) has created its topic. Isolated callers move on to+ * the topic themselves and never switch the store to it, so nothing else clears+ * the optimistic pair they showed there. Left behind, the next blank send of the+ * agent (e.g. a direct @Agent) sent those rows as its new topic's messages and+ * moved them out of the topic they belong to.+ */+export const clearBlankConversationBucket = (+ get: () => ChatStore,+ { agentId, groupId, scope }: Pick<ConversationContext, 'agentId' | 'groupId' | 'scope'>,+) =>+ get().replaceMessages([], {+ action: 'clearBlankConversationBucket',+ context: { agentId, groupId, scope: scope ?? (groupId ? 'group' : 'main'), topicId: null },+ });++/**+ * Leave the blank bucket a send came from once the send has created its topic.+ *+ * An isolated send never switches the store to its topic, so only its bucket+ * is emptied (see `clearBlankConversationBucket`). Any other send switches to+ * the topic and clears the blank bucket it came from, not the current view: the+ * user may be viewing a different conversation by now. If the user navigated+ * to another topic while the persistence round-trip was in flight, they stay+ * there and the new topic's unread badge surfaces the reply. Both the minted+ * and the persisted topic id count as "still here", since the optimistic topic+ * is re-keyed from the former to the latter.+ */+export const leaveBlankConversationBucket = async (+ get: () => ChatStore,+ context: Pick<ConversationContext, 'agentId' | 'groupId' | 'scope' | 'topicId'>,+ { isolated, topicId }: { isolated?: boolean; topicId: string },+) => {+ if (isolated) return clearBlankConversationBucket(get, context);++ await get().switchTopic(topicId, {+ clearNewKey: true,+ clearNewKeyContext: { agentId: context.agentId, groupId: context.groupId },+ onlyIfActiveTopicIn: [context.topicId ?? null, topicId],+ skipRefreshMessage: true,+ });+};diff --git a/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.test.ts b/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.test.tsindex c772bf69500..89dc6ecf598 100644--- a/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.test.ts@@ -1,7 +1,11 @@-import { AgentRuntimeErrorType, ChatErrorType } from '@lobechat/types';-import { describe, expect, it } from 'vitest';+import { AgentRuntimeErrorType, ChatErrorType, ThreadStatus } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';-import { toDirectMentionMessageError } from './directMentionExecutor';+import {+ executeDirectMention,+ toDirectMentionMessageError,+ toDirectMentionThreadTitle,+} from './directMentionExecutor';describe('toDirectMentionMessageError', () => {it('maps an offline execution device to the actionable device-gateway error', () => {@@ -20,3 +24,168 @@ describe('toDirectMentionMessageError', () => {});});});++describe('toDirectMentionThreadTitle', () => {+ it('shows mentions as @name instead of their markup', () => {+ expect(+ toDirectMentionThreadTitle('<mention name="小雯" id="agt_6Hzr1skp1IRb" />你能干什么'),+ ).toBe('@小雯 你能干什么');+ });++ it('keeps the first 50 characters of the readable text', () => {+ expect(toDirectMentionThreadTitle(`<mention name="A" id="agt_a" /> ${'x'.repeat(80)}`)).toBe(+ `@A ${'x'.repeat(47)}`,+ );+ });+});++describe('executeDirectMention', () => {+ it('refreshes the mentioned agent transcripts so an open thread panel shows the reply', async () => {+ const { ClientSubAgentTransport } =+ await import('@/store/chat/agents/transports/ClientSubAgentTransport');+ vi.spyOn(ClientSubAgentTransport.prototype, 'execSubAgent').mockResolvedValue({+ result: 'reply',+ success: true,+ threadId: 'thd_1',+ } as any);+ const store = {+ associateMessageWithOperation: vi.fn(),+ completeOperation: vi.fn(),+ optimisticUpdateMessageContent: vi.fn().mockResolvedValue(undefined),+ refreshMessages: vi.fn().mockResolvedValue(undefined),+ refreshThreads: vi.fn().mockResolvedValue(undefined),+ startOperation: vi.fn(() => ({ operationId: 'op_client' })),+ };++ await executeDirectMention(+ {+ context: { agentId: 'agt_lobe', topicId: 'tpc_1' },+ instruction: '<mention name="小雯" id="agt_xw" />你能干什么',+ parentOperationId: 'op_send',+ runtimeType: 'gateway',+ sourceMessageId: 'msg_src',+ targetAgentId: 'agt_xw',+ },+ () => store as any,+ );++ expect(store.refreshMessages).toHaveBeenCalledWith({ agentId: 'agt_xw', topicId: 'tpc_1' });+ });++ it('shows the running thread at once and streams the child while it runs', async () => {+ const { ClientSubAgentTransport } =+ await import('@/store/chat/agents/transports/ClientSubAgentTransport');+ const stopWatching = vi.fn();+ const store = {+ associateMessageWithOperation: vi.fn(),+ completeOperation: vi.fn(),+ internal_dispatchMessage: vi.fn(),+ optimisticUpdateMessageContent: vi.fn().mockResolvedValue(undefined),+ refreshMessages: vi.fn().mockResolvedValue(undefined),+ refreshThreads: vi.fn().mockResolvedValue(undefined),+ startOperation: vi.fn(() => ({ operationId: 'op_client' })),+ watchSubAgentRun: vi.fn(() => stopWatching),+ };+ vi.spyOn(ClientSubAgentTransport.prototype, 'execSubAgent').mockImplementation(async function (+ this: any,+ ) {+ this.options.onDispatched({+ assistantMessageId: 'msg_child',+ operationId: 'op_child',+ success: true,+ threadId: 'thd_1',+ token: 'child-ticket',+ });+ expect(stopWatching).not.toHaveBeenCalled();+ // The panel needs the thread (and its agent) while the child still runs.+ expect(store.refreshThreads).toHaveBeenCalled();+ return { result: 'reply', success: true, threadId: 'thd_1' } as any;+ });++ await executeDirectMention(+ {+ context: { agentId: 'agt_lobe', topicId: 'tpc_1' },+ instruction: '<mention name="小雯" id="agt_xw" />你能干什么',+ parentOperationId: 'op_send',+ runtimeType: 'gateway',+ sourceMessageId: 'msg_src',+ targetAgentId: 'agt_xw',+ },+ () => store as any,+ );++ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ {+ id: 'msg_src',+ type: 'updateMessage',+ value: {+ taskDetail: expect.objectContaining({ status: 'processing', threadId: 'thd_1' }),+ },+ },+ { operationId: 'op_client' },+ );+ expect(store.watchSubAgentRun).toHaveBeenCalledWith({+ assistantMessageId: 'msg_child',+ context: { agentId: 'agt_xw', scope: 'thread', threadId: 'thd_1', topicId: 'tpc_1' },+ operationId: 'op_child',+ token: 'child-ticket',+ });+ expect(stopWatching).toHaveBeenCalled();+ });++ describe('without a Gateway (the tab runs the agent itself)', () => {+ const run = async () => {+ const { aiAgentService } = await import('@/services/aiAgent');+ vi.spyOn(aiAgentService, 'createClientTaskThread').mockResolvedValue({+ threadId: 'thd_1',+ threadMessages: [],+ userMessageId: 'msg_task',+ } as any);+ vi.spyOn(aiAgentService, 'updateClientTaskThreadStatus').mockResolvedValue({} as any);+ const store = {+ associateMessageWithOperation: vi.fn(),+ completeOperation: vi.fn(),+ dbMessagesMap: {},+ executeClientAgent: vi.fn().mockResolvedValue(undefined),+ internal_dispatchMessage: vi.fn(),+ optimisticUpdateMessageContent: vi.fn().mockResolvedValue(undefined),+ refreshMessages: vi.fn().mockResolvedValue(undefined),+ refreshThreads: vi.fn().mockResolvedValue(undefined),+ replaceMessages: vi.fn(),+ startOperation: vi.fn(() => ({ operationId: 'op_client' })),+ };++ await executeDirectMention(+ {+ context: { agentId: 'agt_lobe', topicId: 'tpc_1' },+ instruction: '<mention name="小雯" id="agt_xw" />帮我查一下天气',+ parentOperationId: 'op_send',+ runtimeType: 'client',+ sourceMessageId: 'msg_src',+ targetAgentId: 'agt_xw',+ },+ () => store as any,+ );++ return { store };+ };++ it('shows the running thread on the reply at once', async () => {+ const { store } = await run();++ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 'msg_src',+ type: 'updateMessage',+ value: {+ taskDetail: expect.objectContaining({+ status: ThreadStatus.Processing,+ threadId: 'thd_1',+ }),+ },+ }),+ { operationId: 'op_client' },+ );+ });+ });+});diff --git a/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.ts b/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.tsindex 3325a5076e9..b59bd184975 100644--- a/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.ts@@ -3,6 +3,7 @@ import {ChatErrorType,type ChatMessageError,type ConversationContext,+ ThreadStatus,} from '@lobechat/types';import { aiAgentService } from '@/services/aiAgent';@@ -40,6 +41,15 @@ export const toDirectMentionMessageError = (error: unknown): ChatMessageError =>};};+const MENTION_MARKUP = /<mention\s[^>]*?name="([^"]*)"[^>]*\/>\s*/g;++/** Thread title for a direct @Agent run: mentions read as `@name`, not as their markup. */+export const toDirectMentionThreadTitle = (instruction: string): string =>+ instruction+ .replaceAll(MENTION_MARKUP, (_, name: string) => `@${name} `)+ .trim()+ .slice(0, 50);+/*** Executes a direct @Agent route as an isolated task and projects its final* answer onto the source assistant message in the parent conversation.@@ -65,19 +75,63 @@ export const executeDirectMention = async (get().associateMessageWithOperation(sourceMessageId, operationId);let clientThreadId: string | undefined;+ let stopWatching: (() => void) | undefined;+ const endWatching = () => {+ stopWatching?.();+ stopWatching = undefined;+ };++ // The progress card needs the thread now, not after the first poll.+ const showRunningThread = (threadId: string) =>+ get().internal_dispatchMessage(+ {+ id: sourceMessageId,+ type: 'updateMessage',+ value: {+ taskDetail: {+ startedAt: new Date().toISOString(),+ status: ThreadStatus.Processing,+ threadId,+ },+ },+ },+ { operationId },+ );try {let resultContent = '';if (runtimeType === 'gateway') {- const result = await new ClientSubAgentTransport(get, operationId).execSubAgent({+ const topicId = context.topicId;+ const transport = new ClientSubAgentTransport(get, operationId, {+ onDispatched: (dispatch) => {+ showRunningThread(dispatch.threadId);+ // The full-record panel resolves the thread's agent from this list.+ void get().refreshThreads();+ // Follow the child live, so its thread fills in as it streams.+ if (!dispatch.token) return;+ stopWatching = get().watchSubAgentRun({+ assistantMessageId: dispatch.assistantMessageId,+ context: {+ agentId: targetAgentId,+ scope: 'thread',+ threadId: dispatch.threadId,+ topicId,+ },+ operationId: dispatch.operationId,+ token: dispatch.token,+ });+ },+ });+ const result = await transport.execSubAgent({agentId: targetAgentId,instruction,parentMessageId: sourceMessageId,parentOperationId: operationId,- title: instruction.slice(0, 50),- topicId: context.topicId,+ title: toDirectMentionThreadTitle(instruction),+ topicId,});+ endWatching();if (!result.success) throw new Error(result.error || 'Mentioned agent execution failed');resultContent = result.result || '';@@ -86,10 +140,11 @@ export const executeDirectMention = async (agentId: targetAgentId,instruction,parentMessageId: sourceMessageId,- title: instruction.slice(0, 50),+ title: toDirectMentionThreadTitle(instruction),topicId: context.topicId,});clientThreadId = task.threadId;+ showRunningThread(task.threadId);const threadContext: ConversationContext = {...context,@@ -136,8 +191,12 @@ export const executeDirectMention = async (operationId,});void get().refreshThreads();+ // The thread panel keys its transcript by the mentioned agent; one fetched+ // while the run was still going would otherwise keep an empty reply.+ void get().refreshMessages({ agentId: targetAgentId, topicId: context.topicId });get().completeOperation(operationId);} catch (error) {+ endWatching();if (clientThreadId) {await aiAgentService.updateClientTaskThreadStatus({@@ -148,6 +207,7 @@ export const executeDirectMention = async (.catch(console.error);void get().refreshThreads();}+ void get().refreshMessages({ agentId: targetAgentId, topicId: context.topicId });await get().optimisticUpdateMessageError(sourceMessageId, toDirectMentionMessageError(error), {diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.tsindex 71314617889..6cc1c77b84c 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts@@ -73,8 +73,12 @@ import {operationSelectors,topicSelectors,} from '@/store/chat/selectors';+import { leaveBlankConversationBucket } from '@/store/chat/slices/agentRun/actions/clearBlankBucket';import { selectRuntimeType } from '@/store/chat/slices/agentRun/actions/dispatch/agentDispatcher';-import { executeDirectMention } from '@/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor';+import {+ executeDirectMention,+ toDirectMentionThreadTitle,+} from '@/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor';import { resolveNewThreadIntent } from '@/store/chat/slices/agentRun/actions/dispatch/newThreadIntent';import { buildRunLifecycle } from '@/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle';import {@@ -1551,25 +1555,11 @@ export class ConversationLifecycleActionImpl {resolveOptimisticTopic(heteroData.topicId, newTopicTitle);void Promise.resolve(this.#get().refreshTopic()).catch(console.error);}- if (context.isolatedTopic) {- await onTopicCreated?.(heteroData.topicId);- } else {- await this.#get().switchTopic(heteroData.topicId, {- clearNewKey: true,- // The cleanup targets the blank bucket this send came from — the- // user may be viewing a different conversation by now.- clearNewKeyContext: {- agentId: operationContext.agentId,- groupId: operationContext.groupId,- },- // Guard against yanking the user back if they navigated to another- // topic while the persistence round-trip was in flight. Accept both- // the minted id and the persisted one: `resolveOptimisticTopic`- // above re-keys `activeTopicId` from the former to the latter.- onlyIfActiveTopicIn: [operationContext.topicId ?? null, heteroData.topicId],- skipRefreshMessage: true,- });- }+ if (context.isolatedTopic) await onTopicCreated?.(heteroData.topicId);+ await leaveBlankConversationBucket(this.#get, operationContext, {+ isolated: context.isolatedTopic,+ topicId: heteroData.topicId,+ });}let directMentionThreadId: string | undefined;@@ -1584,7 +1574,7 @@ export class ConversationLifecycleActionImpl {assistantMessage: { provider: heterogeneousProvider.type },instruction: message,parentMessageId: heteroData.assistantMessageId,- title: message.slice(0, 50),+ title: toDirectMentionThreadTitle(message),topicId: heteroTopicId,});if (!task.assistantMessageId) {@@ -2103,30 +2093,13 @@ export class ConversationLifecycleActionImpl {});if (isCreateNewTopic && data.topicId) {- if (context.isolatedTopic) {- // Notify the isolated caller immediately so its UI re-subscribes to- // the new topic key and picks up the streaming AI response.- await onTopicCreated?.(data.topicId);- } else {- // clearNewKey: true ensures the _new key data is cleared after topic creation- await this.#get().switchTopic(data.topicId, {- clearNewKey: true,- // The cleanup targets the blank bucket this send came from — the- // user may be viewing a different conversation by now.- clearNewKeyContext: {- agentId: operationContext.agentId,- groupId: operationContext.groupId,- },- // The send pivoted to the minted topic bucket at send time. If the- // user navigated to another topic while the persistence round-trip- // was in flight, leave them where they are — the new topic's unread- // badge surfaces the completed reply instead of yanking the view back.- // Both ids are accepted: `resolveOptimisticTopic` above re-keys- // `activeTopicId` from the minted id to the persisted one.- onlyIfActiveTopicIn: [operationContext.topicId ?? null, data.topicId],- skipRefreshMessage: true,- });- }+ // Notify the isolated caller immediately so its UI re-subscribes to+ // the new topic key and picks up the streaming AI response.+ if (context.isolatedTopic) await onTopicCreated?.(data.topicId);+ await leaveBlankConversationBucket(this.#get, operationContext, {+ isolated: context.isolatedTopic,+ topicId: data.topicId,+ });}} catch (e) {console.error(e);diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex c19f28b68b4..9db7aaa93f4 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -46,6 +46,7 @@ import {} from '@/store/chat/pendingSandboxSelection';import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';import { topicSelectors } from '@/store/chat/selectors';+import { leaveBlankConversationBucket } from '@/store/chat/slices/agentRun/actions/clearBlankBucket';import { operationSelectors } from '@/store/chat/slices/operation/selectors';import {SETTLEABLE_TOPIC_RUN_OPERATION_TYPES,@@ -87,6 +88,7 @@ import { flagQueuedMessagesOnRunStart, syncQueuedMessagesFlag } from './queuedMeimport { gatewayRunOperationMetadata } from './runOperationMetadata';import { isCompletedRuntimeEnd } from './runtimeEndReason';import * as serverSteerQueue from './serverSteerQueue';+import { watchSubAgentRun, type WatchSubAgentRunParams } from './watchSubAgentRun';const getGatewayServerConfig = () =>(typeof window !== 'undefined'@@ -1372,23 +1374,10 @@ export class GatewayActionImpl {/* non-critical */}- if (!messageContext.isolatedTopic) {- await this.#get().switchTopic(result.topicId, {- clearNewKey: true,- // The cleanup targets the blank bucket this send came from — the- // user may be viewing a different conversation by now.- clearNewKeyContext: {- agentId: messageContext.agentId,- groupId: messageContext.groupId,- },- // Guard against yanking the user back if they navigated to another- // topic while execAgentTask's persistence round-trip was in flight.- // Both ids are accepted: the optimistic-topic re-key above moves- // `activeTopicId` from the minted id to the persisted one.- onlyIfActiveTopicIn: [messageContext.topicId ?? null, result.topicId],- skipRefreshMessage: true,- });- }+ await leaveBlankConversationBucket(this.#get, messageContext, {+ isolated: messageContext.isolatedTopic,+ topicId: result.topicId,+ });// Refresh the topic list so the new topic appears in topicDataMap (sidebar).// Unlike the direct-API sendMessage path (which receives topics[] in the@@ -1749,6 +1738,13 @@ export class GatewayActionImpl {return resumed;};+ /** Stream a sub-agent run this tab dispatched but does not drive; see `watchSubAgentRun`. */+ watchSubAgentRun = (params: WatchSubAgentRunParams): (() => void) =>+ watchSubAgentRun(this.#get, params, {+ disconnect: this.disconnectFromGateway,+ gatewayUrl: getGatewayServerConfig()?.agentGatewayUrl,+ });+/*** Reconnect to an existing Gateway operation after page reload.* Reads runningOperation from topic metadata, refreshes the JWT token,diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/watchSubAgentRun.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/watchSubAgentRun.tsnew file mode 100644index 00000000000..388cb05cb48--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/watchSubAgentRun.ts@@ -0,0 +1,63 @@+import type { ConversationContext } from '@lobechat/types';++import type { ChatStore } from '@/store/chat/store';++import { createGatewayEventHandler } from './gatewayEventHandler';++export interface WatchSubAgentRunParams {+ assistantMessageId: string;+ context: ConversationContext;+ operationId: string;+ token: string;+}++/**+ * Stream a sub-agent run this tab dispatched but does not drive (a direct+ * @Agent mention), so its thread fills in live instead of all at once.+ *+ * Render-only: the run's events land in `context`'s transcript, and nothing+ * on the topic is settled — the child owns no topic marker, and the+ * dispatcher's task poll owns the outcome. Joins late, so it replays what the+ * run already produced. Returns a stop that drops the subscription.+ */+export const watchSubAgentRun = (+ get: () => ChatStore,+ { assistantMessageId, context, operationId, token }: WatchSubAgentRunParams,+ gateway: { disconnect: (operationId: string) => void; gatewayUrl?: string },+): (() => void) => {+ if (!gateway.gatewayUrl || !context.topicId) return () => {};++ const { operationId: localOperationId } = get().startOperation({+ context,+ metadata: { serverOperationId: operationId },+ type: 'execServerAgentRuntime',+ });+ get().associateMessageWithOperation(assistantMessageId, localOperationId);++ const settle = () => {+ if (get().operations[localOperationId]?.status === 'running')+ get().completeOperation(localOperationId);+ };++ get().connectToGateway({+ executor: false,+ gatewayUrl: gateway.gatewayUrl,+ localOperationId,+ onEvent: createGatewayEventHandler(get, {+ assistantMessageId,+ context,+ gatewayOperationId: operationId,+ operationId: localOperationId,+ }),+ onSessionComplete: settle,+ operationId,+ resumeOnConnect: true,+ token,+ topicId: context.topicId,+ });++ return () => {+ gateway.disconnect(operationId);+ settle();+ };+};