🤯 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
🐛 fix(channel): fail a refused shared Agent reply with a readable reason (#23474)
YuTengjing49f73191c5af
diff --git a/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts b/apps/server/src/services/channel/ChannelCoordinator.advance.test.tsindex 08cde2178a3..c60b5bccc35 100644--- a/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts+++ b/apps/server/src/services/channel/ChannelCoordinator.advance.test.ts@@ -331,7 +331,9 @@ describe('Channel concurrent startup', () => {executions.openingReply.mockResolvedValue('收到,我先翻一下昨天的报错日志。');await coordinator(1).advance('channel');- expect(openChannelReply).toHaveBeenCalledWith(expect.anything(), 'channel', 'job-0');+ expect(openChannelReply).toHaveBeenCalledWith(expect.anything(), 'channel', 'job-0', {+ admitShare: expect.any(Function),+ });expect(order).toEqual(['open', 'claim']);const [{ prompt }] = execAgent.mock.calls[0];expect(prompt).toContain('<channel_opening');diff --git a/apps/server/src/services/channel/ChannelCoordinator.share.test.ts b/apps/server/src/services/channel/ChannelCoordinator.share.test.tsindex fb37dba18e1..54e99d9a6cb 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 { SHARE_VISITOR_PROMPT_MAX_LENGTH } from '@lobechat/const';import { TRPCError } from '@trpc/server';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -6,6 +7,7 @@ import { ChannelCoordinator } from './ChannelCoordinator';const {checkSpend,+ countMessagesBySender,execAgent,executions,findOperation,@@ -15,6 +17,7 @@ const {serviceOptions,} = vi.hoisted(() => ({checkSpend: vi.fn(),+ countMessagesBySender: vi.fn(),getScopedOnlineDevices: vi.fn(),execAgent: vi.fn(),executions: {@@ -49,6 +52,11 @@ vi.mock('@/database/models/agentOperation', () => ({findById = findOperation;},}));+vi.mock('@/database/models/topic', () => ({+ TopicModel: class {+ countMessagesBySender = countMessagesBySender;+ },+}));vi.mock('@/business/server/agent-share/spendGate', () => ({checkAgentShareSpendAllowance: checkSpend,}));@@ -79,7 +87,7 @@ const share = { ownerId: 'owner', shareId: 'share-1', workspaceId: 'owner-ws' };const liveShare = {agentId: 'agt_shared',ownerId: 'owner',- shareConfig: { monthlySpendLimit: 5, toolGrants: [] },+ shareConfig: { maxMessagesPerVisitor: 2, monthlySpendLimit: 5, toolGrants: [] },shareId: 'share-1',visibility: 'link',workspaceId: 'owner-ws',@@ -127,6 +135,7 @@ describe('dispatching a contact’s shared Agent', () => {execAgent.mockResolvedValue({ success: true });findShare.mockResolvedValue(liveShare);checkSpend.mockResolvedValue({ allowed: true });+ countMessagesBySender.mockResolvedValue(1);findOperation.mockResolvedValue({ status: 'idle' });executions.claim.mockResolvedValue({job: {@@ -229,13 +238,57 @@ describe('dispatching a contact’s shared Agent', () => {await coordinator().advance('channel');expect(executions.retireReservation).toHaveBeenCalledWith('channel', 'job', {- message: type,+ message: expect.not.stringContaining(type),type,});},);++ // Sending no longer refuses for a share's limits: the reply fails here, so the visitor's message+ // stays and its failure explains the limit after a reload.+ it('refuses a prompt beyond the share’s length cap before submission', async () => {+ executions.input.mockResolvedValue([+ { content: 'x'.repeat(SHARE_VISITOR_PROMPT_MAX_LENGTH + 1), id: 'message' },+ ]);+ await coordinator().advance('channel');++ expect(execAgent).not.toHaveBeenCalled();+ expect(executions.retireReservation).toHaveBeenCalledWith('channel', 'job', {+ message: `Messages to a shared Agent are limited to ${SHARE_VISITOR_PROMPT_MAX_LENGTH} characters`,+ type: 'SharePromptTooLong',+ });+ });++ // The quoted message rides in the input beside the request, but only the request is the prompt.+ it('admits a short request quoting a message beyond the length cap', async () => {+ const author = { id: 'visitor', name: 'Visitor', type: 'user' };+ executions.input.mockResolvedValue([+ { author, content: 'x'.repeat(SHARE_VISITOR_PROMPT_MAX_LENGTH + 1), id: 'quoted' },+ { author, content: 'Summarize this', id: 'message' },+ ]);+ await coordinator().advance('channel');++ expect(execAgent).toHaveBeenCalledOnce();+ expect(executions.retireReservation).not.toHaveBeenCalled();+ });++ it('refuses once the visitor sent maxMessagesPerVisitor, counted as the owner', async () => {+ countMessagesBySender.mockResolvedValue(2);+ await coordinator().advance('channel');++ expect(countMessagesBySender).toHaveBeenCalledWith({+ agentId: 'agt_shared',+ senderId: 'visitor',+ });+ expect(execAgent).not.toHaveBeenCalled();+ expect(checkSpend).not.toHaveBeenCalled();+ expect(executions.retireReservation).toHaveBeenCalledWith('channel', 'job', {+ message: 'You have sent all the messages this shared Agent allows',+ type: 'ShareMessageLimitExceeded',+ });+ });// 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.+ // (the gate's count can race it); the receipt must still say why, as readable text.it('records the message-limit refusal raised by the turn guard', async () => {execAgent.mockRejectedValue(new TRPCError({ code: 'TOO_MANY_REQUESTS', message: 'ShareMessageLimitExceeded' }),@@ -243,7 +296,7 @@ describe('dispatching a contact’s shared Agent', () => {await coordinator().advance('channel');expect(executions.retireReservation).toHaveBeenCalledWith('channel', 'job', {- message: 'ShareMessageLimitExceeded',+ message: 'You have sent all the messages this shared Agent allows',type: 'ShareMessageLimitExceeded',});});diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.tsindex 262cc0d6c67..a4d06bdb809 100644--- a/apps/server/src/services/channel/ChannelCoordinator.ts+++ b/apps/server/src/services/channel/ChannelCoordinator.ts@@ -1,4 +1,5 @@import { ChannelIdentifier } from '@lobechat/builtin-tool-channel';+import { SHARE_VISITOR_PROMPT_MAX_LENGTH } from '@lobechat/const';import type { LobeChatDatabase } from '@lobechat/database';import { buildChannelPrompt, CHANNEL_INSTRUCTIONS } from '@lobechat/prompts';import type { ChannelExecutionConfig, ChannelSharedAgentAccess } from '@lobechat/types';@@ -57,23 +58,31 @@ class ChannelDispatchError extends Error {}/**- * 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 local CLI Agent- * (Claude Code, Codex, …), 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.+ * Every refusal of a shared Agent's run its visitor can act on, with the readable text its failed+ * job carries. Sending never refuses for these: the message is written, and its reply fails with+ * one of these types, so every limit reads the same way and survives a reload. Raised by+ * {@link ChannelCoordinator.shareGate}, or by the run's own share guards (the turn guard's atomic+ * recount, the device checks of a local CLI Agent such as Claude Code or Codex), which name the+ * type as their message. A client explains the type in the viewer's language; the text is for one that does not know it.*/-const SHARE_REFUSAL_TYPES = new Set<string>([- ChatErrorType.ShareHeterogeneousAgentUnsupported,- ChatErrorType.ShareHeteroDeviceUnavailable,- ChatErrorType.ShareMessageLimitExceeded,-]);+const SHARE_REFUSAL_MESSAGES: Record<string, string> = {+ [ChatErrorType.ShareHeterogeneousAgentUnsupported]:+ 'This shared Agent cannot run for visitors in its current setup',+ [ChatErrorType.ShareHeteroDeviceUnavailable]: 'The device this shared Agent runs on is offline',+ [ChatErrorType.ShareMessageLimitExceeded]:+ 'You have sent all the messages this shared Agent allows',+ [ChatErrorType.SharePromptTooLong]: `Messages to a shared Agent are limited to ${SHARE_VISITOR_PROMPT_MAX_LENGTH} characters`,+ [ChatErrorType.ShareSpendLimitExceeded]: 'This shared Agent reached its monthly usage limit',+};++const shareRefusal = (type: string) => new ChannelDispatchError(type, SHARE_REFUSAL_MESSAGES[type]);-const dispatchFailureType = (error: unknown) =>- error instanceof ChannelDispatchError- ? error.type- : error instanceof Error && SHARE_REFUSAL_TYPES.has(error.message)- ? error.message- : undefined;+/** The failure a refused dispatch records: its type and text, when the requester can act on it. */+const dispatchFailure = (error: unknown): { message: string; type: string } | undefined => {+ if (error instanceof ChannelDispatchError) return { message: error.message, type: error.type };+ if (error instanceof Error && Object.hasOwn(SHARE_REFUSAL_MESSAGES, error.message))+ return { message: SHARE_REFUSAL_MESSAGES[error.message], type: error.message };+};/** A co-addressed Agent as the run reads it: its name, and its title when that says more. */const describePeer = (agent: ChannelCoAddressedAgent) => {@@ -100,13 +109,20 @@ export class ChannelCoordinator {}/**- * Recheck a shared Agent's live share and its owner's spend limit right before submission, as- * the share page does for every visitor turn, and build the gate the run executes under.+ * Admit a visitor's message to a shared Agent right before submission, and build the gate the+ * run executes under. The one place a visitor's limits refuse a Channel reply, in the order the+ * share page checks them: the live share, the prompt length, the messages the visitor may send+ * (`maxMessagesPerVisitor`, across all their conversations with the Agent) and the share's+ * monthly spend. Like the spend limit, the message count is a guardrail rather than a+ * reservation: concurrent replies can each pass here, and the run's turn guard+ * (`reserveShareVisitorTurn`) refuses the one beyond the cap.*/private async shareGate(access: ChannelSharedAgentAccess,agentId: string,requesterId: string,+ /** The visitor's own message; a message it quotes is not part of its prompt. */+ request: string,): Promise<AgentShareGate> {const share = await AgentShareModel.findByShareId(this.db, access.shareId);if (@@ -116,6 +132,17 @@ export class ChannelCoordinator {share.ownerId !== access.ownerId)throw new Error('This Agent is no longer shared');+ if (request.length > SHARE_VISITOR_PROMPT_MAX_LENGTH)+ throw shareRefusal(ChatErrorType.SharePromptTooLong);+ const sent = await new TopicModel(+ this.db,+ share.ownerId,+ share.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ ).countMessagesBySender({ agentId, senderId: requesterId });+ if (sent >= share.shareConfig.maxMessagesPerVisitor)+ throw shareRefusal(ChatErrorType.ShareMessageLimitExceeded);const spend = await checkAgentShareSpendAllowance({agentId,monthlySpendLimit: share.shareConfig.monthlySpendLimit,@@ -124,11 +151,7 @@ export class ChannelCoordinator {visitorUserId: requesterId,workspaceId: share.workspaceId ?? undefined,});- if (!spend.allowed)- throw new ChannelDispatchError(- ChatErrorType.ShareSpendLimitExceeded,- 'This shared Agent reached its monthly usage limit',- );+ if (!spend.allowed) throw shareRefusal(ChatErrorType.ShareSpendLimitExceeded);return {agentId,canUseDevice: await resolveShareVisitorDeviceAccess(this.db, share, requesterId),@@ -207,8 +230,16 @@ export class ChannelCoordinator {await this.complete(channelId, job.id, job.operationId ?? undefined);continue;}- // Before the claim: a reply that moves into a Thread runs there from the start.- await openChannelReply(this.db, channelId, job.id);+ // Before the claim: a reply that moves into a Thread runs there from the start. A+ // shared Agent's reply opens only once its share admits the request.+ await openChannelReply(this.db, channelId, job.id, {+ admitShare: ({ agent, request, requesterUserId, share }) =>+ // Only a refusal skips the opening; a failed check leaves it to dispatch.+ this.shareGate(share, agent.id, requesterUserId, request.content).then(+ () => true,+ (error) => !dispatchFailure(error),+ ),+ });const claimNow = () =>this.executions.claim(channelId, job.id, {leaseMs: LEASE_MS,@@ -349,7 +380,12 @@ export class ChannelCoordinator {]);const shareGate =share && topic.senderId- ? await this.shareGate(share, member.agentId, topic.senderId)+ ? await this.shareGate(+ share,+ member.agentId,+ topic.senderId,+ input.find((message) => message.id === job.manifest!.requestMessageId)?.content ?? '',+ ): undefined;if (share && !shareGate) throw new Error('A shared Agent run needs its requester');// Sending refuses attachments to a shared Agent: the owner's run cannot read them.@@ -394,23 +430,20 @@ export class ChannelCoordinator {await this.executions.accepted(job.channelId, job.id);} catch (error) {console.error('[channel:dispatch]', error);- const type = dispatchFailureType(error);+ const failure = dispatchFailure(error);const operation = await new AgentOperationModel(this.db,topic.userId,workspaceId ?? undefined,).findById(job.operationId);if (operation?.status === 'idle') {- await this.executions.retireReservation(+ await this.executions.retireReservation(job.channelId, job.id, failure);+ } else+ await this.executions.fail(job.channelId,job.id,- type && error instanceof Error ? { message: error.message, type } : undefined,+ failure ?? { message: error instanceof Error ? error.message : 'Agent could not start' },);- } else- await this.executions.fail(job.channelId, job.id, {- message: error instanceof Error ? error.message : 'Agent could not start',- ...(type && { type }),- });} finally {clearInterval(renew);await this.executions.finishDispatch(job.channelId, job.id, lease.leaseOwner);diff --git a/apps/server/src/services/channel/replyOpening.test.ts b/apps/server/src/services/channel/replyOpening.test.tsindex 2a8360927eb..f08ac0099c2 100644--- a/apps/server/src/services/channel/replyOpening.test.ts+++ b/apps/server/src/services/channel/replyOpening.test.ts@@ -211,6 +211,29 @@ describe('openChannelReply', () => {});});+ it('opens a shared Agent’s reply only once its share admits the request', async () => {+ const share = { ownerId: 'owner', shareId: 'share', workspaceId: null };+ executions.openingCandidate.mockResolvedValue({ ...candidate, share });+ const opener = vi.fn().mockResolvedValue({ ack: 'On it', placement: 'channel' });+ const admitShare = vi.fn().mockResolvedValueOnce(false).mockResolvedValueOnce(true);++ await openChannelReply({} as never, 'channel', 'job', {+ admitShare,+ createOpener: () => opener,+ });+ expect(admitShare).toHaveBeenCalledWith(+ expect.objectContaining({ request: candidate.request, share }),+ );+ expect(opener).not.toHaveBeenCalled();+ expect(executions.open).not.toHaveBeenCalled();++ await openChannelReply({} as never, 'channel', 'job', {+ admitShare,+ createOpener: () => opener,+ });+ expect(executions.open).toHaveBeenCalledWith('channel', 'job', { ack: 'On it' });+ });+it('skips a job with nothing to open and never throws', async () => {const opener = vi.fn();executions.openingCandidate.mockResolvedValueOnce(undefined);diff --git a/apps/server/src/services/channel/replyOpening.ts b/apps/server/src/services/channel/replyOpening.tsindex cd4366b36de..09002c96c88 100644--- a/apps/server/src/services/channel/replyOpening.ts+++ b/apps/server/src/services/channel/replyOpening.ts@@ -13,6 +13,13 @@ import { knownQuotaReset } from './quotaReset';const log = debug('lobe-server:channel:reply-opening');export interface OpenChannelReplyDeps {+ /**+ * Whether a shared Agent's share admits the request. A refused one does not open: its reply+ * fails at dispatch where it was asked, instead of acknowledging work it will not do.+ */+ admitShare?: (+ candidate: ChannelOpeningCandidate & Required<Pick<ChannelOpeningCandidate, 'share'>>,+ ) => Promise<boolean>;/** Builds the opener for a candidate; defaults to the Channel's, run as the requester. */createOpener?: (candidate: ChannelOpeningCandidate) => ChannelReplyOpener;/** When the Agent's usage window reopens, if a known one is still closed; see `knownQuotaReset`. */@@ -125,6 +132,12 @@ export const openChannelReply = async (try {const candidate = await executions.openingCandidate(channelId, jobId);if (!candidate) return;+ if (+ candidate.share &&+ deps.admitShare &&+ !(await deps.admitShare({ ...candidate, share: candidate.share }))+ )+ return;// The Agent's last reply on the same login was refused by a usage window that is still// closed: an acknowledgement would promise work the run cannot do. It opens with nothing anddiff --git a/locales/en-US/channel.json b/locales/en-US/channel.jsonindex 7f817eec3aa..70c440d96ad 100644--- a/locales/en-US/channel.json+++ b/locales/en-US/channel.json@@ -191,6 +191,7 @@"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.errorSharePromptTooLong": "This message is longer than a shared Agent accepts. Shorten it and send it again.","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.",@@ -259,6 +260,11 @@"settings.visibility.privateHint": "Only invited members can see this channel. Turn it on to let everyone in the workspace find and join it.","settings.visibility.publicHint": "Everyone in the workspace can find and join this channel.","settings.visibility.title": "Public channel",+ "shareRefusal.addOwner": "Add contact",+ "shareRefusal.added": "Added as a contact",+ "shareRefusal.alreadyContact": "Already your contact",+ "shareRefusal.ownerCaption": "Creator of this Agent",+ "shareRefusal.requestSent": "Request sent","shareVisitorReadOnlyNotice": "A visitor's conversation through your share link. You can read it but can't reply.","sort.by": "Sort by","sort.by.createdAt": "Date created",diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.jsonindex b5c102212ad..bffdb081ce8 100644--- a/locales/zh-CN/channel.json+++ b/locales/zh-CN/channel.json@@ -191,6 +191,7 @@"receipt.errorShareHeteroDevice": "创建者的设备当前离线,请稍后再试。","receipt.errorShareHeteroUnsupported": "这个 Agent 需要创建者授权后才能为你运行,请联系创建者开通。","receipt.errorShareMessageLimit": "你发给这个分享 Agent 的消息已达到创建者设置的上限。",+ "receipt.errorSharePromptTooLong": "这条消息超出了分享 Agent 允许的长度,请缩短后重新发送。","receipt.errorShareSpendLimit": "这个分享的 Agent 已达到创作者设置的每月用量上限,下个月会恢复。","receipt.errorUnavailable": "未记录具体原因,请检查 Agent 的模型与设备设置后重新发送。","receipt.failedHint": "再次 @ 它即可重试。",@@ -259,6 +260,11 @@"settings.visibility.privateHint": "只有被邀请的成员能看到这个频道。开启后,工作区里的所有人都可以找到并加入。","settings.visibility.publicHint": "工作区里的所有人都可以找到并加入这个频道。","settings.visibility.title": "公开频道",+ "shareRefusal.addOwner": "添加联系人",+ "shareRefusal.added": "已添加为联系人",+ "shareRefusal.alreadyContact": "已是你的联系人",+ "shareRefusal.ownerCaption": "这个 Agent 的创建者",+ "shareRefusal.requestSent": "已发送请求","shareVisitorReadOnlyNotice": "这是访客通过你的分享链接发起的对话,你只能查看,不能回复。","sort.by": "排序方式","sort.by.createdAt": "创建时间",diff --git a/packages/database/src/models/message/visitor.ts b/packages/database/src/models/message/visitor.tsindex 167385ace03..68e24e272ef 100644--- a/packages/database/src/models/message/visitor.ts+++ b/packages/database/src/models/message/visitor.ts@@ -199,6 +199,7 @@ export const redactCreatorPrivateBlob = <T>(value: T): T => {const VISITOR_SAFE_ERROR_TYPES = new Set<string>([ChatErrorType.ShareMessageLimitExceeded,ChatErrorType.ShareSpendLimitExceeded,+ ChatErrorType.SharePromptTooLong,ChatErrorType.ShareHeterogeneousAgentUnsupported,ChatErrorType.ShareHeteroDeviceUnavailable,ChatErrorType.AgentShareProviderNotSupported,diff --git a/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts b/packages/database/src/repositories/channel/__tests__/sharedAgent.test.tsindex b8fcf569989..172bc1026d9 100644--- a/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts+++ b/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts@@ -86,8 +86,11 @@ 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 });+ // The conversation view marks it too: its composer reads `detail`, not the list, and a refused+ // reply offers its owner's contact card.+ const detail = await visitor.detail(channel.id);+ expect(detail.channel).toMatchObject({ sharedAgent: true });+ expect(detail.sharedAgentOwner).toMatchObject({ id: ownerId });});it('lists the share id as its handle when the owner set no custom slug', async () => {@@ -138,6 +141,21 @@ describe('a contact’s shared Agent in a direct conversation', () => {});});+ it('names its share to the reply opener, which must admit the request first', async () => {+ const { channel } = await visitor.create({+ agentId,+ sharedAgent: true,+ title: 'Shared Helper',+ });+ const job = await send(channel.id, 'first');++ expect(await execution.openingCandidate(channel.id, job.id)).toMatchObject({+ request: { content: 'Request first' },+ requesterUserId: visitorId,+ share: { ownerId, shareId, workspaceId: null },+ });+ });+// 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 () => {@@ -362,6 +380,32 @@ describe('a contact’s shared Agent in a direct conversation', () => {});});+ // A failure recording only its type skipped redaction, so the visitor read the owner's+ // budget state from the raw type.+ it('redacts a failure that records only its type', async () => {+ const { channel } = await visitor.create({+ agentId,+ sharedAgent: true,+ title: 'Shared Helper',+ });+ const claim = (await execution.claim(+ channel.id,+ (await send(channel.id, 'bare')).id,+ lease,+ ))!;+ await execution.fail(channel.id, claim.job.id, { message: 'unused' });+ await db+ .update(agentOperations)+ .set({ error: { type: 'InsufficientBudgetForModel' } })+ .where(eq(agentOperations.id, claim.job.operationId!));+ const job = (await visitor.detail(channel.id))!.jobs.find(+ (item) => item.id === claim.job.id,+ )!;++ expect(job.errorMessage).toBeNull();+ expect(job.errorType).toBe('AgentRuntimeError');+ });+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 });@@ -372,57 +416,60 @@ describe('a contact’s shared Agent in a direct conversation', () => {});});+ // Every share limit refuses the reply when it is dispatched, never the send, so the visitor's+ // message stays and its failed reply explains the limit, after a reload too.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 () => {+ it('sends a prompt beyond the share’s length cap, queuing its reply', 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();+ const message = await sendText(+ channel.id,+ 'x'.repeat(SHARE_VISITOR_PROMPT_MAX_LENGTH + 1),+ 'long',+ );++ expect(await jobsOf(db, message.id)).toHaveLength(1);});- it('refuses a message once the visitor sent maxMessagesPerVisitor, not counting replies', async () => {+ it('sends past maxMessagesPerVisitor, queuing its reply', async () => {await db.update(agentShares)- .set({ shareConfig: { maxMessagesPerVisitor: 2 } })+ .set({ shareConfig: { maxMessagesPerVisitor: 1 } }).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+ const [topic] = 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',- });+ .values({ content: 'one', role: 'user', topicId: topic.id, userId: ownerId });+ const message = await sendText(channel.id, 'two', 'two');++ expect(await jobsOf(db, message.id)).toHaveLength(1);});++ it.each(['ShareMessageLimitExceeded', 'SharePromptTooLong', 'ShareSpendLimitExceeded'])(+ 'keeps the %s refusal of its reply readable after a reload',+ async (type) => {+ const channel = await open();+ const claim = (await execution.claim(+ channel.id,+ (await send(channel.id, 'hi')).id,+ lease,+ ))!;+ await execution.retireReservation(channel.id, claim.job.id, { message: 'Readable', type });+ const job = (await visitor.detail(channel.id))!.jobs.find(+ (item) => item.id === claim.job.id,+ )!;++ expect(job).toMatchObject({ errorMessage: 'Readable', errorType: type, status: 'failed' });+ },+ );});describe('reading its conversation history', () => {@@ -575,7 +622,25 @@ describe('a shared Agent in the visitor’s workspace', () => {const { channel } = await inWorkspace.create({ agentId: teamAgentId, title: 'Team Helper' });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 });+ expect(listed).toMatchObject({+ id: channel.id,+ sharedAgent: false,+ sharedAgentHandle: null,+ });+ const teamDetail = await inWorkspace.detail(channel.id);+ expect(teamDetail.channel).toMatchObject({ sharedAgent: false });+ expect(teamDetail.sharedAgentOwner).toBeNull();++ // Its link share does not limit a colleague, who runs it as their own: the reply opens freely.+ await db.insert(agentShares).values({ agentId: teamAgentId, visibility: 'link' });+ const message = await inWorkspace.send(channel.id, {+ content: 'Hello team',+ requestKey: 'team',+ routing: 'fallback',+ });+ const [job] = await jobsOf(db, message.id);+ const candidate = await execution.openingCandidate(channel.id, job.id);+ expect(candidate).toBeDefined();+ expect(candidate?.share).toBeUndefined();});});diff --git a/packages/database/src/repositories/channel/agent.ts b/packages/database/src/repositories/channel/agent.tsindex 541cd96cdae..a09fe8faf9b 100644--- a/packages/database/src/repositories/channel/agent.ts+++ b/packages/database/src/repositories/channel/agent.ts@@ -4,6 +4,7 @@ import type {ChannelExecutionConfig,ChannelMemberConfig,ChannelSharedAgentAccess,+ ContactUserProfile,LobeAgentConfig,} from '@lobechat/types';import { agentDisplayName, isChannelRuntime } from '@lobechat/types';@@ -12,8 +13,8 @@ import { and, eq, ne } from 'drizzle-orm';import type { PartialDeep } from 'type-fest';import type { ChannelItem, ChannelMemberItem } from '../../schemas';-import { agents, agentShares, channelMembers, userSettings } from '../../schemas';-import type { Transaction } from '../../type';+import { agents, agentShares, channelMembers, users, userSettings } from '../../schemas';+import type { LobeChatDatabase, Transaction } from '../../type';import { agentUsableByWhere } from '../../utils/agent-access';import { mergeAgentDefaultConfig } from '../../utils/agentConfig';import { normalizeInboxAgentTitle } from '../../utils/inboxAgent';@@ -41,27 +42,62 @@ export const isSharedAgentChannel = (agent.agentVisibility !== 'private');+/**+ * What a listed Channel tells its viewer about another person's shared Agent it is with: that it+ * is one, and its visitor page (`/a/<handle>`), the only page of the Agent the viewer can open.+ */+export const sharedAgentFields = (+ channel: Pick<ChannelItem, 'agentId' | 'workspaceId'>,+ agent: Parameters<typeof isSharedAgentChannel>[1],+ viewerId: string,+ handle: string | null,+) => {+ const sharedAgent = isSharedAgentChannel(channel, agent, viewerId);+ return {+ sharedAgent,+ sharedAgentHandle: sharedAgent ? handle : null,+ };+};+/*** The owner of the Agent a direct conversation is with, when it is another person's shared Agent- * (`isSharedAgentChannel`); `null` otherwise.+ * (`isSharedAgentChannel`): the profile a refused reply's contact card shows. `null` otherwise.*/export const sharedAgentOwner = async (tx: Transaction,channel: Pick<ChannelItem, 'agentId' | 'workspaceId'>,viewerId: string,-): Promise<string | null> => {+): Promise<ContactUserProfile | null> => {if (!channel.agentId) return null;const [agent] = await tx.select({agentOwnerId: agents.userId,agentVisibility: agents.visibility,agentWorkspaceId: agents.workspaceId,+ owner: {+ avatar: users.avatar,+ fullName: users.fullName,+ id: users.id,+ username: users.username,+ },}).from(agents)+ .innerJoin(users, eq(users.id, agents.userId)).where(eq(agents.id, channel.agentId));- return agent?.agentOwnerId && isSharedAgentChannel(channel, agent, viewerId)- ? agent.agentOwnerId- : null;+ return agent && isSharedAgentChannel(channel, agent, viewerId) ? agent.owner : null;+};++/**+ * What a conversation view says about another person's shared Agent it is with: the same marks as+ * `list` (the composer reads them there to hide upload) and the owner's contact card.+ */+export const sharedAgentView = async (+ tx: Transaction,+ channel: Pick<ChannelItem, 'agentId' | 'workspaceId'>,+ viewerId: string,+) => {+ const owner = await sharedAgentOwner(tx, channel, viewerId);+ return { channel: { sharedAgent: !!owner }, owner };};/** Explicitly select environment fields so legacy or untyped copies cannot override an Agent. */@@ -87,7 +123,7 @@ export interface ChannelAddAgentInput {* limits per person.*/export const findSharedChannelAgent = async (- tx: Transaction,+ tx: LobeChatDatabase | Transaction,userId: string,agentId: string,): Promise<@@ -130,6 +166,28 @@ export const findSharedChannelAgent = async (const acceptsSharedAgent = (channel: Pick<ChannelItem, 'agentId'>, agentId: string) =>channel.agentId === agentId;+/**+ * The share a member's reply runs under, resolved as {@link resolveExecutionConfig} does: only in a+ * direct conversation, and only for an Agent the requester cannot use as their own.+ */+export const channelReplyShare = async (+ db: LobeChatDatabase | Transaction,+ channel: Pick<ChannelItem, 'agentId' | 'workspaceId'>,+ agentId: string,+ userId: string,+) => {+ if (!acceptsSharedAgent(channel, agentId)) return;+ const [usable] = await db+ .select({ id: agents.id })+ .from(agents)+ .where(agentUsableByWhere(agentId, { userId, workspaceId: channel.workspaceId ?? undefined }));+ if (usable) return;+ const share = await findSharedChannelAgent(db, userId, agentId);+ return (+ share && { ownerId: share.ownerId, shareId: share.shareId, workspaceId: share.workspaceId }+ );+};+/** Check Agent scope and hold it through creation of the Channel/member reference. */export const requireChannelAgent = async (tx: Transaction,diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 0f758507cf3..a0b7fbfd03c 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -29,11 +29,11 @@ import { normalizeWorkspaceId } from '../../utils/workspace';import type { ChannelAddAgentInput } from './agent';import {addAgentMember,- isSharedAgentChannel,memberEnvironment,requireAgentMember,requireChannelAgent,- sharedAgentOwner,+ sharedAgentFields,+ sharedAgentView,} from './agent';import { openAgentPair } from './agentPair';import { channelAvatarMembers } from './avatars';@@ -452,11 +452,11 @@ 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));+ const shared = await sharedAgentView(tx, access.channel, this.userId);return {- channel: { ...access.channel, canDelete: admin, sharedAgent },+ channel: { ...access.channel, canDelete: admin, ...shared.channel },joined: true,+ sharedAgentOwner: shared.owner,...view,// Mirrors `stop`: the requester or an admin.jobs: viewerJobs(view.jobs, this.userId, (id) => admin || id === access.member.id),@@ -688,13 +688,10 @@ export class ChannelRepository {shareSlug,...agent}) => {- const sharedAgent = isSharedAgentChannel(channel, agent, this.userId);return {...channel,agentIds: agentIdsOf.get(channel.id) ?? [],- sharedAgent,- // Its visitor page (`/a/<handle>`) is where the caller can see this Agent; it has no other.- sharedAgentHandle: sharedAgent ? (shareSlug ?? shareId) : null,+ ...sharedAgentFields(channel, agent, this.userId, shareSlug ?? shareId),canDelete: hasRole(role, 'admin'),hidden,joined: true,diff --git a/packages/database/src/repositories/channel/opening.ts b/packages/database/src/repositories/channel/opening.tsindex 88aa7a23bcb..99e0e1bdc6b 100644--- a/packages/database/src/repositories/channel/opening.ts+++ b/packages/database/src/repositories/channel/opening.ts@@ -1,4 +1,4 @@-import type { ChannelContextMessage } from '@lobechat/types';+import type { ChannelContextMessage, ChannelSharedAgentAccess } from '@lobechat/types';import { and, desc, eq, gte, inArray, isNull, lt, ne } from 'drizzle-orm';import pMap from 'p-map';@@ -16,6 +16,7 @@ import {import type { LobeChatDatabase, Transaction } from '../../type';import { agentTitleSql } from '../../utils/inboxAgent';import { notTrashed } from '../../utils/softDelete';+import { channelReplyShare } from './agent';import { appendMessage } from './delivery';import { readManifestMessages } from './manifest';import type { OpeningFacts, OpeningLayout } from './openingLayout';@@ -90,6 +91,11 @@ export interface ChannelOpeningCandidate {recent: ChannelContextMessage[];request: ChannelContextMessage;requesterUserId: string;+ /**+ * Set when the Agent is another person's, reached through its share: the reply opens only once+ * the share admits the request, so a refused one fails where it was asked, with no acknowledgement.+ */+ share?: ChannelSharedAgentAccess;/*** Open Threads started before the request, nearest first, that the reply may continue in.* Empty when it cannot move: already in a Thread, or asked together with other Agents.@@ -222,7 +228,7 @@ export const findOpeningCandidate = async (.where(eq(channelThreads.id, job.threadId)): [],db- .select({ workspaceId: channels.workspaceId })+ .select({ agentId: channels.agentId, workspaceId: channels.workspaceId }).from(channels).where(eq(channels.id, channelId)),]);@@ -255,6 +261,7 @@ export const findOpeningCandidate = async (recent: messages.filter((message) => message.id !== job.messageId),request: requestMessage,requesterUserId: requester.userId,+ share: await channelReplyShare(db, channel, row.agentId, requester.userId),// Agents asked together share one new Thread under the request instead.threads:job.threadId || coAddressed.lengthdiff --git a/packages/database/src/repositories/channel/send.ts b/packages/database/src/repositories/channel/send.tsindex 1e334b7b84a..89edcde5319 100644--- a/packages/database/src/repositories/channel/send.ts+++ b/packages/database/src/repositories/channel/send.ts@@ -21,7 +21,6 @@ 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';@@ -200,23 +199,13 @@ export const sendMessage = async (peerOf(channel, member.userId)!,);- 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!,- });- }- }+ // Another person's shared Agent runs as its owner, who cannot read the sender's files. The test+ // is the one 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.+ // The share's limits (prompt length, messages per visitor, monthly spend) never refuse the send:+ // the reply fails with the limit's type when dispatched (`ChannelCoordinator.shareGate`).+ if (channel.agentId && fileIds.length && (await sharedAgentOwner(tx, channel, member.userId!)))+ throw new ChannelError('BAD_REQUEST', 'Attachments cannot be sent to a shared Agent');if (fileIds.length) {// A workspace's public files are its members'. An external contact talking in it attachesdiff --git a/packages/database/src/repositories/channel/shareLimits.ts b/packages/database/src/repositories/channel/shareLimits.tsdeleted file mode 100644index f9971048b3b..00000000000--- a/packages/database/src/repositories/channel/shareLimits.ts+++ /dev/null@@ -1,55 +0,0 @@-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/view.ts b/packages/database/src/repositories/channel/view.tsindex 2766a50c7d3..0784ea88eef 100644--- a/packages/database/src/repositories/channel/view.ts+++ b/packages/database/src/repositories/channel/view.ts@@ -4,8 +4,8 @@ import {channelMessageEditedAt,channelMessageReceipt,channelMessageVia,- contactCardOf,type ChatMessageError,+ contactCardOf,defaultChannelAgentDirectory,type LobeAgentAgencyConfig,resolveAgentAgencyConfig,@@ -313,7 +313,9 @@ const redactSharedRunError = <sharedRun,...job}: Job) => {- if (!sharedRun || job.errorMessage === null) return job;+ // A failure that records only its type is redacted too: the type alone can name the owner's+ // provider or budget (`InsufficientBudgetForModel`), which a visitor must not learn.+ if (!sharedRun || (job.errorMessage === null && job.errorType === null)) return job;const safe = sanitizeVisitorError({message: job.errorMessage,type: job.errorType ?? undefined,diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.tsindex f761efb50b7..08810f00ac6 100644--- a/packages/locales/src/default/channel.ts+++ b/packages/locales/src/default/channel.ts@@ -11,10 +11,17 @@ export default {"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.errorSharePromptTooLong':+ 'This message is longer than a shared Agent accepts. Shorten it and send it again.','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.',+ 'shareRefusal.addOwner': 'Add contact',+ 'shareRefusal.added': 'Added as a contact',+ 'shareRefusal.alreadyContact': 'Already your contact',+ 'shareRefusal.ownerCaption': 'Creator of this Agent',+ 'shareRefusal.requestSent': 'Request sent','sort.by': 'Sort by','sort.by.createdAt': 'Date created','sort.by.title': 'Name',diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex 15df7bf4be2..9a6ba3aeaee 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -3,7 +3,7 @@ import {LocalExecutionHeterogeneousAgentTypeSchema,REMOTE_HETEROGENEOUS_AGENT_CONFIGS,} from './agent/heterogeneousAgent';-import type { ContactCard, ContactCardType } from './contact';+import type { ContactCard, ContactCardType, ContactUserProfile } from './contact';import { getWorkingDirEffectivePath } from './device';import type { BotWakeKind } from './signal';import type { ExternalWorkSummaryItem } from './work';@@ -956,6 +956,11 @@ export interface ChannelDetail {*/readOnly?: boolean;rootMessage: ChannelPublicMessage | null;+ /**+ * The person who owns the shared Agent of a `sharedAgent` conversation: the contact card a+ * refused reply offers the visitor. Null or absent otherwise.+ */+ sharedAgentOwner?: ContactUserProfile | null;threads: ChannelPublicThread[];}diff --git a/packages/types/src/fetch.ts b/packages/types/src/fetch.tsindex 1e1c103db49..a4027df2e5e 100644--- a/packages/types/src/fetch.ts+++ b/packages/types/src/fetch.ts@@ -12,6 +12,7 @@ export const ChatErrorType = {WorkspaceSubscriptionInactive: 'WorkspaceSubscriptionInactive', // Workspace's paid subscription has lapsed — view-only for non-primary members; spend blocked until renewedShareMessageLimitExceeded: 'ShareMessageLimitExceeded', // Visitor hit shareConfig.maxMessagesPerVisitor on this shared agentShareSpendLimitExceeded: 'ShareSpendLimitExceeded', // Shared agent reached shareConfig.monthlySpendLimit for the current month — recovers on the next reset+ SharePromptTooLong: 'SharePromptTooLong', // Visitor's message to a shared agent is longer than SHARE_VISITOR_PROMPT_MAX_LENGTHShareHeterogeneousAgentUnsupported: 'ShareHeterogeneousAgentUnsupported', // This agent configuration is not supported for shared visitorsShareHeteroDeviceUnavailable: 'ShareHeteroDeviceUnavailable', // The shared local CLI agent's device is offline or not set — visitor can retry laterAgentShareProviderNotSupported: 'AgentShareProviderNotSupported', // This shared agent uses a provider that is not supported for shared visitorsdiff --git a/src/features/Channels/ChannelConversation.tsx b/src/features/Channels/ChannelConversation.tsxindex cb3402810d8..a79555bd499 100644--- a/src/features/Channels/ChannelConversation.tsx+++ b/src/features/Channels/ChannelConversation.tsx@@ -31,6 +31,7 @@ import { ReadOnlyNotice } from './ReadOnlyNotice';import { ReplyActivity } from './ReplyActivity';import { ReplyFailureRow } from './ReplyFailure';import type { ReplyTopic } from './ReplyTopicPanel';+import { withoutShareRefusals } from './shareRefusal';import { styles } from './styles';import type { ChannelThreadDraft } from './threadDraft';import { useChannelEvents } from './useChannelEvents';@@ -147,7 +148,7 @@ const Timeline = ({): [];const failures = replyFailurePlacement(- detail?.jobs ?? [],+ detail ? withoutShareRefusals(detail, detail.jobs ?? []) : [],new Set([...timeline.flatMap((item) => (item.kind === 'message' ? [item.message.id] : [])),...(detail?.rootMessage ? [detail.rootMessage.id] : []),@@ -227,7 +228,9 @@ const Timeline = ({highlighted={highlighted === detail.rootMessage.id}root={detail.rootMessage}onReply={- channelArchived || readOnly || thread?.status === 'archived' ? undefined : selectReply+ channelArchived || readOnly || thread?.status === 'archived'+ ? undefined+ : selectReply}/>{failureRows(detail.rootMessage.id)}diff --git a/src/features/Channels/ChannelMessage.tsx b/src/features/Channels/ChannelMessage.tsxindex 45dfad86c1c..19c041612b9 100644--- a/src/features/Channels/ChannelMessage.tsx+++ b/src/features/Channels/ChannelMessage.tsx@@ -44,6 +44,8 @@ import { ReplyFailureCard } from './ReplyFailure';import { showsReplyQuote } from './replyQuote';import type { ReplyTopic } from './ReplyTopicPanel';import { ReplyWorks } from './ReplyWorks';+import { shareRefusalOf } from './shareRefusal';+import { ShareRefusalNotice } from './ShareRefusalNotice';import { styles } from './styles';import type { ChannelThreadDraft } from './threadDraft';import { ThreadPreviewCard } from './ThreadPreviewCard';@@ -141,6 +143,7 @@ export const ChannelMessage = ({attachments: detail.attachments.filter((file) => message.fileIds.includes(file.id)),});const isRequest = message.author.type === 'user' && !isRoot;+ const shareRefusal = isRequest && !delivery ? shareRefusalOf(detail, message.id) : undefined;const agentAuthorId = message.author.type === 'agent' ? message.author.id : null;const agentMember = agentAuthorId? detail.members.find((member) => member.agentId === agentAuthorId)@@ -232,7 +235,12 @@ export const ChannelMessage = ({title: message.author.name || t('deletedMember'),}}belowMessage={- delivery ?? (isRequest ? <MessageRoutingStatus message={message} /> : undefined)+ delivery ??+ (shareRefusal ? (+ <ShareRefusalNotice {...shareRefusal} />+ ) : isRequest ? (+ <MessageRoutingStatus message={message} />+ ) : undefined)}customAvatarRender={(_, avatar) => (<Flexbox {...stylex.props(styles.messageAvatar)}>diff --git a/src/features/Channels/MessageReceipts.tsx b/src/features/Channels/MessageReceipts.tsxindex b37e3c7340e..2505d3926a0 100644--- a/src/features/Channels/MessageReceipts.tsx+++ b/src/features/Channels/MessageReceipts.tsx@@ -21,6 +21,7 @@ const RECEIPT_ERROR_KEYS = {[ChatErrorType.ShareHeteroDeviceUnavailable]: 'receipt.errorShareHeteroDevice',[ChatErrorType.ShareHeterogeneousAgentUnsupported]: 'receipt.errorShareHeteroUnsupported',[ChatErrorType.ShareMessageLimitExceeded]: 'receipt.errorShareMessageLimit',+ [ChatErrorType.SharePromptTooLong]: 'receipt.errorSharePromptTooLong',[ChatErrorType.ShareSpendLimitExceeded]: 'receipt.errorShareSpendLimit',} as const;diff --git a/src/features/Channels/ShareRefusalNotice.tsx b/src/features/Channels/ShareRefusalNotice.tsxnew file mode 100644index 00000000000..a61ed090301--- /dev/null+++ b/src/features/Channels/ShareRefusalNotice.tsx@@ -0,0 +1,119 @@+import type { ContactUserProfile } from '@lobechat/types';+import { Button, Flexbox, Icon, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { CircleAlert, UserPlus } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import UserAvatar from '@/components/UserAvatar';+import { contactService } from '@/services/contact';++import { receiptErrorKey } from './MessageReceipts';+import type { ContactRequestOutcome } from './shareRefusal';+import { contactRequestOutcome } from './shareRefusal';+import { statusStyles, toneStyles } from './styles';++const styles = stylex.create({+ // Grows with a long name instead of cutting it short; the conversation width still caps it.+ card: {+ width: 'fit-content',+ minWidth: 280,+ maxWidth: '100%',+ paddingBlock: 10,+ paddingInline: 12,+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: 8,+ backgroundColor: cssVar.colorBgContainer,+ },+ identity: { flex: '1', minWidth: 0 },+ name: { fontWeight: 500 },+});++const OUTCOME_KEYS = {+ added: 'shareRefusal.added',+ alreadyContact: 'shareRefusal.alreadyContact',+ requestSent: 'shareRefusal.requestSent',+} as const satisfies Record<ContactRequestOutcome, string>;++/** The shared Agent's creator as a contact card the visitor can add, to ask them for more. */+function OwnerContactCard({ owner }: { owner: ContactUserProfile }) {+ const { t } = useTranslation('channel');+ const [sending, setSending] = useState(false);+ const [outcome, setOutcome] = useState<ContactRequestOutcome>();+ const [error, setError] = useState<unknown>();+ const name = owner.fullName || owner.username;++ const addOwner = async () => {+ setSending(true);+ setError(undefined);+ try {+ setOutcome(contactRequestOutcome({ result: await contactService.sendRequest(owner.id) }));+ } catch (cause) {+ const settled = contactRequestOutcome({ error: cause });+ if (settled) setOutcome(settled);+ else {+ console.error('Failed to ask the shared Agent creator to be a contact', cause);+ setError(cause);+ }+ } finally {+ setSending(false);+ }+ };++ return (+ <Flexbox gap={8} {...stylex.props(styles.card)}>+ <Flexbox horizontal align="center" gap={10}>+ <UserAvatar avatar={owner.avatar} name={name} shape="circle" size={36} />+ <Flexbox {...stylex.props(styles.identity)}>+ <Text ellipsis {...stylex.props(styles.name)}>+ {name}+ </Text>+ <Text ellipsis fontSize={12} type="secondary">+ {owner.username+ ? `${t('shareRefusal.ownerCaption')} · @${owner.username}`+ : t('shareRefusal.ownerCaption')}+ </Text>+ </Flexbox>+ {outcome ? (+ <Text fontSize={12} type="secondary">+ {t(OUTCOME_KEYS[outcome])}+ </Text>+ ) : (+ <Button icon={UserPlus} loading={sending} size="small" onClick={() => void addOwner()}>+ {t('shareRefusal.addOwner')}+ </Button>+ )}+ </Flexbox>+ {error !== undefined && <AsyncError error={error} variant="inline" />}+ </Flexbox>+ );+}++/**+ * Below a visitor's message whose reply a shared Agent's limit refused: why, and the creator's+ * contact card when the limit is theirs to raise. There is no retry; the limit still holds.+ */+export function ShareRefusalNotice({+ errorType,+ owner,+}: {+ errorType: string;+ owner?: ContactUserProfile;+}) {+ const { t } = useTranslation('channel');+ const reasonKey = receiptErrorKey(errorType);++ return (+ <Flexbox gap={6} {...stylex.props(statusStyles.receipts)}>+ <span {...stylex.props(statusStyles.state, toneStyles.error)}>+ <Icon icon={CircleAlert} size={12} />+ {reasonKey ? t(reasonKey) : t('receipt.errorUnavailable')}+ </span>+ {owner && <OwnerContactCard owner={owner} />}+ </Flexbox>+ );+}diff --git a/src/features/Channels/shareRefusal.test.ts b/src/features/Channels/shareRefusal.test.tsnew file mode 100644index 00000000000..9dcb1ee18b6--- /dev/null+++ b/src/features/Channels/shareRefusal.test.ts@@ -0,0 +1,102 @@+import { ChatErrorType } from '@lobechat/types';+import { TRPCClientError } from '@trpc/client';+import { describe, expect, it } from 'vitest';++import { contactRequestOutcome, shareRefusalOf, withoutShareRefusals } from './shareRefusal';++const owner = { avatar: null, fullName: 'Ada', id: 'owner', username: 'ada' };++const detail = (+ job: { errorType: string | null; status: string },+ sharedAgentOwner: typeof owner | null = owner,+) =>+ ({+ jobs: [{ id: 'job', messageId: 'msg', ...job }],+ sharedAgentOwner,+ }) as never;++describe('shareRefusalOf', () => {+ // A visitor out of messages saw only a red dot, with the reason one click away and no way on.+ it('offers the owner as a contact when the limit is theirs', () => {+ expect(+ shareRefusalOf(+ detail({ errorType: ChatErrorType.ShareMessageLimitExceeded, status: 'failed' }),+ 'msg',+ ),+ ).toEqual({ errorType: ChatErrorType.ShareMessageLimitExceeded, owner });+ expect(+ shareRefusalOf(+ detail({ errorType: ChatErrorType.ShareSpendLimitExceeded, status: 'failed' }),+ 'msg',+ ),+ ).toEqual({ errorType: ChatErrorType.ShareSpendLimitExceeded, owner });+ });++ it('only explains a message that is too long, which the visitor fixes themselves', () => {+ expect(+ shareRefusalOf(+ detail({ errorType: ChatErrorType.SharePromptTooLong, status: 'failed' }),+ 'msg',+ ),+ ).toEqual({ errorType: ChatErrorType.SharePromptTooLong });+ });++ it('leaves other failures, other messages and other conversations to the failure mark', () => {+ expect(+ shareRefusalOf(detail({ errorType: 'AgentRuntimeError', status: 'failed' }), 'msg'),+ ).toBeUndefined();+ expect(+ shareRefusalOf(+ detail({ errorType: ChatErrorType.ShareMessageLimitExceeded, status: 'failed' }),+ 'other',+ ),+ ).toBeUndefined();+ expect(+ shareRefusalOf(+ detail({ errorType: ChatErrorType.ShareMessageLimitExceeded, status: 'failed' }, null),+ 'msg',+ ),+ ).toBeUndefined();+ });+});++describe('contactRequestOutcome', () => {+ it('reads an accepted or pending request', () => {+ expect(contactRequestOutcome({ result: { status: 'accepted' } })).toBe('added');+ expect(contactRequestOutcome({ result: { status: 'pending' } })).toBe('requestSent');+ });++ it('treats a conflict as already reaching the owner, and anything else as an error', () => {+ expect(+ contactRequestOutcome({+ error: new TRPCClientError('Already a contact', {+ result: { error: { data: { code: 'CONFLICT' } } },+ } as any),+ }),+ ).toBe('alreadyContact');+ expect(contactRequestOutcome({ error: new Error('network') })).toBeUndefined();+ });+});++describe('withoutShareRefusals', () => {+ const refused = {+ errorType: ChatErrorType.ShareMessageLimitExceeded,+ id: 'refused',+ status: 'failed',+ };+ const crashed = { errorType: 'AgentRuntimeError', id: 'crashed', status: 'failed' };++ // A refused reply read both below the visitor's message and again as a failure card.+ it("leaves a shared Agent's refusals to the notice below the request", () => {+ expect(withoutShareRefusals({ sharedAgentOwner: owner }, [refused, crashed])).toEqual([+ crashed,+ ]);+ });++ it('keeps every failure card in other conversations', () => {+ expect(withoutShareRefusals({ sharedAgentOwner: null }, [refused, crashed])).toEqual([+ refused,+ crashed,+ ]);+ });+});diff --git a/src/features/Channels/shareRefusal.ts b/src/features/Channels/shareRefusal.tsnew file mode 100644index 00000000000..77314f271d7--- /dev/null+++ b/src/features/Channels/shareRefusal.ts@@ -0,0 +1,62 @@+import type { ChannelDetail, ChannelPublicJob, ContactUserProfile } from '@lobechat/types';+import { ChatErrorType } from '@lobechat/types';+import { TRPCClientError } from '@trpc/client';++/**+ * The share refusals a visitor reads beside their message instead of behind a failure mark,+ * since the reply will never come; each names what the visitor can do next. Running out of+ * messages or of the share's monthly usage is the owner's limit, so the visitor may ask the+ * owner directly: as a contact, they can message them in their own conversation.+ */+const SHARE_REFUSALS: Record<string, { addOwner: boolean }> = {+ [ChatErrorType.ShareMessageLimitExceeded]: { addOwner: true },+ [ChatErrorType.SharePromptTooLong]: { addOwner: false },+ [ChatErrorType.ShareSpendLimitExceeded]: { addOwner: true },+};++export const isShareRefusal = (job: Pick<ChannelPublicJob, 'errorType' | 'status'>) =>+ job.status === 'failed' && !!job.errorType && Object.hasOwn(SHARE_REFUSALS, job.errorType);++/**+ * Replies a conversation shows as cards, without the share refusals its request explains below+ * itself (`ShareRefusalNotice`), so one refusal never reads twice.+ */+export const withoutShareRefusals = <Job extends Pick<ChannelPublicJob, 'errorType' | 'status'>>(+ detail: Pick<ChannelDetail, 'sharedAgentOwner'>,+ jobs: Job[],+) => (detail.sharedAgentOwner ? jobs.filter((job) => !isShareRefusal(job)) : jobs);++/**+ * The refusal of a message's reply in a conversation with another person's shared Agent, and+ * the owner whose contact card it offers. Undefined in any other conversation or when the reply+ * did not fail for a share limit.+ */+export const shareRefusalOf = (+ detail: Pick<ChannelDetail, 'jobs' | 'sharedAgentOwner'>,+ messageId: string,+): { errorType: string; owner?: ContactUserProfile } | undefined => {+ const owner = detail.sharedAgentOwner;+ if (!owner) return;+ const job = (detail.jobs ?? []).find(+ (item) => item.messageId === messageId && isShareRefusal(item),+ );+ if (!job?.errorType) return;+ return {+ errorType: job.errorType,+ ...(SHARE_REFUSALS[job.errorType].addOwner && { owner }),+ };+};++export type ContactRequestOutcome = 'added' | 'alreadyContact' | 'requestSent';++/**+ * What asking the owner to be a contact settled as. Undefined for a failure the visitor should+ * see as an error; a conflict means they already reach the owner (a contact or a colleague).+ */+export const contactRequestOutcome = (+ settled: { result: { status: 'accepted' | 'pending' } } | { error: unknown },+): ContactRequestOutcome | undefined => {+ if ('result' in settled) return settled.result.status === 'accepted' ? 'added' : 'requestSent';+ if (settled.error instanceof TRPCClientError && settled.error.data?.code === 'CONFLICT')+ return 'alreadyContact';+};diff --git a/src/services/contact.ts b/src/services/contact.tsnew file mode 100644index 00000000000..326d3e2a05f--- /dev/null+++ b/src/services/contact.ts@@ -0,0 +1,8 @@+import { lambdaClient } from '@/libs/trpc/client';++class ContactService {+ /** Asks a person to become a contact; accepts at once when they already asked. */+ sendRequest = (userId: string) => lambdaClient.contact.sendRequest.mutate({ userId });+}++export const contactService = new ContactService();