🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent-share): visitors approve humanIntervention tools (#20153)
YuTengjingde867719b297
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.tsindex 5beec551a78..c7a04e2a420 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts@@ -11,7 +11,7 @@ import {deriveAgentInterventionQueueDeduplicationId,} from '@/business/server/agent-run/agentInterventionIdentity';-import { aiAgentRouter } from '../aiAgent';+import { aiAgentRouter, dispatchClaimedAgentIntervention } from '../aiAgent';import { cleanupTestUser, createTestUser } from './integration/setup';const business = vi.hoisted(() => ({@@ -1058,6 +1058,77 @@ describe('aiAgentRouter — remote Human-in-the-loop', () => {expect(params.userInterventionConfig).toEqual({ allowList: [], approvalMode: 'manual' });});+ it("continues a share visitor's run under its share gate and the visitor's own mode", async () => {+ const sourceOperationId = 'operation-share-source';+ stateFor(sourceOperationId, {+ operationId: sourceOperationId,+ principal: { policy: { userIntervention: { approvalMode: 'manual' } } },+ status: 'waiting_for_human',+ });+ // The creator's own allow list must not leak into the visitor's run.+ await serverDB+ .insert(userSettings)+ .values({+ id: userId,+ tool: {+ humanIntervention: {+ allowList: ['lobe-local-system____runCommand'],+ approvalMode: 'allow-list',+ },+ },+ })+ .onConflictDoNothing();+ await insertPendingTool({+ batchId: 'batch-share-source',+ messageId: 'assistant-share',+ operationId: sourceOperationId,+ toolCallId: 'tool-share',+ });+ aiAgentService.execAgent.mockResolvedValueOnce(execution);+ const shareGate = {+ agentId: 'agent-runtime',+ shareConfig: {},+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ };++ await dispatchClaimedAgentIntervention(+ {+ claimId: 'claim-share',+ contractVersion: 2,+ handled: true,+ ownerUserId: userId,+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000045',+ runtimeAction: {+ agentId: 'agent-runtime',+ appContext: { topicId: 'topic-runtime' },+ content: '{"answer":"A"}',+ operationId: sourceOperationId,+ outcome: 'submitted',+ parentMessageId: 'assistant-share',+ toolCallId: 'tool-share',+ type: 'resume_tool_result',+ },+ state: 'claimed',+ } as any,+ {+ aiAgentService: aiAgentService as any,+ serverDB,+ shareGate: shareGate as any,+ userId: 'visitor-1',+ workspaceId: null,+ },+ );++ expect(aiAgentService.execAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ shareGate,+ trigger: 'agent_share',+ userInterventionConfig: { approvalMode: 'manual' },+ }),+ );+ });+it('keeps a continuation headless when the answered run was headless', async () => {const sourceOperationId = 'operation-headless-source';stateFor(sourceOperationId, {diff --git a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts b/apps/server/src/routers/lambda/__tests__/shareChat.test.tsindex 5e0e60011c9..875fbff7ac7 100644--- a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts+++ b/apps/server/src/routers/lambda/__tests__/shareChat.test.ts@@ -81,6 +81,7 @@ vi.mock('@/database/models/topic', () => ({}));const mockMessageCountByTopic = vi.fn();+const mockFindMessagePlugin = vi.fn();const mockMessageQuery = vi.fn();const mockMessageQueryForVisitor = vi.fn();vi.mock('@/database/models/message', async (importOriginal) => {@@ -94,6 +95,7 @@ vi.mock('@/database/models/message', async (importOriginal) => {MessageModel: vi.fn(function () {return {countByTopic: mockMessageCountByTopic,+ findMessagePlugin: mockFindMessagePlugin,query: mockMessageQuery,queryForVisitor: mockMessageQueryForVisitor,};@@ -182,11 +184,13 @@ vi.mock('@/config/db', () => ({const mockExecAgent = vi.fn();const mockInterruptTask = vi.fn();const mockSetQueuedMessages = vi.fn();+const mockStopPendingApproval = vi.fn();const AiAgentServiceMock = vi.fn(function () {return {execAgent: mockExecAgent,interruptTask: mockInterruptTask,setQueuedMessages: mockSetQueuedMessages,+ stopPendingApproval: mockStopPendingApproval,};});vi.mock('@/server/services/aiAgent', () => ({@@ -216,6 +220,20 @@ vi.mock('@/libs/trpc/utils/internalJwt', () => ({signUserJWT: (...args: any[]) => mockSignUserJWT(...args),}));+const mockResolveBySource = vi.fn();+vi.mock('@/business/server/agent-run/agentInterventionReview', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ resolveAgentInterventionBySource: (...args: any[]) => mockResolveBySource(...args),+}));++const mockDispatchClaimed = vi.fn();+const mockBridgeLegacyResume = vi.fn();+vi.mock('../aiAgent', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ bridgeLegacyResumeToSourceIntervention: (...args: any[]) => mockBridgeLegacyResume(...args),+ dispatchClaimedAgentIntervention: (...args: any[]) => mockDispatchClaimed(...args),+}));+const { shareChatRouter } = await import('../shareChat');const VISITOR = 'visitor-1';@@ -279,6 +297,11 @@ describe('shareChatRouter', () => {mockGetFileAccessUrl.mockResolvedValue('https://s3/get');mockGetFileMetadata.mockResolvedValue({ contentLength: 10 });mockDeleteStoredFile.mockResolvedValue(undefined);+ mockResolveBySource.mockResolvedValue({ handled: false });+ mockDispatchClaimed.mockResolvedValue({ status: 'resolving' });+ mockBridgeLegacyResume.mockResolvedValue(undefined);+ mockFindMessagePlugin.mockResolvedValue(undefined);+ mockStopPendingApproval.mockResolvedValue({ operationId: 'op-1', success: true });});describe('execAgent', () => {@@ -547,7 +570,7 @@ describe('shareChatRouter', () => {});});- it('never sets interactiveStart, so concurrent visitor sends contend on the real runningOperation liveness instead of only the short reservation', async () => {+ it('never sets interactiveStart for a new send, so concurrent visitor sends contend on the real runningOperation liveness instead of only the short reservation', async () => {// Regression for Codex P1 (`shareChat.ts:186`): `interactiveStart:// true` makes `TopicModel.tryReserveTaskCallback` skip its `runningOperation`// liveness check entirely (`ignoreRunningOperation`) and contend only on the@@ -569,6 +592,203 @@ describe('shareChatRouter', () => {});});+ describe('intervention approval', () => {+ const shareVisitor = { agentId: share.agentId, ownerUserId: OWNER, topicId: 'tpc_visitor' };+ const resumeApproval = {+ decision: 'approved' as const,+ parentMessageId: 'msg-tool',+ toolCallId: 'call-1',+ };+ const source = {+ action: { scope: 'once' as const, type: 'approve_tool' as const },+ batchId: 'batch-1',+ operationId: 'op-parked',+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000001',+ targets: [{ toolCallId: 'call-1', toolMessageId: 'msg-tool' }],+ };++ 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);+ const caller = await createCaller();++ await caller.execAgent({+ parentMessageId: 'msg-tool',+ prompt: '',+ resumeApproval,+ shareId: 'share-1',+ topicId: 'tpc_visitor',+ userInterventionConfig: { approvalMode: 'allow-list', allowList: ['lobe-web-browsing'] },+ });++ expect(mockMessageCountByTopic).not.toHaveBeenCalled();+ expect(mockBridgeLegacyResume).toHaveBeenCalledWith(+ expect.objectContaining({ resumeApproval, shareVisitor }),+ expect.objectContaining({ shareGate: expect.any(Object), userId: VISITOR }),+ );+ expect(mockExecAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ // The parked operation still holds the topic; the exactly-once+ // approval claim, not the liveness check, serializes resumes.+ interactiveStart: true,+ parentMessageId: 'msg-tool',+ resume: true,+ resumeApproval,+ shareGate: expect.objectContaining({ visitorUserId: VISITOR }),+ userInterventionConfig: {+ allowList: ['lobe-web-browsing'],+ approvalMode: 'allow-list',+ },+ }),+ );+ });++ it('returns the durable claim result instead of starting a legacy resume', async () => {+ mockBridgeLegacyResume.mockResolvedValue({ operationId: 'op-continued', success: true });+ const caller = await createCaller();++ await expect(+ caller.execAgent({+ parentMessageId: 'msg-tool',+ prompt: '',+ resumeApproval,+ shareId: 'share-1',+ topicId: 'tpc_visitor',+ }),+ ).resolves.toMatchObject({ operationId: 'op-continued' });+ expect(mockExecAgent).not.toHaveBeenCalled();+ });++ it('rejects a resume outside an existing visitor topic', async () => {+ const caller = await createCaller();++ await expect(+ caller.execAgent({+ parentMessageId: 'msg-tool',+ prompt: '',+ resumeApproval,+ shareId: 'share-1',+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mockExecAgent).not.toHaveBeenCalled();+ });++ it("resolves a source intervention as the visitor, scoped to the visitor's topic", async () => {+ mockResolveBySource.mockResolvedValue({+ claimId: 'claim-1',+ handled: true,+ ownerUserId: OWNER,+ state: 'claimed',+ });+ mockDispatchClaimed.mockResolvedValue({+ execution: { operationId: 'op-continued', success: true },+ status: 'resolving',+ });+ const caller = await createCaller();++ await expect(+ caller.resolveInterventionBySource({+ ...source,+ shareId: 'share-1',+ topicId: 'tpc_visitor',+ }),+ ).resolves.toMatchObject({ state: 'claimed', success: true });+ expect(mockResolveBySource).toHaveBeenCalledWith(+ expect.objectContaining({ ...source, actorUserId: VISITOR, shareVisitor }),+ );+ expect(mockDispatchClaimed).toHaveBeenCalledWith(+ expect.objectContaining({ claimId: 'claim-1' }),+ expect.objectContaining({+ shareGate: expect.objectContaining({ visitorUserId: VISITOR }),+ userId: VISITOR,+ }),+ );+ });++ it("refuses to remember an approval into the creator's allow list", async () => {+ const caller = await createCaller();++ await expect(+ caller.resolveInterventionBySource({+ ...source,+ action: { scope: 'remember', type: 'approve_tool' },+ shareId: 'share-1',+ topicId: 'tpc_visitor',+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mockResolveBySource).not.toHaveBeenCalled();+ });++ it("fails closed on a topic that is not the visitor's own", async () => {+ mockFindById.mockResolvedValue({ ...visitorTopic, senderId: 'someone-else' });+ const caller = await createCaller();++ await expect(+ caller.resolveInterventionBySource({+ ...source,+ shareId: 'share-1',+ topicId: 'tpc_visitor',+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockResolveBySource).not.toHaveBeenCalled();+ });++ it('reports an unavailable durable store so the client falls back to a resume', async () => {+ const caller = await createCaller();++ await expect(+ caller.resolveInterventionBySource({+ ...source,+ shareId: 'share-1',+ topicId: 'tpc_visitor',+ }),+ ).resolves.toMatchObject({ status: 'unavailable', success: false });+ expect(mockDispatchClaimed).not.toHaveBeenCalled();+ });++ it('stops a parked run through the creator-scoped service without a durable store', async () => {+ const caller = await createCaller();+ const input = {+ batchId: 'batch-1',+ operationId: 'op-parked',+ toolMessageIds: ['msg-tool'],+ topicId: 'tpc_visitor',+ };++ await caller.stopPendingApproval({ ...input, shareId: 'share-1' });++ expect(mockStopPendingApproval).toHaveBeenCalledWith(input);+ });++ it('stops a durable batch through the source claim as the visitor', async () => {+ mockFindMessagePlugin.mockResolvedValue({+ intervention: { batchId: 'batch-1', operationId: 'op-parked' },+ toolCallId: 'call-1',+ });+ mockResolveBySource.mockResolvedValue({ handled: true, state: 'claimed' });+ const caller = await createCaller();++ await caller.stopPendingApproval({+ batchId: 'batch-1',+ operationId: 'op-parked',+ shareId: 'share-1',+ toolMessageIds: ['msg-tool'],+ topicId: 'tpc_visitor',+ });++ expect(mockResolveBySource).toHaveBeenCalledWith(+ expect.objectContaining({+ action: { scope: 'operation', type: 'stop' },+ actorUserId: VISITOR,+ shareVisitor,+ targets: [{ toolCallId: 'call-1', toolMessageId: 'msg-tool' }],+ }),+ );+ expect(mockDispatchClaimed).toHaveBeenCalled();+ expect(mockStopPendingApproval).not.toHaveBeenCalled();+ });+ });+describe('createUploadUrl', () => {const prefix = `files/${OWNER}/agent-share/share-1/`;const MB = 1024 * 1024;diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 6e92782cdc4..5cc4ba8bbcb 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -38,6 +38,7 @@ import {import {type AgentInterventionReviewStatus,type AgentInterventionRuntimeAction,+ type AgentInterventionShareVisitorScope,type AgentInterventionSourceAction,getAgentInterventionReview,getAgentInterventionReviewBySource,@@ -93,6 +94,7 @@ import {import { AgentRuntimeService } from '@/server/services/agentRuntime';import { MAX_CLIENT_OPERATION_SNAPSHOT } from '@/server/services/agentRuntime/foregroundOperation';import { AiAgentService } from '@/server/services/aiAgent';+import type { AgentShareGate } from '@/server/services/aiAgent/shareGate';import { AiChatService } from '@/server/services/aiChat';import { getFileProxyUrl } from '@/server/services/file';import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';@@ -108,9 +110,21 @@ type ClaimedAgentInterventionResolution = Extract<{ state: 'claimed' }>;-interface AgentInterventionDispatchContext {+export interface AgentInterventionDispatchContext {+ /**+ * Creator-scoped service for a share run, caller-scoped otherwise. The+ * continuation always executes as the run owner.+ */aiAgentService: AiAgentService;serverDB: LobeChatDatabase;+ /**+ * Present when a share VISITOR resolved an intervention on their own share+ * run (`shareChat.resolveInterventionBySource`). Rebuilt from the live share row by+ * the caller — never from the parked run's state — so the continuation is+ * gated by the share's CURRENT config exactly like a fresh visitor turn.+ */+ shareGate?: AgentShareGate;+ /** The resolving actor: the owner/member, or the share visitor. */userId: string;workspaceId?: string | null;}@@ -483,6 +497,11 @@ const repairRuntimeActionContinuationAnchor = async (* The owner's persisted allow list is merged in either way: an "Approve, and* don't ask again" answer writes the tool key there before this dispatch, and* the snapshot in the parked run predates it.+ *+ * A share visitor's continuation uses neither owner fallback: the parked run+ * carries the VISITOR's approval mode, a visitor can never "remember" into+ * the owner's allow list, and the owner's own preferences must not decide+ * what runs unattended in someone else's conversation.*/const resolveContinuationUserInterventionConfig = async (resolution: ClaimedAgentInterventionResolution,@@ -503,6 +522,7 @@ const resolveContinuationUserInterventionConfig = async (const persistedAllowList = intervention?.allowList ?? [];const inherited = sourceState ? selectUserInterventionConfig(sourceState) : undefined;+ if (ctx.shareGate) return inherited ?? { approvalMode: 'manual' };if (inherited) {const inheritedAllowList = inherited.allowList ?? [];const remembered = persistedAllowList.filter((key) => !inheritedAllowList.includes(key));@@ -523,7 +543,7 @@ const resolveContinuationUserInterventionConfig = async (* bridge. Both paths arrive here only after Cloud has won the same durable* first-winner claim.*/-const dispatchClaimedAgentIntervention = async (+export const dispatchClaimedAgentIntervention = async (resolution: ClaimedAgentInterventionResolution,ctx: AgentInterventionDispatchContext,/**@@ -584,7 +604,7 @@ const dispatchClaimedAgentIntervention = async (* run's trigger. Without an explicit trigger every LLM call in the* continuation lands in route attempt logs with an unknown source.*/- const continuationTrigger = RequestTrigger.Chat;+ const continuationTrigger = ctx.shareGate ? RequestTrigger.AgentShare : RequestTrigger.Chat;const continuation = continuationRuntimeAction(runtimeAction);const userInterventionConfig = continuation? await resolveContinuationUserInterventionConfig(resolution, continuation.operationId, ctx)@@ -632,6 +652,7 @@ const dispatchClaimedAgentIntervention = async (pluginState: customResult.pluginState,toolCallId: runtimeAction.toolCallId,},+ shareGate: ctx.shareGate,topicStartReservationId: deterministicContinuationOperationId,trigger: continuationTrigger,userInterventionConfig,@@ -663,6 +684,7 @@ const dispatchClaimedAgentIntervention = async (...(runtimeAction.decisions.length === 1? { resumeApproval: singleDecision }: { resumeApprovals: runtimeAction.decisions }),+ shareGate: ctx.shareGate,topicStartReservationId: deterministicContinuationOperationId,trigger: continuationTrigger,userInterventionConfig,@@ -689,6 +711,7 @@ const dispatchClaimedAgentIntervention = async (rejectionReason: runtimeAction.rejectionReason,toolCallId: runtimeAction.toolCallId,},+ shareGate: ctx.shareGate,topicStartReservationId: deterministicContinuationOperationId,trigger: continuationTrigger,userInterventionConfig,@@ -1037,6 +1060,113 @@ const LlmExecutorSchema = z.object({providers: z.array(z.string()).max(256),});+/** One human decision on a pending `role='tool'` message. */+export const ResumeApprovalDecisionSchema = z.object({+ decision: z.enum(['approved', 'rejected', 'rejected_continue']),+ /** ID of the pending `role='tool'` message this decision targets. */+ parentMessageId: z.string(),+ /** Optional user-supplied rejection reason (only meaningful for rejected variants). */+ rejectionReason: z.string().optional(),+ /** tool_call_id of the pending tool call being approved/rejected. */+ toolCallId: z.string(),+});++/** A human-provided result for a pending `humanIntervention: 'always'` tool. */+export const ResumeToolResultSchema = z.object({+ /** The human-provided tool result (the answer text). */+ content: z.string(),+ /** ID of the pending `role='tool'` message this result targets. */+ parentMessageId: z.string(),+ /** Optional plugin state to persist on the tool message. */+ pluginState: z.record(z.string(), z.unknown()).optional(),+ /** Whether the form was submitted or explicitly skipped. */+ outcome: z.enum(['submitted', 'skipped']).optional().default('submitted'),+ /** Optional skip reason, persisted only when outcome is skipped. */+ rejectionReason: z.string().optional(),+ /** tool_call_id of the pending tool call being answered. */+ toolCallId: z.string(),+});++/**+ * Cross-field rules for an intervention resume payload, shared by every+ * execAgent entry point that accepts one (owner and share visitor).+ */+export const validateResumePayload = (+ data: {+ parentMessageId?: string;+ resumeApproval?: z.infer<typeof ResumeApprovalDecisionSchema>;+ resumeApprovals?: z.infer<typeof ResumeApprovalDecisionSchema>[];+ resumeToolResult?: z.infer<typeof ResumeToolResultSchema>;+ },+ ctx: z.RefinementCtx,+) => {+ const resumePayloadCount = [+ data.resumeApproval,+ data.resumeApprovals,+ data.resumeToolResult,+ ].filter(Boolean).length;+ if (resumePayloadCount > 1) {+ ctx.addIssue({+ code: 'custom',+ message: 'Only one of resumeApproval, resumeApprovals, or resumeToolResult is allowed',+ path: ['resumeApproval'],+ });+ }++ if (resumePayloadCount > 0 && !data.parentMessageId) {+ ctx.addIssue({+ code: 'custom',+ message: 'parentMessageId is required for an intervention resume',+ path: ['parentMessageId'],+ });+ }++ if (+ data.resumeApproval &&+ data.parentMessageId &&+ data.resumeApproval.parentMessageId !== data.parentMessageId+ ) {+ ctx.addIssue({+ code: 'custom',+ message: 'resumeApproval must target parentMessageId',+ path: ['resumeApproval', 'parentMessageId'],+ });+ }+ if (+ data.resumeToolResult &&+ data.parentMessageId &&+ data.resumeToolResult.parentMessageId !== data.parentMessageId+ ) {+ ctx.addIssue({+ code: 'custom',+ message: 'resumeToolResult must target parentMessageId',+ path: ['resumeToolResult', 'parentMessageId'],+ });+ }++ if (data.resumeApprovals) {+ const messageIds = data.resumeApprovals.map(({ parentMessageId }) => parentMessageId);+ const toolCallIds = data.resumeApprovals.map(({ toolCallId }) => toolCallId);+ if (+ new Set(messageIds).size !== messageIds.length ||+ new Set(toolCallIds).size !== toolCallIds.length+ ) {+ ctx.addIssue({+ code: 'custom',+ message: 'resumeApprovals cannot contain duplicate targets',+ path: ['resumeApprovals'],+ });+ }+ if (data.parentMessageId && !messageIds.includes(data.parentMessageId)) {+ ctx.addIssue({+ code: 'custom',+ message: 'parentMessageId must be one of the resumeApprovals targets',+ path: ['parentMessageId'],+ });+ }+ }+};+const ExecAgentSchema = z.object({includeFinalState: z.boolean().optional(),@@ -1149,17 +1279,7 @@ const ExecAgentSchema = z* (`rejected`), or surfaces the rejection as user feedback so the LLM* can continue (`rejected_continue`).*/- resumeApproval: z- .object({- decision: z.enum(['approved', 'rejected', 'rejected_continue']),- /** ID of the pending `role='tool'` message this decision targets. */- parentMessageId: z.string(),- /** Optional user-supplied rejection reason (only meaningful for rejected variants). */- rejectionReason: z.string().optional(),- /** tool_call_id of the pending tool call being approved/rejected. */- toolCallId: z.string(),- })- .optional(),+ resumeApproval: ResumeApprovalDecisionSchema.optional(),/*** Batch form of `resumeApproval` — one entry per pending tool the user* resolved in a single action ("approve all" on a parallel tool batch).@@ -1171,20 +1291,7 @@ const ExecAgentSchema = z* empty rows, which forks the parent chain and shows the model blank* results. Mutually exclusive with `resumeApproval`.*/- resumeApprovals: z- .array(- z.object({- decision: z.enum(['approved', 'rejected', 'rejected_continue']),- /** ID of the pending `role='tool'` message this decision targets. */- parentMessageId: z.string(),- /** Optional user-supplied rejection reason (only meaningful for rejected variants). */- rejectionReason: z.string().optional(),- /** tool_call_id of the pending tool call being approved/rejected. */- toolCallId: z.string(),- }),- )- .min(1)- .optional(),+ resumeApprovals: z.array(ResumeApprovalDecisionSchema).min(1).optional(),/*** Resume a previous op paused on a `humanIntervention: 'always'` tool (e.g.* lobe-agent `askUserQuestion`). When set, the new op writes the@@ -1193,22 +1300,7 @@ const ExecAgentSchema = z* overwrites the answer with a fresh "pending" placeholder. Mutually* exclusive with `resumeApproval`.*/- resumeToolResult: z- .object({- /** The human-provided tool result (the answer text). */- content: z.string(),- /** ID of the pending `role='tool'` message this result targets. */- parentMessageId: z.string(),- /** Optional plugin state to persist on the tool message. */- pluginState: z.record(z.string(), z.unknown()).optional(),- /** Whether the form was submitted or explicitly skipped. */- outcome: z.enum(['submitted', 'skipped']).optional().default('submitted'),- /** Optional skip reason, persisted only when outcome is skipped. */- rejectionReason: z.string().optional(),- /** tool_call_id of the pending tool call being answered. */- toolCallId: z.string(),- })- .optional(),+ resumeToolResult: ResumeToolResultSchema.optional(),/*** Tool identifiers the user @-mentioned in this message. Enabled for this* run in addition to the agent's pinned plugins, so a mentioned tool that@@ -1255,73 +1347,175 @@ const ExecAgentSchema = z.refine((data) => data.agentId || data.slug, {message: 'Either agentId or slug must be provided',})- .superRefine((data, ctx) => {- const resumePayloadCount = [- data.resumeApproval,- data.resumeApprovals,- data.resumeToolResult,- ].filter(Boolean).length;- if (resumePayloadCount > 1) {- ctx.addIssue({- code: 'custom',- message: 'Only one of resumeApproval, resumeApprovals, or resumeToolResult is allowed',- path: ['resumeApproval'],- });- }+ .superRefine(validateResumePayload);- if (resumePayloadCount > 0 && !data.parentMessageId) {- ctx.addIssue({- code: 'custom',- message: 'parentMessageId is required for an intervention resume',- path: ['parentMessageId'],- });- }+type ExecAgentInput = z.infer<typeof ExecAgentSchema>;- if (- data.resumeApproval &&- data.parentMessageId &&- data.resumeApproval.parentMessageId !== data.parentMessageId- ) {- ctx.addIssue({- code: 'custom',- message: 'resumeApproval must target parentMessageId',- path: ['resumeApproval', 'parentMessageId'],- });- }- if (- data.resumeToolResult &&- data.parentMessageId &&- data.resumeToolResult.parentMessageId !== data.parentMessageId- ) {- ctx.addIssue({- code: 'custom',- message: 'resumeToolResult must target parentMessageId',- path: ['resumeToolResult', 'parentMessageId'],- });- }+/**+ * Cross-version bridge: older Web clients call execAgent directly with resume+ * payloads and know nothing about the v2 source endpoint. Recover the+ * authoritative operation/batch from the tool rows and claim the same generic+ * intervention before the legacy message CAS can run.+ *+ * Shared by the owner `execAgent` and the share-visitor `shareChat.execAgent`+ * resume paths; `shareVisitor` scopes the claim to the visitor's own share run.+ * Resolves `undefined` when no durable generic row exists (OSS, or a pre-v2+ * row), so the caller continues with the legacy message-row resume.+ */+export const bridgeLegacyResumeToSourceIntervention = async (+ params: {+ messageModel: MessageModel;+ parentMessageId?: string;+ resumeApproval?: ExecAgentInput['resumeApproval'];+ resumeApprovals?: ExecAgentInput['resumeApprovals'];+ resumeToolResult?: ExecAgentInput['resumeToolResult'];+ shareVisitor?: AgentInterventionShareVisitorScope;+ },+ ctx: AgentInterventionDispatchContext,+ /** Forwarded to {@link dispatchClaimedAgentIntervention}; see its `options`. */+ options: { acceptsMemberRuntimeEnd?: boolean } = {},+): Promise<ExecAgentResult | undefined> => {+ const {+ messageModel,+ parentMessageId,+ resumeApproval,+ resumeApprovals,+ resumeToolResult,+ shareVisitor,+ } = params;++ const legacyResumeTargets = [+ ...(resumeApprovals ?? []),+ ...(resumeApproval ? [resumeApproval] : []),+ ...(resumeToolResult+ ? [+ {+ decision: 'approved' as const,+ parentMessageId: resumeToolResult.parentMessageId,+ toolCallId: resumeToolResult.toolCallId,+ },+ ]+ : []),+ ];+ if (legacyResumeTargets.length > 0) {+ const plugins = await pMap(+ legacyResumeTargets,+ ({ parentMessageId }) => messageModel.findMessagePlugin(parentMessageId),+ { concurrency: 5 },+ );+ const firstIntervention = plugins[0]?.intervention;+ const hasGenericSource = Boolean(+ firstIntervention?.operationId &&+ firstIntervention.batchId &&+ plugins.every(+ (plugin) =>+ plugin?.intervention?.operationId === firstIntervention.operationId &&+ plugin?.intervention?.batchId === firstIntervention.batchId,+ ),+ );- if (data.resumeApprovals) {- const messageIds = data.resumeApprovals.map(({ parentMessageId }) => parentMessageId);- const toolCallIds = data.resumeApprovals.map(({ toolCallId }) => toolCallId);- if (- new Set(messageIds).size !== messageIds.length ||- new Set(toolCallIds).size !== toolCallIds.length+ if (hasGenericSource) {+ let sourceAction: AgentInterventionSourceAction | undefined;+ if (resumeToolResult) {+ if (resumeToolResult.outcome === 'skipped') {+ sourceAction = { type: 'skip_interaction' };+ } else {+ const pluginState = resumeToolResult.pluginState as+ | {+ askUserAnswers?: Record<string, unknown>;+ selectedAgentIds?: unknown;+ }+ | undefined;+ const answers = pluginState?.askUserAnswers;+ if (+ answers &&+ Object.keys(answers).length > 0 &&+ Object.values(answers).every(+ (answer) =>+ typeof answer === 'string' ||+ (Array.isArray(answer) && answer.every((item) => typeof item === 'string')),+ )+ ) {+ sourceAction = {+ result: answers as Record<string, string | string[]>,+ type: 'submit_answers',+ };+ } else if (+ plugins[0]?.identifier === 'lobe-web-onboarding' &&+ plugins[0]?.apiName === 'showAgentMarketplace' &&+ Array.isArray(pluginState?.selectedAgentIds) &&+ pluginState.selectedAgentIds.every((id) => typeof id === 'string')+ ) {+ sourceAction = {+ result: {+ kind: 'agent_marketplace',+ selectedTemplateIds: pluginState.selectedAgentIds as string[],+ },+ type: 'submit_custom',+ };+ }+ }+ } else if (legacyResumeTargets.every(({ decision }) => decision === 'approved')) {+ // The legacy resume envelope has neither staged edits nor remember+ // intent. Cloud therefore compares the durable revision with the+ // authoritative message arguments and rejects a pre-mutated old+ // edit as stale with a refresh-required conflict; it must never+ // reinterpret already-written client state as an atomic edit.+ // Old clients may also have changed their personal allow-list+ // before this call, which remains a rollout-only non-atomic edge.+ // Current Web sends both edits and remember through the source+ // endpoint before any side effect.+ sourceAction = { scope: 'once', type: 'approve_tool' };+ } else if (+ legacyResumeTargets.every(+ ({ decision }) => decision === 'rejected' || decision === 'rejected_continue',+ )) {- ctx.addIssue({- code: 'custom',- message: 'resumeApprovals cannot contain duplicate targets',- path: ['resumeApprovals'],- });+ const reasons = [+ ...new Set(+ legacyResumeTargets+ .map(({ rejectionReason }) => rejectionReason)+ .filter((reason): reason is string => Boolean(reason)),+ ),+ ];+ sourceAction = {+ ...(reasons.length === 1 && { reason: reasons[0] }),+ type: 'reject_continue',+ };}- if (data.parentMessageId && !messageIds.includes(data.parentMessageId)) {- ctx.addIssue({- code: 'custom',- message: 'parentMessageId must be one of the resumeApprovals targets',- path: ['parentMessageId'],- });++ if (!sourceAction) {+ throw new Error('Unsupported legacy intervention payload for a durable generic row');+ }++ const sourceResolution = await resolveAgentInterventionBySource({+ action: sourceAction,+ actorUserId: ctx.userId,+ batchId: firstIntervention!.batchId!,+ operationId: firstIntervention!.operationId!,+ resolutionRequestId: randomUUID(),+ targets: legacyResumeTargets.map(({ parentMessageId, toolCallId }) => ({+ toolCallId,+ toolMessageId: parentMessageId,+ })),+ ...(shareVisitor && { shareVisitor }),+ workspaceId: ctx.workspaceId ?? undefined,+ });+ if (sourceResolution.handled) {+ if (sourceResolution.state === 'already_resolved') {+ throw new HumanApprovalAlreadyResolvedError(parentMessageId ?? 'intervention');+ }+ const dispatch = await dispatchClaimedAgentIntervention(sourceResolution, ctx, options);+ if (!dispatch.execution) {+ throw new Error('Durable intervention resume did not create an operation');+ }+ return toClientExecAgentResult(dispatch.execution);}}- });+ }++ return undefined;+};/*** Schema for execGroupAgent - execute Supervisor Agent in Group chat@@ -2324,140 +2518,18 @@ export const aiAgentRouter = router({workspaceId: ctx.workspaceId,});- // Cross-version bridge: older Web clients call execAgent directly with- // resume payloads and know nothing about the v2 source endpoint. Recover- // the authoritative operation/batch from the tool rows and claim the- // same generic intervention before the legacy message CAS can run.- const legacyResumeTargets = [- ...(resumeApprovals ?? []),- ...(resumeApproval ? [resumeApproval] : []),- ...(resumeToolResult- ? [- {- decision: 'approved' as const,- parentMessageId: resumeToolResult.parentMessageId,- toolCallId: resumeToolResult.toolCallId,- },- ]- : []),- ];- if (legacyResumeTargets.length > 0) {- const plugins = await Promise.all(- legacyResumeTargets.map(({ parentMessageId }) =>- ctx.messageModel.findMessagePlugin(parentMessageId),- ),- );- const firstIntervention = plugins[0]?.intervention;- const hasGenericSource = Boolean(- firstIntervention?.operationId &&- firstIntervention.batchId &&- plugins.every(- (plugin) =>- plugin?.intervention?.operationId === firstIntervention.operationId &&- plugin?.intervention?.batchId === firstIntervention.batchId,- ),- );-- if (hasGenericSource) {- let sourceAction: AgentInterventionSourceAction | undefined;- if (resumeToolResult) {- if (resumeToolResult.outcome === 'skipped') {- sourceAction = { type: 'skip_interaction' };- } else {- const pluginState = resumeToolResult.pluginState as- | {- askUserAnswers?: Record<string, unknown>;- selectedAgentIds?: unknown;- }- | undefined;- const answers = pluginState?.askUserAnswers;- if (- answers &&- Object.keys(answers).length > 0 &&- Object.values(answers).every(- (answer) =>- typeof answer === 'string' ||- (Array.isArray(answer) && answer.every((item) => typeof item === 'string')),- )- ) {- sourceAction = {- result: answers as Record<string, string | string[]>,- type: 'submit_answers',- };- } else if (- plugins[0]?.identifier === 'lobe-web-onboarding' &&- plugins[0]?.apiName === 'showAgentMarketplace' &&- Array.isArray(pluginState?.selectedAgentIds) &&- pluginState.selectedAgentIds.every((id) => typeof id === 'string')- ) {- sourceAction = {- result: {- kind: 'agent_marketplace',- selectedTemplateIds: pluginState.selectedAgentIds as string[],- },- type: 'submit_custom',- };- }- }- } else if (legacyResumeTargets.every(({ decision }) => decision === 'approved')) {- // The legacy resume envelope has neither staged edits nor remember- // intent. Cloud therefore compares the durable revision with the- // authoritative message arguments and rejects a pre-mutated old- // edit as stale with a refresh-required conflict; it must never- // reinterpret already-written client state as an atomic edit.- // Old clients may also have changed their personal allow-list- // before this call, which remains a rollout-only non-atomic edge.- // Current Web sends both edits and remember through the source- // endpoint before any side effect.- sourceAction = { scope: 'once', type: 'approve_tool' };- } else if (- legacyResumeTargets.every(- ({ decision }) => decision === 'rejected' || decision === 'rejected_continue',- )- ) {- const reasons = [- ...new Set(- legacyResumeTargets- .map(({ rejectionReason }) => rejectionReason)- .filter((reason): reason is string => Boolean(reason)),- ),- ];- sourceAction = {- ...(reasons.length === 1 && { reason: reasons[0] }),- type: 'reject_continue',- };- }-- if (!sourceAction) {- throw new Error('Unsupported legacy intervention payload for a durable generic row');- }-- const sourceResolution = await resolveAgentInterventionBySource({- action: sourceAction,- actorUserId: ctx.userId,- batchId: firstIntervention!.batchId!,- operationId: firstIntervention!.operationId!,- resolutionRequestId: randomUUID(),- targets: legacyResumeTargets.map(({ parentMessageId, toolCallId }) => ({- toolCallId,- toolMessageId: parentMessageId,- })),- workspaceId: ctx.workspaceId ?? undefined,- });- if (sourceResolution.handled) {- if (sourceResolution.state === 'already_resolved') {- throw new HumanApprovalAlreadyResolvedError(parentMessageId ?? 'intervention');- }- const dispatch = await dispatchClaimedAgentIntervention(sourceResolution, ctx, {- acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),- });- if (!dispatch.execution) {- throw new Error('Durable intervention resume did not create an operation');- }- return toClientExecAgentResult(dispatch.execution);- }- }- }+ const bridged = await bridgeLegacyResumeToSourceIntervention(+ {+ messageModel: ctx.messageModel,+ parentMessageId,+ resumeApproval,+ resumeApprovals,+ resumeToolResult,+ },+ ctx,+ { acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures) },+ );+ if (bridged) return bridged;const result = await ctx.aiAgentService.execAgent({acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),diff --git a/apps/server/src/routers/lambda/shareChat.ts b/apps/server/src/routers/lambda/shareChat.tsindex cb446cbf713..4949519ea36 100644--- a/apps/server/src/routers/lambda/shareChat.ts+++ b/apps/server/src/routers/lambda/shareChat.ts@@ -1,3 +1,5 @@+import { randomUUID } from 'node:crypto';+import {AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,@@ -15,19 +17,26 @@ import {ChatErrorType,entityIdPattern,RequestTrigger,+ UserInterventionConfigSchema,} from '@lobechat/types';import { nanoid } from '@lobechat/utils';import { TRPCError } from '@trpc/server';import debug from 'debug';+import pMap from 'p-map';import { z } from 'zod';+import { resolveAgentInterventionBySource } from '@/business/server/agent-run/agentInterventionReview';import { checkAgentShareSpendAllowance } from '@/business/server/agent-share/spendGate';import { serverDBEnv } from '@/config/db';import { AgentShareModel } from '@/database/models/agentShare';import { DocumentModel } from '@/database/models/document';import { FileModel } from '@/database/models/file';import { FileUploadModel } from '@/database/models/fileUpload';-import { MessageModel, sanitizeVisitorError } from '@/database/models/message';+import {+ HumanApprovalAlreadyResolvedError,+ MessageModel,+ sanitizeVisitorError,+} from '@/database/models/message';import { TopicModel } from '@/database/models/topic';import { UserModel } from '@/database/models/user';import type { LobeChatDatabase } from '@/database/type';@@ -41,7 +50,18 @@ import { FileService } from '@/server/services/file';import { FileUploadService } from '@/server/services/fileUpload';import { reserveUpload } from '@/server/services/fileUploadReservation';+import { mapAgentInterventionTRPCError } from './_helpers/agentInterventionError';import { assertAgentShareVisitorEnabled } from './_helpers/agentShareFeatureGate';+import { toClientExecAgentResult } from './_helpers/groupMemberContinuationResult';+import { ResolveAgentInterventionBySourceSchema } from './_schema/agentIntervention';+import {+ type AgentInterventionDispatchContext,+ bridgeLegacyResumeToSourceIntervention,+ dispatchClaimedAgentIntervention,+ ResumeApprovalDecisionSchema,+ ResumeToolResultSchema,+ validateResumePayload,+} from './aiAgent';const log = debug('lobe-server:router:shareChat');@@ -214,6 +234,74 @@ const authorizeVisitorRunningOperation = async (return { aiAgentService, share };};+type LinkShare = Awaited<ReturnType<typeof resolveLinkShareOrThrow>>;++/**+ * Everything a share VISITOR run executes with: the creator-scoped service and+ * models (the run's rows are written under the creator's identity) plus the+ * `shareGate` that strips whatever the share config does not grant.+ *+ * Built fresh from the live share row on every call — a fresh turn and an+ * intervention continuation alike — so a continuation is gated by the share's+ * CURRENT config, never by a snapshot taken when the run parked.+ */+const createShareRunScope = async (+ db: LobeChatDatabase,+ share: LinkShare,+ visitorUserId: string,+) => {+ const workspaceId = share.workspaceId ?? undefined;+ const modelOptions = { includeShareVisitor: true } as const;+ const topicModel = new TopicModel(db, share.ownerId, workspaceId, undefined, modelOptions);+ const messageModel = new MessageModel(db, share.ownerId, workspaceId, undefined, modelOptions);++ const shareGate: AgentShareGate = {+ agentId: share.agentId,+ shareConfig: share.shareConfig,+ // See `AgentShareGate.shareId`'s JSDoc — the share instance this run is+ // authorized against, and the token every later revalidation compares.+ shareId: share.shareId,+ visitorUserId,+ };++ // Creator's Market access token, mirroring aiAgentProcedure — the+ // server-side tool runtime authenticates against the Market API with it.+ let marketAccessToken: string | undefined;+ if (!share.workspaceId) {+ try {+ const userModel = new UserModel(db, share.ownerId);+ const settings = await userModel.getUserSettings();+ marketAccessToken = (settings?.market as any)?.accessToken;+ } catch {+ // non-fatal — MarketService falls back to trustedClientToken+ }+ }++ const aiAgentService = new AiAgentService(db, share.ownerId, {+ // Share visitor turns persist under the creator's `userId` — the+ // service's internal `messageModel`/`topicModel`/runtime must be+ // constructed with the visitor scope so reads/writes on+ // `topics.senderId <> NULL` rows aren't filtered out.+ includeShareVisitor: true,+ marketAccessToken,+ workspaceId,+ });++ /**+ * Dispatch context for an intervention the VISITOR resolved: the actor is+ * the visitor, the continuation runs as the creator under `shareGate`.+ */+ const dispatchContext: AgentInterventionDispatchContext = {+ aiAgentService,+ serverDB: db,+ shareGate,+ userId: visitorUserId,+ workspaceId: share.workspaceId,+ };++ return { aiAgentService, dispatchContext, messageModel, shareGate, topicModel };+};+/*** Storage key prefix for a share's visitor uploads, under the CREATOR's file* namespace. The prefix is what ties an upload session / file row back to a@@ -559,32 +647,74 @@ export const shareChatRouter = router({*/execAgent: shareChatProcedure.input(- z.object({- /** Client-minted row ids, honoured verbatim (see aiAgent.execAgent). */- clientIds: z- .object({- assistantMessageId: z.string().regex(entityIdPattern('messages')).optional(),- topicId: z.string().regex(entityIdPattern('topics')).optional(),- userMessageId: z.string().regex(entityIdPattern('messages')).optional(),- })- .optional(),- /**- * Ids of files the VISITOR uploaded through `shareChat.createFile`.- * Re-checked below against the file rows' share provenance — see- * `assertShareVisitorFiles`.- */- fileIds: z- .array(z.string().min(1).max(64))- .max(SHARE_VISITOR_MAX_FILES_PER_TURN)- .optional(),- /** See `SHARE_VISITOR_PROMPT_MAX_LENGTH`'s JSDoc for the size-bound rationale. */- prompt: z.string().max(SHARE_VISITOR_PROMPT_MAX_LENGTH),- shareId: z.string(),- /** Queued behind a running turn; see `aiAgent.execAgent`'s `steer`. */- steer: z.boolean().optional(),- /** Absent → the run creates a new visitor topic (counted against the topic cap). */- topicId: z.string().nullish(),- }),+ z+ .object({+ /** Client-minted row ids, honoured verbatim (see aiAgent.execAgent). */+ clientIds: z+ .object({+ assistantMessageId: z.string().regex(entityIdPattern('messages')).optional(),+ topicId: z.string().regex(entityIdPattern('topics')).optional(),+ userMessageId: z.string().regex(entityIdPattern('messages')).optional(),+ })+ .optional(),+ /**+ * Ids of files the VISITOR uploaded through `shareChat.createFile`.+ * Re-checked below against the file rows' share provenance — see+ * `assertShareVisitorFiles`.+ */+ fileIds: z+ .array(z.string().min(1).max(64))+ .max(SHARE_VISITOR_MAX_FILES_PER_TURN)+ .optional(),+ /**+ * The pending tool message a resume targets. Set only together with one+ * of the `resume*` payloads — a visitor never regenerates or continues+ * from an arbitrary message.+ */+ parentMessageId: z.string().optional(),+ /** See `SHARE_VISITOR_PROMPT_MAX_LENGTH`'s JSDoc for the size-bound rationale. */+ prompt: z.string().max(SHARE_VISITOR_PROMPT_MAX_LENGTH),+ /**+ * Legacy (message-row) resume of the visitor's own parked run — the+ * fallback when the deployment has no durable intervention store; see+ * `resolveInterventionBySource` for the primary path.+ */+ resumeApproval: ResumeApprovalDecisionSchema.optional(),+ resumeApprovals: z.array(ResumeApprovalDecisionSchema).min(1).optional(),+ resumeToolResult: ResumeToolResultSchema.optional(),+ shareId: z.string(),+ /** Queued behind a running turn; see `aiAgent.execAgent`'s `steer`. */+ steer: z.boolean().optional(),+ /** Absent → the run creates a new visitor topic (counted against the topic cap). */+ topicId: z.string().nullish(),+ /**+ * The VISITOR's own approval mode / allow list. A share run is approved+ * by the visitor, so it honors their preference exactly like the owner's+ * own chat honors the owner's; absent → `manual` (see+ * `AiAgentService.execAgent`).+ */+ userInterventionConfig: UserInterventionConfigSchema.optional(),+ })+ .superRefine((data, refinementCtx) => {+ validateResumePayload(data, refinementCtx);+ const isResume = Boolean(+ data.resumeApproval || data.resumeApprovals || data.resumeToolResult,+ );+ if (data.parentMessageId && !isResume) {+ refinementCtx.addIssue({+ code: 'custom',+ message: 'parentMessageId is only accepted with an intervention resume',+ path: ['parentMessageId'],+ });+ }+ if (isResume && !data.topicId) {+ refinementCtx.addIssue({+ code: 'custom',+ message: 'topicId is required for an intervention resume',+ path: ['topicId'],+ });+ }+ }),).mutation(async ({ input, ctx }) => {const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);@@ -608,6 +738,16 @@ export const shareChatRouter = router({});}+ const isResume = Boolean(+ input.resumeApproval || input.resumeApprovals || input.resumeToolResult,+ );+ if (isResume && input.fileIds?.length) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'An intervention resume cannot attach files',+ });+ }+// Verify every attachment is this visitor's own share upload before it// is handed to a run that executes (and reads files) as the creator.// Also ahead of any row creation, like the spend gate — a foreign id@@ -621,20 +761,8 @@ export const shareChatRouter = router({share.shareConfig.maxTopicsPerVisitor ?? AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR;const maxTurnsPerTopic =share.shareConfig.maxTurnsPerTopic ?? AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC;- const topicModel = new TopicModel(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- undefined,- { includeShareVisitor: true },- );- const messageModel = new MessageModel(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- undefined,- { includeShareVisitor: true },- );+ 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@@ -652,10 +780,15 @@ export const shareChatRouter = router({visitorUserId: ctx.userId,});- const turnCount = await messageModel.countByTopic({- role: 'user',- topicId: input.topicId,- });+ // 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',@@ -675,44 +808,32 @@ export const shareChatRouter = router({}}- // Creator-scoped service: the run executes under the creator's identity- // (their agent config, connectors, billing context). The shareGate strips- // everything the share config doesn't grant.- const shareGate: AgentShareGate = {- agentId: share.agentId,- shareConfig: share.shareConfig,- // See `AgentShareGate.shareId`'s JSDoc — the share instance this run is- // authorized against, and the token every later revalidation compares.- shareId: share.shareId,- visitorUserId: ctx.userId,- };-- // Creator's Market access token, mirroring aiAgentProcedure — the- // server-side tool runtime authenticates against the Market API with it.- let marketAccessToken: string | undefined;- if (!share.workspaceId) {- try {- const userModel = new UserModel(ctx.serverDB, share.ownerId);- const settings = await userModel.getUserSettings();- marketAccessToken = (settings?.market as any)?.accessToken;- } catch {- // non-fatal — MarketService falls back to trustedClientToken- }- }-- const aiAgentService = new AiAgentService(ctx.serverDB, share.ownerId, {- // Share visitor turns persist under the creator's `userId` — the- // service's internal `messageModel`/`topicModel`/runtime must be- // constructed with the visitor scope so reads/writes on- // `topics.senderId <> NULL` rows aren't filtered out.- includeShareVisitor: true,- marketAccessToken,- workspaceId: share.workspaceId ?? undefined,- });-log('execAgent: share=%s visitor=%s topic=%s', input.shareId, ctx.userId, input.topicId);try {+ if (isResume) {+ // Claim the durable generic intervention first when the deployment+ // provides a durable store, scoped to this visitor's own share run;+ // falls through to the legacy message-row resume when no durable row+ // exists.+ const bridged = await bridgeLegacyResumeToSourceIntervention(+ {+ messageModel,+ parentMessageId: input.parentMessageId,+ resumeApproval: input.resumeApproval,+ resumeApprovals: input.resumeApprovals,+ resumeToolResult: input.resumeToolResult,+ shareVisitor: {+ agentId: share.agentId,+ ownerUserId: share.ownerId,+ topicId: input.topicId!,+ },+ },+ dispatchContext,+ );+ if (bridged) return bridged;+ }+const result = await aiAgentService.execAgent({agentId: share.agentId,appContext: { topicId: input.topicId },@@ -741,8 +862,20 @@ export const shareChatRouter = router({// liveness-checked reservation every non-interactive start uses: a// second concurrent send for a topic with a live operation is// rejected instead of silently displacing the first.- interactiveStart: false,+ //+ // A resume is the exception: the topic is still held by the parked+ // (`waiting_for_human`) operation it answers, so the liveness check+ // would always reject it as busy. Its concurrency guard is the+ // exactly-once approval claim instead (`claimApprovalResume` locks the+ // pending tool rows via `resolveHumanApproval`), so a duplicate resume+ // fails there rather than starting a second continuation.+ interactiveStart: isResume,+ parentMessageId: input.parentMessageId,prompt: input.prompt,+ resume: isResume,+ resumeApproval: input.resumeApproval,+ resumeApprovals: input.resumeApprovals,+ resumeToolResult: input.resumeToolResult,shareGate,steer: input.steer,// Not `RequestTrigger.Chat`: a share run is billed to the CREATOR,@@ -751,6 +884,7 @@ export const shareChatRouter = router({// `state.origin.trigger` all the way into the spend-log metadata.trigger: RequestTrigger.AgentShare,userAgent: ctx.userAgent ?? undefined,+ userInterventionConfig: input.userInterventionConfig,});// `AiAgentService.execAgent` RESOLVES (does not throw) when@@ -776,6 +910,13 @@ export const shareChatRouter = router({return result;} catch (error: any) {if (error instanceof TRPCError) throw error;+ if (error instanceof HumanApprovalAlreadyResolvedError) {+ throw new TRPCError({+ cause: error,+ code: 'CONFLICT',+ message: 'This approval has already been resolved.',+ });+ }throw toVisitorSafeStartupError('execAgent', error, {showErrorDetails: share.shareConfig.showErrorDetails,@@ -921,6 +1062,198 @@ export const shareChatRouter = router({});}),+ /**+ * Resolve an intervention (approve / reject / answer / skip / stop) parked on+ * the VISITOR's own share run — the visitor counterpart of+ * `aiAgent.resolveAgentInterventionBySource`. A share run is approved by the+ * visitor: granting a tool to visitors grants its normal approval flow.+ *+ * The visitor must own `topicId` under this live share; the business slot+ * then binds the durable batch to exactly this creator/agent/topic and a+ * share-run operation, so a visitor can never resolve anyone else's run and+ * the owner can never resolve a visitor's run through their own endpoints.+ * The continuation is dispatched under a `shareGate` rebuilt from the live+ * share row (see {@link createShareRunScope}).+ *+ * `unavailable` means the deployment has no durable intervention store (OSS);+ * the client then falls back to `execAgent`'s legacy `resume*` payloads.+ */+ resolveInterventionBySource: shareChatProcedure+ .input(+ ResolveAgentInterventionBySourceSchema.extend({+ shareId: z.string(),+ topicId: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const { shareId, topicId, ...source } = input;+ const share = await resolveLinkShareOrThrow(ctx.serverDB, shareId, ctx.userId);+ const { dispatchContext, topicModel } = await createShareRunScope(+ ctx.serverDB,+ share,+ ctx.userId,+ );+ await findVisitorTopicOrThrow(topicModel, {+ agentId: share.agentId,+ topicId,+ visitorUserId: ctx.userId,+ });++ // A server-side `remember` writes the OWNER's allow list, so a visitor+ // may only approve once here; their "don't ask again" goes to their own+ // allow list client-side (see `approveToolCalling`).+ if (source.action.type === 'approve_tool' && source.action.scope === 'remember') {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Visitors can only approve once' });+ }++ log(+ 'resolveInterventionBySource: share=%s visitor=%s topic=%s operation=%s action=%s',+ shareId,+ ctx.userId,+ topicId,+ source.operationId,+ source.action.type,+ );++ const resolution = await resolveAgentInterventionBySource({+ ...source,+ actorUserId: ctx.userId,+ shareVisitor: { agentId: share.agentId, ownerUserId: share.ownerId, topicId },+ workspaceId: share.workspaceId ?? undefined,+ }).catch((error: unknown) => {+ throw mapAgentInterventionTRPCError(error);+ });++ if (!resolution.handled) {+ return {+ contractVersion: 2 as const,+ status: 'unavailable' as const,+ success: false as const,+ };+ }+ if (resolution.state === 'already_resolved') {+ return {+ contractVersion: 2 as const,+ state: resolution.state,+ status: resolution.status,+ success: true as const,+ };+ }++ try {+ const dispatch = await dispatchClaimedAgentIntervention(resolution, dispatchContext);+ return {+ contractVersion: 2 as const,+ ...(dispatch.execution && { execution: toClientExecAgentResult(dispatch.execution) }),+ state: resolution.state,+ status: dispatch.status,+ success: true as const,+ };+ } catch (error: any) {+ if (error instanceof TRPCError) throw error;++ throw toVisitorSafeStartupError('resolveInterventionBySource', error, {+ showErrorDetails: share.shareConfig.showErrorDetails,+ });+ }+ }),++ /**+ * Stop the visitor's own parked run from its pending approval card — the+ * visitor counterpart of `aiAgent.stopPendingApproval`, used when the+ * deployment has no durable intervention store (OSS) or the rows predate it.+ * `InterventionController.stopPendingApproval` re-checks that the operation+ * is the parked owner of `topicId` and every message belongs to it.+ */+ stopPendingApproval: shareChatProcedure+ .input(+ ShareTopicScopeSchema.extend({+ batchId: z.string().min(1),+ operationId: z.string().min(1),+ toolMessageIds: z.array(z.string()).min(1),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);+ const { aiAgentService, dispatchContext, messageModel, topicModel } =+ await createShareRunScope(ctx.serverDB, share, ctx.userId);+ await findVisitorTopicOrThrow(topicModel, {+ agentId: share.agentId,+ topicId: input.topicId,+ visitorUserId: ctx.userId,+ });++ const stopPlugins = await pMap(+ input.toolMessageIds,+ (id) => messageModel.findMessagePlugin(id),+ { concurrency: 5 },+ );+ const hasGenericSource = stopPlugins.every(+ (plugin) =>+ Boolean(plugin?.toolCallId) &&+ plugin?.intervention?.operationId === input.operationId &&+ plugin.intervention.batchId === input.batchId,+ );+ if (hasGenericSource) {+ const sourceResolution = await resolveAgentInterventionBySource({+ action: { scope: 'operation', type: 'stop' },+ actorUserId: ctx.userId,+ batchId: input.batchId,+ operationId: input.operationId,+ resolutionRequestId: randomUUID(),+ shareVisitor: {+ agentId: share.agentId,+ ownerUserId: share.ownerId,+ topicId: input.topicId,+ },+ targets: stopPlugins.map((plugin, index) => ({+ toolCallId: plugin!.toolCallId!,+ toolMessageId: input.toolMessageIds[index],+ })),+ workspaceId: share.workspaceId ?? undefined,+ }).catch((error: unknown) => {+ throw mapAgentInterventionTRPCError(error);+ });+ if (sourceResolution.handled) {+ if (sourceResolution.state === 'already_resolved') {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'This approval has already been resolved.',+ });+ }+ try {+ await dispatchClaimedAgentIntervention(sourceResolution, dispatchContext);+ } catch (error: any) {+ if (error instanceof TRPCError) throw error;++ throw toVisitorSafeStartupError('stopPendingApproval', error, {+ showErrorDetails: share.shareConfig.showErrorDetails,+ });+ }+ return {+ operationId: input.operationId,+ settledToolMessageIds: input.toolMessageIds,+ success: true,+ };+ }+ }++ try {+ return await aiAgentService.stopPendingApproval({+ batchId: input.batchId,+ operationId: input.operationId,+ toolMessageIds: input.toolMessageIds,+ topicId: input.topicId,+ });+ } catch (error: any) {+ if (error instanceof TRPCError) throw error;++ throw toVisitorSafeStartupError('stopPendingApproval', error, {+ showErrorDetails: share.shareConfig.showErrorDetails,+ });+ }+ }),+/*** Interrupt a running share operation — the visitor counterpart of* `aiAgent.interruptTask`. Visitors have no owner-scoped access todiff --git a/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.ts b/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.tsindex c9b7156fda2..b5323f55bae 100644--- a/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.ts@@ -114,6 +114,23 @@ describe('buildRuntimeInterventionNotification', () => {expect(result?.batch.allowedActions).toEqual(['approve_tool', 'reject_continue', 'stop']);});+ it("marks a share visitor's run so the creator is not notified, with no one-tap action", async () => {+ const result = await buildRuntimeInterventionNotification({+ operationId: 'operation-1',+ state: buildState({+ principal: {+ actor: {+ shareVisitor: { agentId: 'agent-1', shareId: 'share-1', visitorUserId: 'visitor-1' },+ },+ },+ }),+ userId: 'user-1',+ });++ expect(result?.shareVisitorUserId).toBe('visitor-1');+ expect(result?.systemActionEligibility).toBe('review_only');+ });+it('keeps unknown and incomplete manifest APIs Review-only', async () => {const unknown = await buildRuntimeInterventionNotification({operationId: 'operation-1',diff --git a/apps/server/src/services/agentRuntime/agentInterventionNotification.ts b/apps/server/src/services/agentRuntime/agentInterventionNotification.tsindex 415a0e7db1d..5cab53bd428 100644--- a/apps/server/src/services/agentRuntime/agentInterventionNotification.ts+++ b/apps/server/src/services/agentRuntime/agentInterventionNotification.ts@@ -318,6 +318,7 @@ export const buildRuntimeInterventionNotification = async ({items.push(item);}+ const shareVisitorUserId = boundedString(state?.principal?.actor?.shareVisitor?.visitorUserId);const allBinary = items.every((item) => item.surface === 'binary');const hasSecurityRisk = items.some((item) => item.risk?.level !== undefined);const allApisAuthoritative = pendingTools.every((tool) =>@@ -399,11 +400,18 @@ export const buildRuntimeInterventionNotification = async ({items.length === 1? `${items[0].summary} requires review`: `${items.length} actions require review`,+ // A share run is approved by the visitor on the share page, never through+ // the owner's signed direct actions.systemActionEligibility:- items.length === 1 && allBinary && !hasSecurityRisk && allApisAuthoritative+ !shareVisitorUserId &&+ items.length === 1 &&+ allBinary &&+ !hasSecurityRisk &&+ allApisAuthoritative? 'safe_single_binary': 'review_only',...(supersedes && { supersedes }),+ ...(shareVisitorUserId && { shareVisitorUserId }),userId,workspaceId,};diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.tsindex d3562767924..2e73f161f6c 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts@@ -221,25 +221,33 @@ describe('AiAgentService.execAgent - headless approval default', () => {expect(appContext.userAgent).toBeUndefined();});- it('forces headless for a share-visitor run regardless of what the caller passed', async () => {- // Share runs have no approver: any waiting mode would park the run on- // request_human_approve forever. The override must win over an explicit- // caller-provided config — a call site cannot reintroduce a waiting mode.+ const shareGate = {+ agentId: 'agent-1',+ shareConfig: { toolGrants: [] },+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ };++ it('honors the visitor-selected approval mode on a share-visitor run', async () => {+ // The visitor is the approver of a share run, so their own mode drives it.await service.execAgent({agentId: 'agent-1',prompt: 'Hello',- shareGate: {- agentId: 'agent-1',- shareConfig: { toolGrants: [] },- shareId: 'share-1',- visitorUserId: 'visitor-1',- },- userInterventionConfig: { approvalMode: 'manual' },+ shareGate,+ userInterventionConfig: { approvalMode: 'auto-run' },});- expect(mockCreateOperation).toHaveBeenCalledTimes(1);const callArgs = mockCreateOperation.mock.calls[0][0];- expect(callArgs.userInterventionConfig).toEqual({ approvalMode: 'headless' });+ expect(callArgs.userInterventionConfig).toEqual({ approvalMode: 'auto-run' });+ });++ it('falls back to manual, never headless, for a share-visitor run without a config', async () => {+ // `headless` would auto-run `'required'` calls, granting consent the+ // visitor never gave.+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello', shareGate });++ const callArgs = mockCreateOperation.mock.calls[0][0];+ expect(callArgs.userInterventionConfig).toEqual({ approvalMode: 'manual' });});it('should respect explicit allow-list approval mode with allowList', async () => {diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 2142b98bdc4..5555d02f21a 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -964,27 +964,17 @@ export class AiAgentService {ephemeralUserMessage,} = params;- // Agent Share visitor runs execute under the CREATOR's credentials (see- // `shareChat.ts` `execAgent` → `AiAgentService.execAgent({ shareGate })`)- // with no visitor-facing approval UI at all, so no approval can ever be- // WAITED for: `headless` is the only mode that converts an intervention- // into an immediate blocked tool result ('always'-policy calls become- // `resolve_blocked_tools`) instead of parking the run on- // `request_human_approve` forever. Forced unconditionally — overriding- // whatever the caller passed — so a future execAgent call site cannot- // reintroduce a waiting mode by omission.+ // Agent Share visitor runs execute under the CREATOR's credentials but are+ // approved by the VISITOR: granting a tool grants its normal approval+ // flow, so the run honors the visitor's own approval mode (sent by the+ // share client, see `shareChat.execAgent`) and parks intervention-gated+ // calls for the visitor to resolve on the share page.//- // `headless` DOES auto-run overridable ('required') interventions. That is- // acceptable here only because of the two share-specific layers on top:- // `applyShareGateToInterventionRequiredApis` strips every- // intervention-gated API from what the model is offered, and- // `isShareBlockedBuiltinDispatch` re-blocks intervention-gated (and- // non-enabled, and data-rule-violating) builtin calls at the executor- // dispatch site — re-reading the UNSTRIPPED manifest, since the assembly- // strip removes the very intervention config the runtime would otherwise- // consult. No 'required' builtin API can execute through either layer.+ // A share caller that sends no config falls back to `manual`, never to+ // this method's `headless` default: `headless` auto-runs `'required'`+ // calls, which would grant a consent nobody gave.const userInterventionConfig: UserInterventionConfig = shareGate- ? { approvalMode: 'headless' }+ ? (params.userInterventionConfig ?? { approvalMode: 'manual' }): requestedUserInterventionConfig;// Honour client-minted row ids on a FRESH send only. Resume / regenerationdiff --git a/apps/server/src/services/aiAgent/shareGate.test.ts b/apps/server/src/services/aiAgent/shareGate.test.tsindex afa91f6df3c..789c84cf3c8 100644--- a/apps/server/src/services/aiAgent/shareGate.test.ts+++ b/apps/server/src/services/aiAgent/shareGate.test.ts@@ -225,7 +225,7 @@ describe('AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS', () => {// share visitor's run gets an isolated per-topic sandbox session with no// `lh` CLI JWT shim, so it cannot mint or exfiltrate the creator's// credentials — see the positive-evidence doc block above- // `applyShareGateToInterventionRequiredApis` in `shareGate.ts`.+ // `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS` in `shareGate.ts`.it('allowlists lobe-cloud-sandbox now that visitor runs get a credential-free sandbox session', () => {expect(AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS.has('lobe-cloud-sandbox')).toBe(true);});@@ -719,12 +719,15 @@ describe('applyShareGateToToolSet', () => {]);});- it('strips apis whose humanIntervention can never resolve under reject mode', () => {+ // Share runs honor the visitor's own approval mode, so granting a tool+ // grants its normal approval flow: intervention-gated APIs stay offered+ // WITH their config intact, which is what makes the runtime park them for+ // the visitor's approval instead of auto-running them.+ it('keeps intervention-gated apis and their humanIntervention config', () => {const toolSet = buildToolSet([{apis: [{ name: 'safe' },- { humanIntervention: 'never', name: 'explicitlySafe' },{ humanIntervention: 'required', name: 'needsApproval' },{ humanIntervention: 'always', name: 'alwaysAsks' },{ humanIntervention: { type: 'dynamic' }, name: 'maybeAsks' },@@ -732,23 +735,6 @@ describe('applyShareGateToToolSet', () => {identifier: CalculatorIdentifier,},]);-- applyShareGateToToolSet(- toolSet,- buildGate({ toolGrants: [{ identifier: CalculatorIdentifier }] }),- );-- expect(toolSet.manifestMap[CalculatorIdentifier].api.map((api) => api.name)).toEqual([- 'safe',- 'explicitlySafe',- ]);- expect(toolSet.tools).toHaveLength(2);- });-- it('drops a tool whose tool-level humanIntervention is unusable', () => {- const toolSet = buildToolSet([- { apis: [{ name: 'calculate' }], identifier: CalculatorIdentifier },- ]);(toolSet.manifestMap[CalculatorIdentifier] as any).humanIntervention = 'required';applyShareGateToToolSet(@@ -756,19 +742,21 @@ describe('applyShareGateToToolSet', () => {buildGate({ toolGrants: [{ identifier: CalculatorIdentifier }] }),);- expect(toolSet.manifestMap[CalculatorIdentifier]).toBeUndefined();- expect(toolSet.enabledToolIds).toEqual([]);+ const manifest = toolSet.manifestMap[CalculatorIdentifier] as any;+ expect(manifest.humanIntervention).toBe('required');+ expect(manifest.api.map((api: any) => [api.name, api.humanIntervention])).toEqual([+ ['safe', undefined],+ ['needsApproval', 'required'],+ ['alwaysAsks', 'always'],+ ['maybeAsks', { type: 'dynamic' }],+ ]);+ expect(toolSet.tools).toHaveLength(4);});- it('strips a required-intervention API from a non-builtin (MCP/connector) manifest, keeping its normal APIs', () => {+ it('keeps a required-intervention API on a non-builtin (MCP/connector) manifest', () => {// Mirrors `buildConnectorManifests.ts`: a connector tool with the- // `needs_approval` permission maps to `humanIntervention: 'required'` on- // an otherwise-ordinary MCP manifest. Regression for the fix that widened- // `applyShareGateToInterventionRequiredApis` beyond builtin-only- // manifests — the connector permission gate at dispatch time- // (`ToolExecutionService.executeTool`) only hard-blocks `disabled`, so- // this assembly-time strip is the only thing stopping a share visitor's- // headless run from auto-executing a "needs approval" connector call.+ // `needs_approval` permission maps to `humanIntervention: 'required'`.+ // The config must survive so the visitor is asked before it runs.const toolSet = buildToolSet([{apis: [{ name: 'listRepos' }, { humanIntervention: 'required', name: 'deleteRepo' }],@@ -779,17 +767,12 @@ describe('applyShareGateToToolSet', () => {applyShareGateToToolSet(toolSet, buildGate({ toolGrants: [{ identifier: 'mcp-github' }] }));- expect(toolSet.manifestMap['mcp-github'].api.map((api) => api.name)).toEqual(['listRepos']);- // `type: 'mcp'` means `ToolNameResolver.generate` appends a THIRD- // `____mcp` segment to the function-calling name — a naive- // `identifier____apiName` string would never match this, so this- // assertion only passes when the strip regenerates the real name.- expect(toolSet.tools!.map((tool: any) => tool.function.name)).toEqual([- toolName('mcp-github', 'listRepos', 'mcp'),+ expect(+ toolSet.manifestMap['mcp-github'].api.map((api: any) => [api.name, api.humanIntervention]),+ ).toEqual([+ ['listRepos', undefined],+ ['deleteRepo', 'required'],]);- expect(toolSet.tools!.map((tool: any) => tool.function.name)).not.toContain(- `mcp-github____deleteRepo____mcp`,- );});it('narrows a per-API grant on a non-builtin (MCP) manifest, matching the real `____<type>`-suffixed generated name', () => {@@ -934,8 +917,9 @@ describe('applyShareGateToToolSet', () => {// Dispatch-time full gate, asserted against the REAL manifests: a call that// bypassed assembly must clear the master allowlist, the owner's-// toolGrants picker, the UNSTRIPPED manifest's humanIntervention policy,-// and the data-tool rules — in that order, all fail-closed.+// toolGrants picker, sub-agent dispatch, and the data-tool rules — in that+// order, all fail-closed. `humanIntervention` is not a dispatch rule: the+// runtime parks those calls for the visitor's approval first.describe('isShareBlockedBuiltinDispatch', () => {it('blocks an allowlisted builtin the owner did not enable', () => {expect(isShareBlockedBuiltinDispatch({}, CalculatorIdentifier, 'evalExpression')).toBe(true);@@ -951,11 +935,7 @@ describe('isShareBlockedBuiltinDispatch', () => {).toBe(false);});- it("blocks 'required'- and 'always'-intervention APIs even on an enabled tool", () => {- // createPlan is humanIntervention: 'required' in the real manifest — the- // assembly strip removes that config from the runtime-visible manifest,- // so under headless it would auto-run without its consent step. The- // dispatch gate re-reads the unstripped manifest and blocks.+ it('passes an approved intervention-gated API on an enabled tool', () => {for (const apiName of [LobeAgentApiName.createPlan, LobeAgentApiName.askUserQuestion]) {expect(isShareBlockedBuiltinDispatch(@@ -963,13 +943,13 @@ describe('isShareBlockedBuiltinDispatch', () => {LobeAgentIdentifier,apiName,),- ).toBe(true);+ ).toBe(false);}});it('blocks sub-agent dispatch even on an enabled tool with no intervention config', () => {- // callSubAgent carries no humanIntervention, so neither the intervention- // check nor the data-tool rules would catch it — and the child run it+ // callSubAgent carries no humanIntervention, so neither the approval+ // flow nor the data-tool rules would catch it — and the child run it// spawns does not inherit the parent's shareGate. Must be blocked by its// dedicated dispatch rule.expect(diff --git a/apps/server/src/services/aiAgent/shareGate.ts b/apps/server/src/services/aiAgent/shareGate.tsindex 08f478d82c1..718c9e58583 100644--- a/apps/server/src/services/aiAgent/shareGate.ts+++ b/apps/server/src/services/aiAgent/shareGate.ts@@ -21,7 +21,6 @@ import {} from '@lobechat/builtin-tool-skills';import {AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS,- builtinTools,isBuiltinToolIdentifier,} from '@lobechat/builtin-tools';import {@@ -365,12 +364,11 @@ const DATA_TOOL_ACCESS_RULES: Record<string, DataToolAccessRule> = {grant: (permissions) => (hasShareSkillAuthorization(permissions) ? 'read' : 'none'),// Derived as "everything outside the visitor-safe set" rather than listed,// so a skill API added later is denied by default. Today that resolves to- // `runCommand` / `execScript` / `exportFile`: the first two declare- // `humanIntervention: 'required'` and are therefore ALSO stripped by- // `applyShareGateToInterventionRequiredApis`, but they are named here on- // purpose — that strip exists to honor an approval policy, and the day- // Agent Share grows a real approval step it must be a deliberate decision- // to open them, not a side effect of the policy check going quiet.+ // `runCommand` / `execScript` / `exportFile`. Share runs now honor the+ // visitor's approval flow, so `humanIntervention: 'required'` no longer+ // strips the first two — this list is what keeps them closed until+ // opening skill script execution to visitors is decided on its own+ // (LOBE-14296).writeApiNames: SkillsManifest.api.map((api) => api.name).filter((apiName) => !AGENT_SHARE_SKILL_API_NAMES.has(apiName)),@@ -441,13 +439,7 @@ export const isShareBlockedDataToolCall = (* is necessary but NOT sufficient; a tool the creator never enabled for* this share (e.g. image generation spending the creator's quota) must not* run just because a call reached the executor;- * 3. `humanIntervention` policy, re-derived from the REAL manifest: the- * assembly strip removes intervention-gated APIs from the manifest the- * runtime later consults, so at dispatch time such a call looks- * config-less and `headless` would silently auto-run it — the manifest in- * `@lobechat/builtin-tools` is the unstripped source of truth, so the- * consent-gated call is blocked here instead;- * 4. the per-API data-tool rules ({@link isShareBlockedDataToolCall}).+ * 3. the per-API data-tool rules ({@link isShareBlockedDataToolCall}).** Non-builtin identifiers (MCP/market/custom plugins, LobeHub skills) pass* through untouched: their id namespace does not reliably match@@ -476,20 +468,11 @@ export const isShareBlockedBuiltinDispatch = (// (`stripSubAgentDispatchApis`); this is its dispatch-time counterpart.if (SUB_AGENT_DISPATCH_APIS[identifier]?.apiName === apiName) return true;- const manifest = builtinTools.find((tool) => tool.identifier === identifier)?.manifest;- const toolLevelHumanIntervention = (manifest as { humanIntervention?: unknown } | undefined)- ?.humanIntervention;- // Match assembly's semantics exactly (`applyShareGateToInterventionRequiredApis`- // drops the WHOLE tool when the tool-level fallback is unusable): a- // tool-level 'required'/'always'/dynamic config blocks every API here too —- // an api-level 'never' must not override it at dispatch when it could not- // have survived assembly either.- if (!isApiUsableForShareVisitor(toolLevelHumanIntervention)) return true;- const apiHumanIntervention = manifest?.api?.find(- (api) => api.name === apiName,- )?.humanIntervention;- if (!isApiUsableForShareVisitor(apiHumanIntervention ?? toolLevelHumanIntervention)) return true;-+ // `humanIntervention` is deliberately NOT re-checked here: share runs keep+ // the manifest's intervention config and honor the visitor's own approval+ // mode, so an intervention-gated call reaches this executor only after the+ // visitor approved it (or chose auto-run). Granting a tool grants its normal+ // approval flow.return isShareBlockedDataToolCall(agentShare, identifier, apiName, args);};@@ -613,15 +596,14 @@ export const applyShareGateToToolSet = (toolSet: ShareGateToolSet, gate: AgentShstripSubAgentDispatchApis(toolSet);applyShareGateToDataToolAccess(toolSet, gate);- applyShareGateToInterventionRequiredApis(toolSet);applyShareGateToPerApiGrants(toolSet, grants);};/*** Narrow each surviving tool's offered APIs down to what the owner's picker* actually granted for it. Runs LAST in {@link applyShareGateToToolSet}, after- * every other strip (data-tool write/always-blocked APIs, sub-agent dispatch,- * humanIntervention) has already trimmed `manifest.api` — so a per-API grant+ * every other strip (data-tool write/always-blocked APIs, sub-agent dispatch)+ * has already trimmed `manifest.api` — so a per-API grant* naming an API another rule already removed is simply a no-op here, never an* unstrip.*@@ -663,85 +645,6 @@ const applyShareGateToPerApiGrants = (}};-/**- * Whether an API's own `humanIntervention` policy can ever HONESTLY complete- * for a share-visitor run. Every share run is forced onto `approvalMode:- * 'headless'` (see `AiAgentService.execAgent`'s unconditional override) — the- * only mode with **no approver waited for**: an `'always'`-policy call becomes- * an immediate blocked tool result (`resolve_blocked_tools`), and a- * `'required'`-policy call would silently auto-run, granting itself the- * consent nobody was present to give. Stripping both classes from the offer- * is therefore the fail-closed reading: never offer a function that either- * cannot run or would run without its declared consent step. A `dynamic`- * config might resolve to `'never'` for some argument, but this static,- * schema-assembly-time check cannot prove it always will.- *- * `undefined` (no config at all) and the literal string `'never'` are the only- * two configs that execute with no intervention semantics attached.- */-const isApiUsableForShareVisitor = (humanIntervention: unknown): boolean =>- humanIntervention === undefined || humanIntervention === 'never';--/**- * Structural counterpart to `applyShareGateToDataToolAccess`: strip any tool's- * API whose OWN `humanIntervention` policy cannot honestly complete under a- * share visitor's forced `headless` approval mode. Reads the SAME `humanIntervention`- * metadata every builtin tool already declares for the approval-UI feature, so- * a future tool added to `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS` with an- * intervention-gated API is caught automatically instead of requiring a manual- * audit.- *- * Applies to EVERY manifest still in `toolSet.manifestMap` at this point,- * builtin or not — MCP/connector manifests (`buildConnectorManifests.ts`) map- * a connector tool's `needs_approval` permission onto this SAME `humanIntervention:- * 'required'` field, and `ToolExecutionService.executeTool`'s dispatch-time- * connector-permission gate only hard-blocks `disabled`, deliberately leaving- * `needs_approval` to this manifest strip — so a share run (always `headless`,- * see {@link isApiUsableForShareVisitor}) would otherwise auto-run a- * creator-configured "needs approval" connector call with no approver ever- * present. `isGovernedByBuiltinAllowlist` is intentionally NOT consulted here:- * that allowlist decides which BUILTIN tools may be exposed at all (still- * enforced earlier in {@link applyShareGateToToolSet}), not which manifests- * this intervention strip should look at.- *- * A tool whose TOOL-LEVEL `humanIntervention` (the fallback every API without- * its own entry inherits) is itself unusable loses every API and is dropped- * entirely, the same treatment `applyShareGateToDataToolAccess` gives a- * `'none'` grant.- *- * Under `headless` this strip is MORE than UX for `'required'`-policy APIs:- * headless auto-runs those, so removing them from the offer is the layer that- * keeps a share visitor's model from invoking a consent-gated API without its- * consent step ever happening. `'always'`-policy APIs stay unreachable either- * way (headless converts them to blocked results); data-bearing BUILTIN APIs- * are additionally re-blocked at dispatch by {@link isShareBlockedDataToolCall}- * — non-builtin manifests have no such dispatch-time backstop, which is why- * this assembly-time strip is their ONLY enforcement point.- */-const applyShareGateToInterventionRequiredApis = (toolSet: ShareGateToolSet): void => {- for (const identifier of Object.keys(toolSet.manifestMap)) {- const manifest = toolSet.manifestMap[identifier];- if (!Array.isArray(manifest.api) || manifest.api.length === 0) continue;-- const toolLevelHumanIntervention = (manifest as { humanIntervention?: unknown })- .humanIntervention;-- if (!isApiUsableForShareVisitor(toolLevelHumanIntervention)) {- dropToolFromSet(toolSet, identifier);- continue;- }-- const blockedApiNames = new Set(- manifest.api- .filter((api) => !isApiUsableForShareVisitor(api.humanIntervention))- .map((api) => api.name),- );- if (blockedApiNames.size === 0) continue;-- stripApisFromTool(toolSet, identifier, blockedApiNames);- }-};-/*** Rationale for every registered builtin identifier that is DENIED — i.e.* absent from `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS`. Under a denylist an@@ -838,18 +741,11 @@ const applyShareGateToInterventionRequiredApis = (toolSet: ShareGateToolSet): vo* it would only let the owner-facing tool picker confirm a grant no visitor* conversation can ever exercise.*- * - `lobe-user-interaction` / `lobe-activator`: same "picker promises an- * unusable grant" class, not a data leak. Every share run is forced onto- * `approvalMode: 'headless'` with no approver ever present:- * `lobe-user-interaction`'s only entry point (`askUserQuestion`,- * `humanIntervention: 'always'`) is converted to a blocked tool result and- * never runs, and its other APIs all require a `requestId` only a- * successful `askUserQuestion` mints. `lobe-activator`'s only API- * (`activateTools`, `humanIntervention: 'required'`) would auto-run under- * headless but is stripped from the offer instead. See- * {@link applyShareGateToInterventionRequiredApis} for the structural fix- * that catches this failure mode generically on every ALLOWED tool's- * individual APIs.+ * - `lobe-user-interaction` / `lobe-activator`: originally denied because+ * share runs were forced headless, so neither could ever honestly complete.+ * Share runs now honor the visitor's approval flow, but both stay denied+ * until audited on their own: `lobe-activator` can widen the run's tool+ * surface at runtime, which must be proven not to escape the share grant.*//**diff --git a/apps/server/src/services/toolExecution/__tests__/builtin.test.ts b/apps/server/src/services/toolExecution/__tests__/builtin.test.tsindex e99346fd52c..ad61cca57eb 100644--- a/apps/server/src/services/toolExecution/__tests__/builtin.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/builtin.test.ts@@ -43,9 +43,9 @@ vi.mock('@/server/services/market', () => ({// except `lobe-user-memory`, granted so the memory-permission dispatch tests// below can exercise the per-API data-tool rules.vi.mock('@lobechat/builtin-tools', () => ({- AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS: new Set(['lobe-user-memory', 'lobe-consent-tool']),+ AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS: new Set(['lobe-user-memory']),isBuiltinToolIdentifier: (id: string) =>- ['lobe-notebook', 'lobe-task', 'lobe-user-memory', 'lobe-consent-tool'].includes(id),+ ['lobe-notebook', 'lobe-task', 'lobe-user-memory'].includes(id),builtinTools: [{identifier: 'lobe-notebook',@@ -76,21 +76,11 @@ vi.mock('@lobechat/builtin-tools', () => ({api: [{ name: 'searchUserMemory' },{ name: 'addContextMemory' },- // exercises the dispatch gate's unstripped-manifest intervention check+ // intervention-gated: the dispatch gate must not re-block it{ humanIntervention: 'required', name: 'consentGated' },],},},- {- identifier: 'lobe-consent-tool',- // Tool-level 'required' with an api-level 'never': assembly drops the- // WHOLE tool for such a config, so dispatch must too — the api-level- // 'never' must not override the tool-level restriction.- manifest: {- api: [{ humanIntervention: 'never', name: 'freeApi' }],- humanIntervention: 'required',- },- },{identifier: 'lobe-task',manifest: {@@ -615,10 +605,9 @@ describe('BuiltinToolsExecutor share-visitor gate', () => {expect(mockApiHandler).not.toHaveBeenCalled();});- it('blocks a consent-gated (humanIntervention) API even when the tool is enabled', async () => {- // The assembly strip removes the API's intervention config from the- // runtime-visible manifest, so headless would auto-run it — the dispatch- // gate must re-read the unstripped manifest and block instead.+ it('does not share-block a granted consent-gated (humanIntervention) API', async () => {+ // Share runs keep the intervention config and the visitor approves the+ // call before it is dispatched, so the dispatch gate must not re-block it.const result = await executor.execute(memoryPayload('consentGated'), {...context,agentShareVisitor: {@@ -628,27 +617,7 @@ describe('BuiltinToolsExecutor share-visitor gate', () => {},});- expect(result.error?.code).toBe('SHARE_GATE_BLOCKED');- expect(mockApiHandler).not.toHaveBeenCalled();- });-- it("blocks a tool-level 'required' tool even when the called API is 'never'", async () => {- const result = await executor.execute(- {- apiName: 'freeApi',- arguments: '{}',- id: 't-consent',- identifier: 'lobe-consent-tool',- type: 'default' as any,- },- {- ...context,- agentShareVisitor: { ...visitorIds, toolGrants: [{ identifier: 'lobe-consent-tool' }] },- },- );-- expect(result.error?.code).toBe('SHARE_GATE_BLOCKED');- expect(mockApiHandler).not.toHaveBeenCalled();+ expect(result.error?.code).not.toBe('SHARE_GATE_BLOCKED');});it('blocks memory reads without allowReadMemory', async () => {diff --git a/apps/server/src/services/toolExecution/builtin.ts b/apps/server/src/services/toolExecution/builtin.tsindex 26e21d9db6d..0c0b21e2f67 100644--- a/apps/server/src/services/toolExecution/builtin.ts+++ b/apps/server/src/services/toolExecution/builtin.ts@@ -182,8 +182,9 @@ export class BuiltinToolsExecutor implements IToolExecutor {// this executor runs whatever call reaches it, so a resume path, recovery// hint, or future tool-discovery route that bypasses assembly must still// clear the FULL gate here: master default-deny allowlist, the owner's- // `toolGrants` picker, humanIntervention policy (re-read from the- // unstripped manifest), and the per-API data-tool rules. Non-builtin+ // `toolGrants` picker, and the per-API data-tool rules. `humanIntervention`+ // is not a block reason: the visitor approves granted tools like any+ // other run, so the approval itself already happened upstream. Non-builtin// identifiers pass through (governed by the share's `toolGrants` at// assembly). Fail closed: block, never throw open.if (diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex 111bf888f8d..9bc6d6a32c8 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -411,7 +411,6 @@"share.settings.tabs.stats": "Stats","share.settings.title": "Share Agent","share.settings.tools.apiGrantedCount": "{{granted}} of {{total}} APIs granted",- "share.settings.tools.apiNeedsApproval": "This action needs your approval before it runs, and nobody can approve it during a shared run, so it stays off.","share.settings.tools.apiNotAvailableToVisitors": "This action is never available to visitors in a shared run.","share.settings.tools.apiWritesOwnerData": "Visitors can never write to your memory — this action stays off in shared runs.","share.settings.tools.apiWritesOwnerDocuments": "Visitors can never delete or copy your documents or change their load rules — this action stays off in shared runs.",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex e67caa31d7c..d8e34e7f4d7 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -411,7 +411,6 @@"share.settings.tabs.stats": "统计","share.settings.title": "分享助手","share.settings.tools.apiGrantedCount": "已开放 {{granted}}/{{total}} 个接口",- "share.settings.tools.apiNeedsApproval": "该操作需要你本人确认后才能执行,分享运行中无人确认,因此始终关闭。","share.settings.tools.apiNotAvailableToVisitors": "该操作在分享运行中始终不对访客开放。","share.settings.tools.apiWritesOwnerData": "访客不能写入你的记忆,该操作在分享运行中始终关闭。","share.settings.tools.apiWritesOwnerDocuments": "访客不能删除、复制你的文档或修改其加载规则,该操作在分享运行中始终关闭。",diff --git a/packages/builtin-tool-skills/src/types.ts b/packages/builtin-tool-skills/src/types.tsindex 99262ec5284..06cddde07c3 100644--- a/packages/builtin-tool-skills/src/types.ts+++ b/packages/builtin-tool-skills/src/types.ts@@ -13,12 +13,11 @@ export const SkillsApiName = {* content; WHICH skills they can reach is a separate question, answered by the* share's `skillGrants` allowlist inside the server runtime.*- * The exec-class APIs (`runCommand` / `execScript`) are excluded because they- * declare `humanIntervention: 'required'` and a visitor run is forced headless,- * so there is no approver to honor that declaration; `exportFile` is excluded- * because its only purpose is pulling artifacts out of an execution those APIs- * would have started. Opening them needs Agent Share to grow a real approval- * step first.+ * The exec-class APIs (`runCommand` / `execScript`) stay excluded even though+ * share runs now honor the visitor's approval flow: opening skill script+ * execution to visitors is a separate decision (LOBE-14296). `exportFile` is+ * excluded because its only purpose is pulling artifacts out of an execution+ * those APIs would have started.** Shared with the server share gate (`DATA_TOOL_ACCESS_RULES` in* `apps/server/src/services/aiAgent/shareGate.ts`), which derives its blockdiff --git a/packages/business-server/src/agent-run/agentInterventionReview.ts b/packages/business-server/src/agent-run/agentInterventionReview.tsindex 7d26e0ece49..2a15a0d48d7 100644--- a/packages/business-server/src/agent-run/agentInterventionReview.ts+++ b/packages/business-server/src/agent-run/agentInterventionReview.ts@@ -257,6 +257,8 @@ export interface GetAgentInterventionReviewBySourceParams {actorUserId: string;batchId: string;operationId: string;+ /** Set only by the share-visitor path; see {@link AgentInterventionShareVisitorScope}. */+ shareVisitor?: AgentInterventionShareVisitorScope;targets: AgentInterventionSourceTarget[];workspaceId?: string;}@@ -278,12 +280,27 @@ export type GetAgentInterventionReviewBySourceResult =sourceItemMap: Record<string, string>;});+/**+ * A share visitor resolving an intervention on their OWN share run. The caller+ * (`shareChat.resolveInterventionBySource`) has already authenticated the visitor and+ * proved they own `topicId` under a live share of `agentId`; the business slot+ * must still bind the durable batch to exactly this owner/agent/topic and to a+ * share-run operation, and must refuse every other actor for a share run.+ */+export interface AgentInterventionShareVisitorScope {+ agentId: string;+ ownerUserId: string;+ topicId: string;+}+export interface ResolveAgentInterventionBySourceParams {action: AgentInterventionSourceAction;actorUserId: string;batchId: string;operationId: string;resolutionRequestId: string;+ /** Set only by the share-visitor resolve path; see {@link AgentInterventionShareVisitorScope}. */+ shareVisitor?: AgentInterventionShareVisitorScope;targets: AgentInterventionSourceTarget[];workspaceId?: string;}@@ -488,6 +505,12 @@ export interface NotifyAgentInterventionRequiredParams {context: Omit<AgentInterventionReviewContext, 'agent' | 'topic' | 'triggerRequest'>;deadline?: number;items: NotifyAgentInterventionItem[];+ /**+ * Set when the parked run is a share VISITOR's run. The visitor resolves it+ * on the share page; owner-facing delivery (push, Live Activity, Review+ * links) must be skipped — the owner is not the approver of that run.+ */+ shareVisitorUserId?: string;summary: string;/*** A partial per-card decision may re-park the unresolved rows in a newdiff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex 83bc0dbb06b..ef26f183e2e 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -514,8 +514,6 @@ export default {'Could not load this Agent’s skills. Close and reopen the share settings to try again.','share.settings.skills.loading': 'Loading skills…','share.settings.skills.title': 'Skills visitors can use',- 'share.settings.tools.apiNeedsApproval':- 'This action needs your approval before it runs, and nobody can approve it during a shared run, so it stays off.','share.settings.tools.apiWritesOwnerDocuments':'Visitors can never delete or copy your documents or change their load rules — this action stays off in shared runs.','share.settings.tools.desc':diff --git a/src/features/Conversation/AssistantTurnSettledWatcher.tsx b/src/features/Conversation/AssistantTurnSettledWatcher.tsxindex d292fe07521..6cded3d6ef2 100644--- a/src/features/Conversation/AssistantTurnSettledWatcher.tsx+++ b/src/features/Conversation/AssistantTurnSettledWatcher.tsx@@ -7,15 +7,13 @@ import { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/slices/operation/selectors';import { type Operation, type OperationType } from '@/store/chat/slices/operation/types';-import { useUnexpiredInterventions } from './hooks/useDeadlineClock';+import { usePendingInterventions } from './hooks/usePendingInterventions';import {contextSelectors,conversationSelectors,- dataSelectors,messageStateSelectors,useConversationStore,} from './store';-import { isSamePendingInterventionList } from './store/slices/data/pendingInterventions';const log = debug('lobe-render:features:Conversation');@@ -71,9 +69,7 @@ const AssistantTurnSettledWatcher = () => {// Same list the InterventionBar shows: an expired card must not keep the turn// counted as waiting on the user just because nothing re-ran the selector.- const pendingInterventionCount = useUnexpiredInterventions(- useConversationStore(dataSelectors.pendingInterventions, isSamePendingInterventionList),- ).length;+ const pendingInterventionCount = usePendingInterventions().length;const armedSettledMessageIdRef = useRef<string>(undefined);const firedSettledMessageIdRef = useRef<string>(undefined);diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsxindex 440232c6068..709a84fd9d3 100644--- a/src/features/Conversation/ChatInput/index.tsx+++ b/src/features/Conversation/ChatInput/index.tsx@@ -29,7 +29,7 @@ import { fileChatSelectors, useFileStore } from '@/store/file';import { buildMessageContextSelections } from '../../ChatInput/utils/contextSelections';import WideScreenContainer from '../../WideScreenContainer';-import { useUnexpiredInterventions } from '../hooks/useDeadlineClock';+import { usePendingInterventions } from '../hooks/usePendingInterventions';import InterventionBar from '../InterventionBar';import {dataSelectors,@@ -37,7 +37,6 @@ import {useConversationStore,useConversationStoreApi,} from '../store';-import { isSamePendingInterventionList } from '../store/slices/data/pendingInterventions';import TodoProgress from '../TodoProgress';import InputCompletionErrorAlert from './InputCompletionErrorAlert';import LinkedGoalTray from './LinkedGoalTray';@@ -264,16 +263,7 @@ const ChatInput = memo<ChatInputProps>(operationSelectors.isInputLoadingByContext(context)(s),);- // Pending interventions — use custom equality to prevent infinite re-render loop.- // The selector creates new array/object refs each call; without equality check,- // any store update → new ref → re-render → Intervention's store writes → loop.- const selectedInterventions = useConversationStore(- dataSelectors.pendingInterventions,- isSamePendingInterventionList,- );- // The selector only re-runs on store changes; drop a card the moment its- // producer stops waiting even when nothing in the store moves.- const pendingInterventions = useUnexpiredInterventions(selectedInterventions);+ const pendingInterventions = usePendingInterventions();const hasPendingInterventions = pendingInterventions.length > 0;// Send message error from ConversationStorediff --git a/src/features/Conversation/InterventionBar/PendingInterventionBar.tsx b/src/features/Conversation/InterventionBar/PendingInterventionBar.tsxnew file mode 100644index 00000000000..ad23eafb711--- /dev/null+++ b/src/features/Conversation/InterventionBar/PendingInterventionBar.tsx@@ -0,0 +1,21 @@+import { memo } from 'react';++import { usePendingInterventions } from '../hooks/usePendingInterventions';+import InterventionBar from './index';++/**+ * The conversation's pending approval / question cards, self-selected from the+ * ConversationStore. For surfaces that render their own composer instead of+ * `ChatInput` (which mounts the bar itself), e.g. the Agent Share visitor page.+ */+const PendingInterventionBar = memo(() => {+ const interventions = usePendingInterventions();++ if (interventions.length === 0) return null;++ return <InterventionBar interventions={interventions} />;+});++PendingInterventionBar.displayName = 'PendingInterventionBar';++export default PendingInterventionBar;diff --git a/src/features/Conversation/hooks/usePendingInterventions.ts b/src/features/Conversation/hooks/usePendingInterventions.tsnew file mode 100644index 00000000000..cec53f74502--- /dev/null+++ b/src/features/Conversation/hooks/usePendingInterventions.ts@@ -0,0 +1,22 @@+import { dataSelectors, useConversationStore } from '../store';+import { isSamePendingInterventionList } from '../store/slices/data/pendingInterventions';+import { useUnexpiredInterventions } from './useDeadlineClock';++/**+ * The conversation's unexpired pending approval / question cards.+ *+ * Custom equality: the selector builds a new list on every store change, and+ * without it any store update → new ref → re-render → Intervention's store+ * writes → loop. The deadline filter drops a card the moment its producer stops+ * waiting, even when nothing in the store moves.+ *+ * Kept out of `PendingInterventionBar` so non-UI consumers such as+ * `AssistantTurnSettledWatcher` do not pull in the whole intervention UI tree.+ */+export const usePendingInterventions = () => {+ const selected = useConversationStore(+ dataSelectors.pendingInterventions,+ isSamePendingInterventionList,+ );+ return useUnexpiredInterventions(selected);+};diff --git a/src/features/Conversation/index.ts b/src/features/Conversation/index.tsindex 11d670a1eaa..554917e1119 100644--- a/src/features/Conversation/index.ts+++ b/src/features/Conversation/index.ts@@ -21,5 +21,7 @@ export type {// Componentsexport { default as ChatInput, type ChatInputProps } from './ChatInput';export { default as ChatList, type ChatListProps } from './ChatList';+export { usePendingInterventions } from './hooks/usePendingInterventions';+export { default as PendingInterventionBar } from './InterventionBar/PendingInterventionBar';export { default as MessageItem, type MessageItemProps } from './Messages';export { default as TodoProgress } from './TodoProgress';diff --git a/src/services/shareChat.ts b/src/services/shareChat.tsindex 8b71110ee5d..2834766c4fb 100644--- a/src/services/shareChat.ts+++ b/src/services/shareChat.ts@@ -1,6 +1,12 @@-import type { ExecAgentResult, UIChatMessage } from '@lobechat/types';+import type { ExecAgentResult, UIChatMessage, UserInterventionConfig } from '@lobechat/types';import { lambdaClient } from '@/libs/trpc/client';+import type {+ ResolveAgentInterventionBySourceParams,+ ResolveAgentInterventionBySourceResult,+ ResumeApprovalParam,+ ResumeToolResultParam,+} from '@/services/aiAgent';export interface ShareChatExecParams {/** Client-minted ids for the rows this run creates (fresh sends only). */@@ -11,12 +17,25 @@ export interface ShareChatExecParams {* ids of anyone else's files are rejected rather than leaked.*/fileIds?: string[];+ /** Resumes only: the pending tool message (or assistant) the resume continues from. */+ parentMessageId?: string;prompt: string;+ /** Resume a run parked on a single tool approval (legacy, non-durable path). */+ resumeApproval?: ResumeApprovalParam;+ /** Batch form of `resumeApproval`. */+ resumeApprovals?: ResumeApprovalParam[];+ /** Resume a run parked on a client tool call with its result (e.g. askUserQuestion). */+ resumeToolResult?: ResumeToolResultParam;shareId: string;/** The prompt was queued behind a running turn and renders as its continuation. */steer?: boolean;/** Absent → the server creates a new visitor topic (counted against the topic cap). */topicId?: string | null;+ /**+ * The visitor's own approval mode. Tools granted by the share run their+ * normal `humanIntervention` policy, with the visitor as the approver.+ */+ userInterventionConfig?: UserInterventionConfig;}/**@@ -89,6 +108,43 @@ class ShareChatService {return await lambdaClient.shareChat.execAgent.mutate(params, options);}+ /**+ * Answer a pending intervention of the visitor's own share run through the+ * durable first-winner path — the visitor counterpart of+ * `aiAgentService.resolveAgentInterventionBySource`. `handled: false` means+ * the deployment has no durable store; resume through `execAgentTask`.+ */+ async resolveInterventionBySource(+ shareId: string,+ topicId: string,+ params: ResolveAgentInterventionBySourceParams,+ ): Promise<ResolveAgentInterventionBySourceResult> {+ const result = await lambdaClient.shareChat.resolveInterventionBySource.mutate({+ ...params,+ shareId,+ topicId,+ });++ if (!result.success) return { handled: false };++ return {+ execution: 'execution' in result ? result.execution : undefined,+ handled: true,+ state: result.state,+ };+ }++ /**+ * Stop the visitor's own run parked on a pending approval — the visitor+ * counterpart of `aiAgentService.stopPendingApproval`.+ */+ async stopPendingApproval(+ shareId: string,+ params: { batchId: string; operationId: string; toolMessageIds: string[]; topicId: string },+ ) {+ return await lambdaClient.shareChat.stopPendingApproval.mutate({ ...params, shareId });+ }+async getTopics(shareId: string) {return await lambdaClient.shareChat.getTopics.query({ shareId });}diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.tsindex f2eab2caffe..ce3cdb5376f 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts@@ -31,6 +31,16 @@ vi.mock('@/libs/trpc/client', () => ({},submitHeteroIntervention: { mutate: vi.fn().mockResolvedValue({ success: true }) },},+ shareChat: {+ resolveInterventionBySource: {+ mutate: vi.fn().mockResolvedValue({+ contractVersion: 2,+ status: 'unavailable',+ success: false,+ }),+ },+ stopPendingApproval: { mutate: vi.fn().mockResolvedValue({ success: true }) },+ },},}));@@ -61,6 +71,16 @@ beforeEach(() => {status: 'unavailable',success: false,});+ vi.mocked(lambdaClient.shareChat.resolveInterventionBySource.mutate)+ .mockReset()+ .mockResolvedValue({+ contractVersion: 2,+ status: 'unavailable',+ success: false,+ });+ vi.mocked(lambdaClient.shareChat.stopPendingApproval.mutate)+ .mockReset()+ .mockResolvedValue({ operationId: 'operation-share', success: true } as any);useChatStore.setState({updateTopicStatus: vi.fn().mockResolvedValue(undefined),questionSubmissions: {},@@ -1593,6 +1613,116 @@ describe('ConversationControl actions', () => {});});+ describe('share visitor', () => {+ const agentId = 'shared-agent';+ const topicId = 'visitor-topic';+ const context: ConversationContext = {+ agentId,+ agentShareId: 'share-1',+ scope: 'main',+ topicId,+ };+ const chatKey = messageMapKey(context);++ const seedShareCard = () => {+ const toolMessage = createMockMessage({+ id: 'tool-msg-share',+ pluginIntervention: {+ batchId: 'batch-share',+ operationId: 'operation-share',+ status: 'pending',+ },+ role: 'tool',+ tool_call_id: 'call-share',+ } as any);+ act(() => {+ useChatStore.setState({+ dbMessagesMap: { [chatKey]: [toolMessage] },+ messagesMap: { [chatKey]: [toolMessage] },+ });+ });+ };++ it('answers through the share mirror and resumes on the share gateway', async () => {+ const { result } = renderHook(() => useChatStore());+ seedShareCard();+ const executeGatewayAgentSpy = vi+ .spyOn(result.current, 'executeGatewayAgent')+ .mockResolvedValue({} as any);+ const updateTopicStatusSpy = vi.mocked(result.current.updateTopicStatus);+ updateTopicStatusSpy.mockClear();++ await act(async () => {+ await result.current.approveToolCalling('tool-msg-share', '', context);+ });++ expect(lambdaClient.shareChat.resolveInterventionBySource.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ action: { scope: 'once', type: 'approve_tool' },+ shareId: 'share-1',+ targets: [{ toolCallId: 'call-share', toolMessageId: 'tool-msg-share' }],+ topicId,+ }),+ );+ expect(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate).not.toHaveBeenCalled();+ // No durable store: the legacy resume goes out on the share gateway.+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ context,+ resumeApproval: expect.objectContaining({ decision: 'approved' }),+ }),+ );+ // The visitor's topic belongs to the creator: no owner-scoped write.+ expect(updateTopicStatusSpy).not.toHaveBeenCalled();+ });++ it.each([+ ['durable store', { contractVersion: 2, state: 'claimed', success: true }],+ ['legacy resume', { contractVersion: 2, status: 'unavailable', success: false }],+ ])(+ 'keeps a visitor\'s "don\'t ask again" in their own allow list (%s)',+ async (_label, resolution) => {+ const { result } = renderHook(() => useChatStore());+ seedShareCard();+ vi.mocked(lambdaClient.shareChat.resolveInterventionBySource.mutate).mockResolvedValue(+ resolution as any,+ );+ vi.spyOn(result.current, 'executeGatewayAgent').mockResolvedValue({} as any);+ const addToolToAllowList = vi.fn().mockResolvedValue(undefined);+ useUserStore.setState({ addToolToAllowList });++ await act(async () => {+ await result.current.approveToolCalling('tool-msg-share', '', context, {+ rememberToolKey: 'lobe-cloud-sandbox/runCommand',+ });+ });++ // A server-side `remember` would write the creator's allow list.+ expect(lambdaClient.shareChat.resolveInterventionBySource.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ action: { scope: 'once', type: 'approve_tool' } }),+ );+ expect(addToolToAllowList).toHaveBeenCalledWith('lobe-cloud-sandbox/runCommand');+ },+ );++ it('stops a parked share run through the share mirror', async () => {+ const { result } = renderHook(() => useChatStore());+ seedShareCard();++ await act(async () => {+ await result.current.stopPendingApproval(['tool-msg-share'], context);+ });++ expect(lambdaClient.shareChat.stopPendingApproval.mutate).toHaveBeenCalledWith({+ batchId: 'batch-share',+ operationId: 'operation-share',+ shareId: 'share-1',+ toolMessageIds: ['tool-msg-share'],+ topicId,+ });+ });+ });+describe('durable terminal source lifecycle', () => {const agentId = 'server-agent';const topicId = 'server-topic';diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.tsindex 4de7cdc2a2d..f0a2e161518 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts@@ -27,6 +27,7 @@ import {aiAgentService,type ResolveAgentInterventionBySourceResult,} from '@/services/aiAgent';+import { shareChatService } from '@/services/shareChat';import { getAgentStoreState } from '@/store/agent';import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';import { displayMessageSelectors, topicSelectors } from '@/store/chat/selectors';@@ -182,13 +183,25 @@ export class ConversationControlActionImpl {this.#interventionResolutionRequestIds.get(resolutionKey) ?? globalThis.crypto.randomUUID();this.#interventionResolutionRequestIds.set(resolutionKey, resolutionRequestId);- const result = await aiAgentService.resolveAgentInterventionBySource({+ const sourceParams = {action: params.action,batchId: first.batchId,operationId: first.operationId,resolutionRequestId,targets: sourceTargets,- });+ };+ // A share visitor answers their own share run through the share-authorized+ // mirror; the owner-scoped endpoint would reject them.+ const agentShareId = params.context?.agentShareId;+ const result = agentShareId+ ? params.context?.topicId+ ? await shareChatService.resolveInterventionBySource(+ agentShareId,+ params.context.topicId,+ sourceParams,+ )+ : ({ handled: false } as const)+ : await aiAgentService.resolveAgentInterventionBySource(sourceParams);if (result.handled) {this.#interventionResolutionRequestIds.delete(resolutionKey);if (result.state === 'claimed' && params.context) {@@ -233,6 +246,10 @@ export class ConversationControlActionImpl {* Gateway backend.*/#shouldUseGatewayResume = async (context: ConversationContext): Promise<boolean> => {+ // A share run only ever executes on the server through the share gateway;+ // the visitor has no local runtime nor access to the owner's agent config.+ if (context.agentShareId) return true;+const agentId = context.agentId;if (!agentId) return false;@@ -549,7 +566,9 @@ export class ConversationControlActionImpl {};#writeTopicStatus = (context: ConversationContext, status: ChatTopicStatus): void => {- if (!context.topicId) return;+ // A share visitor's topic belongs to the creator; the owner-scoped topic+ // write would be rejected, and the share page has no topic status UI.+ if (!context.topicId || context.agentShareId) return;const topicScope =context.scope === 'group' || context.scope === 'group_agent' ? context.scope : undefined;@@ -806,13 +825,18 @@ export class ConversationControlActionImpl {// the running marker intact and `#shouldUseGatewayResume` still flags// Gateway mode on retry.const pausedOpIds = this.#getRunningServerOps(effectiveContext).map((op) => op.id);+ // A share run belongs to the agent's owner, so a server-side `remember`+ // would write the OWNER's allow list (the share mirror rejects it). A+ // visitor's "don't ask again" approves once and lands in their own allow+ // list instead, which their share runs send as `userInterventionConfig`.+ const remembersOnServer = !!options?.rememberToolKey && !effectiveContext.agentShareId;try {const sourceResolution = await this.tryResolveAgentInterventionBySource({action: {...(options?.editedArguments && {edits: { [toolMessageId]: options.editedArguments },}),- scope: options?.rememberToolKey ? 'remember' : 'once',+ scope: remembersOnServer ? 'remember' : 'once',type: 'approve_tool',},context: effectiveContext,@@ -853,9 +877,9 @@ export class ConversationControlActionImpl {toolCallId,},});- if (options?.rememberToolKey) {- await useUserStore.getState().addToolToAllowList(options.rememberToolKey);- }+ }+ if (options?.rememberToolKey && !(sourceResolution.handled && remembersOnServer)) {+ await useUserStore.getState().addToolToAllowList(options.rememberToolKey);}this.#writeTopicStatus(effectiveContext, 'active');this.#completeOpsById(pausedOpIds);@@ -1010,12 +1034,10 @@ export class ConversationControlActionImpl {if (this.#discardAlreadyResolvedSource(sourceResolution)) return;if (!sourceResolution.handled) {- await aiAgentService.stopPendingApproval({- batchId,- operationId,- toolMessageIds: addressable,- topicId,- });+ const stopParams = { batchId, operationId, toolMessageIds: addressable, topicId };+ await (effectiveContext.agentShareId+ ? shareChatService.stopPendingApproval(effectiveContext.agentShareId, stopParams)+ : aiAgentService.stopPendingApproval(stopParams));}// Settle the cards locally. A group member's stop ends no stream this// client still listens on, so no refetch would ever land the aborted rowsdiff --git a/src/store/chat/slices/agentRun/actions/entries/questionSubmission.ts b/src/store/chat/slices/agentRun/actions/entries/questionSubmission.tsindex 4e166a70296..ed9f90f5459 100644--- a/src/store/chat/slices/agentRun/actions/entries/questionSubmission.ts+++ b/src/store/chat/slices/agentRun/actions/entries/questionSubmission.ts@@ -2,6 +2,7 @@ import type { ConversationContext, UIChatMessage } from '@lobechat/types';import type { AgentInterventionSourceAction } from '@/services/aiAgent';import { messageService } from '@/services/message';+import { shareChatService } from '@/services/shareChat';import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';import type { ChatStore } from '@/store/chat/store';import type { StoreSetter } from '@/store/types';@@ -56,7 +57,11 @@ export class QuestionSubmissionActionImpl {if (this.#get().questionSubmissions[id] === 'checking') return false;this.#setPhase(id, 'checking');try {- const messages = await messageService.getMessages({ ...context, skipWorks: true });+ // A share visitor can only read their own topic through the share mirror.+ const messages =+ context.agentShareId && context.topicId+ ? await shareChatService.getMessages(context.agentShareId, context.topicId)+ : await messageService.getMessages({ ...context, skipWorks: true });const message = messages.find((item) => item.id === id);if (!message?.pluginIntervention) throw new Error('Question resolution is unavailable');if (message.pluginIntervention.status === 'pending') {diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex c6e85f14fb2..0fd5700c12b 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -1008,8 +1008,10 @@ export class GatewayActionImpl {// Agent-share visitor surface: dispatch through the share-authorized mirror.// It accepts only the share-safe subset (prompt / topic / clientIds /- // the visitor's share-uploaded fileIds) — everything else (tools, devices, mentions) is- // decided server-side by the share config, never by this client.+ // the visitor's share-uploaded fileIds, plus the visitor's own approval+ // mode and their answers to this run's pending interventions) — everything+ // else (tools, devices, mentions) is decided server-side by the share+ // config, never by this client.const agentShareId = executionContext.agentShareId;const serverResult =@@ -1019,10 +1021,15 @@ export class GatewayActionImpl {{clientIds,fileIds,+ parentMessageId,prompt: message,+ resumeApproval,+ resumeApprovals,+ resumeToolResult,shareId: agentShareId,steer: metadata?.steer,topicId: executionContext.topicId,+ userInterventionConfig,},{ signal: abortSignal },)