🤯 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(channel): open shared Agents with share-page guardrails (#23353)
YuTengjing667d1ea96c35
diff --git a/.agents/skills/agent-work/SKILL.md b/.agents/skills/agent-work/SKILL.mdindex b32cc36ee1f..d9194f58b4e 100644--- a/.agents/skills/agent-work/SKILL.md+++ b/.agents/skills/agent-work/SKILL.md@@ -31,7 +31,7 @@ A share visitor's run executes as the creator, so owner scope alone cannot separ- `workOwnership` applies the scope on every path, so a new query built on it inherits the fence. Do not query `works` without it.- Any registration path reachable from a visitor run (skill results, completion scans, anchor stamping) must build its `WorkModel` with the run's scope via `resolveRunWorkAccessScope`. A visitor run without a topic yields `null`: skip registration (fail closed) rather than registering unscoped into the creator's lists.- The resource unique indexes include the visitor topic id, so the creator and each visitor topic keep separate rows for the same external resource.-- Visitor read payloads drop the creator's `userId` / `workspaceId` and gate spend on `showModelInfo` (`toVisitorMessage`).+- Visitor read payloads always drop the creator's `userId` / `workspaceId` and the spend snapshot (`toVisitorMessage`, `sanitizeVisitorWorks`).## Orphaned Works (backing resource deleted)diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.tsindex fbe2c2d6c87..d94def2ca7b 100644--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts@@ -98,7 +98,7 @@ export class AgentRuntimeCoordinator {data: {acceptsMemberRuntimeEnd?: boolean;agentConfig?: any;- visitorRedaction?: { showErrorDetails?: boolean; showModelInfo?: boolean };+ visitorRedaction?: { showErrorDetails?: boolean };mirrorToOperationId?: string;modelRuntimeConfig?: any;streamOwnerUserId?: string;diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.tsindex 591686fbf7d..ac7f06e3668 100644--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts@@ -210,7 +210,7 @@ export interface AgentOperationMetadata {* can still apply the OWNER-configured policy instead of falling back to the* fail-closed full strip.*/- visitorRedaction?: { showErrorDetails?: boolean; showModelInfo?: boolean };+ visitorRedaction?: { showErrorDetails?: boolean };/*** Workspace the operation runs in (null/undefined = personal). Persisted so* queue workers (e.g. QStash `runStep`) can reconstruct a workspace-scoped@@ -564,7 +564,7 @@ export class AgentStateManager {data: {acceptsMemberRuntimeEnd?: boolean;agentConfig?: any;- visitorRedaction?: { showErrorDetails?: boolean; showModelInfo?: boolean };+ visitorRedaction?: { showErrorDetails?: boolean };mirrorToOperationId?: string;modelRuntimeConfig?: any;streamOwnerUserId?: string;diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.tsindex 77eb9c41d45..f6ee0468df8 100644--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts@@ -178,7 +178,7 @@ export class GatewayStreamNotifier implements IStreamEventManager {* Mirrors `mirrorTargets`'s two population paths:* - fast path: set at `publishAgentRuntimeInit` / `publishAgentRuntimeEnd`* from the state's `metadata.agentShareVisitor`, so the share's real- * `showModelInfo` / `showErrorDetails` config is honored.+ * `showErrorDetails` config is honored.* - queue path: lazily resolved from persisted op metadata via* `resolvePersistedShareVisitor`, which can only tell share-or-not — it* therefore falls back to {@link FULL_STRIP_REDACTION}.diff --git a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.tsindex a446a48d573..21fccdcb41c 100644--- a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts+++ b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts@@ -114,7 +114,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {data: {acceptsMemberRuntimeEnd?: boolean;agentConfig?: any;- visitorRedaction?: { showErrorDetails?: boolean; showModelInfo?: boolean };+ visitorRedaction?: { showErrorDetails?: boolean };mirrorToOperationId?: string;modelRuntimeConfig?: any;streamOwnerUserId?: string;diff --git a/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts b/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.tsindex da658180ad7..a5ce0b22e4d 100644--- a/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts+++ b/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts@@ -11,7 +11,7 @@ import { stripFinalStateInEventData } from './StreamEventManager';/*** Per-operation redaction policy for a shared-agent visitor run, derived from- * the share's `AgentShareConfig` (`showModelInfo` / `showErrorDetails`) and+ * the share's `AgentShareConfig` (`showErrorDetails`) and* carried on `state.principal.actor.shareVisitor`.** `null` is the explicit "not a share run — push verbatim" marker, so a@@ -57,10 +57,10 @@ export const isShareVisitorInit = (initialState: any): boolean =>*/export const resolveRedactionFromState = (state: any): GatewayVisitorRedaction => {const share = state?.principal?.actor?.shareVisitor as- { showErrorDetails?: boolean; showModelInfo?: boolean; visitorUserId?: string } | undefined;+ { showErrorDetails?: boolean; visitorUserId?: string } | undefined;if (share?.visitorUserId) {- return { showErrorDetails: share.showErrorDetails, showModelInfo: share.showModelInfo };+ return { showErrorDetails: share.showErrorDetails };}if (!isShareVisitorInit(state)) return null;@@ -170,8 +170,7 @@ const sanitizeErrorEventDataForVisitor = (* `{ body, error, errorType }` shape with no `finalState`/`uiMessages` key* for the other checks to even look at. Skipped when the share opted into* `showErrorDetails`.- * 3. Unless the share opted into `showModelInfo`,- * {@link redactCreatorPrivateBlob} runs over the WHOLE remaining payload.+ * 3. {@link redactCreatorPrivateBlob} runs over the WHOLE remaining payload.* Every other event type for a share run — `stream_start` (`{ model,* provider }`), `tool_end` (a tool's own free-form `result.state` blob, e.g.* `{ model, provider, usage }`), and `step_complete`'s `subagent_progress`@@ -211,9 +210,7 @@ export const sanitizeGatewayEventData = (if (eventType === 'error') return sanitizeErrorEventDataForVisitor(withoutFinalState, redaction);- const redacted = redaction.showModelInfo- ? withoutFinalState- : redactCreatorPrivateBlob(withoutFinalState);+ const redacted = redactCreatorPrivateBlob(withoutFinalState);if (!('uiMessages' in withoutFinalState)) return redacted;diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.tsindex bf2aae68a2e..eaf87016b0f 100644--- a/apps/server/src/modules/AgentRuntime/types.ts+++ b/apps/server/src/modules/AgentRuntime/types.ts@@ -53,7 +53,7 @@ export interface IAgentStateManager {/** See {@link AgentOperationMetadata.acceptsMemberRuntimeEnd}. */acceptsMemberRuntimeEnd?: boolean;agentConfig?: any;- visitorRedaction?: { showErrorDetails?: boolean; showModelInfo?: boolean };+ visitorRedaction?: { showErrorDetails?: boolean };mirrorToOperationId?: string;modelRuntimeConfig?: any;/**diff --git a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts b/apps/server/src/routers/lambda/__tests__/agentShare.test.tsindex a66cebe3a94..a9b340b2818 100644--- a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agentShare.test.ts@@ -161,7 +161,7 @@ describe('share profile configuration', () => {const share = {agentId: 'agent-1',id: 'share-1',- shareConfig: { maxTopicsPerVisitor: 5, maxTurnsPerTopic: 20 },+ shareConfig: { maxMessagesPerVisitor: 100 },visibility: 'private',};@@ -329,7 +329,7 @@ describe('agentShareRouter', () => {it('forwards an atomic share configuration patch', async () => {const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));- const config = { maxTopicsPerVisitor: 10 };+ const config = { maxMessagesPerVisitor: 10 };await caller.updateShareConfig({ agentId: 'agent-1', config });@@ -340,19 +340,19 @@ describe('agentShareRouter', () => {expect(agentShareConfigPatchSchema.safeParse({}).success).toBe(false);});- it('requires positive integer topic and turn limits', async () => {+ it('requires a positive integer message limit', async () => {const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));await expect(caller.updateShareConfig({agentId: 'agent-1',- config: { maxTopicsPerVisitor: 0 },+ config: { maxMessagesPerVisitor: 0 },}),).rejects.toMatchObject({ code: 'BAD_REQUEST' });await expect(caller.updateShareConfig({agentId: 'agent-1',- config: { maxTurnsPerTopic: 1.5 },+ config: { maxMessagesPerVisitor: 1.5 },}),).rejects.toMatchObject({ code: 'BAD_REQUEST' });expect(mockUpdateConfig).not.toHaveBeenCalled();@@ -441,27 +441,6 @@ describe('agentShareRouter', () => {});});- it('caps maxTopicsPerVisitor at the visitor topic list limit', async () => {- // The visitor topic list (`TopicModel.queryBySender`) is not paginated- // and is bounded by `AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT` (200), so a- // cap above it would let visitors create topics they can never reopen.- const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));-- await expect(- caller.updateShareConfig({- agentId: 'agent-1',- config: { maxTopicsPerVisitor: 201 },- }),- ).rejects.toMatchObject({ code: 'BAD_REQUEST' });- expect(mockUpdateConfig).not.toHaveBeenCalled();-- await caller.updateShareConfig({- agentId: 'agent-1',- config: { maxTopicsPerVisitor: 200 },- });- expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', { maxTopicsPerVisitor: 200 });- });-it('accepts a toolset-level grant and a per-API scoped grant in toolGrants', async () => {const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));const config = {@@ -527,13 +506,13 @@ describe('agentShareRouter', () => {expect(agentShareConfigSchema.safeParse({filePermissionConfig: { agentFiles: 'read' },- maxTopicsPerVisitor: 5,+ maxMessagesPerVisitor: 5,}).success,).toBe(false);expect(agentShareConfigSchema.safeParse({guestEnabled: true,- maxTopicsPerVisitor: 5,+ maxMessagesPerVisitor: 5,}).success,).toBe(false);});@@ -601,7 +580,7 @@ describe('agentShareRouter', () => {await expect(caller.updateShareConfig({agentId: 'agent-1',- config: { maxTopicsPerVisitor: 5 },+ config: { maxMessagesPerVisitor: 5 },}),).rejects.toMatchObject({ code: 'NOT_FOUND' });await expect(@@ -654,7 +633,7 @@ describe('agentShareRouter', () => {await caller.updateVisibility({ agentId: 'agent-1', visibility: 'private' });await caller.disableShare({ agentId: 'agent-1' });await caller.getShareStatus({ agentId: 'agent-1' });- await caller.updateShareConfig({ agentId: 'agent-1', config: { maxTurnsPerTopic: 3 } });+ await caller.updateShareConfig({ agentId: 'agent-1', config: { maxMessagesPerVisitor: 3 } });expect(mockUpdateVisibility).toHaveBeenCalledWith('agent-1', 'private');expect(mockUpdateVisibility).toHaveBeenCalledTimes(2);diff --git a/apps/server/src/routers/lambda/__tests__/share.test.ts b/apps/server/src/routers/lambda/__tests__/share.test.tsindex 8cf784bd80d..3645afb39aa 100644--- a/apps/server/src/routers/lambda/__tests__/share.test.ts+++ b/apps/server/src/routers/lambda/__tests__/share.test.ts@@ -222,8 +222,7 @@ describe('shareRouter', () => {ownerFullName: 'Owner Person',ownerUsername: 'owner',shareConfig: {- maxTopicsPerVisitor: 5,- maxTurnsPerTopic: 20,+ maxMessagesPerVisitor: 100,slug: 'shared-agent',toolGrants: [{ apis: ['search'], identifier: 'lobe-web-browsing' }],},@@ -337,8 +336,7 @@ describe('shareRouter', () => {terms: {allowCreatorViewSessions: false,maxFileStorage: 512 * 1024 * 1024,- maxTopicsPerVisitor: 5,- maxTurnsPerTopic: 20,+ maxMessagesPerVisitor: 100,},// Identifier only: the granted API list is owner-facing configuration.toolGrants: ['lobe-web-browsing'],diff --git a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts b/apps/server/src/routers/lambda/__tests__/shareChat.test.tsindex 5bba58e3fb7..dbe065f194d 100644--- a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts+++ b/apps/server/src/routers/lambda/__tests__/shareChat.test.ts@@ -65,12 +65,12 @@ vi.mock('@/database/models/agentShare', () => ({}));const mockFindById = vi.fn();-const mockCountBySender = vi.fn();+const mockCountMessagesBySender = vi.fn();const mockQueryBySender = vi.fn();const mockIsRunningOperationAlive = vi.fn();const TopicModelMock = vi.fn(function () {return {- countBySender: mockCountBySender,+ countMessagesBySender: mockCountMessagesBySender,findById: mockFindById,isRunningOperationAlive: mockIsRunningOperationAlive,queryBySender: mockQueryBySender,@@ -80,7 +80,6 @@ vi.mock('@/database/models/topic', () => ({TopicModel: TopicModelMock,}));-const mockMessageCountByTopic = vi.fn();const mockFindMessagePlugin = vi.fn();const mockMessageQuery = vi.fn();const mockMessageQueryForVisitor = vi.fn();@@ -94,7 +93,6 @@ vi.mock('@/database/models/message', async (importOriginal) => {...actual,MessageModel: vi.fn(function () {return {- countByTopic: mockMessageCountByTopic,findMessagePlugin: mockFindMessagePlugin,query: mockMessageQuery,queryForVisitor: mockMessageQueryForVisitor,@@ -245,8 +243,7 @@ const share = {shareConfig: {allowReadMemory: false,toolGrants: [],- maxTopicsPerVisitor: 2,- maxTurnsPerTopic: 3,+ maxMessagesPerVisitor: 3,},shareId: 'share-1',visibility: 'link',@@ -273,9 +270,8 @@ describe('shareChatRouter', () => {mockLockScopedAgentRow.mockResolvedValue({ id: share.agentId, workspaceId: null });mockFindById.mockResolvedValue(visitorTopic);mockIsRunningOperationAlive.mockResolvedValue(true);- mockCountBySender.mockResolvedValue(0);+ mockCountMessagesBySender.mockResolvedValue(0);mockQueryBySender.mockResolvedValue([]);- mockMessageCountByTopic.mockResolvedValue(0);mockMessageQuery.mockResolvedValue([]);mockExecAgent.mockResolvedValue({ operationId: 'op-1', success: true });mockInterruptTask.mockResolvedValue({ operationId: 'op-1', success: true });@@ -330,7 +326,7 @@ describe('shareChatRouter', () => {code: 'TOO_MANY_REQUESTS',message: 'ShareSpendLimitExceeded',});- expect(mockCountBySender).not.toHaveBeenCalled();+ expect(mockCountMessagesBySender).not.toHaveBeenCalled();expect(mockExecAgent).not.toHaveBeenCalled();});@@ -352,32 +348,32 @@ describe('shareChatRouter', () => {});});- it('rejects a new-topic run once the visitor topic cap is reached', async () => {- mockCountBySender.mockResolvedValue(2);+ it('refuses new and existing topics once the visitor has sent their message cap', async () => {+ mockCountMessagesBySender.mockResolvedValue(3);const caller = await createCaller();+ const refused = { code: 'TOO_MANY_REQUESTS', message: 'ShareMessageLimitExceeded' };- await expect(caller.execAgent({ prompt: 'hi', shareId: 'share-1' })).rejects.toMatchObject({- code: 'TOO_MANY_REQUESTS',- message: 'ShareTopicLimitExceeded',+ await expect(caller.execAgent({ prompt: 'hi', shareId: 'share-1' })).rejects.toMatchObject(+ refused,+ );+ // The cap spans all the visitor's topics, so an existing topic is refused too.+ await expect(+ caller.execAgent({ prompt: 'hi', shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).rejects.toMatchObject(refused);+ expect(mockCountMessagesBySender).toHaveBeenCalledWith({+ agentId: share.agentId,+ senderId: VISITOR,});expect(mockExecAgent).not.toHaveBeenCalled();});- it('rejects an existing-topic run once the turn cap is reached', async () => {- mockMessageCountByTopic.mockResolvedValue(3);+ it('admits a run while the visitor is below the message cap', async () => {+ mockCountMessagesBySender.mockResolvedValue(2);const caller = await createCaller();- await expect(- caller.execAgent({ prompt: 'hi', shareId: 'share-1', topicId: 'tpc_visitor' }),- ).rejects.toMatchObject({- code: 'TOO_MANY_REQUESTS',- message: 'ShareTurnLimitExceeded',- });- expect(mockMessageCountByTopic).toHaveBeenCalledWith({- role: 'user',- topicId: 'tpc_visitor',- });- expect(mockExecAgent).not.toHaveBeenCalled();+ await caller.execAgent({ prompt: 'hi', shareId: 'share-1' });++ expect(mockExecAgent).toHaveBeenCalled();});it("fails closed when the topic is not the visitor's own share topic", async () => {@@ -446,7 +442,7 @@ describe('shareChatRouter', () => {await expect(caller.execAgent({ fileIds, prompt: 'look', shareId: 'share-1' }),).rejects.toMatchObject({ code: 'NOT_FOUND', message: 'File not found' });- expect(mockCountBySender).not.toHaveBeenCalled();+ expect(mockCountMessagesBySender).not.toHaveBeenCalled();expect(mockExecAgent).not.toHaveBeenCalled();});@@ -609,7 +605,7 @@ describe('shareChatRouter', () => {it("resumes the visitor's parked run with their answer and approval mode", async () => {// Answering the last allowed turn's approval must not be refused.- mockMessageCountByTopic.mockResolvedValue(3);+ mockCountMessagesBySender.mockResolvedValue(3);const caller = await createCaller();await caller.execAgent({@@ -621,7 +617,7 @@ describe('shareChatRouter', () => {userInterventionConfig: { approvalMode: 'allow-list', allowList: ['lobe-web-browsing'] },});- expect(mockMessageCountByTopic).not.toHaveBeenCalled();+ expect(mockCountMessagesBySender).not.toHaveBeenCalled();expect(mockBridgeLegacyResume).toHaveBeenCalledWith(expect.objectContaining({ resumeApproval, shareVisitor }),expect.objectContaining({ shareGate: expect.any(Object), userId: VISITOR }),@@ -1341,13 +1337,13 @@ describe('shareChatRouter', () => {});});- it('does not tie the list page size to the live maxTopicsPerVisitor cap', async () => {- // The cap only gates admission of NEW topics. A creator lowering it below- // what a visitor already created must not hide those older conversations —- // the visitor surface has no pagination or deep links to recover them.+ it('does not tie the list page size to the live message cap', async () => {+ // The cap only gates sending. A creator lowering it must not hide the+ // visitor's older conversations — the visitor surface has no pagination+ // or deep links to recover them.mockAccessCheck.mockResolvedValue({...share,- shareConfig: { ...share.shareConfig, maxTopicsPerVisitor: 1 },+ shareConfig: { ...share.shareConfig, maxMessagesPerVisitor: 1 },});const caller = await createCaller();await caller.getTopics({ shareId: 'share-1' });@@ -1383,7 +1379,6 @@ describe('shareChatRouter', () => {expect.objectContaining({redaction: {showErrorDetails: undefined,- showModelInfo: undefined,},// Pinned to share + topic + VISITOR: the ordinary scope would join// the creator's Works, which must never reach a visitor surface.diff --git a/apps/server/src/routers/lambda/agentShare.ts b/apps/server/src/routers/lambda/agentShare.tsindex 0df5f96afb5..7970a4c2e2f 100644--- a/apps/server/src/routers/lambda/agentShare.ts+++ b/apps/server/src/routers/lambda/agentShare.ts@@ -2,7 +2,6 @@ import { builtinSkills } from '@lobechat/builtin-skills';import {AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,AGENT_SHARE_DEVICE_ALLOW_USERS_LIMIT,- AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT,} from '@lobechat/const';import { assembleSkillPool } from '@lobechat/mecha';import { getActivePluginIds, getAutoPluginIds, getDisabledPluginIds } from '@lobechat/types';@@ -85,22 +84,9 @@ export const agentShareConfigSchema = z.optional(),/** Bytes; `0` is a real value (attachments off), so non-negative rather than positive. */maxFileStorage: z.number().int().nonnegative().optional(),- /**- * The visitor topic list (`TopicModel.queryBySender`) is not paginated- * and is bounded by `AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT`, so a cap- * above that constant would let visitors create topics they can never- * reopen.- */- maxTopicsPerVisitor: z- .number()- .int()- .positive()- .max(AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT)- .optional(),- maxTurnsPerTopic: z.number().int().positive().optional(),+ maxMessagesPerVisitor: z.number().int().positive().optional(),monthlySpendLimit: z.number().nonnegative().optional(),showErrorDetails: z.boolean().optional(),- showModelInfo: z.boolean().optional(),/*** Skill identifiers the creator opened to visitors. An empty array is* accepted rather than rejected: unticking the last skill is a normaldiff --git a/apps/server/src/routers/lambda/share.ts b/apps/server/src/routers/lambda/share.tsindex 00818df2d8c..f330fb10783 100644--- a/apps/server/src/routers/lambda/share.ts+++ b/apps/server/src/routers/lambda/share.ts@@ -1,7 +1,6 @@import {AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,- AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,- AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,+ AGENT_SHARE_DEFAULT_MAX_MESSAGES_PER_VISITOR,} from '@lobechat/const';import {type SharedAgentData,@@ -247,10 +246,8 @@ export const shareRouter = router({terms: {allowCreatorViewSessions: share.shareConfig.allowCreatorViewSessions ?? false,maxFileStorage: share.shareConfig.maxFileStorage ?? AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,- maxTopicsPerVisitor:- share.shareConfig.maxTopicsPerVisitor ?? AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,- maxTurnsPerTopic:- share.shareConfig.maxTurnsPerTopic ?? AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,+ maxMessagesPerVisitor:+ share.shareConfig.maxMessagesPerVisitor ?? AGENT_SHARE_DEFAULT_MAX_MESSAGES_PER_VISITOR,},// Identifiers only. The granted API list is owner-facing configuration// and must not reach a visitor.diff --git a/apps/server/src/routers/lambda/shareChat/conversation.ts b/apps/server/src/routers/lambda/shareChat/conversation.tsindex e8d1977eb08..58948c6ebca 100644--- a/apps/server/src/routers/lambda/shareChat/conversation.ts+++ b/apps/server/src/routers/lambda/shareChat/conversation.ts@@ -18,12 +18,8 @@ export const conversationRouter = router({.query(async ({ input, ctx }) => {const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);- // The list is intentionally NOT bounded by the share's live- // `maxTopicsPerVisitor`: that cap gates ADMISSION of new topics (the- // COUNT check in `execAgent`, `exec.ts`), and a creator may lower it below- // what a visitor already created. Tying the page size to it would hide- // those older conversations with no pagination or deep link to reach- // them, so the model applies its own fixed, generous list bound instead.+ // No share setting caps a visitor's topics, so the model applies its own+ // fixed, generous list bound.const topicModel = new TopicModel(ctx.serverDB,share.ownerId,@@ -68,9 +64,9 @@ export const conversationRouter = router({share.workspaceId ?? undefined,);- // queryForVisitor strips the creator's `sender` identity, and — unless the- // share opts in via `showModelInfo` / `showErrorDetails` — the spend/model- // snapshot and raw error payload too. Share messages persist under the+ // queryForVisitor strips the creator's `sender` identity and the+ // spend/model snapshot, and — unless the share opts in via+ // `showErrorDetails` — the raw error payload too. Share messages persist under the// CREATOR's account (see the `shareChatProcedure` doc in `procedures.ts`), so the raw `query()` result// would otherwise leak the creator's account identity to the visitor.return messageModel.queryForVisitor(@@ -79,7 +75,6 @@ export const conversationRouter = router({postProcessUrl: (path, file) => fileService.getFileAccessUrl({ id: file.id, url: path }),redaction: {showErrorDetails: share.shareConfig.showErrorDetails,- showModelInfo: share.shareConfig.showModelInfo,},// Work summaries are assembled under the visitor's OWN share scope:// only Works registered from this share topic resolve, never thediff --git a/apps/server/src/routers/lambda/shareChat/exec.ts b/apps/server/src/routers/lambda/shareChat/exec.tsindex be18e9dd563..91ce00e9cb2 100644--- a/apps/server/src/routers/lambda/shareChat/exec.ts+++ b/apps/server/src/routers/lambda/shareChat/exec.ts@@ -1,6 +1,5 @@import {- AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,- AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,+ AGENT_SHARE_DEFAULT_MAX_MESSAGES_PER_VISITOR,SHARE_VISITOR_MAX_FILES_PER_TURN,SHARE_VISITOR_PROMPT_MAX_LENGTH,} from '@lobechat/const';@@ -177,55 +176,39 @@ export const execRouter = router({// Runtime-normalized (findByShareIdWithAccessCheck fills defaults), but// the config TYPE keeps every field optional — re-apply the same default// constants rather than asserting non-null.- const maxTopicsPerVisitor =- share.shareConfig.maxTopicsPerVisitor ?? AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR;- const maxTurnsPerTopic =- share.shareConfig.maxTurnsPerTopic ?? AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC;+ const maxMessagesPerVisitor =+ share.shareConfig.maxMessagesPerVisitor ?? AGENT_SHARE_DEFAULT_MAX_MESSAGES_PER_VISITOR;const { aiAgentService, dispatchContext, messageModel, shareGate, topicModel } =await createShareRunScope(ctx.serverDB, share, ctx.userId);- // Fast, UX-only pre-check for both caps: reject an obviously-over-cap- // request BEFORE paying for agent-config/tool resolution, instead of only- // at dispatch. This is NOT the enforcement: it is a plain unlocked count,- // so a burst of concurrent requests can all read the same pre-insert- // count and all pass. The atomic, authoritative gate is- // `reserveShareVisitorTopicOrThrow` / `reserveShareVisitorTurnOrThrow`- // (`apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts`), which- // locks and re-checks the same counters immediately around the real- // topic/message INSERT inside `AiAgentService.execAgent`.if (input.topicId) {await findVisitorTopicOrThrow(topicModel, {agentId: share.agentId,topicId: input.topicId,visitorUserId: ctx.userId,});+ }- // A resume continues the turn the visitor already spent — it adds no- // user message (`reserveShareVisitorTurn` skips it too), so a visitor- // on their last allowed turn can still answer that turn's approval.- const turnCount = isResume- ? 0- : await messageModel.countByTopic({- role: 'user',- topicId: input.topicId,- });- if (turnCount >= maxTurnsPerTopic) {- throw new TRPCError({- code: 'TOO_MANY_REQUESTS',- message: ChatErrorType.ShareTurnLimitExceeded,- });- }- } else {- const topicCount = await topicModel.countBySender({+ // Fast, UX-only pre-check: reject an obviously-over-cap request BEFORE+ // paying for agent-config/tool resolution. This is NOT the enforcement:+ // a plain unlocked count lets concurrent requests all pass. The atomic+ // gate is `reserveShareVisitorTurnOrThrow`+ // (`apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts`), which+ // locks and recounts around the real message INSERT. A resume continues+ // the turn the visitor already spent and adds no user message+ // (`reserveShareVisitorTurn` skips it too), so a visitor on their last+ // allowed message can still answer that turn's approval.+ if (+ !isResume &&+ (await topicModel.countMessagesBySender({agentId: share.agentId,senderId: ctx.userId,+ })) >= maxMessagesPerVisitor+ ) {+ throw new TRPCError({+ code: 'TOO_MANY_REQUESTS',+ message: ChatErrorType.ShareMessageLimitExceeded,});- if (topicCount >= maxTopicsPerVisitor) {- throw new TRPCError({- code: 'TOO_MANY_REQUESTS',- message: ChatErrorType.ShareTopicLimitExceeded,- });- }}log('execAgent: share=%s visitor=%s topic=%s', input.shareId, ctx.userId, input.topicId);diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.tsindex a5378ca9423..b8d0a1bc413 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts@@ -216,10 +216,7 @@ export async function createOperation(// applies the owner-configured visitor redaction policy instead of the// fail-closed full strip. See `gatewayVisitorRedaction.ts`.visitorRedaction: agentShareVisitor- ? {- showErrorDetails: agentShareVisitor.showErrorDetails,- showModelInfo: agentShareVisitor.showModelInfo,- }+ ? { showErrorDetails: agentShareVisitor.showErrorDetails }: undefined,mirrorToOperationId,modelRuntimeConfig: withoutFrozenModelFacts(modelRuntimeConfig),diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.shareVisitor.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.shareVisitor.test.tsindex ca58acfd319..d4431ee27a7 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.shareVisitor.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.shareVisitor.test.ts@@ -91,7 +91,7 @@ vi.mock('../codexDeviceRuntime', () => ({const shareGate = {agentId: 'agent-1',canUseDevice: true,- shareConfig: { showErrorDetails: false, showModelInfo: true },+ shareConfig: { showErrorDetails: true },shareId: 'share-1',visitorUserId: 'visitor-1',} as any;@@ -167,7 +167,7 @@ describe('dispatchHeteroAgent — share visitor run', () => {expect(mocks.signUserJWT).toHaveBeenCalledWith('visitor-1');expect(mocks.signUserJWT).not.toHaveBeenCalledWith('creator-1');- const redaction = { showErrorDetails: false, showModelInfo: true };+ const redaction = { showErrorDetails: true };expect(mocks.createOperationMetadata).toHaveBeenCalledWith(expect.any(String),expect.objectContaining({diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.tsindex e9a8b4d42f3..109d72af010 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts@@ -81,10 +81,7 @@ const dispatchHeteroAgentImpl = async (const shareStream = shareGate? {streamOwnerUserId: shareGate.visitorUserId,- visitorRedaction: {- showErrorDetails: shareGate.shareConfig.showErrorDetails,- showModelInfo: shareGate.shareConfig.showModelInfo,- },+ visitorRedaction: { showErrorDetails: shareGate.shareConfig.showErrorDetails },}: undefined;// Same structured shape as the built-in path (`op_{ts}_{agentId}_{topicId}_{rand}`)diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.tsindex 2132a9f94cf..827501212a8 100644--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts@@ -282,7 +282,6 @@ export const startOperation = async (// offered still reaches the runtime.skillGrants: shareGate.shareConfig.skillGrants,showErrorDetails: shareGate.shareConfig.showErrorDetails,- showModelInfo: shareGate.shareConfig.showModelInfo,visitorUserId: shareGate.visitorUserId,}: undefined,diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.tsindex cd46ea0a882..2d2df554a8d 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -685,7 +685,7 @@ export const setupTurn = async (// `TopicModel`'s creator-facing reads (`query`, `count`, `queryTopics`,// `queryRecent`, `rank`) filter out via `notShareVisitorTopic()`, and// what lets shareChat scope reads per visitor (`queryBySender` /- // `countBySender`).+ // `countMessagesBySender`).senderId: shareGate?.visitorUserId,title:title !== undefined@@ -693,10 +693,9 @@ export const setupTurn = async (: fallbackTitleSource.slice(0, 50) + (fallbackTitleSource.length > 50 ? '...' : ''),trigger,};- // Share-visitor runs must reserve the `maxTopicsPerVisitor` slot and- // insert the topic in ONE locked transaction — see- // `reserveShareVisitorTopic`'s JSDoc for the race this closes. Non-share- // runs (no per-visitor cap to enforce) keep the plain unlocked insert.+ // Share-visitor runs insert the topic only under the share's row lock, so+ // a share paused mid-request writes nothing — see+ // `reserveShareVisitorTopic`'s JSDoc. Non-share runs keep the plain insert.const newTopic = shareGate? await reserveShareVisitorTopic({@@ -704,7 +703,6 @@ export const setupTurn = async (db: deps.db,expectedShareId: shareGate.shareId,ownerId: deps.userId,- visitorUserId: shareGate.visitorUserId,workspaceId: deps.workspaceId,},newTopicParams,@@ -988,12 +986,10 @@ export const setupTurn = async (threadId: appContext?.threadId ?? undefined,topicId,};- // Share-visitor runs must reserve the `maxTurnsPerTopic` slot and insert- // the user message in ONE locked transaction — see- // `reserveShareVisitorTurn`'s JSDoc for the race this closes (same class of- // count-then-act bug as the topic cap above). Harmless no-op on a topic- // this same call just created (count is 0). Non-share runs (no per-turn- // cap) keep the plain unlocked insert.+ // Share-visitor runs must reserve the `maxMessagesPerVisitor` slot and+ // insert the user message in ONE locked transaction — see+ // `reserveShareVisitorTurn`'s JSDoc for the race this closes. Non-share+ // runs (no per-visitor cap) keep the plain unlocked insert.const userMessageRecord = runFromHistory? undefined: shareGate@@ -1003,7 +999,7 @@ export const setupTurn = async (db: deps.db,expectedShareId: shareGate.shareId,ownerId: deps.userId,- topicId,+ visitorUserId: shareGate.visitorUserId,workspaceId: deps.workspaceId,},userMessageParams,diff --git a/apps/server/src/services/aiAgent/shareGate/testUtils.ts b/apps/server/src/services/aiAgent/shareGate/testUtils.tsindex 31652425263..29b24689bf2 100644--- a/apps/server/src/services/aiAgent/shareGate/testUtils.ts+++ b/apps/server/src/services/aiAgent/shareGate/testUtils.ts@@ -6,8 +6,7 @@ export const buildGate = (config: Partial<AgentShareGate['shareConfig']> = {}):agentId: 'agent-1',canUseDevice: false,shareConfig: {- maxTopicsPerVisitor: 5,- maxTurnsPerTopic: 20,+ maxMessagesPerVisitor: 100,...config,},shareId: 'share-1',diff --git a/apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts b/apps/server/src/services/aiAgent/shareVisitorAbuseGuards.tsindex 53970299370..ffded89db35 100644--- a/apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts+++ b/apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts@@ -52,33 +52,16 @@ const assertShareStillAuthorized = async (};/**- * Atomically enforce `maxTopicsPerVisitor` at the exact moment a share- * visitor's new topic is written.+ * Write a share visitor's new topic only while the share is still the live+ * `link` share this request was authorized against.*- * `shareChat.ts` runs a `TopicModel.countBySender` pre-check before ever- * dispatching to `AiAgentService.execAgent` (a fast, UX-only reject that skips- * wasted agent-config/tool-resolution work for an obviously-over-cap request),- * but that read and the actual `topics` INSERT this function performs are two- * unrelated statements, on two unrelated requests/connections, with nothing- * serializing them. Concurrent new-topic requests from the same visitor can- * all observe the same pre-insert count and all insert.- *- * `AgentShareModel.lockScopedAgentRow` takes `FOR UPDATE` on the SAME- * `agents.id` row every other share-mutation path locks (`create`,- * `updateConfig`, `updateVisibility`, `deleteByAgentId`). The recount and the- * INSERT both run inside that one locked transaction, so whichever of two- * concurrent callers loses the lock re-reads the FIRST caller's- * already-committed topic and correctly rejects instead of also inserting.- * Reusing the Agent row lock (rather than a visitor-keyed advisory lock) also- * makes the cap read below conflict with a concurrent `updateConfig`, so a- * recount can never straddle an owner's cap reduction.- *- * The cap itself is read via `AgentShareModel.readCurrentVisitorCaps` from- * INSIDE this same locked transaction — deliberately NOT accepted as a- * caller-supplied number. `shareChat.ts` resolves `shareConfig` exactly ONCE,- * long before `AiAgentService` reaches this function (agent-config/tool/- * knowledge-base resolution in between), so a caller-supplied cap would be a- * stale snapshot an owner's mid-flood reduction could never affect.+ * No share setting caps how many topics a visitor has: the visitor's budget is+ * the number of messages they send (`reserveShareVisitorTurn`). This guard only+ * closes the pause race: `AgentShareModel.lockScopedAgentRow` takes `FOR UPDATE`+ * on the SAME `agents.id` row every share-mutation path locks (`create`,+ * `updateConfig`, `updateVisibility`, `deleteByAgentId`), so an owner who makes+ * the link private mid-request never gets a row written under the stale+ * authorization.*/export const reserveShareVisitorTopicOrThrow = async (params: {agentId: string;@@ -91,10 +74,9 @@ export const reserveShareVisitorTopicOrThrow = async (params: {*/expectedShareId: string;ownerId: string;- visitorUserId: string;workspaceId?: string;}): Promise<TopicItem> => {- const { agentId, create, db, expectedShareId, ownerId, visitorUserId, workspaceId } = params;+ const { agentId, create, db, expectedShareId, ownerId, workspaceId } = params;return db.transaction(async (trx) => {const tx = trx as unknown as LobeChatDatabase;@@ -113,28 +95,9 @@ export const reserveShareVisitorTopicOrThrow = async (params: {// Fail closed BEFORE any row is written.await assertShareStillAuthorized(tx, agentId, expectedShareId, workspaceId);- // Fresh read under the lock, not a caller-supplied value — see this- // function's JSDoc for the stale-cap flood this closes.- const { maxTopicsPerVisitor } = await AgentShareModel.readCurrentVisitorCaps(tx, agentId);-- // Share-runtime scope: countBySender reads through `mine()` (visitor-- // inclusive by construction) so this flag is redundant here, but pass it- // so any later read added to this guard doesn't silently fail closed.- const txTopicModel = new TopicModel(tx, ownerId, workspaceId, undefined, {- includeShareVisitor: true,- });- const currentCount = await txTopicModel.countBySender({ agentId, senderId: visitorUserId });-- // Fail closed: a visitor already at (or somehow past) the cap never gets- // another topic, even if `create`'s own params disagree with `agentId`.- if (currentCount >= maxTopicsPerVisitor) {- throw new TRPCError({- code: 'TOO_MANY_REQUESTS',- message: ChatErrorType.ShareTopicLimitExceeded,- });- }-- return create(txTopicModel);+ return create(+ new TopicModel(tx, ownerId, workspaceId, undefined, { includeShareVisitor: true }),+ );});};@@ -145,7 +108,6 @@ export const reserveShareVisitorTopic = (db: LobeChatDatabase;expectedShareId: string;ownerId: string;- visitorUserId: string;workspaceId?: string;},createParams: CreateTopicParams,@@ -157,23 +119,24 @@ export const reserveShareVisitorTopic = (});/**- * Atomically enforce `maxTurnsPerTopic` at the exact moment a share visitor's- * user-turn message is written.+ * Atomically enforce `maxMessagesPerVisitor` at the exact moment a share+ * visitor's message is written.*- * Structurally the same race as {@link reserveShareVisitorTopicOrThrow}:- * `shareChat.ts` pre-checks `MessageModel.countByTopic` against the cap before- * dispatch, but the actual user-message INSERT happens later, deep in- * `execAgent`, on a separate statement with nothing serializing the two. A- * burst of concurrent sends to the SAME topic can all pass the pre-check and- * all insert.+ * Callers may pre-check the count before dispatch (a fast reject that skips+ * wasted agent-config/tool-resolution work), but that read and the actual+ * user-message INSERT, deep in `execAgent`, are separate statements with+ * nothing serializing them: a burst of concurrent sends could all pass the+ * pre-check and all insert.** Locked via `AgentShareModel.lockScopedAgentRow` — the SAME `agents.id FOR- * UPDATE` row {@link reserveShareVisitorTopicOrThrow} and every other- * share-mutation path lock, not a topic-scoped lock, so the cap read below- * also conflicts with a concurrent `updateConfig`. The trade-off is coarser- * contention (this serializes against every OTHER topic's reservation for the- * same agent), which is acceptable: these transactions are a single- * count-then-insert each, with no external I/O.+ * UPDATE` row every share-mutation path locks — so whichever of two concurrent+ * sends loses the lock recounts the first one's committed message, and the cap+ * read below also conflicts with a concurrent `updateConfig`. The cap is read+ * inside the lock rather than accepted from the caller, so an owner's+ * mid-flood reduction is the number actually enforced. The trade-off is coarser+ * contention (this serializes every visitor's send to the same agent), which+ * is acceptable: each transaction is a single count-then-insert with no+ * external I/O.*/export const reserveShareVisitorTurnOrThrow = async (params: {agentId: string;@@ -182,10 +145,10 @@ export const reserveShareVisitorTurnOrThrow = async (params: {/** See {@link reserveShareVisitorTopicOrThrow}'s `expectedShareId` param JSDoc. */expectedShareId: string;ownerId: string;- topicId: string;+ visitorUserId: string;workspaceId?: string;}): Promise<DBMessageItem | undefined> => {- const { agentId, create, db, expectedShareId, ownerId, topicId, workspaceId } = params;+ const { agentId, create, db, expectedShareId, ownerId, visitorUserId, workspaceId } = params;return db.transaction(async (trx) => {const tx = trx as unknown as LobeChatDatabase;@@ -203,24 +166,21 @@ export const reserveShareVisitorTurnOrThrow = async (params: {await assertShareStillAuthorized(tx, agentId, expectedShareId, workspaceId);// Fresh read under the lock, not a caller-supplied value.- const { maxTurnsPerTopic } = await AgentShareModel.readCurrentVisitorCaps(tx, agentId);-- // Share-runtime scope: countByTopic reads through `ownership()`, which- // now excludes visitor rows by default — the visitor topic's rows would- // never be counted without opting in.- const txMessageModel = new MessageModel(tx, ownerId, workspaceId, undefined, {+ const { maxMessagesPerVisitor } = await AgentShareModel.readCurrentVisitorCaps(tx, agentId);+ const sent = await new TopicModel(tx, ownerId, workspaceId, undefined, {includeShareVisitor: true,- });- const turnCount = await txMessageModel.countByTopic({ role: 'user', topicId });-- if (turnCount >= maxTurnsPerTopic) {+ }).countMessagesBySender({ agentId, senderId: visitorUserId });+ if (sent >= maxMessagesPerVisitor) {throw new TRPCError({code: 'TOO_MANY_REQUESTS',- message: ChatErrorType.ShareTurnLimitExceeded,+ message: ChatErrorType.ShareMessageLimitExceeded,});}- return create(txMessageModel);+ // Share-runtime scope: visitor rows are excluded by default.+ return create(+ new MessageModel(tx, ownerId, workspaceId, undefined, { includeShareVisitor: true }),+ );});};@@ -231,7 +191,7 @@ export const reserveShareVisitorTurn = (db: LobeChatDatabase;expectedShareId: string;ownerId: string;- topicId: string;+ visitorUserId: string;workspaceId?: string;},createParams: CreateMessageParams,diff --git a/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts b/apps/server/src/services/channel/ChannelCoordinator.advance.test.tsindex 32e35a66ee8..cc593ff52aa 100644--- a/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts+++ b/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts@@ -149,6 +149,11 @@ describe('Channel concurrent startup', () => {await coordinator(1).advance('channel');const [params] = execAgent.mock.calls[0];+ // An ordinary Channel run keeps its own label and runs unattended.+ expect(params).toMatchObject({+ trigger: 'channel',+ userInterventionConfig: { approvalMode: 'headless' },+ });if ('deviceId' in environment) {expect(params).toMatchObject({ deviceId: 'dev-2', snapshotFollowsCallerDevice: false });expect(params.agentConfigSnapshot.agencyConfig).toEqual({diff --git a/apps/server/src/services/channel/ChannelCoordinator.share.test.ts b/apps/server/src/services/channel/ChannelCoordinator.share.test.tsindex f685175d313..fb37dba18e1 100644--- a/apps/server/src/services/channel/ChannelCoordinator.share.test.ts+++ b/apps/server/src/services/channel/ChannelCoordinator.share.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { TRPCError } from '@trpc/server';import { beforeEach, describe, expect, it, vi } from 'vitest';import { ChannelCoordinator } from './ChannelCoordinator';@@ -176,6 +177,16 @@ describe('dispatching a contact’s shared Agent', () => {expect(executions.accepted).toHaveBeenCalledWith('channel', 'job');});+ it('records the run as a share run that runs only granted tools without approval', async () => {+ await coordinator().advance('channel');++ const [params] = execAgent.mock.calls[0];+ expect(params.trigger).toBe('agent_share');+ // Nobody can approve mid-run; the share gate limits the run to the granted tools.+ expect(params.userInterventionConfig).toEqual({ approvalMode: 'headless' });+ expect(params.shareGate).toBeDefined();+ });+it.each([['the share was paused',@@ -191,6 +202,49 @@ describe('dispatching a contact’s shared Agent', () => {await coordinator().advance('channel');expect(execAgent).not.toHaveBeenCalled();- expect(executions.retireReservation).toHaveBeenCalledWith('channel', 'job');+ expect(executions.retireReservation).toHaveBeenCalledWith(+ 'channel',+ 'job',+ expect.toBeOneOf([undefined, expect.any(Object)]),+ );+ });++ // The visitor saw only "no reason recorded" when the owner's monthly cap refused the reply.+ it('records the spend-limit refusal so the visitor learns why', async () => {+ checkSpend.mockResolvedValue({ allowed: false });+ await coordinator().advance('channel');++ expect(executions.retireReservation).toHaveBeenCalledWith('channel', 'job', {+ message: 'This shared Agent reached its monthly usage limit',+ type: 'ShareSpendLimitExceeded',+ });+ });++ // A shared Claude Code / Codex Agent's run stops at the share gate when the share grants the+ // visitor no device, or the owner's device is offline; the visitor must learn which.+ it.each(['ShareHeterogeneousAgentUnsupported', 'ShareHeteroDeviceUnavailable'])(+ 'records the share gate’s %s refusal so the visitor learns why',+ async (type) => {+ execAgent.mockRejectedValue(new TRPCError({ code: 'FORBIDDEN', message: type }));+ await coordinator().advance('channel');++ expect(executions.retireReservation).toHaveBeenCalledWith('channel', 'job', {+ message: type,+ type,+ });+ },+ );+ // A visitor past the owner's message cap is refused by the atomic turn guard inside execAgent+ // (the admission pre-check can race it); the receipt must still say why.+ it('records the message-limit refusal raised by the turn guard', async () => {+ execAgent.mockRejectedValue(+ new TRPCError({ code: 'TOO_MANY_REQUESTS', message: 'ShareMessageLimitExceeded' }),+ );+ await coordinator().advance('channel');++ expect(executions.retireReservation).toHaveBeenCalledWith('channel', 'job', {+ message: 'ShareMessageLimitExceeded',+ type: 'ShareMessageLimitExceeded',+ });});});diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.tsindex fe37e431e82..a533690322b 100644--- a/apps/server/src/services/channel/ChannelCoordinator.ts+++ b/apps/server/src/services/channel/ChannelCoordinator.ts@@ -2,7 +2,7 @@ import { ChannelIdentifier } from '@lobechat/builtin-tool-channel';import type { LobeChatDatabase } from '@lobechat/database';import { buildChannelPrompt, CHANNEL_INSTRUCTIONS } from '@lobechat/prompts';import type { ChannelExecutionConfig, ChannelSharedAgentAccess } from '@lobechat/types';-import { agentDisplayName } from '@lobechat/types';+import { agentDisplayName, ChatErrorType, RequestTrigger } from '@lobechat/types';import { isRecord } from '@lobechat/utils/object';import { and, eq, inArray } from 'drizzle-orm';import { groupBy } from 'es-toolkit';@@ -42,6 +42,39 @@ import { createChannelWorktree } from './worktree';const LEASE_MS = 60_000;+/**+ * A dispatch refused for a reason the requester can act on. Its `type` is kept on the failed+ * job, so the visitor of a shared Agent (whose failure text is otherwise redacted) still learns+ * why, in their own language.+ */+class ChannelDispatchError extends Error {+ constructor(+ readonly type: string,+ message: string,+ ) {+ super(message);+ }+}++/**+ * Refusals of a shared Agent's run its visitor can act on, raised by the run's share guards before+ * the visitor's message is written: the share grants them no device for a Claude Code / Codex+ * Agent, the owner's device is offline, or the visitor has sent all the messages the share allows.+ * Kept as the job's failure type, as the share page shows them.+ */+const SHARE_REFUSAL_TYPES = new Set<string>([+ ChatErrorType.ShareHeterogeneousAgentUnsupported,+ ChatErrorType.ShareHeteroDeviceUnavailable,+ ChatErrorType.ShareMessageLimitExceeded,+]);++const dispatchFailureType = (error: unknown) =>+ error instanceof ChannelDispatchError+ ? error.type+ : error instanceof Error && SHARE_REFUSAL_TYPES.has(error.message)+ ? error.message+ : undefined;+/** A co-addressed Agent as the run reads it: its name, and its title when that says more. */const describePeer = (agent: ChannelCoAddressedAgent) => {const name = agentDisplayName(agent);@@ -91,7 +124,11 @@ export class ChannelCoordinator {visitorUserId: requesterId,workspaceId: share.workspaceId ?? undefined,});- if (!spend.allowed) throw new Error('This shared Agent reached its monthly usage limit');+ if (!spend.allowed)+ throw new ChannelDispatchError(+ ChatErrorType.ShareSpendLimitExceeded,+ 'This shared Agent reached its monthly usage limit',+ );return {agentId,canUseDevice: await resolveShareVisitorDeviceAccess(this.db, share, requesterId),@@ -343,23 +380,35 @@ export class ChannelCoordinator {}),reservedOperationId: job.operationId,shareGate,- trigger: 'channel',+ // A shared Agent's run is the owner's, paid by the share and read by a visitor: it is+ // recorded as a share run so usage separates it from the owner's own Channel runs. The+ // Channel reply flow keys off the reserved operation and job, never this label.+ trigger: share ? RequestTrigger.AgentShare : 'channel',+ // Nobody can approve a tool mid-run, so tools run without approval. For a shared Agent+ // that is limited to what the creator granted: `shareGate` keeps ungranted tools out of+ // the run and blocks their calls, so granting a tool is the creator's consent to run it.userInterventionConfig: { approvalMode: 'headless' },});if (!result.success) throw new Error(result.error || 'Agent could not start');await this.executions.accepted(job.channelId, job.id);} catch (error) {console.error('[channel:dispatch]', error);+ const type = dispatchFailureType(error);const operation = await new AgentOperationModel(this.db,topic.userId,workspaceId ?? undefined,).findById(job.operationId);if (operation?.status === 'idle') {- await this.executions.retireReservation(job.channelId, job.id);+ await this.executions.retireReservation(+ job.channelId,+ job.id,+ type && error instanceof Error ? { message: error.message, type } : undefined,+ );} elseawait this.executions.fail(job.channelId, job.id, {message: error instanceof Error ? error.message : 'Agent could not start',+ ...(type && { type }),});} finally {clearInterval(renew);diff --git a/locales/ar/agent.json b/locales/ar/agent.jsonindex 3f0081103ba..500a1a3bb7a 100644--- a/locales/ar/agent.json+++ b/locales/ar/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "يتم تخزين الملفات التي يرفقها الزوار في حسابك. تتوقف التحميلات بمجرد الوصول إلى هذا الحد؛ قم بتعيين 0 لإيقاف المرفقات.","share.settings.limits.maxFileStorageLabel": "حد تخزين الملفات","share.settings.limits.maxFileStorageWorkspaceHint": "يتم تخزين الملفات التي يرفقها الزوار في مساحة العمل. تتوقف التحميلات بمجرد الوصول إلى هذا الإجمالي؛ قم بتعيين 0 لإيقاف المرفقات.",- "share.settings.limits.maxTopicsPerVisitor": "المحادثات لكل زائر",- "share.settings.limits.maxTopicsPerVisitorHint": "عدد المحادثات المنفصلة التي يمكن لكل زائر مسجل الدخول أن يبدأها.",- "share.settings.limits.maxTopicsPerVisitorUnit": "مواضيع",- "share.settings.limits.maxTurnsPerTopic": "عدد الرسائل لكل محادثة",- "share.settings.limits.maxTurnsPerTopicHint": "عدد الرسائل التي يمكن للزائر إرسالها داخل محادثة واحدة.",- "share.settings.limits.maxTurnsPerTopicUnit": "تحولات","share.settings.limits.monthlySpendLimit": "الحد الأقصى للإنفاق الشهري","share.settings.limits.monthlySpendLimitHint": "تتوقف تشغيلات الزوار بمجرد أن يصل إنفاق هذا الشهر على هذا الوكيل إلى الحد الأقصى.","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "ما يمكن لتشغيل الزائر قراءته، وما يمكن للزائر رؤيته بالمقابل.","share.settings.permissions.showErrorDetails": "عرض تفاصيل الأخطاء للزوار","share.settings.permissions.showErrorDetailsHint": "معطل افتراضيًا: يرى الزوار إشعار فشل عام بدلاً من نص الخطأ الخام.",- "share.settings.permissions.showModelInfo": "عرض النموذج المستخدم",- "share.settings.permissions.showModelInfoHint": "معطل افتراضيًا: يظل اختيار النموذج والمزود الخاص بك مخفيًا.","share.settings.permissions.title": "الأذونات","share.settings.profile.demoCases.add": "إضافة مثال","share.settings.profile.demoCases.desc": "اكتب أمثلة ليجربها الزوار. هذه منفصلة عن الأسئلة الافتتاحية للوكيل.",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "قام المالك بإيقاف المشاركة مؤقتًا، لذا تم إيقاف الرسائل الجديدة.","share.visitor.errors.spendLimit": "وصل هذا الوكيل المشترك إلى حد الاستخدام الشهري الذي حدده منشئه. سيكون متاحًا مرة أخرى الشهر المقبل.","share.visitor.errors.stopFailed": "تعذر إيقاف التشغيل. يرجى المحاولة مرة أخرى.",- "share.visitor.errors.topicLimit": "لقد وصلت إلى حد المحادثات على هذا الوكيل المشترك.",- "share.visitor.errors.turnLimit": "وصلت هذه المحادثة إلى حد الرسائل. ابدأ محادثة جديدة للمتابعة.","share.visitor.errors.unavailable": "لم تعد هذه المحادثة متاحة. حاول التبديل إلى موضوع آخر أو بدء موضوع جديد.","share.visitor.input.placeholder": "أرسل رسالة إلى هذا الوكيل المشترك…","share.visitor.input.send": "إرسال",@@ -822,8 +812,6 @@"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": "على هذه الصفحة",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "قبل أن تبدأ","share.visitor.profile.terms.tools_one": "{{count}} أداة مفتوحة للزوار.","share.visitor.profile.terms.tools_other": "{{count}} أدوات مفتوحة للزوار.",- "share.visitor.profile.terms.topics": "يمكنك فتح ما يصل إلى {{count}} محادثات.",- "share.visitor.profile.terms.turns": "تسمح كل محادثة بما يصل إلى {{count}} أدوار.","share.visitor.profile.terms.uploads": "يمكنك إرفاق ملفات؛ يحتوي هذا الوكيل على {{size}} لتخزين الملفات للزوار.","share.visitor.profile.terms.uploadsOff": "تم تعطيل المرفقات.","share.visitor.profile.terms.visibilityCreator": "قام المنشئ بتفعيل مراجعة الجلسة، لذا يمكنه قراءة هذه المحادثة.",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "مهمة","share.visitor.profile.works.untitled": "عمل بدون عنوان","share.visitor.topBar.home": "اذهب إلى LobeHub الخاص بي",- "share.visitor.topics.empty": "لا توجد محادثات بعد",- "share.visitor.topics.new": "محادثة جديدة",- "share.visitor.topics.title": "المحادثات",- "share.visitor.topics.untitled": "محادثة بدون عنوان","share.visitor.upload.creatorStorageBlocked": "مساحة التحميل الخاصة بهذا الوكيل ممتلئة. اطلب من منشئه تحرير مساحة أو زيادة الحد.","share.visitor.upload.fileTooLarge": "يجب أن تكون الملفات أقل من {{max}}.","share.visitor.upload.tooManyFiles": "يمكنك إرفاق ما يصل إلى {{max}} ملفًا لكل رسالة.",diff --git a/locales/bg-BG/agent.json b/locales/bg-BG/agent.jsonindex 9b413f5718f..06c8be76c18 100644--- a/locales/bg-BG/agent.json+++ b/locales/bg-BG/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "Файловете, които посетителите прикачват, се съхраняват във вашия акаунт. Качването спира, когато достигне този лимит; задайте 0, за да изключите прикачените файлове.","share.settings.limits.maxFileStorageLabel": "Лимит за съхранение на файлове","share.settings.limits.maxFileStorageWorkspaceHint": "Файловете, които посетителите прикачват, се съхраняват в Работното пространство. Качванията спират, когато достигнат този общ обем; задайте 0, за да изключите прикачванията.",- "share.settings.limits.maxTopicsPerVisitor": "Разговори на посетител",- "share.settings.limits.maxTopicsPerVisitorHint": "Колко отделни разговора може да започне всеки влязъл посетител.",- "share.settings.limits.maxTopicsPerVisitorUnit": "теми",- "share.settings.limits.maxTurnsPerTopic": "Ходове на разговор",- "share.settings.limits.maxTurnsPerTopicHint": "Колко съобщения може да изпрати посетител в рамките на един разговор.",- "share.settings.limits.maxTurnsPerTopicUnit": "ходове","share.settings.limits.monthlySpendLimit": "Месечен лимит на разходите","share.settings.limits.monthlySpendLimitHint": "Използването от посетители спира, когато разходите за този агент достигнат зададения лимит за месеца.","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "Какво може да чете посетителят и какво може да види обратно.","share.settings.permissions.showErrorDetails": "Показвай подробности за грешките на посетителите","share.settings.permissions.showErrorDetailsHint": "Изключено по подразбиране: посетителите виждат общо съобщение за неуспех вместо подробен текст на грешката.",- "share.settings.permissions.showModelInfo": "Показвай кой модел се използва",- "share.settings.permissions.showModelInfoHint": "Изключено по подразбиране: вашият избор на модел и доставчик остава скрит.","share.settings.permissions.title": "Разрешения","share.settings.profile.demoCases.add": "Добавяне на пример","share.settings.profile.demoCases.desc": "Напишете примери, които посетителите да опитат. Те са отделни от началните въпроси на агента.",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "Собственикът е паузирал споделянето, така че новите съобщения са изключени.","share.visitor.errors.spendLimit": "Този споделен агент е достигнал месечния лимит на използване, зададен от създателя му. Той ще бъде наличен отново следващия месец.","share.visitor.errors.stopFailed": "Неуспешно спиране на използването. Моля, опитайте отново.",- "share.visitor.errors.topicLimit": "Достигнахте лимита на разговорите с този споделен агент.",- "share.visitor.errors.turnLimit": "Този разговор е достигнал лимита на ходовете. Започнете нов разговор, за да продължите.","share.visitor.errors.unavailable": "Този разговор вече не е наличен. Опитайте да преминете към друга тема или да започнете нова.","share.visitor.input.placeholder": "Изпратете съобщение до този споделен агент…","share.visitor.input.send": "Изпрати",@@ -822,8 +812,6 @@"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": "на тази страница",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "Преди да започнете","share.visitor.profile.terms.tools_one": "{{count}} инструмент е отворен за посетители.","share.visitor.profile.terms.tools_other": "{{count}} инструменти са отворени за посетители.",- "share.visitor.profile.terms.topics": "Можете да отворите до {{count}} разговора.",- "share.visitor.profile.terms.turns": "Всеки разговор позволява до {{count}} хода.","share.visitor.profile.terms.uploads": "Можете да прикачвате файлове; този Аджент има {{size}} за съхранение на файлове за посетители.","share.visitor.profile.terms.uploadsOff": "Прикачените файлове са изключени.","share.visitor.profile.terms.visibilityCreator": "Създателят е включил преглед на сесията, така че може да прочете този разговор.",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "Задача","share.visitor.profile.works.untitled": "Без заглавие","share.visitor.topBar.home": "Отидете в моя LobeHub",- "share.visitor.topics.empty": "Все още няма разговори",- "share.visitor.topics.new": "Нов разговор",- "share.visitor.topics.title": "Разговори",- "share.visitor.topics.untitled": "Без заглавие","share.visitor.upload.creatorStorageBlocked": "Пространството за качване на този Аджент е запълнено. Помолете създателя му да освободи място или да увеличи лимита.","share.visitor.upload.fileTooLarge": "Файловете трябва да са под {{max}}.","share.visitor.upload.tooManyFiles": "Можете да прикачите до {{max}} файла на съобщение.",diff --git a/locales/de-DE/agent.json b/locales/de-DE/agent.jsonindex 0f5620f2b3b..6ea27533a4a 100644--- a/locales/de-DE/agent.json+++ b/locales/de-DE/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "Dateien, die Besucher anhängen, werden in Ihrem Konto gespeichert. Uploads stoppen, sobald sie dieses Gesamtlimit erreichen; setzen Sie 0, um Anhänge zu deaktivieren.","share.settings.limits.maxFileStorageLabel": "Dateispeicherlimit","share.settings.limits.maxFileStorageWorkspaceHint": "Dateien, die Besucher anhängen, werden im Arbeitsbereich gespeichert. Uploads stoppen, sobald sie dieses Gesamtvolumen erreichen; setzen Sie 0, um Anhänge zu deaktivieren.",- "share.settings.limits.maxTopicsPerVisitor": "Gespräche pro Besucher",- "share.settings.limits.maxTopicsPerVisitorHint": "Wie viele separate Gespräche jeder angemeldete Besucher starten kann.",- "share.settings.limits.maxTopicsPerVisitorUnit": "Themen",- "share.settings.limits.maxTurnsPerTopic": "Beiträge pro Gespräch",- "share.settings.limits.maxTurnsPerTopicHint": "Wie viele Nachrichten ein Besucher innerhalb eines Gesprächs senden kann.",- "share.settings.limits.maxTurnsPerTopicUnit": "Züge","share.settings.limits.monthlySpendLimit": "Monatliches Ausgabenlimit","share.settings.limits.monthlySpendLimitHint": "Besuche werden gestoppt, sobald die monatlichen Ausgaben für diesen Agenten das Limit erreichen.","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "Was ein Besucher während eines Besuchs lesen darf und was der Besucher zurücksehen kann.","share.settings.permissions.showErrorDetails": "Fehlerdetails für Besucher anzeigen","share.settings.permissions.showErrorDetailsHint": "Standardmäßig deaktiviert: Besucher sehen eine allgemeine Fehlermeldung anstelle von Rohfehlertext.",- "share.settings.permissions.showModelInfo": "Anzeigen, welches Modell verwendet wird",- "share.settings.permissions.showModelInfoHint": "Standardmäßig deaktiviert: Ihre Modell- und Anbieterwahl bleibt verborgen.","share.settings.permissions.title": "Berechtigungen","share.settings.profile.demoCases.add": "Beispiel hinzufügen","share.settings.profile.demoCases.desc": "Schreiben Sie Beispiele, die Besucher ausprobieren können. Diese sind getrennt von den Eröffnungsfragen des Ajans.",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "Der Besitzer hat die Freigabe pausiert, daher sind neue Nachrichten deaktiviert.","share.visitor.errors.spendLimit": "Dieser freigegebene Agent hat das monatliche Nutzungslimit erreicht, das vom Ersteller festgelegt wurde. Er wird nächsten Monat wieder verfügbar sein.","share.visitor.errors.stopFailed": "Der Besuch konnte nicht gestoppt werden. Bitte versuchen Sie es erneut.",- "share.visitor.errors.topicLimit": "Sie haben das Gesprächslimit für diesen freigegebenen Agenten erreicht.",- "share.visitor.errors.turnLimit": "Dieses Gespräch hat das Beitragslimit erreicht. Starten Sie ein neues Gespräch, um fortzufahren.","share.visitor.errors.unavailable": "Dieses Gespräch ist nicht mehr verfügbar. Versuchen Sie, zu einem anderen Thema zu wechseln oder ein neues zu starten.","share.visitor.input.placeholder": "Nachricht an diesen freigegebenen Agenten…","share.visitor.input.send": "Senden",@@ -822,8 +812,6 @@"share.visitor.profile.metrics.lastDeliveredCaption": "neueste Aktualisierung","share.visitor.profile.metrics.tools": "Offene Werkzeuge","share.visitor.profile.metrics.toolsCaption": "für Sie verfügbar",- "share.visitor.profile.metrics.turns": "Jedes Gespräch",- "share.visitor.profile.metrics.turnsCaption": "maximal Züge","share.visitor.profile.metrics.unknown": "Noch keine Daten","share.visitor.profile.metrics.views": "Ansichten","share.visitor.profile.metrics.viewsCaption": "auf dieser Seite",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "Bevor Sie beginnen","share.visitor.profile.terms.tools_one": "{{count}} Werkzeug ist für Besucher geöffnet.","share.visitor.profile.terms.tools_other": "{{count}} Werkzeuge sind für Besucher geöffnet.",- "share.visitor.profile.terms.topics": "Sie können bis zu {{count}} Gespräche eröffnen.",- "share.visitor.profile.terms.turns": "Jedes Gespräch erlaubt bis zu {{count}} Züge.","share.visitor.profile.terms.uploads": "Sie können Dateien anhängen; dieser Ajan hat {{size}} Dateispeicher für Besucher.","share.visitor.profile.terms.uploadsOff": "Anhänge sind deaktiviert.","share.visitor.profile.terms.visibilityCreator": "Der Ersteller hat die Sitzungsüberprüfung aktiviert, sodass er dieses Gespräch lesen kann.",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "Aufgabe","share.visitor.profile.works.untitled": "Unbenannte Arbeit","share.visitor.topBar.home": "Gehe zu meinem LobeHub",- "share.visitor.topics.empty": "Noch keine Gespräche",- "share.visitor.topics.new": "Neues Gespräch",- "share.visitor.topics.title": "Gespräche",- "share.visitor.topics.untitled": "Unbenanntes Gespräch","share.visitor.upload.creatorStorageBlocked": "Der Upload-Speicherplatz dieses Ajans ist voll. Bitten Sie den Ersteller, Platz freizugeben oder das Limit zu erhöhen.","share.visitor.upload.fileTooLarge": "Dateien müssen unter {{max}} sein.","share.visitor.upload.tooManyFiles": "Sie können bis zu {{max}} Dateien pro Nachricht anhängen.",diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex b35c70a1a7a..b173b9e26dc 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -691,16 +691,16 @@"channel.wecom.secret": "Secret","channel.wecom.secretHint": "The bot's long-connection Secret. A bot can be connected in only one place at a time: saving here takes over a connection it has elsewhere, and connecting it elsewhere later disconnects it here.","share.entry": "Share this Agent",+ "share.settings.device.desc": "Choose who may run this Agent on your execution environment, for example to read files or run commands. Claude Code and Codex Agents run only there, so other visitors can’t use them. Chatting with the Agent doesn’t include device access.",+ "share.settings.device.title": "Device access",+ "share.settings.device.who": "Who can use your device","share.settings.limits.desc": "Every visitor run is billed to your account, so these caps are what keep a shared link from running up your bill. They always apply — you can change the numbers, but not turn them off.","share.settings.limits.maxFileStorageHint": "Files visitors attach are stored on your account. Uploads stop once they reach this total; set 0 to turn attachments off.","share.settings.limits.maxFileStorageLabel": "File storage limit","share.settings.limits.maxFileStorageWorkspaceHint": "Files visitors attach are stored in the Workspace. Uploads stop once they reach this total; set 0 to turn attachments off.",- "share.settings.limits.maxTopicsPerVisitor": "Topics per visitor",- "share.settings.limits.maxTopicsPerVisitorHint": "How many separate topics each signed-in visitor can start.",- "share.settings.limits.maxTopicsPerVisitorUnit": "topics",- "share.settings.limits.maxTurnsPerTopic": "Turns per topic",- "share.settings.limits.maxTurnsPerTopicHint": "How many messages a visitor can send inside one topic.",- "share.settings.limits.maxTurnsPerTopicUnit": "turns",+ "share.settings.limits.maxMessagesPerVisitor": "Messages per visitor",+ "share.settings.limits.maxMessagesPerVisitorHint": "How many messages each signed-in visitor can send to this Agent in total. The Agent’s replies don’t count.",+ "share.settings.limits.maxMessagesPerVisitorUnit": "messages","share.settings.limits.monthlySpendLimit": "Monthly spend cap","share.settings.limits.monthlySpendLimitHint": "Visitor runs stop once this month’s spend on this Agent reaches the cap. Resets on the 1st of each month (UTC).","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -738,14 +738,12 @@"share.settings.permissions.allowReadMemory": "Allow reading my memory","share.settings.permissions.allowReadMemoryHint": "The Agent may draw on your long-term memory while answering a visitor.","share.settings.permissions.desc": "What a visitor’s run may read, and what the visitor gets to see back.",- "share.settings.permissions.deviceAccess": "Execution environment","share.settings.permissions.deviceAccessConfirm.commands": "They can run any command and read or write any file on the machine this Agent runs on, including through Claude Code or Codex.","share.settings.permissions.deviceAccessConfirm.intro": "People you add will run this Agent on your execution environment:",- "share.settings.permissions.deviceAccessConfirm.limits": "The monthly spend cap does not limit that usage. Only the turn limit per topic does.",+ "share.settings.permissions.deviceAccessConfirm.messageLimit": "The monthly spend cap does not limit that usage. Only the message limit per visitor does.","share.settings.permissions.deviceAccessConfirm.ok": "Allow listed people","share.settings.permissions.deviceAccessConfirm.subscription": "Claude Code and Codex runs use the model subscription signed in on that machine.","share.settings.permissions.deviceAccessConfirm.title": "Let people use your execution environment?",- "share.settings.permissions.deviceAccessHint": "Lets the people you pick run this Agent on its execution environment, including Claude Code and Codex. Everyone else can’t run a Claude Code or Codex Agent.","share.settings.permissions.deviceAccessOption.allowlist": "People from contacts","share.settings.permissions.deviceAccessOption.none": "No visitors","share.settings.permissions.deviceAllowContactsUnavailable": "Only people in your contacts can be added, and contacts aren’t available for your account yet.",@@ -757,8 +755,6 @@"share.settings.permissions.deviceAllowUnlisted": "No longer in contacts, so they can’t use it: {{names}}. They’re removed the next time you edit this list.","share.settings.permissions.showErrorDetails": "Show error details to visitors","share.settings.permissions.showErrorDetailsHint": "Off by default: visitors see a generic failure notice instead of raw error text.",- "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.",@@ -847,6 +843,7 @@"share.visitor.access.signInCta": "Sign in","share.visitor.access.signInDesc": "Sign in to start chatting with this shared agent. Your topics stay tied to your account.","share.visitor.access.signInTitle": "Sign in to continue",+ "share.visitor.chat.channelsDisabled": "Chatting with shared agents isn't available for your account yet.","share.visitor.errors.fileUnavailable": "One of the attachments is no longer available. Remove it and try again.","share.visitor.errors.generic": "Failed to send the message. Please try again.","share.visitor.errors.heteroDeviceUnavailable": "The creator's device is offline. Try again later.",@@ -857,8 +854,6 @@"share.visitor.errors.sharingPaused": "The owner has paused sharing, so new messages are turned off.","share.visitor.errors.spendLimit": "This shared agent has reached its monthly usage limit set by its creator. It will be available again next month.","share.visitor.errors.stopFailed": "Couldn't stop the run. Please try again.",- "share.visitor.errors.topicLimit": "You have reached the topic limit on this shared agent.",- "share.visitor.errors.turnLimit": "This topic has reached its turn limit. Start a new topic to continue.","share.visitor.errors.unavailable": "This topic is no longer available. Try switching to another topic or starting a new one.","share.visitor.input.placeholder": "Message this shared agent…","share.visitor.input.send": "Send",@@ -886,8 +881,6 @@"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 topic",- "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",@@ -901,11 +894,11 @@"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.",+ "share.visitor.profile.terms.messages_one": "You can send up to {{count}} message.",+ "share.visitor.profile.terms.messages_other": "You can send up to {{count}} messages.","share.visitor.profile.terms.title": "Before you start","share.visitor.profile.terms.tools_one": "{{count}} tool is open to visitors.","share.visitor.profile.terms.tools_other": "{{count}} tools are open to visitors.",- "share.visitor.profile.terms.topics": "You can open up to {{count}} topics.",- "share.visitor.profile.terms.turns": "Each topic allows up to {{count}} turns.","share.visitor.profile.terms.uploads": "You can attach files; this Agent has {{size}} of file storage for visitors.","share.visitor.profile.terms.uploadsOff": "Attachments are turned off.","share.visitor.profile.terms.visibilityCreator": "The creator has turned on topic access and may read the messages in your topics.",@@ -920,10 +913,6 @@"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 topics yet",- "share.visitor.topics.new": "New topic",- "share.visitor.topics.title": "Topics",- "share.visitor.topics.untitled": "Untitled topic","share.visitor.upload.creatorStorageBlocked": "This Agent's upload space is full. Ask its creator to free up room or raise the cap.","share.visitor.upload.fileTooLarge": "Files must be under {{max}}.","share.visitor.upload.tooManyFiles": "You can attach up to {{max}} files per message.",diff --git a/locales/en-US/channel.json b/locales/en-US/channel.jsonindex 8c2602ce180..56d6390e823 100644--- a/locales/en-US/channel.json+++ b/locales/en-US/channel.json@@ -189,6 +189,10 @@"profile.view": "View profile","projectAgents": "Project Agents","receipt.errorReason": "Failure reason",+ "receipt.errorShareHeteroDevice": "The creator's device is offline. Try again later.",+ "receipt.errorShareHeteroUnsupported": "This Agent can run for you only with its creator's permission. Ask its creator for access.",+ "receipt.errorShareMessageLimit": "You have sent all the messages its creator allows to this shared Agent.",+ "receipt.errorShareSpendLimit": "This shared Agent reached the monthly usage limit its creator set. It will be available again next month.","receipt.errorUnavailable": "No detailed reason was recorded. Check the Agent’s model and device settings before sending again.","receipt.failedHint": "Mention it again to retry.","receipt.worktree": "Working in its own worktree · {{branch}}",diff --git a/locales/es-ES/agent.json b/locales/es-ES/agent.jsonindex 9015cca7005..6f337aa4af1 100644--- a/locales/es-ES/agent.json+++ b/locales/es-ES/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "Los archivos que los visitantes adjuntan se almacenan en tu cuenta. Las cargas se detienen una vez que alcanzan este total; establece 0 para desactivar los adjuntos.","share.settings.limits.maxFileStorageLabel": "Límite de almacenamiento de archivos","share.settings.limits.maxFileStorageWorkspaceHint": "Los archivos que los visitantes adjuntan se almacenan en el espacio de trabajo. Las cargas se detienen una vez que alcanzan este total; establece 0 para desactivar los adjuntos.",- "share.settings.limits.maxTopicsPerVisitor": "Conversaciones por visitante",- "share.settings.limits.maxTopicsPerVisitorHint": "Cuántas conversaciones separadas puede iniciar cada visitante registrado.",- "share.settings.limits.maxTopicsPerVisitorUnit": "temas",- "share.settings.limits.maxTurnsPerTopic": "Interacciones por conversación",- "share.settings.limits.maxTurnsPerTopicHint": "Cuántos mensajes puede enviar un visitante dentro de una conversación.",- "share.settings.limits.maxTurnsPerTopicUnit": "turnos","share.settings.limits.monthlySpendLimit": "Límite de gasto mensual","share.settings.limits.monthlySpendLimitHint": "Las ejecuciones de visitantes se detienen una vez que el gasto de este mes en este Agente alcanza el límite.","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "Qué puede leer una ejecución de visitante y qué puede ver el visitante a cambio.","share.settings.permissions.showErrorDetails": "Mostrar detalles de errores a los visitantes","share.settings.permissions.showErrorDetailsHint": "Desactivado por defecto: los visitantes ven un aviso genérico de error en lugar del texto del error.",- "share.settings.permissions.showModelInfo": "Mostrar qué modelo se utiliza",- "share.settings.permissions.showModelInfoHint": "Desactivado por defecto: tu elección de modelo y proveedor permanece oculta.","share.settings.permissions.title": "Permisos","share.settings.profile.demoCases.add": "Agregar ejemplo","share.settings.profile.demoCases.desc": "Escribe ejemplos para que los visitantes prueben. Estos son independientes de las preguntas iniciales del Ajan.",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "El propietario ha pausado el uso compartido, por lo que los nuevos mensajes están desactivados.","share.visitor.errors.spendLimit": "Este agente compartido ha alcanzado el límite de uso mensual establecido por su creador. Estará disponible nuevamente el próximo mes.","share.visitor.errors.stopFailed": "No se pudo detener la ejecución. Por favor, inténtalo de nuevo.",- "share.visitor.errors.topicLimit": "Has alcanzado el límite de conversaciones en este agente compartido.",- "share.visitor.errors.turnLimit": "Esta conversación ha alcanzado su límite de interacciones. Inicia una nueva conversación para continuar.","share.visitor.errors.unavailable": "Esta conversación ya no está disponible. Intenta cambiar a otro tema o iniciar uno nuevo.","share.visitor.input.placeholder": "Escribe un mensaje a este agente compartido…","share.visitor.input.send": "Enviar",@@ -822,8 +812,6 @@"share.visitor.profile.metrics.lastDeliveredCaption": "actualización más reciente","share.visitor.profile.metrics.tools": "Abrir herramientas","share.visitor.profile.metrics.toolsCaption": "disponibles para ti",- "share.visitor.profile.metrics.turns": "Cada conversación",- "share.visitor.profile.metrics.turnsCaption": "máximo de turnos","share.visitor.profile.metrics.unknown": "Aún no hay datos","share.visitor.profile.metrics.views": "Vistas","share.visitor.profile.metrics.viewsCaption": "en esta página",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "Antes de comenzar","share.visitor.profile.terms.tools_one": "{{count}} herramienta está abierta a los visitantes.","share.visitor.profile.terms.tools_other": "{{count}} herramientas están abiertas a los visitantes.",- "share.visitor.profile.terms.topics": "Puedes abrir hasta {{count}} conversaciones.",- "share.visitor.profile.terms.turns": "Cada conversación permite hasta {{count}} turnos.","share.visitor.profile.terms.uploads": "Puedes adjuntar archivos; este Ajan tiene {{size}} de almacenamiento de archivos para visitantes.","share.visitor.profile.terms.uploadsOff": "Los adjuntos están desactivados.","share.visitor.profile.terms.visibilityCreator": "El creador ha activado la revisión de sesiones, por lo que puede leer esta conversación.",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "Tarea","share.visitor.profile.works.untitled": "Trabajo sin título","share.visitor.topBar.home": "Ir a mi LobeHub",- "share.visitor.topics.empty": "Aún no hay conversaciones",- "share.visitor.topics.new": "Nueva conversación",- "share.visitor.topics.title": "Conversaciones",- "share.visitor.topics.untitled": "Conversación sin título","share.visitor.upload.creatorStorageBlocked": "El espacio de carga de este Ajan está lleno. Pide a su creador que libere espacio o aumente el límite.","share.visitor.upload.fileTooLarge": "Los archivos deben ser menores de {{max}}.","share.visitor.upload.tooManyFiles": "Puedes adjuntar hasta {{max}} archivos por mensaje.",diff --git a/locales/fa-IR/agent.json b/locales/fa-IR/agent.jsonindex cf17e679482..ac2cf720a62 100644--- a/locales/fa-IR/agent.json+++ b/locales/fa-IR/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "فایلهایی که بازدیدکنندگان پیوست میکنند در حساب شما ذخیره میشوند. آپلودها زمانی متوقف میشوند که به این مقدار برسند؛ برای غیرفعال کردن پیوستها مقدار 0 را تنظیم کنید.","share.settings.limits.maxFileStorageLabel": "محدودیت ذخیرهسازی فایل","share.settings.limits.maxFileStorageWorkspaceHint": "فایلهایی که بازدیدکنندگان پیوست میکنند در فضای کاری ذخیره میشوند. بارگذاریها زمانی که به این مقدار کل برسند متوقف میشوند؛ برای غیرفعال کردن پیوستها مقدار 0 را تنظیم کنید.",- "share.settings.limits.maxTopicsPerVisitor": "مکالمات به ازای هر بازدیدکننده",- "share.settings.limits.maxTopicsPerVisitorHint": "تعداد مکالمات جداگانهای که هر بازدیدکننده وارد شده میتواند شروع کند.",- "share.settings.limits.maxTopicsPerVisitorUnit": "موضوعات",- "share.settings.limits.maxTurnsPerTopic": "تعداد پیامها در هر مکالمه",- "share.settings.limits.maxTurnsPerTopicHint": "تعداد پیامهایی که یک بازدیدکننده میتواند در یک مکالمه ارسال کند.",- "share.settings.limits.maxTurnsPerTopicUnit": "نوبتها","share.settings.limits.monthlySpendLimit": "سقف هزینه ماهانه","share.settings.limits.monthlySpendLimitHint": "اجرای بازدیدکنندگان متوقف میشود وقتی هزینه این عامل در این ماه به سقف تعیینشده برسد.","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "آنچه اجرای بازدیدکننده ممکن است بخواند و آنچه بازدیدکننده میتواند ببیند.","share.settings.permissions.showErrorDetails": "نمایش جزئیات خطا به بازدیدکنندگان","share.settings.permissions.showErrorDetailsHint": "بهطور پیشفرض غیرفعال: بازدیدکنندگان یک اعلان عمومی شکست را میبینند بهجای متن خام خطا.",- "share.settings.permissions.showModelInfo": "نمایش مدل مورد استفاده",- "share.settings.permissions.showModelInfoHint": "بهطور پیشفرض غیرفعال: انتخاب مدل و ارائهدهنده شما مخفی میماند.","share.settings.permissions.title": "مجوزها","share.settings.profile.demoCases.add": "افزودن مثال","share.settings.profile.demoCases.desc": "مثالهایی برای بازدیدکنندگان بنویسید تا امتحان کنند. اینها جدا از سوالات ابتدایی آژان هستند.",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "مالک اشتراکگذاری را متوقف کرده است، بنابراین پیامهای جدید غیرفعال شدهاند.","share.visitor.errors.spendLimit": "این عامل مشترک به محدودیت استفاده ماهانه تعیینشده توسط سازنده خود رسیده است. ماه آینده دوباره در دسترس خواهد بود.","share.visitor.errors.stopFailed": "متوقف کردن اجرا شکست خورد. لطفاً دوباره تلاش کنید.",- "share.visitor.errors.topicLimit": "شما به محدودیت مکالمه در این عامل مشترک رسیدهاید.",- "share.visitor.errors.turnLimit": "این مکالمه به محدودیت پیامهای خود رسیده است. برای ادامه یک مکالمه جدید شروع کنید.","share.visitor.errors.unavailable": "این مکالمه دیگر در دسترس نیست. سعی کنید به موضوع دیگری تغییر دهید یا یک مکالمه جدید شروع کنید.","share.visitor.input.placeholder": "پیام به این عامل مشترک...","share.visitor.input.send": "ارسال",@@ -822,8 +812,6 @@"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": "در این صفحه",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "قبل از شروع","share.visitor.profile.terms.tools_one": "{{count}} ابزار برای بازدیدکنندگان باز است.","share.visitor.profile.terms.tools_other": "{{count}} ابزار برای بازدیدکنندگان باز است.",- "share.visitor.profile.terms.topics": "میتوانید تا {{count}} گفتگو را باز کنید.",- "share.visitor.profile.terms.turns": "هر گفتگو حداکثر {{count}} نوبت دارد.","share.visitor.profile.terms.uploads": "میتوانید فایلها را پیوست کنید؛ این Ajan دارای {{size}} فضای ذخیرهسازی فایل برای بازدیدکنندگان است.","share.visitor.profile.terms.uploadsOff": "پیوستها غیرفعال هستند.","share.visitor.profile.terms.visibilityCreator": "سازنده بازبینی جلسه را فعال کرده است، بنابراین میتواند این گفتگو را بخواند.",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "وظیفه","share.visitor.profile.works.untitled": "اثر بدون عنوان","share.visitor.topBar.home": "رفتن به LobeHub من",- "share.visitor.topics.empty": "هنوز هیچ مکالمهای وجود ندارد",- "share.visitor.topics.new": "مکالمه جدید",- "share.visitor.topics.title": "مکالمات",- "share.visitor.topics.untitled": "مکالمه بدون عنوان","share.visitor.upload.creatorStorageBlocked": "فضای آپلود این Ajan پر است. از سازنده آن بخواهید فضا را آزاد کند یا محدودیت را افزایش دهد.","share.visitor.upload.fileTooLarge": "فایلها باید کمتر از {{max}} باشند.","share.visitor.upload.tooManyFiles": "میتوانید حداکثر {{max}} فایل در هر پیام پیوست کنید.",diff --git a/locales/fr-FR/agent.json b/locales/fr-FR/agent.jsonindex a44244fbc60..11de4d9f212 100644--- a/locales/fr-FR/agent.json+++ b/locales/fr-FR/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "Les fichiers que les visiteurs joignent sont stockés sur votre compte. Les téléchargements s'arrêtent une fois ce total atteint ; définissez 0 pour désactiver les pièces jointes.","share.settings.limits.maxFileStorageLabel": "Limite de stockage de fichiers","share.settings.limits.maxFileStorageWorkspaceHint": "Les fichiers attachés par les visiteurs sont stockés dans l'espace de travail. Les téléchargements s'arrêtent une fois cette limite atteinte ; définissez 0 pour désactiver les pièces jointes.",- "share.settings.limits.maxTopicsPerVisitor": "Conversations par visiteur",- "share.settings.limits.maxTopicsPerVisitorHint": "Nombre de conversations distinctes que chaque visiteur connecté peut démarrer.",- "share.settings.limits.maxTopicsPerVisitorUnit": "sujets",- "share.settings.limits.maxTurnsPerTopic": "Tours par conversation",- "share.settings.limits.maxTurnsPerTopicHint": "Nombre de messages qu'un visiteur peut envoyer dans une conversation.",- "share.settings.limits.maxTurnsPerTopicUnit": "tours","share.settings.limits.monthlySpendLimit": "Plafond de dépenses mensuel","share.settings.limits.monthlySpendLimitHint": "Les exécutions des visiteurs s'arrêtent une fois que les dépenses de ce mois pour cet Agent atteignent le plafond.","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "Ce qu'une exécution par un visiteur peut lire, et ce que le visiteur peut voir en retour.","share.settings.permissions.showErrorDetails": "Afficher les détails des erreurs aux visiteurs","share.settings.permissions.showErrorDetailsHint": "Désactivé par défaut : les visiteurs voient un message d'échec générique au lieu du texte brut de l'erreur.",- "share.settings.permissions.showModelInfo": "Afficher le modèle utilisé",- "share.settings.permissions.showModelInfoHint": "Désactivé par défaut : votre choix de modèle et de fournisseur reste caché.","share.settings.permissions.title": "Autorisations","share.settings.profile.demoCases.add": "Ajouter un exemple","share.settings.profile.demoCases.desc": "Rédigez des exemples pour que les visiteurs puissent les essayer. Ceux-ci sont distincts des questions d'ouverture de l'ajan.",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "Le propriétaire a suspendu le partage, donc les nouveaux messages sont désactivés.","share.visitor.errors.spendLimit": "Cet agent partagé a atteint la limite d'utilisation mensuelle définie par son créateur. Il sera à nouveau disponible le mois prochain.","share.visitor.errors.stopFailed": "Impossible d'arrêter l'exécution. Veuillez réessayer.",- "share.visitor.errors.topicLimit": "Vous avez atteint la limite de conversations sur cet agent partagé.",- "share.visitor.errors.turnLimit": "Cette conversation a atteint sa limite de tours. Démarrez une nouvelle conversation pour continuer.","share.visitor.errors.unavailable": "Cette conversation n'est plus disponible. Essayez de passer à un autre sujet ou de démarrer une nouvelle conversation.","share.visitor.input.placeholder": "Envoyer un message à cet agent partagé…","share.visitor.input.send": "Envoyer",@@ -822,8 +812,6 @@"share.visitor.profile.metrics.lastDeliveredCaption": "mise à jour la plus récente","share.visitor.profile.metrics.tools": "Ouvrir les outils","share.visitor.profile.metrics.toolsCaption": "disponibles pour vous",- "share.visitor.profile.metrics.turns": "Chaque conversation",- "share.visitor.profile.metrics.turnsCaption": "tours au maximum","share.visitor.profile.metrics.unknown": "Pas encore de données","share.visitor.profile.metrics.views": "Vues","share.visitor.profile.metrics.viewsCaption": "sur cette page",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "Avant de commencer","share.visitor.profile.terms.tools_one": "{{count}} outil est ouvert aux visiteurs.","share.visitor.profile.terms.tools_other": "{{count}} outils sont ouverts aux visiteurs.",- "share.visitor.profile.terms.topics": "Vous pouvez ouvrir jusqu'à {{count}} conversations.",- "share.visitor.profile.terms.turns": "Chaque conversation permet jusqu'à {{count}} tours.","share.visitor.profile.terms.uploads": "Vous pouvez joindre des fichiers ; cet Ajan dispose de {{size}} de stockage de fichiers pour les visiteurs.","share.visitor.profile.terms.uploadsOff": "Les pièces jointes sont désactivées.","share.visitor.profile.terms.visibilityCreator": "Le créateur a activé la révision de session, il peut donc lire cette conversation.",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "Tâche","share.visitor.profile.works.untitled": "Travail sans titre","share.visitor.topBar.home": "Aller à mon LobeHub",- "share.visitor.topics.empty": "Aucune conversation pour le moment",- "share.visitor.topics.new": "Nouvelle conversation",- "share.visitor.topics.title": "Conversations",- "share.visitor.topics.untitled": "Conversation sans titre","share.visitor.upload.creatorStorageBlocked": "L'espace de téléchargement de cet Ajan est plein. Demandez à son créateur de libérer de l'espace ou d'augmenter la limite.","share.visitor.upload.fileTooLarge": "Les fichiers doivent être inférieurs à {{max}}.","share.visitor.upload.tooManyFiles": "Vous pouvez joindre jusqu'à {{max}} fichiers par message.",diff --git a/locales/it-IT/agent.json b/locales/it-IT/agent.jsonindex dca358c7c01..82ce46e0072 100644--- a/locales/it-IT/agent.json+++ b/locales/it-IT/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "I file allegati dai visitatori sono archiviati nel tuo account. I caricamenti si interrompono una volta raggiunto questo totale; imposta 0 per disattivare gli allegati.","share.settings.limits.maxFileStorageLabel": "Limite di archiviazione file","share.settings.limits.maxFileStorageWorkspaceHint": "I file allegati dai visitatori sono archiviati nel Workspace. I caricamenti si interrompono una volta raggiunto questo totale; impostare 0 per disattivare gli allegati.",- "share.settings.limits.maxTopicsPerVisitor": "Conversazioni per visitatore",- "share.settings.limits.maxTopicsPerVisitorHint": "Quante conversazioni separate ogni visitatore registrato può avviare.",- "share.settings.limits.maxTopicsPerVisitorUnit": "argomenti",- "share.settings.limits.maxTurnsPerTopic": "Messaggi per conversazione",- "share.settings.limits.maxTurnsPerTopicHint": "Quanti messaggi un visitatore può inviare all'interno di una conversazione.",- "share.settings.limits.maxTurnsPerTopicUnit": "turni","share.settings.limits.monthlySpendLimit": "Limite di spesa mensile","share.settings.limits.monthlySpendLimitHint": "Le esecuzioni dei visitatori si interrompono una volta che la spesa di questo mese per questo Agente raggiunge il limite.","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "Cosa può leggere l'esecuzione di un visitatore e cosa il visitatore può vedere in risposta.","share.settings.permissions.showErrorDetails": "Mostra i dettagli degli errori ai visitatori","share.settings.permissions.showErrorDetailsHint": "Disattivato per impostazione predefinita: i visitatori vedono un avviso generico di errore invece del testo dell'errore.",- "share.settings.permissions.showModelInfo": "Mostra quale modello viene utilizzato",- "share.settings.permissions.showModelInfoHint": "Disattivato per impostazione predefinita: la tua scelta di modello e provider rimane nascosta.","share.settings.permissions.title": "Permessi","share.settings.profile.demoCases.add": "Aggiungi esempio","share.settings.profile.demoCases.desc": "Scrivi esempi per i visitatori da provare. Questi sono separati dalle domande iniziali dell'ajan.",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "Il proprietario ha messo in pausa la condivisione, quindi i nuovi messaggi sono disattivati.","share.visitor.errors.spendLimit": "Questo agente condiviso ha raggiunto il limite di utilizzo mensile impostato dal suo creatore. Sarà di nuovo disponibile il mese prossimo.","share.visitor.errors.stopFailed": "Impossibile interrompere l'esecuzione. Riprova.",- "share.visitor.errors.topicLimit": "Hai raggiunto il limite di conversazioni su questo agente condiviso.",- "share.visitor.errors.turnLimit": "Questa conversazione ha raggiunto il limite di messaggi. Avvia una nuova conversazione per continuare.","share.visitor.errors.unavailable": "Questa conversazione non è più disponibile. Prova a passare a un altro argomento o a iniziarne uno nuovo.","share.visitor.input.placeholder": "Invia un messaggio a questo agente condiviso…","share.visitor.input.send": "Invia",@@ -822,8 +812,6 @@"share.visitor.profile.metrics.lastDeliveredCaption": "aggiornamento più recente","share.visitor.profile.metrics.tools": "Apri strumenti","share.visitor.profile.metrics.toolsCaption": "disponibili per te",- "share.visitor.profile.metrics.turns": "Ogni conversazione",- "share.visitor.profile.metrics.turnsCaption": "massimo di turni","share.visitor.profile.metrics.unknown": "Nessun dato ancora","share.visitor.profile.metrics.views": "Visualizzazioni","share.visitor.profile.metrics.viewsCaption": "su questa pagina",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "Prima di iniziare","share.visitor.profile.terms.tools_one": "{{count}} strumento è aperto ai visitatori.","share.visitor.profile.terms.tools_other": "{{count}} strumenti sono aperti ai visitatori.",- "share.visitor.profile.terms.topics": "Puoi aprire fino a {{count}} conversazioni.",- "share.visitor.profile.terms.turns": "Ogni conversazione consente fino a {{count}} turni.","share.visitor.profile.terms.uploads": "Puoi allegare file; questo Ajan ha {{size}} di spazio di archiviazione file per i visitatori.","share.visitor.profile.terms.uploadsOff": "Gli allegati sono disattivati.","share.visitor.profile.terms.visibilityCreator": "Il creatore ha attivato la revisione della sessione, quindi può leggere questa conversazione.",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "Compito","share.visitor.profile.works.untitled": "Lavoro senza titolo","share.visitor.topBar.home": "Vai al mio LobeHub",- "share.visitor.topics.empty": "Nessuna conversazione ancora",- "share.visitor.topics.new": "Nuova conversazione",- "share.visitor.topics.title": "Conversazioni",- "share.visitor.topics.untitled": "Conversazione senza titolo","share.visitor.upload.creatorStorageBlocked": "Lo spazio di caricamento di questo Ajan è pieno. Chiedi al suo creatore di liberare spazio o aumentare il limite.","share.visitor.upload.fileTooLarge": "I file devono essere inferiori a {{max}}.","share.visitor.upload.tooManyFiles": "Puoi allegare fino a {{max}} file per messaggio.",diff --git a/locales/ja-JP/agent.json b/locales/ja-JP/agent.jsonindex e44439d18c4..4b53ab365bc 100644--- a/locales/ja-JP/agent.json+++ b/locales/ja-JP/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "訪問者が添付するファイルはあなたのアカウントに保存されます。アップロードはこの合計に達すると停止します。添付ファイルを無効にするには0を設定してください。","share.settings.limits.maxFileStorageLabel": "ファイルストレージの制限","share.settings.limits.maxFileStorageWorkspaceHint": "訪問者が添付するファイルはワークスペースに保存されます。アップロードはこの合計に達すると停止します。0に設定すると添付ファイルを無効にします。",- "share.settings.limits.maxTopicsPerVisitor": "訪問者ごとの会話数",- "share.settings.limits.maxTopicsPerVisitorHint": "サインインした訪問者が開始できる個別の会話の数。",- "share.settings.limits.maxTopicsPerVisitorUnit": "トピック",- "share.settings.limits.maxTurnsPerTopic": "会話ごとのターン数",- "share.settings.limits.maxTurnsPerTopicHint": "1つの会話内で訪問者が送信できるメッセージの数。",- "share.settings.limits.maxTurnsPerTopicUnit": "ターン","share.settings.limits.monthlySpendLimit": "月間支出上限","share.settings.limits.monthlySpendLimitHint": "このエージェントに対する今月の支出が上限に達すると、訪問者の実行が停止します。","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "訪問者の実行が読み取れる内容と、訪問者が見られる内容。","share.settings.permissions.showErrorDetails": "訪問者にエラーの詳細を表示","share.settings.permissions.showErrorDetailsHint": "デフォルトではオフ: 訪問者には一般的な失敗通知が表示され、生のエラーテキストは表示されません。",- "share.settings.permissions.showModelInfo": "使用されているモデルを表示",- "share.settings.permissions.showModelInfoHint": "デフォルトではオフ: モデルとプロバイダーの選択は非表示のままです。","share.settings.permissions.title": "権限","share.settings.profile.demoCases.add": "例を追加","share.settings.profile.demoCases.desc": "訪問者が試すための例を作成します。これらはエージェントの開始質問とは別です。",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "所有者が共有を一時停止しているため、新しいメッセージは送信できません。","share.visitor.errors.spendLimit": "この共有エージェントは作成者が設定した月間使用制限に達しました。来月再び利用可能になります。","share.visitor.errors.stopFailed": "実行を停止できませんでした。再試行してください。",- "share.visitor.errors.topicLimit": "この共有エージェントでの会話制限に達しました。",- "share.visitor.errors.turnLimit": "この会話はターン制限に達しました。新しい会話を開始して続行してください。","share.visitor.errors.unavailable": "この会話はもう利用できません。別のトピックに切り替えるか、新しい会話を開始してください。","share.visitor.input.placeholder": "この共有エージェントにメッセージを送信…","share.visitor.input.send": "送信",@@ -822,8 +812,6 @@"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": "このページの閲覧数",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "始める前に","share.visitor.profile.terms.tools_one": "{{count}} つのツールが訪問者に公開されています。","share.visitor.profile.terms.tools_other": "{{count}} つのツールが訪問者に公開されています。",- "share.visitor.profile.terms.topics": "最大 {{count}} 件の会話を開くことができます。",- "share.visitor.profile.terms.turns": "各会話で最大 {{count}} ターンが可能です。","share.visitor.profile.terms.uploads": "ファイルを添付できます。このエージェントには訪問者用に{{size}}のファイルストレージがあります。","share.visitor.profile.terms.uploadsOff": "添付ファイルは無効になっています。","share.visitor.profile.terms.visibilityCreator": "作成者がセッションレビューを有効にしているため、この会話を読むことができます。",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "タスク","share.visitor.profile.works.untitled": "無題の作品","share.visitor.topBar.home": "私のLobeHubに移動",- "share.visitor.topics.empty": "まだ会話がありません",- "share.visitor.topics.new": "新しい会話",- "share.visitor.topics.title": "会話",- "share.visitor.topics.untitled": "無題の会話","share.visitor.upload.creatorStorageBlocked": "このエージェントのアップロードスペースがいっぱいです。作成者に空き容量を確保するか、制限を引き上げるよう依頼してください。","share.visitor.upload.fileTooLarge": "ファイルは{{max}}以下である必要があります。","share.visitor.upload.tooManyFiles": "1メッセージにつき最大{{max}}ファイルを添付できます。",diff --git a/locales/ko-KR/agent.json b/locales/ko-KR/agent.jsonindex cdc140a56f0..faa8f8bb36e 100644--- a/locales/ko-KR/agent.json+++ b/locales/ko-KR/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "방문자가 첨부한 파일은 귀하의 계정에 저장됩니다. 업로드는 총 한도에 도달하면 중지됩니다. 첨부 파일을 비활성화하려면 0으로 설정하세요.","share.settings.limits.maxFileStorageLabel": "파일 저장 한도","share.settings.limits.maxFileStorageWorkspaceHint": "방문자가 첨부한 파일은 작업 공간에 저장됩니다. 업로드는 총 용량에 도달하면 중지됩니다. 첨부 파일을 비활성화하려면 0으로 설정하세요.",- "share.settings.limits.maxTopicsPerVisitor": "방문자당 대화 수",- "share.settings.limits.maxTopicsPerVisitorHint": "로그인한 각 방문자가 시작할 수 있는 별도의 대화 수입니다.",- "share.settings.limits.maxTopicsPerVisitorUnit": "주제",- "share.settings.limits.maxTurnsPerTopic": "대화당 메시지 수",- "share.settings.limits.maxTurnsPerTopicHint": "방문자가 하나의 대화에서 보낼 수 있는 메시지 수입니다.",- "share.settings.limits.maxTurnsPerTopicUnit": "턴","share.settings.limits.monthlySpendLimit": "월간 지출 한도","share.settings.limits.monthlySpendLimitHint": "이 에이전트에 대한 이번 달 지출이 한도에 도달하면 방문자 실행이 중지됩니다.","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "방문자의 실행이 읽을 수 있는 것과 방문자가 볼 수 있는 것.","share.settings.permissions.showErrorDetails": "방문자에게 오류 세부 정보 표시","share.settings.permissions.showErrorDetailsHint": "기본적으로 꺼져 있음: 방문자는 원시 오류 텍스트 대신 일반적인 실패 알림을 봅니다.",- "share.settings.permissions.showModelInfo": "사용 중인 모델 표시",- "share.settings.permissions.showModelInfoHint": "기본적으로 꺼져 있음: 귀하의 모델 및 제공자 선택이 숨겨집니다.","share.settings.permissions.title": "권한","share.settings.profile.demoCases.add": "예제 추가","share.settings.profile.demoCases.desc": "방문자가 시도할 예제를 작성하세요. 이는 에이전트의 시작 질문과는 별개입니다.",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "소유자가 공유를 일시 중지했으므로 새 메시지가 비활성화되었습니다.","share.visitor.errors.spendLimit": "이 공유 에이전트는 생성자가 설정한 월간 사용 한도에 도달했습니다. 다음 달에 다시 사용할 수 있습니다.","share.visitor.errors.stopFailed": "실행을 중지할 수 없습니다. 다시 시도하십시오.",- "share.visitor.errors.topicLimit": "이 공유 에이전트에서 대화 한도에 도달했습니다.",- "share.visitor.errors.turnLimit": "이 대화는 메시지 한도에 도달했습니다. 새 대화를 시작하여 계속하십시오.","share.visitor.errors.unavailable": "이 대화는 더 이상 사용할 수 없습니다. 다른 주제로 전환하거나 새 대화를 시작해 보십시오.","share.visitor.input.placeholder": "이 공유 에이전트에게 메시지 보내기…","share.visitor.input.send": "보내기",@@ -822,8 +812,6 @@"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": "이 페이지에서",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "시작하기 전에","share.visitor.profile.terms.tools_one": "방문자에게 {{count}}개의 도구가 열려 있습니다.","share.visitor.profile.terms.tools_other": "방문자에게 {{count}}개의 도구가 열려 있습니다.",- "share.visitor.profile.terms.topics": "최대 {{count}}개의 대화를 열 수 있습니다.",- "share.visitor.profile.terms.turns": "각 대화는 최대 {{count}} 턴까지 가능합니다.","share.visitor.profile.terms.uploads": "파일을 첨부할 수 있습니다. 이 Ajan은 방문자를 위해 {{size}}의 파일 저장 공간을 제공합니다.","share.visitor.profile.terms.uploadsOff": "첨부 파일이 비활성화되었습니다.","share.visitor.profile.terms.visibilityCreator": "제작자가 세션 검토를 활성화했으므로 이 대화를 읽을 수 있습니다.",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "작업","share.visitor.profile.works.untitled": "제목 없는 작업","share.visitor.topBar.home": "내 LobeHub로 이동",- "share.visitor.topics.empty": "아직 대화가 없습니다",- "share.visitor.topics.new": "새 대화",- "share.visitor.topics.title": "대화",- "share.visitor.topics.untitled": "제목 없는 대화","share.visitor.upload.creatorStorageBlocked": "이 Ajan의 업로드 공간이 가득 찼습니다. 생성자에게 공간을 확보하거나 한도를 늘려달라고 요청하세요.","share.visitor.upload.fileTooLarge": "파일은 {{max}} 이하이어야 합니다.","share.visitor.upload.tooManyFiles": "메시지당 최대 {{max}}개의 파일을 첨부할 수 있습니다.",diff --git a/locales/nl-NL/agent.json b/locales/nl-NL/agent.jsonindex 52947707fe5..df36976ac5a 100644--- a/locales/nl-NL/agent.json+++ b/locales/nl-NL/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "Bestanden die bezoekers bijvoegen worden opgeslagen op uw account. Uploads stoppen zodra ze deze limiet bereiken; stel in op 0 om bijlagen uit te schakelen.","share.settings.limits.maxFileStorageLabel": "Bestandsopslaglimiet","share.settings.limits.maxFileStorageWorkspaceHint": "Bestanden die bezoekers bijvoegen, worden opgeslagen in de Werkruimte. Uploads stoppen zodra ze dit totaal bereiken; stel in op 0 om bijlagen uit te schakelen.",- "share.settings.limits.maxTopicsPerVisitor": "Gesprekken per bezoeker",- "share.settings.limits.maxTopicsPerVisitorHint": "Hoeveel afzonderlijke gesprekken elke ingelogde bezoeker kan starten.",- "share.settings.limits.maxTopicsPerVisitorUnit": "onderwerpen",- "share.settings.limits.maxTurnsPerTopic": "Beurten per gesprek",- "share.settings.limits.maxTurnsPerTopicHint": "Hoeveel berichten een bezoeker kan verzenden binnen één gesprek.",- "share.settings.limits.maxTurnsPerTopicUnit": "beurten","share.settings.limits.monthlySpendLimit": "Maandelijkse uitgavelimiet","share.settings.limits.monthlySpendLimitHint": "Bezoekersacties stoppen zodra de uitgaven voor deze Agent deze maand de limiet bereiken.","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "Wat een bezoeker mag lezen tijdens een actie, en wat de bezoeker te zien krijgt.","share.settings.permissions.showErrorDetails": "Foutdetails tonen aan bezoekers","share.settings.permissions.showErrorDetailsHint": "Standaard uitgeschakeld: bezoekers zien een algemene foutmelding in plaats van de ruwe fouttekst.",- "share.settings.permissions.showModelInfo": "Toon welk model wordt gebruikt",- "share.settings.permissions.showModelInfoHint": "Standaard uitgeschakeld: uw model- en providerkeuze blijft verborgen.","share.settings.permissions.title": "Toestemmingen","share.settings.profile.demoCases.add": "Voorbeeld toevoegen","share.settings.profile.demoCases.desc": "Schrijf voorbeelden voor bezoekers om te proberen. Deze zijn apart van de openingsvragen van de Ajan.",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "De eigenaar heeft het delen gepauzeerd, dus nieuwe berichten zijn uitgeschakeld.","share.visitor.errors.spendLimit": "Deze gedeelde agent heeft de maandelijkse gebruikslimiet bereikt die door de maker is ingesteld. Het zal volgende maand weer beschikbaar zijn.","share.visitor.errors.stopFailed": "Kon de actie niet stoppen. Probeer het opnieuw.",- "share.visitor.errors.topicLimit": "U heeft de gesprekslimiet bereikt op deze gedeelde agent.",- "share.visitor.errors.turnLimit": "Dit gesprek heeft de beurtenlimiet bereikt. Start een nieuw gesprek om door te gaan.","share.visitor.errors.unavailable": "Dit gesprek is niet langer beschikbaar. Probeer over te schakelen naar een ander onderwerp of een nieuw gesprek te starten.","share.visitor.input.placeholder": "Stuur een bericht naar deze gedeelde agent…","share.visitor.input.send": "Verzenden",@@ -822,8 +812,6 @@"share.visitor.profile.metrics.lastDeliveredCaption": "meest recente update","share.visitor.profile.metrics.tools": "Open tools","share.visitor.profile.metrics.toolsCaption": "beschikbaar voor jou",- "share.visitor.profile.metrics.turns": "Elk gesprek",- "share.visitor.profile.metrics.turnsCaption": "maximaal aantal beurten","share.visitor.profile.metrics.unknown": "Nog geen gegevens","share.visitor.profile.metrics.views": "Weergaven","share.visitor.profile.metrics.viewsCaption": "op deze pagina",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "Voordat je begint","share.visitor.profile.terms.tools_one": "{{count}} tool is open voor bezoekers.","share.visitor.profile.terms.tools_other": "{{count}} tools zijn open voor bezoekers.",- "share.visitor.profile.terms.topics": "Je kunt maximaal {{count}} gesprekken openen.",- "share.visitor.profile.terms.turns": "Elk gesprek staat maximaal {{count}} beurten toe.","share.visitor.profile.terms.uploads": "U kunt bestanden bijvoegen; deze Ajan heeft {{size}} aan bestandsopslag voor bezoekers.","share.visitor.profile.terms.uploadsOff": "Bijlagen zijn uitgeschakeld.","share.visitor.profile.terms.visibilityCreator": "De maker heeft sessiebeoordeling ingeschakeld, zodat ze dit gesprek kunnen lezen.",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "Taak","share.visitor.profile.works.untitled": "Naamloos werk","share.visitor.topBar.home": "Ga naar mijn LobeHub",- "share.visitor.topics.empty": "Nog geen gesprekken",- "share.visitor.topics.new": "Nieuw gesprek",- "share.visitor.topics.title": "Gesprekken",- "share.visitor.topics.untitled": "Naamloos gesprek","share.visitor.upload.creatorStorageBlocked": "De uploadruimte van deze Ajan is vol. Vraag de maker om ruimte vrij te maken of de limiet te verhogen.","share.visitor.upload.fileTooLarge": "Bestanden moeten kleiner zijn dan {{max}}.","share.visitor.upload.tooManyFiles": "U kunt maximaal {{max}} bestanden per bericht bijvoegen.",diff --git a/locales/pl-PL/agent.json b/locales/pl-PL/agent.jsonindex 9e13b96726c..7aa13b3a4b5 100644--- a/locales/pl-PL/agent.json+++ b/locales/pl-PL/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "Pliki dołączane przez odwiedzających są przechowywane na Twoim koncie. Przesyłanie zostaje zatrzymane po osiągnięciu tego limitu; ustaw 0, aby wyłączyć załączniki.","share.settings.limits.maxFileStorageLabel": "Limit przechowywania plików","share.settings.limits.maxFileStorageWorkspaceHint": "Pliki załączone przez odwiedzających są przechowywane w obszarze roboczym. Przesyłanie zostaje zatrzymane po osiągnięciu tego limitu; ustaw 0, aby wyłączyć załączniki.",- "share.settings.limits.maxTopicsPerVisitor": "Rozmowy na odwiedzającego",- "share.settings.limits.maxTopicsPerVisitorHint": "Ile oddzielnych rozmów może rozpocząć każdy zalogowany odwiedzający.",- "share.settings.limits.maxTopicsPerVisitorUnit": "tematy",- "share.settings.limits.maxTurnsPerTopic": "Wymiany w rozmowie",- "share.settings.limits.maxTurnsPerTopicHint": "Ile wiadomości odwiedzający może wysłać w jednej rozmowie.",- "share.settings.limits.maxTurnsPerTopicUnit": "rundy","share.settings.limits.monthlySpendLimit": "Miesięczny limit wydatków","share.settings.limits.monthlySpendLimitHint": "Uruchomienia przez odwiedzających zostaną zatrzymane, gdy miesięczne wydatki na tego Agenta osiągną limit.","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "Co może odczytać uruchomienie odwiedzającego i co odwiedzający może zobaczyć w odpowiedzi.","share.settings.permissions.showErrorDetails": "Pokaż szczegóły błędu odwiedzającym","share.settings.permissions.showErrorDetailsHint": "Domyślnie wyłączone: odwiedzający widzą ogólny komunikat o błędzie zamiast szczegółowego tekstu błędu.",- "share.settings.permissions.showModelInfo": "Pokaż, który model jest używany",- "share.settings.permissions.showModelInfoHint": "Domyślnie wyłączone: Twój wybór modelu i dostawcy pozostaje ukryty.","share.settings.permissions.title": "Uprawnienia","share.settings.profile.demoCases.add": "Dodaj przykład","share.settings.profile.demoCases.desc": "Napisz przykłady dla odwiedzających do wypróbowania. Są one oddzielne od początkowych pytań agenta.",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "Właściciel wstrzymał udostępnianie, więc nowe wiadomości są wyłączone.","share.visitor.errors.spendLimit": "Ten udostępniony agent osiągnął miesięczny limit użycia ustalony przez jego twórcę. Będzie ponownie dostępny w przyszłym miesiącu.","share.visitor.errors.stopFailed": "Nie udało się zatrzymać uruchomienia. Spróbuj ponownie.",- "share.visitor.errors.topicLimit": "Osiągnąłeś limit rozmów na tym udostępnionym agencie.",- "share.visitor.errors.turnLimit": "Ta rozmowa osiągnęła limit wymian. Rozpocznij nową rozmowę, aby kontynuować.","share.visitor.errors.unavailable": "Ta rozmowa nie jest już dostępna. Spróbuj przełączyć się na inny temat lub rozpocząć nową rozmowę.","share.visitor.input.placeholder": "Napisz wiadomość do tego udostępnionego agenta…","share.visitor.input.send": "Wyślij",@@ -822,8 +812,6 @@"share.visitor.profile.metrics.lastDeliveredCaption": "najnowsza aktualizacja","share.visitor.profile.metrics.tools": "Otwarte narzędzia","share.visitor.profile.metrics.toolsCaption": "dostępne dla Ciebie",- "share.visitor.profile.metrics.turns": "Każda rozmowa",- "share.visitor.profile.metrics.turnsCaption": "maksymalna liczba tur","share.visitor.profile.metrics.unknown": "Brak danych","share.visitor.profile.metrics.views": "Wyświetlenia","share.visitor.profile.metrics.viewsCaption": "na tej stronie",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "Zanim zaczniesz","share.visitor.profile.terms.tools_one": "{{count}} narzędzie jest dostępne dla odwiedzających.","share.visitor.profile.terms.tools_other": "{{count}} narzędzia są dostępne dla odwiedzających.",- "share.visitor.profile.terms.topics": "Możesz otworzyć do {{count}} rozmów.",- "share.visitor.profile.terms.turns": "Każda rozmowa pozwala na maksymalnie {{count}} tur.","share.visitor.profile.terms.uploads": "Możesz dołączać pliki; ten Ajan ma {{size}} miejsca na pliki dla odwiedzających.","share.visitor.profile.terms.uploadsOff": "Załączniki są wyłączone.","share.visitor.profile.terms.visibilityCreator": "Twórca włączył przegląd sesji, więc może przeczytać tę rozmowę.",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "Zadanie","share.visitor.profile.works.untitled": "Praca bez tytułu","share.visitor.topBar.home": "Przejdź do mojego LobeHub",- "share.visitor.topics.empty": "Brak rozmów",- "share.visitor.topics.new": "Nowa rozmowa",- "share.visitor.topics.title": "Rozmowy",- "share.visitor.topics.untitled": "Rozmowa bez tytułu","share.visitor.upload.creatorStorageBlocked": "Przestrzeń na przesyłanie plików tego Ajana jest pełna. Poproś jego twórcę o zwolnienie miejsca lub zwiększenie limitu.","share.visitor.upload.fileTooLarge": "Pliki muszą być mniejsze niż {{max}}.","share.visitor.upload.tooManyFiles": "Możesz dołączyć maksymalnie {{max}} plików na wiadomość.",diff --git a/locales/pt-BR/agent.json b/locales/pt-BR/agent.jsonindex 7067ccb5ce1..1e846b96f95 100644--- a/locales/pt-BR/agent.json+++ b/locales/pt-BR/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "Os arquivos anexados pelos visitantes são armazenados na sua conta. Os uploads param quando atingem esse total; defina 0 para desativar anexos.","share.settings.limits.maxFileStorageLabel": "Limite de armazenamento de arquivos","share.settings.limits.maxFileStorageWorkspaceHint": "Os arquivos anexados pelos visitantes são armazenados no Espaço de Trabalho. Os uploads param quando atingem esse total; defina 0 para desativar anexos.",- "share.settings.limits.maxTopicsPerVisitor": "Conversas por visitante",- "share.settings.limits.maxTopicsPerVisitorHint": "Quantas conversas separadas cada visitante autenticado pode iniciar.",- "share.settings.limits.maxTopicsPerVisitorUnit": "tópicos",- "share.settings.limits.maxTurnsPerTopic": "Interações por conversa",- "share.settings.limits.maxTurnsPerTopicHint": "Quantas mensagens um visitante pode enviar dentro de uma conversa.",- "share.settings.limits.maxTurnsPerTopicUnit": "turnos","share.settings.limits.monthlySpendLimit": "Limite de gastos mensais","share.settings.limits.monthlySpendLimitHint": "As execuções de visitantes param assim que os gastos deste mês com este Agente atingem o limite.","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "O que a execução de um visitante pode ler e o que o visitante pode ver de volta.","share.settings.permissions.showErrorDetails": "Mostrar detalhes de erro aos visitantes","share.settings.permissions.showErrorDetailsHint": "Desativado por padrão: os visitantes veem um aviso genérico de falha em vez de texto de erro bruto.",- "share.settings.permissions.showModelInfo": "Mostrar qual modelo está sendo usado",- "share.settings.permissions.showModelInfoHint": "Desativado por padrão: sua escolha de modelo e provedor permanece oculta.","share.settings.permissions.title": "Permissões","share.settings.profile.demoCases.add": "Adicionar exemplo","share.settings.profile.demoCases.desc": "Escreva exemplos para os visitantes experimentarem. Estes são separados das perguntas iniciais do agente.",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "O proprietário pausou o compartilhamento, então novas mensagens estão desativadas.","share.visitor.errors.spendLimit": "Este agente compartilhado atingiu o limite de uso mensal definido pelo criador. Ele estará disponível novamente no próximo mês.","share.visitor.errors.stopFailed": "Não foi possível parar a execução. Por favor, tente novamente.",- "share.visitor.errors.topicLimit": "Você atingiu o limite de conversas neste agente compartilhado.",- "share.visitor.errors.turnLimit": "Esta conversa atingiu o limite de interações. Inicie uma nova conversa para continuar.","share.visitor.errors.unavailable": "Esta conversa não está mais disponível. Tente mudar para outro tópico ou iniciar uma nova.","share.visitor.input.placeholder": "Envie uma mensagem para este agente compartilhado…","share.visitor.input.send": "Enviar",@@ -822,8 +812,6 @@"share.visitor.profile.metrics.lastDeliveredCaption": "atualização mais recente","share.visitor.profile.metrics.tools": "Abrir ferramentas","share.visitor.profile.metrics.toolsCaption": "disponíveis para você",- "share.visitor.profile.metrics.turns": "Cada conversa",- "share.visitor.profile.metrics.turnsCaption": "no máximo de turnos","share.visitor.profile.metrics.unknown": "Ainda sem dados","share.visitor.profile.metrics.views": "Visualizações","share.visitor.profile.metrics.viewsCaption": "nesta página",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "Antes de começar","share.visitor.profile.terms.tools_one": "{{count}} ferramenta está aberta para visitantes.","share.visitor.profile.terms.tools_other": "{{count}} ferramentas estão abertas para visitantes.",- "share.visitor.profile.terms.topics": "Você pode abrir até {{count}} conversas.",- "share.visitor.profile.terms.turns": "Cada conversa permite até {{count}} turnos.","share.visitor.profile.terms.uploads": "Você pode anexar arquivos; este Ajan tem {{size}} de armazenamento de arquivos para visitantes.","share.visitor.profile.terms.uploadsOff": "Anexos estão desativados.","share.visitor.profile.terms.visibilityCreator": "O criador ativou a revisão de sessão, então ele pode ler esta conversa.",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "Tarefa","share.visitor.profile.works.untitled": "Trabalho sem título","share.visitor.topBar.home": "Ir para meu LobeHub",- "share.visitor.topics.empty": "Nenhuma conversa ainda",- "share.visitor.topics.new": "Nova conversa",- "share.visitor.topics.title": "Conversas",- "share.visitor.topics.untitled": "Conversa sem título","share.visitor.upload.creatorStorageBlocked": "O espaço de upload deste Ajan está cheio. Peça ao criador para liberar espaço ou aumentar o limite.","share.visitor.upload.fileTooLarge": "Os arquivos devem ter menos de {{max}}.","share.visitor.upload.tooManyFiles": "Você pode anexar até {{max}} arquivos por mensagem.",diff --git a/locales/ru-RU/agent.json b/locales/ru-RU/agent.jsonindex c42447703cd..90faaea98d6 100644--- a/locales/ru-RU/agent.json+++ b/locales/ru-RU/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "Файлы, которые прикрепляют посетители, хранятся в вашей учетной записи. Загрузка прекращается, когда они достигают этого лимита; установите 0, чтобы отключить вложения.","share.settings.limits.maxFileStorageLabel": "Лимит хранения файлов","share.settings.limits.maxFileStorageWorkspaceHint": "Файлы, прикрепленные посетителями, хранятся в рабочем пространстве. Загрузка прекращается, когда достигается этот лимит; установите 0, чтобы отключить вложения.",- "share.settings.limits.maxTopicsPerVisitor": "Беседы на одного посетителя",- "share.settings.limits.maxTopicsPerVisitorHint": "Сколько отдельных бесед может начать каждый авторизованный посетитель.",- "share.settings.limits.maxTopicsPerVisitorUnit": "темы",- "share.settings.limits.maxTurnsPerTopic": "Сообщений на беседу",- "share.settings.limits.maxTurnsPerTopicHint": "Сколько сообщений посетитель может отправить в рамках одной беседы.",- "share.settings.limits.maxTurnsPerTopicUnit": "ходы","share.settings.limits.monthlySpendLimit": "Месячный лимит расходов","share.settings.limits.monthlySpendLimitHint": "Запуски посетителей прекращаются, как только расходы на этого агента в текущем месяце достигают лимита.","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "Что может читать запуск посетителя и что посетитель может видеть в ответ.","share.settings.permissions.showErrorDetails": "Показывать посетителям детали ошибок","share.settings.permissions.showErrorDetailsHint": "По умолчанию отключено: посетители видят общее уведомление об ошибке вместо текста ошибки.",- "share.settings.permissions.showModelInfo": "Показывать, какая модель используется",- "share.settings.permissions.showModelInfoHint": "По умолчанию отключено: выбор модели и провайдера остается скрытым.","share.settings.permissions.title": "Разрешения","share.settings.profile.demoCases.add": "Добавить пример","share.settings.profile.demoCases.desc": "Напишите примеры для посетителей, чтобы попробовать. Они отделены от начальных вопросов агента.",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "Владелец приостановил общий доступ, поэтому новые сообщения отключены.","share.visitor.errors.spendLimit": "Этот общий агент достиг месячного лимита использования, установленного его создателем. Он будет доступен снова в следующем месяце.","share.visitor.errors.stopFailed": "Не удалось остановить запуск. Пожалуйста, попробуйте снова.",- "share.visitor.errors.topicLimit": "Вы достигли лимита бесед с этим общим агентом.",- "share.visitor.errors.turnLimit": "Эта беседа достигла лимита сообщений. Начните новую беседу, чтобы продолжить.","share.visitor.errors.unavailable": "Эта беседа больше недоступна. Попробуйте переключиться на другую тему или начать новую.","share.visitor.input.placeholder": "Напишите этому общему агенту…","share.visitor.input.send": "Отправить",@@ -822,8 +812,6 @@"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": "на этой странице",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "Прежде чем начать","share.visitor.profile.terms.tools_one": "{{count}} инструмент доступен для посетителей.","share.visitor.profile.terms.tools_other": "{{count}} инструментов доступны для посетителей.",- "share.visitor.profile.terms.topics": "Вы можете открыть до {{count}} разговоров.",- "share.visitor.profile.terms.turns": "Каждый разговор допускает до {{count}} ходов.","share.visitor.profile.terms.uploads": "Вы можете прикреплять файлы; у этого Агента есть {{size}} для хранения файлов посетителей.","share.visitor.profile.terms.uploadsOff": "Вложения отключены.","share.visitor.profile.terms.visibilityCreator": "Создатель включил обзор сессии, поэтому он может читать этот разговор.",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "Задача","share.visitor.profile.works.untitled": "Без названия","share.visitor.topBar.home": "Перейти в мой LobeHub",- "share.visitor.topics.empty": "Пока нет бесед",- "share.visitor.topics.new": "Новая беседа",- "share.visitor.topics.title": "Беседы",- "share.visitor.topics.untitled": "Без названия","share.visitor.upload.creatorStorageBlocked": "Место для загрузки этого Агента заполнено. Попросите его создателя освободить место или увеличить лимит.","share.visitor.upload.fileTooLarge": "Файлы должны быть меньше {{max}}.","share.visitor.upload.tooManyFiles": "Вы можете прикрепить до {{max}} файлов за сообщение.",diff --git a/locales/tr-TR/agent.json b/locales/tr-TR/agent.jsonindex 64c60f8d8be..acf4b032b10 100644--- a/locales/tr-TR/agent.json+++ b/locales/tr-TR/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "Ziyaretçilerin eklediği dosyalar hesabınızda depolanır. Yüklemeler bu toplam değere ulaştığında durur; ekleri kapatmak için 0 olarak ayarlayın.","share.settings.limits.maxFileStorageLabel": "Dosya depolama sınırı","share.settings.limits.maxFileStorageWorkspaceHint": "Ziyaretçilerin eklediği dosyalar Çalışma Alanında saklanır. Yüklemeler bu toplam değere ulaştığında durur; ekleri kapatmak için 0 olarak ayarlayın.",- "share.settings.limits.maxTopicsPerVisitor": "Ziyaretçi başına konuşma",- "share.settings.limits.maxTopicsPerVisitorHint": "Her oturum açmış ziyaretçinin başlatabileceği ayrı konuşma sayısı.",- "share.settings.limits.maxTopicsPerVisitorUnit": "konular",- "share.settings.limits.maxTurnsPerTopic": "Konuşma başına mesaj",- "share.settings.limits.maxTurnsPerTopicHint": "Bir ziyaretçinin bir konuşma içinde gönderebileceği mesaj sayısı.",- "share.settings.limits.maxTurnsPerTopicUnit": "dönüşler","share.settings.limits.monthlySpendLimit": "Aylık harcama sınırı","share.settings.limits.monthlySpendLimitHint": "Bu ay bu Ajan için harcama sınırına ulaşıldığında ziyaretçi çalıştırmaları durur.","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "Bir ziyaretçi çalıştırmasının okuyabileceği ve ziyaretçiye geri gösterebileceği şeyler.","share.settings.permissions.showErrorDetails": "Hata ayrıntılarını ziyaretçilere göster","share.settings.permissions.showErrorDetailsHint": "Varsayılan olarak kapalı: ziyaretçiler ham hata metni yerine genel bir hata bildirimi görür.",- "share.settings.permissions.showModelInfo": "Hangi modelin kullanıldığını göster",- "share.settings.permissions.showModelInfoHint": "Varsayılan olarak kapalı: model ve sağlayıcı seçiminiz gizli kalır.","share.settings.permissions.title": "İzinler","share.settings.profile.demoCases.add": "Örnek ekle","share.settings.profile.demoCases.desc": "Ziyaretçilerin denemesi için örnekler yazın. Bunlar, ajanın açılış sorularından ayrıdır.",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "Sahibi paylaşımı duraklattı, bu nedenle yeni mesajlar kapalı.","share.visitor.errors.spendLimit": "Bu paylaşılan ajan, yaratıcısı tarafından belirlenen aylık kullanım sınırına ulaştı. Gelecek ay tekrar kullanılabilir olacak.","share.visitor.errors.stopFailed": "Çalıştırma durdurulamadı. Lütfen tekrar deneyin.",- "share.visitor.errors.topicLimit": "Bu paylaşılan ajan üzerindeki konuşma sınırına ulaştınız.",- "share.visitor.errors.turnLimit": "Bu konuşma mesaj sınırına ulaştı. Devam etmek için yeni bir konuşma başlatın.","share.visitor.errors.unavailable": "Bu konuşma artık mevcut değil. Başka bir konuya geçmeyi veya yeni bir konuşma başlatmayı deneyin.","share.visitor.input.placeholder": "Bu paylaşılan ajana mesaj gönderin…","share.visitor.input.send": "Gönder",@@ -822,8 +812,6 @@"share.visitor.profile.metrics.lastDeliveredCaption": "en son güncelleme","share.visitor.profile.metrics.tools": "Açık araçlar","share.visitor.profile.metrics.toolsCaption": "sizin için mevcut",- "share.visitor.profile.metrics.turns": "Her konuşma",- "share.visitor.profile.metrics.turnsCaption": "en fazla dönüş","share.visitor.profile.metrics.unknown": "Henüz veri yok","share.visitor.profile.metrics.views": "Görüntülemeler","share.visitor.profile.metrics.viewsCaption": "bu sayfada",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "Başlamadan önce","share.visitor.profile.terms.tools_one": "{{count}} araç ziyaretçilere açık.","share.visitor.profile.terms.tools_other": "{{count}} araç ziyaretçilere açık.",- "share.visitor.profile.terms.topics": "En fazla {{count}} konuşma başlatabilirsiniz.",- "share.visitor.profile.terms.turns": "Her konuşma en fazla {{count}} dönüşe izin verir.","share.visitor.profile.terms.uploads": "Dosya ekleyebilirsiniz; bu Ajan ziyaretçiler için {{size}} dosya depolama alanına sahiptir.","share.visitor.profile.terms.uploadsOff": "Ekler kapalı.","share.visitor.profile.terms.visibilityCreator": "Oluşturucu oturum incelemesini açtı, bu nedenle bu konuşmayı okuyabilirler.",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "Görev","share.visitor.profile.works.untitled": "Başlıksız çalışma","share.visitor.topBar.home": "LobeHub'ıma git",- "share.visitor.topics.empty": "Henüz konuşma yok",- "share.visitor.topics.new": "Yeni konuşma",- "share.visitor.topics.title": "Konuşmalar",- "share.visitor.topics.untitled": "Başlıksız konuşma","share.visitor.upload.creatorStorageBlocked": "Bu Ajanın yükleme alanı dolu. Yaratıcısından alanı boşaltmasını veya limiti artırmasını isteyin.","share.visitor.upload.fileTooLarge": "Dosyalar {{max}} boyutundan küçük olmalıdır.","share.visitor.upload.tooManyFiles": "Bir mesajda en fazla {{max}} dosya ekleyebilirsiniz.",diff --git a/locales/vi-VN/agent.json b/locales/vi-VN/agent.jsonindex 764b75a6b40..dfd71c73561 100644--- a/locales/vi-VN/agent.json+++ b/locales/vi-VN/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "Các tệp mà khách truy cập đính kèm sẽ được lưu trữ trên tài khoản của bạn. Việc tải lên sẽ dừng lại khi đạt đến tổng số này; đặt 0 để tắt đính kèm.","share.settings.limits.maxFileStorageLabel": "Giới hạn lưu trữ tệp","share.settings.limits.maxFileStorageWorkspaceHint": "Các tệp mà khách truy cập đính kèm được lưu trữ trong Không gian làm việc. Việc tải lên sẽ dừng khi đạt đến tổng số này; đặt 0 để tắt tệp đính kèm.",- "share.settings.limits.maxTopicsPerVisitor": "Cuộc trò chuyện mỗi khách truy cập",- "share.settings.limits.maxTopicsPerVisitorHint": "Số lượng cuộc trò chuyện riêng biệt mà mỗi khách truy cập đã đăng nhập có thể bắt đầu.",- "share.settings.limits.maxTopicsPerVisitorUnit": "chủ đề",- "share.settings.limits.maxTurnsPerTopic": "Lượt mỗi cuộc trò chuyện",- "share.settings.limits.maxTurnsPerTopicHint": "Số lượng tin nhắn mà khách truy cập có thể gửi trong một cuộc trò chuyện.",- "share.settings.limits.maxTurnsPerTopicUnit": "lượt","share.settings.limits.monthlySpendLimit": "Giới hạn chi tiêu hàng tháng","share.settings.limits.monthlySpendLimitHint": "Các lần chạy của khách truy cập sẽ dừng khi chi tiêu tháng này cho Agent này đạt đến giới hạn.","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "Những gì lần chạy của khách truy cập có thể đọc, và những gì khách truy cập có thể thấy.","share.settings.permissions.showErrorDetails": "Hiển thị chi tiết lỗi cho khách truy cập","share.settings.permissions.showErrorDetailsHint": "Tắt theo mặc định: khách truy cập sẽ thấy thông báo lỗi chung thay vì chi tiết lỗi.",- "share.settings.permissions.showModelInfo": "Hiển thị mô hình được sử dụng",- "share.settings.permissions.showModelInfoHint": "Tắt theo mặc định: lựa chọn mô hình và nhà cung cấp của bạn sẽ được ẩn.","share.settings.permissions.title": "Quyền","share.settings.profile.demoCases.add": "Thêm ví dụ","share.settings.profile.demoCases.desc": "Viết các ví dụ để khách truy cập thử. Đây là các ví dụ riêng biệt với các câu hỏi mở đầu của ajan.",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "Chủ sở hữu đã tạm dừng chia sẻ, vì vậy các tin nhắn mới đã bị tắt.","share.visitor.errors.spendLimit": "Agent được chia sẻ này đã đạt đến giới hạn sử dụng hàng tháng do người tạo đặt. Nó sẽ khả dụng lại vào tháng sau.","share.visitor.errors.stopFailed": "Không thể dừng lần chạy. Vui lòng thử lại.",- "share.visitor.errors.topicLimit": "Bạn đã đạt đến giới hạn cuộc trò chuyện trên Agent được chia sẻ này.",- "share.visitor.errors.turnLimit": "Cuộc trò chuyện này đã đạt đến giới hạn lượt. Bắt đầu một cuộc trò chuyện mới để tiếp tục.","share.visitor.errors.unavailable": "Cuộc trò chuyện này không còn khả dụng. Thử chuyển sang chủ đề khác hoặc bắt đầu một cuộc trò chuyện mới.","share.visitor.input.placeholder": "Nhắn tin cho Agent được chia sẻ này…","share.visitor.input.send": "Gửi",@@ -822,8 +812,6 @@"share.visitor.profile.metrics.lastDeliveredCaption": "cập nhật gần đây nhất","share.visitor.profile.metrics.tools": "Mở công cụ","share.visitor.profile.metrics.toolsCaption": "có sẵn cho bạn",- "share.visitor.profile.metrics.turns": "Mỗi cuộc trò chuyện",- "share.visitor.profile.metrics.turnsCaption": "tối đa lượt","share.visitor.profile.metrics.unknown": "Chưa có dữ liệu","share.visitor.profile.metrics.views": "Lượt xem","share.visitor.profile.metrics.viewsCaption": "trên trang này",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "Trước khi bạn bắt đầu","share.visitor.profile.terms.tools_one": "{{count}} công cụ được mở cho khách truy cập.","share.visitor.profile.terms.tools_other": "{{count}} công cụ được mở cho khách truy cập.",- "share.visitor.profile.terms.topics": "Bạn có thể mở tối đa {{count}} cuộc trò chuyện.",- "share.visitor.profile.terms.turns": "Mỗi cuộc trò chuyện cho phép tối đa {{count}} lượt.","share.visitor.profile.terms.uploads": "Bạn có thể đính kèm tệp; Ajan này có {{size}} dung lượng lưu trữ tệp cho khách truy cập.","share.visitor.profile.terms.uploadsOff": "Đính kèm đã bị tắt.","share.visitor.profile.terms.visibilityCreator": "Người tạo đã bật chế độ xem lại phiên, vì vậy họ có thể đọc cuộc trò chuyện này.",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "Nhiệm vụ","share.visitor.profile.works.untitled": "Tác phẩm chưa có tiêu đề","share.visitor.topBar.home": "Đi đến LobeHub của tôi",- "share.visitor.topics.empty": "Chưa có cuộc trò chuyện nào",- "share.visitor.topics.new": "Cuộc trò chuyện mới",- "share.visitor.topics.title": "Cuộc trò chuyện",- "share.visitor.topics.untitled": "Cuộc trò chuyện chưa đặt tên","share.visitor.upload.creatorStorageBlocked": "Dung lượng tải lên của Ajan này đã đầy. Hãy yêu cầu người tạo giải phóng dung lượng hoặc tăng giới hạn.","share.visitor.upload.fileTooLarge": "Các tệp phải nhỏ hơn {{max}}.","share.visitor.upload.tooManyFiles": "Bạn có thể đính kèm tối đa {{max}} tệp mỗi tin nhắn.",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex 7e92bce06b0..5272a40a870 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -691,16 +691,16 @@"channel.wecom.secret": "Secret","channel.wecom.secretHint": "机器人的长连接 Secret。同一个机器人同一时间只能接入一处:在这里保存会接管它在别处的连接,之后在别处接入也会让这里断开。","share.entry": "分享此助手",+ "share.settings.device.desc": "设定哪些人可以在你的执行环境上运行这个助手,例如读取文件、执行命令。Claude Code 和 Codex 助手只能在这里运行,其他访客无法使用。能和助手对话不代表有设备权限。",+ "share.settings.device.title": "设备权限",+ "share.settings.device.who": "谁可以使用你的设备","share.settings.limits.desc": "访客的每次运行都记在你的账户上,这些上限是分享链接不会跑出高额账单的唯一保障。上限始终生效,你可以调整数值,但不能关闭。","share.settings.limits.maxFileStorageHint": "访客上传的文件会存放在你的账号里。累计达到这个总量后就不能再上传;填 0 表示关闭附件功能。","share.settings.limits.maxFileStorageLabel": "文件存储上限","share.settings.limits.maxFileStorageWorkspaceHint": "访客上传的文件会存放在工作区内。累计达到这个总量后就不能再上传;填 0 表示关闭附件功能。",- "share.settings.limits.maxTopicsPerVisitor": "每位访客的话题数",- "share.settings.limits.maxTopicsPerVisitorHint": "每位已登录访客最多能创建多少个独立话题。",- "share.settings.limits.maxTopicsPerVisitorUnit": "个",- "share.settings.limits.maxTurnsPerTopic": "每个话题的轮次",- "share.settings.limits.maxTurnsPerTopicHint": "访客在一个话题里最多能发送多少条消息。",- "share.settings.limits.maxTurnsPerTopicUnit": "轮",+ "share.settings.limits.maxMessagesPerVisitor": "每位访客的消息数",+ "share.settings.limits.maxMessagesPerVisitorHint": "每位登录访客最多可以给这个助手发送的消息总数,助手的回复不计入。",+ "share.settings.limits.maxMessagesPerVisitorUnit": "条","share.settings.limits.monthlySpendLimit": "每月消耗上限","share.settings.limits.monthlySpendLimitHint": "本月该助手的消耗达到上限后,访客将无法继续运行。按自然月统计,每月 1 日(UTC)重置。","share.settings.limits.monthlySpendLimitUnit": "美元",@@ -738,14 +738,12 @@"share.settings.permissions.allowReadMemory": "允许读取我的记忆","share.settings.permissions.allowReadMemoryHint": "助手在回答访客时可以参考你的长期记忆。","share.settings.permissions.desc": "访客的运行可以读取什么,以及访客能看到什么。",- "share.settings.permissions.deviceAccess": "执行环境","share.settings.permissions.deviceAccessConfirm.commands": "他们可以在这个助手运行的机器上执行任意命令、读写任意文件,包括通过 Claude Code 或 Codex。","share.settings.permissions.deviceAccessConfirm.intro": "你添加的人会在你的执行环境上运行这个助手:",- "share.settings.permissions.deviceAccessConfirm.limits": "这部分用量不受每月消费上限限制,只受每个话题的轮次上限约束。",+ "share.settings.permissions.deviceAccessConfirm.messageLimit": "这部分用量不受每月消耗上限限制,只受每位访客的消息数上限约束。","share.settings.permissions.deviceAccessConfirm.ok": "允许指定的人","share.settings.permissions.deviceAccessConfirm.subscription": "Claude Code 和 Codex 会使用那台机器上登录的模型订阅。","share.settings.permissions.deviceAccessConfirm.title": "允许他人使用你的执行环境?",- "share.settings.permissions.deviceAccessHint": "允许你选中的人在这个助手的执行环境上运行它,包括 Claude Code 和 Codex。其他人无法运行 Claude Code 或 Codex 助手。","share.settings.permissions.deviceAccessOption.allowlist": "通讯录中的人","share.settings.permissions.deviceAccessOption.none": "不允许","share.settings.permissions.deviceAllowContactsUnavailable": "只能添加通讯录中的人,你的账号暂未开通通讯录。",@@ -757,8 +755,6 @@"share.settings.permissions.deviceAllowUnlisted": "已不在通讯录,无法使用:{{names}}。下次修改名单时会被移除。","share.settings.permissions.showErrorDetails": "向访客展示错误详情","share.settings.permissions.showErrorDetailsHint": "默认关闭:访客只会看到一句通用的失败提示,而不是原始报错。",- "share.settings.permissions.showModelInfo": "展示使用的模型",- "share.settings.permissions.showModelInfoHint": "默认关闭:不向访客暴露你选择的模型和服务商。","share.settings.permissions.title": "权限","share.settings.profile.demoCases.add": "添加案例","share.settings.profile.demoCases.desc": "为访客编写可直接试用的案例,独立于助手的开场问题。",@@ -847,6 +843,7 @@"share.visitor.access.signInCta": "登录","share.visitor.access.signInDesc": "登录后即可与这个分享助手对话,你的话题会保留在自己的账号下。","share.visitor.access.signInTitle": "登录后继续",+ "share.visitor.chat.channelsDisabled": "你的账号暂未开放与分享的 Agent 对话。","share.visitor.errors.fileUnavailable": "有附件已不可用,请移除后重试。","share.visitor.errors.generic": "消息发送失败,请重试。","share.visitor.errors.heteroDeviceUnavailable": "创建者的设备当前离线,请稍后再试。",@@ -857,8 +854,6 @@"share.visitor.errors.sharingPaused": "创建者已暂停分享,暂时无法发送新消息。","share.visitor.errors.spendLimit": "该分享助手已达创建者设置的本月用量限额,下月自动恢复。","share.visitor.errors.stopFailed": "停止失败,请重试。",- "share.visitor.errors.topicLimit": "你在这个分享助手上的话题数量已达上限。",- "share.visitor.errors.turnLimit": "本话题的轮数已达上限,新建话题即可继续。","share.visitor.errors.unavailable": "该话题已不可用,请切换或新建话题继续。","share.visitor.input.placeholder": "和这个分享助手聊聊…","share.visitor.input.send": "发送",@@ -886,8 +881,6 @@"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": "次访问",@@ -901,11 +894,11 @@"share.visitor.profile.terms.account": "它运行在创建者的账号上,每一次回复都由创建者付费。","share.visitor.profile.terms.accountWorkspace": "它运行在所属工作区内,每一次回复都从工作区预算扣费。","share.visitor.profile.terms.desc": "这几条规则今天只在你撞上时以报错的形式出现,这里把它们提前讲清楚。",+ "share.visitor.profile.terms.messages_one": "你最多可以发送 {{count}} 条消息。",+ "share.visitor.profile.terms.messages_other": "你最多可以发送 {{count}} 条消息。","share.visitor.profile.terms.title": "开始之前","share.visitor.profile.terms.tools_one": "{{count}} 个工具对访客开放。","share.visitor.profile.terms.tools_other": "有 {{count}} 个工具对访客开放。",- "share.visitor.profile.terms.topics": "你最多可以创建 {{count}} 个话题。",- "share.visitor.profile.terms.turns": "每个话题最多 {{count}} 轮。","share.visitor.profile.terms.uploads": "你可以上传附件,这个智能体为访客预留了 {{size}} 的文件存储空间。","share.visitor.profile.terms.uploadsOff": "附件功能已关闭。","share.visitor.profile.terms.visibilityCreator": "创建者开启了话题查看权限,可能会读取你话题中的消息。",@@ -920,10 +913,6 @@"share.visitor.profile.works.type.task": "任务","share.visitor.profile.works.untitled": "未命名成果","share.visitor.topBar.home": "回到我的 LobeHub",- "share.visitor.topics.empty": "还没有话题",- "share.visitor.topics.new": "新建话题",- "share.visitor.topics.title": "话题",- "share.visitor.topics.untitled": "未命名话题","share.visitor.upload.creatorStorageBlocked": "这个智能体的上传空间已满,请联系创建者清理文件或调高上限。","share.visitor.upload.fileTooLarge": "单个文件不能超过 {{max}}。","share.visitor.upload.tooManyFiles": "每条消息最多可附加 {{max}} 个文件。",diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.jsonindex 351ee17e403..f1de0445e21 100644--- a/locales/zh-CN/channel.json+++ b/locales/zh-CN/channel.json@@ -189,6 +189,10 @@"profile.view": "查看资料","projectAgents": "项目 Agent","receipt.errorReason": "失败原因",+ "receipt.errorShareHeteroDevice": "创建者的设备当前离线,请稍后再试。",+ "receipt.errorShareHeteroUnsupported": "这个 Agent 需要创建者授权后才能为你运行,请联系创建者开通。",+ "receipt.errorShareMessageLimit": "你发给这个分享 Agent 的消息已达到创建者设置的上限。",+ "receipt.errorShareSpendLimit": "这个分享的 Agent 已达到创作者设置的每月用量上限,下个月会恢复。","receipt.errorUnavailable": "未记录具体原因,请检查 Agent 的模型与设备设置后重新发送。","receipt.failedHint": "再次 @ 它即可重试。","receipt.worktree": "在独立 worktree 中工作 · {{branch}}",diff --git a/locales/zh-TW/agent.json b/locales/zh-TW/agent.jsonindex 00824f48294..69731ebbbe0 100644--- a/locales/zh-TW/agent.json+++ b/locales/zh-TW/agent.json@@ -652,12 +652,6 @@"share.settings.limits.maxFileStorageHint": "訪客附加的檔案會儲存在您的帳戶中。一旦上傳達到此總量,將停止上傳;設為 0 可關閉附件功能。","share.settings.limits.maxFileStorageLabel": "檔案存儲限制","share.settings.limits.maxFileStorageWorkspaceHint": "訪客附加的檔案存儲在工作區中。一旦達到此總量,將停止上傳;設置為 0 可關閉附件功能。",- "share.settings.limits.maxTopicsPerVisitor": "每位訪客的對話數",- "share.settings.limits.maxTopicsPerVisitorHint": "每位已登入訪客可以開始的獨立對話數量。",- "share.settings.limits.maxTopicsPerVisitorUnit": "主題",- "share.settings.limits.maxTurnsPerTopic": "每次對話的回合數",- "share.settings.limits.maxTurnsPerTopicHint": "訪客在一次對話中可以發送的訊息數量。",- "share.settings.limits.maxTurnsPerTopicUnit": "回合","share.settings.limits.monthlySpendLimit": "每月支出上限","share.settings.limits.monthlySpendLimitHint": "當本月在此代理上的支出達到上限時,訪客執行將停止。","share.settings.limits.monthlySpendLimitUnit": "USD",@@ -697,8 +691,6 @@"share.settings.permissions.desc": "訪客執行時可以讀取的內容,以及訪客可以看到的回應。","share.settings.permissions.showErrorDetails": "向訪客顯示錯誤詳情","share.settings.permissions.showErrorDetailsHint": "預設為關閉:訪客只會看到通用的失敗通知,而非原始錯誤訊息。",- "share.settings.permissions.showModelInfo": "顯示使用的模型",- "share.settings.permissions.showModelInfoHint": "預設為關閉:您的模型和提供者選擇將保持隱藏。","share.settings.permissions.title": "權限","share.settings.profile.demoCases.add": "添加範例","share.settings.profile.demoCases.desc": "為訪客編寫範例以供嘗試。這些與代理的開場問題分開。",@@ -796,8 +788,6 @@"share.visitor.errors.sharingPaused": "擁有者已暫停共享,因此新訊息已被關閉。","share.visitor.errors.spendLimit": "此共享代理已達到其創建者設定的每月使用上限。它將在下個月重新可用。","share.visitor.errors.stopFailed": "無法停止執行。請重試。",- "share.visitor.errors.topicLimit": "您已達到此共享代理的對話限制。",- "share.visitor.errors.turnLimit": "此對話已達到回合限制。開始新的對話以繼續。","share.visitor.errors.unavailable": "此對話已不可用。嘗試切換到其他主題或開始新的對話。","share.visitor.input.placeholder": "向此共享代理發送訊息…","share.visitor.input.send": "發送",@@ -822,8 +812,6 @@"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": "此頁面上的瀏覽次數",@@ -839,8 +827,6 @@"share.visitor.profile.terms.title": "開始之前","share.visitor.profile.terms.tools_one": "{{count}} 個工具對訪客開放。","share.visitor.profile.terms.tools_other": "{{count}} 個工具對訪客開放。",- "share.visitor.profile.terms.topics": "您最多可以開啟 {{count}} 個對話。",- "share.visitor.profile.terms.turns": "每次對話最多允許 {{count}} 回合。","share.visitor.profile.terms.uploads": "您可以附加檔案;此 Agent 為訪客提供 {{size}} 的檔案儲存空間。","share.visitor.profile.terms.uploadsOff": "附件功能已關閉。","share.visitor.profile.terms.visibilityCreator": "創建者已開啟會話審查,因此他們可以閱讀此對話。",@@ -855,10 +841,6 @@"share.visitor.profile.works.type.task": "任務","share.visitor.profile.works.untitled": "未命名作品","share.visitor.topBar.home": "前往我的 LobeHub",- "share.visitor.topics.empty": "尚無對話",- "share.visitor.topics.new": "新對話",- "share.visitor.topics.title": "對話",- "share.visitor.topics.untitled": "未命名對話","share.visitor.upload.creatorStorageBlocked": "此 Agent 的上傳空間已滿。請要求其創建者釋放空間或提高上限。","share.visitor.upload.fileTooLarge": "檔案大小必須小於 {{max}}。","share.visitor.upload.tooManyFiles": "每則訊息最多可附加 {{max}} 個檔案。",diff --git a/packages/const/src/agentShare.ts b/packages/const/src/agentShare.tsindex f125a61ade2..7ccd8295705 100644--- a/packages/const/src/agentShare.ts+++ b/packages/const/src/agentShare.ts@@ -1,31 +1,18 @@import type { AgentShareToolGrant } from '@lobechat/types';/**- * Default `AgentShareConfig.maxTopicsPerVisitor` applied when a share is- * first created and whenever a legacy/partial config is normalized. Kept+ * Default `AgentShareConfig.maxMessagesPerVisitor` applied when a share is+ * first created and whenever a partial config is normalized. Kept* conservative — the creator can raise it explicitly via `updateShareConfig`.*/-export const AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR = 5;+export const AGENT_SHARE_DEFAULT_MAX_MESSAGES_PER_VISITOR = 100;/**- * Page size of a visitor's own topic list on a shared agent.- *- * Deliberately NOT tied to the share's live `maxTopicsPerVisitor`: that cap- * only gates the ADMISSION of new topics (a COUNT check at creation time).- * Using it as the read-side LIMIT would hide a visitor's older conversations- * the moment the creator lowers the cap below what the visitor had already- * created — and the visitor surface has no pagination or deep links to reach- * them. A fixed, generous bound keeps every topic a visitor was ever allowed- * to create reachable.+ * Page size of a visitor's own topic list on a shared agent. A fixed, generous+ * bound: no share setting caps how many topics a visitor has.*/export const AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT = 200;-/**- * Default `AgentShareConfig.maxTurnsPerTopic` applied when a share is first- * created and whenever a legacy/partial config is normalized.- */-export const AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC = 20;-/*** Default `AgentShareConfig.monthlySpendLimit` (in USD credits) applied when a* share is first created and whenever a partial config is normalized.diff --git a/packages/database/src/models/__tests__/agentShare.coverage.test.ts b/packages/database/src/models/__tests__/agentShare.coverage.test.tsindex bd7056c7ce9..197e403cf4d 100644--- a/packages/database/src/models/__tests__/agentShare.coverage.test.ts+++ b/packages/database/src/models/__tests__/agentShare.coverage.test.ts@@ -133,21 +133,24 @@ describe('AgentShareModel coverage edges', () => {it('keeps the stored config when the patch carries no defined field', async () => {const model = new AgentShareModel(serverDB, userId);await model.create(agentId);- await model.updateConfig(agentId, { maxTurnsPerTopic: 7, showModelInfo: true });+ await model.updateConfig(agentId, { maxMessagesPerVisitor: 7, showErrorDetails: true });const updated = await model.updateConfig(agentId, {- maxTurnsPerTopic: undefined,- showModelInfo: undefined,+ maxMessagesPerVisitor: undefined,+ showErrorDetails: undefined,});expect(updated?.shareConfig).toMatchObject({- maxTurnsPerTopic: 7,- showModelInfo: true,+ maxMessagesPerVisitor: 7,+ showErrorDetails: true,slug: 'ascov-agent-slug',});const empty = await model.updateConfig(agentId, {});- expect(empty?.shareConfig).toMatchObject({ maxTurnsPerTopic: 7, showModelInfo: true });+ expect(empty?.shareConfig).toMatchObject({+ maxMessagesPerVisitor: 7,+ showErrorDetails: true,+ });});});diff --git a/packages/database/src/models/__tests__/agentShare.test.ts b/packages/database/src/models/__tests__/agentShare.test.tsindex 6ff451b8899..fdab611358e 100644--- a/packages/database/src/models/__tests__/agentShare.test.ts+++ b/packages/database/src/models/__tests__/agentShare.test.ts@@ -75,10 +75,8 @@ describe('AgentShareModel', () => {shareConfig: {allowCreatorViewSessions: false,allowReadMemory: false,- maxTopicsPerVisitor: 5,- maxTurnsPerTopic: 20,+ maxMessagesPerVisitor: 100,showErrorDetails: false,- showModelInfo: false,toolGrants: [],},userViewCount: 0,@@ -193,7 +191,7 @@ describe('AgentShareModel', () => {.insert(agentShares).values({agentId: workspaceAgentId,- shareConfig: { maxTopicsPerVisitor: 3, monthlySpendLimit: 2.5 },+ shareConfig: { maxMessagesPerVisitor: 3, monthlySpendLimit: 2.5 },visibility: 'link',}).returning();@@ -208,7 +206,7 @@ describe('AgentShareModel', () => {await expect(AgentShareModel.readCurrentVisitorCaps(serverDB, workspaceAgentId),).resolves.toMatchObject({- maxTopicsPerVisitor: 3,+ maxMessagesPerVisitor: 3,monthlySpendLimit: 2.5,shareId: share.id,workspaceId,@@ -241,10 +239,10 @@ describe('AgentShareModel', () => {AgentShareModel.forceDisableWorkspaceShare(serverDB, otherWorkspaceId, share.id),).resolves.toBeNull();await expect(- workspaceAgentShareModel.updateConfig(workspaceAgentId, { maxTopicsPerVisitor: 4 }),+ workspaceAgentShareModel.updateConfig(workspaceAgentId, { maxMessagesPerVisitor: 4 }),).resolves.toMatchObject({id: share.id,- shareConfig: { maxTopicsPerVisitor: 4 },+ shareConfig: { maxMessagesPerVisitor: 4 },visibility: 'link',});await expect(@@ -342,7 +340,7 @@ describe('AgentShareModel', () => {{ prompt: 'Review this change', description: 'Identify regression risks' },];await agentShareModel.updateConfig(agentId, { demoCases });- await agentShareModel.updateConfig(agentId, { maxTurnsPerTopic: 8 });+ await agentShareModel.updateConfig(agentId, { maxMessagesPerVisitor: 8 });expect((await agentShareModel.getByAgentId(agentId))?.shareConfig.demoCases).toEqual(demoCases,);@@ -393,11 +391,9 @@ describe('AgentShareModel', () => {deviceAllowUserIds: [],featuredWorkIds: [],maxFileStorage: 512 * 1024 * 1024,- maxTopicsPerVisitor: 5,- maxTurnsPerTopic: 20,+ maxMessagesPerVisitor: 100,monthlySpendLimit: 10,showErrorDetails: false,- showModelInfo: false,slug: undefined,toolGrants: [],});@@ -412,11 +408,9 @@ describe('AgentShareModel', () => {deviceAccess: 'allowlist',deviceAllowUserIds: ['user_alice'],maxFileStorage: 256 * 1024 * 1024,- maxTopicsPerVisitor: 10,- maxTurnsPerTopic: 40,+ maxMessagesPerVisitor: 40,monthlySpendLimit: 25,showErrorDetails: true,- showModelInfo: true,toolGrants: [{ identifier: 'search' }],};@@ -434,18 +428,18 @@ describe('AgentShareModel', () => {await agentShareModel.create(agentId);await agentShareModel.updateConfig(agentId, {- maxTopicsPerVisitor: 10,+ maxMessagesPerVisitor: 10,toolGrants: [{ identifier: 'search' }],});const updated = await agentShareModel.updateConfig(agentId, {- maxTurnsPerTopic: 40,- showModelInfo: true,+ maxFileStorage: 1024,+ showErrorDetails: true,});expect(updated?.shareConfig).toMatchObject({- maxTopicsPerVisitor: 10,- maxTurnsPerTopic: 40,- showModelInfo: true,+ maxFileStorage: 1024,+ maxMessagesPerVisitor: 10,+ showErrorDetails: true,toolGrants: [{ identifier: 'search' }],});});@@ -456,14 +450,14 @@ describe('AgentShareModel', () => {const updated = await agentShareModel.updateConfig(agentId, {monthlySpendLimit: 0,- showModelInfo: true,+ showErrorDetails: true,// smuggled past the type on purpose — must be stripped, not persisted...({ slug: 'sneaky-slug' } as object),});// `0` is a real cap ("stop all visitor runs"), never a cleared one.expect(updated?.shareConfig.monthlySpendLimit).toBe(0);- expect(updated?.shareConfig.showModelInfo).toBe(true);+ expect(updated?.shareConfig.showErrorDetails).toBe(true);// The seeded profile slug is untouched; the smuggled one never lands.expect(updated?.shareConfig.slug).toBe('shareable-agent');expect(await AgentShareModel.findBySlugOrId(serverDB, 'sneaky-slug')).toBeNull();@@ -496,7 +490,7 @@ describe('AgentShareModel', () => {it('returns null for missing shares', async () => {expect(await agentShareModel.getByAgentId(agentId)).toBeNull();- expect(await agentShareModel.updateConfig(agentId, { maxTopicsPerVisitor: 5 })).toBeNull();+ expect(await agentShareModel.updateConfig(agentId, { maxMessagesPerVisitor: 5 })).toBeNull();expect(await agentShareModel.updateVisibility(agentId, 'link')).toBeNull();expect(await agentShareModel.deleteByAgentId(agentId)).toBeNull();});@@ -506,7 +500,7 @@ describe('AgentShareModel', () => {expect(await agentShareModel.getByAgentId(otherAgentId)).toBeNull();expect(- await agentShareModel.updateConfig(otherAgentId, { maxTopicsPerVisitor: 5 }),+ await agentShareModel.updateConfig(otherAgentId, { maxMessagesPerVisitor: 5 }),).toBeNull();expect(await agentShareModel.updateVisibility(otherAgentId, 'link')).toBeNull();expect(await agentShareModel.deleteByAgentId(otherAgentId)).toBeNull();@@ -671,10 +665,7 @@ describe('AgentShareModel', () => {agentName: 'Shareable Agent',agentTitle: 'Shareable Agent Title',ownerId: userId,- shareConfig: expect.objectContaining({- maxTopicsPerVisitor: 5,- maxTurnsPerTopic: 20,- }),+ shareConfig: expect.objectContaining({ maxMessagesPerVisitor: 100 }),shareId: created!.id,visibility: 'link',});@@ -808,24 +799,36 @@ describe('AgentShareModel', () => {it('reads fresh caps and the live shareId', async () => {const created = await agentShareModel.create(agentId);await agentShareModel.updateConfig(agentId, {- maxTopicsPerVisitor: 3,- maxTurnsPerTopic: 8,+ maxMessagesPerVisitor: 3,monthlySpendLimit: 2.5,});await expect(AgentShareModel.readCurrentVisitorCaps(serverDB, agentId)).resolves.toEqual({- maxTopicsPerVisitor: 3,- maxTurnsPerTopic: 8,+ maxMessagesPerVisitor: 3,monthlySpendLimit: 2.5,shareId: created!.id,workspaceId: null,});});+ it('ignores retired cap keys left in a stored config', async () => {+ await serverDB.insert(agentShares).values({+ agentId,+ shareConfig: { maxTopicsPerVisitor: 1, maxTurnsPerTopic: 1, showModelInfo: true } as never,+ visibility: 'link',+ });++ const caps = await AgentShareModel.readCurrentVisitorCaps(serverDB, agentId);+ expect(caps).toMatchObject({ maxMessagesPerVisitor: 100, monthlySpendLimit: 10 });+ expect(caps).not.toHaveProperty('maxTurnsPerTopic');+ const share = await agentShareModel.getByAgentId(agentId);+ expect(share?.shareConfig).not.toHaveProperty('maxTopicsPerVisitor');+ expect(share?.shareConfig).not.toHaveProperty('showModelInfo');+ });+it('falls back to defaults and a null shareId when there is no share', async () => {await expect(AgentShareModel.readCurrentVisitorCaps(serverDB, agentId)).resolves.toEqual({- maxTopicsPerVisitor: 5,- maxTurnsPerTopic: 20,+ maxMessagesPerVisitor: 100,monthlySpendLimit: 10,shareId: null,workspaceId: null,diff --git a/packages/database/src/models/__tests__/messages/message.coverage.groupD.test.ts b/packages/database/src/models/__tests__/messages/message.coverage.groupD.test.tsindex 281b954617f..df8b9055d97 100644--- a/packages/database/src/models/__tests__/messages/message.coverage.groupD.test.ts+++ b/packages/database/src/models/__tests__/messages/message.coverage.groupD.test.ts@@ -236,18 +236,7 @@ describe('updateToolMessage guards', () => {});});-describe('toVisitorMessage model-info passthrough', () => {- it('keeps pinnedMessages untouched when the share exposes model info', () => {- const pinnedMessages = [{ content: 'p', id: 'pin-1', model: 'gpt-4o', role: 'assistant' }];-- const visitor = toVisitorMessage(- { content: 'c', id: 'm', pinnedMessages, role: 'assistant' } as unknown as UIChatMessage,- { showModelInfo: true },- );-- expect(visitor.pinnedMessages).toBe(pinnedMessages);- });-+describe('toVisitorMessage council projection', () => {it('projects a null council to an empty member list', () => {const visitor = toVisitorMessage({content: 'c',diff --git a/packages/database/src/models/__tests__/messages/message.publicApi.test.ts b/packages/database/src/models/__tests__/messages/message.publicApi.test.tsindex 61ea4490b76..99197c5ddb8 100644--- a/packages/database/src/models/__tests__/messages/message.publicApi.test.ts+++ b/packages/database/src/models/__tests__/messages/message.publicApi.test.ts@@ -31,7 +31,6 @@ const PUBLIC_INSTANCE_METHODS = ['batchDeleteByAgentId','count','countApproximate',- 'countByTopic','countGroupByTopic','countUpTo','countWords',diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.tsindex 4299ed7347b..9932a5d5aff 100644--- a/packages/database/src/models/__tests__/messages/message.query.test.ts+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts@@ -1887,23 +1887,6 @@ describe('MessageModel Query Tests', () => {expect(works[0]).not.toHaveProperty('workspaceId');});- it('keeps the spend snapshot when the share exposes model info', async () => {- const result = await messageModel.queryForVisitor(- { includeFileWorks: true, topicId: visitorTopicId },- {- redaction: { showModelInfo: true },- workAccessScope: agentShareWorkAccessScope(provenance),- },- );-- const works = findAnchor(result).works;- expect(works[0]).toMatchObject({ totalCost: 0.42 });- expect(works[0].event.cumulativeUsage).toMatchObject({ usage: { totalTokens: 9 } });- // `showModelInfo` exposes spend only, never the creator's identity.- expect(works[0]).not.toHaveProperty('userId');- expect(works[0]).not.toHaveProperty('workspaceId');- });-it('never resolves the visitor Works through the creator scope', async () => {const result = await messageModel.query({ includeFileWorks: true, topicId: visitorTopicId },@@ -1942,28 +1925,6 @@ describe('MessageModel Query Tests', () => {expect(ownTranscript.items.map((item) => item.id)).toEqual(['creator-direct-msg']);});- it('keeps countByTopic working for the visitor turn cap when the runtime opts in', async () => {- // The per-topic turn cap depends on counting visitor messages, and after- // the ownership() flip the default scope excludes visitor rows. The- // share runtime (`reserveShareVisitorTurn` in- // `shareVisitorAbuseGuards.ts`) constructs `MessageModel` with- // `includeShareVisitor: true`; mirror that opt-in here.- const defaultCount = await messageModel.countByTopic({- role: 'user',- topicId: visitorTopicId,- });- expect(defaultCount).toBe(0);-- const shareRuntimeMessageModel = new MessageModel(serverDB, userId, undefined, undefined, {- includeShareVisitor: true,- });- const optedInCount = await shareRuntimeMessageModel.countByTopic({- role: 'user',- topicId: visitorTopicId,- });- expect(optedInCount).toBe(1);- });-it('hides synthetic message-group nodes when the creator reads a visitor topic', async () => {// Regression for `queryMessageGroupNodes`: a creator's default// `query({ topicId })` on a visitor topic returned no messages but@@ -2071,18 +2032,9 @@ describe('MessageModel Query Tests', () => {expect(child.council[0].sender).toBeNull();expect(child.council[0].usage).toBeUndefined();expect(child.council[0].model).toBeUndefined();-- // With `showModelInfo` the model snapshot survives on both the child- // and the recursed council members, and children stay attached.- const kept = toVisitorMessage(compressedGroupNode, { showModelInfo: true });- const keptChild = (kept.compressedMessages as any[])[0].children[0];- expect(keptChild.model).toBe('gpt-4o');- expect(keptChild.usage).toEqual({ totalTokens: 42 });- expect(keptChild.council[0].model).toBe('gpt-4o');- expect(keptChild.council[0].usage).toEqual({ totalTokens: 7 });});- it('keeps the narrow snapshot for compareGroup children in both modes', async () => {+ it('strips model and provider from compareGroup children', async () => {const compareGroupNode = {children: [{@@ -2102,10 +2054,6 @@ describe('MessageModel Query Tests', () => {expect((stripped.children as any[])[0].model).toBeNull();expect((stripped.children as any[])[0].provider).toBeNull();expect((stripped.children as any[])[0].content).toBe('variant');-- const kept = toVisitorMessage(compareGroupNode, { showModelInfo: true });- expect((kept.children as any[])[0].model).toBe('gpt-4o');- expect((kept.children as any[])[0].provider).toBe('openai');});});diff --git a/packages/database/src/models/__tests__/messages/visitor.projection.test.ts b/packages/database/src/models/__tests__/messages/visitor.projection.test.tsindex f2cb01a85af..df77eedb736 100644--- a/packages/database/src/models/__tests__/messages/visitor.projection.test.ts+++ b/packages/database/src/models/__tests__/messages/visitor.projection.test.ts@@ -63,8 +63,8 @@ describe('redactCreatorPrivateBlob', () => {describe('sanitizeVisitorError', () => {it('keeps an allowlisted business code readable', () => {const error = {- message: 'This share hit its turn cap',- type: ChatErrorType.ShareTurnLimitExceeded,+ message: "You reached this share's message limit",+ type: ChatErrorType.ShareMessageLimitExceeded,};expect(sanitizeVisitorError(error)).toEqual(error);@@ -124,25 +124,6 @@ describe('toVisitorMessage', () => {expect(visitor.taskDetail).toEqual({ id: 'td-1', status: 'success' });});- it('keeps the model snapshot when the share opts in', () => {- const visitor = toVisitorMessage(- message({- metadata: { usage: { totalTokens: 9 }, workingDirectory: '/repo' },- model: 'gpt-4o',- provider: 'openai',- taskDetail: { id: 'td-1', usage: { totalTokens: 3 } },- usage: { totalTokens: 9 },- }),- { showModelInfo: true },- );-- expect(visitor.model).toBe('gpt-4o');- expect(visitor.provider).toBe('openai');- expect(visitor.usage).toEqual({ totalTokens: 9 });- expect(visitor.metadata).toEqual({ usage: { totalTokens: 9 }, workingDirectory: '/repo' });- expect(visitor.taskDetail).toEqual({ id: 'td-1', usage: { totalTokens: 3 } });- });-it('strips the per-callback model snapshot from signal callbacks', () => {const visitor = toVisitorMessage(message({@@ -183,12 +164,6 @@ describe('toVisitorMessage', () => {expect(hidden).not.toHaveProperty('workspaceId');expect(hidden.totalCost).toBeNull();expect(hidden.event).toEqual({ cumulativeCost: null, cumulativeUsage: null, status: 'done' });-- const shown = asRecords(- toVisitorMessage(message({ works: [work] }), { showModelInfo: true }).works,- )[0];- expect(shown).not.toHaveProperty('userId');- expect(shown.totalCost).toBe(0.8);});it('nulls the model snapshot on group-node projections', () => {@@ -204,18 +179,6 @@ describe('toVisitorMessage', () => {expect(asRecords(visitor.pinnedMessages)[0]).toMatchObject({ model: null, provider: null });});- it('recurses into a compareGroup that has model info sharing on', () => {- const visitor = toVisitorMessage(- message({- children: [groupSnapshot('child-1', 'first')],- role: 'compareGroup',- }),- { showModelInfo: true },- );-- expect(asRecords(visitor.children)[0]).toMatchObject({ model: 'gpt-4o' });- });-it('recurses into nested assistantGroup children, members and compacted rows', () => {const nested = {content: 'nested',diff --git a/packages/database/src/models/__tests__/shareVisitorAbuseGuards.race.test.ts b/packages/database/src/models/__tests__/shareVisitorAbuseGuards.race.test.tsindex 3187fcfbe52..bd4baca86f8 100644--- a/packages/database/src/models/__tests__/shareVisitorAbuseGuards.race.test.ts+++ b/packages/database/src/models/__tests__/shareVisitorAbuseGuards.race.test.ts@@ -1,4 +1,5 @@-import { and, count, eq } from 'drizzle-orm';+import { ChatErrorType } from '@lobechat/types';+import { and, count, eq, inArray } from 'drizzle-orm';import { afterAll, beforeEach, describe, expect, it } from 'vitest';import {@@ -11,21 +12,20 @@ import { agents, agentShares, messages, topics, users, workspaces } from '../../import type { LobeChatDatabase } from '../../type';import { AgentShareModel } from '../agentShare';-// Real-Postgres reproduction of the agent-share visitor abuse-cap race.+// Real-Postgres reproduction of the agent-share visitor message-cap race.//-// `shareChat.execAgent` counts a visitor's existing topics (or turns) and-// compares against the cap BEFORE dispatching to `AiAgentService.execAgent`,+// `shareChat.execAgent` counts a visitor's user messages and compares against+// `maxMessagesPerVisitor` BEFORE dispatching to `AiAgentService.execAgent`,// which performs the real INSERT much later — two unrelated, unlocked-// statements with nothing serializing them. A burst of concurrent requests-// from the same visitor could all read the same pre-insert count and all-// insert, exceeding `maxTopicsPerVisitor` / `maxTurnsPerTopic` by an arbitrary-// amount.+// statements with nothing serializing them. A burst of concurrent requests from+// the same visitor could all read the same pre-insert count and all insert,+// exceeding the cap by an arbitrary amount.//-// `reserveShareVisitorTopicOrThrow` / `reserveShareVisitorTurnOrThrow`-// (`apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts`) close this by+// `reserveShareVisitorTurnOrThrow`+// (`apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts`) closes this by// taking the SAME `agents.id FOR UPDATE` row lock every share-mutation path-// takes and re-checking the exact same counter INSIDE the same transaction as-// the INSERT, immediately before it runs.+// takes and re-counting INSIDE the same transaction as the INSERT, immediately+// before it runs.//// Under the client-db PGlite engine, concurrent transactions serialize on the// single session, so the cap assertions pass trivially there; against a REAL@@ -46,7 +46,7 @@ const cleanup = async () => {await serverDB.delete(users).where(eq(users.id, ownerId));};-describe('reserveShareVisitorTopicOrThrow — visitor topic cap race (real Postgres)', () => {+describe('reserveShareVisitorTurnOrThrow — visitor message cap (real Postgres)', () => {beforeEach(async () => {await cleanup();await serverDB.insert(users).values([{ id: ownerId }]);@@ -54,108 +54,72 @@ describe('reserveShareVisitorTopicOrThrow — visitor topic cap race (real PostgafterAll(cleanup);- it('never lets concurrent new-topic requests exceed maxTopicsPerVisitor', async () => {+ it('never lets concurrent sends across topics exceed maxMessagesPerVisitor', async () => {const TRIALS = 5;const CONCURRENCY = 6;- const CAP = 3;+ const CAP = 4;let overCapTrials = 0;for (let i = 0; i < TRIALS; i++) {- const agentId = `share-topic-race-agent-${i}`;+ const agentId = `share-message-race-agent-${i}`;+ const topicIds = [`share-message-race-topic-${i}-a`, `share-message-race-topic-${i}-b`];await serverDB.insert(agents).values({ id: agentId, model: 'gpt-4o', userId: ownerId });// The cap is read fresh from the real `agentShares.shareConfig` inside// the guard's own locked transaction (`AgentShareModel// .readCurrentVisitorCaps`) — never a caller-supplied parameter.const share = await new AgentShareModel(serverDB, ownerId).create(agentId, 'link');await new AgentShareModel(serverDB, ownerId).updateConfig(agentId, {- maxTopicsPerVisitor: CAP,- });-- // Simulate CONCURRENCY visitor tabs/scripts all sending a first message- // to a brand-new topic at the same time.- const results = await Promise.allSettled(- Array.from({ length: CONCURRENCY }, (_, n) =>- reserveShareVisitorTopic(- {- agentId,- db: serverDB,- expectedShareId: share.id,- ownerId,- visitorUserId,- },- { agentId, senderId: visitorUserId, title: `visitor topic ${n}`, trigger: 'chat' },- ),- ),- );-- const fulfilled = results.filter((r) => r.status === 'fulfilled').length;- const rejected = results.filter((r) => r.status === 'rejected').length;- expect(fulfilled + rejected).toBe(CONCURRENCY);-- const [{ value: actualTopicCount }] = await serverDB- .select({ value: count(topics.id) })- .from(topics)- .where(and(eq(topics.agentId, agentId), eq(topics.senderId, visitorUserId)));-- // The reservation's own return value and the real row count must agree —- // a lost race would show up as more rows than reservations reported, or- // vice versa.- if (fulfilled !== CAP || actualTopicCount !== CAP) overCapTrials++;- }-- expect(overCapTrials).toBe(0);- });-});--describe('reserveShareVisitorTurnOrThrow — visitor turn cap race (real Postgres)', () => {- beforeEach(async () => {- await cleanup();- await serverDB.insert(users).values([{ id: ownerId }]);- });-- afterAll(cleanup);-- it('never lets concurrent sends to the same topic exceed maxTurnsPerTopic', async () => {- const TRIALS = 5;- const CONCURRENCY = 6;- const CAP = 3;- let overCapTrials = 0;-- for (let i = 0; i < TRIALS; i++) {- const agentId = `share-turn-race-agent-${i}`;- const topicId = `share-turn-race-topic-${i}`;- await serverDB.insert(agents).values({ id: agentId, model: 'gpt-4o', userId: ownerId });- const share = await new AgentShareModel(serverDB, ownerId).create(agentId, 'link');- await new AgentShareModel(serverDB, ownerId).updateConfig(agentId, {- maxTurnsPerTopic: CAP,- });- await serverDB.insert(topics).values({- agentId,- id: topicId,- senderId: visitorUserId,- userId: ownerId,+ maxMessagesPerVisitor: CAP,});+ await serverDB+ .insert(topics)+ .values(topicIds.map((id) => ({ agentId, id, senderId: visitorUserId, userId: ownerId })));+ // One earlier message and the Agent's reply: only the user message counts.+ await serverDB.insert(messages).values([+ {+ content: 'earlier',+ id: `earlier-${i}`,+ role: 'user',+ topicId: topicIds[0],+ userId: ownerId,+ },+ {+ content: 'reply',+ id: `reply-${i}`,+ role: 'assistant',+ topicId: topicIds[0],+ userId: ownerId,+ },+ ]);- // Simulate CONCURRENCY sends to the SAME existing topic at the same time.+ // Simulate CONCURRENCY sends from the same visitor, spread over two topics.const results = await Promise.allSettled(- Array.from({ length: CONCURRENCY }, (_, n) =>- reserveShareVisitorTurn(- { agentId, db: serverDB, expectedShareId: share.id, ownerId, topicId },- { content: `turn ${n}`, role: 'user', topicId },- ),- ),+ Array.from({ length: CONCURRENCY }, (_, n) => {+ const topicId = topicIds[n % 2];+ return reserveShareVisitorTurn(+ { agentId, db: serverDB, expectedShareId: share.id, ownerId, visitorUserId },+ { content: `message ${n}`, role: 'user', topicId },+ );+ }),);const fulfilled = results.filter((r) => r.status === 'fulfilled').length;- const rejected = results.filter((r) => r.status === 'rejected').length;- expect(fulfilled + rejected).toBe(CONCURRENCY);-- const [{ value: actualTurnCount }] = await serverDB+ const rejected = results.filter((r) => r.status === 'rejected');+ expect(fulfilled + rejected.length).toBe(CONCURRENCY);+ for (const r of rejected) {+ expect((r as PromiseRejectedResult).reason).toMatchObject({+ code: 'TOO_MANY_REQUESTS',+ message: ChatErrorType.ShareMessageLimitExceeded,+ });+ }++ const [{ value: actualUserMessages }] = await serverDB.select({ value: count(messages.id) }).from(messages)- .where(and(eq(messages.topicId, topicId), eq(messages.role, 'user')));+ .where(and(inArray(messages.topicId, topicIds), eq(messages.role, 'user')));- if (fulfilled !== CAP || actualTurnCount !== CAP) overCapTrials++;+ // The earlier message uses one slot, so CAP - 1 sends fit.+ if (fulfilled !== CAP - 1 || actualUserMessages !== CAP) overCapTrials++;}expect(overCapTrials).toBe(0);@@ -203,7 +167,6 @@ describe('shareVisitorAbuseGuards — revoked share authorization', () => {db: serverDB,expectedShareId: share.id,ownerId,- visitorUserId,workspaceId,},{ agentId, senderId: visitorUserId, title: 'workspace-scoped topic' },@@ -217,7 +180,6 @@ describe('shareVisitorAbuseGuards — revoked share authorization', () => {db: serverDB,expectedShareId: share.id,ownerId,- visitorUserId,workspaceId: otherWorkspaceId,},{ agentId, senderId: visitorUserId, title: 'wrong-workspace topic' },@@ -242,7 +204,7 @@ describe('shareVisitorAbuseGuards — revoked share authorization', () => {await expect(reserveShareVisitorTopic(- { agentId, db: serverDB, expectedShareId: share.id, ownerId, visitorUserId },+ { agentId, db: serverDB, expectedShareId: share.id, ownerId },{ agentId, senderId: visitorUserId, title: 'stale-topic' },),).rejects.toMatchObject({ code: 'FORBIDDEN' });@@ -270,7 +232,7 @@ describe('shareVisitorAbuseGuards — revoked share authorization', () => {await expect(reserveShareVisitorTopic(- { agentId, db: serverDB, expectedShareId: staleShare.id, ownerId, visitorUserId },+ { agentId, db: serverDB, expectedShareId: staleShare.id, ownerId },{ agentId, senderId: visitorUserId, title: 'stale-instance-topic' },),).rejects.toMatchObject({ code: 'FORBIDDEN' });@@ -297,7 +259,7 @@ describe('shareVisitorAbuseGuards — revoked share authorization', () => {await expect(reserveShareVisitorTurn(- { agentId, db: serverDB, expectedShareId: share.id, ownerId, topicId: topic.id },+ { agentId, db: serverDB, expectedShareId: share.id, ownerId, visitorUserId },{ content: 'stale-turn', role: 'user', topicId: topic.id },),).rejects.toMatchObject({ code: 'FORBIDDEN' });diff --git a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts b/packages/database/src/models/__tests__/topics/topic.characterization.test.tsindex fdcf2afee24..e8073cf3f40 100644--- a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.characterization.test.ts@@ -52,9 +52,9 @@ const PUBLIC_METHODS = ['batchInsert','cancelRateLimitContinuation','count',- 'countBySender','countInFlightInDirectory','countLiveTopicsUsingWorktree',+ 'countMessagesBySender','countShareVisitors','countTopicsForMemoryExtractor','create',@@ -318,14 +318,39 @@ describe('TopicModel - characterization', () => {expect(await topicModel.findShareVisitorTopicIds(['visitor-topic', 'agent-topic'])).toEqual(['visitor-topic',]);- expect(await topicModel.countBySender({ agentId, senderId: 'visitor-1' })).toBe(2);- expect(await topicModel.countBySender({ agentId, senderId: 'visitor-2' })).toBe(0);expect(await topicModel.countShareVisitors({ agentId })).toEqual({topicCount: 2,visitorCount: 1,});});+ it('countMessagesBySender counts only the visitor user messages across their topics', async () => {+ await serverDB.insert(topics).values({+ agentId,+ id: 'visitor-2-topic',+ senderId: 'visitor-2',+ title: 'visitor 2 own',+ userId,+ });+ await serverDB.insert(messages).values([+ { id: 'v1-user-a', role: 'user', topicId: 'visitor-topic', userId },+ { id: 'v1-reply-a', role: 'assistant', topicId: 'visitor-topic', userId },+ { id: 'v1-user-b', role: 'user', topicId: 'visitor-topic', userId },+ { id: 'v1-user-c', role: 'user', topicId: 'visitor-topic-2', userId },+ { id: 'v1-tool', role: 'tool', topicId: 'visitor-topic-2', userId },+ { id: 'v2-user', role: 'user', topicId: 'visitor-2-topic', userId },+ { id: 'creator-user', role: 'user', topicId: 'agent-topic', userId },+ ]);++ // Replies, tool rows, other visitors and the creator's own topics never count.+ expect(await topicModel.countMessagesBySender({ agentId, senderId: 'visitor-1' })).toBe(3);+ expect(await topicModel.countMessagesBySender({ agentId, senderId: 'visitor-2' })).toBe(1);+ expect(await topicModel.countMessagesBySender({ agentId, senderId: 'visitor-3' })).toBe(0);++ const foreignModel = new TopicModel(serverDB, otherUserId);+ expect(await foreignModel.countMessagesBySender({ agentId, senderId: 'visitor-1' })).toBe(0);+ });+it('findRecentByBotThread matches the bot thread id, newest first, limited', async () => {await serverDB.insert(topics).values([{diff --git a/packages/database/src/models/agentShare.ts b/packages/database/src/models/agentShare.tsindex 9a9d3f7d3ce..14aeb07b20e 100644--- a/packages/database/src/models/agentShare.ts+++ b/packages/database/src/models/agentShare.ts@@ -1,7 +1,6 @@import {AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,- AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,- AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,+ AGENT_SHARE_DEFAULT_MAX_MESSAGES_PER_VISITOR,AGENT_SHARE_DEFAULT_MONTHLY_SPEND_LIMIT,AGENT_SHARE_SLUG_PATTERN,RESERVED_AGENT_SHARE_SLUGS,@@ -29,11 +28,9 @@ const DEFAULT_AGENT_SHARE_CONFIG = {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,+ maxMessagesPerVisitor: AGENT_SHARE_DEFAULT_MAX_MESSAGES_PER_VISITOR,monthlySpendLimit: AGENT_SHARE_DEFAULT_MONTHLY_SPEND_LIMIT,showErrorDetails: false,- showModelInfo: false,toolGrants: [],} satisfies AgentShareConfig;@@ -49,12 +46,10 @@ const normalizeAgentShareConfig = (deviceAllowUserIds: config?.deviceAllowUserIds ?? [],featuredWorkIds: config?.featuredWorkIds ?? [],maxFileStorage: config?.maxFileStorage ?? DEFAULT_AGENT_SHARE_CONFIG.maxFileStorage,- maxTopicsPerVisitor:- config?.maxTopicsPerVisitor ?? DEFAULT_AGENT_SHARE_CONFIG.maxTopicsPerVisitor,- maxTurnsPerTopic: config?.maxTurnsPerTopic ?? DEFAULT_AGENT_SHARE_CONFIG.maxTurnsPerTopic,+ maxMessagesPerVisitor:+ config?.maxMessagesPerVisitor ?? DEFAULT_AGENT_SHARE_CONFIG.maxMessagesPerVisitor,monthlySpendLimit: config?.monthlySpendLimit ?? DEFAULT_AGENT_SHARE_CONFIG.monthlySpendLimit,showErrorDetails: config?.showErrorDetails ?? DEFAULT_AGENT_SHARE_CONFIG.showErrorDetails,- showModelInfo: config?.showModelInfo ?? DEFAULT_AGENT_SHARE_CONFIG.showModelInfo,/*** Left absent rather than defaulted to `[]`: both read as "no skill* granted", so a default would only write a value the creator never picked.@@ -528,7 +523,7 @@ export class AgentShareModel {});/**- * Read the CURRENT `maxTopicsPerVisitor` / `maxTurnsPerTopic` caps for an+ * Read the CURRENT `maxMessagesPerVisitor` cap for an* agent's share, bypassing any snapshot a caller might already be holding —* intended to be called from inside the SAME locked transaction a* visitor-abuse guard uses to recount and insert, so a cap reduction the@@ -544,9 +539,7 @@ export class AgentShareModel {db: LobeChatDatabase,agentId: string,): Promise<- Required<- Pick<AgentShareConfig, 'maxTopicsPerVisitor' | 'maxTurnsPerTopic' | 'monthlySpendLimit'>- > & {+ Pick<NormalizedAgentShareConfig, 'maxMessagesPerVisitor' | 'monthlySpendLimit'> & {shareId: string | null;workspaceId: string | null;}@@ -563,9 +556,8 @@ export class AgentShareModel {const normalized = normalizeAgentShareConfig(row?.shareConfig ?? null);return {- maxTopicsPerVisitor: normalized.maxTopicsPerVisitor!,- maxTurnsPerTopic: normalized.maxTurnsPerTopic!,- monthlySpendLimit: normalized.monthlySpendLimit!,+ maxMessagesPerVisitor: normalized.maxMessagesPerVisitor,+ monthlySpendLimit: normalized.monthlySpendLimit,shareId: row?.id ?? null,workspaceId: row?.workspaceId ?? null,};diff --git a/packages/database/src/models/message/analytics.ts b/packages/database/src/models/message/analytics.tsindex b435272ca7e..9ff0d72bc85 100644--- a/packages/database/src/models/message/analytics.ts+++ b/packages/database/src/models/message/analytics.ts@@ -110,9 +110,8 @@ export class MessageAnalyticsQueries extends MessageScope {* Agent-share visitor messages carry the creator's `userId`, so personal* analytics must exclude them (visitor usage is reported separately by the* share usage center) — see `notShareVisitorMessage` in `../utils/shareVisitor`.- *- * MUST NOT be applied to {@link countByTopic} — see that method's JSDoc for- * why exact per-topic turn counting needs the visitor topic's own messages.+ * The per-visitor message cap counts through `TopicModel.countMessagesBySender`+ * instead, because it needs exactly those visitor messages.*/private analyticsConditions = (params?: MessageAnalyticsFilters) => [this.ownership(),diff --git a/packages/database/src/models/message/index.ts b/packages/database/src/models/message/index.tsindex ad0399cd223..361f9c7a231 100644--- a/packages/database/src/models/message/index.ts+++ b/packages/database/src/models/message/index.ts@@ -53,7 +53,6 @@ export class MessageModel {queryLastUserMessageByTopics: MessageConversationQueries['queryLastUserMessageByTopics'];query: MessageConversationQueries['query'];queryForVisitor: MessageConversationQueries['queryForVisitor'];- countByTopic: MessageConversationQueries['countByTopic'];queryTopicTranscript: MessageConversationQueries['queryTopicTranscript'];queryTopicMessageTree: MessageConversationQueries['queryTopicMessageTree'];queryTopicMessagesByCursor: MessageConversationQueries['queryTopicMessagesByCursor'];@@ -173,7 +172,6 @@ export class MessageModel {this.queryLastUserMessageByTopics = conversation.queryLastUserMessageByTopics;this.query = conversation.query;this.queryForVisitor = conversation.queryForVisitor;- this.countByTopic = conversation.countByTopic;this.queryTopicTranscript = conversation.queryTopicTranscript;this.queryTopicMessageTree = conversation.queryTopicMessageTree;this.queryTopicMessagesByCursor = conversation.queryTopicMessagesByCursor;diff --git a/packages/database/src/models/message/query.ts b/packages/database/src/models/message/query.tsindex e112c03d152..df5223a8971 100644--- a/packages/database/src/models/message/query.ts+++ b/packages/database/src/models/message/query.ts@@ -293,8 +293,8 @@ export class MessageConversationQueries extends MessageScope {* Share messages persist under the CREATOR's account (see `shareChat.ts`),* so `query()`'s joined `sender` and the billing/model-snapshot fields* describe the creator, not the visitor reading them. `redaction` carries the- * share's own `showModelInfo` / `showErrorDetails` switches; omitting it- * strips everything (fail closed).+ * share's own `showErrorDetails` switch; omitting it strips everything+ * (fail closed). Model, provider and spend never reach a visitor.*/queryForVisitor = async (params: QueryMessageParams = {},@@ -322,30 +322,6 @@ export class MessageConversationQueries extends MessageScope {return messageItems.map((message) => toVisitorMessage(message, options.redaction));};- /**- * Exact per-topic turn count for one role, used by `maxTurnsPerTopic`.- *- * MUST NOT reuse {@link MessageModel.count}: its `analyticsConditions()` ANDs- * in `notShareVisitorMessage()`, which excludes every message whose topic has- * a non-null `senderId` — i.e. every agent-share visitor topic. That- * predicate is correct for personal analytics (visitor usage is reported- * separately), but it would make `count()` return 0 forever for a share- * topic, silently disabling the turn cap.- *- * Safe without a visitor/ownership check here: the caller (shareChat router /- * `reserveShareVisitorTurn`) already resolved and authorized the topic, and- * `this.ownership()` matches because share messages carry the creator's- * `userId` (the model is constructed with `share.ownerId`).- */- countByTopic = async ({ role, topicId }: { role: string; topicId: string }): Promise<number> => {- const result = await this.db- .select({ count: count(messages.id) })- .from(messages)- .where(and(this.ownership(), eq(messages.topicId, topicId), eq(messages.role, role)));-- return result[0].count;- };-/*** Return a lightweight, ownership-scoped transcript for a topic.*diff --git a/packages/database/src/models/message/types.ts b/packages/database/src/models/message/types.tsindex c790f1e2996..1956956a910 100644--- a/packages/database/src/models/message/types.ts+++ b/packages/database/src/models/message/types.ts@@ -257,12 +257,6 @@ export interface VisitorRedactionOptions {* builds.*/showErrorDetails?: boolean;- /**- * `AgentShareConfig.showModelInfo`. When false, the creator's model /- * provider choice and the token/cost snapshot are stripped everywhere they- * appear, at any nesting depth.- */- showModelInfo?: boolean;}export interface SoftDeletedMessage {diff --git a/packages/database/src/models/message/visitor.ts b/packages/database/src/models/message/visitor.tsindex eb42b30a10f..c3de2d02c98 100644--- a/packages/database/src/models/message/visitor.ts+++ b/packages/database/src/models/message/visitor.ts@@ -199,8 +199,7 @@ export const redactCreatorPrivateBlob = <T>(value: T): T => {* model-runtime change adds.*/const VISITOR_SAFE_ERROR_TYPES = new Set<string>([- ChatErrorType.ShareTurnLimitExceeded,- ChatErrorType.ShareTopicLimitExceeded,+ ChatErrorType.ShareMessageLimitExceeded,ChatErrorType.ShareSpendLimitExceeded,ChatErrorType.ShareHeterogeneousAgentUnsupported,ChatErrorType.ShareHeteroDeviceUnavailable,@@ -286,34 +285,29 @@ const sanitizeVisitorMetadata = (* Project Work summaries for a share visitor. A visitor run executes as the* creator, so `userId` / `workspaceId` on every Work are the CREATOR's account* and workspace — dropped unconditionally, like the message-level `sender`.- * The version spend snapshot is the creator's billing figure and follows the- * `showModelInfo` gate (`stripSpend`).+ * The version spend snapshot is the creator's billing figure and is cleared too.** The identity keys are omitted rather than nulled (`userId` is non-nullable on* `WorkItem`); no visitor-facing Work surface reads them.*/const sanitizeVisitorWorks = (works: WorkSummaryItem[] | undefined,- { stripSpend }: { stripSpend: boolean },): WorkSummaryItem[] | undefined =>works?.map((work) => {const { userId: _userId, workspaceId: _workspaceId, ...rest } = work;- const visible = stripSpend- ? {- ...rest,- event: { ...rest.event, cumulativeCost: null, cumulativeUsage: null },- totalCost: null,- }- : rest;- return visible as WorkSummaryItem;+ return {+ ...rest,+ event: { ...rest.event, cumulativeCost: null, cumulativeUsage: null },+ totalCost: null,+ } as WorkSummaryItem;});/*** Strip creator-only fields from a message row before it reaches an- * agent-share visitor. Creator account identity never crosses the share- * boundary; the creator's model/provider/spend choices cross it only when the- * share sets `showModelInfo`, and raw error payloads only when it sets- * `showErrorDetails` ({@link VisitorRedactionOptions}).+ * agent-share visitor. Creator account identity and the creator's+ * model/provider/spend choices never cross the share boundary; raw error+ * payloads cross it only when the share sets `showErrorDetails`+ * ({@link VisitorRedactionOptions}).** Built from {@link VISITOR_MESSAGE_ALLOWED_KEYS} plus explicit handling for* the fields that need transformation rather than a plain allow/deny.@@ -322,47 +316,30 @@ export const toVisitorMessage = (message: UIChatMessage,options: VisitorRedactionOptions = {},): UIChatMessage => {- const stripModelInfo = !options.showModelInfo;-return {...pickAllowedKeys(message),// `sender` is the CREATOR's account identity — never gated by any config// flag, since no share setting is about exposing whose account runs the// agent.sender: null,- extra: stripModelInfo ? sanitizeVisitorExtra(message.extra) : message.extra,- metadata: stripModelInfo ? sanitizeVisitorMetadata(message.metadata) : message.metadata,+ extra: sanitizeVisitorExtra(message.extra),+ metadata: sanitizeVisitorMetadata(message.metadata),// Unbounded per-tool blobs: a tool runtime controls everything inside// them, so a fixed field allowlist can't classify their contents — the// creator-identity key set is recursed out instead.- pluginError: stripModelInfo- ? redactCreatorPrivateBlob(message.pluginError)- : message.pluginError,- pluginState: stripModelInfo- ? redactCreatorPrivateBlob(message.pluginState)- : message.pluginState,+ pluginError: redactCreatorPrivateBlob(message.pluginError),+ pluginState: redactCreatorPrivateBlob(message.pluginState),// Projected, not redacted — see `sanitizeVisitorError`.error: sanitizeVisitorError(message.error, options),- ...(stripModelInfo- ? {- model: undefined,- provider: undefined,- signalCallbacks: sanitizeVisitorSignalCallbacks(message.signalCallbacks),- taskDetail: sanitizeVisitorTaskDetail(message.taskDetail),- usage: undefined,- }- : {- model: message.model,- provider: message.provider,- signalCallbacks: message.signalCallbacks,- taskDetail: message.taskDetail,- usage: message.usage,- }),+ model: undefined,+ provider: undefined,+ signalCallbacks: sanitizeVisitorSignalCallbacks(message.signalCallbacks),+ taskDetail: sanitizeVisitorTaskDetail(message.taskDetail),+ usage: undefined,// Work summaries reach a visitor only when the query ran under their share// scope (see `queryForVisitor`), so every item here was registered from- // this visitor's own topic. Creator identity is always dropped; spend- // follows the `showModelInfo` gate — see `sanitizeVisitorWorks`.- works: sanitizeVisitorWorks(message.works, { stripSpend: stripModelInfo }),+ // this visitor's own topic. Creator identity and spend are always dropped.+ works: sanitizeVisitorWorks(message.works),// A compacted topic nests raw rows under the group node, and group chat// nests member messages, so anything less than a full recursive sanitize// would leave the creator's identity on everything inside it.@@ -375,15 +352,11 @@ export const toVisitorMessage = (members: message.members.map((nested) => toVisitorMessage(nested, options)),}),// `pinnedMessages` is only ever the narrow group-node projection (see- // `queryMessageGroupNodes` in the Compression branch). Emit it in both- // modes — sanitized when the model snapshot is not shared, otherwise- // untouched.+ // `queryMessageGroupNodes` in the Compression branch)....(message.pinnedMessages && {- pinnedMessages: stripModelInfo- ? (sanitizeVisitorGroupSnapshots(- message.pinnedMessages as unknown as VisitorGroupSnapshotProjection[],- ) as unknown as UIChatMessage['pinnedMessages'])- : message.pinnedMessages,+ pinnedMessages: sanitizeVisitorGroupSnapshots(+ message.pinnedMessages as unknown as VisitorGroupSnapshotProjection[],+ ) as unknown as UIChatMessage['pinnedMessages'],}),// `children` is polymorphic: a `compareGroup` node carries the same bare// {id, role, model, provider, content, createdAt} snapshot as@@ -399,11 +372,9 @@ export const toVisitorMessage = (...(message.children && {children:message.role === 'compareGroup'- ? stripModelInfo- ? (sanitizeVisitorGroupSnapshots(- message.children as unknown as VisitorGroupSnapshotProjection[],- ) as unknown as UIChatMessage['children'])- : message.children+ ? (sanitizeVisitorGroupSnapshots(+ message.children as unknown as VisitorGroupSnapshotProjection[],+ ) as unknown as UIChatMessage['children']): ((message.children as unknown as UIChatMessage[]).map((child) =>toVisitorMessage(child, options),) as unknown as UIChatMessage['children']),diff --git a/packages/database/src/models/topic/context.ts b/packages/database/src/models/topic/context.tsindex b912e807fb2..9a93f556b77 100644--- a/packages/database/src/models/topic/context.ts+++ b/packages/database/src/models/topic/context.ts@@ -62,7 +62,7 @@ export const createTopicModelContext = ({* Raw workspace/user scope, WITHOUT the visitor exclusion. Backing store for* both {@link ownership} and {@link mine}, and the escape hatch for methods* that must see visitor rows independent of the instance flag- * ({@link queryBySender} / {@link countBySender} / {@link countShareVisitors}).+ * ({@link queryBySender} / {@link countMessagesBySender} / {@link countShareVisitors}).*/workspaceScope: () =>buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, topics),@@ -90,7 +90,7 @@ export const createTopicModelContext = ({** `mine()` deliberately does NOT AND {@link notShareVisitor} — it is the* per-user variant of {@link workspaceScope} and the share-scoped methods- * ({@link queryBySender} / {@link countBySender} / {@link countShareVisitors})+ * ({@link queryBySender} / {@link countMessagesBySender} / {@link countShareVisitors})* layer their own `senderId` predicate on top of it. Creator-facing* destructive sweeps that reach for `mine()` still get the visitor* exclusion by AND-ing {@link notShareVisitor} themselves.@@ -108,7 +108,7 @@ export const createTopicModelContext = ({* true`, so the share runtime opts in explicitly and every other caller* gets the visitor guard for free.*- * The visitor-scoped counterparts ({@link queryBySender}, {@link countBySender})+ * The visitor-scoped counterparts ({@link queryBySender}, {@link countMessagesBySender})* intentionally do the opposite — they match on `senderId`, not exclude* it — and use {@link mine} (which skips this helper).*/diff --git a/packages/database/src/models/topic/index.ts b/packages/database/src/models/topic/index.tsindex 1c9e9f71a3b..2708596d4de 100644--- a/packages/database/src/models/topic/index.ts+++ b/packages/database/src/models/topic/index.ts@@ -151,7 +151,7 @@ export class TopicModel {// **************** Agent Share (visitor-scoped) *************** //queryBySender = this.withContext(shareVisitor.queryBySender);- countBySender = this.withContext(shareVisitor.countBySender);+ countMessagesBySender = this.withContext(shareVisitor.countMessagesBySender);countShareVisitors = this.withContext(shareVisitor.countShareVisitors);// **************** Create *************** //diff --git a/packages/database/src/models/topic/shareVisitor.ts b/packages/database/src/models/topic/shareVisitor.tsindex c7c07cf4540..f680bb93c00 100644--- a/packages/database/src/models/topic/shareVisitor.ts+++ b/packages/database/src/models/topic/shareVisitor.ts@@ -2,20 +2,11 @@ import { AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT } from '@lobechat/const';import type { ChatTopicMetadata } from '@lobechat/types';import { and, count, countDistinct, desc, eq, isNotNull } from 'drizzle-orm';-import { topics } from '../../schemas';+import { messages, topics } from '../../schemas';import type { TopicModelContext } from './context';import type { VisitorRunningOperation, VisitorTopicItem } from './types';-/**- * Fallback page size for {@link TopicModel.queryBySender} when a caller- * doesn't pass one. Pinned to the package default per-visitor topic cap.- *- * Callers with a live share config (e.g. `shareChat.getTopics`) MUST pass the- * share's actual resolved `maxTopicsPerVisitor` as `pageSize` instead of- * relying on this default — a creator who raises the cap above the default- * would otherwise have a visitor's list silently truncated below what that- * visitor is actually allowed to create.- */+/** Fallback page size for {@link TopicModel.queryBySender} when a caller doesn't pass one. */export const VISITOR_TOPIC_PAGE_SIZE = AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT;/**@@ -82,33 +73,37 @@ export const queryBySender = async (};/**- * Per-visitor topic count on a shared agent — drives `maxTopicsPerVisitor`.- * Same `(agentId, senderId)` scoping as {@link queryBySender}; see that- * method's JSDoc for why there is no share-id dimension.+ * Messages one visitor sent to a shared agent, across all of their topics —+ * drives `maxMessagesPerVisitor`. Only the visitor's own (`user`) messages+ * count, never the Agent's replies. Same `(agentId, senderId)` scoping as+ * {@link queryBySender}; see that method's JSDoc for why there is no share-id+ * dimension.*/-export const countBySender = async (+export const countMessagesBySender = async (ctx: TopicModelContext,- {- agentId,- senderId,- }: {- agentId: string;- senderId: string;- },+ { agentId, senderId }: { agentId: string; senderId: string },): Promise<number> => {- const result = await ctx.db- .select({ count: count(topics.id) })- .from(topics)- .where(and(ctx.mine(), eq(topics.agentId, agentId), eq(topics.senderId, senderId)));+ const [result] = await ctx.db+ .select({ count: count(messages.id) })+ .from(messages)+ .innerJoin(topics, eq(messages.topicId, topics.id))+ .where(+ and(+ ctx.mine(),+ eq(topics.agentId, agentId),+ eq(topics.senderId, senderId),+ eq(messages.role, 'user'),+ ),+ );- return result[0].count;+ return Number(result?.count ?? 0);};/*** Creator-facing roll-up for one shared agent: how many conversations* visitors started, and how many distinct visitors started them.*- * Counterpart to {@link countBySender}, which counts ONE visitor. Both rely+ * Counterpart to {@link countMessagesBySender}, which counts ONE visitor. Both rely* on `senderId` being non-null only for share-originated topics, so the* creator's own conversations with the same agent are excluded. Scoped by* `ctx.mine()` like every other read here, so the numbers can only everdiff --git a/packages/database/src/models/topic/types.ts b/packages/database/src/models/topic/types.tsindex cd56e0ce4e8..aa2cf491688 100644--- a/packages/database/src/models/topic/types.ts+++ b/packages/database/src/models/topic/types.ts@@ -99,7 +99,7 @@ export interface CreateTopicParams {* attribution) plus the visitor's id here, so creator-facing listings* exclude them (`notShareVisitorTopic`, applied by `query`, `count`,* `queryTopics`, `queryRecent` and `rank`) while the share surface scopes- * reads per visitor (`queryBySender` / `countBySender`).+ * reads per visitor (`queryBySender` / `countMessagesBySender`).** A future opt-in surface (`allowCreatorViewSessions`) may let a creator* explicitly browse visitor sessions; that is not wired up yet — everydiff --git a/packages/database/src/repositories/channel/README.md b/packages/database/src/repositories/channel/README.mdindex 16d830992a1..48bebd2c769 100644--- a/packages/database/src/repositories/channel/README.md+++ b/packages/database/src/repositories/channel/README.md@@ -93,7 +93,7 @@ never take one. The claim freezes `executionConfig.share` (owner, share and the`readMessage`, and `ChannelHistoryRepository` authorizes those reads against the frozen share(owner operation, the person's Channel) while every other use of the run (`currentRun`, so`listChannels` / `sendMessage`) is refused: they would act in the owner's Channels.-- A topic ends at the share's `maxTurnsPerTopic`; the next request starts a new one.+- Each requester can send at most the share's `maxMessagesPerVisitor` messages in total, counted across all their topics with this Agent; sending refuses the next one. Topics still roll over only after the staleness window.## Conversations between contactsdiff --git a/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts b/packages/database/src/repositories/channel/__tests__/sharedAgent.test.tsindex 70912f3008e..143528a0212 100644--- a/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts+++ b/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { SHARE_VISITOR_PROMPT_MAX_LENGTH } from '@lobechat/const';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';@@ -10,6 +11,7 @@ import {channelJobs,files,messages,+ topics,userContacts,userSettings,} from '../../../schemas';@@ -42,7 +44,7 @@ beforeEach(async () => {.insert(agentShares).values({agentId,- shareConfig: { maxTurnsPerTopic: 2, monthlySpendLimit: 1, slug: 'shared-helper' },+ shareConfig: { monthlySpendLimit: 1, slug: 'shared-helper' },visibility: 'link',}).returning();@@ -84,12 +86,14 @@ describe('a contact’s shared Agent in a direct conversation', () => {sharedAgentHandle: 'shared-helper',});expect(listed.memberAvatars).toMatchObject([{ actorType: 'agent', id: agentId }]);+ // The conversation view marks it too: its composer reads `detail`, not the list.+ expect((await visitor.detail(channel.id)).channel).toMatchObject({ sharedAgent: true });});it('lists the share id as its handle when the owner set no custom slug', async () => {await db.update(agentShares)- .set({ shareConfig: { maxTurnsPerTopic: 2, monthlySpendLimit: 1 } })+ .set({ shareConfig: { monthlySpendLimit: 1 } }).where(eq(agentShares.id, shareId));const { channel } = await visitor.create({agentId,@@ -134,6 +138,47 @@ describe('a contact’s shared Agent in a direct conversation', () => {});});+ // The runtimes its share page runs. Whether the share grants the owner's device is the run's+ // share gate's call, so the claim leaves the device unset either way.+ it('runs a Claude Code or Codex Agent, as its share page does', async () => {+ const { channel } = await visitor.create({+ agentId,+ sharedAgent: true,+ title: 'Shared Helper',+ });+ for (const type of ['claude-code', 'codex'] as const) {+ await db+ .update(agents)+ .set({ agencyConfig: { heterogeneousProvider: { command: type, type } } })+ .where(eq(agents.id, agentId));+ const job = await send(channel.id, type);+ const claim = (await execution.claim(channel.id, job.id, lease))!;+ expect(claim.job.executionConfig).toMatchObject({+ runtime: type,+ share: { ownerId, shareId, workspaceId: null },+ });+ expect(claim.job.executionConfig?.deviceId).toBeUndefined();+ await execution.retireReservation(channel.id, job.id);+ }+ });++ it('is blocked for a runtime its share page cannot run', async () => {+ await db+ .update(agents)+ .set({ agencyConfig: { heterogeneousProvider: { command: 'kimi', type: 'kimi-code' } } })+ .where(eq(agents.id, agentId));+ const { channel } = await visitor.create({+ agentId,+ sharedAgent: true,+ title: 'Shared Helper',+ });+ const job = await send(channel.id, 'kimi');++ expect(await execution.claim(channel.id, job.id, lease)).toBeNull();+ const [blocked] = await db.select().from(channelJobs).where(eq(channelJobs.id, job.id));+ expect(blocked.blockedCode).toBe('unavailable');+ });+it('is blocked once the owner pauses the share', async () => {const { channel } = await visitor.create({agentId,@@ -174,7 +219,7 @@ describe('a contact’s shared Agent in a direct conversation', () => {).rejects.toThrow('Attachments cannot be sent to a shared Agent');});- it('continues its topic until the share’s per-topic turn limit', async () => {+ it('keeps continuing its topic however many messages it holds', async () => {const { channel } = await visitor.create({agentId,sharedAgent: true,@@ -194,9 +239,9 @@ describe('a contact’s shared Agent in a direct conversation', () => {const second = await claim('b');expect(second.topic.id).toBe(first.topic.id);- // Two visitor turns reach `maxTurnsPerTopic: 2`.+ // Message count never rolls the topic over; only the staleness window does.await db.insert(messages).values(- ['one', 'two'].map((content) => ({+ ['one', 'two', 'three', 'four', 'five'].map((content) => ({content,role: 'user' as const,topicId: first.topic.id,@@ -205,10 +250,136 @@ describe('a contact’s shared Agent in a direct conversation', () => {);await finish(second.job.id);const third = await claim('c');- expect(third.topic.id).not.toBe(first.topic.id);+ expect(third.topic.id).toBe(first.topic.id);expect(third.topic).toMatchObject({ senderId: visitorId, userId: ownerId });});+ describe('errors a visitor sees', () => {+ const failedView = async (channelId: string, viewer: ChannelRepository) => {+ const claim = (await execution.claim(channelId, (await send(channelId, 'boom')).id, lease))!;+ await execution.fail(channelId, claim.job.id, {+ message: 'Upstream provider key sk-owner-secret rejected',+ });+ const view = await viewer.detail(channelId);+ return view!.jobs.find((job) => job.id === claim.job.id)!;+ };++ it('redacts the failure text of a shared Agent’s run, as the share page does', async () => {+ const { channel } = await visitor.create({+ agentId,+ sharedAgent: true,+ title: 'Shared Helper',+ });+ const job = await failedView(channel.id, visitor);++ expect(job.status).toBe('failed');+ expect(job.errorMessage).toBeNull();+ expect(job.errorType).toBe('AgentRuntimeError');+ });++ it('shows the raw failure when the owner’s share opts into error details', async () => {+ await db+ .update(agentShares)+ .set({ shareConfig: { showErrorDetails: true } })+ .where(eq(agentShares.id, shareId));+ const { channel } = await visitor.create({+ agentId,+ sharedAgent: true,+ title: 'Shared Helper',+ });+ const job = await failedView(channel.id, visitor);++ expect(job.errorMessage).toBe('Upstream provider key sk-owner-secret rejected');+ });++ // The visitor saw "no reason recorded" when the owner's monthly cap refused the reply.+ it('keeps a spend-limit refusal readable for the visitor', async () => {+ const { channel } = await visitor.create({+ agentId,+ sharedAgent: true,+ title: 'Shared Helper',+ });+ const claim = (await execution.claim(channel.id, (await send(channel.id, 'hi')).id, lease))!;+ expect(+ await execution.retireReservation(channel.id, claim.job.id, {+ message: 'This shared Agent reached its monthly usage limit',+ type: 'ShareSpendLimitExceeded',+ }),+ ).toBe(true);+ const job = (await visitor.detail(channel.id))!.jobs.find(+ (item) => item.id === claim.job.id,+ )!;++ expect(job).toMatchObject({+ errorMessage: 'This shared Agent reached its monthly usage limit',+ errorType: 'ShareSpendLimitExceeded',+ status: 'failed',+ });+ });++ it('leaves an ordinary Agent’s failure text as it was', async () => {+ const ownAgentId = 'agt_channel_shared_own';+ await db.insert(agents).values({ id: ownAgentId, title: 'Mine', userId: visitorId });+ const { channel } = await visitor.create({ agentId: ownAgentId, title: 'Mine' });+ const job = await failedView(channel.id, visitor);++ expect(job.errorMessage).toBe('Upstream provider key sk-owner-secret rejected');+ });+ });++ describe('visitor limits', () => {+ const open = async () =>+ (await visitor.create({ agentId, sharedAgent: true, title: 'Shared Helper' })).channel;+ const sendText = (channelId: string, content: string, requestKey: string) =>+ visitor.send(channelId, { content, requestKey, routing: 'fallback' });++ it('refuses a prompt beyond the share’s length cap', async () => {+ const channel = await open();+ await expect(+ sendText(channel.id, 'x'.repeat(SHARE_VISITOR_PROMPT_MAX_LENGTH + 1), 'long'),+ ).rejects.toThrow(`limited to ${SHARE_VISITOR_PROMPT_MAX_LENGTH} characters`);+ await expect(sendText(channel.id, 'ok', 'short')).resolves.toBeDefined();+ });++ it('refuses a message once the visitor sent maxMessagesPerVisitor, not counting replies', async () => {+ await db+ .update(agentShares)+ .set({ shareConfig: { maxMessagesPerVisitor: 2 } })+ .where(eq(agentShares.id, shareId));+ const channel = await open();+ const first = (await execution.claim(channel.id, (await send(channel.id, 'a')).id, lease))!;+ await execution.accepted(channel.id, first.job.id);+ await execution.saveDraft(channel.id, first.job.id, 'Answer');+ await execution.publish(channel.id, first.job.id);+ await execution.releaseWriter(channel.id, first.job.id);++ // One message and several Agent replies: the replies leave room for another message.+ await db.insert(messages).values([+ { content: 'one', role: 'user', topicId: first.topic.id, userId: ownerId },+ ...['r1', 'r2', 'r3'].map((content) => ({+ content,+ role: 'assistant' as const,+ topicId: first.topic.id,+ userId: ownerId,+ })),+ ]);+ await expect(sendText(channel.id, 'b', 'b')).resolves.toBeDefined();++ // A second message, in another topic of the same visitor, reaches the cap.+ const [otherTopic] = await db+ .insert(topics)+ .values({ agentId, senderId: visitorId, userId: ownerId })+ .returning();+ await db+ .insert(messages)+ .values({ content: 'two', role: 'user', topicId: otherTopic.id, userId: ownerId });+ await expect(sendText(channel.id, 'c', 'c')).rejects.toMatchObject({+ code: 'TOO_MANY_REQUESTS',+ message: 'ShareMessageLimitExceeded',+ });+ });+ });+describe('reading its conversation history', () => {const start = async () => {const { channel } = await visitor.create({@@ -319,6 +490,29 @@ describe('a shared Agent in the visitor’s workspace', () => {).rejects.toThrow('Channel operation not found');});+ it('refuses attachments, like a personal conversation', async () => {+ const channel = await open();+ const [file] = await db+ .insert(files)+ .values({+ fileType: 'text/plain',+ name: 'note.txt',+ size: 1,+ url: 'files/ws-note.txt',+ userId: visitorId,+ workspaceId: fixture.workspaceId,+ })+ .returning();+ await expect(+ inWorkspace.send(channel.id, {+ content: 'See file',+ fileIds: [file.id],+ requestKey: 'ws-file',+ routing: 'fallback',+ }),+ ).rejects.toThrow('Attachments cannot be sent to a shared Agent');+ });+it('still cannot join a workspace group', async () => {const { channel } = await inWorkspace.create({ title: 'Group' });await expect(inWorkspace.addAgent(channel.id, { agentId })).rejects.toThrow('Agent not found');@@ -337,5 +531,6 @@ describe('a shared Agent in the visitor’s workspace', () => {const [listed] = await inWorkspace.list();expect(listed).toMatchObject({ id: channel.id, sharedAgent: false, sharedAgentHandle: null });+ expect((await inWorkspace.detail(channel.id)).channel).toMatchObject({ sharedAgent: false });});});diff --git a/packages/database/src/repositories/channel/agent.ts b/packages/database/src/repositories/channel/agent.tsindex 27a2b21587f..db1b9915bc9 100644--- a/packages/database/src/repositories/channel/agent.ts+++ b/packages/database/src/repositories/channel/agent.ts@@ -1,5 +1,5 @@import { DEFAULT_PROVIDER } from '@lobechat/business-const';-import { isHeterogeneousAgentModelId } from '@lobechat/const';+import { isAgentShareVisitorHeteroType, isHeterogeneousAgentModelId } from '@lobechat/const';import type {ChannelExecutionConfig,ChannelMemberConfig,@@ -41,6 +41,29 @@ export const isSharedAgentChannel = (agent.agentVisibility !== 'private');+/**+ * The owner of the Agent a direct conversation is with, when it is another person's shared Agent+ * (`isSharedAgentChannel`); `null` otherwise.+ */+export const sharedAgentOwner = async (+ tx: Transaction,+ channel: Pick<ChannelItem, 'agentId' | 'workspaceId'>,+ viewerId: string,+): Promise<string | null> => {+ if (!channel.agentId) return null;+ const [agent] = await tx+ .select({+ agentOwnerId: agents.userId,+ agentVisibility: agents.visibility,+ agentWorkspaceId: agents.workspaceId,+ })+ .from(agents)+ .where(eq(agents.id, channel.agentId));+ return agent?.agentOwnerId && isSharedAgentChannel(channel, agent, viewerId)+ ? agent.agentOwnerId+ : null;+};+/** Explicitly select environment fields so legacy or untyped copies cannot override an Agent. */export const memberEnvironment = (config?: ChannelMemberConfig | null): ChannelMemberConfig =>cleanObject({@@ -267,11 +290,18 @@ export const resolveExecutionConfig = async (.for('share');if (!owned) return null;const config = await mergeDefaults(tx, owned, share.ownerId, share.workspaceId, serverDefault);- if (agentRuntime(config) !== 'native') return null;+ // The runtimes its share page runs: Native, or Claude Code / Codex. The visitor picks no device;+ // the run's share gate decides whether the share grants the owner's device and routes there.+ const runtime = agentRuntime(config);+ if (+ !isChannelRuntime(runtime) ||+ (runtime !== 'native' && !isAgentShareVisitorHeteroType(runtime))+ )+ return null;return {...config,provider: config.provider || DEFAULT_PROVIDER,- runtime: 'native',+ runtime,share: { ownerId: share.ownerId, shareId: share.shareId, workspaceId: share.workspaceId },};};diff --git a/packages/database/src/repositories/channel/error.ts b/packages/database/src/repositories/channel/error.tsindex 9e3011b6be1..b7cd6f80f5f 100644--- a/packages/database/src/repositories/channel/error.ts+++ b/packages/database/src/repositories/channel/error.ts@@ -1,4 +1,5 @@-export type ChannelErrorCode = 'BAD_REQUEST' | 'CONFLICT' | 'FORBIDDEN' | 'NOT_FOUND';+export type ChannelErrorCode =+ 'BAD_REQUEST' | 'CONFLICT' | 'FORBIDDEN' | 'NOT_FOUND' | 'TOO_MANY_REQUESTS';export class ChannelError extends Error {constructor(diff --git a/packages/database/src/repositories/channel/execution.ts b/packages/database/src/repositories/channel/execution.tsindex 7e5fd262039..9852d5b78fe 100644--- a/packages/database/src/repositories/channel/execution.ts+++ b/packages/database/src/repositories/channel/execution.ts@@ -156,15 +156,22 @@ export class ChannelExecutionRepository {return 'revoked';});- /** Retire only an untouched reservation, racing recordStart on the operation row itself. */- retireReservation = async (channelId: string, jobId: string) =>+ /**+ * Retire only an untouched reservation, racing recordStart on the operation row itself.+ * `failure` records why dispatch refused it, for a reason the requester can act on.+ */+ retireReservation = async (+ channelId: string,+ jobId: string,+ failure?: { message: string; type?: string },+ ) =>withChannelLock(this.db, channelId, async (tx) => {const job = await claimed(tx, channelId, jobId, true);if (!job.operationId || !job.writerHeld) return false;const status = job.publicationRevoked ? 'interrupted' : 'error';const [retired] = await tx.update(agentOperations)- .set({ status, completedAt: new Date() })+ .set({ status, completedAt: new Date(), ...(failure && { error: failure }) }).where(and(eq(agentOperations.id, job.operationId), eq(agentOperations.status, 'idle'))).returning({ id: agentOperations.id });if (!retired) return false;@@ -720,7 +727,7 @@ export class ChannelExecutionRepository {* stopped. The writer stays held until termination is confirmed. A late failure after the* reply was published or the release settled the job changes nothing.*/- fail = async (channelId: string, jobId: string, failure: { message: string }) =>+ fail = async (channelId: string, jobId: string, failure: { message: string; type?: string }) =>withChannelLock(this.db, channelId, async (tx) => {const job = await claimed(tx, channelId, jobId, true);if (job.publishedMessageId || (!job.writerHeld && job.status !== 'running')) return;@@ -738,7 +745,7 @@ export class ChannelExecutionRepository {tx,job,stopping ? 'interrupted' : 'error',- stopping ? undefined : failure.message,+ stopping ? undefined : failure,);await audit(tx, channelId, 'execution_failed', job.id, {message: failure.message,diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 7aac7d87f45..283e2431694 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -32,6 +32,7 @@ import {memberEnvironment,requireAgentMember,requireChannelAgent,+ sharedAgentOwner,} from './agent';import { openAgentPair } from './agentPair';import { channelAvatarMembers } from './avatars';@@ -64,7 +65,7 @@ import { stopScope } from './stop';import { channelThreadMentions } from './threadMentions';import { audit, lockChannel } from './transaction';import type { ChannelAccess, ChannelAgentPairAccess, ChannelWriteOptions } from './types';-import { createChannelThread, readChannelView } from './view';+import { createChannelThread, readChannelView, viewerJobs } from './view';import {readWakeConfig,replaceChannelWake,@@ -454,18 +455,14 @@ export class ChannelRepository {if (access.channel.isDeleted) throw new ChannelError('NOT_FOUND', 'Channel not found');const admin = hasRole(access.member.role, 'admin');const view = await readChannelView(tx, channelId, options, this.userId);+ // Same test as `list`; the composer reads it from here to hide upload.+ const sharedAgent = !!(await sharedAgentOwner(tx, access.channel, this.userId));return {- channel: { ...access.channel, canDelete: admin },+ channel: { ...access.channel, canDelete: admin, sharedAgent },joined: true,...view,- jobs: view.jobs.map(({ requesterMemberId, topicId, topicOwnerId, ...job }) => ({- ...job,- // Mirrors `stop`: the requester or an admin.- canStop: admin || requesterMemberId === access.member.id,- // Only the viewer who runs the reply can follow it into its topic; for anyone else- // the job carries no topic at all.- ...(topicId && topicOwnerId === this.userId ? { topicId } : {}),- })),+ // Mirrors `stop`: the requester or an admin.+ jobs: viewerJobs(view.jobs, this.userId, (id) => admin || id === access.member.id),};},{ allowArchived: true, allowTrashed: true },diff --git a/packages/database/src/repositories/channel/projectAccess.ts b/packages/database/src/repositories/channel/projectAccess.tsindex ffb60660800..57bf159dfb6 100644--- a/packages/database/src/repositories/channel/projectAccess.ts+++ b/packages/database/src/repositories/channel/projectAccess.ts@@ -9,7 +9,7 @@ import { ChannelError } from './error';import { memberInviterMetadata, requireWorkspaceMember } from './people';import { audit } from './transaction';import type { ChannelAccess } from './types';-import { readChannelView } from './view';+import { readChannelView, viewerJobs } from './view';/*** A workspace project's group Channels are open to everyone who can read the project: they find@@ -153,11 +153,7 @@ export const readOpenChannel = async (channel: { ...channel, canDelete: false },joined: false,...view,- jobs: view.jobs.map(({ requesterMemberId: _, topicId, topicOwnerId, ...job }) => ({- ...job,- canStop: false,- ...(topicId && topicOwnerId === userId ? { topicId } : {}),- })),+ jobs: viewerJobs(view.jobs, userId, () => false),};});diff --git a/packages/database/src/repositories/channel/send.ts b/packages/database/src/repositories/channel/send.tsindex fe7adf01f15..cd7a10291f8 100644--- a/packages/database/src/repositories/channel/send.ts+++ b/packages/database/src/repositories/channel/send.ts@@ -3,10 +3,11 @@ import { CHANNEL_LIMITS } from '@lobechat/types';import { and, asc, eq, inArray, sql } from 'drizzle-orm';import type { ChannelMessageItem } from '../../schemas';-import { agents, channelMembers, channelMessages, channelThreads, files } from '../../schemas';+import { channelMembers, channelMessages, channelThreads, files } from '../../schemas';import type { Transaction } from '../../type';import { isUuid } from '../../utils/uuid';import { buildWorkspaceWhere } from '../../utils/workspace';+import { sharedAgentOwner } from './agent';import { attachFiles, fileIdsByMessage } from './attachments';import {activeMembers,@@ -19,6 +20,7 @@ import {} from './delivery';import { ChannelError } from './error';import { isWorkspaceMember, peerOf, requirePeerRelation } from './peer';+import { assertSharedAgentAdmission } from './shareLimits';import { audit } from './transaction';import type { ChannelAccess } from './types';import { createChannelThread } from './view';@@ -172,14 +174,22 @@ export const sendMessage = async (peerOf(channel, member.userId)!,);- if (fileIds.length && channel.agentId) {- // Another person's shared Agent runs as its owner, who cannot read the sender's files.- const [bound] = await tx- .select({ ownerId: agents.userId })- .from(agents)- .where(eq(agents.id, channel.agentId));- if (bound?.ownerId !== member.userId && !channel.workspaceId)- throw new ChannelError('BAD_REQUEST', 'Attachments cannot be sent to a shared Agent');+ if (channel.agentId) {+ // The same test the Channel list uses, so a workspace conversation with a shared Agent is+ // treated like a personal one, while a colleague's public workspace Agent (the workspace's+ // own) is not.+ const agentOwnerId = await sharedAgentOwner(tx, channel, member.userId!);+ if (agentOwnerId) {+ // Another person's shared Agent runs as its owner, who cannot read the sender's files.+ if (fileIds.length)+ throw new ChannelError('BAD_REQUEST', 'Attachments cannot be sent to a shared Agent');+ await assertSharedAgentAdmission(tx, {+ agentId: channel.agentId,+ content: input.content,+ ownerId: agentOwnerId,+ visitorId: member.userId!,+ });+ }}if (fileIds.length) {diff --git a/packages/database/src/repositories/channel/shareLimits.ts b/packages/database/src/repositories/channel/shareLimits.tsnew file mode 100644index 00000000000..f9971048b3b--- /dev/null+++ b/packages/database/src/repositories/channel/shareLimits.ts@@ -0,0 +1,55 @@+import {+ AGENT_SHARE_DEFAULT_MAX_MESSAGES_PER_VISITOR,+ SHARE_VISITOR_PROMPT_MAX_LENGTH,+} from '@lobechat/const';+import { ChatErrorType } from '@lobechat/types';+import { eq } from 'drizzle-orm';++import { TopicModel } from '../../models/topic';+import { agents, agentShares } from '../../schemas';+import type { LobeChatDatabase, Transaction } from '../../type';+import { ChannelError } from './error';++/**+ * Admission for a message sent to another person's shared Agent, with the limits its share page+ * applies to a visitor, so the composer is told at send time instead of the reply failing later.+ *+ * - The prompt length cap (`SHARE_VISITOR_PROMPT_MAX_LENGTH`).+ * - `maxMessagesPerVisitor`: the messages this visitor has sent to the Agent in total, across+ * every conversation, the same count the run's own atomic guard (`reserveShareVisitorTurn`)+ * applies when it writes the visitor's message.+ *+ * Like the spend limit, a send-time guardrail rather than an atomic reservation: concurrent sends+ * can each pass here, and the run's guard refuses the one beyond the cap.+ */+export const assertSharedAgentAdmission = async (+ tx: Transaction,+ params: { agentId: string; content: string; ownerId: string; visitorId: string },+) => {+ const { agentId, content, ownerId, visitorId } = params;+ if (content.length > SHARE_VISITOR_PROMPT_MAX_LENGTH)+ throw new ChannelError(+ 'BAD_REQUEST',+ `Messages to a shared Agent are limited to ${SHARE_VISITOR_PROMPT_MAX_LENGTH} characters`,+ );++ const [share] = await tx+ .select({ config: agentShares.shareConfig, workspaceId: agents.workspaceId })+ .from(agentShares)+ .innerJoin(agents, eq(agents.id, agentShares.agentId))+ .where(eq(agentShares.agentId, agentId))+ .limit(1);+ const limit =+ share?.config?.maxMessagesPerVisitor ?? AGENT_SHARE_DEFAULT_MAX_MESSAGES_PER_VISITOR;+ const sent = await new TopicModel(+ tx as unknown as LobeChatDatabase,+ ownerId,+ share?.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ ).countMessagesBySender({ agentId, senderId: visitorId });+ if (sent < limit) return;+ // The message is the error type, as the share page's refusal is: the composer reads it to+ // explain the refusal in the visitor's language.+ throw new ChannelError('TOO_MANY_REQUESTS', ChatErrorType.ShareMessageLimitExceeded);+};diff --git a/packages/database/src/repositories/channel/topic.ts b/packages/database/src/repositories/channel/topic.tsindex c637eaa1b6d..d33b0bb5e80 100644--- a/packages/database/src/repositories/channel/topic.ts+++ b/packages/database/src/repositories/channel/topic.ts@@ -1,15 +1,14 @@-import { AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC } from '@lobechat/const';import type { ChannelExecutionConfig } from '@lobechat/types';-import { and, count, desc, eq, isNotNull, isNull, ne } from 'drizzle-orm';+import { and, desc, eq, isNotNull, isNull, ne } from 'drizzle-orm';import isEqual from 'fast-deep-equal';import type { ChannelItem, ChannelJobItem, ChannelMemberItem } from '../../schemas';-import { agentOperations, agentShares, channelJobs, messages, topics } from '../../schemas';+import { agentOperations, channelJobs, topics } from '../../schemas';import type { Transaction } from '../../type';import { CHANNEL_TOPIC_TRIGGER } from '../../utils/topicVisibility';// Matches Bot AgentBridgeService: check on the next request, never expire guild Threads.-const TOPIC_STALE_THRESHOLD = 4 * 60 * 60 * 1000;+export const TOPIC_STALE_THRESHOLD = 4 * 60 * 60 * 1000;/*** Resolve continuation from the source-side job history, without Channel fields on topics.@@ -22,8 +21,7 @@ const TOPIC_STALE_THRESHOLD = 4 * 60 * 60 * 1000;** Another person's shared Agent runs as its owner, so the topic belongs to the owner and its* scope, with the requester as `senderId` — the same row a visit to the share page would write,- * hidden from the owner's own lists. Such a topic also ends at the share's per-topic turn limit,- * where the share page would ask for a new conversation.+ * hidden from the owner's own lists.*/export interface ChannelTopicScope {/** The requester when the run executes as a shared Agent's owner. */@@ -83,7 +81,6 @@ export const continuationTopic = async ((topic.senderId ?? undefined) === scope.senderId &&!topic.isDeleted &&(job.threadId || Date.now() - topic.updatedAt.getTime() <= TOPIC_STALE_THRESHOLD) &&- !(executionConfig.share && (await reachedShareTurnLimit(tx, member.agentId!, topic.id))) &&// A topic another branch is still writing into stays that run's own. Gathering a running// peer into a Thread changes only its branch, so its topic would otherwise look settled// here: the main timeline would start on it while the gathered run still holds it, and the@@ -154,17 +151,3 @@ export const resolveTopic = async (.returning();return created;};--const reachedShareTurnLimit = async (tx: Transaction, agentId: string, topicId: string) => {- const [share] = await tx- .select({ config: agentShares.shareConfig })- .from(agentShares)- .where(eq(agentShares.agentId, agentId))- .limit(1);- const limit = share?.config?.maxTurnsPerTopic ?? AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC;- const [turns] = await tx- .select({ value: count() })- .from(messages)- .where(and(eq(messages.topicId, topicId), eq(messages.role, 'user')));- return (turns?.value ?? 0) >= limit;-};diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.tsindex 6ad820e69d6..b1ad2c689ea 100644--- a/packages/database/src/repositories/channel/view.ts+++ b/packages/database/src/repositories/channel/view.ts@@ -4,6 +4,7 @@ import {channelMessageEditedAt,channelMessageReceipt,channelMessageVia,+ type ChatMessageError,defaultChannelAgentDirectory,type LobeAgentAgencyConfig,resolveAgentAgencyConfig,@@ -25,9 +26,11 @@ import {sql,} from 'drizzle-orm';+import { sanitizeVisitorError } from '../../models/message/visitor';import {agentOperations,agents,+ agentShares,channelJobs,channelMembers,channelMessages,@@ -281,20 +284,55 @@ const publicJobColumns = {operationStatus: agentOperations.status,createdAt: channelJobs.createdAt,publicationRevoked: channelJobs.publicationRevoked,+ // Read only to redact the error of a shared Agent's run, then dropped by `readJobs`.+ sharedRun: sql<boolean>`COALESCE(jsonb_exists(${channelJobs.executionConfig}, 'share'), false)`,+ shareShowsErrorDetails: sql<boolean>`COALESCE(${agentShares.shareConfig}->>'showErrorDetails' = 'true', false)`,};/** At most this many of a main view's threads' jobs still at work ride along with its own. */const THREAD_ACTIVE_JOB_LIMIT = 50;-const readJobs = (tx: Transaction, where: SQL | undefined, limit: number) =>- tx+/**+ * A shared Agent runs under its owner's credentials, so its failure text can carry the owner's+ * provider or infrastructure diagnostics. The viewer of such a run is the visitor, who gets the+ * share page's projection (`sanitizeVisitorError`): a classified type, and the message only for+ * the few visitor-safe codes, unless the owner's share opts into `showErrorDetails`.+ */+const redactSharedRunError = <+ Job extends {+ errorMessage: string | null;+ errorType: string | null;+ sharedRun: boolean;+ shareShowsErrorDetails: boolean;+ },+>({+ sharedRun,+ shareShowsErrorDetails,+ ...job+}: Job) => {+ if (!sharedRun || job.errorMessage === null) return job;+ const safe = sanitizeVisitorError(+ { message: job.errorMessage, type: job.errorType ?? undefined } as ChatMessageError,+ { showErrorDetails: shareShowsErrorDetails },+ );+ return { ...job, errorMessage: safe?.message ?? null, errorType: safe?.type?.toString() ?? null };+};++const readJobs = async (tx: Transaction, where: SQL | undefined, limit: number) => {+ const rows = await tx.select(publicJobColumns).from(channelJobs).leftJoin(agentOperations, eq(agentOperations.id, channelJobs.operationId)).leftJoin(topics, eq(topics.id, channelJobs.topicId))+ .leftJoin(+ agentShares,+ sql`${agentShares.id}::text = ${channelJobs.executionConfig}->'share'->>'shareId'`,+ ).where(where).orderBy(desc(channelJobs.createdAt)).limit(limit);+ return rows.map(redactSharedRunError);+};interface MemberDevice {agentId: string | null;@@ -454,6 +492,21 @@ const environmentViewer = async (};};+/**+ * A view's jobs as one viewer sees them: who may stop each, and the run's topic only for the+ * viewer who runs the reply; for anyone else the job carries no topic at all.+ */+export const viewerJobs = (+ jobs: Awaited<ReturnType<typeof readChannelView>>['jobs'],+ viewerUserId: string,+ canStop: (requesterMemberId: string | null) => boolean,+) =>+ jobs.map(({ requesterMemberId, topicId, topicOwnerId, ...job }) => ({+ ...job,+ canStop: canStop(requesterMemberId),+ ...(topicId && topicOwnerId === viewerUserId ? { topicId } : {}),+ }));+export const readChannelView = async (tx: Transaction,channelId: string,diff --git a/packages/database/src/repositories/channel/writer.ts b/packages/database/src/repositories/channel/writer.tsindex 6b3a5a9aeba..f1a22ad7dbe 100644--- a/packages/database/src/repositories/channel/writer.ts+++ b/packages/database/src/repositories/channel/writer.ts@@ -20,7 +20,8 @@ export const advanceOperation = async (tx: Transaction,job: ChannelJobItem,status: AgentOperationStatus,- error?: string,+ /** A bare message, or one with the category a client explains in the viewer's language. */+ error?: string | { message: string; type?: string },) => {if (!job.operationId) return;@@ -29,7 +30,7 @@ export const advanceOperation = async (.set({status,...(status === 'running' ? { startedAt: new Date() } : { completedAt: new Date() }),- ...(error && { error: { message: error } }),+ ...(error && { error: typeof error === 'string' ? { message: error } : error }),}).where(and(diff --git a/packages/database/src/schemas/agentShare.ts b/packages/database/src/schemas/agentShare.tsindex a420637db27..2771f3f5eff 100644--- a/packages/database/src/schemas/agentShare.ts+++ b/packages/database/src/schemas/agentShare.ts@@ -54,10 +54,11 @@ export interface AgentShareConfig {* visitor attachments off entirely. Enforced by `shareChat.createUploadUrl`.*/maxFileStorage?: number;- /** Maximum number of topics each signed-in visitor can create for this share. */- maxTopicsPerVisitor?: number;- /** Maximum number of message turns allowed in each shared topic. */- maxTurnsPerTopic?: number;+ /**+ * Messages each signed-in visitor may send to this share in total, across every conversation.+ * Only the visitor's own messages count; the Agent's replies do not.+ */+ maxMessagesPerVisitor?: number;/*** Per-Agent monthly spend cap for this share, in USD credits.*@@ -76,11 +77,6 @@ export interface AgentShareConfig {* a generic failure notice. Defaults to `false`.*/showErrorDetails?: boolean;- /**- * Whether visitors may see which model/provider is powering the agent.- * Defaults to `false` — the creator's model choice is hidden by default.- */- showModelInfo?: boolean;/*** Skills visitors may load, by skill identifier. Deliberately separate from* {@link toolGrants}: a skill grant governs BOTH the tool path@@ -113,12 +109,13 @@ export interface AgentShareConfig {}/**- * `AgentShareConfig` as returned by `normalizeAgentShareConfig`: the spend cap- * is guaranteed present, so enforcement paths never have to re-derive a+ * `AgentShareConfig` as returned by `normalizeAgentShareConfig`: the caps are+ * guaranteed present, so enforcement paths never have to re-derive a* default (and can never mistake a missing cap for "unlimited").*/export type NormalizedAgentShareConfig = AgentShareConfig & {maxFileStorage: number;+ maxMessagesPerVisitor: number;monthlySpendLimit: number;};diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex 1ffa0bd6e4a..90508660936 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -889,6 +889,10 @@ export default {'channel.statusStarting': 'Starting','share.entry': 'Share this Agent',+ 'share.settings.device.desc':+ 'Choose who may run this Agent on your execution environment, for example to read files or run commands. Claude Code and Codex Agents run only there, so other visitors can’t use them. Chatting with the Agent doesn’t include device access.',+ 'share.settings.device.title': 'Device access',+ 'share.settings.device.who': 'Who can use your device','share.settings.limits.desc':'Every visitor run is billed to your account, so these caps are what keep a shared link from running up your bill. They always apply — you can change the numbers, but not turn them off.','share.settings.limits.maxFileStorageHint':@@ -898,14 +902,10 @@ export default {'share.settings.limits.maxFileStorageLabel': 'File storage limit','share.settings.limits.maxFileStorageWorkspaceHint':'Files visitors attach are stored in the Workspace. Uploads stop once they reach this total; set 0 to turn attachments off.',- 'share.settings.limits.maxTopicsPerVisitor': 'Topics per visitor',- 'share.settings.limits.maxTopicsPerVisitorHint':- 'How many separate topics each signed-in visitor can start.',- 'share.settings.limits.maxTopicsPerVisitorUnit': 'topics',- 'share.settings.limits.maxTurnsPerTopic': 'Turns per topic',- 'share.settings.limits.maxTurnsPerTopicHint':- 'How many messages a visitor can send inside one topic.',- 'share.settings.limits.maxTurnsPerTopicUnit': 'turns',+ 'share.settings.limits.maxMessagesPerVisitor': 'Messages per visitor',+ 'share.settings.limits.maxMessagesPerVisitorHint':+ 'How many messages each signed-in visitor can send to this Agent in total. The Agent’s replies don’t count.',+ 'share.settings.limits.maxMessagesPerVisitorUnit': 'messages','share.settings.limits.monthlySpendLimit': 'Monthly spend cap','share.settings.limits.monthlySpendLimitHint':'Visitor runs stop once this month’s spend on this Agent reaches the cap. Resets on the 1st of each month (UTC).',@@ -958,17 +958,14 @@ export default {'share.settings.permissions.allowReadMemory': 'Allow reading my memory','share.settings.permissions.allowReadMemoryHint':'The Agent may draw on your long-term memory while answering a visitor.',- 'share.settings.permissions.deviceAccess': 'Execution environment',- 'share.settings.permissions.deviceAccessHint':- 'Lets the people you pick run this Agent on its execution environment, including Claude Code and Codex. Everyone else can’t run a Claude Code or Codex Agent.',+ 'share.settings.permissions.deviceAccessConfirm.messageLimit':+ 'The monthly spend cap does not limit that usage. Only the message limit per visitor does.','share.settings.permissions.deviceAccessOption.allowlist': 'People from contacts','share.settings.permissions.deviceAccessOption.none': 'No visitors','share.settings.permissions.deviceAccessConfirm.commands':'They can run any command and read or write any file on the machine this Agent runs on, including through Claude Code or Codex.','share.settings.permissions.deviceAccessConfirm.intro':'People you add will run this Agent on your execution environment:',- 'share.settings.permissions.deviceAccessConfirm.limits':- 'The monthly spend cap does not limit that usage. Only the turn limit per topic does.','share.settings.permissions.deviceAccessConfirm.ok': 'Allow listed people','share.settings.permissions.deviceAccessConfirm.subscription':'Claude Code and Codex runs use the model subscription signed in on that machine.',@@ -991,9 +988,6 @@ export default {'share.settings.permissions.showErrorDetails': 'Show error details to visitors','share.settings.permissions.showErrorDetailsHint':'Off by default: visitors see a generic failure notice instead of raw error text.',- '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.tabs.access': 'Access','share.settings.tabs.profile': 'Public profile',@@ -1066,6 +1060,8 @@ export default {'share.visitor.access.signInDesc':'Sign in to start chatting with this shared agent. Your topics stay tied to your account.','share.visitor.access.signInTitle': 'Sign in to continue',+ 'share.visitor.chat.channelsDisabled':+ "Chatting with shared agents isn't available for your account yet.",'share.visitor.errors.fileUnavailable':'One of the attachments is no longer available. Remove it and try again.','share.visitor.errors.generic': 'Failed to send the message. Please try again.',@@ -1084,9 +1080,6 @@ export default {'share.visitor.errors.spendLimit':'This shared agent has reached its monthly usage limit set by its creator. It will be available again next month.','share.visitor.errors.stopFailed': "Couldn't stop the run. Please try again.",- 'share.visitor.errors.topicLimit': 'You have reached the topic limit on this shared agent.',- 'share.visitor.errors.turnLimit':- 'This topic has reached its turn limit. Start a new topic to continue.','share.visitor.errors.unavailable':'This topic is no longer available. Try switching to another topic or starting a new one.','share.visitor.input.placeholder': 'Message this shared agent…',@@ -1115,8 +1108,6 @@ export default {'share.visitor.profile.metrics.conversationsCaption': 'started so far','share.visitor.profile.metrics.tools': 'Open tools','share.visitor.profile.metrics.toolsCaption': 'available to you',- 'share.visitor.profile.metrics.turns': 'Each topic',- 'share.visitor.profile.metrics.turnsCaption': 'turns at most','share.visitor.profile.metrics.views': 'Views','share.visitor.profile.metrics.viewsCaption': 'on this page','share.visitor.profile.metrics.visitors': 'People who used it',@@ -1129,11 +1120,11 @@ export default {'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.',+ 'share.visitor.profile.terms.messages_one': 'You can send up to {{count}} message.',+ 'share.visitor.profile.terms.messages_other': 'You can send up to {{count}} messages.','share.visitor.profile.terms.title': 'Before you start','share.visitor.profile.terms.tools_one': '{{count}} tool is open to visitors.','share.visitor.profile.terms.tools_other': '{{count}} tools are open to visitors.',- 'share.visitor.profile.terms.topics': 'You can open up to {{count}} topics.',- 'share.visitor.profile.terms.turns': 'Each topic allows up to {{count}} turns.','share.visitor.profile.terms.uploads':'You can attach files; this Agent has {{size}} of file storage for visitors.','share.visitor.profile.terms.uploadsOff': 'Attachments are turned off.',@@ -1141,10 +1132,6 @@ export default {'The creator has turned on topic access and may read the messages in your topics.','share.visitor.profile.terms.visibilityPrivate': 'Only you can see your topics.','share.visitor.topBar.home': 'Go to my LobeHub',- 'share.visitor.topics.empty': 'No topics yet',- 'share.visitor.topics.new': 'New topic',- 'share.visitor.topics.title': 'Topics',- 'share.visitor.topics.untitled': 'Untitled topic','share.visitor.upload.creatorStorageBlocked':"This Agent's upload space is full. Ask its creator to free up room or raise the cap.",'share.visitor.upload.fileTooLarge': 'Files must be under {{max}}.',diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.tsindex 45356d8091f..65b4b73c417 100644--- a/packages/locales/src/default/channel.ts+++ b/packages/locales/src/default/channel.ts@@ -6,6 +6,13 @@ export default {'people.noOthers': 'No one else is in this workspace yet','people.searchMore': 'Showing the first 50 members. Search to find more.','receipt.errorReason': 'Failure reason',+ 'receipt.errorShareHeteroDevice': "The creator's device is offline. Try again later.",+ 'receipt.errorShareHeteroUnsupported':+ "This Agent can run for you only with its creator's permission. Ask its creator for access.",+ 'receipt.errorShareMessageLimit':+ 'You have sent all the messages its creator allows to this shared Agent.',+ 'receipt.errorShareSpendLimit':+ 'This shared Agent reached the monthly usage limit its creator set. It will be available again next month.','receipt.errorUnavailable':'No detailed reason was recorded. Check the Agent’s model and device settings before sending again.','sort.by': 'Sort by',diff --git a/packages/types/src/agent/share.ts b/packages/types/src/agent/share.tsindex 6a8869b769e..4ad5304f877 100644--- a/packages/types/src/agent/share.ts+++ b/packages/types/src/agent/share.ts@@ -47,10 +47,8 @@ export interface SharedAgentTerms {* this share; `0` means attachments are off and the composer hides them.*/maxFileStorage: number;- /** Maximum conversations this visitor may open against the share. */- maxTopicsPerVisitor: number;- /** Maximum message turns allowed inside one shared conversation. */- maxTurnsPerTopic: number;+ /** Messages this visitor may send to the share in total. */+ maxMessagesPerVisitor: number;}/**@@ -123,9 +121,9 @@ export interface SharedAgentData {toolGrants: string[];/*** Which media the visitor composer may attach, derived server-side from- * the agent's model abilities so the model itself stays hidden (it is- * owner-facing unless `showModelInfo` opts in). Documents are always- * allowed; these only gate direct media input.+ * the agent's model abilities so the model itself, which is+ * owner-facing, stays hidden. Documents are always allowed; these only gate+ * direct media input.*/uploadAbility: SharedAgentUploadAbility;visibility: ShareVisibility;diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.tsindex 997d0e15364..5662d3f3c44 100644--- a/packages/types/src/agentRuntime.ts+++ b/packages/types/src/agentRuntime.ts@@ -104,7 +104,7 @@ export enum RequestTrigger {* Everything one shared-agent visitor run carries: WHO the run belongs to* (`agentId` / `shareId` / `visitorUserId`), WHAT the visitor is allowed to* reach (`allowReadMemory` / `toolGrants` / `knowledgeBaseIds`), and HOW- * much of the run is shown back to them (`showErrorDetails` / `showModelInfo`).+ * much of the run is shown back to them (`showErrorDetails`).** Single source of truth for the runtime-side share marker: it is stamped once* at operation creation onto `state.metadata.agentShareVisitor` and read back@@ -150,8 +150,6 @@ export interface AgentShareVisitorContext {shareId: string;/** `AgentShareConfig.showErrorDetails` — gates visitor-facing error redaction. */showErrorDetails?: boolean;- /** `AgentShareConfig.showModelInfo` — gates visitor-facing model/provider/usage redaction. */- showModelInfo?: boolean;/*** Mirrors `shareConfig.skillGrants` so the skill runtime can enforce the same* per-skill allowlist the operation's skill pool was built from. Absent ordiff --git a/packages/types/src/fetch.ts b/packages/types/src/fetch.tsindex bdd1da18cc2..c3b4abdab6d 100644--- a/packages/types/src/fetch.ts+++ b/packages/types/src/fetch.ts@@ -10,8 +10,7 @@ export const ChatErrorType = {WorkspaceFrozenByAdmin: 'WorkspaceFrozenByAdmin', // Workspace manually frozen by admin (reason is operator-written, safe to surface)WorkspaceFrozenByRiskControl: 'WorkspaceFrozenByRiskControl', // Workspace auto-frozen by risk control (reason is engineer debug text, hide from user)WorkspaceSubscriptionInactive: 'WorkspaceSubscriptionInactive', // Workspace's paid subscription has lapsed — view-only for non-primary members; spend blocked until renewed- ShareTurnLimitExceeded: 'ShareTurnLimitExceeded', // Shared-agent topic hit shareConfig.maxTurnsPerTopic — visitor can start a new topic- ShareTopicLimitExceeded: 'ShareTopicLimitExceeded', // Visitor hit shareConfig.maxTopicsPerVisitor on this shared agent+ ShareMessageLimitExceeded: 'ShareMessageLimitExceeded', // Visitor hit shareConfig.maxMessagesPerVisitor on this shared agentShareSpendLimitExceeded: 'ShareSpendLimitExceeded', // Shared agent reached shareConfig.monthlySpendLimit for the current month — recovers on the next resetShareHeterogeneousAgentUnsupported: 'ShareHeterogeneousAgentUnsupported', // This agent configuration is not supported for shared visitorsShareHeteroDeviceUnavailable: 'ShareHeteroDeviceUnavailable', // The shared Claude Code / Codex agent's device is offline or not set — visitor can retry laterdiff --git a/src/features/Channels/ChannelConversation.tsx b/src/features/Channels/ChannelConversation.tsxindex c01d9373caf..dfce7af3367 100644--- a/src/features/Channels/ChannelConversation.tsx+++ b/src/features/Channels/ChannelConversation.tsx@@ -43,12 +43,15 @@ interface ChannelConversationProps {onOpenThread?: (threadId: string, toggle?: boolean) => void;onOpenTopic?: (topic: ReplyTopic) => void;onStartThread?: (draft: ChannelThreadDraft) => void;+ /** Markdown filling the main composer when nothing is saved for it; never sent by itself. */+ starter?: string;threadId?: string | null;}const Timeline = ({channelId,inert,+ starter,threadId = null,onOpenThread,onOpenTopic,@@ -272,6 +275,7 @@ const Timeline = ({key={channelDraftKey(channelId, threadId)}members={activeMembers}replyTarget={reply.target}+ starter={threadId ? undefined : starter}activity={hasReplyActivity(detail, threadId) ? (<ReplyActivity detail={detail} threadId={threadId} />diff --git a/src/features/Channels/Composer.tsx b/src/features/Channels/Composer.tsxindex 8cf6854ca77..c911df8f67b 100644--- a/src/features/Channels/Composer.tsx+++ b/src/features/Channels/Composer.tsx@@ -94,6 +94,7 @@ export function Composer({onSend,placeholder,replyTarget,+ starter,onCancelReply,}: {/** Who is replying right now; shown on the line above the input. Omit to drop that line. */@@ -105,12 +106,14 @@ export function Composer({members: ChannelPublicMember[];placeholder: string;replyTarget?: ChannelReplyTarget | null;+ /** Markdown filling an empty composer when no draft is saved; see {@link useComposerDraft}. */+ starter?: string;onCancelReply?: () => void;} & ComposerDelivery) {const { t } = useTranslation('channel');const workspaceId = useActiveWorkspaceId();const editor = useEditor();- const draft = useComposerDraft(editor, draftKey);+ const draft = useComposerDraft(editor, draftKey, starter);useEffect(() => {if (replyTarget) editor.focus();}, [editor, replyTarget]);@@ -126,7 +129,9 @@ export function Composer({const requests = useSingleton(createChannelSendRequest);const attachments = useAttachments(draftKey);const { allowed } = usePermission('create_content');- const enableUpload = useServerConfigStore((s) => featureFlagsSelectors(s).enableKnowledgeBase);+ const knowledgeBase = useServerConfigStore((s) => featureFlagsSelectors(s).enableKnowledgeBase);+ /** Files sent to another person's shared Agent are refused server-side, so offer no upload. */+ const enableUpload = knowledgeBase && !channel?.sharedAgent;const canUpload = allowed && enableUpload;const upload = (files: File[]) => {if (!sending.current && canUpload) return attachments.upload(files);diff --git a/src/features/Channels/MessageReceipts.test.ts b/src/features/Channels/MessageReceipts.test.tsnew file mode 100644index 00000000000..d6fd5a328e2--- /dev/null+++ b/src/features/Channels/MessageReceipts.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest';++import { receiptErrorText } from './MessageReceipts';++const t = (key: string) => key;++describe('receiptErrorText', () => {+ // A shared Agent's visitor gets no raw failure text; the category must still explain a cap.+ it('explains a shared Agent’s spend-limit refusal in the viewer’s language', () => {+ expect(+ receiptErrorText({ errorMessage: 'monthly limit', errorType: 'ShareSpendLimitExceeded' }, t),+ ).toBe('receipt.errorShareSpendLimit');+ });++ it('explains a shared Claude Code / Codex Agent’s device refusals', () => {+ expect(+ receiptErrorText({ errorMessage: 'x', errorType: 'ShareHeterogeneousAgentUnsupported' }, t),+ ).toBe('receipt.errorShareHeteroUnsupported');+ expect(+ receiptErrorText({ errorMessage: 'x', errorType: 'ShareHeteroDeviceUnavailable' }, t),+ ).toBe('receipt.errorShareHeteroDevice');+ });++ it('explains a shared Agent’s per-visitor message-limit refusal', () => {+ expect(+ receiptErrorText(+ { errorMessage: 'ShareMessageLimitExceeded', errorType: 'ShareMessageLimitExceeded' },+ t,+ ),+ ).toBe('receipt.errorShareMessageLimit');+ });++ it('shows the recorded reason, or the fallback when none was recorded', () => {+ expect(receiptErrorText({ errorMessage: ' boom ', errorType: null }, t)).toBe('boom');+ expect(receiptErrorText({ errorMessage: null, errorType: 'AgentRuntimeError' }, t)).toBe(+ 'receipt.errorUnavailable',+ );+ });+});diff --git a/src/features/Channels/MessageReceipts.tsx b/src/features/Channels/MessageReceipts.tsxindex 089e3cce1cb..b6119077623 100644--- a/src/features/Channels/MessageReceipts.tsx+++ b/src/features/Channels/MessageReceipts.tsx@@ -1,4 +1,5 @@import type { ChannelDetail, ChannelPublicJob, ChannelPublicMessage } from '@lobechat/types';+import { ChatErrorType } from '@lobechat/types';import { Button, Flexbox, Popover, Text, usePopoverContext } from '@lobehub/ui';import * as stylex from '@stylexjs/stylex';import { ExternalLink, Square } from 'lucide-react';@@ -15,6 +16,35 @@ import { memberAvatar, memberName } from './memberName';import { statusStyles, styles } from './styles';import { useOpenReplyAgent } from './useOpenReplyAgent';+/** Failure categories with their own text; a shared Agent's visitor learns why only from these. */+const RECEIPT_ERROR_KEYS = {+ [ChatErrorType.ShareHeteroDeviceUnavailable]: 'receipt.errorShareHeteroDevice',+ [ChatErrorType.ShareHeterogeneousAgentUnsupported]: 'receipt.errorShareHeteroUnsupported',+ [ChatErrorType.ShareMessageLimitExceeded]: 'receipt.errorShareMessageLimit',+ [ChatErrorType.ShareSpendLimitExceeded]: 'receipt.errorShareSpendLimit',+} as const;++type ReceiptErrorKey =+ (typeof RECEIPT_ERROR_KEYS)[keyof typeof RECEIPT_ERROR_KEYS] | 'receipt.errorUnavailable';++/** The viewer-language text for a known failure category, if it is one. */+export const receiptErrorKey = (errorType?: string | null) =>+ errorType && Object.hasOwn(RECEIPT_ERROR_KEYS, errorType)+ ? RECEIPT_ERROR_KEYS[errorType as keyof typeof RECEIPT_ERROR_KEYS]+ : undefined;++/**+ * The failure reason under a reply. A known category reads in the viewer's language: a shared+ * Agent's visitor gets no raw text, so the category is all that explains a share's refusal.+ */+export const receiptErrorText = (+ job: Pick<ChannelPublicJob, 'errorMessage' | 'errorType'>,+ t: (key: ReceiptErrorKey) => string,+) => {+ const key = receiptErrorKey(job.errorType);+ return key ? t(key) : job.errorMessage?.trim() || t('receipt.errorUnavailable');+};+export interface ReplyEntry {agentId?: string | null;avatar?: string;@@ -108,7 +138,7 @@ export function ReplyDetail({<Flexbox gap={4}><Text weight={500}>{t('receipt.errorReason')}</Text><Text style={{ overflowWrap: 'anywhere', whiteSpace: 'pre-wrap' }}>- {job.errorMessage?.trim() || t('receipt.errorUnavailable')}+ {receiptErrorText(job, t)}</Text></Flexbox>)}diff --git a/src/features/Channels/OutgoingStatus.test.tsx b/src/features/Channels/OutgoingStatus.test.tsxnew file mode 100644index 00000000000..681c9b833a6--- /dev/null+++ b/src/features/Channels/OutgoingStatus.test.tsx@@ -0,0 +1,40 @@+/**+ * @vitest-environment happy-dom+ */+import { ChatErrorType } from '@lobechat/types';+import { render, screen } from '@testing-library/react';+import { createElement } from 'react';+import { describe, expect, it, vi } from 'vitest';++import type { ChannelOutgoingMessage } from '@/store/channel';++import { OutgoingStatus } from './OutgoingStatus';++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@lobehub/ui', () => ({+ Button: ({ children }: { children?: unknown }) => createElement('button', {}, children as never),+ Icon: () => null,+}));+vi.mock('@/store/channel', () => ({ channelActions: { discardSend: vi.fn() } }));++const failed = (errorType?: string) =>+ ({ errorType, requestKey: 'key', status: 'failed' }) as ChannelOutgoingMessage;++describe('OutgoingStatus', () => {+ // A visitor over their share's message limit saw only "not sent", with no reason.+ it('explains a refusal the server named', () => {+ render(+ createElement(OutgoingStatus, {+ message: failed(ChatErrorType.ShareMessageLimitExceeded),+ onRetry: () => {},+ }),+ );+ expect(screen.getByRole('alert').textContent).toContain('receipt.errorShareMessageLimit');+ expect(screen.queryByText('outgoing.failed')).toBeNull();+ });++ it('stays generic for any other failure', () => {+ render(createElement(OutgoingStatus, { message: failed('offline'), onRetry: () => {} }));+ expect(screen.getByText('outgoing.failed')).toBeTruthy();+ });+});diff --git a/src/features/Channels/OutgoingStatus.tsx b/src/features/Channels/OutgoingStatus.tsxindex 22f72a21ac3..e1065a30791 100644--- a/src/features/Channels/OutgoingStatus.tsx+++ b/src/features/Channels/OutgoingStatus.tsx@@ -5,9 +5,10 @@ import { useTranslation } from 'react-i18next';import { channelActions, type ChannelOutgoingMessage } from '@/store/channel';+import { receiptErrorKey } from './MessageReceipts';import { statusStyles, toneStyles } from './styles';-/** Below a message this tab sent that failed: retry and delete. */+/** Below a message this tab sent that failed: why, when the server said, then retry and delete. */export function OutgoingStatus({message,onRetry,@@ -19,11 +20,12 @@ export function OutgoingStatus({const { t } = useTranslation('channel');// A message still sending shows faded in place (`ChannelMessage` `pending`), with no line here.if (message.status !== 'failed') return null;+ const reasonKey = receiptErrorKey(message.errorType);return (<span role="alert" {...stylex.props(statusStyles.receipts, statusStyles.state)}><span {...stylex.props(statusStyles.state, toneStyles.error)}><Icon icon={CircleAlert} size={12} />- {t('outgoing.failed')}+ {reasonKey ? t(reasonKey) : t('outgoing.failed')}</span><Button size="small" type="text" onClick={() => onRetry(message)}>{t('outgoing.retry')}diff --git a/src/features/Channels/useComposerDraft.test.ts b/src/features/Channels/useComposerDraft.test.tsindex 789a4ea247a..62e2c341a3e 100644--- a/src/features/Channels/useComposerDraft.test.ts+++ b/src/features/Channels/useComposerDraft.test.ts@@ -53,6 +53,30 @@ describe('useComposerDraft', () => {expect(next.setDocument).toHaveBeenCalledWith('json', { text: 'half a thought' }, undefined);});+ // An opening question picked on a share page lands in the composer as a draft, not a send.+ it('fills an empty composer with the starter when nothing is saved', () => {+ const editor = createFakeEditor();+ const { result } = renderHook(() => useComposerDraft(editor, main, 'What can you do?'));+ act(() => result.current.restore());+ expect(editor.setDocument).toHaveBeenCalledExactlyOnceWith(+ 'markdown',+ 'What can you do?',+ undefined,+ );+ });++ it('prefers a saved draft over the starter', () => {+ saveDraft(main, { text: 'my own words' });+ const editor = createFakeEditor();+ const { result } = renderHook(() => useComposerDraft(editor, main, 'What can you do?'));+ act(() => result.current.restore());+ expect(editor.setDocument).toHaveBeenCalledExactlyOnceWith(+ 'json',+ { text: 'my own words' },+ undefined,+ );+ });+it('keeps each Thread separate from the main timeline', () => {saveDraft(main, { text: 'main draft' });const editor = createFakeEditor();diff --git a/src/features/Channels/useComposerDraft.ts b/src/features/Channels/useComposerDraft.tsindex 80cb69f2958..7b4fb06da1e 100644--- a/src/features/Channels/useComposerDraft.ts+++ b/src/features/Channels/useComposerDraft.ts@@ -18,8 +18,12 @@ export const channelDraftKey = (channelId: string, threadId?: string | null) =>/*** Keeps unsent Channel input across Channel/Thread switches and reloads, in the same* storage as the chat input. The composer remounts per key, so the key never changes here.+ *+ * `starter` is markdown to fill an empty composer when nothing is saved for the key, such as an+ * opening question picked on an Agent's share page. A saved draft wins: it is the person's own+ * input.*/-export const useComposerDraft = (editor: IEditor, draftKey: string) => {+export const useComposerDraft = (editor: IEditor, draftKey: string, starter?: string) => {// The stored revision this editor carries; an empty editor removes only that revision.const loaded = useRef<number | undefined>(undefined);@@ -43,8 +47,10 @@ export const useComposerDraft = (editor: IEditor, draftKey: string) => {if (!canSerialize(editor)) return;const draft = getDraftEntry(draftKey);loaded.current = draft?.updatedAt;- if (draft && editor.isEmpty) writeDocument(editor, 'json', draft.json);- }, [draftKey, editor]);+ if (!editor.isEmpty) return;+ if (draft) writeDocument(editor, 'json', draft.json);+ else if (starter) writeDocument(editor, 'markdown', starter);+ }, [draftKey, editor, starter]);/** Saves pending input and returns its stored revision, taken when a send starts. */const snapshot = useCallback(() => {diff --git a/src/services/channel.ts b/src/services/channel.tsindex 0bda62fc8cf..7a39f741a49 100644--- a/src/services/channel.ts+++ b/src/services/channel.ts@@ -84,6 +84,9 @@ class ChannelService {/** The caller's direct Channel with an Agent, opened if missing; null when it cannot answer there. */openDirect = async (input: { agentId: string }) =>(await lambdaClient.channel.openDirect.mutate(input)).data;+ /** The caller's direct Channel with another person's shared Agent, from its share id or handle. */+ openShared = async (input: { share: string }) =>+ (await lambdaClient.channel.openShared.mutate(input)).data;detail = async (params: ChannelViewParams): Promise<ChannelDetail> =>(await lambdaClient.channel.detail.query(params)).data;list = async (): Promise<ChannelListItem[]> => (await lambdaClient.channel.list.query()).data;diff --git a/src/store/channel/action.openDirect.test.ts b/src/store/channel/action.openDirect.test.tsindex 586bee7b45e..c727d8263f6 100644--- a/src/store/channel/action.openDirect.test.ts+++ b/src/store/channel/action.openDirect.test.ts@@ -5,7 +5,7 @@ import { channelActions } from './action';import { useChannelStore } from './store';vi.mock('@/services/channel', () => ({- channelService: { list: vi.fn(), markRead: vi.fn(), openDirect: vi.fn() },+ channelService: { list: vi.fn(), markRead: vi.fn(), openDirect: vi.fn(), openShared: vi.fn() },}));const { channelService } = await import('@/services/channel');@@ -56,6 +56,31 @@ describe('channelActions.openDirect', () => {});});+describe('channelActions.openShared', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ channelActions.reset();+ vi.mocked(channelService.list).mockResolvedValue([]);+ });++ // A listed direct Channel must not skip the server: it re-checks that the share is still live.+ it('asks the server even when a direct Channel with the Agent is listed', async () => {+ useChannelStore.setState({ listMap: { all: [direct({})] } });+ vi.mocked(channelService.openShared).mockResolvedValue('chn_000000000001');++ await expect(channelActions.openShared('nasa')).resolves.toBe('chn_000000000001');+ expect(channelService.openShared).toHaveBeenCalledExactlyOnceWith({ share: 'nasa' });+ expect(channelService.list).toHaveBeenCalled();+ });++ it('rejects when the share is paused or gone', async () => {+ vi.mocked(channelService.openShared).mockRejectedValue(new Error('Agent not found'));++ await expect(channelActions.openShared('nasa')).rejects.toThrow('Agent not found');+ expect(channelService.list).not.toHaveBeenCalled();+ });+});+describe('channelActions.markRead', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/src/store/channel/action.queueSend.test.ts b/src/store/channel/action.queueSend.test.tsindex c806d4983cc..adc4bdf4c82 100644--- a/src/store/channel/action.queueSend.test.ts+++ b/src/store/channel/action.queueSend.test.ts@@ -85,6 +85,21 @@ describe('Channel queued send', () => {expect(requestKeys).toEqual([failed.requestKey, failed.requestKey]);});+ it('keeps the refusal the server named until the message is retried', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(channelService.send).mockRejectedValueOnce(new Error('ShareMessageLimitExceeded'));+ await channelActions.queueSend(input);+ const [failed] = outgoing();+ expect(failed).toMatchObject({ errorType: 'ShareMessageLimitExceeded', status: 'failed' });++ const gate = Promise.withResolvers<SendResult>();+ vi.mocked(channelService.send).mockReturnValueOnce(gate.promise);+ const retried = channelActions.retrySend(failed);+ expect(outgoing()[0]).toMatchObject({ errorType: undefined, status: 'sending' });+ gate.resolve(result(stored('message', 2)));+ await retried;+ });+it('does not send a failed message after it is deleted', async () => {vi.spyOn(console, 'error').mockImplementation(() => {});vi.mocked(channelService.send).mockRejectedValueOnce(new Error('offline'));diff --git a/src/store/channel/action.ts b/src/store/channel/action.tsindex 042c673e84e..baac76e94d7 100644--- a/src/store/channel/action.ts+++ b/src/store/channel/action.ts@@ -126,6 +126,16 @@ class ChannelActionImpl {if (channelId) await this.#refreshAfterWrite(this.refreshList);return channelId ?? undefined;};+ /**+ * The caller's direct Channel with a shared Agent, opened on first use from its share id or+ * handle. The server resolves the share every time, so a paused or revoked share fails here+ * even when a Channel already exists.+ */+ openShared = async (share: string) => {+ const channelId = await channelService.openShared({ share });+ if (channelId) await this.#refreshAfterWrite(this.refreshList);+ return channelId ?? undefined;+ };remove = async (channelId: string) => {const scope = cacheScope.get();// Optimistically hide the row; failure restores it. Keep the open conversation@@ -323,7 +333,10 @@ class ChannelActionImpl {retrySend = (message: ChannelOutgoingMessage) => {if (findOutgoing(useChannelStore.getState().outbox, message)?.status !== 'failed')return Promise.resolve(undefined);- this.#setOutbox((outbox) => patchOutgoing(outbox, message, { status: 'sending' }), 'retry');+ this.#setOutbox(+ (outbox) => patchOutgoing(outbox, message, { errorType: undefined, status: 'sending' }),+ 'retry',+ );return this.#deliver(message);};discardSend = (message: ChannelOutgoingMessage) => {@@ -398,7 +411,12 @@ class ChannelActionImpl {return data;} catch (error) {console.error('Failed to send Channel message', error);- this.#setOutbox((outbox) => patchOutgoing(outbox, message, { status: 'failed' }), 'failed');+ // A refusal names its category as the message (`ChannelError`); anything else stays generic.+ const errorType = error instanceof Error ? error.message : undefined;+ this.#setOutbox(+ (outbox) => patchOutgoing(outbox, message, { errorType, status: 'failed' }),+ 'failed',+ );}};#refreshAfterSend = (input: ChannelSendInput, threadId: string | null) =>diff --git a/src/store/channel/outbox.ts b/src/store/channel/outbox.tsindex 8511ec7d477..195bc254fab 100644--- a/src/store/channel/outbox.ts+++ b/src/store/channel/outbox.ts@@ -12,6 +12,11 @@ export interface ChannelOutgoingMessage {channelId: string;content: string;createdAt: Date;+ /**+ * Why the server refused a failed send, when it named a known category (a `ChatErrorType`);+ * the conversation explains it in the viewer's language.+ */+ errorType?: string;fileIds: string[];mentions: string[];replyTo?: ChannelPublicMessage['replyTo'];@@ -49,7 +54,7 @@ export const addOutgoing = (outbox: ChannelOutbox, message: ChannelOutgoingMessaexport const patchOutgoing = (outbox: ChannelOutbox,message: ChannelOutgoingMessage,- patch: Partial<Pick<ChannelOutgoingMessage, 'sent' | 'status'>>,+ patch: Partial<Pick<ChannelOutgoingMessage, 'errorType' | 'sent' | 'status'>>,) => {const key = outboxKeyOf(message);const entries = outbox[key];