🤯 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: add curated agent share profile data (#19838)
YuTengjing00d3a60581c1
diff --git a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts b/apps/server/src/routers/lambda/__tests__/agentShare.test.tsindex e0e5d96c73b..6cdf4b5d835 100644--- a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agentShare.test.ts@@ -60,6 +60,7 @@ const mockListWorkspaceSharesForAudit = vi.fn();const mockUpdateConfig = vi.fn();const mockUpdateSlug = vi.fn();const mockUpdateVisibility = vi.fn();+const mockListEligibleWorks = vi.fn();vi.mock('@/database/models/agentShare', () => ({AgentShareModel: Object.assign(@@ -80,6 +81,12 @@ vi.mock('@/database/models/agentShare', () => ({),}));+vi.mock('@/database/models/agentShareProfile', () => ({+ AgentShareProfileModel: vi.fn(function () {+ return { listEligibleWorks: mockListEligibleWorks };+ }),+}));+const mockCountShareVisitors = vi.fn();vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn(function () {@@ -108,6 +115,32 @@ vi.mock('@/server/featureFlags', () => ({const { agentShareConfigPatchSchema, agentShareConfigSchema, agentShareRouter } =await import('../agentShare');+describe('share profile configuration', () => {+ it('accepts independent demo cases and an ordered selection of works', () => {+ const config = {+ demoCases: [{ description: 'Find a minimal fix', prompt: 'Help me debug this error' }],+ featuredWorkIds: ['work-first', 'work-second'],+ };+ expect(agentShareConfigPatchSchema.parse(config)).toEqual(config);+ });++ it('allows clearing profile content without changing other settings', () => {+ expect(agentShareConfigPatchSchema.parse({ demoCases: [], featuredWorkIds: [] })).toEqual({+ demoCases: [],+ featuredWorkIds: [],+ });+ });++ it.each([+ { demoCases: [{ description: 'Empty task', prompt: ' ' }] },+ { demoCases: [{ description: 'Description', prompt: 'Task', openingQuestion: 'Other' }] },+ { featuredWorkIds: ['same', 'same'] },+ { featuredWorkIds: [''] },+ ])('rejects invalid profile content: %j', (config) => {+ expect(agentShareConfigPatchSchema.safeParse(config).success).toBe(false);+ });+});+const share = {agentId: 'agent-1',id: 'share-1',@@ -139,6 +172,7 @@ describe('agentShareRouter', () => {shareConfig: { ...share.shareConfig, slug: 'my-slug' },});mockUpdateVisibility.mockResolvedValue(share);+ mockListEligibleWorks.mockResolvedValue({ hasMore: false, items: [] });mockCountShareVisitors.mockResolvedValue({ topicCount: 7, visitorCount: 3 });mockCountAgentShareUsage.mockResolvedValue(0);mockGetAgentShareMonthlySpend.mockResolvedValue(null);@@ -228,6 +262,54 @@ describe('agentShareRouter', () => {);});+ it('lists paged owner candidates and carries selected ids for older pages', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));+ const page = { hasMore: true, items: [{ id: 'older-work' }] };+ mockListEligibleWorks.mockResolvedValue(page);++ await expect(+ caller.listEligibleWorks({+ agentId: 'agent-1',+ includeWorkIds: ['older-work'],+ limit: 30,+ offset: 30,+ }),+ ).resolves.toEqual(page);+ expect(mockListEligibleWorks).toHaveBeenCalledWith('agent-1', {+ includeWorkIds: ['older-work'],+ limit: 30,+ offset: 30,+ });+ });++ it('rejects an unauthenticated or non-owner candidate request', async () => {+ const anonymousCaller = agentShareRouter.createCaller(await createContextInner());+ await expect(+ anonymousCaller.listEligibleWorks({ agentId: 'agent-1', includeWorkIds: [] }),+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });++ mockGetByAgentId.mockResolvedValue(null);+ const visitorCaller = agentShareRouter.createCaller(+ await createContextInner({ userId: 'visitor-user' }),+ );+ await expect(+ visitorCaller.listEligibleWorks({ agentId: 'agent-1', includeWorkIds: [] }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockListEligibleWorks).not.toHaveBeenCalled();+ });++ it('rejects duplicate selected ids before querying the model', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(+ caller.listEligibleWorks({+ agentId: 'agent-1',+ includeWorkIds: ['same-work', 'same-work'],+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mockListEligibleWorks).not.toHaveBeenCalled();+ });+it('forwards an atomic share configuration patch', async () => {const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));const config = { maxTopicsPerVisitor: 10 };diff --git a/apps/server/src/routers/lambda/__tests__/share.test.ts b/apps/server/src/routers/lambda/__tests__/share.test.tsindex 7bb1b5e4fce..2137fdf9a33 100644--- a/apps/server/src/routers/lambda/__tests__/share.test.ts+++ b/apps/server/src/routers/lambda/__tests__/share.test.ts@@ -6,6 +6,11 @@ import { AgentShareModel } from '@/database/models/agentShare';import { TopicShareModel } from '@/database/models/topicShare';import { createContextInner } from '@/libs/trpc/lambda/context';+vi.mock('@/server/services/agentShare/deliveryStatsCache', () => ({+ getCachedDeliveryStats: (_db: unknown, _owner: string, _agent: string, load: () => unknown) =>+ load(),+}));+vi.mock('@/database/models/agentShare', () => ({AgentShareModel: {assertShareAccess: vi.fn(),@@ -16,6 +21,25 @@ vi.mock('@/database/models/agentShare', () => ({const countShareVisitors = vi.fn();const topicModelConstructor = vi.fn();+const profileModelConstructor = vi.fn();+const listFeaturedWorks = vi.fn();+const getDeliveryStats = vi.fn();+const emptyDeliveryStats = {+ averageOperationDurationSeconds: null,+ averageWorkCost: null,+ lastDeliveredAt: null,+ workCount: 0,+};++vi.mock('@/database/models/agentShareProfile', () => ({+ AgentShareProfileModel: class {+ constructor(...args: unknown[]) {+ profileModelConstructor(...args);+ }+ getStats = getDeliveryStats;+ listFeaturedWorks = listFeaturedWorks;+ },+}));vi.mock('@/database/models/topic', () => ({TopicModel: class {@@ -142,6 +166,8 @@ describe('shareRouter', () => {vi.mocked(AgentShareModel.assertShareAccess).mockReturnValue(undefined);vi.mocked(AgentShareModel.incrementUserViewCount).mockResolvedValue(undefined);countShareVisitors.mockResolvedValue({ topicCount: 12, visitorCount: 7 });+ listFeaturedWorks.mockResolvedValue([]);+ getDeliveryStats.mockResolvedValue(emptyDeliveryStats);loadModelsMock.mockResolvedValue([{abilities: { audio: false, video: false, vision: true },@@ -153,6 +179,48 @@ describe('shareRouter', () => {resolveModelSelectionMock.mockResolvedValue({ model: 'gpt-4o', provider: 'openai' });});+ it('returns independent demos and selected deliveries in the owner scope', async () => {+ const demoCases = [{ prompt: 'Review this migration', description: 'Find deployment risks' }];+ const work = { id: 'work-selected', title: 'Migration review', totalCost: 0.2 };+ vi.mocked(AgentShareModel.findBySlugOrId).mockResolvedValue({+ ...agentShare,+ shareConfig: {+ ...agentShare.shareConfig,+ demoCases,+ featuredWorkIds: [work.id],+ maxFileStorage: 512 * 1024 * 1024,+ monthlySpendLimit: 10,+ },+ agentSlug: 'agent-profile',+ });+ listFeaturedWorks.mockResolvedValue([work]);+ getDeliveryStats.mockResolvedValue({+ averageOperationDurationSeconds: 15,+ averageWorkCost: 0.2,+ lastDeliveredAt: new Date('2026-01-01'),+ workCount: 3,+ });+ const caller = shareRouter.createCaller(await createContextInner({ userId: 'visitor-user' }));+ const result = await caller.getSharedAgent({ slugOrId: 'shared-agent' });+ expect(result.demoCases).toEqual(demoCases);+ expect(result.agentMeta.openingQuestions).toEqual(['What can you do?']);+ expect(result.featuredWorks).toEqual([work]);+ expect(result.stats).toMatchObject({+ averageOperationDurationSeconds: 15,+ averageWorkCost: 0.2,+ workCount: 3,+ });+ expect(profileModelConstructor).toHaveBeenCalledWith(expect.anything(), 'owner-user');+ });++ it('keeps the profile available when delivery analytics fail', async () => {+ getDeliveryStats.mockRejectedValue(new Error('analytics unavailable'));+ const caller = shareRouter.createCaller(await createContextInner({ userId: 'visitor-user' }));+ const result = await caller.getSharedAgent({ slugOrId: 'shared-agent' });+ expect(result.stats).toMatchObject(emptyDeliveryStats);+ expect(result.featuredWorks).toEqual([]);+ });+it('requires authentication without resolving or counting the share', async () => {const caller = shareRouter.createCaller(await createContextInner());@@ -161,6 +229,8 @@ describe('shareRouter', () => {});expect(AgentShareModel.findBySlugOrId).not.toHaveBeenCalled();expect(AgentShareModel.incrementUserViewCount).not.toHaveBeenCalled();+ expect(listFeaturedWorks).not.toHaveBeenCalled();+ expect(getDeliveryStats).not.toHaveBeenCalled();});it('resolves by slug, returns only visitor-safe metadata, and counts the view', async () => {@@ -181,10 +251,12 @@ describe('shareRouter', () => {},billingScope: 'personal',creator: { avatar: 'owner.png', name: 'Owner Person' },+ demoCases: [],+ featuredWorks: [],isOwner: false,shareId: 'agent-share-1',slug: 'shared-agent',- stats: { conversations: 12, views: 42, visitors: 7 },+ stats: { ...emptyDeliveryStats, conversations: 12, views: 42, visitors: 7 },terms: {allowCreatorViewSessions: false,maxFileStorage: 512 * 1024 * 1024,@@ -391,6 +463,8 @@ describe('shareRouter', () => {code,});expect(AgentShareModel.incrementUserViewCount).not.toHaveBeenCalled();+ expect(listFeaturedWorks).not.toHaveBeenCalled();+ expect(getDeliveryStats).not.toHaveBeenCalled();});describe('visitor capability', () => {diff --git a/apps/server/src/routers/lambda/agentShare.ts b/apps/server/src/routers/lambda/agentShare.tsindex b7c99a37c79..e2074e7583d 100644--- a/apps/server/src/routers/lambda/agentShare.ts+++ b/apps/server/src/routers/lambda/agentShare.ts@@ -9,6 +9,7 @@ import { getAgentShareMonthlySpend } from '@/business/server/agent-share/spendGaimport { withRbacPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { AgentShareModel } from '@/database/models/agentShare';+import { AgentShareProfileModel } from '@/database/models/agentShareProfile';import { FileModel } from '@/database/models/file';import { RbacModel } from '@/database/models/rbac';import { TopicModel } from '@/database/models/topic';@@ -47,6 +48,22 @@ export const agentShareConfigSchema = z.object({allowCreatorViewSessions: z.boolean().optional(),allowReadMemory: z.boolean().optional(),+ demoCases: z+ .array(+ z+ .object({+ description: z.string().trim().max(2000),+ prompt: z.string().trim().min(1).max(10000),+ })+ .strict(),+ )+ .max(20)+ .optional(),+ featuredWorkIds: z+ .array(z.string().trim().min(1))+ .max(100)+ .refine((ids) => new Set(ids).size === ids.length, 'Duplicate featured Work')+ .optional(),/** Bytes; `0` is a real value (attachments off), so non-negative rather than positive. */maxFileStorage: z.number().int().nonnegative().optional(),/**@@ -105,6 +122,7 @@ const agentShareProcedure = wsCompatProcedure.use(serverDatabase).use(async (opt}): undefined,}),+ agentShareProfileModel: new AgentShareProfileModel(ctx.serverDB, ctx.userId),},});});@@ -293,6 +311,28 @@ export const agentShareRouter = router({),),+ /** Owner-only candidate Works for the share profile editor. */+ listEligibleWorks: agentShareProcedure+ .input(+ agentIdInput.extend({+ includeWorkIds: z+ .array(z.string().trim().min(1))+ .max(100)+ .refine((ids) => new Set(ids).size === ids.length, 'Duplicate selected Work')+ .optional(),+ limit: z.number().int().positive().max(50).optional(),+ offset: z.number().int().nonnegative().max(10000).optional(),+ }),+ )+ .query(async ({ input, ctx }) => {+ requireShare(await ctx.agentShareModel.getByAgentId(input.agentId));+ return ctx.agentShareProfileModel.listEligibleWorks(input.agentId, {+ includeWorkIds: input.includeWorkIds ?? [],+ limit: input.limit,+ offset: input.offset,+ });+ }),+updateShareConfig: agentShareProcedure.input(zdiff --git a/apps/server/src/routers/lambda/share.ts b/apps/server/src/routers/lambda/share.tsindex 746a1802d47..d90ee0ab006 100644--- a/apps/server/src/routers/lambda/share.ts+++ b/apps/server/src/routers/lambda/share.ts@@ -5,6 +5,7 @@ import {} from '@lobechat/const';import {type SharedAgentData,+ type SharedAgentDeliveryStats,type SharedAgentUploadAbility,type SharedTopicData,} from '@lobechat/types';@@ -14,6 +15,7 @@ import type { ModelAbilities } from 'model-bank';import { z } from 'zod';import { AgentShareModel } from '@/database/models/agentShare';+import { AgentShareProfileModel } from '@/database/models/agentShareProfile';import { AiModelModel } from '@/database/models/aiModel';import { TopicModel } from '@/database/models/topic';import { TopicShareModel } from '@/database/models/topicShare';@@ -22,6 +24,7 @@ import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { resolveModelMediaCapabilities } from '@/server/modules/AgentRuntime/resolveModelMediaCapabilities';import { AgentService } from '@/server/services/agent';+import { getCachedDeliveryStats } from '@/server/services/agentShare/deliveryStatsCache';import { assertAgentShareVisitorEnabled } from './_helpers/agentShareFeatureGate';@@ -138,8 +141,28 @@ export const shareRouter = router({// them. Best-effort — analytics must never turn a valid share page into// an error.let stats = { conversations: 0, visitors: 0 };- const [uploadAbility] = await Promise.all([+ const profileModel = new AgentShareProfileModel(ctx.serverDB, share.ownerId);+ let deliveryStats: SharedAgentDeliveryStats = {+ averageOperationDurationSeconds: null,+ averageWorkCost: null,+ lastDeliveredAt: null,+ workCount: 0,+ };+ const [uploadAbility, featuredWorks] = await Promise.all([resolveVisitorUploadAbility(ctx.serverDB, share),+ profileModel.listFeaturedWorks(share.agentId, share.shareConfig.featuredWorkIds ?? []),+ (async () => {+ try {+ deliveryStats = await getCachedDeliveryStats(+ ctx.serverDB,+ share.ownerId,+ share.agentId,+ () => profileModel.getStats(share.agentId),+ );+ } catch (error) {+ log('failed to count share deliveries for %s: %O', share.shareId, error);+ }+ })(),(async () => {try {const topicModel = new TopicModel(@@ -171,10 +194,12 @@ export const shareRouter = router({avatar: share.ownerAvatar ?? null,name: share.ownerFullName ?? share.ownerUsername ?? null,},+ demoCases: share.shareConfig.demoCases ?? [],+ featuredWorks,isOwner,shareId: share.shareId,slug: share.shareConfig.slug ?? null,- stats: { ...stats, views: share.userViewCount },+ stats: { ...stats, ...deliveryStats, views: share.userViewCount },terms: {allowCreatorViewSessions: share.shareConfig.allowCreatorViewSessions ?? false,maxFileStorage: share.shareConfig.maxFileStorage ?? AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,diff --git a/apps/server/src/services/agentShare/deliveryStatsCache.test.ts b/apps/server/src/services/agentShare/deliveryStatsCache.test.tsnew file mode 100644index 00000000000..40837ef2a45--- /dev/null+++ b/apps/server/src/services/agentShare/deliveryStatsCache.test.ts@@ -0,0 +1,49 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { createDeliveryStatsCache } from './deliveryStatsCache';++const stats = {+ averageOperationDurationSeconds: null,+ averageWorkCost: null,+ lastDeliveredAt: null,+ workCount: 3,+};+afterEach(() => vi.useRealTimers());++describe('delivery stats cache', () => {+ it('coalesces concurrent visitors and refreshes after a minute', async () => {+ vi.useFakeTimers();+ const get = createDeliveryStatsCache();+ const db = {};+ const load = vi.fn().mockResolvedValue(stats);+ const first = get(db, 'owner', 'agent', load);+ expect(get(db, 'owner', 'agent', load)).toBe(first);+ await first;+ await get(db, 'owner', 'agent', load);+ expect(load).toHaveBeenCalledTimes(1);+ vi.advanceTimersByTime(60_000);+ await get(db, 'owner', 'agent', load);+ expect(load).toHaveBeenCalledTimes(2);+ });++ it('isolates databases, owners and agents and retries failures', async () => {+ const get = createDeliveryStatsCache();+ const db = {};+ const load = vi.fn().mockRejectedValueOnce(new Error('unavailable')).mockResolvedValue(stats);+ await expect(get(db, 'owner', 'agent', load)).rejects.toThrow('unavailable');+ await get(db, 'owner', 'agent', load);+ await get(db, 'other', 'agent', load);+ await get(db, 'owner', 'other', load);+ await get({}, 'owner', 'agent', load);+ expect(load).toHaveBeenCalledTimes(5);+ });++ it('evicts old entries at the size bound', async () => {+ const get = createDeliveryStatsCache();+ const db = {};+ const load = vi.fn().mockResolvedValue(stats);+ for (let i = 0; i < 257; i++) await get(db, 'owner', String(i), load);+ await get(db, 'owner', '0', load);+ expect(load).toHaveBeenCalledTimes(258);+ });+});diff --git a/apps/server/src/services/agentShare/deliveryStatsCache.ts b/apps/server/src/services/agentShare/deliveryStatsCache.tsnew file mode 100644index 00000000000..b0cb6e1ab4a--- /dev/null+++ b/apps/server/src/services/agentShare/deliveryStatsCache.ts@@ -0,0 +1,40 @@+import type { SharedAgentDeliveryStats } from '@lobechat/types';++/** Aggregate snapshots may lag by one minute; access checks and curated Works are never cached. */+const TTL_MS = 60_000;+const MAX_ENTRIES = 256;++export const createDeliveryStatsCache = () => {+ const databases = new WeakMap<+ object,+ Map<string, { expiresAt: number; promise: Promise<SharedAgentDeliveryStats> }>+ >();++ return (+ db: object,+ ownerId: string,+ agentId: string,+ load: () => Promise<SharedAgentDeliveryStats>,+ ): Promise<SharedAgentDeliveryStats> => {+ let entries = databases.get(db);+ if (!entries) {+ entries = new Map();+ databases.set(db, entries);+ }+ const key = JSON.stringify([ownerId, agentId]);+ const existing = entries.get(key);+ if (existing && existing.expiresAt > Date.now()) return existing.promise;+ entries.delete(key);+ if (entries.size >= MAX_ENTRIES) entries.delete(entries.keys().next().value!);++ /** Cache the in-flight promise too, so concurrent visitors share the same aggregate query. */+ const promise = Promise.resolve().then(load);+ entries.set(key, { expiresAt: Date.now() + TTL_MS, promise });+ void promise.catch(() => {+ if (entries.get(key)?.promise === promise) entries.delete(key);+ });+ return promise;+ };+};++export const getCachedDeliveryStats = createDeliveryStatsCache();diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex c23734a4f8a..8ab4c65fffe 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -357,7 +357,38 @@"share.settings.permissions.showModelInfo": "Show which model is used","share.settings.permissions.showModelInfoHint": "Off by default: your model and provider choice stays hidden.","share.settings.permissions.title": "Permissions",+ "share.settings.profile.demoCases.add": "Add example",+ "share.settings.profile.demoCases.desc": "Write examples for visitors to try. These are separate from the agent’s opening questions.",+ "share.settings.profile.demoCases.description": "Description",+ "share.settings.profile.demoCases.descriptionHint": "Shown below the task prompt to explain what this agent can help with. This text is not added to the chat.",+ "share.settings.profile.demoCases.descriptionLabel": "Description (optional)",+ "share.settings.profile.demoCases.descriptionPlaceholder": "Explain the expected result (optional)",+ "share.settings.profile.demoCases.empty": "No examples published yet.",+ "share.settings.profile.demoCases.item": "Example {{number}}",+ "share.settings.profile.demoCases.prompt": "Task prompt",+ "share.settings.profile.demoCases.promptHint": "Shown as the example title. Clicking it fills the visitor’s chat input without sending.",+ "share.settings.profile.demoCases.promptLabel": "Task prompt (required)",+ "share.settings.profile.demoCases.promptPlaceholder": "What would you ask this agent to do?",+ "share.settings.profile.demoCases.remove": "Remove example",+ "share.settings.profile.demoCases.title": "Example tasks",+ "share.settings.profile.desc": "Choose what visitors see before starting a conversation. Changes are published when you save.",+ "share.settings.profile.featuredWorks.desc": "Choose this agent’s works to showcase. Visitor works are never included.",+ "share.settings.profile.featuredWorks.empty": "No eligible works yet. Create a work with this agent first.",+ "share.settings.profile.featuredWorks.loadFailed": "Could not load works. Try again.",+ "share.settings.profile.featuredWorks.loadMore": "Load more works",+ "share.settings.profile.featuredWorks.reload": "Retry",+ "share.settings.profile.featuredWorks.select": "Feature",+ "share.settings.profile.featuredWorks.selected": "Selected: {{count}} / 100",+ "share.settings.profile.featuredWorks.title": "Featured works",+ "share.settings.profile.featuredWorks.unavailable": "Unavailable work",+ "share.settings.profile.featuredWorks.withdraw": "Remove",+ "share.settings.profile.invalid": "Each example needs a task prompt. Keep at most 20 examples and 100 featured works.",+ "share.settings.profile.save": "Save profile",+ "share.settings.profile.saveError": "Could not save. Your draft is preserved. Try again.",+ "share.settings.profile.saved": "Profile saved",+ "share.settings.profile.title": "Public profile","share.settings.tabs.access": "Access",+ "share.settings.tabs.profile": "Public profile","share.settings.tabs.stats": "Stats","share.settings.title": "Share Agent","share.settings.tools.apiGrantedCount": "{{granted}} of {{total}} APIs granted",@@ -380,6 +411,7 @@"share.settings.usage.fileStorageOff": "{{used}} · attachments off","share.settings.usage.loadFailed": "Usage could not be loaded","share.settings.usage.monthlySpend": "This month’s spend",+ "share.settings.usage.spendOfLimit": "${{spend}} of ${{limit}}","share.settings.usage.spendOfLimitCredits": "{{spend}} of {{limit}} credits","share.settings.usage.title": "Usage","share.settings.usage.views": "Visits",@@ -415,16 +447,25 @@"share.visitor.profile.freeNoteWorkspace": "Free · paid for by the Workspace","share.visitor.profile.metrics.conversations": "Conversations","share.visitor.profile.metrics.conversationsCaption": "started so far",+ "share.visitor.profile.metrics.cost": "Average cost",+ "share.visitor.profile.metrics.costCaption": "per work · paid by the creator",+ "share.visitor.profile.metrics.duration": "Average duration",+ "share.visitor.profile.metrics.durationCaption": "per operation",+ "share.visitor.profile.metrics.lastDelivered": "Latest delivery",+ "share.visitor.profile.metrics.lastDeliveredCaption": "most recent update","share.visitor.profile.metrics.tools": "Open tools","share.visitor.profile.metrics.toolsCaption": "available to you","share.visitor.profile.metrics.turns": "Each conversation","share.visitor.profile.metrics.turnsCaption": "turns at most",+ "share.visitor.profile.metrics.unknown": "No data yet","share.visitor.profile.metrics.views": "Views","share.visitor.profile.metrics.viewsCaption": "on this page","share.visitor.profile.metrics.visitors": "People who used it","share.visitor.profile.metrics.visitorsCaption": "visitors",+ "share.visitor.profile.metrics.works": "Total works",+ "share.visitor.profile.metrics.worksCaption": "creator deliveries","share.visitor.profile.starters.desc": "Pick one and it goes straight into the composer.",- "share.visitor.profile.starters.title": "Not sure where to start?",+ "share.visitor.profile.starters.title": "Try these","share.visitor.profile.terms.account": "It runs on the creator’s account, and every reply is paid for by them.","share.visitor.profile.terms.accountWorkspace": "It runs in the owner Workspace, and every reply is paid from the Workspace budget.","share.visitor.profile.terms.desc": "Today these rules only show up as errors once you hit them. Here they are up front.",@@ -437,6 +478,14 @@"share.visitor.profile.terms.uploadsOff": "Attachments are turned off.","share.visitor.profile.terms.visibilityCreator": "The creator has turned on session review, so they can read this conversation.","share.visitor.profile.terms.visibilityPrivate": "Only you can see your conversations.",+ "share.visitor.profile.works.desc": "Selected by the creator. See what this agent can deliver.",+ "share.visitor.profile.works.open": "Open work",+ "share.visitor.profile.works.title": "Featured works",+ "share.visitor.profile.works.type.document": "Document",+ "share.visitor.profile.works.type.external": "Linked work",+ "share.visitor.profile.works.type.file": "File",+ "share.visitor.profile.works.type.task": "Task",+ "share.visitor.profile.works.untitled": "Untitled work","share.visitor.topBar.home": "Go to my LobeHub","share.visitor.topics.empty": "No conversations yet","share.visitor.topics.new": "New conversation",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex 6e2183bb038..6ffb5fd8116 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -357,7 +357,38 @@"share.settings.permissions.showModelInfo": "展示使用的模型","share.settings.permissions.showModelInfoHint": "默认关闭:不向访客暴露你选择的模型和服务商。","share.settings.permissions.title": "权限",+ "share.settings.profile.demoCases.add": "添加案例",+ "share.settings.profile.demoCases.desc": "为访客编写可直接试用的案例,独立于助手的开场问题。",+ "share.settings.profile.demoCases.description": "案例说明",+ "share.settings.profile.demoCases.descriptionHint": "显示在任务文本下方,说明助手能提供什么帮助;不会带入对话。",+ "share.settings.profile.demoCases.descriptionLabel": "案例描述(选填)",+ "share.settings.profile.demoCases.descriptionPlaceholder": "说明预期交付的结果(选填)",+ "share.settings.profile.demoCases.empty": "尚未配置演示案例。",+ "share.settings.profile.demoCases.item": "案例 {{number}}",+ "share.settings.profile.demoCases.prompt": "任务文本",+ "share.settings.profile.demoCases.promptHint": "作为案例标题展示,点击后填入访客的对话输入框,不会自动发送。",+ "share.settings.profile.demoCases.promptLabel": "任务文本(必填)",+ "share.settings.profile.demoCases.promptPlaceholder": "你希望访客让这个助手做什么?",+ "share.settings.profile.demoCases.remove": "删除案例",+ "share.settings.profile.demoCases.title": "演示案例",+ "share.settings.profile.desc": "配置访客开始对话前看到的内容,保存后对外展示。",+ "share.settings.profile.featuredWorks.desc": "选择这个助手的成果展示给访客,访客生成的成果不会出现在这里。",+ "share.settings.profile.featuredWorks.empty": "暂无可展示的成果,请先使用这个助手创作成果。",+ "share.settings.profile.featuredWorks.loadFailed": "成果加载失败,请重试。",+ "share.settings.profile.featuredWorks.loadMore": "加载更多成果",+ "share.settings.profile.featuredWorks.reload": "重试",+ "share.settings.profile.featuredWorks.select": "加入精选",+ "share.settings.profile.featuredWorks.selected": "已选择 {{count}} / 100 件",+ "share.settings.profile.featuredWorks.title": "精选成果",+ "share.settings.profile.featuredWorks.unavailable": "已不可用的成果",+ "share.settings.profile.featuredWorks.withdraw": "撤回",+ "share.settings.profile.invalid": "请填写每条案例的任务文本,最多添加 20 条案例和 100 件精选成果。",+ "share.settings.profile.save": "保存宣传页内容",+ "share.settings.profile.saveError": "保存失败,草稿已保留,请重试。",+ "share.settings.profile.saved": "宣传页内容已保存",+ "share.settings.profile.title": "宣传页内容","share.settings.tabs.access": "授权",+ "share.settings.tabs.profile": "宣传页","share.settings.tabs.stats": "统计","share.settings.title": "分享助手","share.settings.tools.apiGrantedCount": "已开放 {{granted}}/{{total}} 个接口",@@ -380,6 +411,7 @@"share.settings.usage.fileStorageOff": "{{used}} · 附件已关闭","share.settings.usage.loadFailed": "用量加载失败","share.settings.usage.monthlySpend": "本月消耗",+ "share.settings.usage.spendOfLimit": "${{spend}} / ${{limit}}","share.settings.usage.spendOfLimitCredits": "{{spend}} / {{limit}} 积分","share.settings.usage.title": "用量","share.settings.usage.views": "访问次数",@@ -415,16 +447,25 @@"share.visitor.profile.freeNoteWorkspace": "免费 · 由工作区付费","share.visitor.profile.metrics.conversations": "累计对话","share.visitor.profile.metrics.conversationsCaption": "次会话",+ "share.visitor.profile.metrics.cost": "平均成本",+ "share.visitor.profile.metrics.costCaption": "每件成果 · 创建者承担",+ "share.visitor.profile.metrics.duration": "平均耗时",+ "share.visitor.profile.metrics.durationCaption": "每次执行",+ "share.visitor.profile.metrics.lastDelivered": "最近交付",+ "share.visitor.profile.metrics.lastDeliveredCaption": "最新成果更新","share.visitor.profile.metrics.tools": "开放工具","share.visitor.profile.metrics.toolsCaption": "项可用","share.visitor.profile.metrics.turns": "每个会话","share.visitor.profile.metrics.turnsCaption": "轮上限",+ "share.visitor.profile.metrics.unknown": "暂无数据","share.visitor.profile.metrics.views": "浏览","share.visitor.profile.metrics.viewsCaption": "次访问","share.visitor.profile.metrics.visitors": "用过的人","share.visitor.profile.metrics.visitorsCaption": "位访客",+ "share.visitor.profile.metrics.works": "累计产物",+ "share.visitor.profile.metrics.worksCaption": "创作者交付","share.visitor.profile.starters.desc": "点一条,它会直接带进输入框。",- "share.visitor.profile.starters.title": "不知道从哪开始?",+ "share.visitor.profile.starters.title": "试试这些","share.visitor.profile.terms.account": "它运行在创建者的账号上,每一次回复都由创建者付费。","share.visitor.profile.terms.accountWorkspace": "它运行在所属工作区内,每一次回复都从工作区预算扣费。","share.visitor.profile.terms.desc": "这几条规则今天只在你撞上时以报错的形式出现,这里把它们提前讲清楚。",@@ -437,6 +478,14 @@"share.visitor.profile.terms.uploadsOff": "附件功能已关闭。","share.visitor.profile.terms.visibilityCreator": "创建者开启了会话查看权限,可以读到这段对话。","share.visitor.profile.terms.visibilityPrivate": "你的对话只有你自己能看到。",+ "share.visitor.profile.works.desc": "由创建者精选,看看这个助手能交付什么。",+ "share.visitor.profile.works.open": "打开成果",+ "share.visitor.profile.works.title": "精选成果",+ "share.visitor.profile.works.type.document": "文档",+ "share.visitor.profile.works.type.external": "外部成果",+ "share.visitor.profile.works.type.file": "文件",+ "share.visitor.profile.works.type.task": "任务",+ "share.visitor.profile.works.untitled": "未命名成果","share.visitor.topBar.home": "回到我的 LobeHub","share.visitor.topics.empty": "还没有会话","share.visitor.topics.new": "新建会话",diff --git a/packages/database/src/models/__tests__/agentShare.test.ts b/packages/database/src/models/__tests__/agentShare.test.tsindex a17196ba01f..3811ed33d69 100644--- a/packages/database/src/models/__tests__/agentShare.test.ts+++ b/packages/database/src/models/__tests__/agentShare.test.ts@@ -335,6 +335,49 @@ describe('AgentShareModel', () => {});describe('owner operations', () => {+ it('persists demo cases independently and retains them through unrelated patches', async () => {+ await agentShareModel.create(agentId);+ const demoCases = [+ { prompt: 'Review this change', description: 'Identify regression risks' },+ ];+ await agentShareModel.updateConfig(agentId, { demoCases });+ await agentShareModel.updateConfig(agentId, { maxTurnsPerTopic: 8 });+ expect((await agentShareModel.getByAgentId(agentId))?.shareConfig.demoCases).toEqual(+ demoCases,+ );+ expect(+ (await AgentShareModel.findBySlugOrId(serverDB, 'shareable-agent'))?.shareConfig.demoCases,+ ).toEqual(demoCases);+ const [agent] = await serverDB+ .select({ openingQuestions: agents.openingQuestions })+ .from(agents)+ .where(eq(agents.id, agentId));+ expect(agent.openingQuestions ?? []).toEqual([]);+ await agentShareModel.updateConfig(agentId, { demoCases: [] });+ expect((await agentShareModel.getByAgentId(agentId))?.shareConfig.demoCases).toEqual([]);+ });++ it('does not let another owner replace profile content', async () => {+ await agentShareModel.create(agentId);+ expect(+ await otherAgentShareModel.updateConfig(agentId, {+ demoCases: [{ prompt: 'Injected', description: '' }],+ }),+ ).toBeNull();+ expect((await agentShareModel.getByAgentId(agentId))?.shareConfig.demoCases).toEqual([]);+ });++ it('rejects unknown selected Works without partially saving the patch', async () => {+ await agentShareModel.create(agentId);+ await expect(+ agentShareModel.updateConfig(agentId, {+ demoCases: [{ prompt: 'Do not save', description: '' }],+ featuredWorkIds: ['missing-work'],+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect((await agentShareModel.getByAgentId(agentId))?.shareConfig.demoCases).toEqual([]);+ });+it('normalizes a legacy null config to conservative defaults', async () => {const [legacyShare] = await serverDB.insert(agentShares).values({ agentId }).returning();@@ -344,6 +387,8 @@ describe('AgentShareModel', () => {expect(ownerShare?.shareConfig).toEqual({allowCreatorViewSessions: false,allowReadMemory: false,+ demoCases: [],+ featuredWorkIds: [],maxFileStorage: 512 * 1024 * 1024,maxTopicsPerVisitor: 5,maxTurnsPerTopic: 20,@@ -375,7 +420,7 @@ describe('AgentShareModel', () => {// The slug seeded from the agent's profile slug at `create` survives a// full config overwrite — it is owner-facing url state, not config.- const expected = { ...config, slug: 'shareable-agent' };+ const expected = { demoCases: [], featuredWorkIds: [], ...config, slug: 'shareable-agent' };expect(updated?.shareConfig).toEqual(expected);expect(readBack?.shareConfig).toEqual(expected);});diff --git a/packages/database/src/models/__tests__/agentShareProfile.test.ts b/packages/database/src/models/__tests__/agentShareProfile.test.tsnew file mode 100644index 00000000000..b20b74e7feb--- /dev/null+++ b/packages/database/src/models/__tests__/agentShareProfile.test.ts@@ -0,0 +1,355 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import {+ agentOperations,+ agents,+ documents,+ topics,+ users,+ works,+ workspaces,+ workVersions,+} from '../../schemas';+import { AgentShareModel } from '../agentShare';+import { AgentShareProfileModel } from '../agentShareProfile';++const db = await getTestDB();+const owner = 'profile-owner';+const agent = 'profile-agent';+const creatorTopic = 'creator-topic';+const visitorTopic = 'visitor-topic';+const model = new AgentShareProfileModel(db, owner);+const shareModel = new AgentShareModel(db, owner);+const deliveredAt = new Date('2026-01-02T00:00:00Z');++const addWork = async (+ id: string,+ overrides: Partial<typeof works.$inferInsert> = {},+ topicId: string | null = creatorTopic,+) => {+ await db.insert(works).values({+ id,+ type: 'external',+ resourceType: 'github_issue',+ userId: owner,+ originAgentId: agent,+ originTopicId: creatorTopic,+ visibility: 'private',+ title: `Title ${id}`,+ description: 'A selected result',+ toolName: 'createIssue',+ toolIdentifier: 'github',+ url: 'https://github.com/example/repo/issues/1',+ ...overrides,+ });+ return addVersion(id, 1, 2, 'operation-1', topicId);+};++const addVersion = async (+ workId: string,+ version: number,+ cumulativeCost: number | null,+ rootOperationId: string | null,+ topicId: string | null = creatorTopic,+) => {+ const [row] = await db+ .insert(workVersions)+ .values({+ workId,+ version,+ cumulativeCost,+ rootOperationId,+ topicId,+ agentId: agent,+ changeType: version === 1 ? 'created' : 'updated',+ toolName: 'createIssue',+ toolIdentifier: 'github',+ createdAt: new Date(deliveredAt.getTime() + version * 1000),+ })+ .returning();+ await db.update(works).set({ currentVersionId: row.id }).where(eq(works.id, workId));+ return row;+};++beforeEach(async () => {+ await db.delete(agentOperations);+ await db.delete(users);+ await db.insert(users).values([{ id: owner }, { id: 'other-owner' }]);+ await db.insert(workspaces).values({+ id: 'profile-workspace',+ name: 'Workspace',+ slug: 'profile-workspace',+ primaryOwnerId: owner,+ });+ await db.insert(agents).values([+ { id: agent, userId: owner, slug: 'profile-agent' },+ { id: 'other-agent', userId: owner },+ { id: 'foreign-agent', userId: 'other-owner' },+ ]);+ await db.insert(topics).values([+ { id: creatorTopic, userId: owner, agentId: agent },+ { id: visitorTopic, userId: owner, agentId: agent, senderId: 'visitor-user' },+ ]);+});++afterEach(async () => {+ await db.delete(agentOperations);+ await db.delete(users);+});++describe('AgentShareProfileModel', () => {+ it('persists ordered selections, exposes only safe fields, and supports withdrawal', async () => {+ await addWork('first');+ await addWork('second');+ await shareModel.create(agent, 'link');+ await shareModel.updateConfig(agent, { featuredWorkIds: ['second', 'first'] });+ const share = await shareModel.getByAgentId(agent);+ const items = await model.listFeaturedWorks(agent, share!.shareConfig.featuredWorkIds!);+ expect(items.map(({ id }) => id)).toEqual(['second', 'first']);+ expect(Object.keys(items[0]).sort()).toEqual(+ [+ 'createdAt',+ 'description',+ 'id',+ 'identifier',+ 'resourceType',+ 'status',+ 'title',+ 'totalCost',+ 'type',+ 'updatedAt',+ 'url',+ ].sort(),+ );+ expect(items[0].totalCost).toBe(2);+ const before = await model.getStats(agent);+ await shareModel.updateConfig(agent, { featuredWorkIds: [] });+ expect(+ await model.listFeaturedWorks(+ agent,+ (await shareModel.getByAgentId(agent))!.shareConfig.featuredWorkIds!,+ ),+ ).toEqual([]);+ expect(await model.getStats(agent)).toEqual(before);+ });++ it('withholds file download URLs while retaining explicitly external links', async () => {+ await addWork('file-download', {+ type: 'file',+ resourceType: 'file',+ url: 'https://example.com/f/private-file',+ });+ await addWork('external-link');+ const items = await model.listFeaturedWorks(agent, ['file-download', 'external-link']);+ expect(items[0].url).toBeNull();+ expect(items[1].url).toBe('https://github.com/example/repo/issues/1');+ });++ it('pages creator candidates and keeps selected Works available outside the page', async () => {+ await addWork('newest');+ await addWork('middle');+ await addWork('oldest');+ await db+ .update(works)+ .set({ updatedAt: new Date('2026-01-03T00:00:00Z') })+ .where(eq(works.id, 'newest'));+ await db+ .update(works)+ .set({ updatedAt: new Date('2026-01-02T00:00:00Z') })+ .where(eq(works.id, 'middle'));+ await db+ .update(works)+ .set({ updatedAt: new Date('2026-01-01T00:00:00Z') })+ .where(eq(works.id, 'oldest'));+ await addWork('visitor', { originTopicId: visitorTopic }, visitorTopic);++ const firstPage = await model.listEligibleWorks(agent, { limit: 1, offset: 0 });+ expect(firstPage.hasMore).toBe(true);+ expect(firstPage.items.map(({ id }) => id)).toEqual(['newest']);++ const secondPageWithSelected = await model.listEligibleWorks(agent, {+ includeWorkIds: ['oldest', 'visitor'],+ limit: 1,+ offset: 1,+ });+ expect(secondPageWithSelected.hasMore).toBe(true);+ expect(secondPageWithSelected.items.map(({ id }) => id)).toEqual(['oldest', 'middle']);++ expect(+ (await new AgentShareProfileModel(db, 'other-owner').listEligibleWorks(agent)).items,+ ).toEqual([]);+ });++ it('rejects visitor, foreign agent/user/workspace, deleted and unknown provenance', async () => {+ await addWork('valid');+ await addWork('visitor', { originTopicId: visitorTopic }, visitorTopic);+ await addWork('foreign-agent-work', { originAgentId: 'other-agent' });+ await addWork('foreign-user-work', { userId: 'other-owner' });+ await addWork('workspace-work', { workspaceId: 'profile-workspace' });+ await addWork('deleted-work', { deletedAt: new Date() });+ await addWork('flagged-work', { isDeleted: true });+ await addWork('live-false', { isDeleted: false });+ await addWork('unknown-origin', { originTopicId: null });+ await addWork('unknown-current', {}, null);+ const invalid = [+ 'visitor',+ 'foreign-agent-work',+ 'foreign-user-work',+ 'workspace-work',+ 'deleted-work',+ 'flagged-work',+ 'unknown-origin',+ 'unknown-current',+ 'missing',+ ];+ for (const id of invalid) {+ await expect(model.validateFeaturedWorks(agent, [id])).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ }+ expect(+ (await model.listFeaturedWorks(agent, ['valid', ...invalid])).map(({ id }) => id),+ ).toEqual(['valid']);+ expect(+ await new AgentShareProfileModel(db, 'other-owner').listFeaturedWorks(agent, ['valid']),+ ).toEqual([]);+ expect((await model.getStats(agent)).workCount).toBe(2);+ await expect(model.validateFeaturedWorks(agent, ['live-false'])).resolves.toBeUndefined();+ });++ it('never republishes a visitor Work after its topic is deleted or after creator edits', async () => {+ await addWork('visitor', { originTopicId: visitorTopic }, visitorTopic);+ await db.delete(topics).where(eq(topics.id, visitorTopic));+ expect(await model.listFeaturedWorks(agent, ['visitor'])).toEqual([]);+ await db+ .insert(topics)+ .values({ id: visitorTopic, userId: owner, agentId: agent, senderId: 'visitor-user' });+ await addWork('mixed');+ await addVersion('mixed', 2, 3, 'visitor-operation', visitorTopic);+ await addVersion('mixed', 3, 4, 'creator-operation');+ expect(await model.listFeaturedWorks(agent, ['mixed'])).toEqual([]);+ });++ it('filters selections again after deletion, workspace moves, or resource removal', async () => {+ await addWork('valid');+ await model.validateFeaturedWorks(agent, ['valid']);+ await db.update(works).set({ deletedAt: new Date() }).where(eq(works.id, 'valid'));+ expect(await model.listFeaturedWorks(agent, ['valid'])).toEqual([]);+ await db.insert(documents).values({+ id: 'document',+ userId: owner,+ fileType: 'custom',+ sourceType: 'agent',+ source: 'test',+ totalCharCount: 0,+ totalLineCount: 0,+ });+ await addWork('document-work', {+ type: 'document',+ resourceType: 'document',+ resourceId: 'document',+ });+ await model.validateFeaturedWorks(agent, ['document-work']);+ await db.delete(documents).where(eq(documents.id, 'document'));+ expect(await model.listFeaturedWorks(agent, ['document-work'])).toEqual([]);+ await addWork('move-work');+ await db.update(agents).set({ workspaceId: 'profile-workspace' }).where(eq(agents.id, agent));+ expect(await model.listFeaturedWorks(agent, ['move-work'])).toEqual([]);+ });++ it('deduplicates operation snapshots and averages measured costs across all creator Works', async () => {+ await addWork('first');+ await addVersion('first', 2, 5, 'operation-1');+ const latest = await addVersion('first', 3, 3, 'operation-2');+ await addWork('second');+ await addWork('unmeasured');+ await db+ .update(workVersions)+ .set({ cumulativeCost: null })+ .where(eq(workVersions.workId, 'unmeasured'));+ await addWork('visitor', { originTopicId: visitorTopic }, visitorTopic);+ const stats = await model.getStats(agent);+ expect(stats.workCount).toBe(3);+ expect(stats.averageWorkCost).toBe(5);+ expect(stats.lastDeliveredAt).toEqual(latest.createdAt);+ const items = await model.listFeaturedWorks(agent, ['first', 'second', 'unmeasured']);+ expect(items.map(({ totalCost }) => totalCost)).toEqual([8, 2, null]);+ await shareModel.create(agent);+ await shareModel.updateConfig(agent, { featuredWorkIds: ['second'] });+ expect(await model.getStats(agent)).toEqual(stats);+ });++ it('keeps zero measured cost and handles versions without an operation id independently', async () => {+ await addWork('first');+ await db+ .update(workVersions)+ .set({ cumulativeCost: 0 })+ .where(eq(workVersions.workId, 'first'));+ expect((await model.getStats(agent)).averageWorkCost).toBe(0);+ await addVersion('first', 2, 2, null);+ await addVersion('first', 3, 3, null);+ expect((await model.getStats(agent)).averageWorkCost).toBe(5);+ });++ it('averages valid finished operations and excludes in-flight, invalid and foreign samples', async () => {+ const startedAt = new Date('2026-01-01T00:00:00Z');+ const operation = (+ id: string,+ seconds: number,+ overrides: Partial<typeof agentOperations.$inferInsert> = {},+ ) => ({+ id,+ userId: owner,+ agentId: agent,+ topicId: creatorTopic,+ status: 'done' as const,+ startedAt,+ completedAt: new Date(startedAt.getTime() + seconds * 1000),+ ...overrides,+ });+ await db+ .insert(agentOperations)+ .values([+ operation('first', 10),+ operation('second', 30, { status: 'error' }),+ operation('running', 500, { status: 'running' }),+ operation('missing', 500, { startedAt: null }),+ operation('negative', -10),+ operation('visitor', 500, { topicId: visitorTopic }),+ operation('other-agent', 500, { agentId: 'other-agent' }),+ operation('other-owner', 500, { userId: 'other-owner' }),+ operation('workspace', 500, { workspaceId: 'profile-workspace' }),+ ]);+ expect((await model.getStats(agent)).averageOperationDurationSeconds).toBe(20);+ expect(+ (await new AgentShareProfileModel(db, 'other-owner').getStats(agent))+ .averageOperationDurationSeconds,+ ).toBeNull();+ });++ it('returns null for absent measurements and removes unsafe URLs', async () => {+ expect(await model.getStats(agent)).toEqual({+ workCount: 0,+ lastDeliveredAt: null,+ averageWorkCost: null,+ averageOperationDurationSeconds: null,+ });+ await addWork('unsafe-url', { url: 'javascript:alert(1)' });+ await db+ .update(workVersions)+ .set({ cumulativeCost: null })+ .where(eq(workVersions.workId, 'unsafe-url'));+ expect((await model.getStats(agent)).averageWorkCost).toBeNull();+ expect((await model.listFeaturedWorks(agent, ['unsafe-url']))[0].url).toBeNull();+ });++ it('stops exposing profile data for a trashed agent', async () => {+ await addWork('first');+ await db.update(agents).set({ isDeleted: true }).where(eq(agents.id, agent));+ expect(await model.listFeaturedWorks(agent, ['first'])).toEqual([]);+ expect((await model.getStats(agent)).workCount).toBe(0);+ });+});diff --git a/packages/database/src/models/agentShare.ts b/packages/database/src/models/agentShare.tsindex ee2c341480d..7157320f17d 100644--- a/packages/database/src/models/agentShare.ts+++ b/packages/database/src/models/agentShare.ts@@ -20,10 +20,13 @@ import { agents, agentShares, users } from '../schemas';import type { LobeChatDatabase } from '../type';import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '../utils/inboxAgent';import { isUuid } from '../utils/uuid';+import { AgentShareProfileModel } from './agentShareProfile';const DEFAULT_AGENT_SHARE_CONFIG = {allowCreatorViewSessions: false,allowReadMemory: false,+ demoCases: [],+ featuredWorkIds: [],maxFileStorage: AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,maxTopicsPerVisitor: AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,maxTurnsPerTopic: AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,@@ -40,6 +43,8 @@ const normalizeAgentShareConfig = (allowCreatorViewSessions:config?.allowCreatorViewSessions ?? DEFAULT_AGENT_SHARE_CONFIG.allowCreatorViewSessions,allowReadMemory: config?.allowReadMemory ?? DEFAULT_AGENT_SHARE_CONFIG.allowReadMemory,+ demoCases: config?.demoCases ?? [],+ featuredWorkIds: config?.featuredWorkIds ?? [],maxFileStorage: config?.maxFileStorage ?? DEFAULT_AGENT_SHARE_CONFIG.maxFileStorage,maxTopicsPerVisitor:config?.maxTopicsPerVisitor ?? DEFAULT_AGENT_SHARE_CONFIG.maxTopicsPerVisitor,@@ -375,6 +380,12 @@ export class AgentShareModel {): Promise<NormalizedAgentShareItem | null> =>this.withScopedAgentLock(agentId, async (tx) => {const { slug: _slug, ...patch } = config as AgentShareConfigPatch & { slug?: unknown };+ if (patch.featuredWorkIds !== undefined) {+ await new AgentShareProfileModel(tx, this.userId).validateFeaturedWorks(+ agentId,+ patch.featuredWorkIds,+ );+ }const setEntries = Object.entries(patch).filter(([, v]) => v !== undefined);let configExpr = sql`COALESCE(${agentShares.shareConfig}, '{}'::jsonb)`;diff --git a/packages/database/src/models/agentShareProfile.ts b/packages/database/src/models/agentShareProfile.tsnew file mode 100644index 00000000000..2ca5c3e0802--- /dev/null+++ b/packages/database/src/models/agentShareProfile.ts@@ -0,0 +1,305 @@+import type { SharedAgentDeliveryStats, SharedAgentWork } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import {+ and,+ avg,+ count,+ desc,+ eq,+ exists,+ inArray,+ isNotNull,+ isNull,+ max,+ ne,+ notExists,+ or,+ sql,+ sum,+} from 'drizzle-orm';+import { alias } from 'drizzle-orm/pg-core';++import { agentOperations, agents, documents, tasks, topics, works, workVersions } from '../schemas';+import type { LobeChatDatabase } from '../type';+import { getTotalCostByWorkIds } from './work/cost';+import { sanitizeExternalUrl } from './work/toolResultParsing';++const originTopics = alias(topics, 'share_work_origin_topics');+const currentTopics = alias(topics, 'share_work_current_topics');+const historyVersions = alias(workVersions, 'share_work_history_versions');+const historyTopics = alias(topics, 'share_work_history_topics');++/** Owner-scoped source for explicitly curated share profiles, not a general resource grant. */+export class AgentShareProfileModel {+ constructor(+ private db: LobeChatDatabase,+ private userId: string,+ ) {}++ /**+ * Visitor runs use the creator's userId too. Require surviving creator-topic+ * provenance at both ends; a deleted topic must never turn a visitor Work+ * into an eligible creator Work through ON DELETE SET NULL.+ */+ private eligibleWorks = (agentId: string, ids?: string[]) =>+ this.db+ .select({+ createdAt: works.createdAt,+ deliveredAt: sql<Date>`${workVersions.createdAt}`+ .mapWith(workVersions.createdAt)+ .as('delivered_at'),+ description: works.description,+ id: works.id,+ identifier: works.identifier,+ resourceType: works.resourceType,+ status: works.status,+ title: works.title,+ type: works.type,+ updatedAt: works.updatedAt,+ url: works.url,+ })+ .from(works)+ .innerJoin(agents, eq(agents.id, works.originAgentId))+ .innerJoin(originTopics, eq(originTopics.id, works.originTopicId))+ .innerJoin(+ workVersions,+ and(eq(workVersions.id, works.currentVersionId), eq(workVersions.workId, works.id)),+ )+ .innerJoin(currentTopics, eq(currentTopics.id, workVersions.topicId))+ .where(+ and(+ eq(works.userId, this.userId),+ eq(works.originAgentId, agentId),+ eq(agents.userId, this.userId),+ isNull(agents.workspaceId),+ sql`${agents.isDeleted} is not true`,+ isNull(works.workspaceId),+ isNull(works.deletedAt),+ sql`${works.isDeleted} is not true`,+ eq(originTopics.userId, this.userId),+ isNull(originTopics.workspaceId),+ isNull(originTopics.senderId),+ isNull(originTopics.deletedAt),+ sql`${originTopics.isDeleted} is not true`,+ eq(currentTopics.userId, this.userId),+ isNull(currentTopics.workspaceId),+ isNull(currentTopics.senderId),+ isNull(currentTopics.deletedAt),+ sql`${currentTopics.isDeleted} is not true`,+ /** Later creator edits can inherit text from a visitor version; reject mixed provenance. */+ notExists(+ this.db+ .select({ id: historyVersions.id })+ .from(historyVersions)+ .leftJoin(historyTopics, eq(historyTopics.id, historyVersions.topicId))+ .where(+ and(+ eq(historyVersions.workId, works.id),+ or(+ isNull(historyTopics.id),+ isNotNull(historyTopics.senderId),+ ne(historyTopics.userId, this.userId),+ isNotNull(historyTopics.workspaceId),+ ),+ ),+ ),+ ),+ ids ? inArray(works.id, ids) : undefined,+ or(+ inArray(works.type, ['external', 'file']),+ and(+ eq(works.type, 'document'),+ exists(+ this.db+ .select({ id: documents.id })+ .from(documents)+ .where(+ and(+ eq(documents.id, works.resourceId),+ eq(documents.userId, this.userId),+ isNull(documents.workspaceId),+ isNull(documents.deletedAt),+ sql`${documents.isDeleted} is not true`,+ ),+ ),+ ),+ ),+ and(+ eq(works.type, 'task'),+ exists(+ this.db+ .select({ id: tasks.id })+ .from(tasks)+ .where(+ and(+ eq(tasks.id, works.resourceId),+ eq(tasks.createdByUserId, this.userId),+ isNull(tasks.workspaceId),+ isNull(tasks.deletedAt),+ sql`${tasks.isDeleted} is not true`,+ ),+ ),+ ),+ ),+ ),+ ),+ );++ validateFeaturedWorks = async (agentId: string, workIds: string[]) => {+ if (workIds.length === 0) return;+ const rows = await this.eligibleWorks(agentId, workIds);+ if (new Set(workIds).size !== workIds.length || rows.length !== workIds.length) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Only available creator Works from this agent can be featured',+ });+ }+ };++ listFeaturedWorks = async (agentId: string, workIds: string[]): Promise<SharedAgentWork[]> => {+ if (workIds.length === 0) return [];+ const rows = await this.eligibleWorks(agentId, workIds);+ const costs = await getTotalCostByWorkIds(+ { db: this.db, userId: this.userId },+ rows.map(({ id }) => id),+ );+ const byId = new Map(+ rows.map(({ deliveredAt: _deliveredAt, ...work }) => [+ work.id,+ {+ ...work,+ totalCost: costs.get(work.id) ?? null,+ /** File URLs can be bearer download links; featuring a Work is not a download grant. */+ url: work.type === 'external' ? (sanitizeExternalUrl(work.url) ?? null) : null,+ },+ ]),+ );+ return workIds.flatMap((id) => {+ const work = byId.get(id);+ return work ? [work] : [];+ });+ };++ /**+ * Candidate Works for the creator's share profile editor. This deliberately+ * uses the same provenance query as featured reads and validation, so the+ * settings surface cannot accidentally offer visitor or mixed-history Works.+ *+ * Selected ids are returned alongside the current page. A creator can keep+ * an older Work selected after it falls outside the newest page, and can+ * still see and withdraw it without making the editor treat the first page+ * as the complete candidate pool.+ */+ listEligibleWorks = async (+ agentId: string,+ {+ includeWorkIds = [],+ limit = 30,+ offset = 0,+ }: { includeWorkIds?: string[]; limit?: number; offset?: number } = {},+ ): Promise<{ hasMore: boolean; items: SharedAgentWork[] }> => {+ const rows = await this.eligibleWorks(agentId)+ .orderBy(desc(works.updatedAt), desc(works.id))+ .limit(limit + 1)+ .offset(offset);+ const hasMore = rows.length > limit;+ const pageRows = hasMore ? rows.slice(0, limit) : rows;+ const selectedRows =+ includeWorkIds.length > 0 ? await this.eligibleWorks(agentId, includeWorkIds) : [];+ const allRows = [...selectedRows, ...pageRows];+ const costs = await getTotalCostByWorkIds(+ { db: this.db, userId: this.userId },+ allRows.map(({ id }) => id),+ );+ const byId = new Map(+ allRows.map(({ deliveredAt: _deliveredAt, ...work }) => [+ work.id,+ {+ ...work,+ totalCost: costs.get(work.id) ?? null,+ url: sanitizeExternalUrl(work.url) ?? null,+ },+ ]),+ );+ const orderedIds = [...includeWorkIds, ...pageRows.map(({ id }) => id)];++ return {+ hasMore,+ items: [...new Set(orderedIds)].flatMap((id) => {+ const work = byId.get(id);+ return work ? [work] : [];+ }),+ };+ };++ getStats = async (agentId: string): Promise<SharedAgentDeliveryStats> => {+ const eligible = this.eligibleWorks(agentId).as('share_eligible_works');+ /** Same cost rule as Work gallery: MAX snapshot per Work/operation, then SUM per Work. */+ const operationKey = sql<string>`coalesce(${workVersions.rootOperationId}, ${workVersions.id}::text)`;+ const operationCosts = this.db+ .select({+ cost: max(workVersions.cumulativeCost).as('operation_cost'),+ workId: workVersions.workId,+ })+ .from(workVersions)+ .innerJoin(eligible, eq(eligible.id, workVersions.workId))+ .groupBy(workVersions.workId, operationKey)+ .as('share_work_operation_costs');+ const workCosts = this.db+ .select({+ cost: sum(operationCosts.cost).as('work_cost'),+ workId: operationCosts.workId,+ })+ .from(operationCosts)+ .groupBy(operationCosts.workId)+ .as('share_work_costs');++ const [workStats, operationStats] = await Promise.all([+ this.db+ .select({+ averageWorkCost: avg(workCosts.cost),+ lastDeliveredAt: sql<Date | null>`max(${eligible.deliveredAt})`.mapWith(+ workVersions.createdAt,+ ),+ workCount: count(),+ })+ .from(eligible)+ .leftJoin(workCosts, eq(workCosts.workId, eligible.id)),+ this.db+ .select({+ duration: sql<+ number | null+ >`avg(extract(epoch from (${agentOperations.completedAt} - ${agentOperations.startedAt})))`.mapWith(+ Number,+ ),+ })+ .from(agentOperations)+ .innerJoin(agents, eq(agents.id, agentOperations.agentId))+ .innerJoin(topics, eq(topics.id, agentOperations.topicId))+ .where(+ and(+ eq(agentOperations.userId, this.userId),+ eq(agentOperations.agentId, agentId),+ eq(agents.userId, this.userId),+ isNull(agents.workspaceId),+ sql`${agents.isDeleted} is not true`,+ isNull(agentOperations.workspaceId),+ eq(topics.userId, this.userId),+ isNull(topics.workspaceId),+ isNull(topics.senderId),+ isNull(topics.deletedAt),+ sql`${topics.isDeleted} is not true`,+ inArray(agentOperations.status, ['done', 'error', 'interrupted', 'abandoned']),+ sql`${agentOperations.completedAt} >= ${agentOperations.startedAt}`,+ ),+ ),+ ]);+ return {+ averageOperationDurationSeconds: operationStats[0]?.duration ?? null,+ averageWorkCost:+ workStats[0]?.averageWorkCost == null ? null : Number(workStats[0].averageWorkCost),+ lastDeliveredAt: workStats[0]?.lastDeliveredAt ?? null,+ workCount: workStats[0]?.workCount ?? 0,+ };+ };+}diff --git a/packages/database/src/schemas/agentShare.ts b/packages/database/src/schemas/agentShare.tsindex 782cda95a46..8fea8d70200 100644--- a/packages/database/src/schemas/agentShare.ts+++ b/packages/database/src/schemas/agentShare.ts@@ -1,4 +1,4 @@-import type { AgentShareToolGrant } from '@lobechat/types';+import type { AgentShareDemoCase, AgentShareToolGrant } from '@lobechat/types';import { index, integer, jsonb, pgTable, text, uniqueIndex, uuid } from 'drizzle-orm/pg-core';import { timestamps } from './_helpers';@@ -16,6 +16,10 @@ export interface AgentShareConfig {* a shared conversation. Defaults to `false`.*/allowReadMemory?: boolean;+ /** Visitor trial scenarios, maintained independently of agents.openingQuestions. */+ demoCases?: AgentShareDemoCase[];+ /** Ordered, explicitly selected creator Works for this share's public profile. */+ featuredWorkIds?: string[];/*** Total bytes this share's visitor uploads may occupy in the Agent's owning* scope (settled files plus in-flight reservations). Mandatory likediff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex 3c83384aa97..cfad828f861 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -468,6 +468,7 @@ export default {'Off by default: your model and provider choice stays hidden.','share.settings.permissions.title': 'Permissions','share.settings.tabs.access': 'Access',+ 'share.settings.tabs.profile': 'Public profile','share.settings.tabs.stats': 'Stats','share.settings.title': 'Share Agent','share.settings.usage.conversations': 'Conversations',@@ -477,6 +478,7 @@ export default {'share.settings.usage.fileStorageOff': '{{used}} · attachments off','share.settings.usage.loadFailed': 'Usage could not be loaded','share.settings.usage.monthlySpend': 'This month’s spend',+ 'share.settings.usage.spendOfLimit': '${{spend}} of ${{limit}}','share.settings.usage.spendOfLimitCredits': '{{spend}} of {{limit}} credits','share.settings.usage.title': 'Usage','share.settings.usage.views': 'Visits',@@ -553,7 +555,7 @@ export default {'share.visitor.profile.metrics.visitors': 'People who used it','share.visitor.profile.metrics.visitorsCaption': 'visitors','share.visitor.profile.starters.desc': 'Pick one and it goes straight into the composer.',- 'share.visitor.profile.starters.title': 'Not sure where to start?',+ 'share.visitor.profile.starters.title': 'Try these','share.visitor.profile.terms.account':'It runs on the creator’s account, and every reply is paid for by them.','share.visitor.profile.terms.accountWorkspace':@@ -669,4 +671,59 @@ export default {'transferRequest.untitledResource': 'Untitled','transferRequest.withdraw': 'Withdraw','transferRequest.withdrawnToast': 'Transfer request withdrawn.',+ 'share.visitor.profile.metrics.unknown': 'No data yet',+ 'share.visitor.profile.metrics.lastDelivered': 'Latest delivery',+ 'share.visitor.profile.metrics.lastDeliveredCaption': 'most recent update',+ 'share.visitor.profile.metrics.works': 'Total works',+ 'share.visitor.profile.metrics.worksCaption': 'creator deliveries',+ 'share.visitor.profile.metrics.duration': 'Average duration',+ 'share.visitor.profile.metrics.durationCaption': 'per operation',+ 'share.visitor.profile.metrics.cost': 'Average cost',+ 'share.visitor.profile.metrics.costCaption': 'per work · paid by the creator',+ 'share.visitor.profile.works.title': 'Featured works',+ 'share.visitor.profile.works.desc': 'Selected by the creator. See what this agent can deliver.',+ 'share.visitor.profile.works.untitled': 'Untitled work',+ 'share.visitor.profile.works.open': 'Open work',+ 'share.visitor.profile.works.type.document': 'Document',+ 'share.visitor.profile.works.type.task': 'Task',+ 'share.visitor.profile.works.type.file': 'File',+ 'share.visitor.profile.works.type.external': 'Linked work',+ 'share.settings.profile.title': 'Public profile',+ 'share.settings.profile.desc':+ 'Choose what visitors see before starting a conversation. Changes are published when you save.',+ 'share.settings.profile.save': 'Save profile',+ 'share.settings.profile.saved': 'Profile saved',+ 'share.settings.profile.saveError': 'Could not save. Your draft is preserved. Try again.',+ 'share.settings.profile.invalid':+ 'Each example needs a task prompt. Keep at most 20 examples and 100 featured works.',+ 'share.settings.profile.demoCases.item': 'Example {{number}}',+ 'share.settings.profile.demoCases.promptLabel': 'Task prompt (required)',+ 'share.settings.profile.demoCases.promptHint':+ 'Shown as the example title. Clicking it fills the visitor’s chat input without sending.',+ 'share.settings.profile.demoCases.descriptionLabel': 'Description (optional)',+ 'share.settings.profile.demoCases.descriptionHint':+ 'Shown below the task prompt to explain what this agent can help with. This text is not added to the chat.',+ 'share.settings.profile.demoCases.title': 'Example tasks',+ 'share.settings.profile.demoCases.desc':+ 'Write examples for visitors to try. These are separate from the agent’s opening questions.',+ 'share.settings.profile.demoCases.add': 'Add example',+ 'share.settings.profile.demoCases.empty': 'No examples published yet.',+ 'share.settings.profile.demoCases.prompt': 'Task prompt',+ 'share.settings.profile.demoCases.promptPlaceholder': 'What would you ask this agent to do?',+ 'share.settings.profile.demoCases.description': 'Description',+ 'share.settings.profile.demoCases.descriptionPlaceholder':+ 'Explain the expected result (optional)',+ 'share.settings.profile.demoCases.remove': 'Remove example',+ 'share.settings.profile.featuredWorks.title': 'Featured works',+ 'share.settings.profile.featuredWorks.desc':+ 'Choose this agent’s works to showcase. Visitor works are never included.',+ 'share.settings.profile.featuredWorks.selected': 'Selected: {{count}} / 100',+ 'share.settings.profile.featuredWorks.select': 'Feature',+ 'share.settings.profile.featuredWorks.withdraw': 'Remove',+ 'share.settings.profile.featuredWorks.empty':+ 'No eligible works yet. Create a work with this agent first.',+ 'share.settings.profile.featuredWorks.loadFailed': 'Could not load works. Try again.',+ 'share.settings.profile.featuredWorks.reload': 'Retry',+ 'share.settings.profile.featuredWorks.loadMore': 'Load more works',+ 'share.settings.profile.featuredWorks.unavailable': 'Unavailable work',} as const;diff --git a/packages/types/src/agent/share.ts b/packages/types/src/agent/share.tsindex dc0ae6d4446..0fc08698699 100644--- a/packages/types/src/agent/share.ts+++ b/packages/types/src/agent/share.ts@@ -1,4 +1,37 @@import type { ShareVisibility } from '../topic';+import type { WorkItem } from '../work';++/** A creator-authored visitor task, independent of the agent's opening questions. */+export interface AgentShareDemoCase {+ description: string;+ /** Displayed as the example task and carried into the visitor's conversation draft. */+ prompt: string;+}++/** Explicit public projection: no conversation, message, owner, or tool provenance. */+export type SharedAgentWork = Pick<+ WorkItem,+ | 'createdAt'+ | 'description'+ | 'id'+ | 'identifier'+ | 'resourceType'+ | 'status'+ | 'title'+ | 'type'+ | 'updatedAt'+ | 'url'+> & { totalCost: number | null };++/** Creator-side delivery aggregates; selection for the showcase does not change the sample. */+export interface SharedAgentDeliveryStats {+ /** Mean elapsed seconds across finished operations with valid timestamps. */+ averageOperationDurationSeconds: number | null;+ /** Mean measured Work cost; cumulative versions from one operation are not added twice. */+ averageWorkCost: number | null;+ lastDeliveredAt: Date | null;+ workCount: number;+}/*** The share's own rules, restated for the visitor BEFORE they invest in a@@ -24,7 +57,7 @@ export interface SharedAgentTerms {* Aggregate reach of the share. `views` is a raw page-view counter (not* deduplicated); `visitors` and `conversations` come from the share's topics.*/-export interface SharedAgentStats {+export interface SharedAgentStats extends SharedAgentDeliveryStats {conversations: number;views: number;visitors: number;@@ -64,6 +97,8 @@ export interface SharedAgentData {avatar: string | null;name: string | null;};+ demoCases: AgentShareDemoCase[];+ featuredWorks: SharedAgentWork[];/*** True when the requesting user (`ctx.userId`) is the creator of the* shared agent — lets the client render owner-only affordances (e.g. andiff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 42e4539cb0c..c785d52020b 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -1240,6 +1240,15 @@ export const shareKeys = {'share:agentShareStats',agentId,]),+ agentShareEligibleWorks: def(+ 'share:agentShareEligibleWorks',+ (agentId: string, offset: number, includeWorkIds: readonly string[]) => [+ 'share:agentShareEligibleWorks',+ agentId,+ offset,+ includeWorkIds,+ ],+ ),agentShareStatus: def('share:agentShareStatus', (agentId: string) => ['share:agentShareStatus',agentId,diff --git a/src/services/agentShare.ts b/src/services/agentShare.tsindex 1f18162a691..97960495b23 100644--- a/src/services/agentShare.ts+++ b/src/services/agentShare.ts@@ -27,6 +27,13 @@ class AgentShareService {return lambdaClient.agentShare.getWorkspaceShareAudit.query(input);}+ async listEligibleWorks(+ agentId: string,+ params?: { includeWorkIds?: string[]; limit?: number; offset?: number },+ ) {+ return lambdaClient.agentShare.listEligibleWorks.query({ agentId, ...params });+ }+/** Resolve a share's visitor-facing metadata, by its custom slug or its raw share id. */async getSharedAgent(slugOrId: string) {// The visitor page renders its own login prompt on UNAUTHORIZED; opt out of