🤯 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): share agents by link with visitor chat (#18998)
YuTengjing4b409744f2ae
diff --git a/apps/server/src/featureFlags/index.test.ts b/apps/server/src/featureFlags/index.test.tsindex 73d5d2a5ebc..a3eae66306f 100644--- a/apps/server/src/featureFlags/index.test.ts+++ b/apps/server/src/featureFlags/index.test.ts@@ -1,6 +1,20 @@-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { applyDevelopmentFeatureFlagDefaults } from './index';+const mockFindById = vi.fn();+vi.mock('@/database/models/user', () => ({+ UserModel: { findById: (...args: unknown[]) => mockFindById(...args) },+}));++const mockGetServerDB = vi.fn();+vi.mock('@/database/server', () => ({+ getServerDB: (...args: unknown[]) => mockGetServerDB(...args),+}));++const {+ applyDevelopmentFeatureFlagDefaults,+ clearFeatureFlagEmailCache,+ resolveEmailForEvaluation,+} = await import('./index');afterEach(() => {vi.unstubAllEnvs();@@ -48,3 +62,102 @@ describe('applyDevelopmentFeatureFlagDefaults', () => {).toEqual(['production-user']);});});++describe('resolveEmailForEvaluation', () => {+ beforeEach(() => {+ mockFindById.mockReset();+ mockGetServerDB.mockReset();+ mockGetServerDB.mockResolvedValue({});+ clearFeatureFlagEmailCache();+ });++ it('returns undefined without a userId, never touching UserModel', async () => {+ await expect(+ resolveEmailForEvaluation({ agent_share: ['[email protected]'] }),+ ).resolves.toBeUndefined();+ expect(mockFindById).not.toHaveBeenCalled();+ });++ it('never touches UserModel when every array flag only carries user IDs', async () => {+ await expect(+ resolveEmailForEvaluation(+ { agent_share: ['user-1', 'user-2'], workspace: ['user-3'] },+ 'user-1',+ ),+ ).resolves.toBeUndefined();+ expect(mockFindById).not.toHaveBeenCalled();+ });++ it('resolves the email when some flag array carries an email entry', async () => {+ mockFindById.mockResolvedValue({ email: '[email protected]' });++ await expect(+ resolveEmailForEvaluation({ agent_share: ['[email protected]', 'user-2'] }, 'user-1'),+ ).resolves.toBe('[email protected]');+ expect(mockFindById).toHaveBeenCalledWith({}, 'user-1');+ });++ it('ignores email entries in flags that are never evaluated against an email', async () => {+ // `workspace` is evaluated by user ID only, so an '@' there must not cost a+ // users-table read on every single flag evaluation.+ await expect(+ resolveEmailForEvaluation({ workspace: ['[email protected]'] }, 'user-1'),+ ).resolves.toBeUndefined();+ expect(mockFindById).not.toHaveBeenCalled();+ });++ it('reuses the cached email for repeated evaluations of the same user', async () => {+ mockFindById.mockResolvedValue({ email: '[email protected]' });+ const flags = { agent_share: ['[email protected]'] };++ await expect(resolveEmailForEvaluation(flags, 'user-1')).resolves.toBe('[email protected]');+ await expect(resolveEmailForEvaluation(flags, 'user-1')).resolves.toBe('[email protected]');++ expect(mockFindById).toHaveBeenCalledTimes(1);+ });++ it('caches per user rather than globally', async () => {+ mockFindById.mockResolvedValueOnce({ email: '[email protected]' });+ mockFindById.mockResolvedValueOnce({ email: '[email protected]' });+ const flags = { agent_share: ['[email protected]'] };++ await expect(resolveEmailForEvaluation(flags, 'user-1')).resolves.toBe('[email protected]');+ await expect(resolveEmailForEvaluation(flags, 'user-2')).resolves.toBe('[email protected]');+ await expect(resolveEmailForEvaluation(flags, 'user-1')).resolves.toBe('[email protected]');++ expect(mockFindById).toHaveBeenCalledTimes(2);+ });++ it('expires cached emails once the TTL has elapsed', async () => {+ vi.useFakeTimers();+ try {+ mockFindById.mockResolvedValue({ email: '[email protected]' });+ const flags = { agent_share: ['[email protected]'] };++ await resolveEmailForEvaluation(flags, 'user-1');+ vi.advanceTimersByTime(5 * 60 * 1000 + 1);+ await resolveEmailForEvaluation(flags, 'user-1');++ expect(mockFindById).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });++ it('swallows a lookup failure and returns undefined instead of throwing', async () => {+ mockFindById.mockRejectedValue(new Error('db unavailable'));++ await expect(+ resolveEmailForEvaluation({ agent_share: ['[email protected]'] }, 'user-1'),+ ).resolves.toBeUndefined();+ });++ it('does not cache a failed lookup, so a transient DB error is retried', async () => {+ const flags = { agent_share: ['[email protected]'] };+ mockFindById.mockRejectedValueOnce(new Error('db unavailable'));+ mockFindById.mockResolvedValueOnce({ email: '[email protected]' });++ await expect(resolveEmailForEvaluation(flags, 'user-1')).resolves.toBeUndefined();+ await expect(resolveEmailForEvaluation(flags, 'user-1')).resolves.toBe('[email protected]');+ });+});diff --git a/apps/server/src/featureFlags/index.ts b/apps/server/src/featureFlags/index.tsindex cefb4e634ec..81a020bac94 100644--- a/apps/server/src/featureFlags/index.ts+++ b/apps/server/src/featureFlags/index.ts@@ -119,11 +119,104 @@ export const getServerFeatureFlagsFromRuntimeConfig = async (userId?: string) =>return flags;};+/**+ * The only flags whose whitelist arrays are ever matched against an email —+ * see `mapFeatureFlagsEnvToState`, where they are the sole `evaluateFeatureFlag`+ * calls that receive `userEmail`. Every other flag is evaluated by user ID+ * alone, so an '@' in one of those arrays can never change an outcome and must+ * not be allowed to trigger a users-table read.+ */+const EMAIL_AWARE_FLAG_KEYS = ['agent_share'] as const satisfies readonly (keyof IFeatureFlags)[];++const EMAIL_CACHE_TTL_MS = 5 * 60 * 1000;+/**+ * Bounded so a burst of distinct users cannot grow the map without limit in a+ * long-lived server process. Eviction is plain insertion-order (oldest first),+ * which is enough here: entries are cheap and expire on their own anyway.+ */+const EMAIL_CACHE_MAX_ENTRIES = 1000;++const emailCache = new Map<string, { email: string | undefined; expiresAt: number }>();++const readCachedEmail = (userId: string) => {+ const cached = emailCache.get(userId);+ if (!cached) return;+ if (cached.expiresAt <= Date.now()) {+ emailCache.delete(userId);+ return;+ }+ return cached;+};++const writeCachedEmail = (userId: string, email: string | undefined) => {+ // Refresh insertion order so the entry counts as recently written.+ emailCache.delete(userId);+ emailCache.set(userId, { email, expiresAt: Date.now() + EMAIL_CACHE_TTL_MS });++ while (emailCache.size > EMAIL_CACHE_MAX_ENTRIES) {+ const oldest = emailCache.keys().next();+ if (oldest.done) break;+ emailCache.delete(oldest.value);+ }+};++/** Test-only escape hatch so cached emails cannot leak across test cases. */+export const clearFeatureFlagEmailCache = () => emailCache.clear();++/**+ * Whitelist arrays may hold emails as well as user IDs (admins configure+ * grayscale rollouts by email — see `evaluateFeatureFlag`). Feature flags are+ * evaluated on essentially every tRPC procedure, so this runs on the hot path+ * and is kept off the database twice over:+ *+ * 1. Only the two email-aware flags are inspected for an '@' entry, so the+ * common configuration (all booleans / user-ID arrays) never looks anything+ * up.+ * 2. Resolved emails are memoized per user for {@link EMAIL_CACHE_TTL_MS}, so+ * repeated evaluations within one user's session hit memory instead of the+ * users table. A stale email only matters while an admin is rolling out by+ * email to a user who just changed their address — bounded by the TTL.+ *+ * Exported (rather than kept module-private) so it has its own focused unit+ * tests instead of only being exercised indirectly through the full+ * RuntimeConfigProvider chain in `getServerFeatureFlagsStateFromRuntimeConfig`.+ */+export const resolveEmailForEvaluation = async (+ flags: IFeatureFlags,+ userId?: string,+): Promise<string | undefined> => {+ if (!userId) return;++ const hasEmailEntry = EMAIL_AWARE_FLAG_KEYS.some((key) => {+ const value = flags[key];+ return Array.isArray(value) && value.some((entry) => entry.includes('@'));+ });+ if (!hasEmailEntry) return;++ const cached = readCachedEmail(userId);+ if (cached) return cached.email;++ try {+ const { UserModel } = await import('@/database/models/user');+ const { getServerDB } = await import('@/database/server');+ const user = await UserModel.findById(await getServerDB(), userId);+ const email = user?.email ?? undefined;+ writeCachedEmail(userId, email);+ return email;+ } catch (error) {+ // Deliberately not cached: a transient DB failure must not pin the user to+ // "no email" (and therefore out of an email whitelist) for the whole TTL.+ debug('Failed to resolve user email for feature flag evaluation: %O', error);+ return;+ }+};+/*** Get server feature flags from RuntimeConfig and map them to state with user ID* @param userId - Optional user ID for user-specific feature flag evaluation*/export const getServerFeatureFlagsStateFromRuntimeConfig = async (userId?: string) => {const flags = await getServerFeatureFlagsFromRuntimeConfig(userId);- return mapFeatureFlagsEnvToState(flags, userId);+ const userEmail = await resolveEmailForEvaluation(flags, userId);+ return mapFeatureFlagsEnvToState(flags, userId, userEmail);};diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.tsindex 39fac6ff4c1..ad5d7ec83a0 100644--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts@@ -92,8 +92,10 @@ export class AgentRuntimeCoordinator {operationId: string,data: {agentConfig?: any;+ visitorRedaction?: { showErrorDetails?: boolean; showModelInfo?: boolean };mirrorToOperationId?: string;modelRuntimeConfig?: any;+ streamOwnerUserId?: string;userId?: string;workspaceId?: string;},diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.tsindex 32c72d28e86..99b6a10edbc 100644--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts@@ -39,9 +39,24 @@ export interface AgentOperationMetadata {mirrorToOperationId?: string;modelRuntimeConfig?: any;status: AgentState['status'];+ /**+ * Gateway WS channel owner when it differs from the executing user. For+ * shared-agent visitor runs the operation EXECUTES as the creator+ * (`userId`), but only the visitor may subscribe to its stream — the+ * gateway registers the channel under this id and rejects other subs.+ */+ streamOwnerUserId?: string;totalCost: number;totalSteps: number;userId?: string;+ /**+ * Visitor-facing redaction policy for a shared-agent visitor run, mirrored+ * from the share's `AgentShareConfig`. Persisted alongside+ * {@link streamOwnerUserId} so a queue worker that never ran this op's init+ * can still apply the OWNER-configured policy instead of falling back to the+ * fail-closed full strip.+ */+ visitorRedaction?: { showErrorDetails?: boolean; showModelInfo?: boolean };/*** Workspace the operation runs in (null/undefined = personal). Persisted so* queue workers (e.g. QStash `runStep`) can reconstruct a workspace-scoped@@ -249,6 +264,9 @@ export class AgentStateManager {return {agentConfig: metadata.agentConfig ? JSON.parse(metadata.agentConfig) : undefined,+ visitorRedaction: metadata.visitorRedaction+ ? JSON.parse(metadata.visitorRedaction)+ : undefined,createdAt: metadata.createdAt,lastActiveAt: metadata.lastActiveAt,modelRuntimeConfig: metadata.modelRuntimeConfig@@ -256,6 +274,7 @@ export class AgentStateManager {: undefined,mirrorToOperationId: metadata.mirrorToOperationId || undefined,status: metadata.status as AgentState['status'],+ streamOwnerUserId: metadata.streamOwnerUserId || undefined,totalCost: parseFloat(metadata.totalCost) || 0,totalSteps: parseInt(metadata.totalSteps) || 0,userId: metadata.userId,@@ -274,8 +293,10 @@ export class AgentStateManager {operationId: string,data: {agentConfig?: any;+ visitorRedaction?: { showErrorDetails?: boolean; showModelInfo?: boolean };mirrorToOperationId?: string;modelRuntimeConfig?: any;+ streamOwnerUserId?: string;userId?: string;workspaceId?: string;},@@ -285,11 +306,13 @@ export class AgentStateManager {try {const metadata: AgentOperationMetadata = {agentConfig: data.agentConfig,+ visitorRedaction: data.visitorRedaction,createdAt: new Date().toISOString(),lastActiveAt: new Date().toISOString(),mirrorToOperationId: data.mirrorToOperationId,modelRuntimeConfig: data.modelRuntimeConfig,status: 'idle',+ streamOwnerUserId: data.streamOwnerUserId,totalCost: 0,totalSteps: 0,userId: data.userId,@@ -306,12 +329,15 @@ export class AgentStateManager {};if (metadata.userId) redisData.userId = metadata.userId;+ if (metadata.streamOwnerUserId) redisData.streamOwnerUserId = metadata.streamOwnerUserId;if (metadata.workspaceId) redisData.workspaceId = metadata.workspaceId;if (metadata.mirrorToOperationId)redisData.mirrorToOperationId = metadata.mirrorToOperationId;if (metadata.modelRuntimeConfig)redisData.modelRuntimeConfig = JSON.stringify(metadata.modelRuntimeConfig);if (metadata.agentConfig) redisData.agentConfig = JSON.stringify(metadata.agentConfig);+ if (metadata.visitorRedaction)+ redisData.visitorRedaction = JSON.stringify(metadata.visitorRedaction);await this.redis.hmset(metaKey, redisData);await this.redis.expire(metaKey, this.DEFAULT_TTL);diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.tsindex 56b4bee072f..c65565e0e5e 100644--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts@@ -1,12 +1,23 @@import type { ToolExecuteData } from '@lobechat/agent-gateway-client';+import type { ChatMessageError } from '@lobechat/types';import debug from 'debug';import urlJoin from 'url-join';+import { sanitizeVisitorError } from '@/database/models/message';++import {+ buildPublicEndEventData,+ buildPublicInitEventData,+ FULL_STRIP_REDACTION,+ type GatewayVisitorRedaction,+ isShareVisitorInit,+ resolveRedactionFromState,+ sanitizeGatewayEventData,+} from './gatewayVisitorRedaction';import {getDefaultReasonDetail,type StreamChunkData,type StreamEvent,- stripFinalStateInEventData,} from './StreamEventManager';import type { IStreamEventManager, PublishAgentRuntimeEndParams } from './types';@@ -50,6 +61,27 @@ export class GatewayStreamNotifier implements IStreamEventManager {/** In-flight resolutions, deduped per op so concurrent events share one read. */private mirrorResolving = new Map<string, Promise<string | undefined>>();+ /**+ * `operationId → visitor redaction policy` for confirmed shared-agent visitor+ * runs. `step_start` events carry neither `streamOwnerUserId` (only on+ * `agent_runtime_init`'s `initialState`) nor `finalState` (only on+ * `agent_runtime_end` / `step_complete`), so this per-operation entry is the+ * only signal `pushEvent` has for scrubbing `uiMessages` on those events.+ * Mirrors `mirrorTargets`'s two population paths:+ * - fast path: set at `publishAgentRuntimeInit` / `publishAgentRuntimeEnd`+ * from the state's `metadata.agentShareVisitor`, so the share's real+ * `showModelInfo` / `showErrorDetails` config is honored.+ * - queue path: lazily resolved from persisted op metadata via+ * `resolvePersistedShareVisitor`, which can only tell share-or-not — it+ * therefore falls back to {@link FULL_STRIP_REDACTION}.+ * Cleared at `publishAgentRuntimeEnd`.+ */+ private shareVisitorOps = new Map<string, GatewayVisitorRedaction>();+ /** Ops whose share-visitor status has been resolved (confirmed share OR not). */+ private shareVisitorResolved = new Set<string>();+ /** In-flight resolutions, deduped per op so concurrent events share one read. */+ private shareVisitorResolving = new Map<string, Promise<GatewayVisitorRedaction>>();+constructor(private inner: IStreamEventManager,private gatewayUrl: string,@@ -60,6 +92,16 @@ export class GatewayStreamNotifier implements IStreamEventManager {* events onto the supervisor channel. Omitted ⇒ in-process map only.*/private resolveMirrorTarget?: (operationId: string) => Promise<string | undefined>,+ /**+ * Resolves an op's persisted share-visitor redaction policy (from+ * `streamOwnerUserId` + `visitorRedaction` on op metadata); `null` for a+ * normal run. Lets a queue worker — which never ran the op's init — still+ * scrub events for that op. Omitted ⇒ in-process map only (safe: init+ * always precedes events for the op it created).+ */+ private resolvePersistedShareVisitor?: (+ operationId: string,+ ) => Promise<GatewayVisitorRedaction>,) {log('Gateway notifier initialized: %s', gatewayUrl);}@@ -121,17 +163,37 @@ export class GatewayStreamNotifier implements IStreamEventManager {// uses the non-lossy request lane: ordinary stream events may be dropped at// MAX_INFLIGHT, but dropping this control-plane barrier would recreate the// exact resume-before-init race under load.+ // Record share-visitor status up front (definitively known from+ // `initialState` here) so every later event for this op — including+ // `step_start`, which carries neither `streamOwnerUserId` nor `finalState`+ // — is sanitized without re-resolving.+ const initRedaction = resolveRedactionFromState(initialState);+ const isShareInit = isShareVisitorInit(initialState);+ if (initRedaction || isShareInit) {+ // Fail closed: `streamOwnerUserId` alone (without a readable+ // `metadata.agentShareVisitor`) still means a visitor is on the other end.+ this.shareVisitorOps.set(operationId, initRedaction ?? FULL_STRIP_REDACTION);+ }+ this.shareVisitorResolved.add(operationId);+try {+ // The gateway DO requires the subscriber JWT's `sub` to equal the userId+ // registered here. `streamOwnerUserId` (shared-agent visitor runs) takes+ // precedence: the op executes as the creator, but only the visitor may+ // subscribe to its stream.await this.httpPostAwait('/api/operations/init', {operationId,- userId: initialState?.userId || 'unknown',+ userId: initialState?.streamOwnerUserId || initialState?.userId || 'unknown',});} catch (error) {log('Gateway /api/operations/init failed: %O', error);}void this.pushEvent(operationId, {- data: initialState,+ // Share-visitor runs must not receive the creator's raw operation+ // metadata (agentConfig / system prompt, modelRuntimeConfig, userId,+ // workspaceId) over their WS channel — see `buildPublicInitEventData`.+ data: isShareInit ? buildPublicInitEventData(initialState) : initialState,operationId,stepIndex: 0,timestamp: Date.now(),@@ -145,21 +207,55 @@ export class GatewayStreamNotifier implements IStreamEventManager {const { operationId, stepIndex, finalState, reason, reasonDetail, uiMessages } = params;const result = await this.inner.publishAgentRuntimeEnd(params);- const effectiveReasonDetail = reasonDetail || getDefaultReasonDetail(finalState, reason);- const errorType = finalState?.error?.type || finalState?.error?.errorType;+ const endRedaction = resolveRedactionFromState(finalState);++ // `errorType`/`reasonDetail` both read `finalState.error` — the same+ // `formatErrorForState` shape `sanitizeVisitorError` projects for+ // `toVisitorMessage` — but land as SIBLINGS of `finalState` on+ // `endEventData` below, so `buildPublicEndEventData`'s wholesale+ // `finalState` drop does not touch them. For a share-visitor run, run the+ // SAME classification here rather than trusting the raw `reasonDetail` the+ // caller passed in: this Gateway push is the enforcement boundary+ // regardless of what upstream already computed from the unredacted error.+ const rawErrorType = finalState?.error?.type ?? finalState?.error?.errorType;+ const safeError = endRedaction+ ? sanitizeVisitorError(+ rawErrorType === undefined+ ? undefined+ : ({ message: finalState?.error?.message, type: rawErrorType } as ChatMessageError),+ endRedaction,+ )+ : undefined;+ const effectiveReasonDetail = endRedaction+ ? safeError?.message || getDefaultReasonDetail(undefined, reason)+ : reasonDetail || getDefaultReasonDetail(finalState, reason);+ const errorType = endRedaction ? safeError?.type : rawErrorType;++ // `finalState` already tells us definitively whether this is a share run,+ // so record it before pushing — covers the case where this runs in a+ // process that never saw the op's `publishAgentRuntimeInit` (queue mode)+ // without waiting on the async metadata resolver.+ if (endRedaction) this.shareVisitorOps.set(operationId, endRedaction);+ this.shareVisitorResolved.add(operationId);++ // Forward `uiMessages` to the gateway push channel so terminal-state+ // clients consuming /push-event get the canonical UIChatMessage[]+ // snapshot — the final step has no later step_start to carry a fresh+ // snapshot, so dropping it here would break the SoT contract.+ const endEventData = {+ errorType,+ finalState,+ reason,+ reasonDetail: effectiveReasonDetail,+ ...(uiMessages !== undefined && { uiMessages }),+ };void this.pushEvent(operationId, {- // Forward `uiMessages` to the gateway push channel so terminal-state- // clients consuming /push-event get the canonical UIChatMessage[]- // snapshot — the final step has no later step_start to carry a fresh- // snapshot, so dropping it here would break the SoT contract.- data: {- errorType,- finalState,- reason,- reasonDetail: effectiveReasonDetail,- ...(uiMessages !== undefined && { uiMessages }),- },+ // Share-visitor runs must not receive the creator's raw AgentState+ // (metadata.userMemory / metadata.agentConfig, systemRole,+ // userInterventionConfig, ...) over their WS channel — see+ // `buildPublicEndEventData`.+ data: endRedaction ? buildPublicEndEventData(endEventData) : endEventData,operationId,stepIndex,timestamp: Date.now(),@@ -171,6 +267,9 @@ export class GatewayStreamNotifier implements IStreamEventManager {this.mirrorTargets.delete(operationId);this.mirrorResolved.delete(operationId);this.mirrorResolving.delete(operationId);+ this.shareVisitorOps.delete(operationId);+ this.shareVisitorResolved.delete(operationId);+ this.shareVisitorResolving.delete(operationId);return result;}@@ -224,14 +323,29 @@ export class GatewayStreamNotifier implements IStreamEventManager {// ─── Gateway HTTP helpers ───private async pushEvent(operationId: string, event: Record<string, unknown>): Promise<void> {+ // Resolve share-visitor status BEFORE building the sanitized payload — the+ // synchronous fast path (the common case: `publishAgentRuntimeInit` /+ // `publishAgentRuntimeEnd` always mark this resolved before calling+ // `pushEvent`) keeps this whole method's pre-`mirrorTargets.get` prefix+ // synchronous, preserving the ordering the mirror-cleanup-after-call+ // pattern in `publishAgentRuntimeEnd` relies on. Only a queue worker's+ // first event for an op it never initialized falls through to the async+ // `resolveShareVisitor` — see its fail-closed contract.+ const known = this.isShareVisitorKnown(operationId);+ const redaction = known === undefined ? await this.resolveShareVisitor(operationId) : known;+// Mirror the Redis publisher's chokepoint — strip// `finalState.messages` + tool-set fields off the gateway WS push// payload too. The gateway forwards events verbatim to clients, and// downstream consumers don't read these fields, so carrying them// would re-introduce the same multi-megabyte serialization that- // crashed the xadd path.+ // crashed the xadd path. Additionally, for a shared-agent visitor run,+ // drop `finalState` wholesale and scrub the rest — see+ // `sanitizeGatewayEventData`.const sanitizedEvent =- event.data === undefined ? event : { ...event, data: stripFinalStateInEventData(event.data) };+ event.data === undefined+ ? event+ : { ...event, data: sanitizeGatewayEventData(event.data, redaction, event.type) };const pushes: Promise<void>[] = [this.httpPost('/api/operations/push-event', {event: sanitizedEvent,@@ -302,6 +416,63 @@ export class GatewayStreamNotifier implements IStreamEventManager {return pending;}+ /**+ * Synchronous share-visitor lookup. Returns `undefined` only when a queue+ * worker resolver is configured AND this op's status hasn't been resolved yet+ * (its first event, in a process that never ran its init) — the caller must+ * then fall back to the async {@link resolveShareVisitor}.+ *+ * Without a configured resolver (non-queue mode), an unresolved op is treated+ * as a normal run synchronously rather than going through the async path at+ * all — this keeps `pushEvent`'s common-case prefix fully synchronous,+ * matching `mirrorTargets.get`'s behavior and the `stream_end` await-ordering+ * contract on `publishStreamEvent`. It's also the correct default: without a+ * resolver this notifier only ever sees events for ops it initialized itself,+ * and init marks resolved synchronously before any event is pushed.+ */+ private isShareVisitorKnown(operationId: string): GatewayVisitorRedaction | undefined {+ const cached = this.shareVisitorOps.get(operationId);+ if (cached) return cached;+ if (this.shareVisitorResolved.has(operationId)) return null;+ if (!this.resolvePersistedShareVisitor) return null;+ return undefined;+ }++ /**+ * Resolve and cache whether an op is a shared-agent visitor run, from+ * persisted metadata (`streamOwnerUserId`). Only reached when a resolver is+ * configured and the op is still unresolved (see {@link isShareVisitorKnown}).+ * Deduped so concurrent events for the same unresolved op share one metadata+ * read.+ *+ * Fails closed: a resolution error returns the full strip rather than risk+ * leaking the creator's identity, and deliberately does NOT cache that+ * outcome as resolved, so the next event retries once the transient failure+ * clears.+ */+ private resolveShareVisitor(operationId: string): Promise<GatewayVisitorRedaction> {+ if (!this.resolvePersistedShareVisitor) return Promise.resolve(null);++ let pending = this.shareVisitorResolving.get(operationId);+ if (!pending) {+ pending = this.resolvePersistedShareVisitor(operationId)+ .then((resolved) => {+ this.shareVisitorResolved.add(operationId);+ this.shareVisitorResolving.delete(operationId);+ if (!resolved) return null;+ this.shareVisitorOps.set(operationId, resolved);+ return resolved;+ })+ .catch((error) => {+ this.shareVisitorResolving.delete(operationId);+ log('[%s] Share visitor resolution failed, failing closed: %O', operationId, error);+ return FULL_STRIP_REDACTION;+ });+ this.shareVisitorResolving.set(operationId, pending);+ }+ return pending;+ }+/*** POST that surfaces errors back to the caller (no swallow). Used for* request-response style pushes like tool_execute where the caller needsdiff --git a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.tsindex 59a37c96a8d..44b6b7e8316 100644--- a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts+++ b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts@@ -125,19 +125,23 @@ export class InMemoryAgentStateManager implements IAgentStateManager {operationId: string,data: {agentConfig?: any;+ visitorRedaction?: { showErrorDetails?: boolean; showModelInfo?: boolean };mirrorToOperationId?: string;modelRuntimeConfig?: any;+ streamOwnerUserId?: string;userId?: string;workspaceId?: string;},): Promise<void> {const metadata: AgentOperationMetadata = {agentConfig: data.agentConfig,+ visitorRedaction: data.visitorRedaction,createdAt: new Date().toISOString(),lastActiveAt: new Date().toISOString(),mirrorToOperationId: data.mirrorToOperationId,modelRuntimeConfig: data.modelRuntimeConfig,status: 'idle',+ streamOwnerUserId: data.streamOwnerUserId,totalCost: 0,totalSteps: 0,userId: data.userId,diff --git a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.tsindex 5f986f04bfa..35a515e9386 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts@@ -3,7 +3,7 @@ import { type ChatToolPayload } from '@lobechat/types';import { describe, expect, it, vi } from 'vitest';import { type RuntimeExecutorContext } from '../context';-import { buildServerVirtualSubAgentRunner } from '../executorHelpers';+import { buildServerAgentMemberRunner, buildServerVirtualSubAgentRunner } from '../executorHelpers';/*** The parent model a spawned `callSubAgent` follows must be the model the@@ -81,3 +81,48 @@ describe('buildServerVirtualSubAgentRunner sub-agent model resolution', () => {);});});++// Fail-close regression for share-visitor runs: the child run spawned by+// either runner does not inherit the parent's shareGate, so for a run with+// `ctx.agentShareVisitor` set, no runner may be built at all.+describe('runner builders fail closed for share-visitor runs', () => {+ const shareCtx = {+ agentShareVisitor: {+ agentId: 'agent-1',+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ execGroupMember: vi.fn(),+ execVirtualSubAgent: vi.fn(),+ messageModel: { create: vi.fn() },+ operationId: 'parent-op',+ topicId: 'topic-1',+ } as unknown as RuntimeExecutorContext;++ const state = {+ metadata: { agentId: 'agent-1', groupId: 'group-1', topicId: 'topic-1' },+ operationId: 'parent-op',+ } as unknown as AgentState;++ it('buildServerVirtualSubAgentRunner returns undefined when agentShareVisitor is set', () => {+ expect(+ buildServerVirtualSubAgentRunner(+ shareCtx,+ state,+ { id: 'tool-call-1' } as ChatToolPayload,+ 'parent-message-1',+ ),+ ).toBeUndefined();+ });++ it('buildServerAgentMemberRunner returns undefined when agentShareVisitor is set', () => {+ expect(+ buildServerAgentMemberRunner(+ shareCtx,+ state,+ { id: 'tool-call-1' } as ChatToolPayload,+ 'parent-message-1',+ ),+ ).toBeUndefined();+ });+});diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.tsindex a20272320b7..9efa8f8ad4b 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts@@ -31,6 +31,7 @@ import {chatSpanName,tracer as agentRuntimeTracer,} from '@lobechat/observability-otel/modules/agent-runtime';+import { toAgentShareVisitorIds } from '@lobechat/types';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';@@ -283,6 +284,12 @@ export class ServerLLMTransport implements LLMTransport {// state.metadata into the attempt so the LLM-call metadata can surface them// for auditing and spend attribution.clientIp: input.state.metadata?.clientIp,+ // Projected, not spread: `state.metadata.agentShareVisitor` also carries+ // the run's tool/memory restrictions, which have no place in billing+ // metadata. Only the three attribution ids travel.+ agentShareVisitorIds: input.state.metadata?.agentShareVisitor+ ? toAgentShareVisitorIds(input.state.metadata.agentShareVisitor)+ : undefined,topicId: input.state.metadata?.topicId,trigger: input.state.metadata?.trigger,userAgent: input.state.metadata?.userAgent,diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.tsindex 68a260e3525..7fd888d493c 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts@@ -82,7 +82,10 @@ export class ServerMessageTransport implements MessageTransport {}async deleteMessage(id: string): Promise<void> {- await this.messageModel.deleteMessage(id);+ // Runtime cleanup path (orphaned placeholders / approval teardown). Agent-share+ // visitor turns run under the creator's identity, so the runtime must be able to+ // delete rows the creator-facing delete guard fails closed on.+ await this.messageModel.deleteMessage(id, { includeShareVisitor: true });}async findToolMessageIdByToolCallId(@@ -117,6 +120,12 @@ export class ServerMessageTransport implements MessageTransport {options?: QueryMessagesOptions,): Promise<UIChatMessage[]> {const messages = await this.messageModel.query(params, {+ // Executors only ever read the operation's own, already-authorized topic.+ // An agent-share visitor run executes under the CREATOR's identity, so+ // without this opt-in `query()`'s creator-facing agent-share exclusion+ // would blank the visitor's conversation mid-run (see `tool.ts`, which+ // re-reads `state.messages` from the DB after every tool call).+ allowShareVisitor: true,postProcessUrl: options?.resolveAssetUrls ? this.options.postProcessUrl : undefined,});diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.tsindex 43f863bc02f..163a75b2d29 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.ts@@ -15,6 +15,10 @@ const fallbackResult = (error: string): ExecSubAgentResult => ({threadId: '',});+const shareGateBlockedResult = fallbackResult(+ 'Sub-agent dispatch is not available for a shared-agent visitor run.',+);+/*** Server {@link SubAgentTransport} adapter — delegates child-run creation to* callbacks injected by AiAgentService while the package owns executor flow.@@ -23,12 +27,23 @@ export class ServerSubAgentTransport implements SubAgentTransport {constructor(private readonly ctx: RuntimeExecutorContext) {}async execSubAgent(params: ExecSubAgentParams): Promise<ExecSubAgentResult> {+ // Agent share (defensive layer): a share-visitor run's `ctx.agentShareVisitor` is+ // set from `state.metadata.agentShareVisitor` (see AgentRuntimeService).+ // `callSubAgent`/`callAgent` children built via `execAgentThreadRun` don't+ // thread the parent's `shareGate` through — they'd otherwise execute with+ // the CREATOR's full, unrestricted tool/file/memory surface. The+ // assembly-time defense (the shareGate tool allowlist + `stripSubAgentDispatchApis`)+ // already keeps `callSubAgent` out of the model's tool list for a share+ // run; this is the fail-closed backstop in case that surface is ever+ // reached some other way (e.g. a stale/replayed tool call).+ if (this.ctx.agentShareVisitor) return shareGateBlockedResult;if (!this.ctx.execSubAgent) return fallbackResult('Sub-agent dispatch is not available.');return this.ctx.execSubAgent(params);}async execVirtualSubAgent(params: ExecVirtualSubAgentParams): Promise<ExecSubAgentResult> {+ if (this.ctx.agentShareVisitor) return shareGateBlockedResult;if (!this.ctx.execVirtualSubAgent) {return fallbackResult('Virtual sub-agent dispatch is not available.');}diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.tsindex 7f0e3b2fb27..1c9422f55a2 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts@@ -206,6 +206,9 @@ export class ServerToolTransport implements ToolTransport {chatToolPayload,context.parentMessageId,),+ // Share-visitor marker: lets `BuiltinToolsExecutor.execute`+ // re-apply the share data-tool gate at the actual dispatch site.+ agentShareVisitor: this.ctx.agentShareVisitor,...(agentVisibility !== undefined && { agentVisibility }),// Assistant message owning this tool call (≠ source user message).assistantMessageId: context.parentMessageId,diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.tsindex cb1c8a34997..5c334b2193b 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts@@ -55,7 +55,11 @@ const resolved = {const createAttempt = (runCallbacks: (options: ChatMethodOptions) => Promise<void>,blobStore?: BlobStore,- attemptOverrides?: { clientIp?: string; userAgent?: string },+ attemptOverrides?: {+ clientIp?: string;+ agentShareVisitorIds?: { agentId: string; shareId: string; visitorUserId: string };+ userAgent?: string;+ },) => {const publishStreamChunk = vi.fn().mockResolvedValue('event-1');const streamManager = {@@ -199,6 +203,36 @@ describe('ServerCallLlmAttempt', () => {);});+ // A share run is billed to the CREATOR's account, so without this the spend+ // row is indistinguishable from the creator's own usage.+ it('forwards share attribution into the chat call metadata', async () => {+ const { attempt, chat } = createAttempt(+ async ({ callback }) => {+ await callback?.onText?.('Answer');+ await callback?.onCompletion?.({ text: '', usage: { totalOutputTokens: 1 } });+ },+ undefined,+ {+ agentShareVisitorIds: {+ agentId: 'agt_shared',+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ },+ );++ await attempt.execute();++ expect(chat).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ metadata: expect.objectContaining({+ agentShare: { agentId: 'agt_shared', shareId: 'share-1', visitorUserId: 'visitor-1' },+ }),+ }),+ );+ });+it('leaves clientIp / userAgent metadata undefined when not provided', async () => {const { attempt, chat } = createAttempt(async ({ callback }) => {await callback?.onText?.('Answer');diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.tsindex 2a7ddc4479c..7650cbbec58 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts@@ -15,6 +15,7 @@ import {ModelRefusalError,} from '@lobechat/model-runtime';import type {+ AgentShareVisitorIds,ChatImageItem,ChatToolPayload,GroundingSearch,@@ -38,6 +39,13 @@ import {import type { ServerCallLlmTooling } from './serverCallLlmTooling';interface CreateServerCallLlmAttemptInput {+ /**+ * Shared-agent attribution for a visitor run. The call is billed to the+ * share's CREATOR, so without this the spend row is indistinguishable from+ * the creator's own usage. Only ids — never the share's tool/memory grants;+ * the caller projects with `toAgentShareVisitorIds`.+ */+ agentShareVisitorIds?: AgentShareVisitorIds;attempt: number;blobStore?: BlobStore;chatPayload: ChatStreamPayload;@@ -152,6 +160,7 @@ export class ServerCallLlmAttempt {private usage?: ModelUsage;constructor({+ agentShareVisitorIds,attempt,blobStore,chatPayload,@@ -182,6 +191,7 @@ export class ServerCallLlmAttempt {this.provider = provider;this.resolved = resolved;this.runtimeMetadata = {+ agentShare: agentShareVisitorIds,clientIp,operationId: ctx.operationId,topicId,diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.tsnew file mode 100644index 00000000000..5f38d6583c6--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.ts@@ -0,0 +1,123 @@+import type { AgentState, CallLLMPayload } from '@lobechat/agent-runtime';+import type { ResolvedToolSet } from '@lobechat/context-engine';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { RuntimeExecutorContext } from '../context';+import { buildServerCallLlmContext } from './serverCallLlmContextBuilder';+import type { ServerCallLlmTooling } from './serverCallLlmTooling';++const getInfoForAIGenerationMock = vi.hoisted(() => vi.fn());+const getUserSettingsMock = vi.hoisted(() => vi.fn());+const resolveServerCallLlmContextHintsMock = vi.hoisted(() => vi.fn());+const serverMessagesEngineMock = vi.hoisted(() => vi.fn());+const marketCredsListMock = vi.hoisted(() => vi.fn());++vi.mock('@/database/models/user', () => ({+ UserModel: class {+ static getInfoForAIGeneration = getInfoForAIGenerationMock;+ getUserSettings = getUserSettingsMock;+ },+}));++vi.mock('@/server/services/market', () => ({+ MarketService: class {+ market = {+ creds: { list: marketCredsListMock },+ organizations: { creds: () => ({ list: marketCredsListMock }) },+ };+ },+}));++vi.mock('@/config/composio', () => ({+ composioEnv: { COMPOSIO_API_KEY: undefined },+}));++vi.mock('./serverCallLlmContextHints', () => ({+ resolveServerCallLlmContextHints: resolveServerCallLlmContextHintsMock,+}));++vi.mock('@/server/modules/Mecha/ContextEngineering', () => ({+ serverMessagesEngine: serverMessagesEngineMock,+}));++const createCtx = (overrides: Partial<RuntimeExecutorContext> = {}): RuntimeExecutorContext =>+ ({+ agentConfig: { chatConfig: {}, files: [], knowledgeBases: [] } as any,+ messageModel: {} as RuntimeExecutorContext['messageModel'],+ operationId: 'operation-1',+ serverDB: {} as RuntimeExecutorContext['serverDB'],+ stepIndex: 0,+ streamManager: {} as RuntimeExecutorContext['streamManager'],+ toolExecutionService: {} as RuntimeExecutorContext['toolExecutionService'],+ userId: 'creator-1',+ ...overrides,+ }) satisfies RuntimeExecutorContext;++const llmPayload = { messages: [] } as unknown as CallLLMPayload;+const state = { metadata: {} } as unknown as AgentState;+const tooling = {+ resolved: {+ enabledToolIds: [],+ manifestMap: {},+ promptManifestMap: {},+ sourceMap: {},+ tools: [],+ } as ResolvedToolSet,+} as unknown as ServerCallLlmTooling;++beforeEach(() => {+ vi.clearAllMocks();++ getInfoForAIGenerationMock.mockResolvedValue({+ responseLanguage: 'en-US',+ userName: 'Some Name',+ });+ getUserSettingsMock.mockResolvedValue({});+ marketCredsListMock.mockResolvedValue({ data: [] });+ serverMessagesEngineMock.mockResolvedValue([]);+ resolveServerCallLlmContextHintsMock.mockResolvedValue({+ capabilities: {+ isCanUseAudio: () => false,+ isCanUseFC: () => false,+ isCanUseVideo: () => false,+ isCanUseVision: () => false,+ },+ messagesForContext: [],+ shouldReplayAssistantReasoning: false,+ });+});++describe('buildServerCallLlmContext - {{username}}/{{language}} placeholder source', () => {+ it('resolves user info from the creator when the run is not a share-visitor run', async () => {+ await buildServerCallLlmContext({+ ctx: createCtx(),+ llmPayload,+ model: 'gpt-4',+ provider: 'openai',+ state,+ tooling,+ });++ expect(getInfoForAIGenerationMock).toHaveBeenCalledWith(expect.anything(), 'creator-1');+ });++ it('resolves user info from the VISITOR, not the creator, on a share-visitor run', async () => {+ await buildServerCallLlmContext({+ ctx: createCtx({+ agentShareVisitor: {+ agentId: 'agent-1',+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ }),+ llmPayload,+ model: 'gpt-4',+ provider: 'openai',+ state,+ tooling,+ });++ expect(getInfoForAIGenerationMock).toHaveBeenCalledWith(expect.anything(), 'visitor-1');+ expect(getInfoForAIGenerationMock).not.toHaveBeenCalledWith(expect.anything(), 'creator-1');+ });+});diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex 4f85ca991f0..7f8370d8391 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -117,27 +117,65 @@ export const buildServerCallLlmContext = async ({if (!alreadyHasTopicRefs && ctx.serverDB && ctx.userId) {const topicModel = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId);const messageModel = new MessageModelClass(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const agentShareVisitor = ctx.agentShareVisitor;+ // Topic references are limited to the visitor's own topics in shared runs.+ // `TopicModel`'s built-in ownership scoping is not sufficient here — the+ // rows are owned by the CREATOR, so every one of the creator's private+ // topics would otherwise be addressable by a `<refer_topic>` tag the+ // visitor typed. Match the visitor/agent pairing of the active share+ // instead: a visitor topic is tied to its share purely through+ // `(agentId, senderId)`, since `agent_shares` is 1:1 per agent.+ //+ // Known gap: a topic created before the owner paused the share still+ // matches `(agentId, senderId)` for a returning visitor, because topics+ // carry no share-instance column. Such a topic is the SAME visitor's own+ // prior conversation with the SAME agent, so this leaks nothing across+ // identities — it only means old context can resurface once the share is+ // turned back on.+ const isTopicVisibleToRun = (+ topic: { agentId?: string | null; senderId?: string | null } | null | undefined,+ ): boolean => {+ if (!agentShareVisitor) return true;+ return (+ topic?.senderId === agentShareVisitor.visitorUserId &&+ topic?.agentId === agentShareVisitor.agentId+ );+ };topicReferences = await resolveTopicReferences(messagesForContext as Array<{ content: string | unknown }>,- async (topicId) => topicModel.findById(topicId),async (topicId) => {const topic = await topicModel.findById(topicId);+ return isTopicVisibleToRun(topic) ? topic : null;+ },+ async (topicId) => {+ const topic = await topicModel.findById(topicId);+ if (!isTopicVisibleToRun(topic)) return [];+return messageModel.query({agentId: topic?.agentId ?? undefined,groupId: topic?.groupId ?? undefined,topicId,},- { postProcessUrl: buildPostProcessUrl(ctx) },+ // `isTopicVisibleToRun` above already proved this referenced topic is+ // the SAME visitor's own conversation with the SAME agent, so the+ // creator-facing agent-share exclusion must not apply here.+ { allowShareVisitor: true, postProcessUrl: buildPostProcessUrl(ctx) },);},);}// Fetch agent documents for context injection.+ // A share visitor run never sees the creator's agent context documents.+ // `applyShareGateToAgentConfig` already blanks `agentConfig.files` /+ // `knowledgeBases`, but this source is fetched independently of agentConfig,+ // so it needs its own gate. Fail closed unconditionally: the share config has+ // no setting that could grant file access.+ const agentDocumentsAllowedForShare = !ctx.agentShareVisitor;let agentDocuments: AgentContextDocument[] | undefined;const agentId = state.metadata?.agentId;- if (agentId && ctx.serverDB && ctx.userId) {+ if (agentId && ctx.serverDB && ctx.userId && agentDocumentsAllowedForShare) {try {const agentDocService = new AgentDocumentsService(ctx.serverDB,@@ -171,7 +209,20 @@ export const buildServerCallLlmContext = async ({);});- if (isOnboardingAgent && !alreadyHasOnboardingContext && ctx.serverDB && ctx.userId) {+ // Onboarding context is the creator's own persona, SOUL document and initial+ // user info — personal profile data with no share permission that could ever+ // grant it, so a share visitor run never builds it. Two paths reach here: the+ // builtin `web-onboarding` agent, and any shared agent whose enabled tools+ // include `lobe-web-onboarding`. Gating on `ctx.agentShareVisitor` closes both.+ const onboardingContextAllowedForShare = !ctx.agentShareVisitor;++ if (+ isOnboardingAgent &&+ onboardingContextAllowedForShare &&+ !alreadyHasOnboardingContext &&+ ctx.serverDB &&+ ctx.userId+ ) {try {const { formatWebOnboardingStateMessage } =await import('@lobechat/builtin-tool-web-onboarding/utils');@@ -249,11 +300,18 @@ export const buildServerCallLlmContext = async ({// Tool-specific template variable resolution. The client-side// contextEngineering.ts resolves these via Zustand stores and lambdaClient.// In execAgent (server/bot) mode we must fetch from DB directly.+ //+ // `{{username}}` / `{{language}}` render back to whoever is actually+ // conversing. In a share-visitor run `ctx.userId` is the CREATOR (the agent+ // still executes under their identity), so resolving from it here would leak+ // the creator's own name/locale into a link visitor's turn. Resolve from the+ // visitor's own user id instead whenever this is a share-visitor run.let serverUsername = '';let serverLanguage = '';- if (ctx.serverDB && ctx.userId) {+ const userInfoUserId = ctx.agentShareVisitor?.visitorUserId ?? ctx.userId;+ if (ctx.serverDB && userInfoUserId) {try {- const userInfo = await UserModel.getInfoForAIGeneration(ctx.serverDB, ctx.userId);+ const userInfo = await UserModel.getInfoForAIGeneration(ctx.serverDB, userInfoUserId);serverUsername = userInfo.userName;serverLanguage = userInfo.responseLanguage;} catch (error) {diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.tsindex 13d369484ed..92ee8b91e82 100644--- a/apps/server/src/modules/AgentRuntime/context.ts+++ b/apps/server/src/modules/AgentRuntime/context.ts@@ -1,6 +1,7 @@import { type AgentState } from '@lobechat/agent-runtime';import { type BotPlatformContext } from '@lobechat/context-engine';import {+ type AgentShareVisitorContext,type ExecSubAgentParams,type ExecSubAgentResult,type ExecVirtualSubAgentParams,@@ -27,6 +28,15 @@ export interface RuntimeExecutorContext {*/abortSignal?: AbortSignal;agentConfig?: any;+ /**+ * Shared-agent visitor marker, read back from+ * `state.metadata.agentShareVisitor`. Present ONLY for a share-visitor run;+ * its presence alone is the signal every per-step consumer keys off. Forwarded+ * into `ToolExecutionContext.agentShareVisitor` so+ * `BuiltinToolsExecutor.execute` can re-check the visitor's grants right+ * before dispatch — see `isShareBlockedDataToolCall` in `shareGate.ts`.+ */+ agentShareVisitor?: AgentShareVisitorContext;/*** Allows call_llm to publish visible_output_end immediately after a no-tool* LLM stream_end. Only the default GeneralChatAgent treats no-tool llm_resultdiff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.tsindex ede9ed80064..3722c59319e 100644--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts@@ -212,6 +212,11 @@ export const buildServerVirtualSubAgentRunner = (chatToolPayload: ChatToolPayload,parentMessageId: string,): ServerSubAgentRunner | undefined => {+ // Share-visitor runs never get a sub-agent runner: the child run spawned+ // here does not thread the parent's shareGate, so it would execute with the+ // creator's full unrestricted tool surface. Same fail-closed stance as+ // `ServerSubAgentTransport` and the `isShareBlockedBuiltinDispatch` gate.+ if (ctx.agentShareVisitor) return undefined;const execVirtualSubAgent = ctx.execVirtualSubAgent;if (!execVirtualSubAgent) return undefined;@@ -288,7 +293,9 @@ export const buildServerVirtualSubAgentRunner = (// an inline tool error instead.if (!result?.success) {try {- await ctx.messageModel.deleteMessage(placeholder.id);+ // Runtime placeholder cleanup — also valid inside an agent-share+ // visitor topic, hence the explicit opt-in.+ await ctx.messageModel.deleteMessage(placeholder.id, { includeShareVisitor: true });} catch (error) {log('buildServerVirtualSubAgentRunner: failed to clean up placeholder %s: %O',@@ -338,6 +345,9 @@ export const buildServerAgentMemberRunner = (chatToolPayload: ChatToolPayload,parentMessageId: string,): ServerAgentMemberRunner | undefined => {+ // Same share-visitor fail-close as `buildServerVirtualSubAgentRunner`:+ // member runs would not inherit the parent's shareGate.+ if (ctx.agentShareVisitor) return undefined;const execGroupMember = ctx.execGroupMember;if (!execGroupMember) return undefined;@@ -348,8 +358,9 @@ export const buildServerAgentMemberRunner = (return {run: async ({ members, mode, onComplete, disableTools, timeout }) => {- const agentMap = (state.metadata?.agentGroup as { agentMap?: Record<string, { name: string }> }- | undefined)?.agentMap;+ const agentMap = (+ state.metadata?.agentGroup as { agentMap?: Record<string, { name: string }> } | undefined+ )?.agentMap;const resolvedMembers = members.map((member) => ({...member,agentId: resolveGroupMemberId(member.agentId, agentMap),@@ -466,7 +477,8 @@ export const buildServerAgentMemberRunner = (if (startedCount === 0) {for (const id of new Set([...anchorIds, groupTool.id])) {try {- await ctx.messageModel.deleteMessage(id);+ // Runtime placeholder cleanup — see the sub-agent runner above.+ await ctx.messageModel.deleteMessage(id, { includeShareVisitor: true });} catch (error) {log('buildServerAgentMemberRunner: cleanup failed for %s: %O', id, error);}diff --git a/apps/server/src/modules/AgentRuntime/factory.ts b/apps/server/src/modules/AgentRuntime/factory.tsindex 6db1def9ef9..e595682af0f 100644--- a/apps/server/src/modules/AgentRuntime/factory.ts+++ b/apps/server/src/modules/AgentRuntime/factory.ts@@ -4,6 +4,7 @@ import { appEnv } from '@/envs/app';import { AgentStateManager } from './AgentStateManager';import { GatewayStreamNotifier } from './GatewayStreamNotifier';+import { FULL_STRIP_REDACTION } from './gatewayVisitorRedaction';import { inMemoryAgentStateManager } from './InMemoryAgentStateManager';import { inMemoryStreamEventManager } from './InMemoryStreamEventManager';import { getAgentRuntimeRedisClient } from './redis';@@ -87,6 +88,15 @@ export const createStreamEventManager = (): IStreamEventManager => {const meta = await stateManager.getOperationMetadata(operationId);return meta?.mirrorToOperationId ?? undefined;},+ // Same reasoning as the mirror resolver above, but for share-visitor+ // detection: a queue worker that never ran `publishAgentRuntimeInit` for+ // this op still needs to know whether its events must be scrubbed of the+ // creator's identity, and under which owner-configured policy.+ async (operationId) => {+ const meta = await stateManager.getOperationMetadata(operationId);+ if (!meta?.streamOwnerUserId) return null;+ return meta.visitorRedaction ?? FULL_STRIP_REDACTION;+ },);}diff --git a/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts b/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.tsnew file mode 100644index 00000000000..d48150c3e81--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts@@ -0,0 +1,216 @@+import type { ChatMessageError, UIChatMessage } from '@lobechat/types';++import {+ redactCreatorPrivateBlob,+ sanitizeVisitorError,+ toVisitorMessage,+ type VisitorRedactionOptions,+} from '@/database/models/message';++import { stripFinalStateInEventData } from './StreamEventManager';++/**+ * Per-operation redaction policy for a shared-agent visitor run, derived from+ * the share's `AgentShareConfig` (`showModelInfo` / `showErrorDetails`) and+ * carried on `state.metadata.agentShareVisitor`.+ *+ * `null` is the explicit "not a share run — push verbatim" marker, so a+ * missing/undefined value can stay reserved for "not resolved yet".+ */+export type GatewayVisitorRedaction = VisitorRedactionOptions | null;++/**+ * The most restrictive policy: strip model/provider/usage AND project errors+ * down to a classified type. Used as the fail-closed fallback whenever the+ * share's real config is unavailable (a queue worker that never ran the op's+ * init can only read `streamOwnerUserId` back from persisted op metadata, not+ * the share config).+ */+export const FULL_STRIP_REDACTION: GatewayVisitorRedaction = {};++/**+ * Whether `publishAgentRuntimeInit` is initializing a shared-agent visitor run.+ * The op EXECUTES as the creator, but `streamOwnerUserId` (set only for+ * share-visitor runs — see `AgentRuntimeService.createOperation`) registers+ * the Gateway WS channel under the *visitor's* id, so the visitor is the one+ * receiving this push over the wire.+ */+export const isShareVisitorInit = (initialState: any): boolean =>+ typeof initialState?.streamOwnerUserId === 'string' && initialState.streamOwnerUserId.length > 0;++/**+ * Read the redaction policy off whatever the notifier was handed.+ *+ * Two shapes reach here, deliberately handled by one function so the fast path+ * never disagrees with itself:+ * - a runtime `AgentState`, whose `metadata.agentShareVisitor` is stamped once at+ * operation creation (`AgentRuntimeService.createOperation`) and rides the+ * state through to the terminal event (`publishAgentRuntimeEnd`);+ * - an `AgentOperationMetadata` record, which is what+ * `AgentRuntimeCoordinator.createAgentOperation` passes to+ * `publishAgentRuntimeInit` — it carries the flattened+ * `streamOwnerUserId` + `visitorRedaction` pair instead.+ *+ * Returns `null` for a normal (non-share) run. Fails closed to+ * {@link FULL_STRIP_REDACTION} when a run is identifiable as a share run but+ * its policy is unreadable.+ */+export const resolveRedactionFromState = (state: any): GatewayVisitorRedaction => {+ const share = state?.metadata?.agentShareVisitor as+ { showErrorDetails?: boolean; showModelInfo?: boolean; visitorUserId?: string } | undefined;++ if (share?.visitorUserId) {+ return { showErrorDetails: share.showErrorDetails, showModelInfo: share.showModelInfo };+ }++ if (!isShareVisitorInit(state)) return null;++ return (state.visitorRedaction as GatewayVisitorRedaction) ?? FULL_STRIP_REDACTION;+};++/**+ * Public `agent_runtime_init` DTO pushed to the Gateway for shared-agent+ * visitor runs. The full operation metadata must never cross the WS boundary to+ * the visitor. The client doesn't render anything from this event today —+ * `runAgent.ts`'s `agent_runtime_init` case only logs it — so `status` is the+ * only field forwarded.+ */+export const buildPublicInitEventData = (initialState: any): { status?: unknown } => ({+ status: initialState?.status,+});++/**+ * Public `agent_runtime_end` DTO pushed to the Gateway for shared-agent visitor+ * runs. `finalState` is the creator's full `AgentState`, none of which the+ * client reads off this event (`gatewayEventHandler.ts` only consumes `reason`+ * and `uiMessages`, both already-sanitized UI-facing values), so drop+ * `finalState` wholesale instead of trying to allowlist inside it.+ */+export const buildPublicEndEventData = <T extends { finalState?: unknown }>(+ data: T,+): Omit<T, 'finalState'> => {+ const { finalState: _finalState, ...rest } = data;+ return rest;+};++/**+ * Sanitize a `uiMessages` snapshot for a shared-agent visitor's WS channel.+ * `uiMessages` is the canonical `UIChatMessage[]` built from the creator's DB+ * rows (a creator-scoped query — unlike `shareChat.getMessages`, which already+ * goes through `MessageModel.queryForVisitor`). Every `step_start` and the+ * terminal `agent_runtime_end` push carry this snapshot, so without this step+ * the creator's joined `sender` identity would ride down the visitor's Gateway+ * WS channel even though `finalState` is already scrubbed. Reuses+ * `toVisitorMessage` — the same projection `shareChat.getMessages` applies — so+ * the two paths cannot drift apart.+ */+const sanitizeUiMessagesForVisitor = (+ uiMessages: unknown,+ redaction: VisitorRedactionOptions,+): unknown => {+ if (!Array.isArray(uiMessages)) return uiMessages;+ return (uiMessages as UIChatMessage[]).map((message) => toVisitorMessage(message, redaction));+};++/**+ * Sanitize a live `type: 'error'` Gateway stream event for a shared-agent+ * visitor. `ServerStreamSink.publishError` builds this event's `data` from+ * `formatErrorEventData`, which — like `formatErrorForState` — copies the raw+ * upstream `body` (provider, budget, upstream diagnostic) straight onto the+ * payload. The client (`gatewayEventHandler.ts`'s `case 'error'`) immediately+ * overlays it onto the visible message, so it reaches the visitor's screen+ * live, during the run, before any DB row (and therefore `toVisitorMessage`) is+ * ever involved. Reuses {@link sanitizeVisitorError}'s classification so the+ * live and reloaded-history projections cannot drift apart, reshaped into+ * `formatErrorEventData`'s flatter `{ error, errorType, phase }` wire shape+ * instead of `ChatMessageError`'s `{ body, message, type }`.+ */+const sanitizeErrorEventDataForVisitor = (+ data: unknown,+ redaction: VisitorRedactionOptions,+): unknown => {+ if (!data || typeof data !== 'object') return data;+ const record = data as { error?: unknown; errorType?: unknown; phase?: unknown };++ const safe = sanitizeVisitorError(+ typeof record.errorType === 'string' || typeof record.errorType === 'number'+ ? ({+ message: typeof record.error === 'string' ? record.error : undefined,+ type: record.errorType,+ } as ChatMessageError)+ : undefined,+ redaction,+ );++ return {+ ...(safe?.message === undefined ? {} : { error: safe.message }),+ ...(safe?.type === undefined ? {} : { errorType: safe.type }),+ ...(record.phase === undefined ? {} : { phase: record.phase }),+ };+};++/**+ * Chokepoint applied to every event `GatewayStreamNotifier` pushes to the+ * Gateway WS channel — not just `agent_runtime_init` / `agent_runtime_end`.+ *+ * For a share-visitor run:+ * 1. `finalState` is dropped wholesale (same DTO shape as+ * {@link buildPublicEndEventData}) — `step_complete`, published via the+ * generic `publishStreamEvent`, has no per-event DTO builder, so this+ * chokepoint is its only sanitization point.+ * 2. A live `type: 'error'` event is routed through+ * {@link sanitizeErrorEventDataForVisitor} — a SEPARATE leak from+ * `uiMessages`/`finalState`, since it carries `formatErrorEventData`'s raw+ * `{ body, error, errorType }` shape with no `finalState`/`uiMessages` key+ * for the other checks to even look at. Skipped when the share opted into+ * `showErrorDetails`.+ * 3. Unless the share opted into `showModelInfo`,+ * {@link redactCreatorPrivateBlob} runs over the WHOLE remaining payload.+ * Every other event type for a share run — `stream_start` (`{ model,+ * provider }`), `tool_end` (a tool's own free-form `result.state` blob, e.g.+ * `{ model, provider, usage }`), and `step_complete`'s `subagent_progress`+ * phase (`{ model, totalCost, totalInputTokens, … }` as SIBLINGS of `phase`)+ * — carries creator model/provider/usage/cost shapes. Rather than enumerate+ * and denylist each event type (which silently stops covering the next+ * producer that lands a new field), the recursive key-set strip is applied+ * at any nesting depth, so a future event type or tool cannot reintroduce+ * this leak by construction. `error` is excluded from this generic pass+ * because it needs PROJECTION rather than key-name redaction.+ * 4. `uiMessages` additionally goes through {@link toVisitorMessage}'s full+ * field allowlist, which the private-blob key strip alone does not cover.+ *+ * For a normal run this falls back to the generic+ * {@link stripFinalStateInEventData} (messages / tool-set fields only),+ * matching the Redis xadd chokepoint.+ */+export const sanitizeGatewayEventData = (+ data: unknown,+ redaction: GatewayVisitorRedaction,+ eventType?: unknown,+): unknown => {+ if (!data || typeof data !== 'object') return data;+ const record = data as Record<string, unknown>;++ if (!redaction) return stripFinalStateInEventData(data);++ const withoutFinalState: Record<string, unknown> =+ 'finalState' in record+ ? (() => {+ const { finalState: _finalState, ...rest } = record;+ return rest;+ })()+ : record;++ if (eventType === 'error') return sanitizeErrorEventDataForVisitor(withoutFinalState, redaction);++ const redacted = redaction.showModelInfo+ ? withoutFinalState+ : redactCreatorPrivateBlob(withoutFinalState);++ if (!('uiMessages' in withoutFinalState)) return redacted;++ return {+ ...redacted,+ uiMessages: sanitizeUiMessagesForVisitor(withoutFinalState.uiMessages, redaction),+ };+};diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.tsindex c7556b51883..7dda84b0d9a 100644--- a/apps/server/src/modules/AgentRuntime/types.ts+++ b/apps/server/src/modules/AgentRuntime/types.ts@@ -36,8 +36,16 @@ export interface IAgentStateManager {operationId: string,data: {agentConfig?: any;+ visitorRedaction?: { showErrorDetails?: boolean; showModelInfo?: boolean };mirrorToOperationId?: string;modelRuntimeConfig?: any;+ /**+ * Agent Share visitor runs only: the visitor's id, under which the+ * gateway WS channel is registered (the op itself executes as the+ * creator, `userId`). Its presence also marks the op as a share run for+ * a queue worker that never saw `publishAgentRuntimeInit`.+ */+ streamOwnerUserId?: string;userId?: string;workspaceId?: string;},diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.tsindex 70b5a7dd8d6..81042952f2f 100644--- a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts+++ b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts@@ -184,13 +184,40 @@ describe('runStep handler', () => {expect(AiAgentService).toHaveBeenCalledWith(expect.anything(),'user-1',- expect.objectContaining({ workspaceId: 'ws-1' }),+ expect.objectContaining({ includeShareVisitor: false, workspaceId: 'ws-1' }),);expect(mockExecuteStep).toHaveBeenCalledWith(expect.objectContaining({ operationId: 'op-1', stepIndex: 2 }),);});+ it('opts the AiAgentService into visitor rows when metadata carries streamOwnerUserId', async () => {+ // A shared-agent visitor run: the op executes as the creator `userId`+ // (`user-owner`) but the visitor (`visitor-1`) owns the stream. The step+ // worker must set `includeShareVisitor: true` so the runtime's+ // MessageModel / TopicModel can still read the visitor-scoped rows that+ // `MessageModel` / `TopicModel` gate out by default.+ mockGetOperationMetadata.mockResolvedValue({+ streamOwnerUserId: 'visitor-1',+ userId: 'user-owner',+ workspaceId: 'ws-1',+ });+ mockExecuteStep.mockResolvedValue({+ nextStepScheduled: false,+ state: { cost: { total: 0 }, status: 'done', stepCount: 1 },+ success: true,+ });++ const { ctx } = buildContext({ body: validBody });+ await runStep(ctx);++ expect(AiAgentService).toHaveBeenCalledWith(+ expect.anything(),+ 'user-owner',+ expect.objectContaining({ includeShareVisitor: true, workspaceId: 'ws-1' }),+ );+ });+it('acks without retry when the runtime already re-queued the locked step', async () => {mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });mockExecuteStep.mockResolvedValue({diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/subAgentCallback.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/subAgentCallback.test.tsindex f072413afd8..8bbcfb589a2 100644--- a/apps/server/src/router-hono/agent/handlers/__tests__/subAgentCallback.test.ts+++ b/apps/server/src/router-hono/agent/handlers/__tests__/subAgentCallback.test.ts@@ -113,9 +113,11 @@ describe('subAgentCallback handler', () => {});// Workspace-scoped like the /run step worker — a personal-scoped runtime// would miss workspace rows in the backfill / barrier queries.- expect(mockAiAgentService).toHaveBeenCalledWith(expect.anything(), 'user-1', {- workspaceId: 'ws-1',- });+ expect(mockAiAgentService).toHaveBeenCalledWith(+ expect.anything(),+ 'user-1',+ expect.objectContaining({ includeShareVisitor: false, workspaceId: 'ws-1' }),+ );});it('defaults reason to done and threadId to empty string when absent', async () => {diff --git a/apps/server/src/router-hono/agent/handlers/finalizeAbandoned.ts b/apps/server/src/router-hono/agent/handlers/finalizeAbandoned.tsindex afc69c4e6ea..875a2b47833 100644--- a/apps/server/src/router-hono/agent/handlers/finalizeAbandoned.ts+++ b/apps/server/src/router-hono/agent/handlers/finalizeAbandoned.ts@@ -53,7 +53,7 @@ export async function finalizeAbandoned(c: Context): Promise<Response> {// being swallowed behind a 200: a 200 here would falsely report the parent// as handled while it stays parked forever.if (result.subAgentResume) {- const { parentOperationId, threadId, toolMessageId, userId, workspaceId } =+ const { parentOperationId, streamOwnerUserId, threadId, toolMessageId, userId, workspaceId } =result.subAgentResume;// Child reached a terminal failure (watchdog kill) → the bridge backfills// the parent's tool slot with an error note rather than a stub answer.@@ -74,7 +74,14 @@ export async function finalizeAbandoned(c: Context): Promise<Response> {// No durable queue configured: run the CAS-guarded, idempotent bridge// inline through AiAgentService so the runtime's models stay// workspace-scoped.- const aiAgentService = new AiAgentService(serverDB, userId, { workspaceId });+ // Mirror the queue-mode `subagent-callback`: opt into visitor rows only+ // when the parent op is a shared-agent visitor run (surfaced via+ // `streamOwnerUserId`). Ordinary creator runs keep the default+ // exclusion.+ const aiAgentService = new AiAgentService(serverDB, userId, {+ includeShareVisitor: Boolean(streamOwnerUserId),+ workspaceId,+ });const won = await aiAgentService.completeSubAgentBridge(bridgeBody);log('[%s] resumed parent %s inline (local mode, won=%s)',diff --git a/apps/server/src/router-hono/agent/handlers/groupMemberCallback.ts b/apps/server/src/router-hono/agent/handlers/groupMemberCallback.tsindex f74b78f715b..d897f3156d7 100644--- a/apps/server/src/router-hono/agent/handlers/groupMemberCallback.ts+++ b/apps/server/src/router-hono/agent/handlers/groupMemberCallback.ts@@ -75,7 +75,13 @@ export async function groupMemberCallback(c: Context): Promise<Response> {}const serverDB = await getServerDB();+ // Opt into visitor rows only for shared-agent visitor runs: metadata+ // carries `streamOwnerUserId` when the operation executes as the creator+ // but the visitor owns the stream. Ordinary creator ops keep the default+ // exclusion.+ const includeShareVisitor = Boolean(metadata.streamOwnerUserId);const aiAgentService = new AiAgentService(serverDB, metadata.userId, {+ includeShareVisitor,workspaceId: metadata.workspaceId,});diff --git a/apps/server/src/router-hono/agent/handlers/runStep.ts b/apps/server/src/router-hono/agent/handlers/runStep.tsindex 2fccc59fefe..d5cb12ae672 100644--- a/apps/server/src/router-hono/agent/handlers/runStep.ts+++ b/apps/server/src/router-hono/agent/handlers/runStep.ts@@ -130,7 +130,13 @@ export async function runStep(c: Context): Promise<Response> {// Thread the operation's workspace through so the runtime's models stay// workspace-scoped. Without it the worker is personal-scoped and the// parent-message lookup misses workspace-scoped rows → ConversationParentMissing.+ // Opt into agent-share visitor rows only when this op is a shared-agent+ // visitor run — signalled by `streamOwnerUserId` (set on the operation+ // metadata when the visitor owns the stream but the run executes as the+ // creator `userId`). Ordinary creator runs keep the default exclusion.+ const includeShareVisitor = Boolean(metadata.streamOwnerUserId);const aiAgentService = new AiAgentService(serverDB, metadata.userId, {+ includeShareVisitor,workspaceId: metadata.workspaceId,});diff --git a/apps/server/src/router-hono/agent/handlers/subAgentCallback.ts b/apps/server/src/router-hono/agent/handlers/subAgentCallback.tsindex 638c74503eb..d6a12da24cd 100644--- a/apps/server/src/router-hono/agent/handlers/subAgentCallback.ts+++ b/apps/server/src/router-hono/agent/handlers/subAgentCallback.ts@@ -63,7 +63,13 @@ export async function subAgentCallback(c: Context): Promise<Response> {// runtime's models stay workspace-scoped — a bare AgentRuntimeService// would be personal-scoped and the tool-message backfill / resume// barrier could miss workspace-scoped rows.+ // Opt into visitor rows only for shared-agent visitor runs: metadata+ // carries `streamOwnerUserId` when the operation executes as the creator+ // but the visitor owns the stream. Ordinary creator ops keep the default+ // exclusion.+ const includeShareVisitor = Boolean(metadata.streamOwnerUserId);const aiAgentService = new AiAgentService(serverDB, metadata.userId, {+ includeShareVisitor,workspaceId: metadata.workspaceId,});diff --git a/apps/server/src/router-hono/webhooks/handlers/video.ts b/apps/server/src/router-hono/webhooks/handlers/video.tsindex 38be075647a..85324949cf2 100644--- a/apps/server/src/router-hono/webhooks/handlers/video.ts+++ b/apps/server/src/router-hono/webhooks/handlers/video.ts@@ -165,6 +165,7 @@ export const videoWebhook = async (c: Context<BlankEnv, '/video/:provider'>) =>await chargeAfterGenerate({isError: true,metadata: {+ ...metadata?.spendOrigin,asyncTaskId: asyncTask.id,generationBatchId: generation.generationBatchId!,topicId: batch?.generationTopicId,@@ -244,6 +245,7 @@ export const videoWebhook = async (c: Context<BlankEnv, '/video/:provider'>) =>},latency: duration,metadata: {+ ...metadata?.spendOrigin,asyncTaskId: asyncTask.id,generationBatchId: generation.generationBatchId!,topicId: batch?.generationTopicId,@@ -283,7 +285,12 @@ export const videoWebhook = async (c: Context<BlankEnv, '/video/:provider'>) =>try {await chargeAfterGenerate({isError: true,- metadata: { asyncTaskId: asyncTaskId ?? '', generationBatchId: '', modelId: '' },+ metadata: {+ ...asyncTaskMetadata.spendOrigin,+ asyncTaskId: asyncTaskId ?? '',+ generationBatchId: '',+ modelId: '',+ },model: '',prechargeResult: asyncTaskMetadata.precharge as any,provider,diff --git a/apps/server/src/router-hono/workflows/task/handlers/scheduledRunKinds.ts b/apps/server/src/router-hono/workflows/task/handlers/scheduledRunKinds.tsindex daec0945aaf..1827fa8e4a7 100644--- a/apps/server/src/router-hono/workflows/task/handlers/scheduledRunKinds.ts+++ b/apps/server/src/router-hono/workflows/task/handlers/scheduledRunKinds.ts@@ -42,7 +42,14 @@ const runResumeAfterRateLimit: ScheduledRunHandlers['resume_after_rate_limit'] =run,{ claimId, db, topic, workspaceId },) => {- const messageModel = new MessageModel(db, topic.userId, workspaceId);+ // Scheduled runs execute under the creator (`topic.userId` is billing+ // owner). When the topic is an agent-share visitor conversation this ends+ // up mutating visitor rows, so opt into the visitor scope for reads too —+ // the existing per-call `includeShareVisitor: true` on the delete already+ // acknowledges this.+ const messageModel = new MessageModel(db, topic.userId, workspaceId, undefined, {+ includeShareVisitor: true,+ });const failedMessage = await messageModel.findById(run.failedAssistantMessageId);let parentMessageId = run.userMessageId;@@ -55,6 +62,9 @@ const runResumeAfterRateLimit: ScheduledRunHandlers['resume_after_rate_limit'] =await messageModel.update(failedMessage.id, { error: null });parentMessageId = failedMessage.id;} else {+ // Scheduled-run retry cleanup runs as the runtime, not as the creator.+ // Instance already opts into visitor scope (see MessageModel above), so the+ // per-call `includeShareVisitor` override is redundant here.await messageModel.deleteMessage(failedMessage.id);parentMessageId = failedMessage.parentId ?? run.userMessageId;}@@ -102,7 +112,14 @@ const runDelayedStart: ScheduledRunHandlers['delayed_start'] = async (run,{ db, topic, workspaceId },) => {- const messageModel = new MessageModel(db, topic.userId, workspaceId);+ // Scheduled runs execute under the creator (`topic.userId` is billing+ // owner). When the topic is an agent-share visitor conversation this ends+ // up mutating visitor rows, so opt into the visitor scope for reads too —+ // the existing per-call `includeShareVisitor: true` on the delete already+ // acknowledges this.+ const messageModel = new MessageModel(db, topic.userId, workspaceId, undefined, {+ includeShareVisitor: true,+ });const userMessage = await messageModel.findById(run.userMessageId);if (!userMessage) throw new Error('Scheduled user message no longer exists');diff --git a/apps/server/src/routers/async/__tests__/image.test.ts b/apps/server/src/routers/async/__tests__/image.test.tsindex 8d086e6e73c..078f6f9d635 100644--- a/apps/server/src/routers/async/__tests__/image.test.ts+++ b/apps/server/src/routers/async/__tests__/image.test.ts@@ -132,6 +132,34 @@ describe('imageRouter.createImage — model mapping failure reconciles billing',);});+ it('stamps the task spend attribution onto the completion charge metadata', async () => {+ // The submitting request is long gone by the time this router charges, so+ // the attribution has to come off the task — otherwise a share visitor's+ // image spend is billed to the creator with no trace of its origin.+ asyncTaskModelMock.findById.mockResolvedValue({+ metadata: {+ precharge: { reservationKey: 'brk-1' },+ spendOrigin: {+ agentShare: { agentId: 'agent-1', shareId: 'share-1', visitorUserId: 'visitor-1' },+ trigger: 'agent_share',+ },+ },+ });+ vi.mocked(resolveBusinessModelMapping).mockRejectedValue(new Error('mapping failed'));++ const caller = imageRouter.createCaller(mockCtx);+ await caller.createImage(createInput());++ expect(chargeAfterGenerate).toHaveBeenCalledWith(+ expect.objectContaining({+ metadata: expect.objectContaining({+ agentShare: { agentId: 'agent-1', shareId: 'share-1', visitorUserId: 'visitor-1' },+ trigger: 'agent_share',+ }),+ }),+ );+ });+it('threads undefined prechargeResult when the task has no precharge handle', async () => {asyncTaskModelMock.findById.mockResolvedValue({ metadata: undefined });vi.mocked(resolveBusinessModelMapping).mockRejectedValue(new Error('mapping failed'));diff --git a/apps/server/src/routers/async/image.ts b/apps/server/src/routers/async/image.tsindex 06dbdff500b..321d1b95e7d 100644--- a/apps/server/src/routers/async/image.ts+++ b/apps/server/src/routers/async/image.ts@@ -5,7 +5,7 @@ import {resolveBusinessModelMapping,} from '@lobechat/business-model-runtime';import { type CreateImageMethodOptions } from '@lobechat/model-runtime';-import { AsyncTaskError, AsyncTaskStatus, RequestTrigger } from '@lobechat/types';+import { AsyncTaskError, AsyncTaskStatus, RequestTrigger, type SpendOrigin } from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';import { type RuntimeImageGenParams } from 'model-bank';@@ -124,6 +124,7 @@ export const imageRouter = router({let requestedModelId: string | undefined = model;let resolvedModelId = model;let prechargeResult: unknown;+ let spendOrigin: SpendOrigin | undefined;log('Updating task status to Processing: %s', taskId);await asyncTaskModel.update(taskId, { status: AsyncTaskStatus.Processing });@@ -142,7 +143,12 @@ export const imageRouter = router({// billing. Loaded before the model mapping so the handle is available// for reconciliation even when mapping resolution throws.const asyncTask = await asyncTaskModel.findById(taskId);- prechargeResult = (asyncTask?.metadata as { precharge?: unknown } | undefined)?.precharge;+ const taskMetadata = asyncTask?.metadata as+ { precharge?: unknown; spendOrigin?: SpendOrigin } | undefined;+ prechargeResult = taskMetadata?.precharge;+ // Origin of the submitting request, stamped on the completion charge so+ // spend keeps its attribution across the async boundary.+ spendOrigin = taskMetadata?.spendOrigin;// Resolve model mapping up front so both the success and error billing// paths can reference the resolved model id.@@ -294,6 +300,7 @@ export const imageRouter = router({await chargeAfterGenerate({metrics: { latency: duration },metadata: {+ ...spendOrigin,asyncTaskId: taskId,generationBatchId,topicId: generationTopicId,@@ -374,6 +381,7 @@ export const imageRouter = router({await chargeAfterGenerate({isError: true,metadata: {+ ...spendOrigin,asyncTaskId: taskId,generationBatchId,topicId: generationTopicId,diff --git a/apps/server/src/routers/async/video.ts b/apps/server/src/routers/async/video.tsindex b5070024825..9ede16a7cc4 100644--- a/apps/server/src/routers/async/video.ts+++ b/apps/server/src/routers/async/video.ts@@ -9,6 +9,7 @@ import {AsyncTaskErrorType,AsyncTaskStatus,RequestTrigger,+ type SpendOrigin,} from '@lobechat/types';import debug from 'debug';import { z } from 'zod';@@ -47,6 +48,11 @@ const createVideoInputSchema = z.object({model: z.string(),prechargeResult: z.any().optional(),provider: z.string(),+ /**+ * Origin of the submitting request, forwarded so the completion charge keeps+ * the spend attributed after the async hand-off.+ */+ spendOrigin: z.custom<SpendOrigin>().optional(),workspaceId: z.string().optional(),});@@ -134,6 +140,7 @@ export const videoRouter = router({model,prechargeResult,provider,+ spendOrigin,workspaceId,} = input;const asyncTaskModel = new AsyncTaskModel(ctx.serverDB, ctx.userId, workspaceId);@@ -223,6 +230,7 @@ export const videoRouter = router({},latency: duration,metadata: {+ ...spendOrigin,asyncTaskId,generationBatchId,topicId: generationTopicId,@@ -300,6 +308,7 @@ export const videoRouter = router({await chargeAfterGenerate({isError: true,metadata: {+ ...spendOrigin,asyncTaskId,generationBatchId,topicId: generationTopicId,diff --git a/apps/server/src/routers/lambda/__tests__/agent.test.ts b/apps/server/src/routers/lambda/__tests__/agent.test.tsindex 918028afa5c..785420c4e90 100644--- a/apps/server/src/routers/lambda/__tests__/agent.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agent.test.ts@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { INBOX_SESSION_ID } from '@/const/session';import { DEFAULT_AGENT_CONFIG } from '@/const/settings';import { AgentModel } from '@/database/models/agent';+import { AgentShareModel } from '@/database/models/agentShare';import { ChatGroupModel } from '@/database/models/chatGroup';import { FileModel } from '@/database/models/file';import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';@@ -48,6 +49,10 @@ vi.mock('@/database/models/agent', () => ({AgentModel: vi.fn(),}));+vi.mock('@/database/models/agentShare', () => ({+ AgentShareModel: { findBySlugOrId: vi.fn() },+}));+vi.mock('@/database/models/session', () => ({SessionModel: vi.fn(),}));@@ -161,6 +166,7 @@ describe('agentRouter', () => {getAgentAssignedKnowledge: vi.fn(),getAgentVisibility: vi.fn().mockResolvedValue(null),publishToWorkspace: vi.fn(),+ resolveIdBySlug: vi.fn().mockResolvedValue(null),toggleFile: vi.fn(),toggleKnowledgeBase: vi.fn(),update: vi.fn(),@@ -1020,4 +1026,97 @@ describe('agentRouter', () => {});});});++ describe('resolveAgentRoute', () => {+ const findBySlugOrIdMock = vi.mocked(AgentShareModel.findBySlugOrId);++ it('treats an id-shaped param as an own agent without touching the database', async () => {+ const caller = agentRouter.createCaller(mockCtx);+ const result = await caller.resolveAgentRoute({ slugOrId: 'agt_abc123' });++ expect(result).toEqual({ agentId: 'agt_abc123', kind: 'own' });+ expect(agentModelMock.resolveIdBySlug).not.toHaveBeenCalled();+ expect(findBySlugOrIdMock).not.toHaveBeenCalled();+ });++ it('resolves an own agent slug to its id, without a share lookup', async () => {+ agentModelMock.resolveIdBySlug.mockResolvedValue('agt_from_slug');++ const caller = agentRouter.createCaller(mockCtx);+ const result = await caller.resolveAgentRoute({ slugOrId: 'my-bot' });++ expect(result).toEqual({ agentId: 'agt_from_slug', kind: 'own' });+ expect(findBySlugOrIdMock).not.toHaveBeenCalled();+ });++ it('falls back to an agent share when no own agent claims the slug', async () => {+ agentModelMock.resolveIdBySlug.mockResolvedValue(null);+ findBySlugOrIdMock.mockResolvedValue({+ ownerId: 'someone-else',+ shareId: 'share-1',+ visibility: 'link',+ } as any);++ const caller = agentRouter.createCaller(mockCtx);++ expect(await caller.resolveAgentRoute({ slugOrId: 'shared-bot' })).toEqual({ kind: 'share' });+ });++ it('sends the creator following their OWN share link to the agent, not the visitor surface', async () => {+ agentModelMock.resolveIdBySlug.mockResolvedValue(null);+ findBySlugOrIdMock.mockResolvedValue({+ agentId: 'agt_mine',+ ownerId: mockCtx.userId,+ shareId: 'share-1',+ } as any);++ const caller = agentRouter.createCaller(mockCtx);++ expect(await caller.resolveAgentRoute({ slugOrId: 'my-share-slug' })).toEqual({+ agentId: 'agt_mine',+ kind: 'ownShare',+ });+ });++ // Same rule as `assertShareAccess`: a paused share must look exactly like+ // a missing one to a stranger, or this resolver becomes a slug oracle.+ it('reports a stranger’s private share as not found', async () => {+ agentModelMock.resolveIdBySlug.mockResolvedValue(null);+ findBySlugOrIdMock.mockResolvedValue({+ ownerId: 'someone-else',+ shareId: 'share-1',+ visibility: 'private',+ } as any);++ const caller = agentRouter.createCaller(mockCtx);++ expect(await caller.resolveAgentRoute({ slugOrId: 'private-bot' })).toEqual({+ kind: 'notFound',+ });+ });++ it('routes a stranger’s link share to the share surface', async () => {+ agentModelMock.resolveIdBySlug.mockResolvedValue(null);+ findBySlugOrIdMock.mockResolvedValue({+ ownerId: 'someone-else',+ shareId: 'share-1',+ visibility: 'link',+ } as any);++ const caller = agentRouter.createCaller(mockCtx);++ expect(await caller.resolveAgentRoute({ slugOrId: 'open-bot' })).toEqual({+ kind: 'share',+ });+ });++ it('reports not found when the slug matches neither an agent nor a share', async () => {+ agentModelMock.resolveIdBySlug.mockResolvedValue(null);+ findBySlugOrIdMock.mockResolvedValue(null);++ const caller = agentRouter.createCaller(mockCtx);++ expect(await caller.resolveAgentRoute({ slugOrId: 'nope' })).toEqual({ kind: 'notFound' });+ });+ });});diff --git a/apps/server/src/routers/lambda/__tests__/agentDocument.toolOutcome.test.ts b/apps/server/src/routers/lambda/__tests__/agentDocument.toolOutcome.test.tsindex 23a5c5888d6..ef3242119ff 100644--- a/apps/server/src/routers/lambda/__tests__/agentDocument.toolOutcome.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agentDocument.toolOutcome.test.ts@@ -32,7 +32,7 @@ vi.mock('@/database/models/agentDocuments', async (importOriginal) => {vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({- findById: agentDocumentMocks.findTopicById,+ findOwnTopicById: agentDocumentMocks.findTopicById,})),}));diff --git a/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts b/apps/server/src/routers/lambda/__tests__/agentNotify.test.tsindex 6cdb4277809..72dd401a58c 100644--- a/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts@@ -16,6 +16,10 @@ vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({}));const mockTopicFindById = vi.fn();+// The entry lookup goes through the visitor-excluding twin; by default it+// mirrors `findById` so the existing scenarios keep their single source of+// topic state.+const mockTopicFindOwnTopicById = vi.fn((...args: unknown[]) => mockTopicFindById(...args));const mockTopicSettleRunningOperation = vi.fn();const mockTopicUpdateMetadata = vi.fn();const mockTopicRemoveRunningOperationChild = vi.fn();@@ -39,6 +43,7 @@ vi.mock('@/server/services/verify', async (orig) => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn(() => ({findById: mockTopicFindById,+ findOwnTopicById: mockTopicFindOwnTopicById,removeRunningOperationChild: mockTopicRemoveRunningOperationChild,settleRunningOperation: mockTopicSettleRunningOperation,updateMetadata: mockTopicUpdateMetadata,@@ -126,6 +131,26 @@ describe('agentNotifyRouter.notify — remote hetero terminal signal', () => {hookDispatcher.unregister(OP);});+ // Visitor topics carry the creator's userId, so an ownership-only lookup+ // would let a creator-side caller append to or overwrite a visitor+ // transcript through this callback.+ it('rejects an agent-share visitor topic with NOT_FOUND before any write', async () => {+ mockTopicFindOwnTopicById.mockResolvedValueOnce(undefined);++ await expect(+ createCaller().notify({+ content: 'hi',+ messageId: 'msg-1',+ role: 'assistant',+ topicId: TOPIC,+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockMessageUpdate).not.toHaveBeenCalled();+ expect(mockMessageCreate).not.toHaveBeenCalled();+ expect(mockExecAgent).not.toHaveBeenCalled();+ });+it('empty done signal finalizes success AND carries the final reply into the hooks', async () => {const { onComplete, onError } = registerHooks();diff --git a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts b/apps/server/src/routers/lambda/__tests__/agentShare.test.tsnew file mode 100644index 00000000000..e9447a099ef--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/agentShare.test.ts@@ -0,0 +1,443 @@+// @vitest-environment node+import type * as BusinessConst from '@lobechat/business-const';+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createContextInner } from '@/libs/trpc/lambda/context';++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => ({})),+}));++// `assertAgentShareCreationEnabled` (`_helpers/agentShareFeatureGate.ts`) runs+// for real in this suite — only its own two dependencies are mocked+// (`mockGetFeatureFlagsState` below, and this mutable business-const object)+// — so the router tests exercise the actual gate, not a stand-in.+const mocks = vi.hoisted(() => ({+ businessConst: { ENABLE_BUSINESS_FEATURES: true },+}));+vi.mock('@lobechat/business-const', async () => {+ const actual = await vi.importActual<typeof BusinessConst>('@lobechat/business-const');+ return {+ ...actual,+ // `packages/utils/src/apiKey.ts` reads this dynamically (`import * as+ // businessConst`), pulled in transitively via the unmocked+ // `createContextInner` -> `ApiKeyModel` chain below. `actual` here+ // resolves to the cloud override, which omits this key entirely (see+ // that file's own doc comment), so vitest's mock-export validation has+ // no own property to find unless it is listed explicitly.+ API_KEY_PREFIX: (actual as Record<string, unknown>).API_KEY_PREFIX,+ // A getter (not a static spread) so per-test mutation of+ // `mocks.businessConst.ENABLE_BUSINESS_FEATURES` is observed by every+ // subsequent read, including inside the already-imported gate helper.+ get ENABLE_BUSINESS_FEATURES() {+ return mocks.businessConst.ENABLE_BUSINESS_FEATURES;+ },+ };+});++const mockCreate = vi.fn();+const mockGetByAgentId = vi.fn();+const mockUpdateConfig = vi.fn();+const mockUpdateSlug = vi.fn();+const mockUpdateVisibility = vi.fn();++vi.mock('@/database/models/agentShare', () => ({+ AgentShareModel: vi.fn(() => ({+ create: mockCreate,+ getByAgentId: mockGetByAgentId,+ updateConfig: mockUpdateConfig,+ updateSlug: mockUpdateSlug,+ updateVisibility: mockUpdateVisibility,+ })),+}));++const mockCountShareVisitors = vi.fn();+vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn(() => ({ countShareVisitors: mockCountShareVisitors })),+}));++const mockGetAgentShareMonthlySpend = vi.fn();+vi.mock('@/business/server/agent-share/spendGate', () => ({+ getAgentShareMonthlySpend: (...args: unknown[]) => mockGetAgentShareMonthlySpend(...args),+}));++const mockGetFeatureFlagsState = vi.fn();+vi.mock('@/server/featureFlags', () => ({+ getServerFeatureFlagsStateFromRuntimeConfig: (...args: unknown[]) =>+ mockGetFeatureFlagsState(...args),+}));++const { agentShareConfigPatchSchema, agentShareConfigSchema, agentShareRouter } =+ await import('../agentShare');++const share = {+ agentId: 'agent-1',+ id: 'share-1',+ shareConfig: { maxTopicsPerVisitor: 5, maxTurnsPerTopic: 20 },+ visibility: 'private',+};++describe('agentShareRouter', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.businessConst.ENABLE_BUSINESS_FEATURES = true;+ mockCreate.mockResolvedValue(share);+ mockGetByAgentId.mockResolvedValue(share);+ mockUpdateConfig.mockResolvedValue(share);+ mockUpdateSlug.mockResolvedValue({+ ...share,+ shareConfig: { ...share.shareConfig, slug: 'my-slug' },+ });+ mockUpdateVisibility.mockResolvedValue(share);+ mockCountShareVisitors.mockResolvedValue({ topicCount: 7, visitorCount: 3 });+ mockGetAgentShareMonthlySpend.mockResolvedValue(null);+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: true });+ });++ it('requires authentication for share management', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner());++ await expect(caller.getShareStatus({ agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+ expect(mockGetByAgentId).not.toHaveBeenCalled();+ });++ it('enables a private share by default', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(caller.enableShare({ agentId: 'agent-1' })).resolves.toEqual(share);+ expect(mockCreate).toHaveBeenCalledWith('agent-1', undefined);+ });++ it('enables a share with an explicit visibility', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await caller.enableShare({ agentId: 'agent-1', visibility: 'link' });+ expect(mockCreate).toHaveBeenCalledWith('agent-1', 'link');+ });++ it('returns null when a personal agent has no share', async () => {+ mockGetByAgentId.mockResolvedValue(null);+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(caller.getShareStatus({ agentId: 'agent-1' })).resolves.toBeNull();+ });++ it('forwards an atomic share configuration patch', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));+ const config = { maxTopicsPerVisitor: 10 };++ await caller.updateShareConfig({ agentId: 'agent-1', config });++ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', config);+ });++ it('rejects an empty share configuration patch', () => {+ expect(agentShareConfigPatchSchema.safeParse({}).success).toBe(false);+ });++ it('requires positive integer topic and turn limits', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(+ caller.updateShareConfig({+ agentId: 'agent-1',+ config: { maxTopicsPerVisitor: 0 },+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ await expect(+ caller.updateShareConfig({+ agentId: 'agent-1',+ config: { maxTurnsPerTopic: 1.5 },+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mockUpdateConfig).not.toHaveBeenCalled();+ });++ it('caps maxTopicsPerVisitor at the visitor topic list limit', async () => {+ // The visitor topic list (`TopicModel.queryBySender`) is not paginated+ // and is bounded by `AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT` (200), so a+ // cap above it would let visitors create topics they can never reopen.+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(+ caller.updateShareConfig({+ agentId: 'agent-1',+ config: { maxTopicsPerVisitor: 201 },+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mockUpdateConfig).not.toHaveBeenCalled();++ await caller.updateShareConfig({+ agentId: 'agent-1',+ config: { maxTopicsPerVisitor: 200 },+ });+ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', { maxTopicsPerVisitor: 200 });+ });++ it('accepts a toolset-level grant and a per-API scoped grant in toolGrants', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));+ const config = {+ toolGrants: [+ { identifier: 'calculator' },+ { apis: ['analyzeMedia'], identifier: 'lobe-agent' },+ ],+ };++ await caller.updateShareConfig({ agentId: 'agent-1', config });++ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', config);+ });++ it('rejects a malformed toolGrants entry', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ // Empty identifier.+ await expect(+ caller.updateShareConfig({+ agentId: 'agent-1',+ config: { toolGrants: [{ identifier: '' }] },+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ // Empty `apis` array — a tool with no granted API must be absent instead.+ await expect(+ caller.updateShareConfig({+ agentId: 'agent-1',+ config: { toolGrants: [{ apis: [], identifier: 'lobe-agent' }] },+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ // Unknown key.+ await expect(+ caller.updateShareConfig({+ agentId: 'agent-1',+ config: { toolGrants: [{ apiName: 'analyzeMedia', identifier: 'lobe-agent' } as any] },+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mockUpdateConfig).not.toHaveBeenCalled();+ });++ it('rejects duplicate identifiers and duplicate api names in toolGrants', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(+ caller.updateShareConfig({+ agentId: 'agent-1',+ config: { toolGrants: [{ identifier: 'calculator' }, { identifier: 'calculator' }] },+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ await expect(+ caller.updateShareConfig({+ agentId: 'agent-1',+ config: {+ toolGrants: [{ apis: ['analyzeMedia', 'analyzeMedia'], identifier: 'lobe-agent' }],+ },+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mockUpdateConfig).not.toHaveBeenCalled();+ });++ it('does not expose dropped v1 config fields in the config API', () => {+ expect(+ agentShareConfigSchema.safeParse({+ filePermissionConfig: { agentFiles: 'read' },+ maxTopicsPerVisitor: 5,+ }).success,+ ).toBe(false);+ expect(+ agentShareConfigSchema.safeParse({+ guestEnabled: true,+ maxTopicsPerVisitor: 5,+ }).success,+ ).toBe(false);+ });++ // Disabling is a pause, not a revocation: it flips the row to `private` and+ // never deletes it, so the share id and slug (i.e. the link already handed+ // out) survive and re-enabling republishes the same url.+ it('disables an existing share by making it private, keeping the row', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await caller.updateVisibility({ agentId: 'agent-1', visibility: 'link' });+ const disabled = await caller.disableShare({ agentId: 'agent-1' });++ expect(mockUpdateVisibility).toHaveBeenNthCalledWith(1, 'agent-1', 'link');+ expect(mockUpdateVisibility).toHaveBeenNthCalledWith(2, 'agent-1', 'private');+ expect(disabled.id).toBe('share-1');+ });++ it('updates the custom slug', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ const result = await caller.updateSlug({ agentId: 'agent-1', slug: 'my-slug' });++ expect(mockUpdateSlug).toHaveBeenCalledWith('agent-1', 'my-slug');+ expect(result.shareConfig).toMatchObject({ slug: 'my-slug' });+ });++ it('lower-cases and trims the slug input before forwarding it', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await caller.updateSlug({ agentId: 'agent-1', slug: ' My-Slug ' });++ expect(mockUpdateSlug).toHaveBeenCalledWith('agent-1', 'my-slug');+ });++ it('rejects an obviously too-short slug before reaching the model', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(caller.updateSlug({ agentId: 'agent-1', slug: 'ab' })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ expect(mockUpdateSlug).not.toHaveBeenCalled();+ });++ it('propagates a slug conflict as CONFLICT', async () => {+ mockUpdateSlug.mockRejectedValue(+ new TRPCError({ code: 'CONFLICT', message: 'SHARE_SLUG_TAKEN' }),+ );+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(+ caller.updateSlug({ agentId: 'agent-1', slug: 'taken-slug' }),+ ).rejects.toMatchObject({ code: 'CONFLICT' });+ });++ it('returns NOT_FOUND when an existing share is required', async () => {+ mockUpdateConfig.mockResolvedValue(null);+ mockUpdateVisibility.mockResolvedValue(null);+ mockUpdateSlug.mockResolvedValue(null);+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(caller.disableShare({ agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ await expect(+ caller.updateShareConfig({+ agentId: 'agent-1',+ config: { maxTopicsPerVisitor: 5 },+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ await expect(+ caller.updateVisibility({ agentId: 'agent-1', visibility: 'private' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ await expect(caller.updateSlug({ agentId: 'agent-1', slug: 'my-slug' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ });++ describe('publish capability', () => {+ it('rejects enabling a share on a deployment without business features, even when the flag is on', async () => {+ mocks.businessConst.ENABLE_BUSINESS_FEATURES = false;+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: true });+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(caller.enableShare({ agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ // The compile-time gate short-circuits before the flag is even read.+ expect(mockGetFeatureFlagsState).not.toHaveBeenCalled();+ expect(mockCreate).not.toHaveBeenCalled();+ });++ it('rejects enabling a share when the capability is off for this user', async () => {+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: false });+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(caller.enableShare({ agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(mockGetFeatureFlagsState).toHaveBeenCalledWith('user-1');+ expect(mockCreate).not.toHaveBeenCalled();+ });++ it('rejects publishing an existing share when the capability is off', async () => {+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: false });+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(+ caller.updateVisibility({ agentId: 'agent-1', visibility: 'link' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mockUpdateVisibility).not.toHaveBeenCalled();+ });++ it('still lets a user unpublish, read and manage a share when the capability is off', async () => {+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: false });+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await caller.updateVisibility({ agentId: 'agent-1', visibility: 'private' });+ await caller.disableShare({ agentId: 'agent-1' });+ await caller.getShareStatus({ agentId: 'agent-1' });+ await caller.updateShareConfig({ agentId: 'agent-1', config: { maxTurnsPerTopic: 3 } });++ expect(mockUpdateVisibility).toHaveBeenCalledWith('agent-1', 'private');+ expect(mockUpdateVisibility).toHaveBeenCalledTimes(2);+ });++ // Fails closed: an unconfigured flag is treated the same as `false`, not+ // as "open" — a deployment must explicitly opt a user in.+ it('rejects publishing when the capability is unconfigured', async () => {+ mockGetFeatureFlagsState.mockResolvedValue({});+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(caller.enableShare({ agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(mockCreate).not.toHaveBeenCalled();+ });+ });++ describe('getShareStats', () => {+ it('returns visitor aggregates and the configured cap for the owner', async () => {+ mockGetByAgentId.mockResolvedValue({+ ...share,+ shareConfig: { ...share.shareConfig, monthlySpendLimit: 10 },+ userViewCount: 42,+ });+ mockGetAgentShareMonthlySpend.mockResolvedValue(2.5);+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(caller.getShareStats({ agentId: 'agent-1' })).resolves.toEqual({+ monthlySpend: 2.5,+ monthlySpendLimit: 10,+ topicCount: 7,+ userViewCount: 42,+ visitorCount: 3,+ });+ expect(mockCountShareVisitors).toHaveBeenCalledWith({ agentId: 'agent-1' });+ expect(mockGetAgentShareMonthlySpend).toHaveBeenCalledWith({+ agentId: 'agent-1',+ ownerUserId: 'user-1',+ });+ });++ it('reports unknown spend as null rather than zero', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));++ const stats = await caller.getShareStats({ agentId: 'agent-1' });++ expect(stats.monthlySpend).toBeNull();+ });++ it('refuses stats for an agent the caller does not own', async () => {+ // `getByAgentId` is ownership-scoped, so a non-owner resolves to null.+ mockGetByAgentId.mockResolvedValue(null);+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-2' }));++ await expect(caller.getShareStats({ agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect(mockCountShareVisitors).not.toHaveBeenCalled();+ expect(mockGetAgentShareMonthlySpend).not.toHaveBeenCalled();+ });++ it('requires authentication', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner());++ await expect(caller.getShareStats({ agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+ });+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.operationReadGuard.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.operationReadGuard.test.tsnew file mode 100644index 00000000000..79b5a27be17--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.operationReadGuard.test.ts@@ -0,0 +1,149 @@+// @vitest-environment node+import { type LobeChatDatabase } from '@lobechat/database';+import { agentOperations, topics } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { aiAgentRouter } from '../aiAgent';+import { cleanupTestUser, createTestUser } from './integration/setup';++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => testDB),+}));++const mockGetOperationStatus = vi.fn();+const mockGetPendingInterventions = vi.fn();+vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(() => ({+ getOperationStatus: mockGetOperationStatus,+ getPendingInterventions: mockGetPendingInterventions,+ })),+}));++vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: vi.fn().mockImplementation(() => ({})),+}));++vi.mock('@/server/services/aiChat', () => ({+ AiChatService: vi.fn().mockImplementation(() => ({})),+}));++/**+ * Operation ids are creator-scoped but, since Agent Share, are handed to a+ * DIFFERENT user (the visitor) so they can attach to the redacted Gateway+ * stream. These read endpoints return the raw, unredacted operation metadata+ * from the coordinator, so the id alone must never be enough to read them.+ */+describe('aiAgentRouter operation read guard', () => {+ let serverDB: LobeChatDatabase;+ let ownerId: string;+ let visitorId: string;+ let operationId: string;++ beforeEach(async () => {+ serverDB = await getTestDB();+ testDB = serverDB;+ ownerId = await createTestUser(serverDB);+ visitorId = await createTestUser(serverDB);+ operationId = `op-share-run-${crypto.randomUUID()}`;++ await serverDB.insert(agentOperations).values({+ id: operationId,+ model: 'gpt-4o-mini',+ provider: 'openai',+ status: 'running',+ userId: ownerId,+ });++ mockGetOperationStatus.mockReset().mockResolvedValue({ metadata: { agentConfig: {} } });+ mockGetPendingInterventions.mockReset().mockResolvedValue({ pendingInterventions: [] });+ });++ afterEach(async () => {+ await serverDB.delete(agentOperations).where(eq(agentOperations.id, operationId));+ await cleanupTestUser(serverDB, visitorId);+ await cleanupTestUser(serverDB, ownerId);+ vi.clearAllMocks();+ });++ const callerFor = (userId: string) =>+ aiAgentRouter.createCaller({ jwtPayload: { userId }, userId } as any);++ describe('getOperationStatus', () => {+ it('lets the owner read their own operation', async () => {+ const result = await callerFor(ownerId).getOperationStatus({ operationId });++ expect(result).toEqual({ metadata: { agentConfig: {} } });+ expect(mockGetOperationStatus).toHaveBeenCalledWith(expect.objectContaining({ operationId }));+ });++ it('rejects a share visitor holding the creator-scoped operation id', async () => {+ await expect(callerFor(visitorId).getOperationStatus({ operationId })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });++ expect(mockGetOperationStatus).not.toHaveBeenCalled();+ });++ // Share runs execute under the CREATOR's userId inside a visitor topic+ // (`topics.senderId`), so plain ownership would let the creator read the+ // visitor's run — the same exclusion `findOwnOperationById` applies.+ it('hides a visitor-topic operation from its creator-owner', async () => {+ const [topic] = await serverDB+ .insert(topics)+ .values({ senderId: visitorId, title: 'visitor chat', userId: ownerId })+ .returning();+ await serverDB+ .update(agentOperations)+ .set({ topicId: topic.id })+ .where(eq(agentOperations.id, operationId));++ await expect(callerFor(ownerId).getOperationStatus({ operationId })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ await expect(+ callerFor(ownerId).getPendingInterventions({ operationId }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockGetOperationStatus).not.toHaveBeenCalled();+ expect(mockGetPendingInterventions).not.toHaveBeenCalled();+ });++ it('rejects an unknown operation id without touching the runtime', async () => {+ await expect(+ callerFor(ownerId).getOperationStatus({ operationId: 'op-does-not-exist' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockGetOperationStatus).not.toHaveBeenCalled();+ });+ });++ describe('getPendingInterventions', () => {+ it('rejects a foreign operation id', async () => {+ await expect(+ callerFor(visitorId).getPendingInterventions({ operationId }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockGetPendingInterventions).not.toHaveBeenCalled();+ });++ it("refuses to list another user's operations by userId", async () => {+ await expect(+ callerFor(visitorId).getPendingInterventions({ userId: ownerId }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });++ expect(mockGetPendingInterventions).not.toHaveBeenCalled();+ });++ it("lists only the caller's own operations", async () => {+ await callerFor(ownerId).getPendingInterventions({ userId: ownerId });++ expect(mockGetPendingInterventions).toHaveBeenCalledWith({+ operationId: undefined,+ userId: ownerId,+ });+ });+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/resourceTransferRequest.test.ts b/apps/server/src/routers/lambda/__tests__/resourceTransferRequest.test.tsindex 659999b6506..5806a6b7594 100644--- a/apps/server/src/routers/lambda/__tests__/resourceTransferRequest.test.ts+++ b/apps/server/src/routers/lambda/__tests__/resourceTransferRequest.test.ts@@ -50,7 +50,8 @@ vi.mock('@/server/services/resourcePermission', () => ({const { TRANSFER_REQUEST_EXPIRED, TRANSFER_REQUEST_NOT_PENDING } =await import('@/database/models/resourceTransferRequest');-const { AGENT_OWNERSHIP_STALE } = await import('@/database/models/agent');+const { AGENT_OWNERSHIP_STALE, AGENT_SHARED_TRANSFER_BLOCKED } =+ await import('@/database/models/agent');const { CHAT_GROUP_OWNERSHIP_STALE } = await import('@/database/models/chatGroup');const { resourceTransferRequestRouter } = await import('../resourceTransferRequest');@@ -169,6 +170,19 @@ describe('resourceTransferRequestRouter', () => {expect(mockInvalidate).toHaveBeenCalledWith('agent', ['agent-1']);});+ it('surfaces PRECONDITION_FAILED (and keeps the request pending) when the agent is still shared', async () => {+ mockFindById.mockResolvedValue(pendingRequest);+ mockExecuteAcceptedTransfer.mockRejectedValue(new Error(AGENT_SHARED_TRANSFER_BLOCKED));++ await expect(caller.accept({ requestId: 'req-1' })).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ });+ // Recoverable: the previous owner can disable sharing and the recipient+ // can retry, so the request must NOT be invalidated.+ expect(mockInvalidate).not.toHaveBeenCalled();+ expect(mockInvalidateRequest).not.toHaveBeenCalled();+ });+it('accepts a group request through the same execute path', async () => {const groupRequest = { ...pendingRequest, resourceId: 'group-1', resourceType: 'agentGroup' };mockFindById.mockResolvedValue(groupRequest);diff --git a/apps/server/src/routers/lambda/__tests__/share.test.ts b/apps/server/src/routers/lambda/__tests__/share.test.tsindex d81edbe0e94..31c62fd2b81 100644--- a/apps/server/src/routers/lambda/__tests__/share.test.ts+++ b/apps/server/src/routers/lambda/__tests__/share.test.ts@@ -1,7 +1,18 @@+import type * as BusinessConst from '@lobechat/business-const';import { TRPCError } from '@trpc/server';-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { AgentShareModel } from '@/database/models/agentShare';import { TopicShareModel } from '@/database/models/topicShare';+import { createContextInner } from '@/libs/trpc/lambda/context';++vi.mock('@/database/models/agentShare', () => ({+ AgentShareModel: {+ assertShareAccess: vi.fn(),+ findBySlugOrId: vi.fn(),+ incrementUserViewCount: vi.fn(),+ },+}));vi.mock('@/database/models/topicShare', () => ({TopicShareModel: {@@ -10,11 +21,220 @@ vi.mock('@/database/models/topicShare', () => ({},}));+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => ({})),+}));+vi.mock('@/database/server', () => ({getServerDB: vi.fn(),}));+// The availability gate (cloud-only const + visitor grayscale flag) has its+// own suite (`_helpers/__tests__/agentShareFeatureGate.test.ts`) plus a+// dedicated "visitor capability" block below; elsewhere it is pinned open so+// the read-path behavior under test is reachable.+const mocks = vi.hoisted(() => ({+ businessConst: { ENABLE_BUSINESS_FEATURES: true },+}));+vi.mock('@lobechat/business-const', async () => {+ const actual = await vi.importActual<typeof BusinessConst>('@lobechat/business-const');+ return {+ ...actual,+ // `packages/utils/src/apiKey.ts` reads this dynamically (`import * as+ // businessConst`), pulled in transitively via the unmocked+ // `createContextInner` -> `ApiKeyModel` chain below. `actual` here+ // resolves to the cloud override, which omits this key entirely (see+ // that file's own doc comment), so vitest's mock-export validation has+ // no own property to find unless it is listed explicitly.+ API_KEY_PREFIX: (actual as Record<string, unknown>).API_KEY_PREFIX,+ // A getter (not a static spread) so per-test mutation of+ // `mocks.businessConst.ENABLE_BUSINESS_FEATURES` is observed by every+ // subsequent read, including inside the already-imported gate helper.+ get ENABLE_BUSINESS_FEATURES() {+ return mocks.businessConst.ENABLE_BUSINESS_FEATURES;+ },+ };+});++const mockGetFeatureFlagsState = vi.fn();+vi.mock('@/server/featureFlags', () => ({+ getServerFeatureFlagsStateFromRuntimeConfig: (...args: unknown[]) =>+ mockGetFeatureFlagsState(...args),+}));++const { shareRouter } = await import('../share');+describe('shareRouter', () => {+ describe('getSharedAgent', () => {+ const agentShare = {+ agentAvatar: 'avatar.png',+ agentBackgroundColor: '#ffffff',+ agentDescription: 'A shared agent',+ agentId: 'agent-1',+ agentName: 'Alice',+ agentTitle: 'Research Assistant',+ ownerId: 'owner-user',+ shareConfig: { maxTopicsPerVisitor: 5, maxTurnsPerTopic: 20, slug: 'shared-agent' },+ shareId: 'agent-share-1',+ userViewCount: 42,+ visibility: 'link',+ };++ beforeEach(() => {+ vi.clearAllMocks();+ mocks.businessConst.ENABLE_BUSINESS_FEATURES = true;+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: true });+ vi.mocked(AgentShareModel.findBySlugOrId).mockResolvedValue(agentShare as any);+ vi.mocked(AgentShareModel.assertShareAccess).mockReturnValue(undefined);+ vi.mocked(AgentShareModel.incrementUserViewCount).mockResolvedValue(undefined);+ });++ it('requires authentication without resolving or counting the share', async () => {+ const caller = shareRouter.createCaller(await createContextInner());++ await expect(caller.getSharedAgent({ slugOrId: 'shared-agent' })).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+ expect(AgentShareModel.findBySlugOrId).not.toHaveBeenCalled();+ expect(AgentShareModel.incrementUserViewCount).not.toHaveBeenCalled();+ });++ it('resolves by slug, returns only visitor-safe metadata, and counts the view', async () => {+ const caller = shareRouter.createCaller(await createContextInner({ userId: 'visitor-user' }));++ const result = await caller.getSharedAgent({ slugOrId: 'shared-agent' });++ expect(result).toEqual({+ agentId: 'agent-1',+ agentMeta: {+ avatar: 'avatar.png',+ backgroundColor: '#ffffff',+ description: 'A shared agent',+ name: 'Alice',+ title: 'Research Assistant',+ },+ isOwner: false,+ shareId: 'agent-share-1',+ slug: 'shared-agent',+ visibility: 'link',+ });+ expect(result).not.toHaveProperty('ownerId');+ expect(result).not.toHaveProperty('shareConfig');+ expect(result).not.toHaveProperty('userViewCount');+ expect(AgentShareModel.findBySlugOrId).toHaveBeenCalledWith(+ expect.anything(),+ 'shared-agent',+ );+ expect(AgentShareModel.assertShareAccess).toHaveBeenCalledWith(agentShare, 'visitor-user');+ expect(AgentShareModel.incrementUserViewCount).toHaveBeenCalledWith(+ expect.anything(),+ 'agent-share-1',+ );+ });++ it('does not count owner views', async () => {+ const caller = shareRouter.createCaller(await createContextInner({ userId: 'owner-user' }));++ await expect(caller.getSharedAgent({ slugOrId: 'shared-agent' })).resolves.toMatchObject({+ isOwner: true,+ });+ expect(AgentShareModel.incrementUserViewCount).not.toHaveBeenCalled();+ });++ it('resolves by raw share id', async () => {+ const caller = shareRouter.createCaller(await createContextInner({ userId: 'visitor-user' }));++ await caller.getSharedAgent({ slugOrId: 'agent-share-1' });++ expect(AgentShareModel.findBySlugOrId).toHaveBeenCalledWith(+ expect.anything(),+ 'agent-share-1',+ );+ });++ it('allows the owner to resolve a private share', async () => {+ vi.mocked(AgentShareModel.findBySlugOrId).mockResolvedValue({+ ...agentShare,+ visibility: 'private',+ } as any);+ const caller = shareRouter.createCaller(await createContextInner({ userId: 'owner-user' }));++ await expect(caller.getSharedAgent({ slugOrId: 'shared-agent' })).resolves.toMatchObject({+ isOwner: true,+ visibility: 'private',+ });+ });++ it('still resolves the share when the view counter fails', async () => {+ vi.mocked(AgentShareModel.incrementUserViewCount).mockRejectedValue(new Error('db down'));+ const caller = shareRouter.createCaller(await createContextInner({ userId: 'visitor-user' }));++ await expect(caller.getSharedAgent({ slugOrId: 'shared-agent' })).resolves.toMatchObject({+ isOwner: false,+ shareId: 'agent-share-1',+ });+ });++ it('returns NOT_FOUND without counting a view when the slug/id does not resolve', async () => {+ vi.mocked(AgentShareModel.findBySlugOrId).mockResolvedValue(null);+ const caller = shareRouter.createCaller(await createContextInner({ userId: 'visitor-user' }));++ await expect(caller.getSharedAgent({ slugOrId: 'no-such-slug' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect(AgentShareModel.incrementUserViewCount).not.toHaveBeenCalled();+ });++ it('does not count a failed FORBIDDEN access', async () => {+ const code = 'FORBIDDEN';+ vi.mocked(AgentShareModel.assertShareAccess).mockImplementation(() => {+ throw new TRPCError({ code, message: 'This share is private' });+ });+ const caller = shareRouter.createCaller(await createContextInner({ userId: 'visitor-user' }));++ await expect(caller.getSharedAgent({ slugOrId: 'shared-agent' })).rejects.toMatchObject({+ code,+ });+ expect(AgentShareModel.incrementUserViewCount).not.toHaveBeenCalled();+ });++ describe('visitor capability', () => {+ it('rejects on a deployment without business features, even for the owner', async () => {+ mocks.businessConst.ENABLE_BUSINESS_FEATURES = false;+ const caller = shareRouter.createCaller(await createContextInner({ userId: 'owner-user' }));++ await expect(caller.getSharedAgent({ slugOrId: 'shared-agent' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(AgentShareModel.findBySlugOrId).not.toHaveBeenCalled();+ });++ it('rejects a non-owner visitor when the agent share flag is off', async () => {+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: false });+ const caller = shareRouter.createCaller(+ await createContextInner({ userId: 'visitor-user' }),+ );++ await expect(caller.getSharedAgent({ slugOrId: 'shared-agent' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(mockGetFeatureFlagsState).toHaveBeenCalledWith('visitor-user');+ expect(AgentShareModel.incrementUserViewCount).not.toHaveBeenCalled();+ });++ it('still lets the owner preview their own share when the agent share flag is off', async () => {+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: false });+ const caller = shareRouter.createCaller(await createContextInner({ userId: 'owner-user' }));++ await expect(caller.getSharedAgent({ slugOrId: 'shared-agent' })).resolves.toMatchObject({+ isOwner: true,+ });+ // The owner path never consults the agent share flag at all.+ expect(mockGetFeatureFlagsState).not.toHaveBeenCalled();+ });+ });+ });+describe('getSharedTopic', () => {it('should return shared topic data for valid share', async () => {const mockShare = {diff --git a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts b/apps/server/src/routers/lambda/__tests__/shareChat.test.tsnew file mode 100644index 00000000000..5e8597b6291--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/shareChat.test.ts@@ -0,0 +1,584 @@+// @vitest-environment node+import type * as BusinessConst from '@lobechat/business-const';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as MessageModelModule from '@/database/models/message';+import { createContextInner } from '@/libs/trpc/lambda/context';++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => ({})),+}));++// Pin the cloud-only capability open so the visitor procedures under test are+// reachable: ENABLE_BUSINESS_FEATURES is false in OSS builds, and the+// shareChatProcedure middleware (`_helpers/agentShareFeatureGate.ts`) would+// otherwise reject everything with FORBIDDEN before reaching any of the+// behavior these tests exercise. The "gate itself" is covered separately by+// `_helpers/__tests__/agentShareFeatureGate.test.ts` and the dedicated+// "visitor capability" describe block below.+const mocks = vi.hoisted(() => ({+ businessConst: { ENABLE_BUSINESS_FEATURES: true },+}));+vi.mock('@lobechat/business-const', async () => {+ const actual = await vi.importActual<typeof BusinessConst>('@lobechat/business-const');+ return {+ ...actual,+ // `packages/utils/src/apiKey.ts` reads this dynamically (`import * as+ // businessConst`), pulled in transitively via the unmocked+ // `createContextInner` -> `ApiKeyModel` chain below. `actual` here+ // resolves to the cloud override, which omits this key entirely (see+ // that file's own doc comment), so vitest's mock-export validation has+ // no own property to find unless it is listed explicitly.+ API_KEY_PREFIX: (actual as Record<string, unknown>).API_KEY_PREFIX,+ // A getter (not a static spread) so per-test mutation of+ // `mocks.businessConst.ENABLE_BUSINESS_FEATURES` is observed by every+ // subsequent read, including inside the already-imported gate helper.+ get ENABLE_BUSINESS_FEATURES() {+ return mocks.businessConst.ENABLE_BUSINESS_FEATURES;+ },+ };+});++const mockGetFeatureFlagsState = vi.fn();+vi.mock('@/server/featureFlags', () => ({+ getServerFeatureFlagsStateFromRuntimeConfig: (...args: unknown[]) =>+ mockGetFeatureFlagsState(...args),+}));++const mockAccessCheck = vi.fn();+vi.mock('@/database/models/agentShare', () => ({+ AgentShareModel: { findByShareIdWithAccessCheck: (...args: any[]) => mockAccessCheck(...args) },+}));++const mockFindById = vi.fn();+const mockCountBySender = vi.fn();+const mockQueryBySender = vi.fn();+const TopicModelMock = vi.fn(() => ({+ countBySender: mockCountBySender,+ findById: mockFindById,+ queryBySender: mockQueryBySender,+}));+vi.mock('@/database/models/topic', () => ({+ TopicModel: TopicModelMock,+}));++const mockMessageCountByTopic = vi.fn();+const mockMessageQuery = vi.fn();+const mockMessageQueryForVisitor = vi.fn();+vi.mock('@/database/models/message', async (importOriginal) => {+ // Keep the real `sanitizeVisitorError` (rather than re-stubbing it) so the+ // startup-error regression below exercises the SAME projection shareChat+ // reuses in production — not a test-only stand-in that could silently+ // drift from it.+ const actual = await importOriginal<typeof MessageModelModule>();+ return {+ ...actual,+ MessageModel: vi.fn(() => ({+ countByTopic: mockMessageCountByTopic,+ query: mockMessageQuery,+ queryForVisitor: mockMessageQueryForVisitor,+ })),+ };+});++vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn(() => ({ getUserSettings: vi.fn().mockResolvedValue({}) })),+}));++const mockExecAgent = vi.fn();+const mockInterruptTask = vi.fn();+const AiAgentServiceMock = vi.fn(() => ({+ execAgent: mockExecAgent,+ interruptTask: mockInterruptTask,+}));+vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: AiAgentServiceMock,+}));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(() => ({ getFileAccessUrl: vi.fn() })),+}));++const mockSpendGate = vi.fn();+vi.mock('@/business/server/agent-share/spendGate', () => ({+ checkAgentShareSpendAllowance: (...args: any[]) => mockSpendGate(...args),+}));++const mockSignUserJWT = vi.fn();+vi.mock('@/libs/trpc/utils/internalJwt', () => ({+ signUserJWT: (...args: any[]) => mockSignUserJWT(...args),+}));++const { shareChatRouter } = await import('../shareChat');++const VISITOR = 'visitor-1';+const OWNER = 'owner-1';++const share = {+ agentId: 'agt_share',+ ownerId: OWNER,+ shareConfig: {+ allowReadMemory: false,+ toolGrants: [],+ maxTopicsPerVisitor: 2,+ maxTurnsPerTopic: 3,+ },+ shareId: 'share-1',+ visibility: 'link',+};++const visitorTopic = {+ agentId: share.agentId,+ id: 'tpc_visitor',+ metadata: { runningOperation: { operationId: 'op-1' } },+ senderId: VISITOR,+};++const createCaller = async () =>+ shareChatRouter.createCaller(await createContextInner({ userId: VISITOR }));++describe('shareChatRouter', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.businessConst.ENABLE_BUSINESS_FEATURES = true;+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: true });+ mockAccessCheck.mockResolvedValue(share);+ mockFindById.mockResolvedValue(visitorTopic);+ mockCountBySender.mockResolvedValue(0);+ mockQueryBySender.mockResolvedValue([]);+ mockMessageCountByTopic.mockResolvedValue(0);+ mockMessageQuery.mockResolvedValue([]);+ mockExecAgent.mockResolvedValue({ operationId: 'op-1', success: true });+ mockInterruptTask.mockResolvedValue({ operationId: 'op-1', success: true });+ mockSignUserJWT.mockResolvedValue('visitor-jwt');+ mockSpendGate.mockResolvedValue({ allowed: true });+ });++ describe('execAgent', () => {+ // The owner never uses the visitor chain, so this entry point demands the+ // same `link` visibility the per-step revalidation+ // (`AgentShareModel.isRunStillAuthorized`) demands — otherwise an owner+ // previewing their own private share could start a run its own step loop+ // would immediately abort.+ it('rejects a share that is not link-visible, even for the owner', async () => {+ mockAccessCheck.mockResolvedValue({ ...share, visibility: 'private' });+ const caller = await createCaller();++ await expect(caller.execAgent({ prompt: 'hi', shareId: 'share-1' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(mockExecAgent).not.toHaveBeenCalled();+ });++ // The spend gate runs before ANY row is created, so a rejected run leaves+ // no orphan topic / placeholder assistant message behind.+ it('rejects the run when the spend gate vetoes it, before any topic lookup', async () => {+ mockSpendGate.mockResolvedValue({ allowed: false });+ const caller = await createCaller();++ await expect(caller.execAgent({ prompt: 'hi', shareId: 'share-1' })).rejects.toMatchObject({+ code: 'TOO_MANY_REQUESTS',+ message: 'ShareSpendLimitExceeded',+ });+ expect(mockCountBySender).not.toHaveBeenCalled();+ expect(mockExecAgent).not.toHaveBeenCalled();+ });++ it('passes the creator, share and configured cap to the spend gate', async () => {+ mockAccessCheck.mockResolvedValue({+ ...share,+ shareConfig: { ...share.shareConfig, monthlySpendLimit: 25 },+ });+ const caller = await createCaller();++ await caller.execAgent({ prompt: 'hi', shareId: 'share-1' });++ expect(mockSpendGate).toHaveBeenCalledWith({+ agentId: share.agentId,+ monthlySpendLimit: 25,+ ownerUserId: OWNER,+ shareId: 'share-1',+ visitorUserId: VISITOR,+ });+ });++ it('rejects a new-topic run once the visitor topic cap is reached', async () => {+ mockCountBySender.mockResolvedValue(2);+ const caller = await createCaller();++ await expect(caller.execAgent({ prompt: 'hi', shareId: 'share-1' })).rejects.toMatchObject({+ code: 'TOO_MANY_REQUESTS',+ message: 'ShareTopicLimitExceeded',+ });+ expect(mockExecAgent).not.toHaveBeenCalled();+ });++ it('rejects an existing-topic run once the turn cap is reached', async () => {+ mockMessageCountByTopic.mockResolvedValue(3);+ const caller = await createCaller();++ await expect(+ caller.execAgent({ prompt: 'hi', shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).rejects.toMatchObject({+ code: 'TOO_MANY_REQUESTS',+ message: 'ShareTurnLimitExceeded',+ });+ expect(mockMessageCountByTopic).toHaveBeenCalledWith({+ role: 'user',+ topicId: 'tpc_visitor',+ });+ expect(mockExecAgent).not.toHaveBeenCalled();+ });++ it("fails closed when the topic is not the visitor's own share topic", async () => {+ mockFindById.mockResolvedValue({ ...visitorTopic, senderId: 'someone-else' });+ const caller = await createCaller();++ await expect(+ caller.execAgent({ prompt: 'hi', shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockExecAgent).not.toHaveBeenCalled();+ });++ it('dispatches a creator-scoped run carrying the share gate', async () => {+ const caller = await createCaller();++ await expect(caller.execAgent({ prompt: 'hi', shareId: 'share-1' })).resolves.toMatchObject({+ operationId: 'op-1',+ });++ // Service runs as the CREATOR — the share's owner, never the visitor.+ expect(AiAgentServiceMock).toHaveBeenCalledWith(expect.anything(), OWNER, expect.any(Object));+ expect(mockExecAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ // Agent id comes from the share record, not client input.+ agentId: share.agentId,+ shareGate: {+ agentId: share.agentId,+ shareConfig: share.shareConfig,+ shareId: share.shareId,+ visitorUserId: VISITOR,+ },+ }),+ );+ });++ // Regression for Codex P1 (LOBE-11930, `shareChat.ts` prompt schema): a+ // direct RPC caller (bypassing any client-side textarea limit) could+ // previously submit an HTTP-infrastructure-limit-sized `prompt`, which+ // `AiAgentService.execAgent` would persist verbatim into the CREATOR's+ // messages before any topic/turn cap even runs (those gate request+ // COUNT, not per-request SIZE). The schema now rejects an oversized+ // prompt before any row is touched.+ it('rejects an oversized prompt before any DB row is touched', async () => {+ const caller = await createCaller();+ const oversizedPrompt = 'a'.repeat(20_001);++ await expect(+ caller.execAgent({ prompt: oversizedPrompt, shareId: 'share-1' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mockAccessCheck).not.toHaveBeenCalled();+ expect(mockExecAgent).not.toHaveBeenCalled();+ });++ it('accepts a prompt right at the size limit', async () => {+ const caller = await createCaller();+ const maxPrompt = 'a'.repeat(20_000);++ await expect(+ caller.execAgent({ prompt: maxPrompt, shareId: 'share-1' }),+ ).resolves.toMatchObject({ operationId: 'op-1' });+ });++ // Regression for Codex P2 (LOBE-11930): a startup failure BEFORE Gateway+ // streaming begins (e.g. the queue/runtime backend returning a raw+ // diagnostic) must not reach the visitor verbatim — the run executes+ // under the CREATOR's identity, so `error.message` here can carry+ // provider/infra detail. `toVisitorSafeStartupError` must project it+ // through the same `sanitizeVisitorError` classification used elsewhere+ // in this branch, not echo it back raw.+ it('redacts a diagnostic startup failure instead of leaking it to the visitor', async () => {+ const diagnostic = new Error(+ 'ECONNREFUSED connecting to internal-runtime-queue.prod.internal:6379 (provider=openai, apiKey=sk-***)',+ );+ mockExecAgent.mockRejectedValueOnce(diagnostic);+ const caller = await createCaller();++ const rejection = caller.execAgent({ prompt: 'hi', shareId: 'share-1' });+ await expect(rejection).rejects.toMatchObject({ code: 'INTERNAL_SERVER_ERROR' });+ await rejection.catch((error: any) => {+ expect(error.message).not.toContain('internal-runtime-queue');+ expect(error.message).not.toContain('openai');+ expect(error.message).not.toContain('sk-');+ });+ });++ // Regression for Codex P2 follow-up (LOBE-11930, `shareChat.ts:249`):+ // `AiAgentService.execAgent` RESOLVES (rather than throws) with+ // `{ success: false, error }` when `createOperation` itself fails to+ // start (see `aiAgent/index.ts`'s `execAgent` catch block) — a case the+ // surrounding try/catch above never sees because nothing was thrown.+ // Without a check on the resolved value, that raw `error` (and the+ // whole "started" shape) would flow straight back to the visitor and+ // the Gateway client would try to open a WebSocket for an operation+ // that never began.+ it('redacts a RESOLVED (not thrown) startup failure and never returns it as a live operation', async () => {+ const diagnostic =+ 'QStash publish failed: 503 from internal-queue.prod.internal (token=shhh)';+ mockExecAgent.mockResolvedValueOnce({+ agentId: share.agentId,+ assistantMessageId: 'msg_assistant',+ autoStarted: false,+ createdAt: new Date().toISOString(),+ error: diagnostic,+ message: 'Agent operation failed to start',+ operationId: 'op-failed',+ status: 'error',+ success: false,+ timestamp: new Date().toISOString(),+ topicId: 'tpc_visitor',+ userMessageId: 'msg_user',+ });+ const caller = await createCaller();++ const rejection = caller.execAgent({ prompt: 'hi', shareId: 'share-1' });+ await expect(rejection).rejects.toMatchObject({ code: 'INTERNAL_SERVER_ERROR' });+ await rejection.catch((error: any) => {+ expect(error.message).not.toContain('internal-queue');+ expect(error.message).not.toContain('token=shhh');+ });+ });++ it('never sets interactiveStart, so concurrent visitor sends contend on the real runningOperation liveness instead of only the short reservation', async () => {+ // Regression for Codex P1 (LOBE-11930, `shareChat.ts:186`): `interactiveStart:+ // true` makes `TopicModel.tryReserveTaskCallback` skip its `runningOperation`+ // liveness check entirely (`ignoreRunningOperation`) and contend only on the+ // short-lived `taskCallbackReservation`, which is released right after the+ // FIRST operation is created — long before it finishes running. That let a+ // second concurrent visitor send for the same topic claim the topic-start+ // reservation too, create its own creator-credentialed operation, and+ // overwrite the topic's `runningOperation` marker, orphaning the first+ // operation beyond the reach of `interruptTask` / the revocation sweep. See+ // `topicStartReservation.shareVisitorConcurrency.race.test.ts` for the+ // real-Postgres proof of the underlying reservation mechanics this pins.+ const caller = await createCaller();++ await caller.execAgent({ prompt: 'hi', shareId: 'share-1' });++ expect(mockExecAgent).toHaveBeenCalledWith(+ expect.objectContaining({ interactiveStart: false }),+ );+ });+ });++ describe('interruptTask', () => {+ it('interrupts a running operation that matches the topic ownership and running marker', async () => {+ const caller = await createCaller();++ await expect(+ caller.interruptTask({ operationId: 'op-1', shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).resolves.toMatchObject({ operationId: 'op-1', success: true });++ // Service runs as the CREATOR — the run's operation/thread rows live there.+ expect(AiAgentServiceMock).toHaveBeenCalledWith(expect.anything(), OWNER, {+ includeShareVisitor: true,+ });+ expect(mockInterruptTask).toHaveBeenCalledWith({+ operationId: 'op-1',+ topicId: 'tpc_visitor',+ });+ });++ it("fails closed when the topic is not the visitor's own share topic", async () => {+ mockFindById.mockResolvedValue({ ...visitorTopic, senderId: 'someone-else' });+ const caller = await createCaller();++ await expect(+ caller.interruptTask({ operationId: 'op-1', shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockInterruptTask).not.toHaveBeenCalled();+ });++ it('rejects an operationId that does not match the topic’s current running operation', async () => {+ const caller = await createCaller();++ await expect(+ caller.interruptTask({+ operationId: 'op-someone-elses',+ shareId: 'share-1',+ topicId: 'tpc_visitor',+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockInterruptTask).not.toHaveBeenCalled();+ });++ it('rejects when the topic has no running operation at all', async () => {+ mockFindById.mockResolvedValue({ ...visitorTopic, metadata: {} });+ const caller = await createCaller();++ await expect(+ caller.interruptTask({ operationId: 'op-1', shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockInterruptTask).not.toHaveBeenCalled();+ });++ // Regression for Codex P2 (LOBE-11930): same startup-failure redaction as+ // `execAgent` — `AiAgentService.interruptTask` also runs creator-scoped+ // and can throw a raw infra/provider diagnostic before any Gateway event+ // exists to sanitize.+ it('redacts a diagnostic interrupt failure instead of leaking it to the visitor', async () => {+ const diagnostic = new Error(+ 'pg driver error: relation "operations_internal" does not exist',+ );+ mockInterruptTask.mockRejectedValueOnce(diagnostic);+ const caller = await createCaller();++ const rejection = caller.interruptTask({+ operationId: 'op-1',+ shareId: 'share-1',+ topicId: 'tpc_visitor',+ });+ await expect(rejection).rejects.toMatchObject({ code: 'INTERNAL_SERVER_ERROR' });+ await rejection.catch((error: any) => {+ expect(error.message).not.toContain('operations_internal');+ expect(error.message).not.toContain('pg driver');+ });+ });+ });++ describe('getTopics', () => {+ it("returns only the visitor's own topics via agentId + senderId scoping", async () => {+ const caller = await createCaller();+ await caller.getTopics({ shareId: 'share-1' });++ // Topic model is creator-scoped; the query narrows to this visitor's own+ // topics on this agent. `agent_shares` is 1:1 per agent, so `(agentId,+ // senderId)` unambiguously identifies the share conversation without a+ // share-instance column on `topics`.+ expect(TopicModelMock).toHaveBeenCalledWith(expect.anything(), OWNER, undefined, undefined, {+ includeShareVisitor: true,+ });+ expect(mockQueryBySender).toHaveBeenCalledWith({+ agentId: share.agentId,+ senderId: VISITOR,+ });+ });++ it('does not tie the list page size to the live maxTopicsPerVisitor cap', async () => {+ // The cap only gates admission of NEW topics. A creator lowering it below+ // what a visitor already created must not hide those older conversations —+ // the visitor surface has no pagination or deep links to recover them.+ mockAccessCheck.mockResolvedValue({+ ...share,+ shareConfig: { ...share.shareConfig, maxTopicsPerVisitor: 1 },+ });+ const caller = await createCaller();+ await caller.getTopics({ shareId: 'share-1' });++ expect(mockQueryBySender).toHaveBeenCalledWith({+ agentId: share.agentId,+ senderId: VISITOR,+ });+ });+ });++ describe('getMessages', () => {+ it('rejects a topic on a different agent of the same creator', async () => {+ mockFindById.mockResolvedValue({ ...visitorTopic, agentId: 'agt_other' });+ const caller = await createCaller();++ await expect(+ caller.getMessages({ shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockMessageQueryForVisitor).not.toHaveBeenCalled();+ });++ it('serves messages without Work summaries', async () => {+ const caller = await createCaller();+ await caller.getMessages({ shareId: 'share-1', topicId: 'tpc_visitor' });++ expect(mockMessageQueryForVisitor).toHaveBeenCalledWith(+ { skipWorks: true, topicId: 'tpc_visitor' },+ expect.objectContaining({+ redaction: {+ showErrorDetails: undefined,+ showModelInfo: undefined,+ },+ }),+ );+ });++ it('uses the visitor-redacted read path, never the raw creator-scoped query()', async () => {+ // Regression: getMessages must call `queryForVisitor` (which strips the+ // creator's sender/spend fields), not `query()` — see message.ts+ // `toVisitorMessage` for what that redaction guards against.+ const caller = await createCaller();+ await caller.getMessages({ shareId: 'share-1', topicId: 'tpc_visitor' });++ expect(mockMessageQuery).not.toHaveBeenCalled();+ });+ });++ describe('refreshGatewayToken', () => {+ it('signs the token for the VISITOR, never the creator', async () => {+ const caller = await createCaller();++ await expect(+ caller.refreshGatewayToken({ shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).resolves.toEqual({ token: 'visitor-jwt' });+ expect(mockSignUserJWT).toHaveBeenCalledWith(VISITOR);+ });++ it('rejects when the topic has no running operation', async () => {+ mockFindById.mockResolvedValue({ ...visitorTopic, metadata: {} });+ const caller = await createCaller();++ await expect(+ caller.refreshGatewayToken({ shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockSignUserJWT).not.toHaveBeenCalled();+ });+ });++ it('requires authentication', async () => {+ const caller = shareChatRouter.createCaller(await createContextInner());++ await expect(caller.getTopics({ shareId: 'share-1' })).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+ });++ describe('visitor capability', () => {+ it('rejects on a deployment without business features, before any share lookup', async () => {+ mocks.businessConst.ENABLE_BUSINESS_FEATURES = false;+ const caller = await createCaller();++ await expect(caller.getTopics({ shareId: 'share-1' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(mockAccessCheck).not.toHaveBeenCalled();+ });++ it('rejects every procedure when the agent share flag is off for this visitor', async () => {+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: false });+ const caller = await createCaller();++ await expect(caller.getTopics({ shareId: 'share-1' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(+ caller.getMessages({ shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(caller.execAgent({ prompt: 'hi', shareId: 'share-1' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(+ caller.interruptTask({ operationId: 'op-1', shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(+ caller.refreshGatewayToken({ shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mockAccessCheck).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts b/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.tsnew file mode 100644index 00000000000..9c6d584e66b--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts@@ -0,0 +1,428 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++// serverDatabase middleware calls getServerDB(); stub it (the model mocks+// ignore the db handle anyway).+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => ({})),+}));++const mockTopicFindOwnTopicById = vi.fn();+const mockTopicFindShareVisitorTopicIds = vi.fn();+const mockTopicFindOwnersByIds = vi.fn();+const mockTopicBatchCreate = vi.fn();+const mockTopicBatchMoveToAgent = vi.fn();+const mockTopicCreate = vi.fn();+const mockTopicDelete = vi.fn();+const mockTopicDuplicate = vi.fn();+const mockTopicSettleRunningOperation = vi.fn();+const mockTopicUpdate = vi.fn();+vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn(() => ({+ batchCreate: mockTopicBatchCreate,+ batchMoveToAgent: mockTopicBatchMoveToAgent,+ create: mockTopicCreate,+ delete: mockTopicDelete,+ duplicate: mockTopicDuplicate,+ findOwnersByIds: mockTopicFindOwnersByIds,+ findOwnTopicById: mockTopicFindOwnTopicById,+ findShareVisitorTopicIds: mockTopicFindShareVisitorTopicIds,+ settleRunningOperation: mockTopicSettleRunningOperation,+ update: mockTopicUpdate,+ })),+}));++const mockMessageFindShareVisitorMessageIds = vi.fn();+const mockMessageDeleteMessagesBySession = vi.fn();+const mockMessageUpdateTTS = vi.fn();+const mockMessageUpdateTranslate = vi.fn();+vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn(() => ({+ deleteMessagesBySession: mockMessageDeleteMessagesBySession,+ findShareVisitorMessageIds: mockMessageFindShareVisitorMessageIds,+ updateTTS: mockMessageUpdateTTS,+ updateTranslate: mockMessageUpdateTranslate,+ })),+}));++const mockServiceAddFilesToMessage = vi.fn();+const mockServiceBatchMutate = vi.fn();+const mockServiceCancelCompression = vi.fn();+const mockServiceCreateCompressionGroup = vi.fn();+const mockServiceCreateMessage = vi.fn();+const mockServiceFinalizeCompression = vi.fn();+const mockServiceUpdateMessage = vi.fn();+const mockServiceUpdateMessageGroupMetadata = vi.fn();+const mockServiceUpdateMessagePlugin = vi.fn();+const mockServiceUpdateToolArguments = vi.fn();+vi.mock('@/server/services/message', () => ({+ MessageService: vi.fn(() => ({+ addFilesToMessage: mockServiceAddFilesToMessage,+ batchMutate: mockServiceBatchMutate,+ cancelCompression: mockServiceCancelCompression,+ createCompressionGroup: mockServiceCreateCompressionGroup,+ createMessage: mockServiceCreateMessage,+ finalizeCompression: mockServiceFinalizeCompression,+ updateMessage: mockServiceUpdateMessage,+ updateMessageGroupMetadata: mockServiceUpdateMessageGroupMetadata,+ updateMessagePlugin: mockServiceUpdateMessagePlugin,+ updateToolArguments: mockServiceUpdateToolArguments,+ })),+}));++const mockFindDeletableFilesByTopicId = vi.fn();+const mockFileDeleteMany = vi.fn();+vi.mock('@/database/models/file', () => ({+ FileModel: vi.fn(() => ({+ deleteMany: mockFileDeleteMany,+ findDeletableFilesByTopicId: mockFindDeletableFilesByTopicId,+ })),+}));++const mockDeleteFiles = vi.fn();+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(() => ({ deleteFiles: mockDeleteFiles })),+}));++// Topic creation canonicalizes agent/session through the DB; the guard under+// test runs after that step, so short-circuit it.+vi.mock('../_helpers/resolveContext', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ resolveContextWithAgentId: vi.fn(async (input: { agentId?: string }) => ({+ agentId: input.agentId,+ sessionId: 'session-1',+ })),+}));++const { topicRouter } = await import('../topic');+const { messageRouter } = await import('../message');++const userId = 'user-creator';+const visitorTopicId = 'topic-visitor';+const visitorMessageId = 'msg-visitor';++const topicCaller = () => topicRouter.createCaller({ userId } as any);+const messageCaller = () => messageRouter.createCaller({ userId } as any);++/**+ * Agent-share visitor conversations are owned by the creator's `userId`, so+ * every creator-facing write RPC must refuse a raw visitor id.+ */+describe('agent-share visitor guards on creator-facing RPCs', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ // Default: nothing the caller names is a visitor row.+ mockTopicFindShareVisitorTopicIds.mockResolvedValue([]);+ mockMessageFindShareVisitorMessageIds.mockResolvedValue([]);+ mockTopicDelete.mockResolvedValue({ rowCount: 1 });+ mockTopicUpdate.mockResolvedValue([{ id: 'topic-1' }]);+ mockFindDeletableFilesByTopicId.mockResolvedValue(['file-1']);+ mockFileDeleteMany.mockResolvedValue([{ url: 's3://file-1' }]);+ mockTopicFindOwnTopicById.mockResolvedValue({ id: 'topic-1', userId });+ mockTopicFindOwnersByIds.mockResolvedValue([]);+ });++ describe('topic.removeTopic', () => {+ it('does not delete attachments when the id is a visitor topic', async () => {+ // The visitor topic is invisible to `findOwnTopicById`, and+ // `TopicModel.delete` refuses to remove it — so its files must survive.+ mockTopicFindOwnTopicById.mockResolvedValue(undefined);++ await topicCaller().removeTopic({ id: visitorTopicId, removeFiles: true });++ expect(mockFindDeletableFilesByTopicId).not.toHaveBeenCalled();+ expect(mockFileDeleteMany).not.toHaveBeenCalled();+ expect(mockDeleteFiles).not.toHaveBeenCalled();+ });++ it('still deletes attachments of the creator’s own topic', async () => {+ await topicCaller().removeTopic({ id: 'topic-1', removeFiles: true });++ expect(mockFindDeletableFilesByTopicId).toHaveBeenCalledWith('topic-1');+ expect(mockDeleteFiles).toHaveBeenCalledWith(['s3://file-1']);+ });+ });++ describe('topic.updateTopic', () => {+ it('rejects a visitor topic with NOT_FOUND and never updates', async () => {+ mockTopicFindShareVisitorTopicIds.mockResolvedValue([visitorTopicId]);++ await expect(+ topicCaller().updateTopic({ id: visitorTopicId, value: { title: 'hacked' } }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockTopicUpdate).not.toHaveBeenCalled();+ });++ it('updates the creator’s own topic', async () => {+ await topicCaller().updateTopic({ id: 'topic-1', value: { title: 'ok' } });++ expect(mockTopicUpdate).toHaveBeenCalled();+ });+ });++ describe('topic.batchMoveTopics', () => {+ it('rejects a visitor topic with NOT_FOUND and never moves', async () => {+ mockTopicFindShareVisitorTopicIds.mockResolvedValue([visitorTopicId]);++ await expect(+ topicCaller().batchMoveTopics({ targetAgentId: 'agent-1', topicIds: [visitorTopicId] }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockTopicBatchMoveToAgent).not.toHaveBeenCalled();+ });+ });++ describe('topic.cloneTopic', () => {+ it('rejects a visitor topic with NOT_FOUND and never duplicates', async () => {+ mockTopicFindShareVisitorTopicIds.mockResolvedValue([visitorTopicId]);++ await expect(topicCaller().cloneTopic({ id: visitorTopicId })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });++ expect(mockTopicDuplicate).not.toHaveBeenCalled();+ });+ });++ describe('topic.settleRunningOperation', () => {+ it('rejects a visitor topic with NOT_FOUND and never settles', async () => {+ mockTopicFindShareVisitorTopicIds.mockResolvedValue([visitorTopicId]);++ await expect(+ topicCaller().settleRunningOperation({ id: visitorTopicId, operationId: 'op-1' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockTopicSettleRunningOperation).not.toHaveBeenCalled();+ });+ });++ describe('message write RPCs', () => {+ beforeEach(() => {+ mockMessageFindShareVisitorMessageIds.mockResolvedValue([visitorMessageId]);+ });++ it('message.update rejects a visitor message with NOT_FOUND', async () => {+ await expect(+ messageCaller().update({ id: visitorMessageId, value: { content: 'hacked' } }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockServiceUpdateMessage).not.toHaveBeenCalled();+ });++ it('message.updateMessagePlugin rejects a visitor message with NOT_FOUND', async () => {+ await expect(+ messageCaller().updateMessagePlugin({ id: visitorMessageId, value: { toolCallId: 'x' } }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockServiceUpdateMessagePlugin).not.toHaveBeenCalled();+ });++ it('message.updateTTS rejects a visitor message with NOT_FOUND', async () => {+ await expect(+ messageCaller().updateTTS({ id: visitorMessageId, value: { voice: 'alloy' } }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockMessageUpdateTTS).not.toHaveBeenCalled();+ });++ it('message.updateTranslate rejects a visitor message with NOT_FOUND', async () => {+ await expect(+ messageCaller().updateTranslate({ id: visitorMessageId, value: { to: 'zh-CN' } }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockMessageUpdateTranslate).not.toHaveBeenCalled();+ });++ it('message.batchMutate rejects a batch that targets a visitor message with NOT_FOUND', async () => {+ await expect(+ messageCaller().batchMutate({+ operations: [+ { id: 'msg-1', type: 'updateMessage', value: { content: 'ok' } },+ { id: visitorMessageId, type: 'updateToolMessage', value: { content: 'hacked' } },+ ],+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockServiceBatchMutate).not.toHaveBeenCalled();+ });++ it('message.addFilesToMessage rejects a visitor message with NOT_FOUND', async () => {+ await expect(+ messageCaller().addFilesToMessage({ fileIds: ['file-1'], id: visitorMessageId }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockServiceAddFilesToMessage).not.toHaveBeenCalled();+ });++ it('lets the creator update their own message', async () => {+ mockMessageFindShareVisitorMessageIds.mockResolvedValue([]);+ mockServiceUpdateMessage.mockResolvedValue({ messages: [], success: true });++ await messageCaller().update({ id: 'msg-1', value: { content: 'ok' } });++ expect(mockServiceUpdateMessage).toHaveBeenCalled();+ });+ });++ describe('message write RPCs guarded by topicId', () => {+ beforeEach(() => {+ mockTopicFindShareVisitorTopicIds.mockResolvedValue([visitorTopicId]);+ });++ it('message.updateToolArguments rejects a visitor topic with NOT_FOUND', async () => {+ await expect(+ messageCaller().updateToolArguments({+ toolCallId: 'tool-1',+ topicId: visitorTopicId,+ value: 'hacked',+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockServiceUpdateToolArguments).not.toHaveBeenCalled();+ });++ it('message.removeMessagesByAssistant rejects a visitor topic with NOT_FOUND', async () => {+ await expect(+ messageCaller().removeMessagesByAssistant({ topicId: visitorTopicId }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockMessageDeleteMessagesBySession).not.toHaveBeenCalled();+ });++ it('message.removeMessagesByGroup rejects a visitor topic with NOT_FOUND', async () => {+ await expect(+ messageCaller().removeMessagesByGroup({ groupId: 'group-1', topicId: visitorTopicId }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockMessageDeleteMessagesBySession).not.toHaveBeenCalled();+ });++ it('message.cancelCompression rejects a visitor topic with NOT_FOUND', async () => {+ await expect(+ messageCaller().cancelCompression({+ agentId: 'agent-1',+ messageGroupId: 'group-1',+ topicId: visitorTopicId,+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockServiceCancelCompression).not.toHaveBeenCalled();+ });++ it('message.createCompressionGroup rejects a visitor topic with NOT_FOUND', async () => {+ await expect(+ messageCaller().createCompressionGroup({+ agentId: 'agent-1',+ messageIds: ['msg-1'],+ topicId: visitorTopicId,+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockServiceCreateCompressionGroup).not.toHaveBeenCalled();+ });++ it('message.finalizeCompression rejects a visitor topic with NOT_FOUND', async () => {+ await expect(+ messageCaller().finalizeCompression({+ agentId: 'agent-1',+ content: 'summary',+ messageGroupId: 'group-1',+ topicId: visitorTopicId,+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockServiceFinalizeCompression).not.toHaveBeenCalled();+ });++ it('message.updateMessageGroupMetadata rejects a visitor topic with NOT_FOUND', async () => {+ await expect(+ messageCaller().updateMessageGroupMetadata({+ context: { agentId: 'agent-1', topicId: visitorTopicId },+ expanded: true,+ messageGroupId: 'group-1',+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockServiceUpdateMessageGroupMetadata).not.toHaveBeenCalled();+ });+ });++ // Creation paths name no existing message id, but they can still reach a+ // visitor transcript: a new message can be appended INTO a visitor topic,+ // and a new topic can ADOPT visitor messages (reparenting them out of the+ // `senderId` scope the visitor predicates key on).+ describe('creation paths', () => {+ beforeEach(() => {+ mockTopicFindShareVisitorTopicIds.mockImplementation(async (ids: string[]) =>+ ids.filter((id) => id === visitorTopicId),+ );+ mockMessageFindShareVisitorMessageIds.mockImplementation(async (ids: string[]) =>+ ids.filter((id) => id === visitorMessageId),+ );+ });++ it('message.createMessage rejects a visitor topic with NOT_FOUND', async () => {+ await expect(+ messageCaller().createMessage({+ agentId: 'agent-1',+ content: 'injected',+ role: 'user',+ topicId: visitorTopicId,+ } as any),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockServiceCreateMessage).not.toHaveBeenCalled();+ });++ it('message.batchMutate rejects a createMessage into a visitor topic with NOT_FOUND', async () => {+ await expect(+ messageCaller().batchMutate({+ operations: [+ {+ message: { agentId: 'agent-1', content: 'x', role: 'user', topicId: visitorTopicId },+ type: 'createMessage',+ } as any,+ ],+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockServiceBatchMutate).not.toHaveBeenCalled();+ });++ it('topic.createTopic rejects adopting a visitor message with NOT_FOUND', async () => {+ await expect(+ topicCaller().createTopic({+ agentId: 'agent-1',+ messages: ['msg-1', visitorMessageId],+ title: 'stolen',+ } as any),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockTopicCreate).not.toHaveBeenCalled();+ });++ it('topic.batchCreateTopics rejects adopting a visitor message with NOT_FOUND', async () => {+ await expect(+ topicCaller().batchCreateTopics([+ { agentId: 'agent-1', messages: ['msg-1'], title: 'fine' },+ { agentId: 'agent-1', messages: [visitorMessageId], title: 'stolen' },+ ] as any),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(mockTopicBatchCreate).not.toHaveBeenCalled();+ });++ it('still lets the creator create a topic adopting their own messages', async () => {+ mockTopicCreate.mockResolvedValue({ id: 'topic-new' });++ await topicCaller().createTopic({+ agentId: 'agent-1',+ messages: ['msg-1'],+ title: 'ok',+ } as any);++ expect(mockTopicCreate).toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/topicShare.router.test.ts b/apps/server/src/routers/lambda/__tests__/topicShare.router.test.tsindex e7200b25e47..c52834d76b3 100644--- a/apps/server/src/routers/lambda/__tests__/topicShare.router.test.ts+++ b/apps/server/src/routers/lambda/__tests__/topicShare.router.test.ts@@ -8,9 +8,9 @@ vi.mock('@/database/core/db-adaptor', () => ({getServerDB: vi.fn(() => ({})),}));-const mockTopicFindById = vi.fn();+const mockTopicFindOwnTopicById = vi.fn();vi.mock('@/database/models/topic', () => ({- TopicModel: vi.fn(() => ({ findById: mockTopicFindById })),+ TopicModel: vi.fn(() => ({ findOwnTopicById: mockTopicFindOwnTopicById })),}));const mockShareCreate = vi.fn();@@ -57,7 +57,7 @@ const RESOLVED_CONVERSATION = [{ meta: {}, resourceId: 'agt_1', resourceType: 'adescribe('topic share management gate', () => {beforeEach(() => {vi.clearAllMocks();- mockTopicFindById.mockResolvedValue({ id: topicId, userId: creatorId });+ mockTopicFindOwnTopicById.mockResolvedValue({ id: topicId, userId: creatorId });mockShareGetByTopicId.mockResolvedValue(null);mockShareCreate.mockResolvedValue({ id: 'share-1', topicId, visibility: 'private' });mockShareUpdateVisibility.mockResolvedValue({ id: 'share-1', topicId, visibility: 'link' });@@ -101,16 +101,30 @@ describe('topic share management gate', () => {expect(mockShareCreate).toHaveBeenCalledWith(topicId, undefined);});- it('skips the guard entirely in personal mode', async () => {+ it('skips the workspace checks in personal mode but still resolves the topic', async () => {const caller = topicRouter.createCaller({ userId: memberId } as any);await caller.enableSharing({ topicId });- expect(mockTopicFindById).not.toHaveBeenCalled();+ expect(mockTopicFindOwnTopicById).toHaveBeenCalledWith(topicId);expect(mockAssertCanUseTopicTargets).not.toHaveBeenCalled();expect(mockShareCreate).toHaveBeenCalledWith(topicId, undefined);});+ // Agent-share visitor topics live under the creator's userId and exist in+ // personal mode too; publishing one would expose the visitor's title on+ // the public share endpoint, so the exclusion must not hide behind the+ // workspace short-circuit.+ it('rejects an agent-share visitor topic in personal mode', async () => {+ mockTopicFindOwnTopicById.mockResolvedValue(null);+ const caller = topicRouter.createCaller({ userId: creatorId } as any);++ await expect(caller.enableSharing({ topicId })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect(mockShareCreate).not.toHaveBeenCalled();+ });+it('rejects a member on a topic that backs no conversation at all', async () => {// Legacy row: no agent, no group, no resolvable session — the co-editing// guard has nothing to check and would otherwise pass for everyone.@@ -134,7 +148,7 @@ describe('topic share management gate', () => {});it('throws NOT_FOUND when the topic does not exist in the workspace', async () => {- mockTopicFindById.mockResolvedValue(null);+ mockTopicFindOwnTopicById.mockResolvedValue(null);const caller = topicRouter.createCaller({ userId: memberId, workspaceId } as any);await expect(caller.enableSharing({ topicId })).rejects.toMatchObject({diff --git a/apps/server/src/routers/lambda/_helpers/__tests__/agentShareFeatureGate.test.ts b/apps/server/src/routers/lambda/_helpers/__tests__/agentShareFeatureGate.test.tsnew file mode 100644index 00000000000..f74048b30a0--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/__tests__/agentShareFeatureGate.test.ts@@ -0,0 +1,94 @@+// @vitest-environment node+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ businessConst: { ENABLE_BUSINESS_FEATURES: true },+ getFlags: vi.fn(),+}));++vi.mock('@lobechat/business-const', () => mocks.businessConst);+vi.mock('@/server/featureFlags', () => ({+ getServerFeatureFlagsStateFromRuntimeConfig: mocks.getFlags,+}));++const { assertAgentShareCreationEnabled, assertAgentShareVisitorEnabled } =+ await import('../agentShareFeatureGate');++describe('assertAgentShareCreationEnabled', () => {+ beforeEach(() => {+ mocks.businessConst.ENABLE_BUSINESS_FEATURES = true;+ mocks.getFlags.mockReset();+ });++ it('rejects on deployments without business features regardless of flags', async () => {+ mocks.businessConst.ENABLE_BUSINESS_FEATURES = false;+ mocks.getFlags.mockResolvedValue({ enableAgentShare: true });++ await expect(assertAgentShareCreationEnabled('user-1')).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ // The compile-time gate short-circuits: a self-hosted deployment cannot+ // reach the flag evaluation at all, even with FEATURE_FLAGS=+agent_share.+ expect(mocks.getFlags).not.toHaveBeenCalled();+ });++ it('rejects users outside the grayscale whitelist', async () => {+ mocks.getFlags.mockResolvedValue({ enableAgentShare: false });++ await expect(assertAgentShareCreationEnabled('user-1')).rejects.toBeInstanceOf(TRPCError);+ expect(mocks.getFlags).toHaveBeenCalledWith('user-1');+ });++ it('fails closed when the flag is unconfigured', async () => {+ mocks.getFlags.mockResolvedValue({ enableAgentShare: undefined });++ await expect(assertAgentShareCreationEnabled('user-1')).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ });++ it('admits whitelisted users', async () => {+ mocks.getFlags.mockResolvedValue({ enableAgentShare: true });++ await expect(assertAgentShareCreationEnabled('user-1')).resolves.toBeUndefined();+ });+});++describe('assertAgentShareVisitorEnabled', () => {+ beforeEach(() => {+ mocks.businessConst.ENABLE_BUSINESS_FEATURES = true;+ mocks.getFlags.mockReset();+ });++ it('rejects on deployments without business features regardless of flags', async () => {+ mocks.businessConst.ENABLE_BUSINESS_FEATURES = false;+ mocks.getFlags.mockResolvedValue({ enableAgentShare: true });++ await expect(assertAgentShareVisitorEnabled('visitor-1')).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(mocks.getFlags).not.toHaveBeenCalled();+ });++ it('rejects visitors outside the grayscale whitelist', async () => {+ mocks.getFlags.mockResolvedValue({ enableAgentShare: false });++ await expect(assertAgentShareVisitorEnabled('visitor-1')).rejects.toBeInstanceOf(TRPCError);+ expect(mocks.getFlags).toHaveBeenCalledWith('visitor-1');+ });++ it('fails closed when the flag is unconfigured', async () => {+ mocks.getFlags.mockResolvedValue({ enableAgentShare: undefined });++ await expect(assertAgentShareVisitorEnabled('visitor-1')).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ });++ it('admits whitelisted visitors', async () => {+ mocks.getFlags.mockResolvedValue({ enableAgentShare: true });++ await expect(assertAgentShareVisitorEnabled('visitor-1')).resolves.toBeUndefined();+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/agentShareFeatureGate.ts b/apps/server/src/routers/lambda/_helpers/agentShareFeatureGate.tsnew file mode 100644index 00000000000..b5a0d3b7041--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/agentShareFeatureGate.ts@@ -0,0 +1,70 @@+import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';+import { TRPCError } from '@trpc/server';++import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';++/**+ * Shared shape of {@link assertAgentShareCreationEnabled} and+ * {@link assertAgentShareVisitorEnabled}: both check the same+ * `ENABLE_BUSINESS_FEATURES` compile-time gate, then the same+ * `enableAgentShare` feature flag, differing only in which error message to+ * use. Factored out so the two exports cannot drift.+ */+const createAgentShareGate =+ (flagKey: 'enableAgentShare', notEnabledMessage: string) => async (userId: string) => {+ if (!ENABLE_BUSINESS_FEATURES) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Agent sharing is not available on this deployment',+ });+ }++ const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);+ if (featureFlags[flagKey] !== true) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: notEnabledMessage,+ });+ }+ };++/**+ * Availability gates for Agent Share. The feature has two capabilities —+ * CREATING a share (publishing) and VISITING one (opening/chatting on an+ * already-live share) — but a SINGLE rollout allowlist governs both: a user+ * matched by `agent_share` can publish and visit, everyone else can do+ * neither. Two exports remain only so each call site can raise the message+ * that fits its surface.+ *+ * Both gates are checked here on the server rather than only in the UI (the+ * gap topic-share has — its `ENABLE_BUSINESS_FEATURES` check is client-only,+ * so a self-hosted deployment can enable topic sharing by calling the API+ * directly), in two layers:+ *+ * 1. `ENABLE_BUSINESS_FEATURES` — compile-time business-slot constant, false+ * in OSS builds. Self-hosted deployments cannot flip it with env vars, so+ * agent sharing is structurally cloud-only end to end.+ * 2. The `enableAgentShare` feature flag — the grayscale whitelist (user IDs+ * or emails) published by admins, evaluated per user. It fails closed on+ * anything other than `true` (including `undefined`, i.e. unconfigured),+ * so a deployment must explicitly opt a user in.+ *+ * Deliberately NOT applied to `disableShare` / visibility→private, nor to any+ * other management mutation (`updateShareConfig`, `updateSlug`,+ * `getShareStatus`, `getShareStats`): a creator removed from the whitelist+ * must still be able to revoke and manage an existing share. Symmetrically,+ * `assertAgentShareVisitorEnabled` must never run for the share OWNER+ * previewing their own share — an owner who is later dropped from the+ * whitelist would otherwise lose access to their own live share. See the call+ * site in `share.ts`'s `getSharedAgent`, which only applies it to non-owner+ * viewers.+ */+export const assertAgentShareCreationEnabled = createAgentShareGate(+ 'enableAgentShare',+ 'Agent sharing is not enabled for this account',+);++export const assertAgentShareVisitorEnabled = createAgentShareGate(+ 'enableAgentShare',+ 'Shared agents are not available for this account',+);diff --git a/apps/server/src/routers/lambda/_helpers/shareVisitorTargetGuard.ts b/apps/server/src/routers/lambda/_helpers/shareVisitorTargetGuard.tsnew file mode 100644index 00000000000..e081b0fd0ab--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/shareVisitorTargetGuard.ts@@ -0,0 +1,75 @@+import { TRPCError } from '@trpc/server';++import { MessageModel } from '@/database/models/message';+import { TopicModel } from '@/database/models/topic';+import type { LobeChatDatabase } from '@/database/type';++interface ShareVisitorGuardCtx {+ db: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+}++/**+ * Agent-share visitor conversations are stored under the CREATOR's `userId`+ * (billing/data attribution) with `topics.senderId` set to the visitor, so a+ * plain ownership predicate matches them. A creator who obtains a raw visitor+ * topic/message id out of band (data export, a shared screenshot, …) could+ * otherwise mutate a conversation `allowCreatorViewSessions=false` is meant to+ * hide.+ *+ * ## Why the guard lives here and not in the model defaults+ *+ * The update methods these guards protect (`MessageModel.update`,+ * `updateMessagePlugin`, `updateMetadata`, `updatePluginState`, `updateTTS`,+ * `updateTranslate`, `TopicModel.update`) are also the write path for+ * legitimate in-flight VISITOR turns: `ServerMessageTransport`,+ * `HeterogeneousPersistenceHandler`, `services/aiAgent/*`,+ * `agentRuntime/CompletionLifecycle`, `AbandonOperationService` and friends all+ * persist a visitor's streaming turn under the creator's identity through the+ * very same methods. Flipping the model defaults to exclude visitor rows would+ * silently break live share streaming, and threading an opt-in flag through+ * ~15 runtime call sites is far easier to get wrong than gating the handful of+ * creator-facing RPC entry points. Delete paths differ: those genuinely default+ * to excluding visitors (`ShareVisitorWriteOptions.includeShareVisitor`),+ * because only a few runtime cleanups delete.+ *+ * `NOT_FOUND` (never `FORBIDDEN`) is thrown on purpose: the response must not+ * confirm that the row exists.+ */+const assertNoVisitorTargets = (visitorIds: string[], kind: 'message' | 'topic') => {+ if (visitorIds.length === 0) return;++ throw new TRPCError({+ code: 'NOT_FOUND',+ message: `${kind === 'message' ? 'Message' : 'Topic'} not found`,+ });+};++/**+ * Reject creator-facing writes that target an agent-share visitor message.+ * See the module note above for why this sits at the RPC entry point.+ */+export const assertCreatorMessageTargets = async (+ ctx: ShareVisitorGuardCtx,+ messageIds: string[],+) => {+ const ids = messageIds.filter(Boolean);+ if (ids.length === 0) return;++ const messageModel = new MessageModel(ctx.db, ctx.userId, ctx.workspaceId ?? undefined);++ assertNoVisitorTargets(await messageModel.findShareVisitorMessageIds(ids), 'message');+};++/**+ * Topic twin of {@link assertCreatorMessageTargets}.+ */+export const assertCreatorTopicTargets = async (ctx: ShareVisitorGuardCtx, topicIds: string[]) => {+ const ids = topicIds.filter(Boolean);+ if (ids.length === 0) return;++ const topicModel = new TopicModel(ctx.db, ctx.userId, ctx.workspaceId ?? undefined);++ assertNoVisitorTargets(await topicModel.findShareVisitorTopicIds(ids), 'topic');+};diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.tsindex 3947627d212..6d96f9cd10a 100644--- a/apps/server/src/routers/lambda/agent.ts+++ b/apps/server/src/routers/lambda/agent.ts@@ -13,8 +13,13 @@ import {import { notifyResourceTransfer } from '@/business/server/resource-transfer/notify';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';-import { AgentModel, AgentOwnedByGroupError } from '@/database/models/agent';+import {+ AGENT_SHARED_TRANSFER_BLOCKED,+ AgentModel,+ AgentOwnedByGroupError,+} from '@/database/models/agent';import { AGENT_COPY_IN_PROGRESS } from '@/database/models/agentCopyJob';+import { AgentShareModel } from '@/database/models/agentShare';import {AGENT_TRANSFER_IN_PROGRESS,AgentTransferJobModel,@@ -112,6 +117,21 @@ const protectAgentConfig = async <T extends Record<string, any>>(return access === 'profile' ? redactAgentConfig(config) : config;};+/** What a `/agent/:slugOrId` param resolves to — see `resolveAgentRoute`. */+export interface AgentRouteResolution {+ /** The resolved agent id. Present for `own` and `ownShare` routes. */+ agentId?: string;+ /**+ * `own`: one of the caller's agents (by id or by agent slug).+ * `ownShare`: a share link of the caller's OWN agent — the creator opened+ * their own share URL, and is sent to that agent's share settings instead+ * of the visitor surface.+ * `share`: someone else's agent share (access is still gated by `getSharedAgent`).+ * `notFound`: neither — the caller sees the agent not-found surface.+ */+ kind: 'own' | 'ownShare' | 'share' | 'notFound';+}+const agentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;const wsId = ctx.workspaceId ?? undefined;@@ -1155,6 +1175,13 @@ export const agentRouter = router({message: 'A previous transfer of this agent is still migrating its history',});}+ if (error instanceof Error && error.message === AGENT_SHARED_TRANSFER_BLOCKED) {+ throw new TRPCError({+ cause: { data: { code: TransferErrorCode.SharedTransferBlocked } },+ code: 'PRECONDITION_FAILED',+ message: 'This agent has a share link, so its owner cannot be changed.',+ });+ }throw error;}@@ -1330,6 +1357,13 @@ export const agentRouter = router({message: 'A previous transfer of these agents is still migrating their history',});}+ if (error instanceof Error && error.message === AGENT_SHARED_TRANSFER_BLOCKED) {+ throw new TRPCError({+ cause: { data: { code: TransferErrorCode.SharedTransferBlocked } },+ code: 'PRECONDITION_FAILED',+ message: 'One of these agents has a share link, so its owner cannot be changed.',+ });+ }throw error;}@@ -1427,6 +1461,10 @@ export const agentRouter = router({** Read-only and ownership-scoped: an unknown slug and someone else's slug both* return `null`, so this cannot be used to probe which slugs exist.+ *+ * @deprecated Superseded by `resolveAgentRoute`, which answers the same+ * question plus "is this an agent share?" in one round trip. Kept because+ * already-shipped clients (e.g. an installed desktop bundle) still call it.*/resolveAgentIdBySlug: agentProcedure.input(z.object({ slug: z.string() }))@@ -1435,6 +1473,47 @@ export const agentRouter = router({return { agentId };}),+ /**+ * Decide what `/agent/:slugOrId` points at: one of the caller's own agents,+ * or an agent share opened by a visitor. Both surfaces live on the same+ * route, so the client needs a single answer before it can pick a shell.+ *+ * Resolution order, cheapest first:+ * 1. an id-shaped param is always an own-agent route (no query at all);+ * 2. an ownership-scoped agent-slug lookup;+ * 3. an agent-share lookup by custom slug or share id.+ *+ * Step 3 applies the same existence rule as `assertShareAccess`: a private+ * share is only visible to its owner, so a stranger gets `notFound` rather+ * than `share` and cannot use this resolver to probe which custom slugs /+ * ids exist. `share.getSharedAgent` remains the access gate for everything+ * else (sign-in state, view counting). An own slug always wins over a share+ * slug of the same name.+ */+ resolveAgentRoute: agentProcedure+ .input(z.object({ slugOrId: z.string().trim().min(1) }))+ .query(async ({ input, ctx }): Promise<AgentRouteResolution> => {+ const { slugOrId } = input;++ // Every generated agent id carries an underscore (`agt_…`) and no+ // generated slug does, so the shape alone settles this case. A bogus+ // id still routes to the own-agent shell, which owns the not-found UI.+ if (slugOrId.includes('_')) return { agentId: slugOrId, kind: 'own' };++ const agentId = await ctx.agentModel.resolveIdBySlug(slugOrId);+ if (agentId) return { agentId, kind: 'own' };++ const share = await AgentShareModel.findBySlugOrId(ctx.serverDB, slugOrId);+ // The creator following their own share link is not a visitor: the+ // client redirects `ownShare` to the agent's share settings.+ if (share) {+ if (share.ownerId === ctx.userId) return { agentId: share.agentId, kind: 'ownShare' };+ if (share.visibility === 'link') return { kind: 'share' };+ }++ return { kind: 'notFound' };+ }),+/*** Rename an agent's url slug. Separate from `updateAgentConfig` because `slug`* is immutable there by design — see `IMMUTABLE_AGENT_FIELDS`.diff --git a/apps/server/src/routers/lambda/agentDocument.ts b/apps/server/src/routers/lambda/agentDocument.tsindex ab3f0058081..5e0be619c99 100644--- a/apps/server/src/routers/lambda/agentDocument.ts+++ b/apps/server/src/routers/lambda/agentDocument.ts@@ -1047,7 +1047,11 @@ export const agentDocumentRouter = router({).mutation(async ({ ctx, input }) => {try {- const topic = input.title.trim() ? undefined : await ctx.topicModel.findById(input.topicId);+ // Use the creator-facing finder: a visitor topic's title must not be+ // copied into a creator-owned document.+ const topic = input.title.trim()+ ? undefined+ : await ctx.topicModel.findOwnTopicById(input.topicId);const title = input.title.trim() || topic?.title || '';const doc = await ctx.agentDocumentService.createForTopic(input.agentId,diff --git a/apps/server/src/routers/lambda/agentNotify.ts b/apps/server/src/routers/lambda/agentNotify.tsindex 8832ce5e78f..18c26bb5695 100644--- a/apps/server/src/routers/lambda/agentNotify.ts+++ b/apps/server/src/routers/lambda/agentNotify.ts@@ -139,8 +139,13 @@ export const agentNotifyRouter = router({content.slice(0, 80),);- // 1. Verify the topic exists and get its agentId + running operationId- const topic = await ctx.topicModel.findById(topicId);+ // 1. Verify the topic exists and get its agentId + running operationId.+ // `findOwnTopicById` excludes agent-share visitor topics: they live under+ // the creator's userId, and no legitimate visitor run reaches this+ // callback (heterogeneous providers, sub-agent dispatch and the sandbox+ // `lh` CLI are all refused for share runs), so a visitor topic id here can+ // only be a creator-side caller trying to write into a private transcript.+ const topic = await ctx.topicModel.findOwnTopicById(topicId);if (!topic) {throw new TRPCError({code: 'NOT_FOUND',diff --git a/apps/server/src/routers/lambda/agentShare.ts b/apps/server/src/routers/lambda/agentShare.tsnew file mode 100644index 00000000000..c4838e2bb96--- /dev/null+++ b/apps/server/src/routers/lambda/agentShare.ts@@ -0,0 +1,207 @@+import { AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT } from '@lobechat/const';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { getAgentShareMonthlySpend } from '@/business/server/agent-share/spendGate';+import { AgentShareModel } from '@/database/models/agentShare';+import { TopicModel } from '@/database/models/topic';+import { authedProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';++import { assertAgentShareCreationEnabled } from './_helpers/agentShareFeatureGate';++const agentIdInput = z.object({ agentId: z.string().trim().min(1) }).strict();++/**+ * One `toolGrants` entry: a tool identifier, optionally narrowed to specific+ * API names. `apis` omitted grants every API the tool offers (still subject to+ * the runtime visitor gates); `apis` present grants only the named ones, and+ * is never empty — a tool with no granted API is simply absent from the list.+ * Duplicate API names within one entry are rejected rather than silently+ * deduped, so a client bug surfaces instead of persisting a redundant row.+ */+const shareToolGrantSchema = z+ .object({+ apis: z+ .array(z.string().trim().min(1))+ .min(1)+ .refine((apis) => new Set(apis).size === apis.length, {+ message: 'Duplicate api name in a tool grant',+ })+ .optional(),+ identifier: z.string().trim().min(1),+ })+ .strict();++export const agentShareConfigSchema = z+ .object({+ allowCreatorViewSessions: z.boolean().optional(),+ allowReadMemory: z.boolean().optional(),+ /**+ * The visitor topic list (`TopicModel.queryBySender`) is not paginated+ * and is bounded by `AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT`, so a cap+ * above that constant would let visitors create topics they can never+ * reopen.+ */+ maxTopicsPerVisitor: z+ .number()+ .int()+ .positive()+ .max(AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT)+ .optional(),+ maxTurnsPerTopic: z.number().int().positive().optional(),+ monthlySpendLimit: z.number().nonnegative().optional(),+ showErrorDetails: z.boolean().optional(),+ showModelInfo: z.boolean().optional(),+ /**+ * At most one entry per identifier: two entries for the same tool would+ * make the effective grant depend on the merge rule in+ * `resolveShareToolGrants` rather than on what the creator picked, so the+ * ambiguity is rejected at the door instead of silently resolved.+ */+ toolGrants: z+ .array(shareToolGrantSchema)+ .refine((grants) => new Set(grants.map((grant) => grant.identifier)).size === grants.length, {+ message: 'Duplicate tool identifier in toolGrants',+ })+ .optional(),+ })+ .strict();++export const agentShareConfigPatchSchema = agentShareConfigSchema.refine(+ (config) => Object.keys(config).length > 0,+ 'Config patch cannot be empty',+);++const agentShareProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;++ return opts.next({+ ctx: {+ agentShareModel: new AgentShareModel(ctx.serverDB, ctx.userId),+ },+ });+});++/** `updateConfig` / `updateVisibility` / `updateSlug` all return `null` when the share (or its owning agent) does not resolve for this caller. */+const requireShare = <T>(share: T | null): T => {+ if (!share) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent share not found' });+ }++ return share;+};++export const agentShareRouter = router({+ /**+ * Turning sharing OFF is a pause, not a revocation: the row (and with it the+ * share id and custom slug the owner handed out) is kept and only flipped to+ * `private`, so re-enabling later resolves the very same link. Visitors are+ * locked out in the meantime — `getSharedAgent` and the runtime's+ * `isRunStillAuthorized` both require `link`.+ */+ disableShare: agentShareProcedure+ .input(agentIdInput)+ .mutation(async ({ input, ctx }) =>+ requireShare(await ctx.agentShareModel.updateVisibility(input.agentId, 'private')),+ ),++ enableShare: agentShareProcedure+ .input(agentIdInput.extend({ visibility: z.enum(['private', 'link']).optional() }).strict())+ .mutation(async ({ input, ctx }) => {+ await assertAgentShareCreationEnabled(ctx.userId);++ return ctx.agentShareModel.create(input.agentId, input.visibility);+ }),++ /**+ * Aggregate usage of one share, for its owner only — `getByAgentId` is+ * ownership-scoped, so a non-owner never gets past the NOT_FOUND below.+ *+ * Visitor counts come from `topics.senderId` (set for share-originated+ * topics only); `monthlySpend` comes from the billing business slot and is+ * `null` in deployments that do not meter share spend, which the UI renders+ * as "no spend data" rather than as zero.+ */+ getShareStats: agentShareProcedure.input(agentIdInput).query(async ({ input, ctx }) => {+ const share = requireShare(await ctx.agentShareModel.getByAgentId(input.agentId));++ const topicModel = new TopicModel(ctx.serverDB, ctx.userId);+ const [visitors, monthlySpend] = await Promise.all([+ topicModel.countShareVisitors({ agentId: input.agentId }),+ getAgentShareMonthlySpend({ agentId: input.agentId, ownerUserId: ctx.userId }),+ ]);++ return {+ monthlySpend,+ monthlySpendLimit: share.shareConfig.monthlySpendLimit,+ topicCount: visitors.topicCount,+ // Raw page-view count (`agentShares.userViewCount`): bumped on every+ // non-owner page load, NOT deduplicated by visitor — a repeat visitor+ // inflates this every reload. For unique visitors, use `visitorCount`+ // below (distinct `topics.senderId` via `countShareVisitors`).+ userViewCount: share.userViewCount,+ visitorCount: visitors.visitorCount,+ };+ }),++ getShareStatus: agentShareProcedure+ .input(agentIdInput)+ .query(async ({ input, ctx }) => ctx.agentShareModel.getByAgentId(input.agentId)),++ updateShareConfig: agentShareProcedure+ .input(+ z+ .object({+ agentId: z.string().trim().min(1),+ config: agentShareConfigPatchSchema,+ })+ .strict(),+ )+ .mutation(async ({ input, ctx }) =>+ requireShare(await ctx.agentShareModel.updateConfig(input.agentId, input.config)),+ ),++ /**+ * Custom URL slug for this share's public link. Pattern/reserved-word+ * validation runs again inside `AgentShareModel.updateSlug` — this router+ * check exists only to fail obviously-malformed input as `BAD_REQUEST`+ * before it reaches the ownership-locking transaction. `slug: null` clears+ * the custom slug.+ */+ updateSlug: agentShareProcedure+ .input(+ z+ .object({+ agentId: z.string().trim().min(1),+ slug: z.string().trim().toLowerCase().min(3).max(64).nullable(),+ })+ .strict(),+ )+ .mutation(async ({ input, ctx }) =>+ requireShare(await ctx.agentShareModel.updateSlug(input.agentId, input.slug)),+ ),++ updateVisibility: agentShareProcedure+ .input(+ z+ .object({+ agentId: z.string().trim().min(1),+ visibility: z.enum(['private', 'link']),+ })+ .strict(),+ )+ .mutation(async ({ input, ctx }) => {+ // Flipping to `link` publishes the share, so it is the same capability+ // as `enableShare`; going back to `private` unpublishes and stays open.+ if (input.visibility === 'link') await assertAgentShareCreationEnabled(ctx.userId);++ return requireShare(+ await ctx.agentShareModel.updateVisibility(input.agentId, input.visibility),+ );+ }),+});++export type AgentShareConfigInput = z.infer<typeof agentShareConfigSchema>;+export type AgentShareConfigPatchInput = z.infer<typeof agentShareConfigPatchSchema>;+export type AgentShareRouter = typeof agentShareRouter;diff --git a/apps/server/src/routers/lambda/agentTrace.test.ts b/apps/server/src/routers/lambda/agentTrace.test.tsindex 9624a1c04b4..1f592b697e0 100644--- a/apps/server/src/routers/lambda/agentTrace.test.ts+++ b/apps/server/src/routers/lambda/agentTrace.test.ts@@ -10,7 +10,7 @@ import { agentTraceRouter } from './agentTrace';const mockServerDB = vi.hoisted(() => ({}));const mocks = vi.hoisted(() => ({createPreSignedUrlForPreview: vi.fn(),- findById: vi.fn(),+ findOwnOperationById: vi.fn(),listByTopic: vi.fn(),}));@@ -20,7 +20,7 @@ vi.mock('@/database/core/db-adaptor', () => ({vi.mock('@/database/models/agentOperation', () => ({AgentOperationModel: vi.fn().mockImplementation(() => ({- findById: mocks.findById,+ findOwnOperationById: mocks.findOwnOperationById,listByTopic: mocks.listByTopic,})),}));@@ -47,7 +47,7 @@ describe('agentTraceRouter', () => {describe('getSnapshotUrl', () => {it('signs the key recorded on the operation', async () => {- mocks.findById.mockResolvedValue({ id: 'op-1', traceS3Key: TRACE_KEY });+ mocks.findOwnOperationById.mockResolvedValue({ id: 'op-1', traceS3Key: TRACE_KEY });mocks.createPreSignedUrlForPreview.mockResolvedValue('https://s3.example.com/obj?sig=abc');await expect(router.getSnapshotUrl({ operationId: 'op-1' })).resolves.toEqual({@@ -62,9 +62,11 @@ describe('agentTraceRouter', () => {});it('refuses an operation the caller cannot see, without reaching storage', async () => {- // findById is ownership-scoped, so somebody else's operation reads as- // absent — a leaked operation id must not become a readable trace.- mocks.findById.mockResolvedValue(null);+ // findOwnOperationById is ownership-scoped AND excludes agent-share+ // visitor operations, so somebody else's operation — or a visitor+ // conversation's — reads as absent: a leaked operation id must not+ // become a readable trace.+ mocks.findOwnOperationById.mockResolvedValue(null);await expect(router.getSnapshotUrl({ operationId: 'op-foreign' })).rejects.toThrow(expect.objectContaining({ code: 'NOT_FOUND' }) as TRPCError,@@ -73,7 +75,7 @@ describe('agentTraceRouter', () => {});it('says the run recorded no trace instead of signing an empty key', async () => {- mocks.findById.mockResolvedValue({ id: 'op-1', traceS3Key: null });+ mocks.findOwnOperationById.mockResolvedValue({ id: 'op-1', traceS3Key: null });await expect(router.getSnapshotUrl({ operationId: 'op-1' })).rejects.toThrow(/No trace was recorded/,diff --git a/apps/server/src/routers/lambda/agentTrace.ts b/apps/server/src/routers/lambda/agentTrace.tsindex b527510bb2c..b4f5b256db1 100644--- a/apps/server/src/routers/lambda/agentTrace.ts+++ b/apps/server/src/routers/lambda/agentTrace.ts@@ -45,7 +45,11 @@ export const agentTraceRouter = router({try {// Ownership-scoped: an operation belonging to someone else reads as// absent rather than forbidden, so this can't be used to probe ids.- const operation = await ctx.agentOperationModel.findById(input.operationId);+ // Agent-share visitor runs execute under the CREATOR's identity and so+ // pass plain ownership — `findOwnOperationById` additionally excludes+ // them, otherwise a creator holding a visitor operation id could pull+ // that conversation's full trajectory snapshot.+ const operation = await ctx.agentOperationModel.findOwnOperationById(input.operationId);if (!operation) {throw new TRPCError({ code: 'NOT_FOUND', message: 'Operation not found' });}diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex f1f31cd7480..e27fe023022 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -54,6 +54,7 @@ import { TopicModel } from '@/database/models/topic';import { UserModel } from '@/database/models/user';import { agentOperations, topics, workspaceMembers } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { notShareVisitorTopicRef } from '@/database/utils/shareVisitor';import { heteroAuthedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { signHeteroOperationJWT, signUserJWT } from '@/libs/trpc/utils/internalJwt';@@ -752,6 +753,63 @@ const assertCanUseOperationAgent = async (params: {});};+/**+ * Ownership guard for operation-keyed READ endpoints (`getOperationStatus`,+ * `getPendingInterventions`). The runtime coordinator keys operations purely+ * by id and returns the raw operation metadata — including the executing+ * user's full `agentConfig` and `modelRuntimeConfig` — so the id itself must+ * not act as a bearer token.+ *+ * Historically that was inert: an operation id was only ever known to the+ * user who started it. Agent Share breaks the assumption on purpose — a share+ * run executes under the CREATOR's identity while the VISITOR receives the+ * `operationId` (to attach to the Gateway stream, which redacts creator+ * details). Without this guard the visitor could replay that id here and read+ * the unredacted creator config the stream path deliberately hides.+ *+ * Visible to: the operation's owner, or (workspace runs) a member with `use`+ * access to the operation's agent in the SAME workspace as the caller.+ * Everything else — share visitors, AND the creator looking at a visitor's+ * run — resolves as NOT_FOUND so the endpoint does not confirm which ids+ * exist.+ */+const assertOperationVisibleToCaller = async (params: {+ db: LobeChatDatabase;+ operationId: string;+ userId: string;+ workspaceId?: string | null;+}) => {+ const { db, operationId, userId, workspaceId } = params;++ // Share-visitor runs are ALSO excluded (`notShareVisitorTopicRef`): they+ // execute under the creator's userId, so the owner shortcut below would+ // otherwise hand the creator the visitor's run metadata, history and+ // stream events — the same exclusion `findOwnOperationById` applies to+ // the trace reads.+ const [row] = await db+ .select({+ agentId: agentOperations.agentId,+ userId: agentOperations.userId,+ workspaceId: agentOperations.workspaceId,+ })+ .from(agentOperations)+ .where(+ and(eq(agentOperations.id, operationId), notShareVisitorTopicRef(agentOperations.topicId)),+ )+ .limit(1);++ const notFound = () => new TRPCError({ code: 'NOT_FOUND', message: 'Operation not found' });++ if (!row) throw notFound();+ if (row.userId === userId) return;++ if (!row.workspaceId || !workspaceId || row.workspaceId !== workspaceId || !row.agentId) {+ throw notFound();+ }++ await assertCanUseWorkspaceAgent({ agentId: row.agentId, db, userId, workspaceId });+};+/*** Resolve client-supplied conversation ids before an agent run writes through* AiAgentService. Checking only the requested agent/group is insufficient: an@@ -2577,6 +2635,13 @@ export const aiAgentRouter = router({log('Getting operation status for %s', operationId);+ await assertOperationVisibleToCaller({+ db: ctx.serverDB,+ operationId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+// Get operation status using AgentRuntimeServiceconst operationStatus = await ctx.agentRuntimeService.getOperationStatus({historyLimit,@@ -2594,10 +2659,28 @@ export const aiAgentRouter = router({log('Getting pending interventions for operationId: %s, userId: %s', operationId, userId);+ // Same bearer-token hazard as `getOperationStatus`: an operation id must+ // resolve to a run the caller may see, and the user-wide listing may only+ // ever enumerate the CALLER's own runs — `input.userId` is not a way to+ // read another user's pending interventions.+ if (operationId) {+ await assertOperationVisibleToCaller({+ db: ctx.serverDB,+ operationId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ } else if (userId && userId !== ctx.userId) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Cannot list operations of another user',+ });+ }+// Get pending interventions using AgentRuntimeServiceconst result = await ctx.agentRuntimeService.getPendingInterventions({operationId: operationId || undefined,- userId: userId || undefined,+ userId: operationId ? undefined : ctx.userId,});return result;@@ -3594,8 +3677,11 @@ export const aiAgentRouter = router({refreshGatewayToken: aiAgentProcedure.input(z.object({ topicId: z.string() })).query(async ({ input, ctx }) => {- // Verify the topic belongs to this user and has a running operation- const topic = await ctx.topicModel.findById(input.topicId);+ // Verify the topic belongs to this user and has a running operation.+ // Use the creator-facing finder: a creator must not mint a token+ // against a visitor's running operation; visitors use+ // `shareChat.refreshGatewayToken` instead.+ const topic = await ctx.topicModel.findOwnTopicById(input.topicId);if (!topic?.metadata?.runningOperation) {throw new TRPCError({diff --git a/apps/server/src/routers/lambda/image/index.test.ts b/apps/server/src/routers/lambda/image/index.test.tsindex 5a464659034..0a940f37e16 100644--- a/apps/server/src/routers/lambda/image/index.test.ts+++ b/apps/server/src/routers/lambda/image/index.test.ts@@ -463,6 +463,49 @@ describe('imageRouter', () => {);});+ it('forwards the caller spend attribution to the charge and every asyncTask', async () => {+ // A share visitor's image generation bills the agent CREATOR, so the+ // origin must reach both the reserve-time charge and the async settle —+ // otherwise the spend escapes the per-agent monthly cap.+ mockChargeBeforeGenerate.mockResolvedValue({+ prechargeItems: [{ reservationKey: 'k-1' }, { reservationKey: 'k-2' }],+ });+ const spendOrigin = {+ agentShare: { agentId: 'agent-1', shareId: 'share-1', visitorUserId: 'visitor-1' },+ trigger: 'agent_share',+ };++ const caller = imageRouter.createCaller(createMockCtx({ spendOrigin }));+ await caller.createImage(createDefaultInput());++ expect(mockChargeBeforeGenerate).toHaveBeenCalledWith(+ expect.objectContaining({ spendOrigin }),+ );+ expect(mockInsertValues[2]).toEqual(+ expect.objectContaining({+ metadata: { precharge: { reservationKey: 'k-1' }, spendOrigin },+ }),+ );+ expect(mockInsertValues[3]).toEqual(+ expect.objectContaining({+ metadata: { precharge: { reservationKey: 'k-2' }, spendOrigin },+ }),+ );+ });++ it('stores spend attribution on the asyncTask even without a precharge handle', async () => {+ mockChargeBeforeGenerate.mockResolvedValue({ prechargeItems: undefined });+ const spendOrigin = {+ agentShare: { agentId: 'agent-1', shareId: 'share-1', visitorUserId: 'visitor-1' },+ trigger: 'agent_share',+ };++ const caller = imageRouter.createCaller(createMockCtx({ spendOrigin }));+ await caller.createImage(createDefaultInput());++ expect(mockInsertValues[2]).toEqual(expect.objectContaining({ metadata: { spendOrigin } }));+ });+it('leaves asyncTask metadata unset when there are no prechargeItems', async () => {mockChargeBeforeGenerate.mockResolvedValue({ prechargeItems: undefined });diff --git a/apps/server/src/routers/lambda/image/index.ts b/apps/server/src/routers/lambda/image/index.tsindex 3337868fb46..e90dd130200 100644--- a/apps/server/src/routers/lambda/image/index.ts+++ b/apps/server/src/routers/lambda/image/index.ts@@ -198,6 +198,7 @@ export const imageRouter = router({imageNum,model,provider,+ spendOrigin: ctx.spendOrigin,userId,workspaceId: wsId,});@@ -265,10 +266,19 @@ export const imageRouter = router({// Presence check (not truthiness): handles are opaque, so falsy// values like 0 or '' must still be stored verbatim.const prechargeItem = prechargeItems?.[index];+ // The completion charge runs in the async router, which no longer+ // sees this request; carry the origin attribution on the task so+ // it can still be stamped on the spend log. Stored independently+ // of `precharge` because paths without a billing handle (free /+ // unpriced models) still charge at completion.+ const taskMetadata = {+ ...(prechargeItem === undefined ? {} : { precharge: prechargeItem }),+ ...(ctx.spendOrigin ? { spendOrigin: ctx.spendOrigin } : {}),+ };const [createdAsyncTask] = await tx.insert(asyncTasks).values({- metadata: prechargeItem === undefined ? undefined : { precharge: prechargeItem },+ metadata: Object.keys(taskMetadata).length === 0 ? undefined : taskMetadata,status: AsyncTaskStatus.Pending,type: AsyncTaskType.ImageGeneration,userId,@@ -365,6 +375,7 @@ export const imageRouter = router({await chargeAfterGenerate({isError: true,metadata: {+ ...ctx.spendOrigin,asyncTaskId,generationBatchId: createdBatch.id,modelId: model,diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex e1cc246eee7..b5d821083a9 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -30,6 +30,7 @@ import { agentGroupRouter } from './agentGroup';import { agentLabelRouter } from './agentLabel';import { agentNotifyRouter } from './agentNotify';import { agentQuotaRouter } from './agentQuota';+import { agentShareRouter } from './agentShare';import { agentSignalRouter } from './agentSignal';import { agentSkillsRouter } from './agentSkills';import { agentTraceRouter } from './agentTrace';@@ -84,6 +85,7 @@ import { searchRouter } from './search';import { sessionRouter } from './session';import { sessionGroupRouter } from './sessionGroup';import { shareRouter } from './share';+import { shareChatRouter } from './shareChat';import { taskRouter } from './task';import { threadRouter } from './thread';import { topicRouter } from './topic';@@ -119,6 +121,7 @@ export const lambdaRouter = router({aiChat: aiChatRouter,aiModel: aiModelRouter,agentQuota: agentQuotaRouter,+ agentShare: agentShareRouter,aiProvider: aiProviderRouter,apiKey: apiKeyRouter,asr: asrRouter,@@ -166,6 +169,7 @@ export const lambdaRouter = router({session: sessionRouter,sessionGroup: sessionGroupRouter,share: shareRouter,+ shareChat: shareChatRouter,task: taskRouter,thread: threadRouter,topic: topicRouter,diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.tsindex 6ece866b249..b9a3e8d6c67 100644--- a/apps/server/src/routers/lambda/message.ts+++ b/apps/server/src/routers/lambda/message.ts@@ -30,6 +30,10 @@ import {assertCanUseTopicTargets,} from './_helpers/conversationResourceGuard';import { resolveAgentIdFromSession, resolveContext } from './_helpers/resolveContext';+import {+ assertCreatorMessageTargets,+ assertCreatorTopicTargets,+} from './_helpers/shareVisitorTargetGuard';import { basicContextSchema } from './_schema/context';const { logTiming, runTimedStage } = createTimingHelpers('lobe-server:chat:lobehub:timing');@@ -129,6 +133,11 @@ export const messageRouter = router({.mutation(async ({ input, ctx }) => {const { id, fileIds, agentId, ...options } = input;await assertCanUseMessageTargets(guardCtx(ctx), [id]);+ // Agent-share visitor messages live under the creator's `userId`;+ // attaching files to one on the creator's behalf would leak into the+ // visitor's transcript — see `assertCreatorMessageTargets` for why this+ // guard sits at the RPC boundary rather than in the model defaults.+ await assertCreatorMessageTargets(guardCtx(ctx), [id]);const resolved = await resolveContext({ agentId, ...options },ctx.serverDB,@@ -175,14 +184,24 @@ export const messageRouter = router({}),);- await assertCanUseMessageTargets(- guardCtx(ctx),- operations.flatMap((op) => (op.type === 'createMessage' ? [] : [op.id])),- );+ const targetedIds = operations.flatMap((op) => (op.type === 'createMessage' ? [] : [op.id]));+ await assertCanUseMessageTargets(guardCtx(ctx), targetedIds);+ // Same visitor exclusion the single-message update RPCs apply — the+ // batch path reaches the ownership-only model writes directly.+ await assertCreatorMessageTargets(guardCtx(ctx), targetedIds);await assertCanUseCreateMessageTargets(guardCtx(ctx),operations.flatMap((op) => (op.type === 'createMessage' ? [op.message] : [])),);+ // Creates carry no message id, but they DO name a topic: refuse to+ // append creator rows into a visitor transcript (the workspace guard+ // above is a no-op in personal mode, where every share lives).+ await assertCreatorTopicTargets(+ guardCtx(ctx),+ operations.flatMap((op) =>+ op.type === 'createMessage' && op.message.topicId ? [op.message.topicId] : [],+ ),+ );return ctx.messageService.batchMutate(operations);}),@@ -205,6 +224,8 @@ export const messageRouter = router({.mutation(async ({ input, ctx }) => {const { messageGroupId, agentId, groupId, threadId, topicId } = input;await assertCanUseTopicTargets(guardCtx(ctx), [topicId]);+ // Same visitor guard as `addFilesToMessage` above.+ await assertCreatorTopicTargets(guardCtx(ctx), [topicId]);return ctx.messageService.cancelCompression(messageGroupId, {agentId,@@ -274,6 +295,10 @@ export const messageRouter = router({.mutation(async ({ input, ctx }) => {const { topicId, messageIds, agentId, groupId, threadId } = input;await assertCanUseTopicTargets(guardCtx(ctx), [topicId]);+ // Same visitor guard as `addFilesToMessage` above, plus the message ids+ // themselves — compression reads and rewrites their content.+ await assertCreatorTopicTargets(guardCtx(ctx), [topicId]);+ await assertCreatorMessageTargets(guardCtx(ctx), messageIds);return ctx.messageService.createCompressionGroup(topicId, messageIds, {agentId,@@ -304,6 +329,9 @@ export const messageRouter = router({// DB-resolved target as well.if (input.topicId) {await assertCanUseTopicTargets(guardCtx(ctx), [input.topicId]);+ // Visitor topics carry the creator's userId, so ownership alone would+ // let the creator write into a visitor's private transcript.+ await assertCreatorTopicTargets(guardCtx(ctx), [input.topicId]);}// Create message with the resolved agentId@@ -328,6 +356,8 @@ export const messageRouter = router({.mutation(async ({ input, ctx }) => {const { messageGroupId, content, ...params } = input;await assertCanUseTopicTargets(guardCtx(ctx), [params.topicId]);+ // Same visitor guard as `addFilesToMessage` above.+ await assertCreatorTopicTargets(guardCtx(ctx), [params.topicId]);return ctx.messageService.finalizeCompression(messageGroupId, content, params);}),@@ -399,6 +429,10 @@ export const messageRouter = router({// it the ownership filter degrades to `workspace_id IS NULL` and returns// no messages for workspace topics.const shareWorkspaceId = share.workspaceId ?? undefined;+ // Legacy `share.topicId` (chat share) is a creator topic. Agent-share+ // visitor topics have their own router (`shareChat.ts`), and this+ // path is only entered when a creator publishes their own conversation+ // via the classic share link — so we do NOT opt into visitor scope.const messageModel = new MessageModel(ctx.serverDB, share.ownerId, shareWorkspaceId);const fileService = new FileService(ctx.serverDB, share.ownerId, shareWorkspaceId);@@ -419,6 +453,20 @@ export const messageRouter = router({throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Authentication required' });}+ // Align with every other topic-scoped procedure in this router: a raw+ // `topicId` from the client must still pass the conversation+ // General-access guard before its messages are read.+ if (queryParams.topicId) {+ await assertCanUseTopicTargets(+ guardCtx({+ serverDB: ctx.serverDB,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ [queryParams.topicId],+ );+ }+const wsId = ctx.workspaceId ?? undefined;const messageModel = new MessageModel(ctx.serverDB, ctx.userId, wsId);const fileService = new FileService(ctx.serverDB, ctx.userId, wsId);@@ -512,6 +560,8 @@ export const messageRouter = router({if (options.topicId) await assertCanUseTopicTargets(guardCtx(ctx), [options.topicId]);elseawait assertCanUseConversationTargets(guardCtx(ctx), [{ agentId, groupId: input.groupId }]);+ // Same visitor guard as `addFilesToMessage` above.+ if (options.topicId) await assertCreatorTopicTargets(guardCtx(ctx), [options.topicId]);const resolved = await resolveContext({ agentId, ...options },ctx.serverDB,@@ -537,6 +587,8 @@ export const messageRouter = router({.mutation(async ({ input, ctx }) => {if (input.topicId) await assertCanUseTopicTargets(guardCtx(ctx), [input.topicId]);else await assertCanUseConversationTargets(guardCtx(ctx), [{ groupId: input.groupId }]);+ // Same visitor guard as `addFilesToMessage` above.+ if (input.topicId) await assertCreatorTopicTargets(guardCtx(ctx), [input.topicId]);return ctx.messageModel.deleteMessagesBySession(null, input.topicId, input.groupId);}),@@ -560,6 +612,11 @@ export const messageRouter = router({.mutation(async ({ input, ctx }) => {const { id, value, agentId, ...options } = input;await assertCanUseMessageTargets(guardCtx(ctx), [id]);+ // Agent-share visitor messages live under the creator's `userId`, so the+ // ownership predicate alone would let a creator edit a visitor's turn —+ // see `assertCreatorMessageTargets` for why the guard sits here and not+ // in the model defaults (the runtime writes visitor turns through them).+ await assertCreatorMessageTargets(guardCtx(ctx), [id]);const timingContext = { requestId: createTimingRequestId(), startedAt: Date.now() };logTiming(timingContext, 'lambda.message.update:start', {hasAgentId: !!agentId,@@ -619,6 +676,8 @@ export const messageRouter = router({.mutation(async ({ input, ctx }) => {const { messageGroupId, expanded, context } = input;await assertCanUseTopicTargets(guardCtx(ctx), [context.topicId]);+ // Same visitor guard as `addFilesToMessage` above.+ await assertCreatorTopicTargets(guardCtx(ctx), [context.topicId]);return ctx.messageService.updateMessageGroupMetadata(messageGroupId, { expanded }, context);}),@@ -636,6 +695,7 @@ export const messageRouter = router({.mutation(async ({ input, ctx }) => {const { id, value, agentId, ...options } = input;await assertCanUseMessageTargets(guardCtx(ctx), [id]);+ await assertCreatorMessageTargets(guardCtx(ctx), [id]);const resolved = await resolveContext({ agentId, ...options },ctx.serverDB,@@ -652,6 +712,7 @@ export const messageRouter = router({.mutation(async ({ input, ctx }) => {const { id, value, agentId, ...options } = input;await assertCanUseMessageTargets(guardCtx(ctx), [id]);+ await assertCreatorMessageTargets(guardCtx(ctx), [id]);const resolved = await resolveContext({ agentId, ...options },ctx.serverDB,@@ -675,6 +736,7 @@ export const messageRouter = router({.mutation(async ({ input, ctx }) => {const { id, value, agentId, ...options } = input;await assertCanUseMessageTargets(guardCtx(ctx), [id]);+ await assertCreatorMessageTargets(guardCtx(ctx), [id]);const resolved = await resolveContext({ agentId, ...options },ctx.serverDB,@@ -698,6 +760,7 @@ export const messageRouter = router({.mutation(async ({ input, ctx }) => {const { id, value, agentId, ...options } = input;await assertCanUseMessageTargets(guardCtx(ctx), [id]);+ await assertCreatorMessageTargets(guardCtx(ctx), [id]);const resolved = await resolveContext({ agentId, ...options },ctx.serverDB,@@ -721,6 +784,7 @@ export const messageRouter = router({.mutation(async ({ input, ctx }) => {const { id, value, agentId, ...options } = input;await assertCanUseMessageTargets(guardCtx(ctx), [id]);+ await assertCreatorMessageTargets(guardCtx(ctx), [id]);const resolved = await resolveContext({ agentId, ...options },ctx.serverDB,@@ -747,6 +811,7 @@ export const messageRouter = router({).mutation(async ({ input, ctx }) => {await assertCanUseMessageTargets(guardCtx(ctx), [input.id]);+ await assertCreatorMessageTargets(guardCtx(ctx), [input.id]);if (input.value === false) {return ctx.messageModel.deleteMessageTTS(input.id);}@@ -773,6 +838,9 @@ export const messageRouter = router({await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId, groupId: options.groupId },]);+ // Same visitor guard as `addFilesToMessage` above — no message id here,+ // so it's applied to the resolved topic instead.+ if (options.topicId) await assertCreatorTopicTargets(guardCtx(ctx), [options.topicId]);const resolved = await resolveContext({ agentId, ...options },ctx.serverDB,@@ -806,6 +874,7 @@ export const messageRouter = router({.mutation(async ({ input, ctx }) => {const { id, value, agentId, ...options } = input;await assertCanUseMessageTargets(guardCtx(ctx), [id]);+ await assertCreatorMessageTargets(guardCtx(ctx), [id]);const resolved = await resolveContext({ agentId, ...options },ctx.serverDB,@@ -831,6 +900,7 @@ export const messageRouter = router({).mutation(async ({ input, ctx }) => {await assertCanUseMessageTargets(guardCtx(ctx), [input.id]);+ await assertCreatorMessageTargets(guardCtx(ctx), [input.id]);if (input.value === false) {return ctx.messageModel.deleteMessageTranslate(input.id);}diff --git a/apps/server/src/routers/lambda/resourceTransferRequest.ts b/apps/server/src/routers/lambda/resourceTransferRequest.tsindex c5655ad79ac..10fdf2cf64a 100644--- a/apps/server/src/routers/lambda/resourceTransferRequest.ts+++ b/apps/server/src/routers/lambda/resourceTransferRequest.ts@@ -5,7 +5,11 @@ import { z } from 'zod';import { notifyResourceTransfer } from '@/business/server/resource-transfer/notify';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';-import { AGENT_OWNERSHIP_STALE, AgentOwnedByGroupError } from '@/database/models/agent';+import {+ AGENT_OWNERSHIP_STALE,+ AGENT_SHARED_TRANSFER_BLOCKED,+ AgentOwnedByGroupError,+} from '@/database/models/agent';import { AGENT_COPY_IN_PROGRESS } from '@/database/models/agentCopyJob';import { AGENT_TRANSFER_IN_PROGRESS } from '@/database/models/agentTransferJob';import {@@ -283,6 +287,16 @@ export const resourceTransferRequestRouter = router({message: 'A previous copy of this agent is still duplicating its history',});}+ if (error.message === AGENT_SHARED_TRANSFER_BLOCKED) {+ // Not permanently stale: once the share row is removed (no product+ // entry point yet — see the `transferAgents` guard) the recipient+ // can retry, so the request stays pending.+ throw new TRPCError({+ cause: { data: { code: TransferErrorCode.SharedTransferBlocked } },+ code: 'PRECONDITION_FAILED',+ message: 'This agent has a share link, so its owner cannot be changed.',+ });+ }}console.error('[resourceTransferRequest:accept]', error);throw new TRPCError({diff --git a/apps/server/src/routers/lambda/share.ts b/apps/server/src/routers/lambda/share.tsindex 45ee0d5dc4f..d71b1470a33 100644--- a/apps/server/src/routers/lambda/share.ts+++ b/apps/server/src/routers/lambda/share.ts@@ -1,11 +1,95 @@-import { type SharedTopicData } from '@lobechat/types';+import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';+import { type SharedAgentData, type SharedTopicData } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import debug from 'debug';import { z } from 'zod';+import { AgentShareModel } from '@/database/models/agentShare';import { TopicShareModel } from '@/database/models/topicShare';-import { publicProcedure, router } from '@/libs/trpc/lambda';+import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { assertAgentShareVisitorEnabled } from './_helpers/agentShareFeatureGate';++const log = debug('lobe-server:router:share');+export const shareRouter = router({+ /**+ * Resolve the visitor-facing metadata for an agent share, by its custom+ * slug or its raw share id, after enforcing signed-in access.+ *+ * `findBySlugOrId` intentionally does NOT enforce visibility — it resolves+ * whatever share matches, of ANY visibility; the (private → owner only,+ * link → any authed viewer) gate runs on the resolved row via the shared+ * `assertShareAccess` helper, so no second lookup is needed.+ *+ * Gated in two layers matching `_helpers/agentShareFeatureGate.ts`:+ * `ENABLE_BUSINESS_FEATURES` applies unconditionally (even to the OWNER+ * previewing their own share — an OSS deployment has no agent-share surface+ * at all), while the `enableAgentShare` grayscale flag only ever applies to+ * OTHER visitors, never the owner.+ */+ getSharedAgent: authedProcedure+ .use(serverDatabase)+ .input(z.object({ slugOrId: z.string().trim().min(1) }))+ .query(async ({ input, ctx }): Promise<SharedAgentData> => {+ if (!ENABLE_BUSINESS_FEATURES) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Agent sharing is not available on this deployment',+ });+ }++ const share = await AgentShareModel.findBySlugOrId(ctx.serverDB, input.slugOrId);++ if (!share) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Share not found' });+ }++ AgentShareModel.assertShareAccess(share, ctx.userId);++ const isOwner = share.ownerId === ctx.userId;++ if (!isOwner) {+ // The owner previewing their own (possibly unpublished) share must+ // always be able to see it — the grayscale rollout only narrows OTHER+ // visitors' admission.+ await assertAgentShareVisitorEnabled(ctx.userId);++ // Owner previews are not counted: userViewCount tracks visitor page+ // views (PV, not deduplicated visitors). The counter is analytics+ // only, so it is best-effort: a failed increment must never turn an+ // otherwise valid share page into an error for the visitor.+ try {+ await AgentShareModel.incrementUserViewCount(ctx.serverDB, share.shareId);+ } catch (error) {+ log('failed to increment view count for share %s: %O', share.shareId, error);+ }+ }++ return {+ agentId: share.agentId,+ agentMeta: {+ avatar: share.agentAvatar,+ backgroundColor: share.agentBackgroundColor,+ description: share.agentDescription,+ name: share.agentName,+ title: share.agentTitle,+ },+ isOwner,+ shareId: share.shareId,+ slug: share.shareConfig.slug ?? null,+ // TODO(cloud budget gate): the spend gate itself is already enforced —+ // `shareChat.execAgent` checks `checkAgentShareSpendAllowance` before+ // dispatching a run. This READ-ONLY endpoint just doesn't yet expose+ // whether the budget is currently exhausted; it only carries the+ // creator's configured `monthlySpendLimit`. Surfacing a `budgetExhausted`+ // flag here (so the visitor page can show the state before the visitor+ // even sends a message) is a tracked followup, not a missing gate.+ visibility: share.visibility as SharedAgentData['visibility'],+ };+ }),+/*** Get shared topic metadata for public access* Uses shareId (not topicId) for accessdiff --git a/apps/server/src/routers/lambda/shareChat.ts b/apps/server/src/routers/lambda/shareChat.tsnew file mode 100644index 00000000000..f55d410747c--- /dev/null+++ b/apps/server/src/routers/lambda/shareChat.ts@@ -0,0 +1,521 @@+import {+ AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,+ AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,+ SHARE_VISITOR_PROMPT_MAX_LENGTH,+} from '@lobechat/const';+import type { ChatMessageError } from '@lobechat/types';+import { ChatErrorType, entityIdPattern, RequestTrigger } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import debug from 'debug';+import { z } from 'zod';++import { checkAgentShareSpendAllowance } from '@/business/server/agent-share/spendGate';+import { AgentShareModel } from '@/database/models/agentShare';+import { MessageModel, sanitizeVisitorError } from '@/database/models/message';+import { TopicModel } from '@/database/models/topic';+import { UserModel } from '@/database/models/user';+import type { LobeChatDatabase } from '@/database/type';+import { authedProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { signUserJWT } from '@/libs/trpc/utils/internalJwt';+import { AiAgentService } from '@/server/services/aiAgent';+import type { AgentShareGate } from '@/server/services/aiAgent/shareGate';+import { FileService } from '@/server/services/file';++import { assertAgentShareVisitorEnabled } from './_helpers/agentShareFeatureGate';++const log = debug('lobe-server:router:shareChat');++/**+ * Visitor-facing execution chain for shared agents (Agent Share).+ *+ * All procedures authenticate the VISITOR (ctx.userId) but operate on+ * CREATOR-owned rows: topics/messages of a share conversation carry the+ * creator's userId (so runtime, billing, and tool paths behave exactly as a+ * creator-owned chat) plus `topics.senderId = visitor` for scoping. Every+ * read/write here is therefore manually authorized: resolve the share via+ * {@link resolveLinkShareOrThrow}, then require+ * `topic.senderId === visitor && topic.agentId === share.agentId`+ * ({@link findVisitorTopicOrThrow}).+ *+ * There is no share-instance column on `topics`: a visitor topic is tied to+ * its share purely through `(agentId, senderId)`, which is unambiguous because+ * `agent_shares` is 1:1 per agent. The known consequence is that a visitor's+ * own older topics resurface after an owner disables and re-enables the share+ * (a pause that keeps the same row, so nothing marks the topics as belonging+ * to an earlier run of it). That crosses no identity boundary — it is the same+ * visitor's own prior conversation with the same agent — but it does mean the+ * per-visitor topic cap counts them.+ *+ * Agent sharing is personal-only (workspace agents cannot be shared), so no+ * workspaceId is ever threaded into the creator-scoped models/services.+ */+const shareChatProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+ // Availability gate for the VISITOR side of Agent Share (see+ // `_helpers/agentShareFeatureGate.ts`): `ENABLE_BUSINESS_FEATURES`+ // (compile-time, false in OSS) AND the `enableAgentShare` grayscale flag,+ // both evaluated for the VISITOR calling in — never the share owner,+ // who reaches their own agent through `aiAgent.execAgent`, not this router.+ await assertAgentShareVisitorEnabled(opts.ctx.userId);++ return opts.next();+});++const ShareTopicScopeSchema = z.object({+ shareId: z.string(),+ topicId: z.string(),+});++/**+ * Resolve a share for the VISITOR execution path.+ *+ * Stricter than the plain `findByShareIdWithAccessCheck` used by the read-only+ * share page: that helper deliberately lets the OWNER through on a `private`+ * share (so they can preview their own unpublished page), but the owner never+ * uses this visitor chain — they chat with their own agent through+ * `aiAgent.execAgent`. Requiring `link` here keeps this entry point in exact+ * agreement with the per-step revalidation+ * (`AgentShareModel.isRunStillAuthorized`, which also demands `link`), so a+ * run can never be authorized to start under a rule its own step loop would+ * immediately abort it for.+ */+const resolveLinkShareOrThrow = async (db: LobeChatDatabase, shareId: string, viewerId: string) => {+ const share = await AgentShareModel.findByShareIdWithAccessCheck(db, shareId, viewerId);++ if (share.visibility !== 'link') {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'This share is private' });+ }++ return share;+};++/**+ * Resolve a visitor-owned share topic or fail closed. The topic row belongs to+ * the creator (creator-scoped TopicModel), so the senderId + agentId match is+ * the ONLY thing standing between a visitor and the creator's other topics.+ */+const findVisitorTopicOrThrow = async (+ topicModel: TopicModel,+ params: { agentId: string; topicId: string; visitorUserId: string },+) => {+ const topic = await topicModel.findById(params.topicId);++ if (!topic || topic.senderId !== params.visitorUserId || topic.agentId !== params.agentId) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });+ }++ return topic;+};++/**+ * Convert an internal startup failure into a visitor-safe `TRPCError` — reuses+ * `sanitizeVisitorError` (`packages/database/src/models/message.ts`) instead of+ * a third ad-hoc redaction. `execAgent`/`interruptTask` can throw BEFORE any+ * Gateway streaming starts (e.g. the queue or runtime backend returns a+ * diagnostic), a failure surface neither existing visitor projection covers —+ * `toVisitorMessage` only runs over persisted rows and the Gateway event+ * sanitizer only runs over live stream events — so without this, the raw+ * `error.message` (which can carry the creator's provider/infra diagnostic,+ * since the run executes under the CREATOR's identity) went straight to the+ * visitor. Logs the raw error server-side and returns only the classified+ * `{ type }` (or `{ message }` for the narrow allowlisted codes) that+ * `sanitizeVisitorError` already deems visitor-safe.+ *+ * `showErrorDetails` (the owner's opt-in on the share config) bypasses the+ * projection, exactly as it does for persisted rows and live stream events.+ *+ * Also the sink for a RESOLVED (not thrown) `{ success: false, error }` from+ * `AiAgentService.execAgent` — a `createOperation` startup failure resolves+ * rather than rejects there, so the visitor-facing `execAgent` handler below+ * re-throws that case through this same function instead of letting the raw+ * message escape via a normal `return`.+ */+const toVisitorSafeStartupError = (+ context: string,+ error: unknown,+ options: { showErrorDetails?: boolean } = {},+): TRPCError => {+ log('%s failed: %O', context, error);++ const raw = error as { message?: unknown; type?: unknown } | null | undefined;+ const safe = sanitizeVisitorError(+ raw && typeof raw === 'object'+ ? ({+ message: typeof raw.message === 'string' ? raw.message : undefined,+ type: raw.type,+ } as ChatMessageError)+ : undefined,+ options,+ );++ // `type` widens to `string | number` (the numeric HTTP-status error codes),+ // while `TRPCError.message` is `string | undefined` — stringify rather than+ // drop the numeric codes, which are exactly as visitor-safe as the rest.+ const publicMessage = safe?.message ?? safe?.type;++ return new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: publicMessage === undefined ? 'Internal error' : String(publicMessage),+ });+};++export const shareChatRouter = router({+ /**+ * Execute a shared agent as a visitor — the gateway-transport mirror of+ * `aiAgent.execAgent`, restricted to the share surface: fixed agent, no+ * device/local targets, share-config tool allowlist, per-visitor caps.+ */+ 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(),+ /** 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(),+ /** Absent → the run creates a new visitor topic (counted against the topic cap). */+ topicId: z.string().nullish(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);++ // Spend admission runs FIRST, before any row is created: a run rejected+ // by the runtime billing path instead fails mid-run, after the topic and+ // placeholder messages have persisted, leaving junk topics with a "..."+ // assistant row. No-op in deployments that do not meter share spend.+ const spendGate = await checkAgentShareSpendAllowance({+ agentId: share.agentId,+ monthlySpendLimit: share.shareConfig.monthlySpendLimit,+ ownerUserId: share.ownerId,+ shareId: share.shareId,+ visitorUserId: ctx.userId,+ });+ if (!spendGate.allowed) {+ throw new TRPCError({+ code: 'TOO_MANY_REQUESTS',+ message: ChatErrorType.ShareSpendLimitExceeded,+ });+ }++ // Runtime-normalized (findByShareIdWithAccessCheck fills defaults), but+ // the config TYPE keeps every field optional — re-apply the same default+ // constants rather than asserting non-null.+ const maxTopicsPerVisitor =+ share.shareConfig.maxTopicsPerVisitor ?? AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR;+ const maxTurnsPerTopic =+ share.shareConfig.maxTurnsPerTopic ?? AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC;+ const topicModel = new TopicModel(ctx.serverDB, share.ownerId, undefined, undefined, {+ includeShareVisitor: true,+ });+ const messageModel = new MessageModel(ctx.serverDB, share.ownerId, undefined, undefined, {+ includeShareVisitor: true,+ });++ // Fast, UX-only pre-check for both caps: reject an obviously-over-cap+ // request BEFORE paying for agent-config/tool resolution, instead of only+ // at dispatch. This is NOT the enforcement: it is a plain unlocked count,+ // so a burst of concurrent requests can all read the same pre-insert+ // count and all pass. The atomic, authoritative gate is+ // `reserveShareVisitorTopicOrThrow` / `reserveShareVisitorTurnOrThrow`+ // (`apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts`), which+ // locks and re-checks the same counters immediately around the real+ // topic/message INSERT inside `AiAgentService.execAgent`.+ if (input.topicId) {+ await findVisitorTopicOrThrow(topicModel, {+ agentId: share.agentId,+ topicId: input.topicId,+ visitorUserId: ctx.userId,+ });++ const turnCount = await messageModel.countByTopic({+ role: 'user',+ topicId: input.topicId,+ });+ if (turnCount >= maxTurnsPerTopic) {+ throw new TRPCError({+ code: 'TOO_MANY_REQUESTS',+ message: ChatErrorType.ShareTurnLimitExceeded,+ });+ }+ } else {+ const topicCount = await topicModel.countBySender({+ agentId: share.agentId,+ senderId: ctx.userId,+ });+ if (topicCount >= maxTopicsPerVisitor) {+ throw new TRPCError({+ code: 'TOO_MANY_REQUESTS',+ message: ChatErrorType.ShareTopicLimitExceeded,+ });+ }+ }++ // 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;+ 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,+ });++ log('execAgent: share=%s visitor=%s topic=%s', input.shareId, ctx.userId, input.topicId);++ try {+ const result = await aiAgentService.execAgent({+ agentId: share.agentId,+ appContext: { topicId: input.topicId },+ clientIds: input.clientIds,+ clientIp: ctx.clientIp ?? undefined,+ // `interactiveStart: true` (the `aiAgent.execAgent` owner path's+ // default) makes `TopicModel.tryReserveTaskCallback` skip its+ // `runningOperation` liveness check entirely — a policy that is safe+ // there ONLY because the owner's OWN client serializes sends.+ //+ // An untrusted visitor has no such client-side gate: firing two+ // concurrent `execAgent` mutations for the SAME topic would let both+ // pass the reservation (each only contends on the short-lived+ // `taskCallbackReservation`, released right after the first operation+ // is CREATED, long before it finishes streaming), so both would+ // create creator-credentialed operations. The second operation's+ // `runningOperation` marker write then overwrites the first's,+ // leaving the first unreachable by `shareChat.interruptTask` (which+ // matches on the topic's current marker) — an orphaned run that keeps+ // using tools and the creator's budget until it finishes on its own.+ //+ // Leaving this `false` routes visitor sends through the SAME+ // 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,+ prompt: input.prompt,+ shareGate,+ // Not `RequestTrigger.Chat`: a share run is billed to the CREATOR,+ // so its spend rows must be separable from the creator's own chat+ // spend (they land on the same account). The trigger rides+ // `state.metadata.trigger` all the way into the spend-log metadata.+ trigger: RequestTrigger.AgentShare,+ userAgent: ctx.userAgent ?? undefined,+ });++ // `AiAgentService.execAgent` RESOLVES (does not throw) when+ // `createOperation` itself fails to start (e.g. the queue/runtime+ // backend is unavailable). That `error` is the same raw+ // `error.message` the thrown path guards against, so it must go through+ // the exact same projection instead of reaching the visitor verbatim.+ //+ // Reject rather than sanitize-and-return: the Gateway client never+ // checks `result.success` — it unconditionally treats the resolved+ // value as a live operation and connects with its+ // `operationId`/`token`. A sanitized `success: false` object would+ // still be consumed as if the run started, opening a WebSocket for an+ // operation that never began.+ if (!result.success) {+ throw toVisitorSafeStartupError(+ 'execAgent',+ { message: result.error },+ { showErrorDetails: share.shareConfig.showErrorDetails },+ );+ }++ return result;+ } catch (error: any) {+ if (error instanceof TRPCError) throw error;++ throw toVisitorSafeStartupError('execAgent', error, {+ showErrorDetails: share.shareConfig.showErrorDetails,+ });+ }+ }),++ /** Messages of one visitor-owned share topic. */+ getMessages: shareChatProcedure.input(ShareTopicScopeSchema).query(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);++ const topicModel = new TopicModel(ctx.serverDB, share.ownerId, undefined, undefined, {+ includeShareVisitor: true,+ });+ await findVisitorTopicOrThrow(topicModel, {+ agentId: share.agentId,+ topicId: input.topicId,+ visitorUserId: ctx.userId,+ });++ const messageModel = new MessageModel(ctx.serverDB, share.ownerId, undefined, undefined, {+ includeShareVisitor: true,+ });+ const fileService = new FileService(ctx.serverDB, share.ownerId);++ // queryForVisitor strips the creator's `sender` identity, and — unless the+ // share opts in via `showModelInfo` / `showErrorDetails` — the spend/model+ // snapshot and raw error payload too. Share messages persist under the+ // CREATOR's account (see the module doc above), so the raw `query()` result+ // would otherwise leak the creator's account identity to the visitor.+ return messageModel.queryForVisitor(+ // skipWorks: Work summaries join live task/version state of the CREATOR's+ // account — never serve them to a visitor surface.+ { skipWorks: true, topicId: input.topicId },+ {+ postProcessUrl: (path, file) => fileService.getFileAccessUrl({ id: file.id, url: path }),+ redaction: {+ showErrorDetails: share.shareConfig.showErrorDetails,+ showModelInfo: share.shareConfig.showModelInfo,+ },+ },+ );+ }),++ /** The visitor's own topics on this shared agent. */+ getTopics: shareChatProcedure+ .input(z.object({ shareId: z.string() }))+ .query(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);++ // The list is intentionally NOT bounded by the share's live+ // `maxTopicsPerVisitor`: that cap gates ADMISSION of new topics (the+ // COUNT check in `execAgent` above), and a creator may lower it below+ // what a visitor already created. Tying the page size to it would hide+ // those older conversations with no pagination or deep link to reach+ // them, so the model applies its own fixed, generous list bound instead.+ const topicModel = new TopicModel(ctx.serverDB, share.ownerId, undefined, undefined, {+ includeShareVisitor: true,+ });+ return topicModel.queryBySender({+ agentId: share.agentId,+ senderId: ctx.userId,+ });+ }),++ /**+ * Interrupt a running share operation — the visitor counterpart of+ * `aiAgent.interruptTask`. Visitors have no owner-scoped access to+ * `aiAgent.interruptTask` (its models are scoped to the caller, and share+ * runs execute under the CREATOR's identity), so without this endpoint a+ * visitor's Stop / tab-close cannot reach the server: the run keeps streaming+ * and consuming the creator's budget until it finishes on its own.+ *+ * Authorization is intentionally stricter than `execAgent`/`getMessages`: it+ * is not enough that the topic belongs to this visitor — the `operationId`+ * must also match the operation CURRENTLY recorded as running on that topic.+ * Without that check a visitor could pass an arbitrary operationId+ * (topics/operations are creator-owned rows) and interrupt an unrelated run+ * on the creator's account.+ */+ interruptTask: shareChatProcedure+ .input(ShareTopicScopeSchema.extend({ operationId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);++ const topicModel = new TopicModel(ctx.serverDB, share.ownerId, undefined, undefined, {+ includeShareVisitor: true,+ });+ const topic = await findVisitorTopicOrThrow(topicModel, {+ agentId: share.agentId,+ topicId: input.topicId,+ visitorUserId: ctx.userId,+ });++ const runningOperationId = topic.metadata?.runningOperation?.operationId;+ if (!runningOperationId || runningOperationId !== input.operationId) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: 'No matching running operation found on this topic',+ });+ }++ // Creator-scoped service, same as `execAgent` — the run's operation /+ // thread rows were written under the creator's identity, so the+ // underlying `interruptTask` implementation must resolve them there.+ const aiAgentService = new AiAgentService(ctx.serverDB, share.ownerId, {+ includeShareVisitor: true,+ });++ log(+ 'interruptTask: share=%s visitor=%s topic=%s operation=%s',+ input.shareId,+ ctx.userId,+ input.topicId,+ input.operationId,+ );++ try {+ return await aiAgentService.interruptTask({+ operationId: input.operationId,+ topicId: input.topicId,+ });+ } catch (error: any) {+ if (error instanceof TRPCError) throw error;++ throw toVisitorSafeStartupError('interruptTask', error, {+ showErrorDetails: share.shareConfig.showErrorDetails,+ });+ }+ }),++ /**+ * Refresh the Gateway WS JWT for a running share operation — the visitor+ * counterpart of `aiAgent.refreshGatewayToken` (which cannot serve visitors:+ * its TopicModel is scoped to the caller, and share topics belong to the+ * creator). Signs for the VISITOR — the gateway channel is registered under+ * their id (`streamOwnerUserId`), and a creator-signed token in the visitor's+ * browser would be creator account access.+ */+ refreshGatewayToken: shareChatProcedure+ .input(ShareTopicScopeSchema)+ .query(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);++ const topicModel = new TopicModel(ctx.serverDB, share.ownerId, undefined, undefined, {+ includeShareVisitor: true,+ });+ const topic = await findVisitorTopicOrThrow(topicModel, {+ agentId: share.agentId,+ topicId: input.topicId,+ visitorUserId: ctx.userId,+ });++ if (!topic.metadata?.runningOperation) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: 'No running operation found on this topic',+ });+ }++ const token = await signUserJWT(ctx.userId);++ return { token };+ }),+});++export type ShareChatRouter = typeof shareChatRouter;diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex 3991375aba2..84a54e58e80 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -53,6 +53,10 @@ import {resolveContext,resolveContextWithAgentId,} from './_helpers/resolveContext';+import {+ assertCreatorMessageTargets,+ assertCreatorTopicTargets,+} from './_helpers/shareVisitorTargetGuard';import { basicContextSchema } from './_schema/context';/** Ctx slice consumed by the conversation General-access guards. */@@ -172,13 +176,20 @@ const assertCanManageTopicShare = async (topicId: string,targetVisibility?: 'link' | 'private',) => {- if (!ctx.workspaceId) return;-- const topic = await ctx.topicModel.findById(topicId);+ // `findOwnTopicById`: an agent-share visitor topic is stored under the+ // creator's userId, and publishing a public link for one would expose the+ // visitor's conversation. It is never a shareable topic — fail closed, and+ // do so BEFORE the personal-mode short-circuit below: visitor topics exist+ // in personal mode too, so the exclusion cannot depend on a workspace.+ const topic = await ctx.topicModel.findOwnTopicById(topicId);if (!topic) {throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });}+ // Outside a workspace the remaining checks (agent publish policy, workspace+ // ownership) have no subject — personal-mode ownership is the whole story.+ if (!ctx.workspaceId) return;+// Publishing under a restricted agent overrides even topic ownership —// that is the whole point of the policy. Resolved only on the publish path// so the common case keeps the query count it had.@@ -239,7 +250,7 @@ export const topicRouter = router({getTopicDetail: topicProcedure.input(z.object({ id: z.string() })).query(async ({ input, ctx }) => {- const topic = await ctx.topicModel.findById(input.id);+ const topic = await ctx.topicModel.findOwnTopicById(input.id);if (!topic) return null;return topic;}),@@ -254,7 +265,7 @@ export const topicRouter = router({}),).query(async ({ input, ctx }) => {- const topic = await ctx.topicModel.findById(input.topicId);+ const topic = await ctx.topicModel.findOwnTopicById(input.topicId);if (!topic) {throw new TRPCError({@@ -279,7 +290,7 @@ export const topicRouter = router({getTopicContext: topicProcedure.input(z.object({ topicId: z.string() })).query(async ({ input, ctx }) => {- const topic = await ctx.topicModel.findById(input.topicId);+ const topic = await ctx.topicModel.findOwnTopicById(input.topicId);if (!topic) {return { content: `Topic not found: ${input.topicId}`, success: false };@@ -351,6 +362,13 @@ export const topicRouter = router({guardCtx(ctx),resolvedTopics.map((item) => ({ agentId: item.agentId, groupId: item.groupId })),);+ // `messages` are REPARENTED onto the new topic by ownership only. A+ // visitor message (creator-owned row under a `senderId` topic) moved to+ // a creator topic would escape `notShareVisitorMessage()` for good.+ await assertCreatorMessageTargets(+ guardCtx(ctx),+ resolvedTopics.flatMap((item) => item.messages ?? []),+ );const data = await ctx.topicModel.batchCreate(resolvedTopics as any);@@ -432,6 +450,11 @@ export const topicRouter = router({// Moving needs `use` on both the source conversations and the target agent.await assertCanUseTopicTargets(guardCtx(ctx), input.topicIds);await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId: input.targetAgentId }]);+ // Moving a visitor topic re-parents it off the share and strands the+ // visitor outside the senderId scope the share depends on — see+ // `assertCreatorTopicTargets` for why this guard sits at the RPC+ // boundary rather than in the model defaults.+ await assertCreatorTopicTargets(guardCtx(ctx), input.topicIds);return ctx.topicModel.batchMoveToAgent(input.topicIds, input.targetAgentId);}),@@ -441,6 +464,9 @@ export const topicRouter = router({.input(z.object({ id: z.string(), newTitle: z.string().optional() })).mutation(async ({ input, ctx }) => {await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);+ // Duplicating a visitor topic would copy its content into creator scope+ // (see `assertCreatorTopicTargets` on `batchMoveTopics` above).+ await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);const data = await ctx.topicModel.duplicate(input.id, input.newTitle);return data.topic.id;@@ -490,6 +516,8 @@ export const topicRouter = router({await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId: resolved.agentId, groupId: rest.groupId },]);+ // See batchCreateTopics — reparenting a visitor message would leak it.+ await assertCreatorMessageTargets(guardCtx(ctx), rest.messages ?? []);const data = await ctx.topicModel.create({...rest,@@ -900,10 +928,17 @@ export const topicRouter = router({.use(withScopedPermission('topic:delete')).input(z.object({ id: z.string(), removeFiles: z.boolean().optional() })).mutation(async ({ input, ctx }) => {- const topic = await ctx.topicModel.findById(input.id);+ // `findOwnTopicById` (not `findById`): an agent-share visitor topic is+ // stored under the creator's `userId`, and `TopicModel.delete` refuses to+ // remove it. Resolving through the visitor-excluding lookup keeps the+ // file cleanup below from destroying a visitor conversation's attachments+ // (DB rows + S3 objects) while the topic itself survives.+ const topic = await ctx.topicModel.findOwnTopicById(input.id);if (topic) assertWorkspaceRowManageable(ctx, topic.userId, 'topic');- if (!input.removeFiles) return ctx.topicModel.delete(input.id);+ // No creator-visible topic behind this id: run the (no-op) delete for the+ // unchanged return shape, but never touch any files.+ if (!input.removeFiles || !topic) return ctx.topicModel.delete(input.id);// Collect the topic's deletable attachments BEFORE deleting it — the lookup// joins messages, which are cascade-deleted along with the topic. Files@@ -1015,6 +1050,7 @@ export const topicRouter = router({// Co-editing still requires `use`-level General access on the agent —// view-only members are read-only.await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);+ await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);const { agentId, ...restValue } = input.value;if (agentId) await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId }]);@@ -1047,6 +1083,7 @@ export const topicRouter = router({// runningOperation on shared topics); only delete/transfer is gated.// Co-editing still requires `use`-level General access on the agent.await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);+ await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);return ctx.topicModel.updateMetadata(input.id, input.metadata);}),@@ -1062,6 +1099,8 @@ export const topicRouter = router({).mutation(async ({ input, ctx }) => {await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);+ // Same visitor guard as `batchMoveTopics`/`cloneTopic` above.+ await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);return ctx.topicModel.settleRunningOperation(input.id, input.operationId, input.status);}),diff --git a/apps/server/src/routers/lambda/video/index.ts b/apps/server/src/routers/lambda/video/index.tsindex 54a8f8442c6..6555605abc1 100644--- a/apps/server/src/routers/lambda/video/index.ts+++ b/apps/server/src/routers/lambda/video/index.ts@@ -222,6 +222,10 @@ export const videoRouter = router({.values({metadata: {...(prechargeResult ? { precharge: prechargeResult } : {}),+ // The completion charge runs in a webhook/polling context that no+ // longer sees this request; carry the origin so the spend stays+ // attributed to it.+ ...(ctx.spendOrigin ? { spendOrigin: ctx.spendOrigin } : {}),webhookToken,},status: AsyncTaskStatus.Pending,diff --git a/apps/server/src/routers/tools/market.test.ts b/apps/server/src/routers/tools/market.test.tsindex 6f448d3b60c..08fa7285e8c 100644--- a/apps/server/src/routers/tools/market.test.ts+++ b/apps/server/src/routers/tools/market.test.ts@@ -88,6 +88,39 @@ describe('tools marketRouter', () => {});});+ // Regression: `input.userId` used to override `ctx.userId`, so any+ // authenticated caller could make the server mint another user's JWT into a+ // sandbox command they control (and read their skills/files).+ it('should ignore a client-supplied userId and always use the authenticated ctx.userId', async () => {+ const caller = marketRouter.createCaller({+ serverDB: {},+ userId: 'caller-user',+ workspaceId: null,+ } as any);+ mockPreprocessLhCommand.mockResolvedValue({+ command: 'lh agent view agt_1',+ isLhCommand: true,+ skipSkillLookup: true,+ });+ mockSandboxCallTool.mockResolvedValue({ result: { ok: true }, success: true });++ await caller.execInSandbox({+ params: { command: 'lh agent view agt_1' },+ toolName: 'runCommand',+ topicId: 'topic-1',+ userId: 'someone-else',+ });++ expect(mockPreprocessLhCommand).toHaveBeenCalledWith(+ 'lh agent view agt_1',+ 'caller-user',+ undefined,+ );+ expect(mockCreateSandboxService).toHaveBeenCalledWith(+ expect.objectContaining({ topicId: 'topic-1', userId: 'caller-user' }),+ );+ });+it('should fall back to static tools when live discovery fails', async () => {const caller = marketRouter.createCaller({ userId: 'user-1' } as any);mockMarketSDK.skills.listLiveTools.mockRejectedValue(new Error('Live discovery failed'));diff --git a/apps/server/src/routers/tools/market.ts b/apps/server/src/routers/tools/market.tsindex a83d7d5bc3a..e151d38735e 100644--- a/apps/server/src/routers/tools/market.ts+++ b/apps/server/src/routers/tools/market.ts@@ -130,7 +130,20 @@ const execInSandboxSchema = z.object({params: z.record(z.string(), z.any()),toolName: z.string(),topicId: z.string(),- userId: z.string().optional(), // Optional: fallback to ctx.userId if not provided+ /**+ * SECURITY: accepted for backward compatibility with older clients (the SPA+ * and desktop still send it, see `src/services/cloudSandbox.ts`) but+ * ALWAYS IGNORED by the handler — the effective identity is `ctx.userId`.+ *+ * It used to override `ctx.userId`, which let any authenticated caller mint+ * and read another user's JWT: `preprocessLhCommand` signs a user JWT and+ * inlines it into the shell command run inside a sandbox the caller fully+ * controls (`declare -f lh` prints the injected token back). The same forged+ * id also selected the AgentSkill/File rows and the sandbox session.+ *+ * @deprecated Ignored by the server; will be dropped once no client sends it.+ */+ userId: z.string().optional(),});// Schema for export and upload file (combined operation)@@ -191,7 +204,19 @@ const execInSandboxHandler = async ({input: ExecInSandboxInput;}): Promise<CallToolResult> => {const { toolName, params, topicId } = input;- const userId = input?.userId || ctx.userId;+ // SECURITY: never trust `input.userId` — see the JSDoc on `execInSandboxSchema`.+ // Everything downstream (JWT minting, skill/file lookups, sandbox session+ // isolation) is keyed off this id, so it must come from the authenticated+ // context only.+ const userId = ctx.userId;++ if (input?.userId && input.userId !== ctx.userId) {+ log(+ 'execInSandbox: ignored deprecated input.userId=%s (differs from ctx.userId=%s)',+ input.userId,+ ctx.userId,+ );+ }log('execInSandbox: tool=%s, topicId=%s', toolName, topicId);@@ -199,6 +224,12 @@ const execInSandboxHandler = async ({let enhancedParams = params;// Preprocess lh commands: rewrite to npx @lobehub/cli + inject auth env vars+ //+ // The minted credential is always scoped to `ctx.userId`, i.e. the caller+ // themselves. This route is an `authedProcedure` invoked directly by a+ // client, so it carries no `agentShareVisitor` context; a visitor reaching+ // it can therefore only ever act as (and spend as) their own account, which+ // is why no `shareVisitorBlocked` guard is applied here.if ((toolName === 'execScript' || toolName === 'runCommand') && params.command) {const lhResult = await preprocessLhCommand(params.command,diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.tsindex c7d9cfd8a09..12f5e2d9d3d 100644--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts@@ -34,6 +34,13 @@ interface AbandonOperationOptions {*/export interface AbandonedSubAgentResume {parentOperationId: string;+ /**+ * When true, the parent op is a shared-agent visitor run (its metadata+ * carries `streamOwnerUserId`). The inline resume path must construct+ * services with `includeShareVisitor: true` so the visitor-owned rows+ * remain visible.+ */+ streamOwnerUserId?: string;threadId: string;/** The parent's placeholder `role: 'tool'` message to backfill (= thread.sourceMessageId). */toolMessageId: string;@@ -108,6 +115,8 @@ export class AbandonOperationService {assistantMessageId?: string;isSubAgent?: boolean;orchestrationRole?: 'supervisor' | 'member';+ /** Present only for shared-agent visitor runs (visitor owns the stream). */+ streamOwnerUserId?: string;threadId?: string | null;topicId?: string | null;userId?: string;@@ -150,9 +159,22 @@ export class AbandonOperationService {result.finalized = partial !== null;}+ // Shared-agent visitor runs mark themselves with `streamOwnerUserId` on+ // the operation metadata (the op executes as the creator `userId`, but the+ // visitor owns the stream). The visitor-owned rows are excluded from+ // MessageModel/TopicModel/CompletionLifecycle by default, so the cleanup+ // path must opt in when this flag is present.+ const includeShareVisitor = Boolean(metadata.streamOwnerUserId);+if (metadata.userId && metadata.assistantMessageId) {try {- const messageModel = new MessageModel(this.db, metadata.userId, metadata.workspaceId);+ const messageModel = new MessageModel(+ this.db,+ metadata.userId,+ metadata.workspaceId,+ undefined,+ { includeShareVisitor },+ );await messageModel.update(metadata.assistantMessageId, { error });result.assistantMessageUpdated = true;} catch (e) {@@ -162,7 +184,13 @@ export class AbandonOperationService {if (metadata.topicId && metadata.userId) {try {- const topicModel = new TopicModel(this.db, metadata.userId, metadata.workspaceId);+ const topicModel = new TopicModel(+ this.db,+ metadata.userId,+ metadata.workspaceId,+ undefined,+ { includeShareVisitor },+ );await topicModel.settleRunningOperation(metadata.topicId, operationId);} catch (e) {log('[%s] abandoned op runningOperation cleanup failed (non-fatal): %O', operationId, e);@@ -171,14 +199,11 @@ export class AbandonOperationService {if (!metadata.isSubAgent && metadata.userId && shouldDispatchAbandonedLifecycle) {try {- await new CompletionLifecycle(this.db, metadata.userId, metadata.workspaceId).dispatchHooks(- operationId,- finalState,- 'error',- {- skipErrorMessageWrite: result.assistantMessageUpdated,- },- );+ await new CompletionLifecycle(this.db, metadata.userId, metadata.workspaceId, {+ includeShareVisitor,+ }).dispatchHooks(operationId, finalState, 'error', {+ skipErrorMessageWrite: result.assistantMessageUpdated,+ });} catch (e) {log('[%s] abandoned op lifecycle dispatch failed (non-fatal): %O', operationId, e);}@@ -218,6 +243,11 @@ export class AbandonOperationService {if (toolMessageId) {result.subAgentResume = {parentOperationId,+ // Forward the visitor-run marker so an inline resume (local mode)+ // constructs its services with `includeShareVisitor: true`; the+ // queue-mode `subagent-callback` re-derives the same flag from+ // the parent op's coordinator metadata.+ streamOwnerUserId: metadata.streamOwnerUserId,threadId,toolMessageId,userId: metadata.userId,@@ -293,7 +323,19 @@ export class AbandonOperationService {if (!assistantMessageId) return;try {- const messageModel = new MessageModel(this.db, op.userId, op.workspaceId ?? undefined);+ // No-state cleanup path: this is a system-side finalize keyed on ids+ // read from the persisted `agentOperations` row (no user input), and the+ // op may belong to a shared-agent visitor conversation whose rows the+ // default MessageModel gate would hide. Opt in unconditionally so the+ // placeholder can still be marked errored when the coordinator state has+ // already evaporated.+ const messageModel = new MessageModel(+ this.db,+ op.userId,+ op.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ );await messageModel.update(assistantMessageId, { content: '', error });result.assistantMessageUpdated = true;} catch (e) {@@ -320,7 +362,13 @@ export class AbandonOperationService {if (op.topicId) {try {- topicModel = new TopicModel(this.db, op.userId, op.workspaceId ?? undefined);+ // No-state cleanup path: same rationale as the MessageModel above —+ // system-side finalize keyed on ids from the persisted operation row,+ // and the op may belong to a shared-agent visitor topic that the+ // default TopicModel gate would exclude. Opt in unconditionally.+ topicModel = new TopicModel(this.db, op.userId, op.workspaceId ?? undefined, undefined, {+ includeShareVisitor: true,+ });const settled = await topicModel.settleRunningOperation(op.topicId, operationId);if (settled.status !== 'settled') return undefined;if (settled.assistantMessageId) return settled.assistantMessageId;diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex 280ff2cd190..774f1301b81 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -1969,10 +1969,29 @@ describe('AgentRuntimeService', () => {metadata: { agentId: 'agt_1', topicId: 'tpc_1' },} as any);- expect(queryMessages).toHaveBeenCalledWith({ agentId: 'agt_1', topicId: 'tpc_1' });+ expect(queryMessages).toHaveBeenCalledWith(+ { agentId: 'agt_1', topicId: 'tpc_1' },+ expect.anything(),+ );expect(result).toEqual(stubMessages);});+ it('opts the snapshot into agent-share visitor rows', async () => {+ // Regression: `MessageModel.query()` hides share-visitor messages by+ // default. A visitor run executes under the creator's identity, so+ // without the opt-in the terminal snapshot for the visitor's topic is+ // `[]` and the client replaces the conversation it just streamed with+ // nothing.+ const queryMessages = vi.fn().mockResolvedValue([]);+ stubMessageService(service, queryMessages);++ await service.queryUiMessages({+ metadata: { agentId: 'agt_1', topicId: 'tpc_1' },+ } as any);++ expect(queryMessages).toHaveBeenCalledWith(expect.anything(), { allowShareVisitor: true });+ });+it('scopes the snapshot to the run thread when the operation is a subtopic run', async () => {// Regression: without `threadId` the snapshot is the topic's MAIN// conversation, and the client writes it into the thread's bucket at@@ -1987,6 +2006,7 @@ describe('AgentRuntimeService', () => {expect(queryMessages).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'agt_1', threadId: 'thd_1', topicId: 'tpc_1' }),+ expect.anything(),);});@@ -2505,7 +2525,10 @@ describe('AgentRuntimeService', () => {threadId: 'thread-1',});- expect((service as any).messageModel.query).toHaveBeenCalledWith({ threadId: 'thread-1' });+ expect((service as any).messageModel.query).toHaveBeenCalledWith(+ { threadId: 'thread-1' },+ { allowShareVisitor: true },+ );expect(updateToolMessage).toHaveBeenCalledWith('grp-tool-1',expect.objectContaining({ content: 'hello from the CLI' }),@@ -2717,7 +2740,10 @@ describe('AgentRuntimeService', () => {await service.completeSubAgentBridge(bridgeParams);- expect((service as any).messageModel.query).toHaveBeenCalledWith({ threadId: 'thread-1' });+ expect((service as any).messageModel.query).toHaveBeenCalledWith(+ { threadId: 'thread-1' },+ { allowShareVisitor: true },+ );expect(updateToolMessage).toHaveBeenCalledWith('tool-msg-1',expect.objectContaining({ content: 'hello from the CLI' }),diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 60cf89fabf7..d3f4452b4a2 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -80,6 +80,7 @@ import {CriticalAgentInterventionPersistenceError,extractTextFromMessage,findLastAssistantMessage,+ isAgentShareRun,isSuccessLikeCompletionReason,normalizeCompletionMessages,} from './CompletionLifecycle';@@ -332,6 +333,25 @@ export interface AgentRuntimeDelegate {* placeholder before resuming the parked parent operation.*/execVirtualSubAgent?: (params: ExecVirtualSubAgentParams) => Promise<ExecSubAgentResult>;+ /**+ * Re-check that an Agent Share visitor run is STILL authorized to continue,+ * called on EVERY step. Without it, a revocation that lands mid-run (link →+ * private, share disabled, agent deleted) would only stop NEW requests: the+ * already-created operation keeps its tool snapshot and gateway channel and+ * keeps running under the CREATOR's credentials and budget, unstoppable by+ * the visitor (whose Stop button re-resolves the now-private share and gets+ * `FORBIDDEN`). Re-checking at every step boundary means a revocation always+ * takes effect within one step, with no durable interrupt-retry machinery.+ *+ * Implemented by AiAgentService via `AgentShareModel.isRunStillAuthorized`.+ * Returns `false` (not a throw) for an ordinary "no longer authorized"+ * outcome; the caller treats a THROWN error the same as `false` — fail+ * closed, never fail open.+ */+ verifyShareRunStillAuthorized?: (params: {+ agentId: string;+ shareId: string;+ }) => Promise<boolean>;}export interface AgentRuntimeServiceOptions {@@ -354,6 +374,13 @@ export interface AgentRuntimeServiceOptions {* circular import.*/delegate?: AgentRuntimeDelegate;+ /**+ * Opt IN to agent-share visitor rows for the models this service owns.+ * Reserved for share-runtime entry points that drive a visitor turn under+ * the CREATOR's `userId`. Defaults to false. See+ * {@link import('@/database/models/message').MessageModelOptions}.+ */+ includeShareVisitor?: boolean;/*** Custom QueueService* Set to null to disable queue scheduling (for synchronous execution tests)@@ -455,9 +482,14 @@ export class AgentRuntimeService {this.userId = userId;this.workspaceId = options?.workspaceId;const workspaceId = this.workspaceId;+ const includeShareVisitor = options?.includeShareVisitor ?? false;this.agentOperationModel = new AgentOperationModel(db, this.userId, workspaceId);- this.messageModel = new MessageModel(db, this.userId, workspaceId);- this.completionLifecycle = new CompletionLifecycle(db, userId, workspaceId);+ this.messageModel = new MessageModel(db, this.userId, workspaceId, undefined, {+ includeShareVisitor,+ });+ this.completionLifecycle = new CompletionLifecycle(db, userId, workspaceId, {+ includeShareVisitor,+ });this.humanIntervention = new HumanInterventionHandler(db, this.messageModel);// Initialize ToolExecutionService with dependencies@@ -734,6 +766,64 @@ export class AgentRuntimeService {}}+ /**+ * Terminate an Agent Share visitor run whose authorization was revoked+ * mid-flight (see the per-step check in `executeStep`).+ *+ * Persists `interrupted` onto the already-loaded state — the same terminal+ * status a visitor's own Stop produces — so the client's stream settles+ * normally instead of hanging. Falls back to `interruptOperation` when no+ * state was readable. A persistence failure is logged, never rethrown: the+ * run must stop regardless of whether the terminal status could be written.+ *+ * The completion lifecycle (`emitSignalEvents` + `dispatchHooks`) must run+ * here too: this abort short-circuits `executeStep` before `runtime.step()`,+ * so no downstream path is left to persist the terminal status. Without it+ * `saveAgentState` would only update the runtime-state cache and publish the+ * terminal stream event, leaving `agent_operations` stuck on `running` —+ * which `TopicModel.tryReserveTaskCallback` then reads as a live run and+ * blocks the visitor's next send on that topic for the abandoned-run TTL.+ */+ private async buildShareAbortResult(+ operationId: string,+ state: AgentState | null | undefined,+ ): Promise<AgentExecutionResult> {+ log('[%s] Aborting share visitor run — the share is no longer authorized', operationId);++ try {+ if (state) {+ const interruptedState: AgentState = {+ ...state,+ lastModified: new Date().toISOString(),+ status: 'interrupted',+ };+ await this.coordinator.saveAgentState(operationId, interruptedState);++ await this.completionLifecycle.emitSignalEvents(+ operationId,+ interruptedState,+ 'interrupted',+ );+ await this.completionLifecycle.dispatchHooks(operationId, interruptedState, 'interrupted');+ } else {+ await this.interruptOperation(operationId);+ }+ } catch (error) {+ log(+ '[%s] Failed to persist interrupted state for an aborted share run: %O',+ operationId,+ error,+ );+ }++ return {+ nextStepScheduled: false,+ state: { status: 'interrupted' },+ stepResult: null,+ success: false,+ };+ }+// ==================== Operation Management ====================/**@@ -747,6 +837,7 @@ export class AgentRuntimeService {initialContext,agentConfig,agentGroup,+ agentShareVisitor,modelRuntimeConfig,userId,autoStart = true,@@ -888,6 +979,7 @@ export class AgentRuntimeService {activeDeviceScope,agentConfig,agentGroup,+ agentShareVisitor,botContext,botPlatformContext,deviceAccessPolicy,@@ -938,8 +1030,20 @@ export class AgentRuntimeService {appContext?.orchestrationRole === 'member' ? (parentOperationId ?? undefined) : undefined;await this.coordinator.createAgentOperation(operationId, {agentConfig,+ // Persisted so a queue worker that never ran this op's init still+ // applies the owner-configured visitor redaction policy instead of the+ // fail-closed full strip. See `gatewayVisitorRedaction.ts`.+ visitorRedaction: agentShareVisitor+ ? {+ showErrorDetails: agentShareVisitor.showErrorDetails,+ showModelInfo: agentShareVisitor.showModelInfo,+ }+ : undefined,mirrorToOperationId,modelRuntimeConfig,+ // Share-visitor runs execute as the creator (`userId`) but stream only+ // to the visitor — the gateway registers the WS channel under this id.+ streamOwnerUserId: agentShareVisitor?.visitorUserId,userId,workspaceId: this.workspaceId,});@@ -1103,13 +1207,23 @@ export class AgentRuntimeService {if (!agentId || !topicId) return undefined;try {- return await this.messageService.queryMessages({- agentId,- groupId,- skipWorks: options?.skipWorks,- threadId,- topicId,- });+ return await this.messageService.queryMessages(+ {+ agentId,+ groupId,+ skipWorks: options?.skipWorks,+ threadId,+ topicId,+ },+ // The run's own topic is already resolved and authorized; an agent-share+ // visitor run executes under the CREATOR's identity, so without this the+ // creator-facing exclusion in `MessageModel.query()` returns an EMPTY+ // snapshot for the visitor's topic, and the client applies it as the+ // terminal Source of Truth — wiping the conversation the run just+ // produced. Visitor-facing redaction of the pushed snapshot happens in+ // `GatewayStreamNotifier`.+ { allowShareVisitor: true },+ );} catch (error) {// Stream events must never fail the step. If the DB hiccups, fall back// to letting the client refresh as before.@@ -1529,32 +1643,76 @@ export class AgentRuntimeService {};}+ // Agent Share: re-prove this visitor run's authorization on EVERY step.+ // A revocation only flips the `agent_shares` row — nothing tears down+ // an operation that was already created, so without this the run keeps+ // going under the creator's credentials/budget for the rest of its+ // (potentially very long) lifetime, and the visitor's own Stop button+ // has already stopped working (it re-resolves the now-private share and+ // gets FORBIDDEN). Re-checking here means a revocation cannot survive a+ // step boundary. See `AgentShareModel.isRunStillAuthorized`'s JSDoc for+ // why one query covers every revocation path (visibility flip — which+ // is what turning sharing off does — share delete, agent delete).+ if (this.delegate.verifyShareRunStillAuthorized) {+ const shareMarker = agentState.metadata?.agentShareVisitor as+ { agentId?: string; shareId?: string } | undefined;+ if (shareMarker?.agentId && shareMarker.shareId) {+ let stillAuthorized = false;+ try {+ stillAuthorized = await this.delegate.verifyShareRunStillAuthorized({+ agentId: shareMarker.agentId,+ shareId: shareMarker.shareId,+ });+ } catch (error) {+ // Fail closed: a read failure must not be read as "still+ // authorized". Falls through to the abort below with+ // `stillAuthorized` left `false`.+ log(+ '[%s][%d] Share run authorization re-check failed: %O',+ operationId,+ stepIndex,+ error,+ );+ }+ if (!stillAuthorized) {+ return this.buildShareAbortResult(operationId, agentState);+ }+ }+ }+let beforeStepSignalEvents: Array<{ [key: string]: unknown; type: string }> = [];// Dispatch beforeStep hookstry {const beforeStepMetadata = agentState?.metadata || {};- const beforeStepSignalEmission = await emitAgentSignalSourceEvent(- {- payload: {- agentId: beforeStepMetadata?.agentId,- operationId,- serializedContext: undefined,- stepIndex,- topicId: beforeStepMetadata?.topicId,- turnCount: agentState?.stepCount || 0,- },- sourceId: `${operationId}:before:${stepIndex}`,- sourceType: 'runtime.before_step',- },- {- agentId: beforeStepMetadata?.agentId,- db: this.serverDB,- userId: beforeStepMetadata?.userId || this.userId,- workspaceId: this.workspaceId,- },- { ignoreError: true },- );+ // Agent Share visitor runs execute AS the creator, so this+ // `userId`-scoped source event would record creator-owned Agent+ // Signal state for a turn an anonymous link visitor triggered — same+ // reasoning (and same predicate) as the completion-signal guard in+ // `CompletionLifecycle.emitSignalEvents`.+ const beforeStepSignalEmission = isAgentShareRun(beforeStepMetadata)+ ? undefined+ : await emitAgentSignalSourceEvent(+ {+ payload: {+ agentId: beforeStepMetadata?.agentId,+ operationId,+ serializedContext: undefined,+ stepIndex,+ topicId: beforeStepMetadata?.topicId,+ turnCount: agentState?.stepCount || 0,+ },+ sourceId: `${operationId}:before:${stepIndex}`,+ sourceType: 'runtime.before_step',+ },+ {+ agentId: beforeStepMetadata?.agentId,+ db: this.serverDB,+ userId: beforeStepMetadata?.userId || this.userId,+ workspaceId: this.workspaceId,+ },+ { ignoreError: true },+ );beforeStepSignalEvents = toAgentSignalSnapshotEvents(beforeStepSignalEmission);await hookDispatcher.dispatch(operationId,@@ -1881,27 +2039,31 @@ export class AgentRuntimeService {: undefined;const stepLabel = metadata?._stepLabel;+ // See the `runtime.before_step` guard above — same share-visitor+ // suppression at the sibling per-step emission.afterStepSignalEvents = toAgentSignalSnapshotEvents(- await emitAgentSignalSourceEvent(- {- payload: {- agentId: metadata?.agentId,- operationId,- serializedContext: undefined,- stepIndex,- topicId: metadata?.topicId,- turnCount: stepResult.newState?.stepCount || 0,- },- sourceId: `${operationId}:after:${stepIndex}`,- sourceType: 'runtime.after_step',- },- {- agentId: metadata?.agentId,- db: this.serverDB,- userId: metadata?.userId || this.userId,- },- { ignoreError: true },- ),+ isAgentShareRun(metadata)+ ? undefined+ : await emitAgentSignalSourceEvent(+ {+ payload: {+ agentId: metadata?.agentId,+ operationId,+ serializedContext: undefined,+ stepIndex,+ topicId: metadata?.topicId,+ turnCount: stepResult.newState?.stepCount || 0,+ },+ sourceId: `${operationId}:after:${stepIndex}`,+ sourceType: 'runtime.after_step',+ },+ {+ agentId: metadata?.agentId,+ db: this.serverDB,+ userId: metadata?.userId || this.userId,+ },+ { ignoreError: true },+ ),);await hookDispatcher.dispatch(@@ -3322,7 +3484,10 @@ export class AgentRuntimeService {threadId: state.metadata?.threadId,topicId: state.metadata?.topicId,},- { postProcessUrl },+ // The run's own topic is already resolved and authorized; an agent-share+ // visitor run executes under the CREATOR's identity, so it must opt out+ // of `query()`'s creator-facing agent-share exclusion.+ { allowShareVisitor: true, postProcessUrl },);}@@ -3377,7 +3542,7 @@ export class AgentRuntimeService {private async resolveLastAssistantContentFromThread(threadId: string,): Promise<string | undefined> {- const messages = await this.messageModel.query({ threadId });+ const messages = await this.messageModel.query({ threadId }, { allowShareVisitor: true });const lastAssistant = findLastAssistantMessage(normalizeCompletionMessages(messages));return extractTextFromMessage(lastAssistant) || undefined;}@@ -3550,6 +3715,7 @@ export class AgentRuntimeService {// an early hint would end the visible loading seconds before that card// can exist. Deferring to the terminal `visible_output_end` lets loading// cover the export and the card land with `agent_runtime_end`.+ agentShareVisitor: metadata?.agentShareVisitor,allowEarlyFinalAnswerVisibleOutputEnd:agent instanceof GeneralChatAgent && !stateHasEntityFileEdits(agentState),botContext: metadata?.botContext,@@ -3590,14 +3756,17 @@ export class AgentRuntimeService {*/private async computeDeviceContext(state: any) {try {- const dbMessages = await this.messageModel.query({- agentId: state.metadata?.agentId,- // Group runs need groupId or the query returns no group messages- // (standard branch filters `groupId IS NULL`), losing the device context.- groupId: state.metadata?.groupId,- threadId: state.metadata?.threadId,- topicId: state.metadata?.topicId,- });+ const dbMessages = await this.messageModel.query(+ {+ agentId: state.metadata?.agentId,+ // Group runs need groupId or the query returns no group messages+ // (standard branch filters `groupId IS NULL`), losing the device context.+ groupId: state.metadata?.groupId,+ threadId: state.metadata?.threadId,+ topicId: state.metadata?.topicId,+ },+ { allowShareVisitor: true },+ );return findInMessages(dbMessages,diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex eebde940719..51184cf44b8 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -69,6 +69,23 @@ export class CriticalAgentInterventionPersistenceError extends Error {type SignalEvent = { [key: string]: unknown; type: string };+/**+ * Whether a lifecycle event's `metadata` belongs to an Agent Share visitor+ * run. `metadata.agentShareVisitor.visitorUserId` is stamped once at operation+ * creation (`AgentRuntimeService.createOperation`'s `initialState.metadata`)+ * and rides the state through to the terminal event — mirrors+ * `GatewayStreamNotifier`'s share-visitor check, the sibling chokepoint that+ * scrubs the creator's `AgentState` off the visitor's WS channel.+ *+ * Exported so every OTHER chokepoint that emits a `userId`-scoped Agent+ * Signal source event on the runtime's `state`/operation metadata (the+ * `runtime.before_step` / `runtime.after_step` emissions in+ * `AgentRuntimeService`) can reuse the exact same check instead of+ * hand-rolling their own.+ */+export const isAgentShareRun = (metadata: Record<string, unknown> | undefined | null): boolean =>+ Boolean((metadata?.agentShareVisitor as { visitorUserId?: string } | undefined)?.visitorUserId);+/*** Normalized terminal-completion input for {@link CompletionLifecycle.completeOperation}.*@@ -164,12 +181,25 @@ export class CompletionLifecycle {private readonly serverDB: LobeChatDatabase,private readonly userId: string,workspaceId?: string,+ options?: {+ /**+ * Opt IN to agent-share visitor rows on this service's `messageModel`.+ * Reserved for share-runtime callers driving a visitor turn under the+ * creator's identity.+ */+ includeShareVisitor?: boolean;+ },) {this.workspaceId = workspaceId;- this.messageModel = new MessageModel(serverDB, userId, workspaceId);+ this.includeShareVisitor = options?.includeShareVisitor ?? false;+ this.messageModel = new MessageModel(serverDB, userId, workspaceId, undefined, {+ includeShareVisitor: this.includeShareVisitor,+ });this.agentOperationModel = new AgentOperationModel(serverDB, userId, workspaceId);}+ private readonly includeShareVisitor: boolean;+/*** Persist the initial `agent_operations` row when an operation is created.* Returns whether the row write succeeded so security-sensitive callers can@@ -456,6 +486,23 @@ export class CompletionLifecycle {async emitSignalEvents(operationId: string, state: any, reason: string): Promise<SignalEvent[]> {try {const { assistantMessageId, metadata } = this.buildLifecycleEvent(operationId, state, reason);++ // Agent Share visitor runs execute AS the creator (`metadata.userId` is+ // the creator's id — see `isAgentShareRun`'s JSDoc), so every completion+ // signal below (`agent.execution.completed` / `.failed`) would otherwise+ // run synchronous policy processing and record creator-scoped windows /+ // telemetry for a run an anonymous link visitor triggered. Suppress the+ // whole emission rather than merely re-scoping it: a share visitor has no+ // Agent Signal identity of its own to attribute this to.+ if (isAgentShareRun(metadata)) {+ log(+ '[completion-lifecycle] skip agent signal emission for share visitor run op=%s reason=%s',+ operationId,+ reason,+ );+ return [];+ }+let selfIteration =reason === 'error' ? undefined : extractSelfIterationCompletionPayload(state);if (reason !== 'error' && !selfIteration) {@@ -588,7 +635,9 @@ export class CompletionLifecycle {const op = await new AgentOperationModel(this.serverDB, userId).findById(operationId);if (!op?.topicId) return;- const messageModel = new MessageModel(this.serverDB, userId);+ const messageModel = new MessageModel(this.serverDB, userId, undefined, undefined, {+ includeShareVisitor: this.includeShareVisitor,+ });await messageModel.create({agentId: op.agentId ?? undefined,content: '',@@ -855,10 +904,18 @@ export class CompletionLifecycle {// WITHOUT `isSubAgent` (see execAgentMember), so guard both. The// remaining condition — only interactive chat runs recall the user —// lives in recallUserOnCompletion.+ //+ // Agent Share visitor runs execute AS the creator, so this `userId`-scoped+ // recall would otherwise reach the creator's push/inbox for every turn an+ // arbitrary link visitor completes — a visitor could spam the owner by+ // repeatedly running the shared agent, and the notification would deep-link+ // into a visitor topic (`topics.senderId`) that is deliberately excluded+ // from creator-facing surfaces.if (isSuccessLikeCompletionReason(reason) &&metadata?.isSubAgent !== true &&- metadata?.orchestrationRole !== 'member'+ metadata?.orchestrationRole !== 'member' &&+ !isAgentShareRun(metadata)) {void this.recallUserOnCompletion(operationId, event, metadata).catch((error) =>log('[%s] Completion notification failed (non-fatal): %O', operationId, error),@@ -1001,7 +1058,9 @@ export class CompletionLifecycle {const messageModel =userId === this.userId? this.messageModel- : new MessageModel(this.serverDB, userId, this.workspaceId);+ : new MessageModel(this.serverDB, userId, this.workspaceId, undefined, {+ includeShareVisitor: this.includeShareVisitor,+ });const row = await messageModel.findById(assistantMessageId);const raw = typeof row?.content === 'string' ? row.content : undefined;if (!raw?.trim()) return undefined;diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.tsindex 763e1a0e43a..5f0380aee48 100644--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts@@ -1,7 +1,11 @@// @vitest-environment nodeimport { beforeEach, describe, expect, it, vi } from 'vitest';+import { MessageModel } from '@/database/models/message';+import { TopicModel } from '@/database/models/topic';+import { AbandonOperationService } from '../AbandonOperationService';+import { CompletionLifecycle } from '../CompletionLifecycle';const buildStore = () => ({get: vi.fn(),@@ -530,6 +534,116 @@ describe('AbandonOperationService', () => {expect(coord.deleteAgentOperation).toHaveBeenCalledWith('op_member');});+ it('opts message/topic/lifecycle models into visitor rows for a visitor run (streamOwnerUserId present)', async () => {+ // Shared-agent visitor run: op executes as the creator (`user_owner`)+ // but the visitor (`visitor_1`) owns the stream. The abandon cleanup+ // touches rows on `topics.senderId <> NULL`, so MessageModel /+ // TopicModel / CompletionLifecycle must be constructed with+ // `includeShareVisitor: true` — otherwise the cleanup silently no-ops.+ (MessageModel as unknown as ReturnType<typeof vi.fn>).mockClear();+ (TopicModel as unknown as ReturnType<typeof vi.fn>).mockClear();+ (CompletionLifecycle as unknown as ReturnType<typeof vi.fn>).mockClear();++ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(+ stateWith({+ metadata: {+ agentId: 'agt_x',+ assistantMessageId: 'msg_assist_1',+ streamOwnerUserId: 'visitor_1',+ topicId: 'tpc_x',+ userId: 'user_owner',+ workspaceId: 'ws_1',+ },+ }),+ ),+ });+ const store = buildStore();+ store.loadPartial.mockResolvedValue(null);++ await new AbandonOperationService({} as any, {+ coordinator: coord as any,+ snapshotStore: store as any,+ }).finalizeAbandoned('op_visitor', 'inactivity_5m');++ expect(MessageModel).toHaveBeenCalledWith(expect.anything(), 'user_owner', 'ws_1', undefined, {+ includeShareVisitor: true,+ });+ expect(TopicModel).toHaveBeenCalledWith(expect.anything(), 'user_owner', 'ws_1', undefined, {+ includeShareVisitor: true,+ });+ expect(CompletionLifecycle).toHaveBeenCalledWith(expect.anything(), 'user_owner', 'ws_1', {+ includeShareVisitor: true,+ });+ });++ it('keeps the visitor exclusion for an ordinary creator run (no streamOwnerUserId)', async () => {+ (MessageModel as unknown as ReturnType<typeof vi.fn>).mockClear();+ (TopicModel as unknown as ReturnType<typeof vi.fn>).mockClear();+ (CompletionLifecycle as unknown as ReturnType<typeof vi.fn>).mockClear();++ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(stateWith()),+ });+ const store = buildStore();+ store.loadPartial.mockResolvedValue(null);++ await new AbandonOperationService({} as any, {+ coordinator: coord as any,+ snapshotStore: store as any,+ }).finalizeAbandoned('op_x', 'inactivity_5m');++ expect(MessageModel).toHaveBeenCalledWith(expect.anything(), 'user_x', undefined, undefined, {+ includeShareVisitor: false,+ });+ expect(TopicModel).toHaveBeenCalledWith(expect.anything(), 'user_x', undefined, undefined, {+ includeShareVisitor: false,+ });+ expect(CompletionLifecycle).toHaveBeenCalledWith(expect.anything(), 'user_x', undefined, {+ includeShareVisitor: false,+ });+ });++ it('opts the no-state cleanup path into visitor rows unconditionally', async () => {+ // No-state path only has the persisted `agentOperations` row; the op may+ // belong to a visitor topic whose rows the default gate would hide.+ // The service opts in unconditionally so the placeholder can still be+ // errored / topic settled.+ (MessageModel as unknown as ReturnType<typeof vi.fn>).mockClear();+ (TopicModel as unknown as ReturnType<typeof vi.fn>).mockClear();++ const coord = buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) });+ const store = buildStore();+ const db = buildDb({+ operationRow: {+ agentId: 'agt_x',+ id: 'op_ns',+ provider: 'claude-code',+ startedAt: new Date('2026-06-30T11:51:14.745Z'),+ status: 'running',+ topicId: 'tpc_x',+ userId: 'user_x',+ workspaceId: 'ws_1',+ },+ });+ topicSettleRunningOperationMock.mockResolvedValue({+ assistantMessageId: 'msg_ns',+ status: 'settled',+ });++ await new AbandonOperationService(db, {+ coordinator: coord as any,+ snapshotStore: store as any,+ }).finalizeAbandoned('op_ns', 'inactivity_watchdog');++ expect(TopicModel).toHaveBeenCalledWith(expect.anything(), 'user_x', 'ws_1', undefined, {+ includeShareVisitor: true,+ });+ expect(MessageModel).toHaveBeenCalledWith(expect.anything(), 'user_x', 'ws_1', undefined, {+ includeShareVisitor: true,+ });+ });+it('omits subAgentResume for a non-sub-agent abandoned op', async () => {const coord = buildCoordinator({loadAgentState: vi.fn().mockResolvedValue(stateWith()),diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.tsindex b4415070688..280d57056ed 100644--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts@@ -1724,3 +1724,70 @@ describe('AgentRuntimeService.executeStep - pre-snapshot file-Work registration'expect(registerSpy).not.toHaveBeenCalled();});});++describe('AgentRuntimeService.executeStep - Agent Share authorization revoked mid-run', () => {+ it('persists the terminal status through the completion lifecycle when the share is revoked', async () => {+ vi.mocked(createRuntimeExecutors).mockClear();++ const operationId = 'op-share-revoked';+ const verifyShareRunStillAuthorized = vi.fn().mockResolvedValue(false);+ const service = new AgentRuntimeService({} as any, 'user-1', {+ delegate: { verifyShareRunStillAuthorized } as any,+ queueService: null,+ });++ const agentState = {+ lastModified: new Date().toISOString(),+ metadata: { agentShareVisitor: { agentId: 'agent-1', shareId: 'share-1' } },+ status: 'running',+ stepCount: 3,+ };+ const coordinator = (service as any).coordinator;+ coordinator.loadAgentState = vi.fn().mockResolvedValue(agentState);+ coordinator.saveAgentState = vi.fn().mockResolvedValue(undefined);++ const completionLifecycle = (service as any).completionLifecycle;+ const emitSignalEvents = vi+ .spyOn(completionLifecycle, 'emitSignalEvents')+ .mockResolvedValue([]);+ const dispatchHooks = vi+ .spyOn(completionLifecycle, 'dispatchHooks')+ .mockResolvedValue(undefined);++ const result = await service.executeStep({+ context: { phase: 'user_input' } as any,+ operationId,+ stepIndex: 4,+ });++ expect(verifyShareRunStillAuthorized).toHaveBeenCalledWith({+ agentId: 'agent-1',+ shareId: 'share-1',+ });+ expect(coordinator.saveAgentState).toHaveBeenCalledWith(+ operationId,+ expect.objectContaining({ status: 'interrupted' }),+ );+ expect(emitSignalEvents).toHaveBeenCalledWith(+ operationId,+ expect.objectContaining({ status: 'interrupted' }),+ 'interrupted',+ );+ expect(dispatchHooks).toHaveBeenCalledWith(+ operationId,+ expect.objectContaining({ status: 'interrupted' }),+ 'interrupted',+ );+ // The run must abort before any model/tool work happens+ expect(createRuntimeExecutors).not.toHaveBeenCalled();+ expect(result).toMatchObject({+ nextStepScheduled: false,+ state: { status: 'interrupted' },+ stepResult: null,+ success: false,+ });++ emitSignalEvents.mockRestore();+ dispatchHooks.mockRestore();+ });+});diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex f631ecf11af..6986e467825 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -8,6 +8,7 @@ import type {ToolSource,} from '@lobechat/context-engine';import type {+ AgentShareVisitorContext,ChatTopicBotContext,EvalToolForwardingConfig,ExpertiseContextSnapshot,@@ -357,6 +358,14 @@ export interface OperationCreationParams {* `agt_*` IDs) — no per-step DB lookup, mirroring `botContext`.*/agentGroup?: AgentGroupConfig;+ /**+ * Shared-agent visitor marker. Persisted to+ * `state.metadata.agentShareVisitor` so every later step can re-derive the+ * share's restrictions without re-reading the share, and so+ * `AgentRuntimeService.executeStep` can re-prove the run's authorization at+ * each step boundary.+ */+ agentShareVisitor?: AgentShareVisitorContext;appContext: {agentId?: string;/**diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.tsindex 0b5105ab591..275bec56019 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts@@ -104,6 +104,13 @@ vi.mock('@/server/modules/ModelRuntime', () => ({initModelRuntimeFromDB: vi.fn(),}));+// The share path's atomic cap reservations open real DB transactions — stub+// them so the forced-headless test below can drive execAgent with a bare mock db.+vi.mock('../shareVisitorAbuseGuards', () => ({+ reserveShareVisitorTopic: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ reserveShareVisitorTurn: vi.fn().mockResolvedValue({ id: 'msg-1' }),+}));+vi.mock('model-bank', async (importOriginal) => {const actual = await importOriginal<typeof ModelBankModule>();return {@@ -194,6 +201,27 @@ 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.+ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Hello',+ shareGate: {+ agentId: 'agent-1',+ shareConfig: { toolGrants: [] },+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ userInterventionConfig: { approvalMode: 'manual' },+ });++ expect(mockCreateOperation).toHaveBeenCalledTimes(1);+ const callArgs = mockCreateOperation.mock.calls[0][0];+ expect(callArgs.userInterventionConfig).toEqual({ approvalMode: 'headless' });+ });+it('should respect explicit allow-list approval mode with allowList', async () => {const config = { allowList: ['tool-a', 'tool-b'], approvalMode: 'allow-list' as const };diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorTimezone.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorTimezone.test.tsnew file mode 100644index 00000000000..575747a2615--- /dev/null+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorTimezone.test.ts@@ -0,0 +1,201 @@+import type * as ModelBankModule from 'model-bank';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AiAgentService } from '../index';++const { mockCreateOperation, mockGetAgentConfig, mockGetUserSettings, mockMessageCreate } =+ vi.hoisted(() => ({+ mockCreateOperation: vi.fn(),+ mockGetAgentConfig: vi.fn(),+ mockGetUserSettings: vi.fn(),+ mockMessageCreate: vi.fn(),+ }));++vi.mock('@/libs/trusted-client', () => ({+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),+}));++vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(() => ({+ create: mockMessageCreate,+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),+ query: vi.fn().mockResolvedValue([]),+ update: vi.fn().mockResolvedValue({}),+ })),+}));++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(() => ({+ getAgentConfig: vi.fn(),+ queryAgents: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn().mockImplementation(() => ({+ getAgentConfig: mockGetAgentConfig,+ })),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(() => ({+ query: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),+ })),+}));++vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(() => ({+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+ })),+}));++// `UserModel` here is what actually resolves `userTimezone`. Constructed with+// the userId it was called with, so the test can distinguish "read the+// creator's settings" from "read the visitor's settings" purely by which id+// the call site passed in.+vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn().mockImplementation((_db: unknown, userId: string) => ({+ getUserPreference: vi.fn().mockResolvedValue({}),+ getUserSettings: () => mockGetUserSettings(userId),+ })),+}));++vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(() => ({+ createOperation: mockCreateOperation,+ })),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn().mockImplementation(() => ({+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/server/services/composio', () => ({+ ComposioService: vi.fn().mockImplementation(() => ({+ getComposioManifests: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(() => ({+ uploadFromUrl: vi.fn(),+ })),+}));++vi.mock('@/server/modules/Mecha', () => ({+ createServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),+}));++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ isConfigured: false,+ queryDeviceList: vi.fn().mockResolvedValue([]),+ },+}));++vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));++// The share path's atomic cap reservations open real DB transactions — stub+// them so the forced-headless test below can drive execAgent with a bare mock db.+vi.mock('../shareVisitorAbuseGuards', () => ({+ reserveShareVisitorTopic: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ reserveShareVisitorTurn: vi.fn().mockResolvedValue({ id: 'msg-1' }),+}));++vi.mock('model-bank', async (importOriginal) => {+ const actual = await importOriginal<typeof ModelBankModule>();+ return {+ ...actual,+ LOBE_DEFAULT_MODEL_LIST: [+ {+ abilities: { functionCall: true, video: false, vision: true },+ id: 'gpt-4',+ providerId: 'openai',+ },+ ],+ };+});++describe('AiAgentService.execAgent - share-visitor timezone resolution', () => {+ let service: AiAgentService;+ const mockDb = {} as any;+ const creatorId = 'creator-1';+ const visitorId = 'visitor-1';++ beforeEach(() => {+ vi.clearAllMocks();+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });+ mockCreateOperation.mockResolvedValue({+ autoStarted: true,+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ success: true,+ });+ mockGetAgentConfig.mockResolvedValue({+ chatConfig: {},+ id: 'agent-1',+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: '',+ });+ mockGetUserSettings.mockImplementation((userId: string) =>+ Promise.resolve({+ general: { timezone: userId === creatorId ? 'America/Los_Angeles' : 'Asia/Tokyo' },+ }),+ );+ service = new AiAgentService(mockDb, creatorId);+ });++ it('reads the timezone from the CREATOR when the run is not a share-visitor run', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Hello',+ });++ expect(mockCreateOperation).toHaveBeenCalledTimes(1);+ const callArgs = mockCreateOperation.mock.calls[0][0];+ expect(callArgs.userTimezone).toBe('America/Los_Angeles');+ });++ it('reads the timezone from the VISITOR, not the creator, on a share-visitor run', async () => {+ // The creator's timezone must never leak into a link visitor's session-date+ // placeholder — the visitor is the person actually conversing.+ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Hello',+ shareGate: {+ agentId: 'agent-1',+ shareConfig: { toolGrants: [] },+ shareId: 'share-1',+ visitorUserId: visitorId,+ },+ });++ expect(mockCreateOperation).toHaveBeenCalledTimes(1);+ const callArgs = mockCreateOperation.mock.calls[0][0];+ expect(callArgs.userTimezone).toBe('Asia/Tokyo');+ });+});diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.topicHistory.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.topicHistory.test.tsindex 06705acb37d..f12426811c7 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.topicHistory.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.topicHistory.test.ts@@ -4,11 +4,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { AiAgentService } from '../index';// Use vi.hoisted to ensure mock functions are available before vi.mock runs-const { mockMessageCreate, mockMessageQuery, mockCreateOperation } = vi.hoisted(() => ({- mockCreateOperation: vi.fn(),- mockMessageCreate: vi.fn(),- mockMessageQuery: vi.fn(),-}));+const { mockMessageCreate, mockMessageQuery, mockCreateOperation, mockTopicFindById } = vi.hoisted(+ () => ({+ mockCreateOperation: vi.fn(),+ mockMessageCreate: vi.fn(),+ mockMessageQuery: vi.fn(),+ mockTopicFindById: vi.fn(),+ }),+);// Mock trusted client to avoid server-side env accessvi.mock('@/libs/trusted-client', () => ({@@ -69,11 +72,25 @@ vi.mock('@/database/models/topic', () => ({releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-new' }),- findById: vi.fn().mockResolvedValue(undefined),+ findById: mockTopicFindById,updateMetadata: vi.fn().mockResolvedValue(undefined),})),}));+// Real implementation wraps the create in a `db.transaction(...)` for+// per-visitor cap enforcement — irrelevant to the read-side guard under test+// here, and `mockDb = {}` has no `transaction`. Delegate straight to the+// underlying model methods so a share-gated run in these tests exercises the+// same message-creation call the non-share path does.+vi.mock('../shareVisitorAbuseGuards', () => ({+ // Not exercised by these tests (they all target an existing topic), but+ // stubbed so an accidental new-topic share run doesn't hit `db.transaction`.+ reserveShareVisitorTopic: vi.fn().mockResolvedValue({ id: 'topic-shared-new' }),+ reserveShareVisitorTurn: vi.fn((_params, createParams, id) =>+ mockMessageCreate(createParams, id),+ ),+}));+vi.mock('@/database/models/thread', () => ({ThreadModel: vi.fn().mockImplementation(() => ({create: vi.fn(),@@ -145,6 +162,7 @@ describe('AiAgentService.execAgent - topic history loading', () => {mockMessageCreate.mockClear();mockMessageQuery.mockClear();mockCreateOperation.mockClear();+ mockTopicFindById.mockClear();mockMessageCreate.mockResolvedValue({ id: 'msg-1' });mockCreateOperation.mockResolvedValue({@@ -153,6 +171,7 @@ describe('AiAgentService.execAgent - topic history loading', () => {operationId: 'op-123',success: true,});+ mockTopicFindById.mockResolvedValue(undefined);service = new AiAgentService(mockDb, userId);});@@ -161,6 +180,7 @@ describe('AiAgentService.execAgent - topic history loading', () => {mockMessageCreate.mockClear();mockMessageQuery.mockClear();mockCreateOperation.mockClear();+ mockTopicFindById.mockClear();});describe('when topicId is provided (follow-up message in existing thread)', () => {@@ -178,10 +198,15 @@ describe('AiAgentService.execAgent - topic history loading', () => {prompt: '你能复述我说的第一句话吗',});- // Verify messageModel.query was called to load history for the topic+ // Verify messageModel.query was called to load history for the topic.+ // `allowShareVisitor` must be false for a non-share run — the history+ // loader must not opt out of the creator-facing agent-share exclusion.expect(mockMessageQuery).toHaveBeenCalledWith(expect.objectContaining({ topicId: 'topic-existing' }),- expect.objectContaining({ postProcessUrl: expect.any(Function) }),+ expect.objectContaining({+ allowShareVisitor: false,+ postProcessUrl: expect.any(Function),+ }),);// Verify createOperation received all history messages + the new user message@@ -219,4 +244,53 @@ describe('AiAgentService.execAgent - topic history loading', () => {expect(initialMessages[0]).toMatchObject({ content: 'Hello', role: 'user' });});});++ describe('share-visitor topic guard', () => {+ // Visitor topics carry the CREATOR's own userId (billing attribution) plus+ // `senderId` set to the visitor — see `packages/database/src/utils/shareVisitor.ts`.+ // A non-share run must never be able to load one via a leaked/guessed topicId.+ const visitorTopic = { id: 'topic-visitor', model: null, senderId: 'visitor-1' };++ it('rejects a non-share run whose topicId resolves to a share-visitor topic', async () => {+ mockTopicFindById.mockResolvedValue(visitorTopic);++ await expect(+ service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-visitor' },+ prompt: 'hi',+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ // The guard must fail BEFORE any history read reaches the visitor+ // transcript.+ expect(mockMessageQuery).not.toHaveBeenCalled();+ expect(mockCreateOperation).not.toHaveBeenCalled();+ });++ it("still allows the visitor's own authorized share run to load the same topic", async () => {+ mockTopicFindById.mockResolvedValue(visitorTopic);+ mockMessageQuery.mockResolvedValue([]);++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-visitor' },+ prompt: 'hi',+ shareGate: {+ agentId: 'agent-1',+ shareConfig: { toolGrants: [] },+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ });++ expect(mockCreateOperation).toHaveBeenCalled();+ // Authorized share run must opt into `allowShareVisitor` so it keeps+ // seeing its own transcript.+ expect(mockMessageQuery).toHaveBeenCalledWith(+ expect.objectContaining({ topicId: 'topic-visitor' }),+ expect.objectContaining({ allowShareVisitor: true }),+ );+ });+ });});diff --git a/apps/server/src/services/aiAgent/deviceAccessPolicy.ts b/apps/server/src/services/aiAgent/deviceAccessPolicy.tsindex 77c2a6bea51..445f62711d8 100644--- a/apps/server/src/services/aiAgent/deviceAccessPolicy.ts+++ b/apps/server/src/services/aiAgent/deviceAccessPolicy.ts@@ -30,7 +30,14 @@ export type DeviceAccessReason =* webhook didn't deliver the author). Treated as untrusted external —* fail-closed.*/- | 'bot-owner-not-configured';+ | 'bot-owner-not-configured'+ /**+ * Shared-agent visitor conversation — DENY device tools. The run executes+ * under the creator's identity, so device access would hand the visitor the+ * creator's machines; hetero targets degrade to sandbox, native device tools+ * to plain chat.+ */+ | 'share-visitor';/*** Bot platforms whose LobeHub integration is **personal-scope-only at the@@ -57,6 +64,8 @@ const PERSONAL_SCOPE_BOT_PLATFORMS = new Set<string>(['wechat']);export interface DeviceAccessPolicyInput {/** Undefined when the caller is a first-party UI (web / desktop / mobile). */botContext?: ChatTopicBotContext;+ /** True when the run serves a shared-agent visitor (share gate present). */+ shareVisitor?: boolean;}export interface DeviceAccessPolicyOutput {@@ -78,7 +87,13 @@ export interface DeviceAccessPolicyOutput {export const resolveDeviceAccessPolicy = (input: DeviceAccessPolicyInput,): DeviceAccessPolicyOutput => {- const { botContext } = input;+ const { botContext, shareVisitor } = input;++ // Checked before every trust branch: a share visitor is never allowed to+ // reach the creator's devices, regardless of how the request arrived.+ if (shareVisitor) {+ return { canUseDevice: false, reason: 'share-visitor' };+ }if (!botContext) {return { canUseDevice: true, reason: 'first-party' };diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 9319077ef33..ba814910af6 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -10,6 +10,7 @@ import type {ExecVirtualSubAgentParams,ScheduleAgentRunParams,ScheduleAgentRunResult,+ UserInterventionConfig,WorkingDirConfig,} from '@lobechat/types';import { getWorkingDirEffectivePath, RequestTrigger } from '@lobechat/types';@@ -23,6 +24,7 @@ import {} from '@/business/server/agent-run/agentInterventionIdentity';import { AgentModel } from '@/database/models/agent';import { AgentOperationModel } from '@/database/models/agentOperation';+import { AgentShareModel } from '@/database/models/agentShare';import { ConnectorModel } from '@/database/models/connector';import { ConnectorToolModel } from '@/database/models/connectorTool';import { DeviceModel } from '@/database/models/device';@@ -66,6 +68,7 @@ import { resolveRunAgentConfig } from './pipeline/resolveRunAgentConfig';import { startOperation } from './pipeline/startOperation';import { discoverTools } from './pipeline/toolDiscovery';import { setupTurn } from './pipeline/turnSetup';+import { applyShareGateToAgentConfig } from './shareGate';import type { SubAgentRunDeps } from './subAgentRuns';import { execAgentMember, execAgentThreadRun } from './subAgentRuns';import { acquireTopicStartReservation } from './topicStartReservation';@@ -113,6 +116,14 @@ export class AiAgentService {db: LobeChatDatabase,userId: string,options?: {+ /**+ * Opt IN to agent-share visitor rows for the models this service (and+ * the {@link AgentRuntimeService} it constructs) owns. Reserved for+ * share-runtime entry points that drive a visitor turn under the+ * creator's `userId` (`share.ownerId`). Defaults to false; ordinary+ * creator-facing entry points get the visitor exclusion for free.+ */+ includeShareVisitor?: boolean;marketAccessToken?: string;runtimeOptions?: AgentRuntimeServiceOptions;withholdGatewayToken?: boolean;@@ -124,19 +135,23 @@ export class AiAgentService {this.workspaceId = options?.workspaceId;this.withholdGatewayToken = options?.withholdGatewayToken ?? false;const wsId = this.workspaceId;+ const includeShareVisitor = options?.includeShareVisitor ?? false;+ const messageModelOptions = { includeShareVisitor };+ const topicModelOptions = { includeShareVisitor };this.agentDocumentsService = new AgentDocumentsService(db, userId, wsId);this.agentModel = new AgentModel(db, userId, wsId);this.agentOperationModel = new AgentOperationModel(db, userId, wsId);this.agentService = new AgentService(db, userId, wsId);- this.messageModel = new MessageModel(db, userId, wsId);+ this.messageModel = new MessageModel(db, userId, wsId, undefined, messageModelOptions);this.connectorModel = new ConnectorModel(db, userId, wsId);this.connectorToolModel = new ConnectorToolModel(db, userId, wsId);this.pluginModel = new PluginModel(db, userId, wsId);this.taskModel = new TaskModel(db, userId, wsId);this.threadModel = new ThreadModel(db, userId, wsId);- this.topicModel = new TopicModel(db, userId, wsId);+ this.topicModel = new TopicModel(db, userId, wsId, undefined, topicModelOptions);this.agentRuntimeService = new AgentRuntimeService(db, userId, {...options?.runtimeOptions,+ includeShareVisitor,agentFactory: createGraphAwareAgentFactory(options?.runtimeOptions?.agentFactory),// ── Runtime delegate ─────────────────────────────────────────────────// Operations the runtime delegates back UP to this layer. The dependency@@ -150,6 +165,7 @@ export class AiAgentService {execSubAgent: this.execSubAgent,execVirtualSubAgent: this.execVirtualSubAgent,execGroupMember: this.execGroupMember,+ verifyShareRunStillAuthorized: this.verifyShareRunStillAuthorized,},workspaceId: wsId,});@@ -635,7 +651,7 @@ export class AiAgentService {disableLocalSystem,initialStepCount,signal,- userInterventionConfig = { approvalMode: 'headless' },+ userInterventionConfig: requestedUserInterventionConfig = { approvalMode: 'headless' },queueRetries,queueRetryDelay,parentMessageId,@@ -647,11 +663,35 @@ export class AiAgentService {approvalResolutionRequestId: providedApprovalResolutionRequestId,approvalSourceOperationId: providedApprovalSourceOperationId,selectedToolIds,+ shareGate,mentionedAgents,suppressUserMessage,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.+ //+ // `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.+ const userInterventionConfig: UserInterventionConfig = shareGate+ ? { approvalMode: 'headless' }+ : requestedUserInterventionConfig;+// Honour client-minted row ids on a FRESH send only. Resume / regeneration// replays reach this method too (resumeApproval, resumeToolResult,// parentMessageId), and a replayed id there would collide with the row the@@ -751,6 +791,11 @@ export class AiAgentService {},);+ // Share-visitor runs must never see the creator's files/knowledge bases.+ // Applied to the resolved config before anything downstream (knowledge+ // flags, tools engine, context snapshot) reads it.+ if (shareGate) applyShareGateToAgentConfig(agentConfig);+let resumeParentMessage: Awaited<ReturnType<MessageModel['findById']>>;// `resumeApproval` implies the same "load parent message + skip user@@ -908,6 +953,7 @@ export class AiAgentService {resolvedAgentId,resume,runFromHistory,+ shareGate,throwIfExecutionAborted,title,trigger,@@ -942,6 +988,7 @@ export class AiAgentService {prompt,provider,resolvedAgentId,+ shareGate,topicId,trigger,userMessageId: turn.userMessageId,@@ -996,8 +1043,24 @@ export class AiAgentService {globalMemoryEnabled = agentMemoryEnabled ?? memorySettings?.enabled !== false;- const generalSettings = settings?.general as { timezone?: string } | undefined;- userTimezone = generalSettings?.timezone;+ // Timezone drives the session-date placeholder rendered back to whoever+ // is actually conversing. In a share-visitor run that is the VISITOR,+ // not the creator whose settings this block otherwise reads — memory /+ // expertise intentionally stay creator-scoped below (gated by+ // `allowReadMemory`), but the timezone has no such gate and must not+ // leak the creator's own setting into a visitor's turn.+ if (shareGate) {+ const visitorSettings = await new UserModel(+ this.db,+ shareGate.visitorUserId,+ ).getUserSettings();+ const visitorGeneralSettings = visitorSettings?.general as+ { timezone?: string } | undefined;+ userTimezone = visitorGeneralSettings?.timezone;+ } else {+ const generalSettings = settings?.general as { timezone?: string } | undefined;+ userTimezone = generalSettings?.timezone;+ }} catch (error) {log('execAgent: failed to fetch user settings: %O', error);}@@ -1007,6 +1070,13 @@ export class AiAgentService {} catch (error) {console.error('Failed to resolve expertise injection Lab preference:', error);}+ // Share visitors only get the creator's memory (persona + learned+ // expertise) when the share explicitly allows it — both surfaces would+ // otherwise leak the creator's personal context into visitor turns.+ if (shareGate && !shareGate.shareConfig.allowReadMemory) {+ globalMemoryEnabled = false;+ enableExpertise = false;+ }log('execAgent: globalMemoryEnabled=%s, timezone=%s',globalMemoryEnabled,@@ -1018,6 +1088,7 @@ export class AiAgentService {const loadHistoryMessages = createHistoryMessagesLoader({db: this.db,+ isShareVisitorRun: !!shareGate,messageModel: this.messageModel,userId: this.userId,workspaceId: this.workspaceId,@@ -1304,6 +1375,27 @@ export class AiAgentService {};}+ /**+ * `AgentRuntimeDelegate.verifyShareRunStillAuthorized` implementation — see+ * `AgentShareModel.isRunStillAuthorized`'s JSDoc for what "authorized" means+ * and why a per-step recheck (not only at step 0) is what actually stops a+ * revoked share's run: nothing tears down an operation that already exists,+ * and the visitor's own Stop button breaks the instant the share goes+ * private, so the step loop has to re-prove authorization itself.+ *+ * A plain top-level `db` read (not scoped to `this.userId`/workspace):+ * `agent_shares` has no ownership predicate applicable here — this call runs+ * from inside the CREATOR's own runtime step, so `this.db` is already the+ * correct connection.+ *+ * Arrow field (not a method) so it stays bound when handed to+ * AgentRuntimeService.+ */+ verifyShareRunStillAuthorized = async (params: {+ agentId: string;+ shareId: string;+ }): Promise<boolean> => AgentShareModel.isRunStillAuthorized(this.db, params);+/*** Execute an agent in an isolated Thread context.*diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.tsnew file mode 100644index 00000000000..40834bd5b91--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts@@ -0,0 +1,250 @@+import type * as ModelBankModule from 'model-bank';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AiAgentService } from '../../index';++// The share-gate filter now runs at the top of `discoverTools`, before+// connector resolution / stale-tool refresh — so an ungranted HTTP connector+// pinned on the creator's agent must never reach either callsite for a+// visitor turn. These spies live at hoist time so the `vi.mock` factories+// below (which run before the test body) can wire them into stubbed models.+const {+ mockCreateOperation,+ mockGetAgentConfig,+ mockGetUserSettings,+ mockMessageCreate,+ mockResolveByIdentifiers,+ mockScheduleStaleConnectorToolsRefresh,+} = vi.hoisted(() => ({+ mockCreateOperation: vi.fn(),+ mockGetAgentConfig: vi.fn(),+ mockGetUserSettings: vi.fn(),+ mockMessageCreate: vi.fn(),+ // Returns `[]` so `connectorsMcp` stays empty — we only care about the+ // identifier list the share-gate filter allowed through to this call.+ mockResolveByIdentifiers: vi.fn().mockResolvedValue([]),+ mockScheduleStaleConnectorToolsRefresh: vi.fn(),+}));++vi.mock('@/libs/trusted-client', () => ({+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),+}));++vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(() => ({+ create: mockMessageCreate,+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),+ query: vi.fn().mockResolvedValue([]),+ update: vi.fn().mockResolvedValue({}),+ })),+}));++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(() => ({+ getAgentConfig: vi.fn(),+ queryAgents: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn().mockImplementation(() => ({+ getAgentConfig: mockGetAgentConfig,+ })),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(() => ({+ query: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/database/models/connector', () => ({+ ConnectorModel: vi.fn().mockImplementation(() => ({+ queryByIdentifiers: vi.fn().mockResolvedValue([]),+ resolveByIdentifiers: mockResolveByIdentifiers,+ })),+}));++vi.mock('@/database/models/connectorTool', () => ({+ ConnectorToolModel: vi.fn().mockImplementation(() => ({+ queryAllByConnectorIds: vi.fn().mockResolvedValue([]),+ queryByConnector: vi.fn().mockResolvedValue([]),+ queryByConnectorIds: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(() => ({+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),+ })),+}));++vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(() => ({+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+ })),+}));++vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn().mockImplementation(() => ({+ getUserPreference: vi.fn().mockResolvedValue({}),+ getUserSettings: () => mockGetUserSettings(),+ })),+}));++vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(() => ({+ createOperation: mockCreateOperation,+ })),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn().mockImplementation(() => ({+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/server/services/composio', () => ({+ ComposioService: vi.fn().mockImplementation(() => ({+ getComposioManifests: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(() => ({+ uploadFromUrl: vi.fn(),+ })),+}));++vi.mock('@/server/modules/Mecha', () => ({+ createServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),+}));++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ isConfigured: false,+ queryDeviceList: vi.fn().mockResolvedValue([]),+ },+}));++vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));++vi.mock('@/server/services/connector/refresh', () => ({+ buildLastSyncedAtMap: vi.fn().mockReturnValue(new Map()),+ scheduleStaleConnectorToolsRefresh: mockScheduleStaleConnectorToolsRefresh,+}));++// The share path's atomic cap reservations open real DB transactions — stub+// them so this test can drive execAgent with a bare mock db.+vi.mock('../../shareVisitorAbuseGuards', () => ({+ reserveShareVisitorTopic: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ reserveShareVisitorTurn: vi.fn().mockResolvedValue({ id: 'msg-1' }),+}));++vi.mock('model-bank', async (importOriginal) => {+ const actual = await importOriginal<typeof ModelBankModule>();+ return {+ ...actual,+ LOBE_DEFAULT_MODEL_LIST: [+ {+ abilities: { functionCall: true, video: false, vision: true },+ id: 'gpt-4',+ providerId: 'openai',+ },+ ],+ };+});++describe('discoverTools - share gate blocks ungranted connectors early', () => {+ let service: AiAgentService;+ const mockDb = {} as any;++ beforeEach(() => {+ vi.clearAllMocks();+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });+ mockCreateOperation.mockResolvedValue({+ autoStarted: true,+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ success: true,+ });+ mockGetUserSettings.mockResolvedValue({ general: { timezone: 'UTC' } });+ // Pinned plugins on the creator's agent — one granted by the share, the+ // other is a connector-backed identifier that must not be resolved for a+ // visitor.+ mockGetAgentConfig.mockResolvedValue({+ chatConfig: {},+ id: 'agent-1',+ model: 'gpt-4',+ plugins: ['granted-plugin', 'ungranted-connector'],+ provider: 'openai',+ systemRole: '',+ });+ service = new AiAgentService(mockDb, 'creator-1');+ });++ it('does not resolve or schedule refresh for a pinned connector missing from toolGrants', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Hello',+ shareGate: {+ agentId: 'agent-1',+ // Only the first plugin is granted; the connector-backed one is not.+ shareConfig: { toolGrants: [{ identifier: 'granted-plugin' }] },+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ });++ expect(mockResolveByIdentifiers).toHaveBeenCalledTimes(1);+ const resolvedIdentifiers = mockResolveByIdentifiers.mock.calls[0][0] as string[];+ expect(resolvedIdentifiers).toContain('granted-plugin');+ expect(resolvedIdentifiers).not.toContain('ungranted-connector');++ // `resolveByIdentifiers` mock returns [] → `connectorsMcp` stays empty →+ // the schedule call is invoked with an empty MCP-connector list. The key+ // assertion here is that no work is scheduled against the ungranted+ // connector; asserting the array is empty proves it.+ expect(mockScheduleStaleConnectorToolsRefresh).toHaveBeenCalledTimes(1);+ const scheduledConnectors = mockScheduleStaleConnectorToolsRefresh.mock+ .calls[0][0] as unknown[];+ expect(scheduledConnectors).toEqual([]);+ });++ it('still resolves connectors that the share explicitly grants', async () => {+ // Both pinned identifiers are granted → both must reach the connector+ // resolver as normal, proving the early filter is not over-aggressive.+ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Hello',+ shareGate: {+ agentId: 'agent-1',+ shareConfig: {+ toolGrants: [{ identifier: 'granted-plugin' }, { identifier: 'ungranted-connector' }],+ },+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ });++ expect(mockResolveByIdentifiers).toHaveBeenCalledTimes(1);+ const resolvedIdentifiers = mockResolveByIdentifiers.mock.calls[0][0] as string[];+ expect(resolvedIdentifiers).toEqual(+ expect.arrayContaining(['granted-plugin', 'ungranted-connector']),+ );+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.tsindex 31ffa23d0f9..822d9769a43 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts@@ -331,7 +331,14 @@ export const dispatchHeteroAgent = async (let conversationHistory: ConversationHistoryEntry[] | undefined;if (heteroType !== 'amp') {try {- const recentMsgs = await deps.messageModel.query({ topicId, pageSize: 200 });+ // `allowShareVisitor`: this is the RUN's own topic, already resolved+ // and authorized upstream. An agent-share visitor run executes under+ // the creator's identity, so without the opt-in `query()`'s+ // creator-facing default would hand the agent an empty history.+ const recentMsgs = await deps.messageModel.query(+ { topicId, pageSize: 200 },+ { allowShareVisitor: true },+ );const turns = recentMsgs.filter((m) =>diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.tsindex 652c0e26120..50e4b0cda9d 100644--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts@@ -33,6 +33,7 @@ import { FileService } from '@/server/services/file';import { pruneRegeneratedBranch } from '../pruneRegeneratedBranch';import { resolveDeviceWorkingDirectoryConfig } from '../resolveDeviceWorkingDirectory';+import { applyShareGateToToolSet, filterPluginsByShareGate } from '../shareGate';import type { ExecRunContext, InternalExecAgentParams, ResolvedWorkspaceInit } from '../types';import { isWorkspaceCacheFresh, upsertWorkspaceScan } from '../workspaceInitCache';import type { ToolDiscoveryResult } from './toolDiscovery';@@ -55,7 +56,13 @@ export interface HistoryLoaderInput {* cached so the run pays the query at most once.*/export const createHistoryMessagesLoader = (- deps: { db: LobeChatDatabase; messageModel: MessageModel; userId: string; workspaceId?: string },+ deps: {+ db: LobeChatDatabase;+ isShareVisitorRun: boolean;+ messageModel: MessageModel;+ userId: string;+ workspaceId?: string;+ },input: HistoryLoaderInput,): (() => Promise<any[]>) => {const {@@ -72,6 +79,17 @@ export const createHistoryMessagesLoader = (const postProcessUrl = (path: string | null, file: { id?: string | null }) =>fileService.getFileAccessUrl({ id: file.id, url: path });let historyMessagesCache: any[] | undefined;+ // The run's own topic was resolved and authorized upstream (a share visitor+ // run reaches here through `findVisitorTopicOrThrow`), and it executes under+ // the CREATOR's identity — so an AUTHORIZED share run must opt out of+ // `query()`'s creator-facing agent-share exclusion or the agent loses its+ // history. A non-share run must NOT get this opt-out: `turnSetup`'s+ // visitor-topic guard rejects a non-share run whose `appContext.topicId`+ // resolves to a visitor topic, but this loader is cheap defense-in-depth in+ // case that guard is ever bypassed or a future call site skips it — without+ // it, a non-share run pointed at a leaked visitor topicId would still load+ // the visitor's transcript into the owner's model context.+ const historyQueryOptions = { allowShareVisitor: deps.isShareVisitorRun, postProcessUrl };return async () => {if (historyMessagesCache) return historyMessagesCache;@@ -83,7 +101,7 @@ export const createHistoryMessagesLoader = (threadId: appContext?.threadId,topicId: appContext?.topicId ?? undefined,},- { postProcessUrl },+ historyQueryOptions,);const idSet = new Set(existingMessageIds);historyMessagesCache = messages.filter((msg) => idSet.has(msg.id));@@ -98,7 +116,7 @@ export const createHistoryMessagesLoader = (threadId: appContext?.threadId,topicId: appContext?.topicId,},- { postProcessUrl },+ historyQueryOptions,);historyMessagesCache = messages.filter((msg) => !selfMessageIds.has(msg.id));} else {@@ -325,6 +343,7 @@ export const prepareOperation = async (prompt,provider,resolvedAgentId,+ shareGate,topicId,userMessageId,} = ctx;@@ -648,6 +667,31 @@ export const prepareOperation = async (}).enabledToolIds: [];+ // Final share-gate allowlist enforcement — run once here, after every+ // manifest/default/dynamic-activation source (installed plugins, LobeHub+ // Skills, Composio, real-MCP connectors, always-on builtin defaults) has+ // been merged into `toolManifestMap` / `toolsResult.enabledToolIds` /+ // `tools` / `activatableToolIds` by `toolDiscovery` and the historical+ // re-activation pass above. `filterPluginsByShareGate` in `toolDiscovery`+ // only trimmed the initial candidate id list — it does not stop+ // `lobe-activator` from dynamically activating (and `ToolExecutionService`+ // from executing, with the CREATOR's credentials) a creator-connected tool+ // that was never in `shareConfig.toolGrants`. Mutates the discovery maps+ // in place, so the `toolSet` handed to `createOperation` is the pruned one.+ if (shareGate) {+ applyShareGateToToolSet(+ {+ activatableToolIds,+ enabledToolIds: toolsResult.enabledToolIds,+ executorMap: discovery.toolExecutorMap,+ manifestMap: discovery.toolManifestMap,+ sourceMap: discovery.toolSourceMap,+ tools,+ },+ shareGate,+ );+ }+log('execAgent: prepared evalContext for executor');await throwIfExecutionAborted('operation preparation');@@ -909,10 +953,28 @@ export const prepareOperation = async (// against, so a disabled identifier absent here is neither listed nor// activatable — mirrors the tool-manifest treatment above (installedPlugins/// additionalManifests), which this array had never received.+ //+ // Shared runs only see skills allowed by the share configuration. The+ // candidate pool must be trimmed here rather than left to+ // `SkillEngine.generate`, which annotates activation state on its input+ // rather than shrinking it. Reuse `filterPluginsByShareGate` (id-list+ // intersection, not tool-specific) to keep this pool the single+ // enforcement point — an empty/missing allowlist collapses it to nothing.+ const shareAllowedSkillIds = shareGate+ ? new Set(+ filterPluginsByShareGate(+ [...projectMetas, ...dbMetas, ...agentSkillMetas, ...builtinMetas].map(+ (skill) => skill.identifier,+ ),+ shareGate,+ ),+ )+ : undefined;const seenNames = new Set<string>();const skills = [...projectMetas, ...dbMetas, ...agentSkillMetas, ...builtinMetas].filter((skill) => {if (disabledPluginIds.includes(skill.identifier)) return false;+ if (shareAllowedSkillIds && !shareAllowedSkillIds.has(skill.identifier)) return false;if (seenNames.has(skill.name)) return false;seenNames.add(skill.name);return true;diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.tsindex 08ed10c2f93..f584eaa57cf 100644--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts@@ -82,6 +82,7 @@ export const startOperation = async (parentMessageId,provider,resolvedAgentId,+ shareGate,topicId,trigger,userMessageId,@@ -136,6 +137,40 @@ export const startOperation = async (activeDeviceScope: discovery.activeDeviceScope,agentConfig,agentGroup: discovery.operationAgentGroup,+ agentShareVisitor: shareGate+ ? {+ agentId: shareGate.agentId,+ // Mirrors `shareConfig.allowReadMemory` so `BuiltinToolsExecutor`+ // can re-check the memory tool's grant at dispatch time (the+ // actual chokepoint) via `isShareBlockedDataToolCall` — see+ // `shareGate.ts`.+ allowReadMemory: shareGate.shareConfig.allowReadMemory,+ // Mirrors `shareConfig.toolGrants` so tool runtimes resolved+ // outside `toolManifestMap` (e.g. `activateSkill`, which queries+ // builtin/DB skills by name) can enforce the same allowlist.+ toolGrants: shareGate.shareConfig.toolGrants,+ // Sourced from the agent's OWN persisted assignment+ // (`agentConfig.knowledgeBases`, already blanked by+ // `applyShareGateToAgentConfig` in `execAgent`), never from visitor+ // input. Lets `isShareBlockedDataToolCall` scope+ // `lobe-knowledge-base.viewKnowledgeBase`'s `id` argument to+ // knowledge bases actually mounted on this agent.+ knowledgeBaseIds: (agentConfig.knowledgeBases ?? [])+ .filter((kb: { enabled?: boolean | null; id?: string | null }) => kb.enabled && kb.id)+ .map((kb: { id?: string | null }) => kb.id as string),+ // The share instance this run was authorized against. Re-read (not+ // reused) at every step boundary by+ // `AgentRuntimeService.executeStep` via+ // `AgentShareModel.isRunStillAuthorized`, so a revocation+ // committed mid-run is caught at the next step instead of only at+ // creation time. See `AgentShareGate.shareId`'s JSDoc for why the+ // id itself is the revocation token.+ shareId: shareGate.shareId,+ showErrorDetails: shareGate.shareConfig.showErrorDetails,+ showModelInfo: shareGate.shareConfig.showModelInfo,+ visitorUserId: shareGate.visitorUserId,+ }+ : undefined,deviceSystemInfo:Object.keys(prep.deviceSystemInfo).length > 0 ? prep.deviceSystemInfo : undefined,executionPlan: discovery.executionPlan,@@ -285,11 +320,16 @@ export const startOperation = async (});}- // Generate a short-lived JWT for Gateway WebSocket authentication+ // Generate a short-lived JWT for Gateway WebSocket authentication.+ // Share-visitor runs sign for the VISITOR: signUserJWT mints a full+ // oidcAuth token, so a creator-signed token handed to the visitor's+ // browser would be creator account access. The gateway channel is+ // registered under the visitor's id (`streamOwnerUserId`), so the+ // visitor's own `sub` matches.let gatewayToken: string | undefined;if (!deps.withholdGatewayToken) {try {- gatewayToken = await signUserJWT(deps.userId);+ gatewayToken = await signUserJWT(shareGate?.visitorUserId ?? deps.userId);} catch {log('execAgent: failed to sign gateway JWT, gateway auth will be unavailable');}diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.tsindex 0063bff36a2..85c0be8a312 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts@@ -80,6 +80,7 @@ import {isMultimodalUnderstandingConfigured,} from '../helpers/mediaAvailability';import { resolveServerSearchDecision } from '../searchDecision';+import { filterPluginsByShareGate, shareGateGrantsCloudSandbox } from '../shareGate';import type { ExecRunContext, InternalExecAgentParams } from '../types';const log = debug('lobe-server:ai-agent-service');@@ -176,6 +177,7 @@ export const discoverTools = async (prompt,provider,resolvedAgentId,+ shareGate,topicId,} = ctx;const {@@ -249,6 +251,19 @@ export const discoverTools = async (]),];+ // Share allowlist runs EARLY, before connector resolution / credential+ // decryption / stale-tool refresh scheduling — otherwise an ungranted HTTP+ // connector pinned on the creator's agent would still be resolved and its+ // OAuth credentials touched for a visitor turn (issuing background MCP+ // traffic and refresh jobs on behalf of the creator). The later pass right+ // before manifest discovery (~line 618) stays as defense in depth: internal+ // additions like the topic-reference / bot message / multimodal+ // understanding tool are appended after this point and must run through the+ // same allowlist.+ if (shareGate) {+ agentPlugins = filterPluginsByShareGate(agentPlugins, shareGate);+ }+// Model metadata is needed both for tool support checks and agent-management context.const { loadModels } = await import('@/business/client/model-bank/loadModels');const builtinModels = await loadModels();@@ -604,6 +619,26 @@ export const discoverTools = async (...(shouldEnableMultimodalUnderstanding ? [LobeAgentManifest.identifier] : []),];+ // Share allowlist filters the full candidate set (pinned + mentioned ++ // internal additions) before manifest discovery. This only trims which+ // plugin ids get *activated*; the separate skill candidate pool built in+ // `operationPrep` (`skills`, consumed by `SkillEngine`) needs its own pass+ // against the same allowlist, since building the skill list is a distinct+ // step from `SkillEngine.generate` and is not scoped by the plugin id list+ // on its own. The operationToolSet snapshot then carries the restricted+ // surface into every later step.+ //+ // Defense in depth: the same filter also runs at the top of+ // `discoverTools` (before connector resolution) so that ungranted+ // connectors never reach `resolveByIdentifiers` /+ // `scheduleStaleConnectorToolsRefresh`. Keep this second pass — the+ // internal additions above (topic reference, bot message tool,+ // multimodal understanding) are appended after the first pass and would+ // otherwise slip through.+ if (shareGate) {+ agentPlugins = filterPluginsByShareGate(agentPlugins, shareGate);+ }+// Resolve THE device decision for this run. All rules live in// `resolveExecutionPlan` (gated on `canUseDevice` first, `none`/`sandbox`// never route to a device, offline bindings stay unrouted, unbound runs@@ -624,6 +659,12 @@ export const discoverTools = async (// Pass `chatConfig` so the plan degrades to `none` in chat mode — the// chat-mode derivation lives in `resolveExecutionPlan` (`resolveToolMode`),// the same source of truth the tools engine uses.+ //+ // A share visitor never passes `canUseDevice`, so a creator agent that+ // targets `local`/`auto` would collapse to `none` and silently drop a+ // `lobe-cloud-sandbox` grant (the sandbox manifest only materializes when+ // the plan resolves to `sandbox`). `sandboxFallback` keeps that decision+ // inside the resolver instead of patching its result here.executionPlan = resolveExecutionPlan({agencyConfig: agentConfig.agencyConfig,canUseDevice,@@ -632,6 +673,7 @@ export const discoverTools = async (localDeviceId,onlineDeviceIds: onlineDevices.map((device) => device.deviceId),requestedDeviceId,+ sandboxFallback: shareGate ? shareGateGrantsCloudSandbox(shareGate) : false,trigger: requestTrigger,});// A fixed device target must never degrade to the cloud sandbox or a@@ -1000,8 +1042,19 @@ export const discoverTools = async (const agentSelfIterationEnabled = agentConfig.chatConfig?.selfIteration?.enabled === true;const isLobeAiAgent = isLobeAiAgentSlug(agentSlug);+ // Share-visitor fail-closed gate — never expose the+ // `declareSelfFeedbackIntent` tool to a share-visitor turn. This tool sits+ // outside the normal `toolManifestMap` / `applyShareGateToToolSet`+ // allowlist (it's injected directly into `tools` below), so the visitor's+ // own model call can reach it even with an empty `enabledToolIds`. Its+ // execution context is stamped with the share CREATOR's user id, and the+ // resulting `agent.self_feedback_intent.declared` event dispatches a full+ // autonomous background run under the creator's account, which can write+ // to the creator's memory. Same root cause as the `agent.user.message`+ // gate in `turnSetup`; `allowReadMemory` is a read-only grant so this must+ // not be conditional on it either.const shouldCheckUserSelfIterationGate =- !disableSelfFeedbackIntentTool && (agentSelfIterationEnabled || isLobeAiAgent);+ !shareGate && !disableSelfFeedbackIntentTool && (agentSelfIterationEnabled || isLobeAiAgent);if (shouldCheckUserSelfIterationGate) {const featureUserEnabled = await isAgentSignalEnabledForUser(deps.db, deps.userId);const effectiveAgentSelfIterationEnabled = resolveAgentSelfIterationCapability({diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.tsindex da360390f2c..793cab669e3 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -7,7 +7,12 @@ import type {ChatVideoItem,HeterogeneousTopicModel,} from '@lobechat/types';-import { RequestTrigger, resolveHeterogeneousProviderTopicModel } from '@lobechat/types';+import {+ ChatErrorType,+ RequestTrigger,+ resolveHeterogeneousProviderTopicModel,+} from '@lobechat/types';+import { TRPCError } from '@trpc/server';import debug from 'debug';import type { MessageModel } from '@/database/models/message';@@ -23,6 +28,8 @@ import { markdownToTxt } from '@/utils/markdownToTxt';import type { DeviceAccessReason } from '../deviceAccessPolicy';import { resolveDeviceAccessPolicy } from '../deviceAccessPolicy';import { ingestAttachment } from '../ingestAttachment';+import type { AgentShareGate } from '../shareGate';+import { reserveShareVisitorTopic, reserveShareVisitorTurn } from '../shareVisitorAbuseGuards';import type { InternalExecAgentParams } from '../types';const log = debug('lobe-server:ai-agent-service');@@ -249,6 +256,8 @@ export interface TurnSetupInput {/** Raw resume flag — a resume run must land on an existing topic. */resume?: boolean;runFromHistory: boolean;+ /** Shared-agent visitor gate — set only by the shareChat router. */+ shareGate?: AgentShareGate;throwIfExecutionAborted: (stage: string) => Promise<void>;title?: string;trigger?: string;@@ -317,6 +326,7 @@ export const setupTurn = async (resolvedAgentId,resume,runFromHistory,+ shareGate,throwIfExecutionAborted,title,trigger,@@ -351,6 +361,19 @@ export const setupTurn = async (: undefined;let pinnedHeterogeneousTopicModel: HeterogeneousTopicModel | undefined;+ // Share-visitor fail-closed gate — reject a heterogeneous (Claude Code /+ // Codex / …) agent BEFORE any topic/message row is written. Heterogeneous+ // agents are not available for shared visitor runs. Checked here (using the+ // agent-level config, before any topic-pinned model override) rather than+ // at the later hetero-detection site (`isHeteroAgent`) so it runs ahead of+ // ALL row creation, not just the message rows.+ if (shareGate && (heterogeneousProvider?.type || isHeterogeneousAgentModelId(model))) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: ChatErrorType.ShareHeterogeneousAgentUnsupported,+ });+ }+if (!topicId) {if (resume) {throw new Error('Resume mode requires the parent message to belong to a topic');@@ -400,29 +423,53 @@ export const setupTurn = async (heterogeneousProvider?.type ?? (isHeterogeneousAgentModelId(model) ? model : undefined);// Second argument: the id the client already rendered this topic under// (sidebar row, message bucket). Absent → the model mints one as before.- const newTopic = await deps.topicModel.create(- {- agentId: resolvedAgentId,- // Persist the group association when running inside a group conversation.- // Without it the topic is created group-less and only shows under the- // member agent's topic list — never in the group sidebar (which queries- // `topics.groupId`), so the conversation silently "disappears" from the- // group. execGroupAgent normally pre-creates the topic, but any path- // that reaches execAgent without a topicId (e.g. the async/queue run)- // must carry the groupId through too (group topic sidebar + ownership fix).- groupId: appContext?.groupId,- metadata,- // Snapshot the effective model as the topic's pinned model (config).- model: heterogeneousTopicModelSnapshot?.model ?? (heteroSnapshotType ? undefined : model),- provider: heterogeneousTopicModelSnapshot?.provider ?? heteroSnapshotType ?? provider,- title:- title !== undefined- ? title- : fallbackTitleSource.slice(0, 50) + (fallbackTitleSource.length > 50 ? '...' : ''),- trigger,- },- clientIds?.topicId,- );+ const newTopicParams = {+ agentId: resolvedAgentId,+ // Persist the group association when running inside a group conversation.+ // Without it the topic is created group-less and only shows under the+ // member agent's topic list — never in the group sidebar (which queries+ // `topics.groupId`), so the conversation silently "disappears" from the+ // group. execGroupAgent normally pre-creates the topic, but any path+ // that reaches execAgent without a topicId (e.g. the async/queue run)+ // must carry the groupId through too (group topic sidebar + ownership fix).+ groupId: appContext?.groupId,+ metadata,+ // Snapshot the effective model as the topic's pinned model (config).+ model: heterogeneousTopicModelSnapshot?.model ?? (heteroSnapshotType ? undefined : model),+ provider: heterogeneousTopicModelSnapshot?.provider ?? heteroSnapshotType ?? provider,+ // Share-visitor runs: the topic row belongs to the creator+ // (`deps.userId`), but stamping the visitor's id here is what+ // `TopicModel`'s creator-facing reads (`query`, `count`, `queryTopics`,+ // `queryRecent`, `rank`) filter out via `notShareVisitorTopic()`, and+ // what lets shareChat scope reads per visitor (`queryBySender` /+ // `countBySender`). There is no share-instance column — a visitor+ // topic is tied to its share purely through `(agentId, senderId)`,+ // which is unambiguous because `agent_shares` is 1:1 per agent.+ senderId: shareGate?.visitorUserId,+ title:+ title !== undefined+ ? title+ : fallbackTitleSource.slice(0, 50) + (fallbackTitleSource.length > 50 ? '...' : ''),+ trigger,+ };+ // Share-visitor runs must reserve the `maxTopicsPerVisitor` slot and+ // insert the topic in ONE locked transaction — see+ // `reserveShareVisitorTopic`'s JSDoc for the race this closes. Non-share+ // runs (no per-visitor cap to enforce) keep the plain unlocked insert.+ const newTopic = shareGate+ ? await reserveShareVisitorTopic(+ {+ agentId: resolvedAgentId,+ db: deps.db,+ expectedShareId: shareGate.shareId,+ ownerId: deps.userId,+ visitorUserId: shareGate.visitorUserId,+ workspaceId: deps.workspaceId,+ },+ newTopicParams,+ clientIds?.topicId,+ )+ : await deps.topicModel.create(newTopicParams, clientIds?.topicId);topicId = newTopic.id;log('execAgent: created new topic %s with trigger %s, groupId %s, cronJobId %s',@@ -440,6 +487,20 @@ export const setupTurn = async (// The pinned model lives in the top-level `topics.model`/`provider` columns// (config source of truth), NOT in metadata.const existingTopic = await deps.topicModel.findById(topicId);++ // Fail-closed guard: a non-share run must never operate on a share-visitor+ // topic. `findById` is ownership-scoped but deliberately does NOT exclude+ // visitor topics (see its JSDoc) — they carry the CREATOR's own userId for+ // billing attribution, so `deps.userId`'s ownership check alone lets a+ // creator-authenticated but non-share call (e.g. hitting `aiAgent.execAgent`+ // directly with a leaked/guessed visitor topicId) load a visitor+ // conversation as if it were their own. A share visitor's own run is+ // authorized separately via `shareGate` — already re-validated upstream by+ // `findVisitorTopicOrThrow` in `shareChat.ts` — and must keep working.+ if (!shareGate && existingTopic?.senderId) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });+ }+const pinnedModel = existingTopic?.model;if (pinnedModel) {model = modelOverride || pinnedModel;@@ -452,6 +513,15 @@ export const setupTurn = async (topicId,);}++ // Re-assert the share restriction after topic overrides are applied.+ // Heterogeneous agents are not available for shared visitor runs.+ if (shareGate && isHeterogeneousAgentModelId(model)) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: ChatErrorType.ShareHeterogeneousAgentUnsupported,+ });+ }}await throwIfExecutionAborted('topic setup');@@ -465,6 +535,7 @@ export const setupTurn = async (// chat) and stops the device list from leaking into the LLM context.const { canUseDevice, reason: deviceAccessReason } = resolveDeviceAccessPolicy({botContext,+ shareVisitor: !!shareGate,});log('execAgent: device access policy → canUseDevice=%s, reason=%s, hasBotContext=%s',@@ -538,26 +609,47 @@ export const setupTurn = async (return fallbackId;};const userMessageParentId = await resolveUserMessageParentId();+ const userMessageParams = {+ agentId: conversationAgentId,+ content: prompt,+ files: runAttachments.fileIds,+ // Group reads filter on messages.groupId (MessageModel.query group+ // branch), so a group turn must stamp groupId or the message never+ // shows when the topic is reopened (group topic sidebar + ownership fix).+ groupId: appContext?.groupId ?? undefined,+ metadata: requestTriggerMetadata,+ parentId: userMessageParentId,+ role: 'user' as const,+ threadId: appContext?.threadId ?? undefined,+ topicId,+ };+ // Share-visitor runs must reserve the `maxTurnsPerTopic` slot and insert+ // the user message in ONE locked transaction — see+ // `reserveShareVisitorTurn`'s JSDoc for the race this closes (same class of+ // count-then-act bug as the topic cap above). Harmless no-op on a topic+ // this same call just created (count is 0). Non-share runs (no per-turn+ // cap) keep the plain unlocked insert.const userMessageRecord = runFromHistory? undefined- : await deps.messageModel.create(- {- agentId: conversationAgentId,- content: prompt,- files: runAttachments.fileIds,- // Group reads filter on messages.groupId (MessageModel.query group- // branch), so a group turn must stamp groupId or the message never- // shows when the topic is reopened (group topic sidebar + ownership fix).- groupId: appContext?.groupId ?? undefined,- metadata: requestTriggerMetadata,- parentId: userMessageParentId,- role: 'user',- threadId: appContext?.threadId ?? undefined,- topicId,- },- // The id the client's optimistic user row already renders under.- clientIds?.userMessageId,- );+ : shareGate+ ? await reserveShareVisitorTurn(+ {+ agentId: shareGate.agentId,+ db: deps.db,+ expectedShareId: shareGate.shareId,+ ownerId: deps.userId,+ topicId,+ workspaceId: deps.workspaceId,+ },+ userMessageParams,+ // The id the client's optimistic user row already renders under.+ clientIds?.userMessageId,+ )+ : await deps.messageModel.create(+ userMessageParams,+ // The id the client's optimistic user row already renders under.+ clientIds?.userMessageId,+ );if (userMessageRecord) {selfMessageIds.add(userMessageRecord.id);log('execAgent: created user message %s', userMessageRecord.id);@@ -634,9 +726,21 @@ export const setupTurn = async (// only applies to the server-side LLM pipeline, so it is intentionally NOT// enqueued for hetero runs (which hand off to an external CLI). Skip when this// invocation is itself an Agent Signal background run to avoid recursion.+ //+ // Share-visitor fail-closed gate — never enqueue this event for a+ // share-visitor turn. `enqueueAgentSignalSourceEvent` is always called with+ // `userId: deps.userId`, which is the share CREATOR (this service is+ // instantiated with `share.ownerId` for every visitor run — see+ // `shareChat.ts`), never `shareGate.visitorUserId`. The `agent.user.message`+ // event it produces feeds policies that can reach the `userMemory` action+ // and WRITE to the creator's memory. `allowReadMemory` only grants READING+ // the creator's memory through the visible memory tool, so this gate must+ // never be conditional on it: any share configuration would otherwise let a+ // link visitor mutate the creator's account via this out-of-band channel.if (userMessageRecord &&!isHeteroAgent &&+ !shareGate &&!shouldSuppressSignal({ appContext, slug: agentSlug ?? undefined })) {void enqueueAgentSignalSourceEvent(diff --git a/apps/server/src/services/aiAgent/shareGate.test.ts b/apps/server/src/services/aiAgent/shareGate.test.tsnew file mode 100644index 00000000000..d8c48fb85ca--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate.test.ts@@ -0,0 +1,798 @@+import {+ AgentDocumentsApiName,+ AgentDocumentsIdentifier,+} from '@lobechat/builtin-tool-agent-documents';+import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';+import { CalculatorIdentifier } from '@lobechat/builtin-tool-calculator';+import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';+import {+ KnowledgeBaseApiName,+ KnowledgeBaseIdentifier,+} from '@lobechat/builtin-tool-knowledge-base';+import {+ LobeAgentApiName,+ LobeAgentIdentifier,+ systemPromptWithoutSubAgent,+} from '@lobechat/builtin-tool-lobe-agent';+import { MemoryApiName, MemoryIdentifier } from '@lobechat/builtin-tool-memory';+import { TopicReferenceIdentifier } from '@lobechat/builtin-tool-topic-reference';+import {+ AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS,+ AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS,+ builtinTools,+} from '@lobechat/builtin-tools';+import { ToolNameResolver } from '@lobechat/context-engine';+import { describe, expect, it } from 'vitest';++import type { AgentShareGate, ShareGateToolSet } from './shareGate';+import {+ applyShareGateToAgentConfig,+ applyShareGateToToolSet,+ filterPluginsByShareGate,+ isShareBlockedBuiltinDispatch,+ isShareBlockedDataToolCall,+ shareGateGrantsCloudSandbox,+} from './shareGate';++const buildGate = (config: Partial<AgentShareGate['shareConfig']> = {}): AgentShareGate => ({+ agentId: 'agent-1',+ shareConfig: {+ maxTopicsPerVisitor: 5,+ maxTurnsPerTopic: 20,+ ...config,+ },+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+});++/**+ * Go through the REAL `ToolNameResolver` — the same class `shareGate.ts` and+ * `ToolsEngine` use — instead of hand-concatenating `identifier____apiName`.+ * A hand-built string only matches what the resolver actually produces when+ * neither segment needs normalizing; it silently diverges for a `type` other+ * than `builtin`/`default` (an extra `____<type>` segment) or for an+ * api/identifier name the resolver MD5-hashes (invalid characters, or long+ * enough to hit the provider name-length cap). Using the real resolver here+ * is what makes the MCP-manifest and long-name tests below fail against a+ * naive slice-based strip instead of staying false-green.+ */+const toolNameResolver = new ToolNameResolver();+const toolName = (identifier: string, apiName: string, type: string = 'builtin') =>+ toolNameResolver.generate(identifier, apiName, type);++/**+ * Build a tool set whose parallel structures (manifests, maps, id arrays and+ * the function-calling `tools` schema) are all consistent, so an assertion can+ * check that a strip touched EVERY structure rather than just the manifest.+ */+const buildToolSet = (+ entries: Array<{+ apis: Array<{ humanIntervention?: unknown; name: string }>;+ identifier: string;+ type?: string;+ }>,+): ShareGateToolSet => {+ const toolSet: ShareGateToolSet = {+ activatableToolIds: entries.map((entry) => entry.identifier),+ enabledToolIds: entries.map((entry) => entry.identifier),+ executorMap: {},+ manifestMap: {},+ sourceMap: {},+ tools: [],+ };++ for (const { apis, identifier, type = 'builtin' } of entries) {+ toolSet.manifestMap[identifier] = {+ api: apis.map((api) => ({+ description: api.name,+ humanIntervention: api.humanIntervention,+ name: api.name,+ parameters: { properties: {}, type: 'object' },+ })),+ identifier,+ type,+ } as any;+ toolSet.sourceMap[identifier] = 'builtin' as any;+ toolSet.executorMap[identifier] = {} as any;+ for (const api of apis) {+ toolSet.tools!.push({+ function: { name: toolName(identifier, api.name, type) },+ type: 'function',+ });+ }+ }++ return toolSet;+};++describe('filterPluginsByShareGate', () => {+ it('keeps only allowlisted plugin ids', () => {+ const gate = buildGate({+ toolGrants: [{ identifier: 'web-search' }, { identifier: 'mcp-github' }],+ });++ expect(filterPluginsByShareGate(['web-search', 'local-system', 'mcp-github'], gate)).toEqual([+ 'web-search',+ 'mcp-github',+ ]);+ });++ it('exposes no tools when the allowlist is missing or empty', () => {+ expect(filterPluginsByShareGate(['web-search'], buildGate())).toEqual([]);+ expect(filterPluginsByShareGate(['web-search'], buildGate({ toolGrants: [] }))).toEqual([]);+ });++ it('treats a per-API grant as candidacy for the whole identifier', () => {+ // Narrowing down to the specific granted API happens later, in+ // `applyShareGateToToolSet`, once the real manifest is known — this pass+ // only decides whether the identifier is a candidate at all.+ const gate = buildGate({+ toolGrants: [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }],+ });++ expect(filterPluginsByShareGate([LobeAgentIdentifier, 'mcp-github'], gate)).toEqual([+ LobeAgentIdentifier,+ ]);+ });+});++describe('applyShareGateToAgentConfig', () => {+ it('always strips files and knowledge bases', () => {+ const agentConfig = {+ files: [{ enabled: true, id: 'f1' }],+ knowledgeBases: [{ enabled: true, id: 'kb1' }],+ };++ applyShareGateToAgentConfig(agentConfig);++ expect(agentConfig.files).toEqual([]);+ expect(agentConfig.knowledgeBases).toEqual([]);+ });+});++describe('AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS', () => {+ it('only names identifiers that exist in the real builtin registry', () => {+ const registered = new Set(builtinTools.map((tool) => tool.identifier));++ for (const identifier of AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS) {+ expect(registered.has(identifier), `${identifier} is not a registered builtin`).toBe(true);+ }+ });++ it('does not allowlist the confirmed creator-data leak tools', () => {+ for (const identifier of [+ AgentManagementIdentifier,+ 'lobe-local-system',+ 'lobe-creds',+ 'lobe-task',+ TopicReferenceIdentifier,+ ]) {+ expect(AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS.has(identifier)).toBe(false);+ }+ });++ // `lobe-cloud-sandbox` is allowlisted despite its general-purpose reach: a+ // 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`.+ 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);+ });+});++/**+ * The owner-facing share settings tool picker renders this set as permanently+ * unavailable. If a grant here is ever relaxed server-side without updating+ * the exported set, the UI would start offering a toggle the gate still+ * ignores — so pin the two together.+ */+describe('AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS', () => {+ const maximalPermissions = { allowReadMemory: true, knowledgeBaseIds: ['kb1'] };++ it('names only allowlisted identifiers', () => {+ for (const identifier of AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS) {+ expect(AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS.has(identifier)).toBe(true);+ }+ });++ it('matches exactly the allowlisted identifiers blocked under maximal permissions', () => {+ // `readOnlyApiName` stands in for any API: an unconditional `none` grant+ // blocks the identifier before the per-API rules are ever consulted.+ const blockedUnderMaximalPermissions = [...AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS].filter(+ (identifier) => isShareBlockedDataToolCall(maximalPermissions, identifier, 'readOnlyApiName'),+ );++ expect(new Set(blockedUnderMaximalPermissions)).toEqual(+ AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS,+ );+ });++ it('excludes memory, whose grant is conditional on allowReadMemory', () => {+ expect(AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS.has(MemoryIdentifier)).toBe(false);+ });+});++describe('isShareBlockedDataToolCall', () => {+ it('lets non-builtin identifiers through untouched', () => {+ expect(isShareBlockedDataToolCall({}, 'mcp-github', 'anything')).toBe(false);+ });++ it('default-denies any builtin outside the allowlist', () => {+ expect(isShareBlockedDataToolCall({}, AgentManagementIdentifier, 'searchAgent')).toBe(true);+ });++ it('allows an allowlisted builtin with no data rule', () => {+ expect(isShareBlockedDataToolCall({}, CalculatorIdentifier, 'calculate')).toBe(false);+ });++ describe('memory', () => {+ it('blocks every api without allowReadMemory', () => {+ expect(isShareBlockedDataToolCall({}, MemoryIdentifier, MemoryApiName.searchUserMemory)).toBe(+ true,+ );+ });++ it('allows reads but never writes with allowReadMemory', () => {+ const permissions = { allowReadMemory: true };++ expect(+ isShareBlockedDataToolCall(permissions, MemoryIdentifier, MemoryApiName.searchUserMemory),+ ).toBe(false);+ expect(+ isShareBlockedDataToolCall(permissions, MemoryIdentifier, MemoryApiName.addContextMemory),+ ).toBe(true);+ });+ });++ it('blocks agent documents and knowledge base outright (no grant exists)', () => {+ expect(+ isShareBlockedDataToolCall(+ { allowReadMemory: true },+ AgentDocumentsIdentifier,+ AgentDocumentsApiName.listDocuments,+ ),+ ).toBe(true);+ expect(+ isShareBlockedDataToolCall(+ { allowReadMemory: true, knowledgeBaseIds: ['kb1'] },+ KnowledgeBaseIdentifier,+ KnowledgeBaseApiName.viewKnowledgeBase,+ { id: 'kb1' },+ ),+ ).toBe(true);+ });+});++describe('applyShareGateToToolSet', () => {+ it('drops everything the owner picker did not enable', () => {+ const toolSet = buildToolSet([+ { apis: [{ name: 'calculate' }], identifier: CalculatorIdentifier },+ { apis: [{ name: 'searchAgent' }], identifier: AgentManagementIdentifier },+ ]);++ applyShareGateToToolSet(+ toolSet,+ buildGate({ toolGrants: [{ identifier: CalculatorIdentifier }] }),+ );++ expect(toolSet.enabledToolIds).toEqual([CalculatorIdentifier]);+ expect(toolSet.activatableToolIds).toEqual([CalculatorIdentifier]);+ expect(Object.keys(toolSet.manifestMap)).toEqual([CalculatorIdentifier]);+ expect(Object.keys(toolSet.sourceMap)).toEqual([CalculatorIdentifier]);+ expect(Object.keys(toolSet.executorMap)).toEqual([CalculatorIdentifier]);+ expect(toolSet.tools).toHaveLength(1);+ });++ it('drops a builtin the owner enabled but the master allowlist denies', () => {+ const toolSet = buildToolSet([+ { apis: [{ name: 'searchAgent' }], identifier: AgentManagementIdentifier },+ ]);++ applyShareGateToToolSet(+ toolSet,+ buildGate({ toolGrants: [{ identifier: AgentManagementIdentifier }] }),+ );++ expect(toolSet.enabledToolIds).toEqual([]);+ expect(toolSet.manifestMap).toEqual({});+ expect(toolSet.tools).toEqual([]);+ });++ it('drops a stale lobe-topic-reference grant left over from before it was denied', () => {+ // `TopicReferenceExecutionRuntime.getTopicContext` resolves a free-form+ // topicId via `TopicModel.findOwnTopicById`, scoped only to the creator's+ // whole store — not to this share/agent. A share config saved while it was+ // still allowlisted could still carry it in `toolGrants`; the gate must+ // keep dropping it rather than newly trusting the stored config.+ const toolSet = buildToolSet([+ { apis: [{ name: 'getTopicContext' }], identifier: TopicReferenceIdentifier },+ ]);++ applyShareGateToToolSet(+ toolSet,+ buildGate({ toolGrants: [{ identifier: TopicReferenceIdentifier }] }),+ );++ expect(toolSet.enabledToolIds).toEqual([]);+ expect(toolSet.manifestMap).toEqual({});+ expect(toolSet.tools).toEqual([]);+ });++ it('keeps a non-builtin plugin the owner enabled', () => {+ const toolSet = buildToolSet([{ apis: [{ name: 'run' }], identifier: 'mcp-github' }]);++ applyShareGateToToolSet(toolSet, buildGate({ toolGrants: [{ identifier: 'mcp-github' }] }));++ expect(toolSet.enabledToolIds).toEqual(['mcp-github']);+ });++ it('collapses the whole set when no tools are enabled', () => {+ const toolSet = buildToolSet([+ { apis: [{ name: 'calculate' }], identifier: CalculatorIdentifier },+ ]);++ applyShareGateToToolSet(toolSet, buildGate());++ expect(toolSet.enabledToolIds).toEqual([]);+ expect(toolSet.tools).toEqual([]);+ });++ it('narrows a per-API grant down to just the named API', () => {+ const toolSet = buildToolSet([+ {+ apis: [{ name: LobeAgentApiName.analyzeMedia }, { name: LobeAgentApiName.updatePlan }],+ identifier: LobeAgentIdentifier,+ },+ ]);++ applyShareGateToToolSet(+ toolSet,+ buildGate({+ toolGrants: [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }],+ }),+ );++ // The identifier itself stays enabled (it has a surviving API)...+ expect(toolSet.enabledToolIds).toEqual([LobeAgentIdentifier]);+ // ...but only the granted API remains on the manifest and the+ // function-calling schema.+ expect(toolSet.manifestMap[LobeAgentIdentifier].api.map((api) => api.name)).toEqual([+ LobeAgentApiName.analyzeMedia,+ ]);+ expect(toolSet.tools!.map((tool: any) => tool.function.name)).toEqual([+ toolName(LobeAgentIdentifier, LobeAgentApiName.analyzeMedia),+ ]);+ });++ it('drops the whole tool when a per-API grant names no surviving API', () => {+ const toolSet = buildToolSet([+ { apis: [{ name: LobeAgentApiName.analyzeMedia }], identifier: LobeAgentIdentifier },+ ]);++ // Granted API name does not exist on this manifest at all (e.g. stale+ // config from a renamed API) — zero APIs survive, so the identifier is+ // dropped entirely rather than left offering nothing.+ applyShareGateToToolSet(+ toolSet,+ buildGate({ toolGrants: [{ apis: ['noSuchApi'], identifier: LobeAgentIdentifier }] }),+ );++ expect(toolSet.enabledToolIds).toEqual([]);+ expect(toolSet.manifestMap).toEqual({});+ expect(toolSet.tools).toEqual([]);+ });++ it('lets a toolset-level entry grant every surviving API, overriding a redundant per-API entry', () => {+ const toolSet = buildToolSet([+ {+ apis: [{ name: LobeAgentApiName.analyzeMedia }, { name: LobeAgentApiName.updatePlan }],+ identifier: LobeAgentIdentifier,+ },+ ]);++ applyShareGateToToolSet(+ toolSet,+ buildGate({+ toolGrants: [+ { identifier: LobeAgentIdentifier },+ { apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier },+ ],+ }),+ );++ expect(toolSet.manifestMap[LobeAgentIdentifier].api.map((api) => api.name).sort()).toEqual(+ [LobeAgentApiName.analyzeMedia, LobeAgentApiName.updatePlan].sort(),+ );+ });++ it('strips callSubAgent and pins the dispatch-free systemRole', () => {+ const toolSet = buildToolSet([+ {+ apis: [{ name: LobeAgentApiName.callSubAgent }, { name: LobeAgentApiName.analyzeMedia }],+ identifier: LobeAgentIdentifier,+ },+ ]);++ applyShareGateToToolSet(+ toolSet,+ buildGate({ toolGrants: [{ identifier: LobeAgentIdentifier }] }),+ );++ const manifest = toolSet.manifestMap[LobeAgentIdentifier];+ expect(manifest.api.map((api) => api.name)).not.toContain(LobeAgentApiName.callSubAgent);+ expect(manifest.systemRole).toBe(systemPromptWithoutSubAgent);+ expect(toolSet.tools!.map((tool: any) => tool.function.name)).not.toContain(+ toolName(LobeAgentIdentifier, LobeAgentApiName.callSubAgent),+ );+ });++ it('drops a memory tool without allowReadMemory and strips its writes with it', () => {+ const build = () =>+ buildToolSet([+ {+ apis: [+ { name: MemoryApiName.searchUserMemory },+ { name: MemoryApiName.addContextMemory },+ ],+ identifier: MemoryIdentifier,+ },+ ]);++ const denied = build();+ applyShareGateToToolSet(denied, buildGate({ toolGrants: [{ identifier: MemoryIdentifier }] }));+ expect(denied.manifestMap[MemoryIdentifier]).toBeUndefined();+ expect(denied.enabledToolIds).toEqual([]);++ const granted = build();+ applyShareGateToToolSet(+ granted,+ buildGate({ allowReadMemory: true, toolGrants: [{ identifier: MemoryIdentifier }] }),+ );+ expect(granted.manifestMap[MemoryIdentifier].api.map((api) => api.name)).toEqual([+ MemoryApiName.searchUserMemory,+ ]);+ expect(granted.tools!.map((tool: any) => tool.function.name)).toEqual([+ toolName(MemoryIdentifier, MemoryApiName.searchUserMemory),+ ]);+ });++ it('strips apis whose humanIntervention can never resolve under reject mode', () => {+ const toolSet = buildToolSet([+ {+ apis: [+ { name: 'safe' },+ { humanIntervention: 'never', name: 'explicitlySafe' },+ { humanIntervention: 'required', name: 'needsApproval' },+ { humanIntervention: 'always', name: 'alwaysAsks' },+ { humanIntervention: { type: 'dynamic' }, name: 'maybeAsks' },+ ],+ 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(+ toolSet,+ buildGate({ toolGrants: [{ identifier: CalculatorIdentifier }] }),+ );++ expect(toolSet.manifestMap[CalculatorIdentifier]).toBeUndefined();+ expect(toolSet.enabledToolIds).toEqual([]);+ });++ it('strips a required-intervention API from a non-builtin (MCP/connector) manifest, keeping its normal APIs', () => {+ // 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.+ const toolSet = buildToolSet([+ {+ apis: [{ name: 'listRepos' }, { humanIntervention: 'required', name: 'deleteRepo' }],+ identifier: 'mcp-github',+ type: 'mcp',+ },+ ]);++ 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.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', () => {+ const toolSet = buildToolSet([+ {+ apis: [{ name: 'listRepos' }, { name: 'deleteRepo' }],+ identifier: 'mcp-github',+ type: 'mcp',+ },+ ]);++ // The grant in `shareConfig.toolGrants` names the RAW api name, independent+ // of whatever `ToolNameResolver.generate` does for the WIRE tool-call name+ // — the third `____mcp` segment only ever appears on the generated+ // dispatch name asserted below, never on the grant itself.+ applyShareGateToToolSet(+ toolSet,+ buildGate({ toolGrants: [{ apis: ['listRepos'], identifier: 'mcp-github' }] }),+ );++ expect(toolSet.manifestMap['mcp-github'].api.map((api) => api.name)).toEqual(['listRepos']);+ expect(toolSet.tools!.map((tool: any) => tool.function.name)).toEqual([+ toolName('mcp-github', 'listRepos', 'mcp'),+ ]);+ });++ it('narrows a per-API grant on an MCP manifest whose blocked API name is long/non-ASCII enough to be MD5-hashed', () => {+ // `ToolNameResolver.generate` hashes the API segment once the raw name+ // would push the generated tool-call name past the provider length cap,+ // and hashes on invalid characters regardless of length — both common+ // for server-controlled MCP API names, unlike a builtin's small fixed+ // API surface. A strip that slices `identifier.length + SEPARATOR.length`+ // off the generated name (instead of regenerating it) would recover+ // garbage here and fail to match either API, leaving the blocked one+ // reachable.+ const longApiName = 'a'.repeat(80);+ const nonAsciiApiName = '删除仓库';+ const toolSet = buildToolSet([+ {+ apis: [{ name: longApiName }, { name: nonAsciiApiName }],+ identifier: 'mcp-github',+ type: 'mcp',+ },+ ]);++ applyShareGateToToolSet(+ toolSet,+ buildGate({ toolGrants: [{ apis: [longApiName], identifier: 'mcp-github' }] }),+ );++ expect(toolSet.manifestMap['mcp-github'].api.map((api) => api.name)).toEqual([longApiName]);+ expect(toolSet.tools!.map((tool: any) => tool.function.name)).toEqual([+ toolName('mcp-github', longApiName, 'mcp'),+ ]);+ expect(toolSet.tools!.map((tool: any) => tool.function.name)).not.toContain(+ toolName('mcp-github', nonAsciiApiName, 'mcp'),+ );+ });++ // `ToolNameResolver.generate` hashes the IDENTIFIER segment too — on+ // invalid characters unconditionally, and on length once the api segment+ // alone is not enough to fit under the cap. A prune that decides "belongs+ // to this identifier" by comparing the generated name's first segment+ // against the raw identifier never matches such a tool and silently keeps+ // every entry — failing OPEN for exactly the MCP connectors whose+ // identifiers are server-supplied and unconstrained.+ it('narrows a per-API grant on an MCP manifest whose IDENTIFIER is non-ASCII and therefore MD5-hashed', () => {+ const identifier = '中文连接器';+ const toolSet = buildToolSet([+ { apis: [{ name: 'listRepos' }, { name: 'deleteRepo' }], identifier, type: 'mcp' },+ ]);++ // Sanity: the generated name must NOT start with the literal identifier,+ // otherwise this test would not exercise the hashed path.+ expect(toolName(identifier, 'listRepos', 'mcp').startsWith(identifier)).toBe(false);++ applyShareGateToToolSet(+ toolSet,+ buildGate({ toolGrants: [{ apis: ['listRepos'], identifier }] }),+ );++ expect(toolSet.manifestMap[identifier].api.map((api) => api.name)).toEqual(['listRepos']);+ expect(toolSet.tools!.map((tool: any) => tool.function.name)).toEqual([+ toolName(identifier, 'listRepos', 'mcp'),+ ]);+ });++ it('narrows a per-API grant on an MCP manifest whose IDENTIFIER is long enough to be MD5-hashed', () => {+ const identifier = 'x'.repeat(70);+ const apiName = 'y'.repeat(20);+ const toolSet = buildToolSet([+ { apis: [{ name: apiName }, { name: 'deleteRepo' }], identifier, type: 'mcp' },+ ]);++ expect(toolName(identifier, apiName, 'mcp').startsWith(identifier)).toBe(false);++ applyShareGateToToolSet(toolSet, buildGate({ toolGrants: [{ apis: [apiName], identifier }] }));++ expect(toolSet.manifestMap[identifier].api.map((api) => api.name)).toEqual([apiName]);+ expect(toolSet.tools!.map((tool: any) => tool.function.name)).toEqual([+ toolName(identifier, apiName, 'mcp'),+ ]);+ });++ it('drops an MCP tool entirely (dropToolFromSet) even when its IDENTIFIER segment is MD5-hashed', () => {+ const identifier = '中文连接器';+ const toolSet = buildToolSet([+ { apis: [{ name: 'listRepos' }], identifier, type: 'mcp' },+ { apis: [{ name: 'listRepos' }], identifier: 'mcp-gitlab', type: 'mcp' },+ ]);++ applyShareGateToToolSet(toolSet, buildGate({ toolGrants: [{ identifier: 'mcp-gitlab' }] }));++ expect(toolSet.manifestMap[identifier]).toBeUndefined();+ expect(toolSet.tools!.map((tool: any) => tool.function.name)).toEqual([+ toolName('mcp-gitlab', 'listRepos', 'mcp'),+ ]);+ });++ it('drops an MCP tool identifier entirely (dropToolFromSet) without leaving stray generated-name entries behind', () => {+ const toolSet = buildToolSet([+ { apis: [{ name: 'listRepos' }], identifier: 'mcp-github', type: 'mcp' },+ { apis: [{ name: 'listRepos' }], identifier: 'mcp-gitlab', type: 'mcp' },+ ]);++ // `mcp-github` gets no grant at all; `mcp-gitlab` does, and must survive+ // untouched — proves `dropToolFromSet`'s identifier-prefix match isn't+ // accidentally over- or under-matching once a third `____mcp` segment is+ // in play.+ applyShareGateToToolSet(toolSet, buildGate({ toolGrants: [{ identifier: 'mcp-gitlab' }] }));++ expect(toolSet.manifestMap['mcp-github']).toBeUndefined();+ expect(toolSet.manifestMap['mcp-gitlab']).toBeDefined();+ expect(toolSet.tools!.map((tool: any) => tool.function.name)).toEqual([+ toolName('mcp-gitlab', 'listRepos', 'mcp'),+ ]);+ });+});++// 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.+describe('isShareBlockedBuiltinDispatch', () => {+ it('blocks an allowlisted builtin the owner did not enable', () => {+ expect(isShareBlockedBuiltinDispatch({}, CalculatorIdentifier, 'evalExpression')).toBe(true);+ });++ it('passes an enabled builtin with no intervention semantics', () => {+ expect(+ isShareBlockedBuiltinDispatch(+ { toolGrants: [{ identifier: LobeAgentIdentifier }] },+ LobeAgentIdentifier,+ LobeAgentApiName.analyzeMedia,+ ),+ ).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.+ for (const apiName of [LobeAgentApiName.createPlan, LobeAgentApiName.askUserQuestion]) {+ expect(+ isShareBlockedBuiltinDispatch(+ { toolGrants: [{ identifier: LobeAgentIdentifier }] },+ LobeAgentIdentifier,+ apiName,+ ),+ ).toBe(true);+ }+ });++ 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+ // spawns does not inherit the parent's shareGate. Must be blocked by its+ // dedicated dispatch rule.+ expect(+ isShareBlockedBuiltinDispatch(+ { toolGrants: [{ identifier: LobeAgentIdentifier }] },+ LobeAgentIdentifier,+ LobeAgentApiName.callSubAgent,+ ),+ ).toBe(true);+ });++ it('still applies the data-tool rules after the enable check', () => {+ const enabled = { toolGrants: [{ identifier: MemoryIdentifier }] };++ expect(+ isShareBlockedBuiltinDispatch(enabled, MemoryIdentifier, MemoryApiName.searchUserMemory),+ ).toBe(true);+ expect(+ isShareBlockedBuiltinDispatch(+ { ...enabled, allowReadMemory: true },+ MemoryIdentifier,+ MemoryApiName.searchUserMemory,+ ),+ ).toBe(false);+ expect(+ isShareBlockedBuiltinDispatch(+ { ...enabled, allowReadMemory: true },+ MemoryIdentifier,+ MemoryApiName.addContextMemory,+ ),+ ).toBe(true);+ });++ it('ignores non-builtin identifiers entirely', () => {+ expect(isShareBlockedBuiltinDispatch({}, 'some-mcp-server', 'anything')).toBe(false);+ });++ it('blocks a builtin outside the master allowlist regardless of enablement', () => {+ expect(+ isShareBlockedBuiltinDispatch(+ { toolGrants: [{ identifier: AgentManagementIdentifier }] },+ AgentManagementIdentifier,+ 'searchAgent',+ ),+ ).toBe(true);+ });++ it('a per-API grant grants only the named API, not the whole identifier', () => {+ const enabled = {+ toolGrants: [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }],+ };++ expect(+ isShareBlockedBuiltinDispatch(enabled, LobeAgentIdentifier, LobeAgentApiName.analyzeMedia),+ ).toBe(false);+ // updatePlan carries no intervention config either, so only the picker's+ // per-API scoping is what blocks it here.+ expect(+ isShareBlockedBuiltinDispatch(enabled, LobeAgentIdentifier, LobeAgentApiName.updatePlan),+ ).toBe(true);+ });+});++describe('shareGateGrantsCloudSandbox', () => {+ it('is false when the share does not grant lobe-cloud-sandbox', () => {+ expect(shareGateGrantsCloudSandbox(buildGate())).toBe(false);+ expect(+ shareGateGrantsCloudSandbox(buildGate({ toolGrants: [{ identifier: 'web-search' }] })),+ ).toBe(false);+ });++ it('is true for a whole-identifier grant', () => {+ expect(+ shareGateGrantsCloudSandbox(+ buildGate({ toolGrants: [{ identifier: CloudSandboxManifest.identifier }] }),+ ),+ ).toBe(true);+ });++ // The plan only needs to know the sandbox is in play at all — narrowing to+ // the granted APIs happens later in `applyShareGateToToolSet`.+ it('treats an apis-scoped grant as a grant of the identifier', () => {+ expect(+ shareGateGrantsCloudSandbox(+ buildGate({+ toolGrants: [{ apis: ['runCommand'], identifier: CloudSandboxManifest.identifier }],+ }),+ ),+ ).toBe(true);+ });+});diff --git a/apps/server/src/services/aiAgent/shareGate.ts b/apps/server/src/services/aiAgent/shareGate.tsnew file mode 100644index 00000000000..7b032e68e0e--- /dev/null+++ b/apps/server/src/services/aiAgent/shareGate.ts@@ -0,0 +1,945 @@+import {+ AgentDocumentsApiName,+ AgentDocumentsIdentifier,+} from '@lobechat/builtin-tool-agent-documents';+import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';+import {+ KnowledgeBaseApiName,+ KnowledgeBaseIdentifier,+} from '@lobechat/builtin-tool-knowledge-base';+import {+ LobeAgentApiName,+ LobeAgentIdentifier,+ systemPromptWithoutSubAgent,+} from '@lobechat/builtin-tool-lobe-agent';+import { MEMORY_WRITE_API_NAMES, MemoryIdentifier } from '@lobechat/builtin-tool-memory';+import {+ AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS,+ builtinTools,+ isBuiltinToolIdentifier,+} from '@lobechat/builtin-tools';+import {+ hasShareToolGrant,+ isShareToolApiGranted,+ PLUGIN_SCHEMA_SEPARATOR,+ resolveShareToolGrants,+ type ShareToolGrant,+} from '@lobechat/const';+import type { LobeToolManifest, ToolExecutor, ToolSource } from '@lobechat/context-engine';+import { ToolNameResolver } from '@lobechat/context-engine';+import type { AgentShareToolGrant } from '@lobechat/types';++import type { AgentShareConfig } from '@/database/schemas';++/**+ * Single shared resolver instance for regenerating function-calling names+ * from a manifest's identifier/api/type — same class `ToolsEngine` used to+ * build `toolSet.tools` in the first place. Stateless (no per-call config),+ * so one instance is safe to reuse across every gate pass.+ */+const toolNameResolver = new ToolNameResolver();++/**+ * Server-side gate for shared-agent visitor conversations.+ *+ * Built exclusively by the shareChat router after the share access check —+ * never from client input. The gate is applied at operation-build time inside+ * `AiAgentService.execAgent`, so the restricted tool/memory/file surface is+ * snapshotted into the operation state and every later step inherits it+ * without the context engine knowing about shares.+ */+export interface AgentShareGate {+ agentId: string;+ shareConfig: AgentShareConfig;+ /**+ * The `agentShares.id` this run was authorized against — read together with+ * `shareConfig` in the SAME `AgentShareModel.findByShareIdWithAccessCheck`+ * call.+ *+ * "The share row for this agent still exists AND its id still equals+ * `shareId` AND its visibility is still `link`" is exactly the condition+ * "this run's authorization has not been revoked". Every re-validation in+ * the visitor chain (`shareVisitorAbuseGuards`, the per-step runtime+ * re-check) is that one comparison.+ *+ * The visibility half carries the ordinary case: turning sharing off flips+ * the row to `private` and keeps it, so the owner can resume the same link+ * later (`AgentShareModel.updateVisibility`). The id half covers a row that+ * genuinely went away and came back as a different instance — a hard delete+ * (`AgentShareModel.deleteByAgentId`) or an agent delete + recreate.+ */+ shareId: string;+ /**+ * The signed-in visitor driving this run. Recorded on `topics.senderId` and+ * spend-log metadata; the run itself executes as the creator.+ */+ visitorUserId: string;+}++/**+ * Intersect a run's candidate plugin/skill ids with the share whitelist.+ * The whitelist defaults to empty, so an unconfigured share exposes no tools.+ *+ * Identifier-level only: an entry granting just one API+ * (`{ identifier: 'lobe-agent', apis: ['analyzeMedia'] }`) still counts as+ * "this identifier is a+ * candidate" here — narrowing the offer down to that specific API happens+ * later, in {@link applyShareGateToToolSet}, once the real manifest is known.+ */+export const filterPluginsByShareGate = (pluginIds: string[], gate: AgentShareGate): string[] => {+ const grants = resolveShareToolGrants(gate.shareConfig.toolGrants);++ return pluginIds.filter((id) => hasShareToolGrant(grants, id));+};++/**+ * Whether the share grants `lobe-cloud-sandbox` (at any API scope). Drives+ * `resolveExecutionPlan`'s `sandboxFallback`: a visitor can never reach the+ * creator's device, so this grant is only meaningful if the plan resolves to+ * the sandbox instead of collapsing to `none`.+ */+export const shareGateGrantsCloudSandbox = (gate: AgentShareGate): boolean =>+ hasShareToolGrant(+ resolveShareToolGrants(gate.shareConfig.toolGrants),+ CloudSandboxManifest.identifier,+ );++/**+ * Strip agent files / knowledge bases from a share visitor's resolved agent+ * config. Mutates in place — `agentConfig` is threaded through the whole+ * orchestration by reference (tool discovery, knowledge flags, context builder+ * snapshot), so a filtered copy would silently diverge.+ *+ * ADAPTATION vs the original design: the share config no longer carries a+ * `filePermissionConfig` field, so there is no grant a creator could set that+ * would expose their agent files or knowledge bases to a visitor. The gate is+ * therefore unconditional rather than conditional — the fail-closed reading of+ * "no configured permission". Re-introducing a file grant means restoring the+ * config field AND relaxing this function together.+ */+export const applyShareGateToAgentConfig = (agentConfig: {+ files?: unknown[] | null;+ knowledgeBases?: unknown[] | null;+}): void => {+ agentConfig.files = [];+ agentConfig.knowledgeBases = [];+};++/**+ * Minimal shape a `DataToolAccessRule.grant` needs — either the full share+ * gate's `shareConfig`, or the trimmed `agentShare` marker threaded through+ * `RuntimeExecutorContext` / `ToolExecutionContext` for tool calls resolved+ * outside this module (see {@link isShareBlockedDataToolCall}).+ */+export interface ShareDataToolPermissions {+ allowReadMemory?: boolean;+ /**+ * Agent's own persisted, `enabled` knowledge-base ids (never+ * visitor-supplied). Currently always empty for a share run — see+ * {@link applyShareGateToAgentConfig} — but kept so the id-scoping rule+ * below stays wired should a knowledge-base grant return.+ */+ knowledgeBaseIds?: string[];+}++/**+ * See `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS`'s JSDoc in+ * `@lobechat/builtin-tools` for the full per-identifier evidence. Aliased here+ * so the two enforcement points below read as one local rule.+ */+const SHARE_VISITOR_ALLOWED_IDENTIFIERS = AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS;++/**+ * Whether `identifier` belongs to the population this allowlist governs — the+ * real builtin tool registry (`@lobechat/builtin-tools`), the same source+ * `BuiltinToolsExecutor`/`hasServerRuntime` resolve against. MCP servers,+ * market plugins, and custom plugins never appear in this registry, so they+ * fall outside this allowlist's jurisdiction entirely and are left to+ * {@link filterPluginsByShareGate} / `shareConfig.toolGrants` — the+ * pre-existing (and unaffected) gate for that population.+ */+const isGovernedByBuiltinAllowlist = isBuiltinToolIdentifier;++type DataToolGrant = 'none' | 'read';++/**+ * Read/write surface of a builtin tool whose APIs act directly on the+ * creator's private data store (memory, knowledge bases, agent documents).+ *+ * These tools are gated by three independent axes: whether the share grants+ * ANY access at all (`grant`) — share grants are `none` | `read` only, there+ * is no write grant to honor; whether a given API is a write regardless of+ * grant (`writeApiNames`); and whether a "read" API can even be scoped to what+ * the share actually grants at all (`alwaysBlockedApiNames`,+ * `isArgsOutOfScope`) — some reads act on the caller's ENTIRE personal data+ * store with no id parameter tying them to the agent's own assignment, so a+ * `read` grant must not enable them.+ */+interface DataToolAccessRule {+ /**+ * API names that read across the creator's whole personal store+ * (independent of what this specific agent is assigned) with no id argument+ * that could scope the call. Always blocked for a share visitor, even when+ * `grant` is `read` — unlike `writeApiNames`, these ARE reads, but a read+ * grant only ever means "read what this agent is assigned," never "read+ * everything the creator owns."+ */+ alwaysBlockedApiNames?: string[];+ /** Resolve this share's grant for the tool from its permission fields. */+ grant: (permissions: ShareDataToolPermissions) => DataToolGrant;+ /**+ * For an API that DOES take an id scoping it to a specific resource (e.g.+ * `viewKnowledgeBase`'s `id`): whether the id(s) `args` references fall+ * outside what this share's permissions actually allow. Must fail closed —+ * an id that cannot be verified (missing, wrong type, or the allowlist+ * itself is empty/absent) is out of scope.+ */+ isArgsOutOfScope?: (permissions: ShareDataToolPermissions, apiName: string, args: any) => boolean;+ /** API names that mutate creator data; stripped/blocked unconditionally. */+ writeApiNames: string[];+}++/**+ * Registry of data-bearing builtin tools a share visitor can be whitelisted+ * into (`shareConfig.toolGrants`) without the whitelist itself implying+ * read OR write access to the underlying store. `filterPluginsByShareGate` /+ * `applyShareGateToToolSet`'s allowlist intersection only answers "is this+ * tool id enabled for the share" — it says nothing about `allowReadMemory`,+ * which is why a whitelisted memory/knowledge-base/agent-documents tool would+ * otherwise execute read-write under the creator's own permissions no matter+ * what the share granted.+ *+ * Adding a new write API to one of these packages must add it here too —+ * `shareGate.test.ts` asserts against the REAL exported manifests, so a rename+ * or omission fails that test instead of silently reopening the hole.+ */+const DATA_TOOL_ACCESS_RULES: Record<string, DataToolAccessRule> = {+ [AgentDocumentsIdentifier]: {+ // No file grant exists in the current `AgentShareConfig` — see+ // `applyShareGateToAgentConfig`'s adaptation note. Fail closed rather than+ // silently defaulting the missing grant to `read`.+ grant: () => 'none',+ writeApiNames: [+ AgentDocumentsApiName.createDocument,+ AgentDocumentsApiName.copyDocument,+ AgentDocumentsApiName.modifyNodes,+ AgentDocumentsApiName.removeDocument,+ AgentDocumentsApiName.renameDocument,+ AgentDocumentsApiName.replaceDocumentContent,+ AgentDocumentsApiName.updateLoadRule,+ ],+ },+ [KnowledgeBaseIdentifier]: {+ // `listFiles` / `getFileDetail` browse the creator's whole resource+ // library (files not yet in any knowledge base) — that library has no+ // per-agent assignment concept at all, so no grant can scope it to "what+ // this agent is assigned." `listKnowledgeBases` lists every knowledge base+ // the creator owns, not just the ones mounted on this agent, and takes no+ // id to scope it either. `readKnowledge` accepts arbitrary+ // `file_*`/`docs_*` ids read straight from the creator's file/document+ // store with no knowledge-base-membership check of its own. Blocking them+ // is the fail-closed choice: `searchKnowledgeBase` (already agent/task-id+ // scoped server-side) still returns real chunk/document text, so a `read`+ // grant would remain useful without this hole.+ alwaysBlockedApiNames: [+ KnowledgeBaseApiName.listFiles,+ KnowledgeBaseApiName.getFileDetail,+ KnowledgeBaseApiName.listKnowledgeBases,+ KnowledgeBaseApiName.readKnowledge,+ ],+ // Same adaptation as `AgentDocumentsIdentifier` above: no knowledge-base+ // grant exists in the current `AgentShareConfig`.+ grant: () => 'none',+ // `viewKnowledgeBase` DOES take an `id`, and the agent's own assignment+ // would be known (`ShareDataToolPermissions.knowledgeBaseIds`) — kept+ // wired so restoring a knowledge-base grant only needs the `grant` line+ // above changed, not this scoping rule re-derived.+ isArgsOutOfScope: (permissions, apiName, args) => {+ if (apiName !== KnowledgeBaseApiName.viewKnowledgeBase) return false;+ const id = args?.id;+ if (typeof id !== 'string' || !id) return true;+ const allowed = permissions.knowledgeBaseIds;+ return !allowed || !allowed.includes(id);+ },+ writeApiNames: [+ KnowledgeBaseApiName.createKnowledgeBase,+ KnowledgeBaseApiName.deleteKnowledgeBase,+ KnowledgeBaseApiName.createDocument,+ KnowledgeBaseApiName.addFiles,+ KnowledgeBaseApiName.removeFiles,+ ],+ },+ [MemoryIdentifier]: {+ grant: (permissions) => (permissions.allowReadMemory ? 'read' : 'none'),+ // Shared with the share settings picker so the owner is never offered a+ // write API the gate strips anyway.+ writeApiNames: [...MEMORY_WRITE_API_NAMES],+ },+};++/**+ * Whether a specific `identifier`/`apiName` tool call must be blocked for a+ * share visitor run. This is the enforcement counterpart of+ * `applyShareGateToDataToolAccess` below, reusable from the actual dispatch+ * chokepoint (`BuiltinToolsExecutor.execute`, which invokes+ * `runtime[apiName](...)` directly and never re-consults the possibly+ * already-trimmed manifest — the trimmed manifest only changes what the model+ * is OFFERED via function-calling schema, not what the executor is willing to+ * run if the model calls it anyway).+ *+ * DEFAULT-DENY for the builtin population: an `identifier` that resolves+ * against the real `@lobechat/builtin-tools` registry+ * (`isGovernedByBuiltinAllowlist`) but is NOT in+ * `SHARE_VISITOR_ALLOWED_IDENTIFIERS` is blocked outright, with no+ * `apiName`-level distinction. A non-builtin identifier (MCP server, market+ * plugin, custom plugin) is NOT this function's concern at all — it falls+ * through to `false` untouched, left entirely to+ * {@link filterPluginsByShareGate} / `shareConfig.toolGrants`.+ *+ * `args` is the tool call's parsed arguments, needed only for+ * `isArgsOutOfScope` rules. Omit it for call sites that only need the+ * identifier/apiName-level check (grant / write / always-blocked).+ */+export const isShareBlockedDataToolCall = (+ permissions: ShareDataToolPermissions,+ identifier: string,+ apiName: string,+ args?: any,+): boolean => {+ // Outside this gate's jurisdiction entirely — MCP/market/custom plugin+ // identifiers are governed by the toolGrants picker, not this allowlist.+ if (!isGovernedByBuiltinAllowlist(identifier)) return false;++ // Default-deny: a known builtin identifier not on the allowlist is blocked+ // unconditionally, including any tool registered after this allowlist was+ // written — the whole point of inverting a denylist.+ if (!SHARE_VISITOR_ALLOWED_IDENTIFIERS.has(identifier)) return true;++ const rule = DATA_TOOL_ACCESS_RULES[identifier];+ if (!rule) return false;++ const grant = rule.grant(permissions);+ if (grant === 'none') return true;++ if (rule.writeApiNames.includes(apiName)) return true;+ if (rule.alwaysBlockedApiNames?.includes(apiName)) return true;+ if (args !== undefined && rule.isArgsOutOfScope?.(permissions, apiName, args)) return true;++ return false;+};++/**+ * FULL dispatch-time gate for a share-visitor builtin tool call — the check+ * `BuiltinToolsExecutor.execute` runs on every call that reaches it. Strictly+ * wider than {@link isShareBlockedDataToolCall}: a call that bypassed+ * assembly (resume path, recovery hint, model-fabricated call to a tool it+ * was never offered) must clear ALL the same gates the assembled tool set+ * enforced, not only the data-tool rules:+ *+ * 1. master default-deny allowlist (`SHARE_VISITOR_ALLOWED_IDENTIFIERS`);+ * 2. the owner's own `toolGrants` picker — being on the master allowlist+ * 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}).+ *+ * Non-builtin identifiers (MCP/market/custom plugins, LobeHub skills) pass+ * through untouched: their id namespace does not reliably match+ * `toolGrants` identifiers, so they remain governed by the assembly-time+ * `filterPluginsByShareGate` intersection only.+ */+export const isShareBlockedBuiltinDispatch = (+ agentShare: ShareDataToolPermissions & { toolGrants?: AgentShareToolGrant[] },+ identifier: string,+ apiName: string,+ args?: any,+): boolean => {+ if (!isGovernedByBuiltinAllowlist(identifier)) return false;++ if (!SHARE_VISITOR_ALLOWED_IDENTIFIERS.has(identifier)) return true;+ // The owner's picker must grant this identifier at all (toolset-level or+ // naming this specific `apiName`) — a grant scoped to a DIFFERENT api on+ // the same identifier does not authorize this call.+ if (!isShareToolApiGranted(resolveShareToolGrants(agentShare.toolGrants), identifier, apiName))+ return true;++ // Sub-agent dispatch has no humanIntervention config to catch it, and the+ // server sub-agent runner spawns the child via a plain `execAgent` call+ // that does NOT thread the parent's shareGate — the child would run with+ // the creator's full, unrestricted tool surface. Assembly strips the API+ // (`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;++ return isShareBlockedDataToolCall(agentShare, identifier, apiName, args);+};++/**+ * The assembled operation-level tool set, right before it is handed to+ * `AgentRuntimeService.createOperation` as `toolSet`.+ */+export interface ShareGateToolSet {+ activatableToolIds: string[];+ enabledToolIds: string[];+ executorMap: Record<string, ToolExecutor>;+ manifestMap: Record<string, LobeToolManifest>;+ sourceMap: Record<string, ToolSource>;+ tools: any[] | undefined;+}++/**+ * Apply {@link DATA_TOOL_ACCESS_RULES} to the assembled tool set: drop a data+ * tool entirely when its grant is `none`, or strip its write APIs (from both+ * the manifest and the function-calling `tools` schema) when the grant is+ * `read`. Runs as part of {@link applyShareGateToToolSet} — after that pass's+ * allowlist intersection has already decided which identifiers survive at all+ * — so this only needs to further restrict, never re-add.+ *+ * This is UX/defense-in-depth (the model is never offered the disallowed+ * function); the actual unbypassable enforcement is+ * {@link isShareBlockedDataToolCall} at the `BuiltinToolsExecutor` dispatch+ * site.+ */+const applyShareGateToDataToolAccess = (toolSet: ShareGateToolSet, gate: AgentShareGate): void => {+ for (const [identifier, rule] of Object.entries(DATA_TOOL_ACCESS_RULES)) {+ if (!toolSet.manifestMap[identifier]) continue;++ const grant = rule.grant(gate.shareConfig);++ if (grant === 'none') {+ dropToolFromSet(toolSet, identifier);+ continue;+ }++ // Under a `read` grant, strip both mutations (`writeApiNames`) AND the+ // creator-wide reads that no grant can honestly scope to this agent+ // (`alwaysBlockedApiNames`) — same treatment, since both are never offered+ // to the model regardless of grant. `isArgsOutOfScope`-covered APIs are+ // NOT stripped here: they stay offered because they CAN be in scope+ // depending on the id the model picks, and that per-call id check only+ // runs at dispatch time, not against a static manifest.+ const blockedApiNames = new Set([...rule.writeApiNames, ...(rule.alwaysBlockedApiNames ?? [])]);++ stripApisFromTool(toolSet, identifier, blockedApiNames);+ }+};++/**+ * Final allowlist enforcement for a share visitor's fully-assembled tool set.+ *+ * `shareConfig.toolGrants` is the single source of truth for what a share+ * visitor can see or run. This pass mutates `toolSet` in place and must run+ * once, after every manifest/default/dynamic-activation source has been merged+ * in, immediately before the operation's `toolSet` is persisted. An+ * empty/missing whitelist collapses the set to nothing (no built-in tool is+ * exempted; a share with no configured tools is a plain-chat run).+ */+export const applyShareGateToToolSet = (toolSet: ShareGateToolSet, gate: AgentShareGate): void => {+ const grants = resolveShareToolGrants(gate.shareConfig.toolGrants);++ // A tool must clear BOTH gates: the owner's own `toolGrants` picker+ // (`grants` — toolset-level OR scoped to at least one API), AND — for+ // builtin identifiers only — the default-deny master allowlist+ // (`SHARE_VISITOR_ALLOWED_IDENTIFIERS`). Non-builtin identifiers (MCP/market/+ // custom plugins) are outside `isGovernedByBuiltinAllowlist`'s population, so+ // they pass straight through to the owner-picker check unaffected — this+ // allowlist must never decide their fate, in either direction.+ const isAllowed = (id: string) => {+ if (!hasShareToolGrant(grants, id)) return false;+ if (!isGovernedByBuiltinAllowlist(id)) return true;+ return SHARE_VISITOR_ALLOWED_IDENTIFIERS.has(id);+ };++ // Prune arrays in place (`splice`, not reassignment) so this works whether+ // the caller's binding for `enabledToolIds` / `activatableToolIds` / `tools`+ // is a `const` array reference — callers only need to pass the array they+ // already hold, not receive a new one back.+ pruneArrayInPlace(toolSet.enabledToolIds, isAllowed);+ pruneArrayInPlace(toolSet.activatableToolIds, isAllowed);++ // Regenerate every allowed manifest's tool-call names BEFORE the manifests+ // are pruned: `ToolNameResolver.generate` MD5-hashes an identifier segment+ // that is non-ASCII or oversized, so the `tools[]` entry of such a tool does+ // not start with its literal identifier and a prefix-only check would drop+ // a granted MCP tool along with everything else (fail-closed, but breaks+ // the grant). See `pruneToolsForIdentifier` for the mirror-image, fail-OPEN+ // hazard on the per-API path.+ const allowedToolNames = new Set<string>();+ for (const [id, manifest] of Object.entries(toolSet.manifestMap)) {+ if (!isAllowed(id)) continue;+ for (const name of generateOwnedToolNames(id, manifest)) allowedToolNames.add(name);+ }++ for (const id of Object.keys(toolSet.manifestMap)) {+ if (!isAllowed(id)) delete toolSet.manifestMap[id];+ }+ for (const id of Object.keys(toolSet.sourceMap)) {+ if (!isAllowed(id)) delete toolSet.sourceMap[id];+ }+ for (const id of Object.keys(toolSet.executorMap)) {+ if (!isAllowed(id)) delete toolSet.executorMap[id];+ }++ if (toolSet.tools) {+ pruneArrayInPlace(toolSet.tools, (tool) => {+ const name: string | undefined = tool?.function?.name;+ if (!name) return false;+ if (allowedToolNames.has(name)) return true;+ // Fallback for an entry with no manifest to regenerate from — only its+ // literal identifier prefix can vouch for it.+ const identifier = name.split(PLUGIN_SCHEMA_SEPARATOR)[0];+ return !!identifier && isAllowed(identifier);+ });+ }++ stripSubAgentDispatchApis(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+ * naming an API another rule already removed is simply a no-op here, never an+ * unstrip.+ *+ * A toolset-level entry (`grant === 'all'`) leaves the tool's remaining APIs+ * untouched. A per-API entry (`grant` is a `Set`) drops every remaining API+ * not named in it; if that empties the API list entirely, the tool is dropped+ * outright — the same treatment `applyShareGateToDataToolAccess` gives a+ * `'none'` grant, since an identifier with zero callable APIs offers a share+ * visitor's model nothing.+ *+ * Matches on the manifest's real `api[].name` list (via `stripApisFromTool`)+ * rather than parsing generated tool-call names directly:+ * `ToolNameResolver.generate` MD5-hashes an oversized or invalid-character API+ * segment, so the manifest is the only reliable source for which entries in+ * `toolSet.tools` belong to which granted API.+ */+const applyShareGateToPerApiGrants = (+ toolSet: ShareGateToolSet,+ grants: Map<string, ShareToolGrant>,+): void => {+ for (const identifier of Object.keys(toolSet.manifestMap)) {+ const grant = grants.get(identifier);+ if (!grant || grant === 'all') continue;++ const manifest = toolSet.manifestMap[identifier];+ if (!Array.isArray(manifest.api) || manifest.api.length === 0) continue;++ const blockedApiNames = new Set(+ manifest.api.filter((api) => !grant.has(api.name)).map((api) => api.name),+ );+ if (blockedApiNames.size === 0) continue;++ if (blockedApiNames.size === manifest.api.length) {+ dropToolFromSet(toolSet, identifier);+ continue;+ }++ stripApisFromTool(toolSet, identifier, blockedApiNames);+ }+};++/**+ * 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+ * identifier had to be explicitly proven dangerous to be blocked; under the+ * allowlist an identifier has to be explicitly proven safe to be exposed, so+ * this block exists purely to record the evidence trail for reviewers — the+ * denial itself needs no code beyond "not in the Set".+ *+ * Confirmed leak paths (a concrete visitor→creator-data route was found):+ *+ * - `lobe-agent-management`: `agentManagementRuntime` is scoped by `userId`+ * (the creator — the run executes as the creator), but `agentId` is a+ * free-form model argument on nearly every API. `searchAgent` enumerates the+ * creator's whole workspace; `getAgentDetail` returns any creator-owned+ * agent's full config (system prompt included) for an arbitrary id;+ * `createAgent` / `updateAgent` / `updatePrompt` / `duplicateAgent` /+ * `installPlugin` persistently mutate the creator's agent collection.+ *+ * - `agent-signal-review`: `listManagedSkills` / `getManagedSkill` prefer an+ * optional model-supplied `agentId` over the context-bound one, letting a+ * visitor read ANY other agent's private managed-skill catalog under the+ * same creator. `writeMemory` / `createSkillIfAbsent` /+ * `replaceSkillContentCAS` are unconditional creator-scoped mutations, and+ * share grants are `none`/`read` only.+ *+ * - `lobe-skill-maintainer` / `agent-signal-skill-management`: hidden,+ * system-only tools whose every API WRITES agent-document rows under the+ * creator's account. No write grant exists to honor.+ *+ * - `lobe-task` / `lobe-goal`: `TaskModel`/`taskRouter` are scoped only by+ * `userId`/`workspaceId` — the CREATOR's. Every mutating and single-task-read+ * API takes a model-supplied identifier resolved with no topic/conversation+ * check, letting a visitor read, edit, delete, reschedule or RUN (spending+ * the creator's budget) any task in the workspace. `listTasks`'s `scope:+ * 'allAgents'` makes the breadth explicit.+ *+ * - `lobe-creds`: `injectCreds` takes a free-form `keys: string[]` and decrypts+ * matching entries out of the creator's ENTIRE saved credential store.+ *+ * - `lobe-message`: every bot-management API resolves `botId` straight from+ * model args with no check against `context.agentId`; the messenger APIs act+ * on the creator's whole personal messenger account.+ *+ * - `lobe-skill-store`: the `importFrom*` family fetches attacker-chosen+ * remote code/zip content and persists it into the creator's skill catalog.+ *+ * - `lobe-agent-builder`: `updateConfig`/`updatePrompt` overwrite the shared+ * agent's own `systemRole`/config wholesale — a visitor rewriting the+ * creator's live agent. `installPlugin` installs an arbitrary market MCP+ * plugin onto it as the creator, with no consent step.+ *+ * - `lobe-skills`: `findById`/`findByName` resolve any skill across the+ * creator's ENTIRE personal skill catalog, scoped only by an opt-out+ * `disabledSkillIds` set.+ *+ * - `lobe-brief`: `createBrief` unconditionally persists a row via+ * `BriefModel.create` under `context.userId` (the creator) from+ * model-supplied content, with no intervention marker to gate it.+ *+ * - `lobe-group-agent-builder` / `lobe-group-management`: group-orchestration+ * tools operating on the creator's group-agent collection and membership,+ * with no share-run scoping designed in — same risk class as+ * `lobe-agent-management`.+ *+ * - `lobe-topic-reference`: `topicReferenceRuntime.getTopicContext`+ * (`apps/server/src/services/toolExecution/serverRuntimes/topicReference.ts`)+ * resolves a free-form model-supplied `topicId` via+ * `TopicModel.findOwnTopicById`, scoped only to the creator's `userId` — not+ * to this share or agent — letting a visitor's model read the summary or+ * recent messages of ANY other topic the creator owns by guessing/enumerating+ * ids. `DATA_TOOL_ACCESS_RULES` has no entry for it (it isn't a+ * memory/knowledge-base/agent-documents style store), so nothing narrows the+ * allowlist grant. The automatic `<refer_topic>` injection path+ * (`serverCallLlmContextBuilder.ts`) is separately share-scoped via+ * `isTopicVisibleToRun` and is unaffected by this denial — only the+ * model-invokable tool-call path is unsafe.+ *+ * Denied for lack of positive safety evidence (no confirmed exploit was+ * required to withhold access — the point of default-deny is that an unproven+ * tool does not ship):+ *+ * - `lobe-local-system` / `lobe-browser` / `lobe-remote-device`: these proxy+ * through `deviceGateway` to the creator's own registered physical+ * device(s). A visitor executing arbitrary commands or driving a live+ * browser session on the CREATOR's own machine is a far larger blast radius+ * than any single data store.+ *+ * - `lobe-web-onboarding`: reads and WRITES the creator's own onboarding+ * `SOUL.md` document and persona.+ *+ * - `lobe-self-feedback-intent` / `agent-signal-reflection` /+ * `agent-signal-feedback-intent`: hidden, system-only self-iteration tools+ * whose write paths were never audited for share safety.+ *+ * - `lobe-page-agent`: not unsafe — genuinely unreachable for a share+ * visitor's run (`execAgent` strips it whenever `appContext?.scope !==+ * 'page'`, and the share visitor path never sets `scope`), so allowlisting+ * 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.+ */++/**+ * Positive evidence for builtin identifiers that WERE added to+ * `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS` despite reaching outside a single+ * data store — recorded here, rather than left implicit, because their+ * general-purpose reach needs an explicit safety argument instead of just the+ * absence of a known exploit.+ *+ * - `lobe-cloud-sandbox`: general-purpose shell/script execution, but a share+ * visitor's run gets a fresh, isolated per-topic sandbox session — never+ * the creator's own sandbox state. The `lh` CLI's JWT credential shim+ * (`preprocessLhCommand.ts`) that would otherwise mint a creator-scoped+ * token inside a shell the visitor controls is skipped entirely for+ * `agentShareVisitor` runs (`serverRuntimes/cloudSandbox.ts`), and+ * `lobe-creds` stays denied above so nothing ever writes `~/.creds/env`+ * into that session either. No creator credential or JWT is therefore+ * reachable from inside a visitor's sandbox command.+ */++/**+ * Sub-agent dispatch is not available in shared visitor runs. This strip runs+ * unconditionally on `lobe-agent`, independent of whether the manifest was+ * resolved through the normal context-aware path, so a whitelisted entry can+ * never surface `callSubAgent` — nor a `systemRole` that instructs the model+ * to call it — to a share visitor's model or the activator. `lobe-agent`+ * already ships a precise systemRole variant without the dispatch section+ * (`systemPromptWithoutSubAgent`, also used by its own context-aware+ * `resolveManifest`).+ *+ * `lobe-agent-management`'s dispatch API (`callAgent`) does NOT need an entry+ * here: the whole tool — dispatch included — is simply absent from+ * `SHARE_VISITOR_ALLOWED_IDENTIFIERS`, so it never survives that gate.+ */+const SUB_AGENT_DISPATCH_APIS: Record<+ string,+ { apiName: string; systemRoleWithoutDispatch: string }+> = {+ [LobeAgentIdentifier]: {+ apiName: LobeAgentApiName.callSubAgent,+ systemRoleWithoutDispatch: systemPromptWithoutSubAgent,+ },+};++const stripSubAgentDispatchApis = (toolSet: ShareGateToolSet): void => {+ for (const [identifier, { apiName, systemRoleWithoutDispatch }] of Object.entries(+ SUB_AGENT_DISPATCH_APIS,+ )) {+ const manifest = toolSet.manifestMap[identifier];+ if (manifest) {+ // Always pin the sanitized `systemRole`, not only when `api` still+ // carries the dispatch entry — an already context-aware-trimmed manifest+ // (api filtered upstream) could otherwise keep a stale `systemRole` that+ // still instructs the model to call the removed tool.+ toolSet.manifestMap[identifier] = {+ ...manifest,+ api: manifest.api.filter((api) => api.name !== apiName),+ systemRole: systemRoleWithoutDispatch,+ };+ }++ if (toolSet.tools) {+ const dispatchToolName = `${identifier}${PLUGIN_SCHEMA_SEPARATOR}${apiName}`;+ pruneArrayInPlace(toolSet.tools, (tool) => tool?.function?.name !== dispatchToolName);+ }+ }+};++/**+ * Regenerate the exact function-calling name `ToolsEngine` would have used+ * for each of `apiNames`, via the SAME `ToolNameResolver.generate` it used to+ * build `toolSet.tools` originally.+ *+ * A naive `` `${identifier}${SEP}${apiName}` `` string only matches what is+ * actually in `toolSet.tools` when neither segment needed normalizing.+ * `generate` (1) MD5-hashes an api/identifier segment that contains+ * characters strict providers reject or that pushes the name past the+ * provider length cap, and (2) appends a third `${SEP}<type>` segment for any+ * manifest whose `type` isn't `builtin`/`default` — MCP/connector manifests+ * are `type: 'mcp'` (see `buildConnectorManifests.ts`). Both are common for+ * MCP tools (server-controlled, often long/non-ASCII api names), so skipping+ * this and slicing the raw string instead silently fails OPEN: the manifest+ * loses the API but its generated tool-call name survives in `tools[]` and+ * stays callable.+ */+const generateToolNames = (+ identifier: string,+ apiNames: Iterable<string>,+ type: LobeToolManifest['type'],+): Set<string> => {+ const names = new Set<string>();+ for (const apiName of apiNames) names.add(toolNameResolver.generate(identifier, apiName, type));+ return names;+};++/**+ * Drop every `toolSet.tools` entry that belongs to `identifier` and is not in+ * `allowedNames`. Pass an empty `allowedNames` to drop every entry for the+ * identifier.+ *+ * "Belongs to `identifier`" is decided by `ownedNames` — the full set of+ * generated names for every API on the identifier's manifest, produced by+ * the SAME `ToolNameResolver.generate` that built `toolSet.tools`. A raw+ * first-segment comparison against `identifier` is NOT enough on its own:+ * `generate` MD5-hashes the identifier segment whenever it contains+ * characters strict providers reject (non-ASCII, punctuation) or whenever+ * the assembled name is still over the provider length cap after hashing+ * the api segment, so for such identifiers no entry ever starts with the+ * literal identifier text and a prefix-only match keeps everything —+ * silently failing OPEN. The prefix check is kept only as a fallback for+ * entries that survived without a manifest (nothing to regenerate from).+ */+const pruneToolsForIdentifier = (+ toolSet: ShareGateToolSet,+ identifier: string,+ ownedNames: ReadonlySet<string>,+ allowedNames: ReadonlySet<string>,+): void => {+ if (!toolSet.tools) return;+ pruneArrayInPlace(toolSet.tools, (tool) => {+ const name: string | undefined = tool?.function?.name;+ if (!name) return true;+ const owned = ownedNames.has(name) || name.split(PLUGIN_SCHEMA_SEPARATOR)[0] === identifier;+ if (!owned) return true;+ return allowedNames.has(name);+ });+};++/** Every generated tool-call name the manifest can currently produce. */+const generateOwnedToolNames = (+ identifier: string,+ manifest: LobeToolManifest | undefined,+): Set<string> =>+ manifest+ ? generateToolNames(+ identifier,+ manifest.api.map((api) => api.name),+ manifest.type,+ )+ : new Set();++const EMPTY_TOOL_NAME_SET: ReadonlySet<string> = new Set();++/** Remove one tool identifier from every parallel structure of the tool set. */+const dropToolFromSet = (toolSet: ShareGateToolSet, identifier: string): void => {+ // Regenerate the owned names BEFORE the manifest is gone — it is the only+ // source that can reproduce a hashed identifier segment.+ const ownedNames = generateOwnedToolNames(identifier, toolSet.manifestMap[identifier]);+ delete toolSet.manifestMap[identifier];+ delete toolSet.sourceMap[identifier];+ delete toolSet.executorMap[identifier];+ pruneArrayInPlace(toolSet.enabledToolIds, (id) => id !== identifier);+ pruneArrayInPlace(toolSet.activatableToolIds, (id) => id !== identifier);+ pruneToolsForIdentifier(toolSet, identifier, ownedNames, EMPTY_TOOL_NAME_SET);+};++/** Drop `blockedApiNames` from one tool's manifest AND its function-calling schema. */+const stripApisFromTool = (+ toolSet: ShareGateToolSet,+ identifier: string,+ blockedApiNames: Set<string>,+): void => {+ const manifest = toolSet.manifestMap[identifier];+ if (!manifest) return;++ const survivingApi = manifest.api.filter((api) => !blockedApiNames.has(api.name));++ toolSet.manifestMap[identifier] = { ...manifest, api: survivingApi };++ // Fail-closed: only keep `tools[]` entries this file can PROVE still+ // belong to a surviving API, by regenerating their exact names rather than+ // reverse-parsing whatever is already in `tools[]`.+ pruneToolsForIdentifier(+ toolSet,+ identifier,+ generateOwnedToolNames(identifier, manifest),+ generateToolNames(+ identifier,+ survivingApi.map((api) => api.name),+ manifest.type,+ ),+ );+};++const pruneArrayInPlace = <T>(array: T[], keep: (item: T) => boolean): void => {+ for (let i = array.length - 1; i >= 0; i -= 1) {+ if (!keep(array[i])) array.splice(i, 1);+ }+};diff --git a/apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts b/apps/server/src/services/aiAgent/shareVisitorAbuseGuards.tsnew file mode 100644index 00000000000..1fbc944694c--- /dev/null+++ b/apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts@@ -0,0 +1,229 @@+import type { LobeChatDatabase } from '@lobechat/database';+import type { CreateMessageParams, DBMessageItem } from '@lobechat/types';+import { ChatErrorType } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { eq } from 'drizzle-orm';++import { AgentShareModel } from '@/database/models/agentShare';+import { MessageModel } from '@/database/models/message';+import type { CreateTopicParams } from '@/database/models/topic';+import { TopicModel } from '@/database/models/topic';+import type { TopicItem } from '@/database/schemas';+import { agentShares } from '@/database/schemas';++/**+ * Re-validate the share is still the SAME live `link` share this request was+ * authorized against, from INSIDE the same `agents.id FOR UPDATE` transaction+ * `AgentShareModel.lockOwnedAgentRow` just took.+ *+ * WHY this must run BEFORE the topic/message INSERT the two guard functions+ * below perform, not only later: an owner who makes the link private while a+ * visitor's request is mid-flight must never get ANY row written under the+ * stale authorization.+ *+ * `expectedShareId` is checked alongside `visibility === 'link'` because the+ * row can also be replaced by a different instance (a hard delete via+ * `AgentShareModel.deleteByAgentId`, or an agent delete + recreate), which a+ * bare visibility check would miss since the replacement is `link` too. See+ * `AgentShareGate.shareId`'s JSDoc. Fail closed on a missing row, a non-`link`+ * visibility, or an id mismatch.+ */+const assertShareStillAuthorized = async (+ tx: LobeChatDatabase,+ agentId: string,+ expectedShareId: string,+): Promise<void> => {+ const [share] = await tx+ .select({ id: agentShares.id, visibility: agentShares.visibility })+ .from(agentShares)+ .where(eq(agentShares.agentId, agentId));++ if (!share || share.visibility !== 'link' || share.id !== expectedShareId) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'This share is private' });+ }+};++/**+ * Atomically enforce `maxTopicsPerVisitor` at the exact moment a share+ * visitor's new topic is written.+ *+ * `shareChat.ts` runs a `TopicModel.countBySender` pre-check before ever+ * dispatching to `AiAgentService.execAgent` (a fast, UX-only reject that skips+ * wasted agent-config/tool-resolution work for an obviously-over-cap request),+ * but that read and the actual `topics` INSERT this function performs are two+ * unrelated statements, on two unrelated requests/connections, with nothing+ * serializing them. Concurrent new-topic requests from the same visitor can+ * all observe the same pre-insert count and all insert.+ *+ * `AgentShareModel.lockOwnedAgentRow` takes `FOR UPDATE` on the SAME+ * `agents.id` row every other share-mutation path locks (`create`,+ * `updateConfig`, `updateVisibility`, `deleteByAgentId`). The recount and the+ * INSERT both run inside that one locked transaction, so whichever of two+ * concurrent callers loses the lock re-reads the FIRST caller's+ * already-committed topic and correctly rejects instead of also inserting.+ * Reusing the Agent row lock (rather than a visitor-keyed advisory lock) also+ * makes the cap read below conflict with a concurrent `updateConfig`, so a+ * recount can never straddle an owner's cap reduction.+ *+ * The cap itself is read via `AgentShareModel.readCurrentVisitorCaps` from+ * INSIDE this same locked transaction — deliberately NOT accepted as a+ * caller-supplied number. `shareChat.ts` resolves `shareConfig` exactly ONCE,+ * long before `AiAgentService` reaches this function (agent-config/tool/+ * knowledge-base resolution in between), so a caller-supplied cap would be a+ * stale snapshot an owner's mid-flood reduction could never affect.+ */+export const reserveShareVisitorTopicOrThrow = async (params: {+ agentId: string;+ create: (topicModel: TopicModel) => Promise<TopicItem>;+ db: LobeChatDatabase;+ /**+ * The `agentShares.id` the caller resolved this request against+ * (`AgentShareGate.shareId`) — re-checked fresh under this same row lock via+ * {@link assertShareStillAuthorized} before anything is inserted.+ */+ expectedShareId: string;+ ownerId: string;+ visitorUserId: string;+ workspaceId?: string;+}): Promise<TopicItem> => {+ const { agentId, create, db, expectedShareId, ownerId, visitorUserId, workspaceId } = params;++ return db.transaction(async (trx) => {+ const tx = trx as unknown as LobeChatDatabase;++ // Fail closed: a deleted/transferred/no-longer-owned agent never gets a+ // new visitor topic, same as every other share-mutation path locking this+ // row — see `lockOwnedAgentRow`'s JSDoc.+ const locked = await AgentShareModel.lockOwnedAgentRow(tx, agentId, ownerId);+ if (!locked) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'This share is private' });+ }++ // Fail closed BEFORE any row is written.+ await assertShareStillAuthorized(tx, agentId, expectedShareId);++ // Fresh read under the lock, not a caller-supplied value — see this+ // function's JSDoc for the stale-cap flood this closes.+ const { maxTopicsPerVisitor } = await AgentShareModel.readCurrentVisitorCaps(tx, agentId);++ // Share-runtime scope: countBySender reads through `mine()` (visitor-+ // inclusive by construction) so this flag is redundant here, but pass it+ // so any later read added to this guard doesn't silently fail closed.+ const txTopicModel = new TopicModel(tx, ownerId, workspaceId, undefined, {+ includeShareVisitor: true,+ });+ const currentCount = await txTopicModel.countBySender({ agentId, senderId: visitorUserId });++ // Fail closed: a visitor already at (or somehow past) the cap never gets+ // another topic, even if `create`'s own params disagree with `agentId`.+ if (currentCount >= maxTopicsPerVisitor) {+ throw new TRPCError({+ code: 'TOO_MANY_REQUESTS',+ message: ChatErrorType.ShareTopicLimitExceeded,+ });+ }++ return create(txTopicModel);+ });+};++/** Convenience wrapper so callers can pass `TopicModel.create`'s own params directly. */+export const reserveShareVisitorTopic = (+ params: {+ agentId: string;+ db: LobeChatDatabase;+ expectedShareId: string;+ ownerId: string;+ visitorUserId: string;+ workspaceId?: string;+ },+ createParams: CreateTopicParams,+ id?: string,+): Promise<TopicItem> =>+ reserveShareVisitorTopicOrThrow({+ ...params,+ create: (topicModel) => topicModel.create(createParams, id),+ });++/**+ * Atomically enforce `maxTurnsPerTopic` at the exact moment a share visitor's+ * user-turn message is written.+ *+ * Structurally the same race as {@link reserveShareVisitorTopicOrThrow}:+ * `shareChat.ts` pre-checks `MessageModel.countByTopic` against the cap before+ * dispatch, but the actual user-message INSERT happens later, deep in+ * `execAgent`, on a separate statement with nothing serializing the two. A+ * burst of concurrent sends to the SAME topic can all pass the pre-check and+ * all insert.+ *+ * Locked via `AgentShareModel.lockOwnedAgentRow` — the SAME `agents.id FOR+ * UPDATE` row {@link reserveShareVisitorTopicOrThrow} and every other+ * share-mutation path lock, not a topic-scoped lock, so the cap read below+ * also conflicts with a concurrent `updateConfig`. The trade-off is coarser+ * contention (this serializes against every OTHER topic's reservation for the+ * same agent), which is acceptable: these transactions are a single+ * count-then-insert each, with no external I/O.+ */+export const reserveShareVisitorTurnOrThrow = async (params: {+ agentId: string;+ create: (messageModel: MessageModel) => Promise<DBMessageItem | undefined>;+ db: LobeChatDatabase;+ /** See {@link reserveShareVisitorTopicOrThrow}'s `expectedShareId` param JSDoc. */+ expectedShareId: string;+ ownerId: string;+ topicId: string;+ workspaceId?: string;+}): Promise<DBMessageItem | undefined> => {+ const { agentId, create, db, expectedShareId, ownerId, topicId, workspaceId } = params;++ return db.transaction(async (trx) => {+ const tx = trx as unknown as LobeChatDatabase;++ // Fail closed: same ownership/existence check as the topic guard.+ const locked = await AgentShareModel.lockOwnedAgentRow(tx, agentId, ownerId);+ if (!locked) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'This share is private' });+ }++ // Fail closed BEFORE any row is written.+ await assertShareStillAuthorized(tx, agentId, expectedShareId);++ // Fresh read under the lock, not a caller-supplied value.+ const { maxTurnsPerTopic } = await AgentShareModel.readCurrentVisitorCaps(tx, agentId);++ // Share-runtime scope: countByTopic reads through `ownership()`, which+ // now excludes visitor rows by default — the visitor topic's rows would+ // never be counted without opting in.+ const txMessageModel = new MessageModel(tx, ownerId, workspaceId, undefined, {+ includeShareVisitor: true,+ });+ const turnCount = await txMessageModel.countByTopic({ role: 'user', topicId });++ if (turnCount >= maxTurnsPerTopic) {+ throw new TRPCError({+ code: 'TOO_MANY_REQUESTS',+ message: ChatErrorType.ShareTurnLimitExceeded,+ });+ }++ return create(txMessageModel);+ });+};++/** Convenience wrapper so callers can pass `MessageModel.create`'s own params directly. */+export const reserveShareVisitorTurn = (+ params: {+ agentId: string;+ db: LobeChatDatabase;+ expectedShareId: string;+ ownerId: string;+ topicId: string;+ workspaceId?: string;+ },+ createParams: CreateMessageParams,+ id?: string,+): Promise<DBMessageItem | undefined> =>+ reserveShareVisitorTurnOrThrow({+ ...params,+ create: (messageModel) => messageModel.create(createParams, id),+ });diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.tsindex 307a4d10dcb..bffb225b3a6 100644--- a/apps/server/src/services/aiAgent/types.ts+++ b/apps/server/src/services/aiAgent/types.ts@@ -15,6 +15,7 @@ import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';import type { EvalRuntimeContext } from '@/server/services/agentRuntime/types';import type { DeviceAccessReason } from './deviceAccessPolicy';+import type { AgentShareGate } from './shareGate';/*** Resolved run state shared by the {@link AiAgentService.execAgent} pipeline@@ -43,6 +44,13 @@ export interface ExecRunContext {provider: string;/** The actual executing agent row id resolved from id/slug. */resolvedAgentId: string;+ /**+ * Shared-agent visitor gate for this run, mirrored from+ * {@link InternalExecAgentParams.shareGate} so every extracted pipeline stage+ * can enforce it without threading a separate argument. Undefined for every+ * ordinary (non-share) run.+ */+ shareGate?: AgentShareGate;/** Topic id — guaranteed to exist by the time pipeline stages run. */topicId: string;trigger?: string;@@ -211,6 +219,12 @@ export interface InternalExecAgentParams extends ExecAgentParams {* downstream (connectors, installed plugins) keep it to the caller's own tools.*/selectedToolIds?: string[];+ /**+ * Shared-agent visitor gate. Set ONLY by the shareChat router after the+ * share access check — never client-passable. Restricts tools/memory/files at+ * operation-build time, denies device access, and scopes the visitor's rows.+ */+ shareGate?: AgentShareGate;/** Abort startup before the agent runtime operation is created */signal?: AbortSignal;/**diff --git a/apps/server/src/services/expertise/ingestion.history.test.ts b/apps/server/src/services/expertise/ingestion.history.test.tsindex a72c496745c..168b9381a94 100644--- a/apps/server/src/services/expertise/ingestion.history.test.ts+++ b/apps/server/src/services/expertise/ingestion.history.test.ts@@ -134,4 +134,58 @@ describe('ExpertiseIngestionService historical topic resolution', () => {await expect(service.countHistoricalTopics('hist-agent')).resolves.toBe(0);});++ // Agent-share visitor topics are stored under the creator's userId (billing+ // attribution) but carry a non-null senderId. They must never surface as+ // historical-backfill candidates, since that would feed self-learning/expertise+ // ingestion with a visitor's conversation instead of the creator's own activity.+ it('excludes agent-share visitor topics from historical topic candidates', async () => {+ await serverDB.insert(topics).values([+ // Reached through the message-agent arm.+ {+ agentId: 'hist-agent',+ id: 'topic-visitor-explicit',+ senderId: 'visitor-user-x',+ title: 'visitor explicit',+ userId,+ },+ // Reached through the legacy topic-agent arm.+ {+ agentId: 'hist-agent',+ id: 'topic-visitor-legacy',+ senderId: 'visitor-user-x',+ title: 'visitor legacy',+ userId,+ },+ ]);+ await serverDB.insert(messages).values([+ {+ agentId: 'hist-agent',+ content: 'visitor explicit',+ createdAt: new Date('2026-01-07T00:00:00Z'),+ id: 'msg-visitor-explicit',+ role: 'user',+ topicId: 'topic-visitor-explicit',+ userId,+ },+ {+ content: 'visitor legacy',+ createdAt: new Date('2026-01-08T00:00:00Z'),+ id: 'msg-visitor-legacy',+ role: 'user',+ topicId: 'topic-visitor-legacy',+ userId,+ },+ ]);++ const service = new ExpertiseIngestionService(serverDB, userId);++ // Still 2, not 4 — the two new visitor topics never qualify as candidates.+ await expect(service.countHistoricalTopics('hist-agent')).resolves.toBe(2);++ const listed = await service.listHistoricalTopics('hist-agent', { limit: 50 });+ expect(listed.map((t) => t.topicId)).not.toEqual(+ expect.arrayContaining(['topic-visitor-explicit', 'topic-visitor-legacy']),+ );+ });});diff --git a/apps/server/src/services/expertise/ingestion.ts b/apps/server/src/services/expertise/ingestion.tsindex 7ff3c0a21d5..bf991eacee1 100644--- a/apps/server/src/services/expertise/ingestion.ts+++ b/apps/server/src/services/expertise/ingestion.ts@@ -21,6 +21,7 @@ import { z } from 'zod';import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';import { ExpertiseModel } from '@/database/models/expertise';import type { LobeChatDatabase } from '@/database/type';+import { notShareVisitorMessage, notShareVisitorTopic } from '@/database/utils/shareVisitor';import type { CompletionCallbackParams } from '@/server/services/agentSignal/policies/completionPolicy';import { AiGenerationService } from '@/server/services/aiGeneration';@@ -162,15 +163,27 @@ export class ExpertiseIngestionService {? eq(messages.workspaceId, this.workspaceId): and(eq(messages.userId, this.userId), isNull(messages.workspaceId));+ // Share-visitor topics/messages are billed to the creator but are visitor traffic,+ // not the creator's own activity — they must never feed self-learning/expertise+ // ingestion. See `notShareVisitorMessage`/`notShareVisitorTopic` for the shared rule.const byMessageAgent = this.db.select({ topicId: messages.topicId }).from(messages)- .where(and(scope, eq(messages.agentId, agentId), isNotNull(messages.topicId)));+ .where(+ and(+ scope,+ eq(messages.agentId, agentId),+ isNotNull(messages.topicId),+ notShareVisitorMessage(),+ ),+ );const byTopicAgent = this.db.select({ topicId: messages.topicId }).from(messages).innerJoin(topics, eq(topics.id, messages.topicId))- .where(and(scope, isNull(messages.agentId), eq(topics.agentId, agentId)));+ .where(+ and(scope, isNull(messages.agentId), eq(topics.agentId, agentId), notShareVisitorTopic()),+ );return byMessageAgent.union(byTopicAgent).as('historical_topic_candidates');};@@ -327,6 +340,8 @@ export class ExpertiseIngestionService {: and(eq(messages.userId, this.userId), isNull(messages.workspaceId)),eq(messages.topicId, topicId),isNull(messages.threadId),+ // Same rule as `historicalTopicCandidates` above — exclude share-visitor messages.+ notShareVisitorMessage(),),});return {diff --git a/apps/server/src/services/followUpAction/index.test.ts b/apps/server/src/services/followUpAction/index.test.tsindex ee1ff303f3e..41623e39cdd 100644--- a/apps/server/src/services/followUpAction/index.test.ts+++ b/apps/server/src/services/followUpAction/index.test.ts@@ -1,6 +1,7 @@// @vitest-environment nodeimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { notShareVisitorMessage } from '@/database/utils/shareVisitor';import * as ModelRuntimeModule from '@/server/modules/ModelRuntime';import { FollowUpActionService } from './index';@@ -39,6 +40,33 @@ describe('FollowUpActionService.extract', () => {vi.restoreAllMocks();});+ it('excludes agent-share visitor messages from the assistant lookup', async () => {+ queryFindFirstSpy.mockResolvedValue(undefined);+ await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });++ const { where } = queryFindFirstSpy.mock.calls[0][0];+ const operators = {+ and: (...conditions: unknown[]) => conditions,+ eq: (column: unknown, value: unknown) => ({ column, op: 'eq', value }),+ isNotNull: (column: unknown) => ({ column, op: 'isNotNull' }),+ isNull: (column: unknown) => ({ column, op: 'isNull' }),+ ne: (column: unknown, value: unknown) => ({ column, op: 'ne', value }),+ };+ const conditions = where(+ {+ content: 'content',+ role: 'role',+ threadId: 'threadId',+ topicId: 'topicId',+ userId: 'userId',+ workspaceId: 'workspaceId',+ },+ operators,+ ) as unknown[];++ expect(conditions).toContainEqual(notShareVisitorMessage());+ });+it('returns empty (with empty messageId) when no eligible assistant message found', async () => {queryFindFirstSpy.mockResolvedValue(undefined);const result = await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });diff --git a/apps/server/src/services/followUpAction/index.ts b/apps/server/src/services/followUpAction/index.tsindex 7ef5d300493..5c447f51560 100644--- a/apps/server/src/services/followUpAction/index.ts+++ b/apps/server/src/services/followUpAction/index.ts@@ -9,6 +9,7 @@ import type { FollowUpChip, FollowUpExtractInput, FollowUpExtractResult } from 'import debug from 'debug';import type { LobeChatDatabase } from '@/database/type';+import { notShareVisitorMessage } from '@/database/utils/shareVisitor';import { AiGenerationService } from '@/server/services/aiGeneration';import { RawResponseSchema } from './schema';@@ -51,6 +52,11 @@ export class FollowUpActionService {eq(m.role, 'assistant'),isNotNull(m.content),ne(m.content, ''),+ // `topicId` is client input and agent-share visitor topics carry the+ // creator's userId, so without this a creator could feed a visitor+ // topic id here and get the visitor's assistant reply summarized+ // into chips — the same read the creator-facing routers deny.+ notShareVisitorMessage(),),});diff --git a/apps/server/src/services/memory/userMemory/__tests__/embedding.test.ts b/apps/server/src/services/memory/userMemory/__tests__/embedding.test.tsindex 0a759c9e903..a6348f23156 100644--- a/apps/server/src/services/memory/userMemory/__tests__/embedding.test.ts+++ b/apps/server/src/services/memory/userMemory/__tests__/embedding.test.ts@@ -102,4 +102,49 @@ describe('embedUserMemoryTexts', () => {);expect(result).toEqual([[1, 2, 3]]);});++ it('overrides the default memory trigger with the caller spend attribution', async () => {+ const runtime = {+ embeddings: vi.fn(async () => [[1, 2, 3]]),+ } satisfies UserMemoryEmbeddingRuntime;++ await embedUserMemoryTexts({+ input: ['short text'],+ model: 'text-embedding-3-large',+ runtime,+ source: 'test:share',+ spendOrigin: {+ agentShare: { agentId: 'agent-1', shareId: 'share-1', visitorUserId: 'visitor-1' },+ trigger: 'agent_share',+ },+ userId: 'creator-1',+ });++ expect(runtime.embeddings).toHaveBeenCalledWith(expect.anything(), {+ metadata: {+ agentShare: { agentId: 'agent-1', shareId: 'share-1', visitorUserId: 'visitor-1' },+ trigger: 'agent_share',+ },+ user: 'creator-1',+ });+ });++ it('keeps the memory trigger when no spend attribution is supplied', async () => {+ const runtime = {+ embeddings: vi.fn(async () => [[1, 2, 3]]),+ } satisfies UserMemoryEmbeddingRuntime;++ await embedUserMemoryTexts({+ input: ['short text'],+ model: 'text-embedding-3-large',+ runtime,+ source: 'test:plain',+ userId: 'user-test',+ });++ expect(runtime.embeddings).toHaveBeenCalledWith(expect.anything(), {+ metadata: { trigger: 'memory' },+ user: 'user-test',+ });+ });});diff --git a/apps/server/src/services/memory/userMemory/embedding.ts b/apps/server/src/services/memory/userMemory/embedding.tsindex 884ebe1889d..15bb4bdbb7f 100644--- a/apps/server/src/services/memory/userMemory/embedding.ts+++ b/apps/server/src/services/memory/userMemory/embedding.ts@@ -1,6 +1,6 @@import { DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS } from '@lobechat/const';import type { ModelRuntime } from '@lobechat/model-runtime';-import { RequestTrigger } from '@lobechat/types';+import { RequestTrigger, type SpendOrigin } from '@lobechat/types';import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';import { trimBasedOnBatchProbe } from '@/utils/chunkers';@@ -39,6 +39,13 @@ export interface EmbedUserMemoryTextsParams {* Stable call-site label used for trim diagnostics.*/source: string;+ /**+ * Origin attribution for the embedding spend. A shared-agent visitor run+ * supplies it so the embedding is billed to the shared agent instead of+ * disappearing into the creator's plain memory usage; its `trigger`+ * overrides the default {@link RequestTrigger.Memory}.+ */+ spendOrigin?: SpendOrigin;/*** User id passed to runtime billing/tracing metadata.*/@@ -108,7 +115,13 @@ export const embedUserMemoryTexts = async (input: requests.map((item) => item.text),model: params.model,},- { metadata: { trigger: RequestTrigger.Memory }, user: params.userId },+ {+ metadata: {+ ...params.spendOrigin,+ trigger: params.spendOrigin?.trigger ?? RequestTrigger.Memory,+ },+ user: params.userId,+ },);for (const [requestIndex, embeddingVector] of (embeddings ?? []).entries()) {diff --git a/apps/server/src/services/message/index.ts b/apps/server/src/services/message/index.tsindex aedd87f16de..2255c58397c 100644--- a/apps/server/src/services/message/index.ts+++ b/apps/server/src/services/message/index.ts@@ -163,8 +163,22 @@ export class MessageService {* so server-internal callers (e.g. agent runtime stream events) can push* the same payload the client would otherwise fetch.*/- async queryMessages(params: QueryMessageParams): Promise<UIChatMessage[]> {- return this.messageModel.query(params, this.getQueryOptions());+ async queryMessages(+ params: QueryMessageParams,+ options?: {+ /**+ * Include agent-share visitor rows. `MessageModel.query()` hides them by+ * default (they live under the creator's account but belong to the+ * visitor); only run-execution seams whose topic is already resolved and+ * authorized may opt in.+ */+ allowShareVisitor?: boolean;+ },+ ): Promise<UIChatMessage[]> {+ return this.messageModel.query(params, {+ ...this.getQueryOptions(),+ ...(options?.allowShareVisitor && { allowShareVisitor: true }),+ });}/**diff --git a/apps/server/src/services/onboarding/index.test.ts b/apps/server/src/services/onboarding/index.test.tsindex 050644f6821..befe7175ea5 100644--- a/apps/server/src/services/onboarding/index.test.ts+++ b/apps/server/src/services/onboarding/index.test.ts@@ -76,6 +76,7 @@ describe('OnboardingService', () => {let mockTopicModel: {create: ReturnType<typeof vi.fn>;findById: ReturnType<typeof vi.fn>;+ findOwnTopicById: ReturnType<typeof vi.fn>;updateMetadata: ReturnType<typeof vi.fn>;};let persistedUserState: any;@@ -174,6 +175,12 @@ describe('OnboardingService', () => {return topic;}),findById: vi.fn(async (id: string) => persistedTopics[id]),+ findOwnTopicById: vi.fn(async (id: string) => {+ const topic = persistedTopics[id];+ // Mirror the real predicate: creator-facing lookup hides share-visitor topics.+ if (!topic || topic.senderId) return undefined;+ return topic;+ }),updateMetadata: vi.fn(async (id: string, metadata: any) => {const existing = persistedTopics[id] ?? { id, metadata: undefined };const nextTopic = {@@ -628,6 +635,34 @@ describe('OnboardingService', () => {});});+ it('does not transfer a visitor topic pointed at by activeTopicId', async () => {+ // Regression: `updateAgentOnboarding` lets a creator set any topic id as+ // `activeTopicId`. If that id is a share-visitor topic (creator's userId+ // but non-null senderId), finishing onboarding must NOT re-parent it into+ // the creator's inbox.+ const visitorTopicId = 'visitor-topic';+ persistedUserState.agentOnboarding = {+ activeTopicId: visitorTopicId,+ version: CURRENT_ONBOARDING_VERSION,+ };+ persistedTopics[visitorTopicId] = {+ agentId: 'shared-agent-1',+ id: visitorTopicId,+ metadata: {},+ senderId: 'visitor-user-1',+ };++ const service = new OnboardingService(mockDb, userId);+ const result = await service.finishOnboarding();++ expect(result.success).toBe(true);+ // The transfer transaction must not have fired for the visitor topic.+ expect(mockDb.transaction).not.toHaveBeenCalled();+ expect(transactionUpdateCalls).toHaveLength(0);+ // Topic is untouched — agentId still the visitor-facing shared agent.+ expect(persistedTopics[visitorTopicId]?.agentId).toBe('shared-agent-1');+ });+it('writes onboarding milestones only once as phase advances', async () => {vi.useFakeTimers();persistedUserState.agentOnboarding = {diff --git a/apps/server/src/services/onboarding/index.ts b/apps/server/src/services/onboarding/index.tsindex df8cdc92aba..9c025cca763 100644--- a/apps/server/src/services/onboarding/index.ts+++ b/apps/server/src/services/onboarding/index.ts@@ -36,6 +36,7 @@ import {userPersonaDocuments,} from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { notShareVisitorTopic, notShareVisitorTopicRef } from '@/database/utils/shareVisitor';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { AgentService } from '@/server/services/agent';import { AgentDocumentsService } from '@/server/services/agentDocuments';@@ -195,7 +196,12 @@ export class OnboardingService {private transferToInbox = async (topicId: string): Promise<void> => {const inboxAgentId = await this.getInboxAgentId();- const topic = await this.topicModel.findById(topicId);+ // Use the creator-scoped lookup so an `activeTopicId` pointing at an+ // agent-share visitor topic (which lives under the creator's userId with+ // a non-null `senderId`) resolves to nothing and turns the transfer into+ // a no-op. The `notShareVisitor*` predicates below keep the write guarded+ // as defense in depth even if a caller ever bypasses the lookup.+ const topic = await this.topicModel.findOwnTopicById(topicId);if (!topic || topic.agentId === inboxAgentId) return;@@ -203,17 +209,29 @@ export class OnboardingService {await tx.update(topics).set({ agentId: inboxAgentId, updatedAt: topics.updatedAt })- .where(and(eq(topics.id, topicId), eq(topics.userId, this.userId)));+ .where(and(eq(topics.id, topicId), eq(topics.userId, this.userId), notShareVisitorTopic()));await tx.update(messages).set({ agentId: inboxAgentId, updatedAt: messages.updatedAt })- .where(and(eq(messages.topicId, topicId), eq(messages.userId, this.userId)));+ .where(+ and(+ eq(messages.topicId, topicId),+ eq(messages.userId, this.userId),+ notShareVisitorTopicRef(messages.topicId),+ ),+ );await tx.update(threads).set({ agentId: inboxAgentId, updatedAt: threads.updatedAt })- .where(and(eq(threads.topicId, topicId), eq(threads.userId, this.userId)));+ .where(+ and(+ eq(threads.topicId, topicId),+ eq(threads.userId, this.userId),+ notShareVisitorTopicRef(threads.topicId),+ ),+ );});};diff --git a/apps/server/src/services/toolExecution/__tests__/builtin.test.ts b/apps/server/src/services/toolExecution/__tests__/builtin.test.tsindex f31fa9bfba4..ded1646a245 100644--- a/apps/server/src/services/toolExecution/__tests__/builtin.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/builtin.test.ts@@ -12,7 +12,10 @@ const mockApiHandler = mocks.apiHandler;vi.mock('../serverRuntimes', () => ({hasServerRuntime: vi.fn().mockReturnValue(true),- getServerRuntime: vi.fn(async () => ({ createDocument: mocks.apiHandler })),+ getServerRuntime: vi.fn(async () => ({+ createDocument: mocks.apiHandler,+ searchUserMemory: mocks.apiHandler,+ })),}));vi.mock('@/server/services/composio', () => ({@@ -27,12 +30,41 @@ vi.mock('@/server/services/market', () => ({// The runtime mock above only exposes `createDocument`, but the manifest is the// authoritative source of declared APIs — it also lists `listDocuments`, so an// UNKNOWN_API hint sourced from the manifest must surface both.+//+// The share-gate exports mirror the real module's semantics on this mock's+// registry: both mocked identifiers are "builtin", neither is share-allowed —+// 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']),+ isBuiltinToolIdentifier: (id: string) =>+ ['lobe-notebook', 'lobe-task', 'lobe-user-memory', 'lobe-consent-tool'].includes(id),builtinTools: [{identifier: 'lobe-notebook',manifest: { api: [{ name: 'createDocument' }, { name: 'listDocuments' }] },},+ {+ identifier: 'lobe-user-memory',+ manifest: {+ api: [+ { name: 'searchUserMemory' },+ { name: 'addContextMemory' },+ // exercises the dispatch gate's unstripped-manifest intervention check+ { 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: {@@ -427,3 +459,128 @@ describe('BuiltinToolsExecutor manifest-driven Work registration', () => {});});});++// Regression for the share-visitor dispatch gate: the assembly-time tool-set+// trim only shapes what the model is OFFERED — the executor must re-block on+// its own, or any path that bypasses assembly (resume, recovery hints, future+// discovery routes) executes with the creator's full permissions.+describe('BuiltinToolsExecutor share-visitor gate', () => {+ const executor = new BuiltinToolsExecutor({} as any, 'user-1');++ const memoryPayload = (apiName: string): ChatToolPayload => ({+ apiName,+ arguments: '{"query":"hi"}',+ id: 't-share',+ identifier: 'lobe-user-memory',+ type: 'default' as any,+ });++ // AgentShareVisitorContext now requires these id fields for billing+ // attribution and revocation checks; the gate tests below only vary the+ // permission fields, so share the ids across fixtures.+ const visitorIds = { agentId: 'agent-1', shareId: 'share-1', visitorUserId: 'visitor-1' };++ beforeEach(() => {+ mockApiHandler.mockReset();+ mockApiHandler.mockResolvedValue({ content: 'ok', success: true });+ });++ it('blocks a builtin identifier outside the share allowlist', async () => {+ const result = await executor.execute(buildPayload('{}'), {+ ...context,+ agentShareVisitor: { ...visitorIds },+ });++ expect(result.success).toBe(false);+ expect(result.error?.code).toBe('SHARE_GATE_BLOCKED');+ expect(mockApiHandler).not.toHaveBeenCalled();+ });++ it('executes the same call untouched when the run is not a share run', async () => {+ const result = await executor.execute(buildPayload('{}'), context);++ expect(result.error?.code).not.toBe('SHARE_GATE_BLOCKED');+ expect(mockApiHandler).toHaveBeenCalled();+ });++ it('blocks an allowlisted builtin the owner did not enable for the share', async () => {+ // On the master allowlist AND permission-granted, but absent from the+ // owner's toolGrants picker — must still be blocked at dispatch.+ const result = await executor.execute(memoryPayload('searchUserMemory'), {+ ...context,+ agentShareVisitor: { ...visitorIds, allowReadMemory: true },+ });++ expect(result.error?.code).toBe('SHARE_GATE_BLOCKED');+ 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.+ const result = await executor.execute(memoryPayload('consentGated'), {+ ...context,+ agentShareVisitor: {+ ...visitorIds,+ allowReadMemory: true,+ toolGrants: [{ identifier: 'lobe-user-memory' }],+ },+ });++ 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();+ });++ it('blocks memory reads without allowReadMemory', async () => {+ const result = await executor.execute(memoryPayload('searchUserMemory'), {+ ...context,+ agentShareVisitor: { ...visitorIds, toolGrants: [{ identifier: 'lobe-user-memory' }] },+ });++ expect(result.error?.code).toBe('SHARE_GATE_BLOCKED');+ expect(mockApiHandler).not.toHaveBeenCalled();+ });++ it('allows memory reads with allowReadMemory but still blocks memory writes', async () => {+ const read = await executor.execute(memoryPayload('searchUserMemory'), {+ ...context,+ agentShareVisitor: {+ ...visitorIds,+ allowReadMemory: true,+ toolGrants: [{ identifier: 'lobe-user-memory' }],+ },+ });+ expect(read.error?.code).not.toBe('SHARE_GATE_BLOCKED');+ expect(mockApiHandler).toHaveBeenCalled();++ const write = await executor.execute(memoryPayload('addContextMemory'), {+ ...context,+ agentShareVisitor: {+ ...visitorIds,+ allowReadMemory: true,+ toolGrants: [{ identifier: 'lobe-user-memory' }],+ },+ });+ expect(write.error?.code).toBe('SHARE_GATE_BLOCKED');+ });+});diff --git a/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts b/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.tsindex d3fda0b1128..6d16f2d8797 100644--- a/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts@@ -88,6 +88,30 @@ describe('preprocessLhCommand', () => {expect(result.error).toBe('Failed to authenticate for CLI execution');expect(result.command).toBe('lh topic list');});++ // Belt-and-braces guard: `serverRuntimes/cloudSandbox.ts` already+ // short-circuits before ever calling this function for a share-visitor `lh`+ // command, but this function must independently refuse too — the caller+ // remembering to keep re-checking it must not be the only thing standing+ // between a share visitor and the creator's own JWT.+ it('should refuse and never sign a JWT when shareVisitorBlocked is set', async () => {+ mockSignUserJWT.mockClear();++ const result = await preprocessLhCommand('lh topic list', 'user-1', undefined, true);++ expect(result.isLhCommand).toBe(true);+ expect(result.error).toBe('The LobeHub CLI is unavailable in shared conversations.');+ expect(result.command).toBe('lh topic list');+ expect(mockSignUserJWT).not.toHaveBeenCalled();+ });++ it('should leave a non-lh command untouched even when shareVisitorBlocked is set', async () => {+ const result = await preprocessLhCommand('echo hello', 'user-1', undefined, true);++ expect(result.isLhCommand).toBe(false);+ expect(result.error).toBeUndefined();+ expect(result.command).toBe('echo hello');+ });});describe('isLhCommand', () => {diff --git a/apps/server/src/services/toolExecution/builtin.ts b/apps/server/src/services/toolExecution/builtin.tsindex b6ed68dbfbe..6a007e64557 100644--- a/apps/server/src/services/toolExecution/builtin.ts+++ b/apps/server/src/services/toolExecution/builtin.ts@@ -9,6 +9,7 @@ import { detectTruncatedJSON, safeParseJSON } from '@lobechat/utils';import debug from 'debug';import { UserModel } from '@/database/models/user';+import { isShareBlockedBuiltinDispatch } from '@/server/services/aiAgent/shareGate';import { ComposioService } from '@/server/services/composio';import { MarketService } from '@/server/services/market';@@ -116,6 +117,27 @@ export class BuiltinToolsExecutor implements IToolExecutor {const args = parsed || {};+ // Share-visitor gate at the ACTUAL dispatch site. The assembly-time tool-set+ // trim (`applyShareGateToToolSet`) only shapes what the model is offered —+ // 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+ // identifiers pass through (governed by the share's `toolGrants` at+ // assembly). Fail closed: block, never throw open.+ if (+ context.agentShareVisitor &&+ isShareBlockedBuiltinDispatch(context.agentShareVisitor, identifier, apiName, args)+ ) {+ log('Share gate blocked builtin dispatch: %s:%s', identifier, apiName);+ return {+ content: `The tool API ${identifier}:${apiName} is not available in this shared conversation.`,+ error: { code: 'SHARE_GATE_BLOCKED', message: 'Tool call blocked by agent share gate' },+ success: false,+ };+ }+log('Executing builtin tool: %s:%s (source: %s) with args: %O',identifier,diff --git a/apps/server/src/services/toolExecution/preprocessLhCommand.ts b/apps/server/src/services/toolExecution/preprocessLhCommand.tsindex 02f33dd3e4d..6ea87e739a3 100644--- a/apps/server/src/services/toolExecution/preprocessLhCommand.ts+++ b/apps/server/src/services/toolExecution/preprocessLhCommand.ts@@ -7,6 +7,10 @@ import { isDev } from '@/utils/env';const log = debug('lobe-server:lh-command');+/** Error surfaced when an Agent Share visitor's sandbox command tries to invoke the `lh` CLI. */+export const SHARE_VISITOR_LH_BLOCKED_MESSAGE =+ 'The LobeHub CLI is unavailable in shared conversations.';+export interface PreprocessResult {command: string;error?: string;@@ -115,11 +119,33 @@ export const preprocessLhCommand = async (command: string,userId: string,workspaceId?: string,+ /**+ * Belt-and-braces guard: true when the caller is executing inside an Agent+ * Share visitor's run (`context.agentShareVisitor` set). The visitor's+ * shell command is model-supplied and the visitor fully controls it, so+ * minting `signUserJWT(userId)` here would hand them a JWT scoped to the+ * CREATOR's own account inside a shell they control.+ * `serverRuntimes/cloudSandbox.ts` already short-circuits before ever+ * reaching this function for a share-visitor `lh` command — this second+ * check exists so the refusal doesn't rely solely on that caller+ * remembering to keep re-checking it.+ */+ shareVisitorBlocked = false,): Promise<PreprocessResult> => {if (!isLhCommand(command)) {return { command, isLhCommand: false, skipSkillLookup: false };}+ if (shareVisitorBlocked) {+ log('Refused lh command for Agent Share visitor run (user %s)', userId);+ return {+ command,+ error: SHARE_VISITOR_LH_BLOCKED_MESSAGE,+ isLhCommand: true,+ skipSkillLookup: true,+ };+ }+try {const jwt = await signUserJWT(userId);diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.tsindex 33c5fc1a15b..0859bea0666 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts@@ -32,6 +32,7 @@ vi.mock('@/server/services/sandbox', () => ({vi.mock('@/server/services/toolExecution/preprocessLhCommand', () => ({isLhCommand: (command: string) => command.startsWith('lh'),preprocessLhCommand: mocks.preprocessLhCommand,+ SHARE_VISITOR_LH_BLOCKED_MESSAGE: 'The LobeHub CLI is unavailable in shared conversations.',}));const buildContext = (overrides: Record<string, unknown> = {}) =>@@ -79,6 +80,7 @@ describe('cloudSandboxRuntime', () => {'lh agent edit agt_1 -t x','user-1','ws-42',+ false,);expect(mocks.sandboxService.callTool).toHaveBeenCalledWith('runCommand',@@ -135,6 +137,44 @@ describe('cloudSandboxRuntime', () => {expect(result.state).toMatchObject({ success: false });});+ // `lobe-cloud-sandbox` is allowlisted for Agent Share visitors specifically+ // because this shim never mints the creator's JWT for them — a visitor+ // controls the shell command, so an `lh` invocation must fail closed+ // instead of ever reaching `preprocessLhCommand` (which would sign a+ // creator-scoped token).+ it('refuses an lh command outright for a share-visitor run, without preprocessing or touching the sandbox', async () => {+ const { cloudSandboxRuntime } = await import('../cloudSandbox');+ const runtime = await cloudSandboxRuntime.factory(+ buildContext({ agentShareVisitor: { agentId: 'agent-1' } }),+ );++ const result = await runtime.runCommand({ command: 'lh agent list', description: 'list' });++ expect(mocks.preprocessLhCommand).not.toHaveBeenCalled();+ expect(mocks.sandboxService.callTool).not.toHaveBeenCalled();+ expect(result.state).toMatchObject({ success: false });+ });++ // Belt-and-braces: even though the short-circuit above already stops an+ // `lh` command before this call, every OTHER shell command in a+ // share-visitor run still threads `shareVisitorBlocked: true` through to+ // `preprocessLhCommand` (4th arg), so its own internal guard stays armed+ // independent of the caller-side check.+ it('still runs a non-lh command normally for a share-visitor run, marking it share-visitor-blocked', async () => {+ const { cloudSandboxRuntime } = await import('../cloudSandbox');+ const runtime = await cloudSandboxRuntime.factory(+ buildContext({ agentShareVisitor: { agentId: 'agent-1' } }),+ );++ await runtime.runCommand({ command: 'ls -la', description: 'list files' });++ expect(mocks.preprocessLhCommand).toHaveBeenCalledWith('ls -la', 'user-1', undefined, true);+ expect(mocks.sandboxService.callTool).toHaveBeenCalledWith(+ 'runCommand',+ expect.objectContaining({ command: 'ls -la' }),+ );+ });+it('keeps delegating exportAndUploadFile through the wrapper', async () => {mocks.sandboxService.exportAndUploadFile.mockResolvedValue({filename: 'result.csv',diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.tsindex 7a2d2bb7b54..fd99a97843a 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts@@ -84,6 +84,40 @@ describe('credsRuntime', () => {'userId is required for Creds execution',);});++ // `lobe-creds` is already absent from `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS`,+ // so this runtime should never even be constructed for a share visitor —+ // this is the belt-and-braces backstop in case that allowlist gate is ever+ // bypassed: the sandbox write path must refuse on its own too, since+ // `~/.creds/env` must never receive the creator's decrypted credentials+ // inside a sandbox a visitor's model can run arbitrary shell commands in.+ it('refuses to write credentials into the sandbox for a share-visitor run', async () => {+ vi.mocked(MarketService).mockImplementation(+ () =>+ ({+ market: {+ creds: {+ inject: vi.fn().mockResolvedValue({+ credentials: { env: { FOO: 'bar' } },+ }),+ },+ },+ }) as any,+ );++ const runtime = await credsRuntime.factory({+ agentShareVisitor: { agentId: 'agent-1' } as any,+ serverDB,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ });++ const result = await (runtime as any).injectCredsToSandbox({ keys: ['FOO'] });++ expect(result.success).toBe(false);+ expect(result.error?.message).toContain('unavailable in shared conversations');+ });});describe('ServerCredsService.injectCreds', () => {diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/imageGeneration.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/imageGeneration.test.tsindex 149e22f6c7a..4aa61c7477e 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/imageGeneration.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/imageGeneration.test.ts@@ -2,12 +2,22 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { imageGenerationRuntime } from '../imageGeneration';+// Narrow shape of the `callerContext` the runtime passes to every+// `*Router.createCaller`, just enough to type-check the spend-attribution+// assertions below without pulling in the full tRPC caller context type.+interface ImageCallerContext {+ spendOrigin?: {+ agentShare: { agentId: string; shareId: string; visitorUserId: string };+ trigger: string;+ };+}+const callerMocks = vi.hoisted(() => ({aiModel: vi.fn(() => ({})),aiProvider: vi.fn(() => ({})),generation: vi.fn(() => ({})),generationTopic: vi.fn(() => ({})),- image: vi.fn(() => ({})),+ image: vi.fn((_ctx: ImageCallerContext) => ({})),}));vi.mock('@/server/routers/lambda/aiModel', () => ({@@ -56,6 +66,36 @@ describe('imageGenerationRuntime', () => {expect(callerMocks.image).toHaveBeenCalledWith(callerContext);});+ it('projects share attribution onto the image caller so visitor spend stays attributed', () => {+ imageGenerationRuntime.factory({+ agentShareVisitor: {+ agentId: 'agent-1',+ allowReadMemory: true,+ toolGrants: [{ identifier: 'lobe-image-generation' }],+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ toolManifestMap: {},+ userId: 'creator-1',+ });++ const [callerContext] = callerMocks.image.mock.calls.at(-1)!;+ expect(callerContext.spendOrigin).toEqual({+ agentShare: { agentId: 'agent-1', shareId: 'share-1', visitorUserId: 'visitor-1' },+ trigger: 'agent_share',+ });+ // Permission fields of the runtime object must never leak into billing metadata.+ expect(callerContext.spendOrigin!.agentShare).not.toHaveProperty('allowReadMemory');+ expect(callerContext.spendOrigin!.agentShare).not.toHaveProperty('toolGrants');+ });++ it('omits spend attribution for a non-share run', () => {+ imageGenerationRuntime.factory({ toolManifestMap: {}, userId: 'user-1' });++ const [callerContext] = callerMocks.image.mock.calls.at(-1)!;+ expect(callerContext.spendOrigin).toBeUndefined();+ });+it('preserves public agent visibility for generated image topics', async () => {const createTopic = vi.fn().mockResolvedValue('topic-1');callerMocks.generationTopic.mockReturnValue({ createTopic });diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/topicReference.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/topicReference.test.tsindex 4e3bb2b7d6d..30a9f780a20 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/topicReference.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/topicReference.test.ts@@ -4,12 +4,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { type ToolExecutionContext } from '../../types';// Mock database models-const mockTopicModelFindById = vi.fn();+const mockTopicModelFindOwnTopicById = vi.fn();const mockMessageModelQuery = vi.fn();vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({- findById: (...args: any[]) => mockTopicModelFindById(...args),+ findOwnTopicById: (...args: any[]) => mockTopicModelFindOwnTopicById(...args),})),}));@@ -74,7 +74,7 @@ describe('topicReferenceRuntime', () => {workspaceId: 'workspace-1',});- mockTopicModelFindById.mockResolvedValue({ id: 'topic-1', title: 'Topic' });+ mockTopicModelFindOwnTopicById.mockResolvedValue({ id: 'topic-1', title: 'Topic' });mockMessageModelQuery.mockResolvedValue([]);await runtime.getTopicContext({ topicId: 'topic-1' });@@ -112,7 +112,7 @@ describe('topicReferenceRuntime', () => {});it('should return error when topic is not found', async () => {- mockTopicModelFindById.mockResolvedValue(null);+ mockTopicModelFindOwnTopicById.mockResolvedValue(null);const result = await runtime.getTopicContext({ topicId: 'topic-123' });@@ -120,11 +120,11 @@ describe('topicReferenceRuntime', () => {content: 'Topic not found: topic-123',success: false,});- expect(mockTopicModelFindById).toHaveBeenCalledWith('topic-123');+ expect(mockTopicModelFindOwnTopicById).toHaveBeenCalledWith('topic-123');});it('should return historySummary when topic has one', async () => {- mockTopicModelFindById.mockResolvedValue({+ mockTopicModelFindOwnTopicById.mockResolvedValue({historySummary: 'This is a summary of the conversation.',id: 'topic-123',title: 'My Topic',@@ -141,7 +141,7 @@ describe('topicReferenceRuntime', () => {});it('should use "Untitled" when topic has no title and has historySummary', async () => {- mockTopicModelFindById.mockResolvedValue({+ mockTopicModelFindOwnTopicById.mockResolvedValue({historySummary: 'Summary content',id: 'topic-123',title: null,@@ -154,7 +154,7 @@ describe('topicReferenceRuntime', () => {});it('should fallback to messages when topic has no historySummary', async () => {- mockTopicModelFindById.mockResolvedValue({+ mockTopicModelFindOwnTopicById.mockResolvedValue({agentId: 'agent-1',groupId: 'group-1',id: 'topic-123',@@ -182,7 +182,7 @@ describe('topicReferenceRuntime', () => {});it('should pass undefined agentId/groupId when topic has none', async () => {- mockTopicModelFindById.mockResolvedValue({+ mockTopicModelFindOwnTopicById.mockResolvedValue({id: 'topic-123',title: 'Simple Topic',});@@ -199,7 +199,7 @@ describe('topicReferenceRuntime', () => {});it('should limit messages to last 30', async () => {- mockTopicModelFindById.mockResolvedValue({+ mockTopicModelFindOwnTopicById.mockResolvedValue({id: 'topic-123',title: 'Long Chat',});@@ -222,7 +222,7 @@ describe('topicReferenceRuntime', () => {});it('should skip messages with empty content', async () => {- mockTopicModelFindById.mockResolvedValue({+ mockTopicModelFindOwnTopicById.mockResolvedValue({id: 'topic-123',title: 'Topic',});@@ -245,7 +245,7 @@ describe('topicReferenceRuntime', () => {});it('should handle non-user and non-assistant roles', async () => {- mockTopicModelFindById.mockResolvedValue({+ mockTopicModelFindOwnTopicById.mockResolvedValue({id: 'topic-123',title: 'Topic',});@@ -264,7 +264,7 @@ describe('topicReferenceRuntime', () => {it('should return error when topic model throws', async () => {const error = new Error('Database connection failed');- mockTopicModelFindById.mockRejectedValue(error);+ mockTopicModelFindOwnTopicById.mockRejectedValue(error);const result = await runtime.getTopicContext({ topicId: 'topic-123' });@@ -274,7 +274,7 @@ describe('topicReferenceRuntime', () => {});it('should return error when message model throws', async () => {- mockTopicModelFindById.mockResolvedValue({+ mockTopicModelFindOwnTopicById.mockResolvedValue({id: 'topic-123',title: 'Topic',});@@ -290,7 +290,7 @@ describe('topicReferenceRuntime', () => {});it('should handle non-Error exceptions', async () => {- mockTopicModelFindById.mockRejectedValue('string error');+ mockTopicModelFindOwnTopicById.mockRejectedValue('string error');const result = await runtime.getTopicContext({ topicId: 'topic-123' });@@ -299,7 +299,7 @@ describe('topicReferenceRuntime', () => {});it('should handle null message content', async () => {- mockTopicModelFindById.mockResolvedValue({+ mockTopicModelFindOwnTopicById.mockResolvedValue({id: 'topic-123',title: 'Topic',});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.tsindex a98d6dca81c..7e9cd98487e 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts@@ -1,5 +1,6 @@import { CloudSandboxIdentifier, type ISandboxService } from '@lobechat/builtin-tool-cloud-sandbox';import { CloudSandboxExecutionRuntime } from '@lobechat/builtin-tool-cloud-sandbox/executionRuntime';+import debug from 'debug';import { UserModel } from '@/database/models/user';import { FileService } from '@/server/services/file';@@ -8,11 +9,14 @@ import { createSandboxService } from '@/server/services/sandbox';import {isLhCommand,preprocessLhCommand,+ SHARE_VISITOR_LH_BLOCKED_MESSAGE,} from '@/server/services/toolExecution/preprocessLhCommand';import { resolveContentWorkspaceId } from './resolveWorkspaceScope';import { type ServerRuntimeRegistration } from './types';+const log = debug('lobe-server:cloud-sandbox');+/** Sandbox tools whose `command` param can carry an `lh` invocation. */const SHELL_TOOL_NAMES = new Set(['execScript', 'runCommand']);@@ -24,12 +28,23 @@ const SHELL_TOOL_NAMES = new Set(['execScript', 'runCommand']);* model that reaches for the cloud-sandbox shell instead of the skills one —* both expose a `runCommand` and nothing tells the model they differ — gets a* bare `lh: not found` for a command the platform advertises.+ *+ * `isShareVisitor` (set from `context.agentShareVisitor`, see the factory+ * below) disables the shim entirely: a share visitor's run executes under the+ * creator's identity, so the shim's `lh() { LOBEHUB_JWT=… }` prelude would+ * otherwise hand a JWT scoped to the CREATOR's own account into a shell the+ * VISITOR fully controls. `lobe-cloud-sandbox` is allowlisted for share+ * visitors specifically because this shim is skipped for them — see+ * `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS` in `@lobechat/builtin-tools`.*/const withLhPreprocessing = (service: ISandboxService,resolve: {userId: string;+ /** Raw context workspace id, log-only — cheap to read, unlike {@link resolveContentWorkspaceId}. */+ workspaceIdHint: string | undefined;workspaceId: () => Promise<string | undefined>;+ isShareVisitor: boolean;},): ISandboxService => ({// Delegated explicitly rather than spread: `createSandboxService` returns a@@ -40,8 +55,37 @@ const withLhPreprocessing = (return service.callTool(toolName, params);}+ // Fail closed BEFORE any workspace/JWT resolution: a share visitor never+ // gets the `lh` shim, so an `lh` invocation in their sandbox command+ // returns a plain error result the model can react to, instead of+ // silently falling through to `preprocessLhCommand` (which independently+ // refuses too — see its `shareVisitorBlocked` param — but this is the+ // primary, intended-to-be-load-bearing check).+ if (resolve.isShareVisitor && isLhCommand(command)) {+ // Deliberately no command content: it is visitor/model-controlled and+ // may carry an inline token — same as the `preprocessLhCommand` refusal.+ log(+ 'Refused lh command for share visitor (user %s, workspace %s)',+ resolve.userId,+ resolve.workspaceIdHint,+ );+ return {+ error: {+ message: SHARE_VISITOR_LH_BLOCKED_MESSAGE,+ name: 'ShareVisitorBlocked',+ },+ result: null,+ success: false,+ };+ }+const workspaceId = isLhCommand(command) ? await resolve.workspaceId() : undefined;- const result = await preprocessLhCommand(command, resolve.userId, workspaceId);+ const result = await preprocessLhCommand(+ command,+ resolve.userId,+ workspaceId,+ resolve.isShareVisitor,+ );if (result.error) {return {@@ -98,8 +142,10 @@ export const cloudSandboxRuntime: ServerRuntimeRegistration = {return new CloudSandboxExecutionRuntime(withLhPreprocessing(sandboxService, {+ isShareVisitor: Boolean(context.agentShareVisitor),userId: context.userId,workspaceId: () => (workspaceIdPromise ??= resolveContentWorkspaceId(context)),+ workspaceIdHint: context.workspaceId,}),);},diff --git a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts b/apps/server/src/services/toolExecution/serverRuntimes/creds.tsindex a07fa060950..7d35a5dcaa1 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/creds.ts@@ -18,9 +18,25 @@ export class ServerCredsService implements ICredsService {private marketService: MarketService;private workspaceId?: string;- constructor(marketService: MarketService, workspaceId?: string) {+ private isShareVisitor: boolean;++ constructor(+ marketService: MarketService,+ workspaceId?: string,+ /**+ * Belt-and-braces guard: true for an Agent Share visitor's run+ * (`context.agentShareVisitor` set). `lobe-creds` is already absent from+ * `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS`, so this runtime should never+ * be constructed for a visitor in the first place — but `injectCreds`+ * refuses again here too, so the guarantee that the creator's decrypted+ * credentials never land in a sandbox a visitor controls doesn't rest on+ * the allowlist alone.+ */+ isShareVisitor = false,+ ) {this.marketService = marketService;this.workspaceId = workspaceId;+ this.isShareVisitor = isShareVisitor;}/**@@ -110,6 +126,16 @@ export class ServerCredsService implements ICredsService {}> {log('injectCreds: keys=%O, topicId=%s', params.keys, params.topicId);+ // Refuse before the Market call, not after: Market's inject endpoint+ // writes the creator's REAL credentials into the sandbox's ~/.creds/env+ // server-side as part of handling the request (see the comment below),+ // so for a share visitor the only safe place to stop is here.+ if (this.isShareVisitor) {+ throw new Error(+ 'Credential injection into the sandbox is unavailable in shared conversations.',+ );+ }+// Market's generic inject endpoint resolves organization credentials from// the workspaceId signed into this service's trusted-client token, and —// when `sandbox` is true (the default) — already writes the *real*@@ -209,7 +235,11 @@ export const credsRuntime: ServerRuntimeRegistration = {userInfo: { userId: context.userId, workspaceId: context.workspaceId },});- const credsService = new ServerCredsService(marketService, context.workspaceId);+ const credsService = new ServerCredsService(+ marketService,+ context.workspaceId,+ Boolean(context.agentShareVisitor),+ );return new CredsExecutionRuntime(credsService, {topicId: context.topicId,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/imageGeneration.ts b/apps/server/src/services/toolExecution/serverRuntimes/imageGeneration.tsindex 28b482cff5d..49589f65166 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/imageGeneration.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/imageGeneration.ts@@ -1,6 +1,7 @@import type { ImageGenerationModelSummary } from '@lobechat/builtin-tool-image-generation';import { ImageGenerationIdentifier } from '@lobechat/builtin-tool-image-generation';import { ImageGenerationExecutionRuntime } from '@lobechat/builtin-tool-image-generation/executionRuntime';+import { RequestTrigger, toAgentShareVisitorIds } from '@lobechat/types';import type { AiProviderModelListItem } from 'model-bank';import { aiModelRouter } from '@/server/routers/lambda/aiModel';@@ -29,6 +30,19 @@ export const imageGenerationRuntime: ServerRuntimeRegistration = {const callerContext = {clientIp: context.clientIp,+ /**+ * A share-visitor run executes under the shared agent's CREATOR, so the+ * image spend it triggers is indistinguishable from the creator's own+ * usage unless the origin is stamped on the charge. Projected fields+ * only — never spread `context.agentShareVisitor`, which also carries the+ * run's tool/memory permissions.+ */+ spendOrigin: context.agentShareVisitor+ ? {+ agentShare: toAgentShareVisitorIds(context.agentShareVisitor),+ trigger: RequestTrigger.AgentShare,+ }+ : undefined,userId: context.userId,workspaceId: context.workspaceId,};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/memory.ts b/apps/server/src/services/toolExecution/serverRuntimes/memory.tsindex 2eb7a8ff741..024116b8759 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/memory.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/memory.ts@@ -29,9 +29,10 @@ import type {RemoveIdentityMemoryResult,SearchMemoryParams,SearchMemoryResult,+ SpendOrigin,UpdateIdentityMemoryResult,} from '@lobechat/types';-import { LayersEnum } from '@lobechat/types';+import { LayersEnum, RequestTrigger, toAgentShareVisitorIds } from '@lobechat/types';import { eq } from 'drizzle-orm';import type { z } from 'zod';@@ -113,6 +114,7 @@ const createEmbedder = (agentRuntime: UserMemoryEmbeddingRuntime,embeddingModel: string,userId: string,+ spendOrigin?: SpendOrigin,) => {return async (value?: string | null): Promise<number[] | undefined> => {if (!value || value.trim().length === 0) return undefined;@@ -122,6 +124,7 @@ const createEmbedder = (model: embeddingModel,runtime: agentRuntime,source: 'toolRuntime:userMemory.tool',+ spendOrigin,userId,});@@ -141,6 +144,12 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {private topicId?: string;private memoryEffort: MemoryEffort;private memoryEmbeddingRuntime?: ToolExecutionMemoryEmbeddingRuntime;+ /**+ * Origin attribution stamped on every embedding this runtime bills. Set only+ * for a shared-agent visitor run, whose embeddings are otherwise billed to+ * the creator as ordinary memory usage.+ */+ private spendOrigin?: SpendOrigin;private userId: string;private workspaceId?: string;@@ -153,6 +162,7 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {memoryModel: UserMemoryModel;operationId?: string;serverDB: LobeChatDatabase;+ spendOrigin?: SpendOrigin;taskId?: string;toolCallId?: string;topicId?: string;@@ -170,6 +180,7 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {this.topicId = options.topicId;this.memoryEffort = options.memoryEffort;this.memoryEmbeddingRuntime = options.memoryEmbeddingRuntime;+ this.spendOrigin = options.spendOrigin;this.userId = options.userId;this.workspaceId = options.workspaceId;}@@ -240,6 +251,7 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {model: embeddingModel,runtime: modelRuntime,source: 'toolRuntime:userMemory.search',+ spendOrigin: this.spendOrigin,userId: this.userId,})).filter((embedding): embedding is number[] => Boolean(embedding))@@ -286,7 +298,7 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {this.userId,this.workspaceId,);- const embed = createEmbedder(agentRuntime, embeddingModel, this.userId);+ const embed = createEmbedder(agentRuntime, embeddingModel, this.userId, this.spendOrigin);const summaryEmbedding = await embed(input.summary);const detailsEmbedding = await embed(input.details);@@ -358,7 +370,7 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {this.userId,this.workspaceId,);- const embed = createEmbedder(agentRuntime, embeddingModel, this.userId);+ const embed = createEmbedder(agentRuntime, embeddingModel, this.userId, this.spendOrigin);const summaryEmbedding = await embed(input.summary);const detailsEmbedding = await embed(input.details);@@ -437,7 +449,7 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {this.userId,this.workspaceId,);- const embed = createEmbedder(agentRuntime, embeddingModel, this.userId);+ const embed = createEmbedder(agentRuntime, embeddingModel, this.userId, this.spendOrigin);const summaryEmbedding = await embed(input.summary);const detailsEmbedding = await embed(input.details);@@ -510,7 +522,7 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {this.userId,this.workspaceId,);- const embed = createEmbedder(agentRuntime, embeddingModel, this.userId);+ const embed = createEmbedder(agentRuntime, embeddingModel, this.userId, this.spendOrigin);const summaryEmbedding = await embed(input.summary);const detailsEmbedding = await embed(input.details);@@ -595,7 +607,7 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {this.userId,this.workspaceId,);- const embed = createEmbedder(agentRuntime, embeddingModel, this.userId);+ const embed = createEmbedder(agentRuntime, embeddingModel, this.userId, this.spendOrigin);const summaryEmbedding = await embed(input.summary);const detailsEmbedding = await embed(input.details);@@ -672,7 +684,7 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {this.userId,this.workspaceId,);- const embed = createEmbedder(agentRuntime, embeddingModel, this.userId);+ const embed = createEmbedder(agentRuntime, embeddingModel, this.userId, this.spendOrigin);let summaryVector1024: number[] | null | undefined;if (input.set.summary !== undefined) {@@ -901,6 +913,14 @@ export const memoryRuntime: ServerRuntimeRegistration = {memoryModel,operationId: context.operationId,serverDB: context.serverDB,+ // Projected fields only — `context.agentShareVisitor` also carries the+ // run's tool/memory permissions, which have no place in billing metadata.+ spendOrigin: context.agentShareVisitor+ ? {+ agentShare: toAgentShareVisitorIds(context.agentShareVisitor),+ trigger: RequestTrigger.AgentShare,+ }+ : undefined,taskId: context.taskId,toolCallId: context.toolCallId,topicId: context.topicId,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.tsindex 72cd2407ec1..ed721059b1a 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts@@ -182,6 +182,9 @@ class SkillServerRuntimeService implements SkillRuntimeService {): Promise<{ command: string; error?: string }> => {const workspaceId =this.workspaceId ?? (isLhCommand(command) ? await this.resolveWorkspaceId() : undefined);+ // No `shareVisitorBlocked` guard needed here: `lobe-skills` is absent from+ // `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS`, so this runtime is never+ // constructed for an Agent Share visitor's run in the first place.const result = await preprocessLhCommand(command, this.userId, workspaceId);return { command: result.command, error: result.error };diff --git a/apps/server/src/services/toolExecution/serverRuntimes/topicReference.ts b/apps/server/src/services/toolExecution/serverRuntimes/topicReference.tsindex 7215f493465..dbd0390d7ee 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/topicReference.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/topicReference.ts@@ -33,7 +33,10 @@ class TopicReferenceExecutionRuntime {try {const topicModel = new TopicModel(this.db, this.userId, this.workspaceId);- const topic = await topicModel.findById(topicId);+ // `findOwnTopicById`: this tool runs under the account owner's identity,+ // so a raw topic id must never resolve to an agent-share visitor topic+ // (those are stored under the creator's userId).+ const topic = await topicModel.findOwnTopicById(topicId);if (!topic) {return { content: `Topic not found: ${topicId}`, success: false };diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.tsindex 822bb5dd55a..51842df3604 100644--- a/apps/server/src/services/toolExecution/types.ts+++ b/apps/server/src/services/toolExecution/types.ts@@ -1,6 +1,7 @@import { type LobeToolManifest } from '@lobechat/context-engine';import { type LobeChatDatabase } from '@lobechat/database';import {+ type AgentShareVisitorContext,type ChatToolPayload,type ClientSecretPayload,type ExecSubAgentParams,@@ -155,6 +156,26 @@ export interface ToolExecutionContext {* result; the member barrier backfills + resumes/finishes the parked supervisor.*/agentMember?: ServerAgentMemberRunner;+ /**+ * Shared-agent visitor marker, forwarded from+ * `RuntimeExecutorContext.agentShareVisitor` (see+ * `modules/AgentRuntime/context.ts`). Present ONLY for a share-visitor run.+ * `BuiltinToolsExecutor.execute` re-checks every builtin dispatch against+ * `isShareBlockedBuiltinDispatch` with these permissions — the unbypassable+ * counterpart of the assembly-time tool-set trim, which only shapes what the+ * model is OFFERED, not what the executor will run. That gate is strictly+ * wider than a plain data-tool check: master default-deny allowlist, the+ * owner's `toolGrants` picker, and humanIntervention policy, and it+ * internally delegates to `isShareBlockedDataToolCall` for the per-API+ * data-tool rules.+ *+ * Tool runtimes that trigger their own billed work (e.g. image generation)+ * project it with `toAgentShareVisitorIds` into a `spendOrigin` payload so+ * the resulting spend log is attributed to the shared agent, exactly like the+ * LLM path. Only those ids may be projected; never forward this object as a+ * whole, since its permission fields have no place in billing metadata.+ */+ agentShareVisitor?: AgentShareVisitorContext;/*** Visibility of the agent executing this tool call. Resolved once per tool* call in the runtime executor. Tool runtimes that persist agent side-effectsdiff --git a/apps/server/src/services/topicAutoSummary/index.test.ts b/apps/server/src/services/topicAutoSummary/index.test.tsindex 612d10236d3..1e6238beafe 100644--- a/apps/server/src/services/topicAutoSummary/index.test.ts+++ b/apps/server/src/services/topicAutoSummary/index.test.ts@@ -31,9 +31,9 @@ vi.mock('@/server/services/systemAgent/modelConfig', () => ({}),}));-const createDb = () => {- const results = [- [{ historySummary: 'Earlier decision: use PostgreSQL.' }],+const createDb = (+ results: unknown[][] = [+ [{ historySummary: 'Earlier decision: use PostgreSQL.', senderId: null }],[{content: 'What is next?',@@ -42,8 +42,8 @@ const createDb = () => {updatedAt: new Date('2026-07-31T10:00:00Z'),},],- ];-+ ],+) => {return {select: vi.fn(() => ({from: vi.fn(() => ({@@ -97,6 +97,20 @@ describe('TopicAutoSummaryService', () => {expect(mocks.generateObject).not.toHaveBeenCalled();});+ it('skips a share-visitor topic without invoking generation', async () => {+ // The topic row load returns a non-null senderId → visitor conversation.+ // These are creator-billed only through the share spend gate, so the+ // auto-summary worker must never call the LLM for them.+ const db = createDb([[{ historySummary: null, senderId: 'visitor-9' }]]);+ const service = new TopicAutoSummaryService(db, 'creator-1');++ const result = await service.summarize('shared-topic');++ expect(result).toEqual({ reason: 'disabled', summarized: false });+ expect(mocks.generateObject).not.toHaveBeenCalled();+ expect(mocks.updateSummaryIfCurrent).not.toHaveBeenCalled();+ });+it('still summarizes an opted-out user when forced', async () => {mocks.getUserSettings.mockResolvedValue({systemAgent: { topicAutoSummary: { enabled: false } },diff --git a/apps/server/src/services/topicAutoSummary/index.ts b/apps/server/src/services/topicAutoSummary/index.tsindex 1f6ef47f799..bfb2673f806 100644--- a/apps/server/src/services/topicAutoSummary/index.ts+++ b/apps/server/src/services/topicAutoSummary/index.ts@@ -6,6 +6,7 @@ import {TOPIC_AUTO_SUMMARY_PROMPT_VERSION,} from '@lobechat/prompts';import type { SystemAgentItem, UserSystemAgentConfig } from '@lobechat/types';+import debug from 'debug';import { and, desc, eq } from 'drizzle-orm';import { topicSummaryEligibleMessage, TopicSummaryModel } from '@/database/models/topicSummary';@@ -15,6 +16,8 @@ import type { LobeChatDatabase } from '@/database/type';import { AiGenerationService } from '@/server/services/aiGeneration';import { resolveSystemAgentModelConfig } from '@/server/services/systemAgent/modelConfig';+const log = debug('lobe-server:service:topic-auto-summary');+const MAX_MESSAGES = 80;const MAX_MESSAGE_CHARS = 12_000;const MAX_PREVIOUS_SUMMARY_CHARS = 20_000;@@ -51,10 +54,21 @@ export class TopicAutoSummaryService {? eq(topics.workspaceId, this.workspaceId): eq(topics.userId, this.userId);const [topic] = await this.db- .select({ historySummary: topics.historySummary })+ .select({ historySummary: topics.historySummary, senderId: topics.senderId }).from(topics).where(and(eq(topics.id, topicId), topicOwnership)).limit(1);+ // Share-visitor topics are creator-billed only through the share spend+ // gate. Reject them defensively before any LLM call — the dispatch query+ // and TopicSummaryModel.updateSummaryIfCurrent both filter them out, this+ // guard covers replays / direct callers that skip the dispatch path.+ if (topic?.senderId) {+ log(+ 'skipping share-visitor topic %s: visitor turns are outside the auto-summary scope',+ topicId,+ );+ return { reason: 'disabled', summarized: false };+ }const recent = await this.db.select({content: messages.content,diff --git a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.tsindex 23a2c432331..255765374b3 100644--- a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts+++ b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts@@ -6,6 +6,7 @@ import { AcceptanceService } from '../acceptanceService';const mocks = vi.hoisted(() => ({attachToAcceptance: vi.fn(),findById: vi.fn(),+ findOwnTopicById: vi.fn(),findPolicyById: vi.fn(),findReportByRun: vi.fn(),findRunById: vi.fn(),@@ -42,7 +43,9 @@ vi.mock('@/database/models/verifyReport', () => ({vi.mock('@/database/models/task', () => ({TaskModel: vi.fn(() => ({ resolve: mocks.taskResolve })),}));-vi.mock('@/database/models/topic', () => ({ TopicModel: vi.fn() }));+vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn(() => ({ findOwnTopicById: mocks.findOwnTopicById })),+}));vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn() }));vi.mock('@/server/services/task', () => ({ TaskService: vi.fn() }));@@ -78,6 +81,18 @@ describe('AcceptanceService decision gating', () => {});});+ it('treats an agent-share visitor topic as a non-existent subject', async () => {+ // findOwnTopicById excludes visitor topics, so it resolves null here even+ // though the id exists as a raw row — the creator must not be able to+ // attach an acceptance to a visitor's conversation.+ mocks.findOwnTopicById.mockResolvedValue(undefined);++ await expect(+ service().ensureForSubject('topic', 'tpc-visitor-1', { requirement: 'The topic works' }),+ ).rejects.toThrow('topic "tpc-visitor-1" not found in the current workspace');+ expect(mocks.ensureForSubject).not.toHaveBeenCalled();+ });+it.each(['pending', 'planned', 'verifying', 'repairing'])('refuses to accept while the round chain is still %s',async (status) => {diff --git a/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.ts b/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.tsindex 09fd6240761..b54088636d1 100644--- a/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.ts+++ b/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.ts@@ -21,7 +21,7 @@ vi.mock('@/database/models/task', () => ({}));vi.mock('@/database/models/topic', () => ({TopicModel: class {- findByIds = mocks.resolveTopics;+ findOwnTopicsByIds = mocks.resolveTopics;},}));diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.tsindex a7a124551f2..bff15a5af8f 100644--- a/apps/server/src/services/verify/acceptanceService.ts+++ b/apps/server/src/services/verify/acceptanceService.ts@@ -480,7 +480,9 @@ export class AcceptanceService {return task ? { title: task.name ?? task.identifier } : null;}case 'topic': {- const topic = await new TopicModel(this.db, this.userId, this.workspaceId).findById(+ // Creator-facing lookup: an agent-share visitor topic must not be+ // treated as a valid acceptance subject for the creator.+ const topic = await new TopicModel(this.db, this.userId, this.workspaceId).findOwnTopicById(subjectId,);return topic ? { title: topic.title ?? null } : null;@@ -1027,7 +1029,9 @@ export class AcceptanceService {new TaskModel(this.db, this.userId, this.workspaceId).resolveMany(idsByType.get('task') ?? [],),- new TopicModel(this.db, this.userId, this.workspaceId).findByIds(+ // Creator-facing lookup: exclude agent-share visitor topics from the+ // subject summary batch.+ new TopicModel(this.db, this.userId, this.workspaceId).findOwnTopicsByIds(idsByType.get('topic') ?? [],),new DocumentModel(this.db, this.userId, this.workspaceId).findByIds(diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex f396102e4ba..44aee57b918 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -289,6 +289,91 @@"channel.wechatTips": "Open WeChat on your phone, scan this code, and confirm. This code is single-use and expires in 5 minutes.","channel.wechatUserId": "WeChat User ID","channel.wechatUserIdHint": "WeChat account identifier returned by the authorization flow.",+ "share.entry": "Share this Agent",+ "share.settings.limits.desc": "Every visitor run is billed to your account, so these caps are what keep a shared link from running up your bill. They always apply — you can change the numbers, but not turn them off.",+ "share.settings.limits.maxTopicsPerVisitor": "Conversations per visitor",+ "share.settings.limits.maxTopicsPerVisitorHint": "How many separate conversations each signed-in visitor can start.",+ "share.settings.limits.maxTurnsPerTopic": "Turns per conversation",+ "share.settings.limits.maxTurnsPerTopicHint": "How many messages a visitor can send inside one conversation.",+ "share.settings.limits.monthlySpendLimit": "Monthly spend cap",+ "share.settings.limits.monthlySpendLimitHint": "Visitor runs stop once this month’s spend on this Agent reaches the cap.",+ "share.settings.limits.title": "Limits",+ "share.settings.link.copied": "Link copied",+ "share.settings.link.copy": "Copy link",+ "share.settings.link.desc": "Anyone signed in who has the link can chat with this Agent. Runs execute on your account.",+ "share.settings.link.disableConfirmContent": "Visitors lose access to the link right away. The link itself is kept, so turning sharing back on later republishes the exact same URL.",+ "share.settings.link.disableConfirmOk": "Turn off sharing",+ "share.settings.link.disableConfirmTitle": "Turn off sharing?",+ "share.settings.link.offHint": "Sharing is off. Turn it on to get a link you can hand out — turning it off again only pauses it, and the same link resumes whenever you turn it back on.",+ "share.settings.link.publishDisabled": "Sharing is not available on your account yet. You can still turn off a share you already published.",+ "share.settings.link.slugError.invalid": "Use lowercase letters, numbers and hyphens only, and don’t start or end with a hyphen.",+ "share.settings.link.slugError.reserved": "This word is reserved. Please pick another one.",+ "share.settings.link.slugError.taken": "This custom link is already taken.",+ "share.settings.link.slugError.tooLong": "Custom links can be at most 64 characters.",+ "share.settings.link.slugError.tooShort": "Custom links need at least 3 characters.",+ "share.settings.link.slugHint": "3–64 characters: lowercase letters, numbers and hyphens. Leave it empty to use the generated link.",+ "share.settings.link.slugLabel": "Custom link",+ "share.settings.link.slugPlaceholder": "my-agent",+ "share.settings.link.slugSaved": "Custom link updated",+ "share.settings.link.title": "Share link",+ "share.settings.link.viewCount": "{{views}} views",+ "share.settings.notice.desc": "Visitors don’t just read this Agent — they run it. Every reply is generated on your account and charged to your balance, and the Agent acts with whatever access you grant below.",+ "share.settings.notice.title": "Visitors run this Agent on your account",+ "share.settings.permissions.allowCreatorViewSessions": "Let me read visitor conversations",+ "share.settings.permissions.allowCreatorViewSessionsHint": "Off by default: visitor conversations stay private to the visitor.",+ "share.settings.permissions.allowReadMemory": "Allow reading my memory",+ "share.settings.permissions.allowReadMemoryHint": "The Agent may draw on your long-term memory while answering a visitor.",+ "share.settings.permissions.desc": "What a visitor’s run may read, and what the visitor gets to see back.",+ "share.settings.permissions.showErrorDetails": "Show error details to visitors",+ "share.settings.permissions.showErrorDetailsHint": "Off by default: visitors see a generic failure notice instead of raw error text.",+ "share.settings.permissions.showModelInfo": "Show which model is used",+ "share.settings.permissions.showModelInfoHint": "Off by default: your model and provider choice stays hidden.",+ "share.settings.permissions.title": "Permissions",+ "share.settings.title": "Share Agent",+ "share.settings.tools.apiNotAvailableToVisitors": "This action can never be used in a shared run — it either needs your approval or is otherwise off-limits to visitors.",+ "share.settings.tools.apiWritesOwnerData": "Visitors can never write to your memory — this action stays off in shared runs.",+ "share.settings.tools.availableGroup": "Not granted · {{count}}",+ "share.settings.tools.desc": "Only the tools you tick here can be called during a visitor run. Tools that could reach your device or local files are never offered.",+ "share.settings.tools.empty": "This Agent has no tools that can be granted to visitors.",+ "share.settings.tools.grantedEmpty": "No tools granted yet — visitors get a plain chat. Pick from the list below to grant one.",+ "share.settings.tools.grantedGroup": "Granted to visitors · {{count}}",+ "share.settings.tools.needsMemoryPermission": "Also turn on “Allow reading my memory” above, or this tool stays inert for visitors.",+ "share.settings.tools.notAvailableToVisitors": "This tool can never be used in a shared run — visitor runs are blocked from your knowledge base and Agent files.",+ "share.settings.tools.title": "Tools visitors can use",+ "share.settings.updateError": "Could not save the change. Please try again.",+ "share.settings.usage.conversations": "Conversations",+ "share.settings.usage.desc": "What this share has attracted, and what it has cost you.",+ "share.settings.usage.loadFailed": "Usage could not be loaded",+ "share.settings.usage.monthlySpend": "This month’s spend",+ "share.settings.usage.spendOfLimit": "${{spend}} of ${{limit}}",+ "share.settings.usage.title": "Usage",+ "share.settings.usage.views": "Visits",+ "share.settings.usage.visitors": "Visitors",+ "share.visitor.access.backHome": "Back to home",+ "share.visitor.access.forbidden": "You don't have access to this shared agent.",+ "share.visitor.access.notFound": "This share link is no longer available.",+ "share.visitor.access.signInCta": "Sign in",+ "share.visitor.access.signInDesc": "Sign in to start chatting with this shared agent. Your conversations stay tied to your account.",+ "share.visitor.access.signInTitle": "Sign in to continue",+ "share.visitor.errors.generic": "Failed to send the message. Please try again.",+ "share.visitor.errors.heterogeneousUnsupported": "This shared agent isn't available for visitor chat yet. Please contact its owner.",+ "share.visitor.errors.insufficientBudget": "This shared agent has run out of budget. Please contact its owner.",+ "share.visitor.errors.promptTooLong": "Your message is too long. Please shorten it to {{max}} characters or fewer and try again.",+ "share.visitor.errors.providerNotSupported": "This shared agent is not available right now. Please contact its owner.",+ "share.visitor.errors.sharingPaused": "The owner has paused sharing, so new messages are turned off.",+ "share.visitor.errors.spendLimit": "This shared agent has reached its monthly usage limit set by its creator. It will be available again next month.",+ "share.visitor.errors.stopFailed": "Couldn't stop the run. Please try again.",+ "share.visitor.errors.topicLimit": "You have reached the conversation limit on this shared agent.",+ "share.visitor.errors.turnLimit": "This conversation has reached its turn limit. Start a new conversation to continue.",+ "share.visitor.errors.unavailable": "This conversation is no longer available. Try switching to another topic or starting a new one.",+ "share.visitor.input.placeholder": "Message this shared agent…",+ "share.visitor.input.send": "Send",+ "share.visitor.input.stop": "Stop",+ "share.visitor.privacyNotice": "This conversation runs on the owner’s account and may be visible to them. Avoid sharing sensitive information.",+ "share.visitor.topics.empty": "No conversations yet",+ "share.visitor.topics.new": "New conversation",+ "share.visitor.topics.title": "Conversations",+ "share.visitor.topics.untitled": "Untitled conversation","transfer.button": "Move","transfer.confirm.botChannels": "Bot channel connections may need to be refreshed after moving","transfer.confirm.chatGroups": "Multi-agent group associations will be removed",diff --git a/locales/en-US/electron.json b/locales/en-US/electron.jsonindex b411c968ed1..e7784828588 100644--- a/locales/en-US/electron.json+++ b/locales/en-US/electron.json@@ -5,6 +5,7 @@"gateway.statusConnecting": "This device is connecting to Gateway...","gateway.statusDisconnected": "This device is not connected to Gateway","gateway.title": "Device Gateway",+ "navigation.agentShare": "Share","navigation.agents": "Agents","navigation.apps": "Apps","navigation.channels": "Channels",@@ -50,6 +51,7 @@"navigation.resources": "Resources","navigation.selfLearning": "Self-evolving","navigation.settings": "Settings",+ "navigation.sharedAgent": "Shared Agent","navigation.stats": "Statistics","navigation.task": "Task","navigation.tasks": "Tasks",diff --git a/locales/en-US/error.json b/locales/en-US/error.jsonindex 987f635fbf1..c4bd1b15540 100644--- a/locales/en-US/error.json+++ b/locales/en-US/error.json@@ -126,6 +126,7 @@"transfer.ownerOnly": "Only workspace owners can transfer resources created by other members.","transfer.resourceNotFound": "This resource no longer exists or you no longer have access. Refresh and try again.","transfer.sameWorkspace": "This resource is already in the selected workspace. Choose another target.",+ "transfer.sharedTransferBlocked": "This agent has a share link, so its owner cannot be changed.","transfer.targetIsCurrentOwner": "This agent already belongs to that member. Pick someone else.","transfer.targetNoWriteAccess": "You need Member or Owner access to move resources into the target workspace.","transfer.targetNotWorkspaceMember": "The selected recipient is not an active member of this workspace. Refresh the member list and try again.",diff --git a/locales/en-US/spend.json b/locales/en-US/spend.jsonindex 0cacdd4f82a..27c6f198e00 100644--- a/locales/en-US/spend.json+++ b/locales/en-US/spend.json@@ -12,6 +12,7 @@"table.columns.spend": "Credits","table.columns.time": "Time","table.columns.totalTokens": "Token Usage",+ "table.columns.trigger.enums.agent_share": "Agent Share","table.columns.trigger.enums.agent_signal": "Agent Signal","table.columns.trigger.enums.api": "API Call","table.columns.trigger.enums.bot": "Bot Message",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex ede6231446b..b8c0f1436b4 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -289,6 +289,91 @@"channel.wechatTips": "请在手机上打开微信,扫描此二维码并确认。此二维码仅可使用一次,有效期为 5 分钟。","channel.wechatUserId": "微信用户 ID","channel.wechatUserIdHint": "通过授权流程返回的微信账号标识符。",+ "share.entry": "分享此助手",+ "share.settings.limits.desc": "访客的每次运行都记在你的账户上,这些上限是分享链接不会跑出高额账单的唯一保障。上限始终生效,你可以调整数值,但不能关闭。",+ "share.settings.limits.maxTopicsPerVisitor": "每位访客的会话数",+ "share.settings.limits.maxTopicsPerVisitorHint": "每位已登录访客最多能发起多少个独立会话。",+ "share.settings.limits.maxTurnsPerTopic": "每个会话的轮次",+ "share.settings.limits.maxTurnsPerTopicHint": "访客在一个会话里最多能发送多少条消息。",+ "share.settings.limits.monthlySpendLimit": "每月消耗上限",+ "share.settings.limits.monthlySpendLimitHint": "本月该助手的消耗达到上限后,访客将无法继续运行。",+ "share.settings.limits.title": "使用限制",+ "share.settings.link.copied": "链接已复制",+ "share.settings.link.copy": "复制链接",+ "share.settings.link.desc": "任何拿到链接并已登录的人都能和这个助手对话,运行都发生在你的账户上。",+ "share.settings.link.disableConfirmContent": "访客会立即无法访问。链接本身会保留,之后重新开启分享时仍然是同一个链接。",+ "share.settings.link.disableConfirmOk": "关闭分享",+ "share.settings.link.disableConfirmTitle": "要关闭分享吗?",+ "share.settings.link.offHint": "分享已关闭。开启后会生成一条可以分发的链接;再次关闭只是暂停访问,重新开启时链接保持不变。",+ "share.settings.link.publishDisabled": "分享功能暂未对你的账号开放。已经分享出去的链接仍然可以关闭。",+ "share.settings.link.slugError.invalid": "只能使用小写字母、数字和连字符,且不能以连字符开头或结尾。",+ "share.settings.link.slugError.reserved": "这是保留词,请换一个。",+ "share.settings.link.slugError.taken": "这个自定义链接已被占用。",+ "share.settings.link.slugError.tooLong": "自定义链接最多 64 个字符。",+ "share.settings.link.slugError.tooShort": "自定义链接至少需要 3 个字符。",+ "share.settings.link.slugHint": "3–64 个字符,仅支持小写字母、数字和连字符。留空则使用系统生成的链接。",+ "share.settings.link.slugLabel": "自定义链接",+ "share.settings.link.slugPlaceholder": "my-agent",+ "share.settings.link.slugSaved": "自定义链接已更新",+ "share.settings.link.title": "分享链接",+ "share.settings.link.viewCount": "被浏览 {{views}} 次",+ "share.settings.notice.desc": "访客不只是查看这个助手,而是真的在运行它。每一次回复都由你的账户生成并扣你的余额,助手也会带着你在下面授予的权限行动。",+ "share.settings.notice.title": "访客将在你的账户上运行此助手",+ "share.settings.permissions.allowCreatorViewSessions": "允许我查看访客会话",+ "share.settings.permissions.allowCreatorViewSessionsHint": "默认关闭:访客的会话内容只有访客自己能看到。",+ "share.settings.permissions.allowReadMemory": "允许读取我的记忆",+ "share.settings.permissions.allowReadMemoryHint": "助手在回答访客时可以参考你的长期记忆。",+ "share.settings.permissions.desc": "访客的运行可以读取什么,以及访客能看到什么。",+ "share.settings.permissions.showErrorDetails": "向访客展示错误详情",+ "share.settings.permissions.showErrorDetailsHint": "默认关闭:访客只会看到一句通用的失败提示,而不是原始报错。",+ "share.settings.permissions.showModelInfo": "展示使用的模型",+ "share.settings.permissions.showModelInfoHint": "默认关闭:不向访客暴露你选择的模型和服务商。",+ "share.settings.permissions.title": "权限",+ "share.settings.title": "分享助手",+ "share.settings.tools.apiNotAvailableToVisitors": "该操作无法在分享运行中使用:它要么需要你本人确认,要么本就不对访客开放。",+ "share.settings.tools.apiWritesOwnerData": "访客不能写入你的记忆,该操作在分享运行中始终关闭。",+ "share.settings.tools.availableGroup": "未开放 · {{count}}",+ "share.settings.tools.desc": "只有在这里勾选的工具才能在访客运行中被调用。可能触达你设备或本地文件的工具永远不会出现在列表中。",+ "share.settings.tools.empty": "这个助手没有可以开放给访客的工具。",+ "share.settings.tools.grantedEmpty": "还没有开放任何工具,访客只能纯聊天。从下面的列表里勾选即可开放。",+ "share.settings.tools.grantedGroup": "已开放给访客 · {{count}}",+ "share.settings.tools.needsMemoryPermission": "还需要打开上面的「允许读取我的记忆」,否则该工具对访客不起作用。",+ "share.settings.tools.notAvailableToVisitors": "该工具无法在分享运行中使用:访客运行被禁止访问你的知识库和助手文件。",+ "share.settings.tools.title": "访客可用的工具",+ "share.settings.updateError": "保存失败,请重试。",+ "share.settings.usage.conversations": "会话数",+ "share.settings.usage.desc": "这个分享带来了多少访问,又花了你多少钱。",+ "share.settings.usage.loadFailed": "用量加载失败",+ "share.settings.usage.monthlySpend": "本月消耗",+ "share.settings.usage.spendOfLimit": "${{spend}} / ${{limit}}",+ "share.settings.usage.title": "用量",+ "share.settings.usage.views": "访问次数",+ "share.settings.usage.visitors": "访客数",+ "share.visitor.access.backHome": "返回首页",+ "share.visitor.access.forbidden": "你没有访问这个分享助手的权限。",+ "share.visitor.access.notFound": "该分享链接已失效。",+ "share.visitor.access.signInCta": "登录",+ "share.visitor.access.signInDesc": "登录后即可与这个分享助手对话,你的会话会保留在自己的账号下。",+ "share.visitor.access.signInTitle": "登录后继续",+ "share.visitor.errors.generic": "消息发送失败,请重试。",+ "share.visitor.errors.heterogeneousUnsupported": "该分享助手暂不支持访客对话,请联系创建者。",+ "share.visitor.errors.insufficientBudget": "该分享助手的额度已用尽,请联系创建者。",+ "share.visitor.errors.promptTooLong": "消息太长了,请精简到 {{max}} 个字符以内后重试。",+ "share.visitor.errors.providerNotSupported": "该分享助手当前不可用,请联系创建者。",+ "share.visitor.errors.sharingPaused": "创建者已暂停分享,暂时无法发送新消息。",+ "share.visitor.errors.spendLimit": "该分享助手本月的使用额度已用完,下月自动恢复。",+ "share.visitor.errors.stopFailed": "停止失败,请重试。",+ "share.visitor.errors.topicLimit": "你在这个分享助手上的会话数量已达上限。",+ "share.visitor.errors.turnLimit": "本次会话的轮数已达上限,新建会话即可继续。",+ "share.visitor.errors.unavailable": "该会话已不可用,请切换或新建会话继续。",+ "share.visitor.input.placeholder": "和这个分享助手聊聊…",+ "share.visitor.input.send": "发送",+ "share.visitor.input.stop": "停止",+ "share.visitor.privacyNotice": "本次会话运行在创建者的账号下,内容可能对创建者可见,请勿发送敏感信息。",+ "share.visitor.topics.empty": "还没有会话",+ "share.visitor.topics.new": "新建会话",+ "share.visitor.topics.title": "会话",+ "share.visitor.topics.untitled": "未命名会话","transfer.button": "移动","transfer.confirm.botChannels": "移动后可能需要重新刷新机器人频道连接","transfer.confirm.chatGroups": "多助理群组关联将被移除",diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.jsonindex 6a2f5f39b4c..6f3c6deb916 100644--- a/locales/zh-CN/electron.json+++ b/locales/zh-CN/electron.json@@ -5,6 +5,7 @@"gateway.statusConnecting": "本机正在连接设备网关...","gateway.statusDisconnected": "本机未连接设备网关","gateway.title": "设备网关",+ "navigation.agentShare": "分享","navigation.agents": "助手","navigation.apps": "应用","navigation.channels": "消息频道",@@ -50,6 +51,7 @@"navigation.resources": "资源","navigation.selfLearning": "自进化","navigation.settings": "设置",+ "navigation.sharedAgent": "分享助手","navigation.stats": "统计","navigation.task": "任务","navigation.tasks": "任务",diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.jsonindex d75a8305463..af3b3e98f80 100644--- a/locales/zh-CN/error.json+++ b/locales/zh-CN/error.json@@ -126,6 +126,7 @@"transfer.ownerOnly": "只有工作区所有者可以转移其他成员创建的资源。","transfer.resourceNotFound": "此资源已不存在或您已无法访问。请刷新后重试。","transfer.sameWorkspace": "此资源已在选定的工作区中。请选择其他目标。",+ "transfer.sharedTransferBlocked": "该 Agent 已创建过分享链接,暂不能变更所有者。","transfer.targetIsCurrentOwner": "该 Agent 已属于这位成员,请选择其他人。","transfer.targetNoWriteAccess": "您需要成员或所有者权限才能将资源移动到目标工作区。","transfer.targetNotWorkspaceMember": "所选接收人不是该工作区的有效成员。请刷新成员列表后重试。",diff --git a/locales/zh-CN/spend.json b/locales/zh-CN/spend.jsonindex c94a3d9e072..229dadd342f 100644--- a/locales/zh-CN/spend.json+++ b/locales/zh-CN/spend.json@@ -12,6 +12,7 @@"table.columns.spend": "消耗积分","table.columns.time": "时间","table.columns.totalTokens": "Token 使用量",+ "table.columns.trigger.enums.agent_share": "助手分享","table.columns.trigger.enums.agent_signal": "代理信号","table.columns.trigger.enums.api": "API 调用","table.columns.trigger.enums.bot": "Bot 消息",diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.tsindex 84ebbc6a8c1..f01296c854b 100644--- a/packages/app-config/src/featureFlags/schema.test.ts+++ b/packages/app-config/src/featureFlags/schema.test.ts@@ -114,6 +114,14 @@ describe('evaluateFeatureFlag', () => {expect(evaluateFeatureFlag([], 'user-123')).toBe(false);expect(evaluateFeatureFlag([])).toBe(false);});++ it('should match allowlist entries against the user email as well', () => {+ const allowlist = ['[email protected]', 'user-456'];+ expect(evaluateFeatureFlag(allowlist, 'user-123', '[email protected]')).toBe(true);+ expect(evaluateFeatureFlag(allowlist, 'user-456', '[email protected]')).toBe(true);+ expect(evaluateFeatureFlag(allowlist, 'user-123', '[email protected]')).toBe(false);+ expect(evaluateFeatureFlag(allowlist, 'user-123')).toBe(false);+ });});describe('mapFeatureFlagsEnvToState', () => {@@ -171,6 +179,38 @@ describe('mapFeatureFlagsEnvToState', () => {expect(mapFeatureFlagsEnvToState(config).enableDevDock).toBe(false);});+ it('should keep agent share off by default and narrow it to listed user IDs or emails', () => {+ expect(DEFAULT_FEATURE_FLAGS.agent_share).toBe(false);+ expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableAgentShare).toBe(false);++ const config = { agent_share: ['creator-123', '[email protected]'] };++ expect(mapFeatureFlagsEnvToState(config, 'creator-123').enableAgentShare).toBe(true);+ expect(+ mapFeatureFlagsEnvToState(config, 'user-456', '[email protected]').enableAgentShare,+ ).toBe(true);+ expect(mapFeatureFlagsEnvToState(config, 'user-456').enableAgentShare).toBe(false);+ expect(mapFeatureFlagsEnvToState(config).enableAgentShare).toBe(false);+ });++ it('should gate agent share visitors with the same `agent_share` allowlist', () => {+ // One flag drives both capabilities, so a visitor is admitted by exactly+ // the same entry (id or email) that would let them publish a share.+ expect(DEFAULT_FEATURE_FLAGS.agent_share).toBe(false);+ expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'visitor-1').enableAgentShare).toBe(+ false,+ );++ const config = { agent_share: ['visitor-123', '[email protected]'] };++ expect(mapFeatureFlagsEnvToState(config, 'visitor-123').enableAgentShare).toBe(true);+ expect(+ mapFeatureFlagsEnvToState(config, 'user-456', '[email protected]').enableAgentShare,+ ).toBe(true);+ expect(mapFeatureFlagsEnvToState(config, 'user-456').enableAgentShare).toBe(false);+ expect(mapFeatureFlagsEnvToState(config).enableAgentShare).toBe(false);+ });+it('should correctly map boolean feature flags to state', () => {const config = {provider_settings: true,diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.tsindex d34fe082c79..4b4cf78088f 100644--- a/packages/app-config/src/featureFlags/schema.ts+++ b/packages/app-config/src/featureFlags/schema.ts@@ -2,6 +2,13 @@ import type { IFeatureFlagsState } from '@lobechat/types';import { z } from 'zod';// Define a union type for feature flag values: either boolean or array of user IDs+//+// NOTE: `agent_share` additionally accepts raw EMAIL addresses in that array+// (see `evaluateFeatureFlag`). Such arrays live in the published runtime config+// (Redis) and in env vars, which therefore hold user email addresses — a data+// category that was previously absent from flag storage. Keep that in mind when+// logging, exporting, or replicating the runtime config, and prefer user IDs+// when an ID is already at hand.const FeatureFlagValue = z.union([z.boolean(), z.array(z.string())]);const isDev = process.env.NODE_ENV === 'development';@@ -18,6 +25,20 @@ export const FeatureFlagsSchema = z.object({api_key_manage: FeatureFlagValue.optional(),edit_agent: FeatureFlagValue.optional(),+ /**+ * Cloud-only grayscale gate for Agent Share, covering BOTH capabilities the+ * feature has: PUBLISHING a share (creator side) and OPENING/chatting on a+ * shared agent (visitor side). A user matched by this flag can do both;+ * everyone else can do neither. Array values are user IDs or emails (see+ * `evaluateFeatureFlag`), so admins can grant a rollout by email without+ * resolving a user ID first. The share OWNER previewing their own share is+ * never subject to the visitor check — only other visitors are. Self-hosted+ * builds are additionally hard-blocked server-side by+ * `ENABLE_BUSINESS_FEATURES` (see `_helpers/agentShareFeatureGate.ts`), so+ * this flag alone can never enable the feature outside Cloud.+ */+ agent_share: FeatureFlagValue.optional(),+ai_image: FeatureFlagValue.optional(),speech_to_text: FeatureFlagValue.optional(),voice_dictation: FeatureFlagValue.optional(),@@ -53,19 +74,25 @@ export const FeatureFlagsSchema = z.object({export type IFeatureFlags = z.infer<typeof FeatureFlagsSchema>;/**- * Evaluate a feature flag value against a user ID- * @param flagValue - The feature flag value (boolean or array of user IDs)+ * Evaluate a feature flag value against a user ID (and optionally their email)+ * @param flagValue - The feature flag value (boolean or array of user IDs/emails)* @param userId - The current user ID+ * @param userEmail - The current user's email; array entries match either+ * identifier, so an admin can whitelist a rollout by email without+ * resolving user IDs first* @returns boolean indicating if the feature is enabled for the user*/export const evaluateFeatureFlag = (flagValue: boolean | string[] | undefined,userId?: string,+ userEmail?: string,): boolean | undefined => {if (typeof flagValue === 'boolean') return flagValue;if (Array.isArray(flagValue)) {- return userId ? flagValue.includes(userId) : false;+ if (userId && flagValue.includes(userId)) return true;+ if (userEmail && flagValue.includes(userEmail)) return true;+ return false;}};@@ -78,6 +105,12 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {api_key_manage: false,edit_agent: true,+ // Cloud-only grayscale: off everywhere until an admin publishes a whitelist+ // (array of user IDs/emails) or flips it to true. Self-hosted deployments+ // are additionally hard-blocked by ENABLE_BUSINESS_FEATURES on the server+ // gate, so setting this env-side does not enable the feature there.+ agent_share: false,+ai_image: true,check_updates: true,@@ -114,9 +147,14 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {export const mapFeatureFlagsEnvToState = (config: IFeatureFlags,userId?: string,+ userEmail?: string,): IFeatureFlagsState => {return {isAgentEditable: evaluateFeatureFlag(config.edit_agent, userId),++ // The only email-aware flag: its grayscale whitelist is maintained by+ // admins as raw emails (see evaluateFeatureFlag).+ enableAgentShare: evaluateFeatureFlag(config.agent_share, userId, userEmail),showProvider: evaluateFeatureFlag(config.provider_settings, userId),showOpenAIApiKey: evaluateFeatureFlag(config.openai_api_key, userId),diff --git a/packages/builtin-tool-memory/src/index.ts b/packages/builtin-tool-memory/src/index.tsindex 8bb61d6f34c..33fb982e422 100644--- a/packages/builtin-tool-memory/src/index.ts+++ b/packages/builtin-tool-memory/src/index.ts@@ -1,3 +1,3 @@export { MemoryIdentifier, MemoryManifest } from './manifest';export { systemPrompt } from './systemRole';-export { MemoryApiName, type MemoryApiNameType } from './types';+export { MEMORY_WRITE_API_NAMES, MemoryApiName, type MemoryApiNameType } from './types';diff --git a/packages/builtin-tool-memory/src/types.ts b/packages/builtin-tool-memory/src/types.tsindex e6ef1685538..e1691ee828e 100644--- a/packages/builtin-tool-memory/src/types.ts+++ b/packages/builtin-tool-memory/src/types.ts@@ -24,6 +24,22 @@ export const MemoryApiName = {export type MemoryApiNameType = (typeof MemoryApiName)[keyof typeof MemoryApiName];+/**+ * APIs that mutate the user's memory store. Single source of truth shared by+ * the Agent Share server gate (which strips them from visitor runs+ * unconditionally) and the share settings picker (which pre-disables them),+ * so adding a write API here keeps both sides in step.+ */+export const MEMORY_WRITE_API_NAMES: ReadonlySet<MemoryApiNameType> = new Set([+ MemoryApiName.addActivityMemory,+ MemoryApiName.addContextMemory,+ MemoryApiName.addExperienceMemory,+ MemoryApiName.addIdentityMemory,+ MemoryApiName.addPreferenceMemory,+ MemoryApiName.removeIdentityMemory,+ MemoryApiName.updateIdentityMemory,+]);+/** @deprecated Use MemoryApiName instead */export const UserMemoryApiName = MemoryApiName;diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex 8057cb05841..a32073de9e3 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -169,6 +169,101 @@ export const runtimeManagedToolIds = [WebBrowsingManifest.identifier,];+/**+ * Master allowlist of builtin tool identifiers a share visitor's run may ever+ * touch, at BOTH the tool-set-assembly layer (server+ * `applyShareGateToToolSet`) and the dispatch layer (server+ * `isShareBlockedDataToolCall`) — see+ * `apps/server/src/services/aiAgent/shareGate.ts`. Also the single source of+ * truth for the agent-owner-facing share settings tool picker, which must+ * show a builtin tool as unavailable-to-visitors rather than let the owner+ * select (and the UI silently confirm) a grant the server gate can never+ * honor.+ *+ * Exported from `@lobechat/builtin-tools` — not `apps/server` — specifically+ * so the client settings UI can import the exact same Set the server gate+ * enforces, instead of hand-copying identifiers that could drift. This+ * package is already the shared boundary for cross-cutting builtin-tool+ * identifier lists consumed by both the frontend (`createAgentToolsEngine`)+ * and the server (`createServerAgentToolsEngine`) — see `defaultToolIds` /+ * `chatModeAllowedToolIds` / `runtimeManagedToolIds` above.+ *+ * DEFAULT-DENY, not default-allow-minus-a-blocklist. A share visitor's run+ * executes with the CREATOR's full credentials, and every builtin runtime+ * defaults to creator-scoped — it is written for the creator's own+ * conversation, where "the caller" and "the data owner" are the same person.+ * A share visitor breaks that assumption (caller ≠ data owner), and nothing+ * about a builtin tool's manifest or registration signals whether its+ * runtime happens to re-derive its scope from a model-suppliable argument+ * (unsafe for a visitor) or purely from server-side context like+ * `context.agentId` / `context.operationId` (safe). Under this allowlist, a+ * newly registered builtin tool — or a newly added API on an already-allowed+ * one — is exposed to a share visitor ONLY once someone explicitly adds it+ * here with file:line evidence for why its runtime cannot resolve to the+ * creator's data outside what this specific share/agent grants.+ *+ * Every entry was verified against its actual server runtime+ * (`apps/server/src/services/toolExecution/serverRuntimes/*`), not just its+ * manifest. For the rationale behind every DENIED identifier+ * (`lobe-agent-management`, `lobe-task`, `lobe-creds`, `lobe-message`,+ * `lobe-skill-store`, `lobe-agent-builder`, `lobe-skills`,+ * `lobe-group-agent-builder`, `lobe-group-management`, `agent-signal-review`,+ * `lobe-user-interaction`, `lobe-activator`,+ * `lobe-local-system`, `lobe-browser`, `lobe-remote-device`,+ * `lobe-topic-reference`, and the hidden system-only self-iteration tools),+ * see the denied-bucket doc block at the bottom of+ * `apps/server/src/services/aiAgent/shareGate.ts`.+ */+export const AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS = new Set<string>([+ CalculatorManifest.identifier,+ WebBrowsingManifest.identifier,+ ImageGenerationManifest.identifier,+ VerifyToolManifest.identifier,+ AcceptanceEvidenceManifest.identifier,+ LobeAgentManifest.identifier,+ // `lobe-cloud-sandbox`: allowed because a share-visitor run gets its own+ // fresh per-topic sandbox session, not the creator's. The `lh` CLI JWT+ // shim that would otherwise mint a creator-scoped token inside the shell+ // is skipped for visitor runs (see `cloudSandbox.ts` /+ // `preprocessLhCommand.ts`), and `lobe-creds` stays denied so+ // `~/.creds/env` is never written into that session either. See the+ // positive-evidence doc block in `shareGate.ts` for the full rationale.+ CloudSandboxManifest.identifier,+ // Data-bearing tools whose whole-identifier grant AND per-API write/always-+ // blocked surface is further narrowed server-side by+ // `DATA_TOOL_ACCESS_RULES` in `shareGate.ts` — being on this allowlist only+ // lets them survive to that narrower gate, it does not itself grant read or+ // write access.+ KnowledgeBaseManifest.identifier,+ MemoryManifest.identifier,+ AgentDocumentsManifest.identifier,+]);++/**+ * Subset of {@link AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS} whose server-side+ * data grant is UNCONDITIONALLY `none` — surviving the master allowlist only+ * to be blocked outright by `DATA_TOOL_ACCESS_RULES` in+ * `apps/server/src/services/aiAgent/shareGate.ts`, for every API and no matter+ * what the share config says. There is no knowledge-base or agent-file grant+ * in `AgentShareConfig` at all (see `applyShareGateToAgentConfig`), so a+ * visitor run can never reach either store.+ *+ * Memory is deliberately NOT here: its grant is conditional on+ * `allowReadMemory`, so the owner enabling that switch does change what a+ * visitor run can do.+ *+ * Exists so the owner-facing share settings tool picker can render these as+ * permanently unavailable instead of offering a toggle the server will always+ * ignore. `shareGate.test.ts` asserts this set stays exactly the set of+ * identifiers `isShareBlockedDataToolCall` blocks under maximal permissions,+ * so relaxing a grant server-side without updating this list fails there+ * rather than silently lying in the UI.+ */+export const AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS = new Set<string>([+ KnowledgeBaseManifest.identifier,+ AgentDocumentsManifest.identifier,+]);+const builtinToolRegistry: LobeBuiltinTool[] = [{discoverable: false,@@ -441,3 +536,30 @@ const recommendedBuiltinIds = new Set(export const defaultUninstalledBuiltinTools = builtinTools.filter((t) => !t.hidden && !recommendedBuiltinIds.has(t.identifier)).map((t) => t.identifier);++const builtinIdentifierSet = new Set(builtinTools.map((tool) => tool.identifier));++/**+ * Whether `identifier` belongs to the population+ * {@link AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS} governs — the real builtin+ * tool registry above, the same source the server gate+ * (`hasServerRuntime`/`BuiltinToolsExecutor`) resolves against. MCP servers,+ * market plugins, and custom plugins never appear in this registry, so they+ * fall outside this allowlist's jurisdiction entirely.+ */+export const isBuiltinToolIdentifier = (identifier: string): boolean =>+ builtinIdentifierSet.has(identifier);++/**+ * Whether `identifier` would survive the agent-share builtin-tool gate: true+ * for anything outside this allowlist's jurisdiction (MCP/market/custom+ * plugins — left entirely to the owner's `enabledToolIds` picker), and for a+ * governed builtin identifier, true only when it is explicitly listed in+ * {@link AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS}.+ *+ * Shared by the server gate (`shareGate.ts`) and the owner-facing tool picker+ * so both sides agree on exactly which builtin tools a share visitor's run+ * can ever reach.+ */+export const isAgentShareAllowedBuiltinIdentifier = (identifier: string): boolean =>+ !isBuiltinToolIdentifier(identifier) || AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS.has(identifier);diff --git a/packages/business-server/src/agent-share/spendGate.ts b/packages/business-server/src/agent-share/spendGate.tsnew file mode 100644index 00000000000..e2669ff8f61--- /dev/null+++ b/packages/business-server/src/agent-share/spendGate.ts@@ -0,0 +1,61 @@+/**+ * Optional business hook for deployments that meter shared-agent usage.+ *+ * A shared agent runs under its CREATOR's identity, so every visitor turn is+ * billed to the creator. `AgentShareConfig.monthlySpendLimit` lets the creator+ * bound that exposure; this slot is where a deployment that actually tracks+ * spend decides whether the next visitor run may start.+ *+ * The slot is a pure admission check called BEFORE any topic/message row is+ * created — the caller is responsible for turning a denial into a+ * visitor-facing error.+ */+export interface AgentShareSpendGateParams {+ /** The shared agent. */+ agentId: string;+ /**+ * The creator's configured cap for this share, in USD. Always present —+ * `normalizeAgentShareConfig` guarantees a share carries a cap, and `0` is a+ * real lower bound meaning "stop all visitor runs".+ */+ monthlySpendLimit: number;+ /** The creator whose account is billed for this run. */+ ownerUserId: string;+ /** The `agentShares.id` this run is authorized against. */+ shareId: string;+ /** The signed-in visitor asking to run the agent. */+ visitorUserId: string;+}++export interface AgentShareSpendGateResult {+ /** `false` rejects the run before any row is written. */+ allowed: boolean;+}++/**+ * Default: no spend accounting, so nothing is ever refused. A deployment that+ * meters shared-agent spend overrides this module.+ */+export async function checkAgentShareSpendAllowance(+ _params: AgentShareSpendGateParams,+): Promise<AgentShareSpendGateResult> {+ return { allowed: true };+}++/**+ * Spend already billed to the creator by visitor runs of one shared agent in+ * the current calendar month, for the creator's own usage panel.+ *+ * Read-only companion to {@link checkAgentShareSpendAllowance}: same source of+ * truth, but reported instead of enforced.+ *+ * Default: `null`, meaning "this deployment does not meter shared-agent+ * spend". Callers must render that as unknown, NOT as `0` — a zero would read+ * as "nothing has been spent", which is a different and misleading claim.+ */+export async function getAgentShareMonthlySpend(_params: {+ agentId: string;+ ownerUserId: string;+}): Promise<number | null> {+ return null;+}diff --git a/packages/business-server/src/image-generation/chargeAfterGenerate.ts b/packages/business-server/src/image-generation/chargeAfterGenerate.tsindex 172ee92a67a..e8a2fd326ff 100644--- a/packages/business-server/src/image-generation/chargeAfterGenerate.ts+++ b/packages/business-server/src/image-generation/chargeAfterGenerate.ts@@ -1,10 +1,11 @@import { type ModelPricingContext } from '@lobechat/model-runtime';+import { type SpendOrigin } from '@lobechat/types';import { type ModelPerformance, type ModelUsage } from '@/types/index';interface ChargeParams {isError?: boolean;- metadata: {+ metadata: SpendOrigin & {asyncTaskId: string;generationBatchId: string;modelId: string;diff --git a/packages/business-server/src/image-generation/chargeBeforeGenerate.ts b/packages/business-server/src/image-generation/chargeBeforeGenerate.tsindex 5bba92eb7aa..ef8a28f3d53 100644--- a/packages/business-server/src/image-generation/chargeBeforeGenerate.ts+++ b/packages/business-server/src/image-generation/chargeBeforeGenerate.ts@@ -1,3 +1,5 @@+import { type SpendOrigin } from '@lobechat/types';+import { type NewGeneration, type NewGenerationBatch } from '@/database/schemas';import { type CreateImageServicePayload } from '@/server/routers/lambda/image';@@ -9,6 +11,11 @@ interface ChargeParams {imageNum: number;model: string;provider: string;+ /**+ * Origin of the request, so an implementation that defers the charge to a+ * later async step can persist it and still attribute the final spend.+ */+ spendOrigin?: SpendOrigin;userId: string;workspaceId?: string;}diff --git a/packages/business-server/src/video-generation/chargeAfterGenerate.ts b/packages/business-server/src/video-generation/chargeAfterGenerate.tsindex c6fbd78cb99..ac56eb8c9ea 100644--- a/packages/business-server/src/video-generation/chargeAfterGenerate.ts+++ b/packages/business-server/src/video-generation/chargeAfterGenerate.ts@@ -1,9 +1,11 @@+import { type SpendOrigin } from '@lobechat/types';+interface ChargeParams {computePriceParams?: { generateAudio?: boolean; resolution?: string };isError?: boolean;/** Total time from task submission to webhook callback (ms) */latency?: number;- metadata: {+ metadata: SpendOrigin & {asyncTaskId: string;generationBatchId: string;modelId: string;diff --git a/packages/const/src/agentShare.test.ts b/packages/const/src/agentShare.test.tsnew file mode 100644index 00000000000..cf107abf4e9--- /dev/null+++ b/packages/const/src/agentShare.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest';++import { hasShareToolGrant, isShareToolApiGranted, resolveShareToolGrants } from './agentShare';++describe('resolveShareToolGrants', () => {+ it('grants every API for a grant without `apis`', () => {+ const grants = resolveShareToolGrants([{ identifier: 'lobe-agent' }]);+ expect(grants.get('lobe-agent')).toBe('all');+ });++ it('collects the granted `apis` into a Set', () => {+ const grants = resolveShareToolGrants([+ { apis: ['analyzeMedia', 'updatePlan'], identifier: 'lobe-agent' },+ ]);+ expect(grants.get('lobe-agent')).toEqual(new Set(['analyzeMedia', 'updatePlan']));+ });++ it('lets a toolset-level grant win over a per-API one for the same identifier, regardless of order', () => {+ const before = resolveShareToolGrants([+ { identifier: 'lobe-agent' },+ { apis: ['analyzeMedia'], identifier: 'lobe-agent' },+ ]);+ expect(before.get('lobe-agent')).toBe('all');++ const after = resolveShareToolGrants([+ { apis: ['analyzeMedia'], identifier: 'lobe-agent' },+ { identifier: 'lobe-agent' },+ ]);+ expect(after.get('lobe-agent')).toBe('all');+ });++ it('unions two per-API grants for the same identifier', () => {+ const grants = resolveShareToolGrants([+ { apis: ['analyzeMedia'], identifier: 'lobe-agent' },+ { apis: ['updatePlan'], identifier: 'lobe-agent' },+ ]);+ expect(grants.get('lobe-agent')).toEqual(new Set(['analyzeMedia', 'updatePlan']));+ });++ it('reads an explicit empty `apis` array fail-closed as no grant, never as a toolset-level grant', () => {+ const grants = resolveShareToolGrants([{ apis: [], identifier: 'calculator' }]);++ expect(grants.has('calculator')).toBe(false);+ });++ it('ignores an entry with an empty identifier', () => {+ const grants = resolveShareToolGrants([{ identifier: '' }, { identifier: 'calculator' }]);+ expect(grants.has('')).toBe(false);+ expect(grants.get('calculator')).toBe('all');+ });++ it('tolerates an unset grants array', () => {+ expect(resolveShareToolGrants(undefined).size).toBe(0);+ });+});++describe('hasShareToolGrant / isShareToolApiGranted', () => {+ it('reports presence of any grant for an identifier', () => {+ const grants = resolveShareToolGrants([{ apis: ['analyzeMedia'], identifier: 'lobe-agent' }]);+ expect(hasShareToolGrant(grants, 'lobe-agent')).toBe(true);+ expect(hasShareToolGrant(grants, 'calculator')).toBe(false);+ });++ it('checks per-API grants precisely', () => {+ const grants = resolveShareToolGrants([{ apis: ['analyzeMedia'], identifier: 'lobe-agent' }]);+ expect(isShareToolApiGranted(grants, 'lobe-agent', 'analyzeMedia')).toBe(true);+ expect(isShareToolApiGranted(grants, 'lobe-agent', 'callSubAgent')).toBe(false);+ });++ it('a toolset-level grant covers every API', () => {+ const grants = resolveShareToolGrants([{ identifier: 'lobe-agent' }]);+ expect(isShareToolApiGranted(grants, 'lobe-agent', 'anything')).toBe(true);+ });++ it('an ungranted identifier grants nothing', () => {+ const grants = resolveShareToolGrants([]);+ expect(isShareToolApiGranted(grants, 'lobe-agent', 'analyzeMedia')).toBe(false);+ });+});diff --git a/packages/const/src/agentShare.ts b/packages/const/src/agentShare.tsnew file mode 100644index 00000000000..c1cf290c791--- /dev/null+++ b/packages/const/src/agentShare.ts@@ -0,0 +1,166 @@+import type { AgentShareToolGrant } from '@lobechat/types';++/**+ * Default `AgentShareConfig.maxTopicsPerVisitor` applied when a share is+ * first created and whenever a legacy/partial config is normalized. Kept+ * conservative — the creator can raise it explicitly via `updateShareConfig`.+ */+export const AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR = 5;++/**+ * Page size of a visitor's own topic list on a shared agent.+ *+ * Deliberately NOT tied to the share's live `maxTopicsPerVisitor`: that cap+ * only gates the ADMISSION of new topics (a COUNT check at creation time).+ * Using it as the read-side LIMIT would hide a visitor's older conversations+ * the moment the creator lowers the cap below what the visitor had already+ * created — and the visitor surface has no pagination or deep links to reach+ * them. A fixed, generous bound keeps every topic a visitor was ever allowed+ * to create reachable.+ */+export const AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT = 200;++/**+ * Default `AgentShareConfig.maxTurnsPerTopic` applied when a share is first+ * created and whenever a legacy/partial config is normalized.+ */+export const AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC = 20;++/**+ * Default `AgentShareConfig.monthlySpendLimit` (in USD credits) applied when a+ * share is first created and whenever a partial config is normalized.+ *+ * The cap is mandatory — a share never runs uncapped — so this is the value a+ * creator starts from and can raise or lower, but never clear.+ */+export const AGENT_SHARE_DEFAULT_MONTHLY_SPEND_LIMIT = 10;++/**+ * Upper bound on a visitor-submitted `prompt` for an agent-share visitor run.+ *+ * Unlike the creator's own account (where oversized input is self-inflicted),+ * a share visitor run executes as the CREATOR: the text is persisted verbatim+ * into creator-owned messages. Without a size bound, any authenticated+ * visitor with a live link could submit HTTP-infrastructure-limit-sized+ * prompts on repeat, bloating the creator's message rows.+ *+ * 20,000 characters (~5-8k tokens for typical English/code text) comfortably+ * covers legitimate long-form asks (pasted code, long questions) while+ * keeping a single turn's contribution to storage/transport negligible.+ *+ * Kept in `@lobechat/const` (instead of inline in a router) so both the+ * server input schema and any client-side `maxLength`/error copy share one+ * source of truth — the server bound is still the real gate; a client mirror+ * is convenience only.+ */+export const SHARE_VISITOR_PROMPT_MAX_LENGTH = 20_000;++/**+ * Validates `AgentShareConfig.slug`: lowercase alphanumerics and hyphens+ * only, 3-64 characters, no leading/trailing hyphen. Deliberately excludes+ * uppercase and underscores to keep share URLs visually unambiguous and+ * case-insensitive-safe. UUID-shaped slugs are additionally rejected in+ * `AgentShareModel.updateSlug` — `findBySlugOrId` resolves UUID-shaped input+ * as a share id first, so such a slug would be unreachable.+ */+export const AGENT_SHARE_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$/;++/**+ * Slugs a share may not claim. Two groups:+ *+ * 1. words that collide with existing (or foreseeable) static routes under the+ * agent surface (e.g. `/agent/<slug>`, `/agent/new`), or that would+ * otherwise confuse a share URL;+ * 2. every builtin agent slug — a share lives at `/agent/<slug>`, the same+ * route the creator's own agents use, and an own agent always wins the+ * lookup, so a share taking a builtin slug would be permanently unreachable.+ *+ * The builtin slugs are duplicated here rather than imported: `@lobechat/const`+ * sits *below* `@lobechat/builtin-agents` in the dependency graph. The copy is+ * kept honest by a test that diffs it against `BUILTIN_AGENT_SLUGS`.+ *+ * Checked by `AgentShareModel.updateSlug` before a custom slug is written.+ */+export const RESERVED_AGENT_SHARE_SLUGS: string[] = [+ 'admin',+ 'api',+ 'edit',+ 'index',+ 'new',+ 'profile',+ 'settings',+ 'share',+ // Builtin agent slugs — mirror of `BUILTIN_AGENT_SLUGS`.+ 'agent-builder',+ 'group-agent-builder',+ 'group-supervisor',+ 'inbox',+ 'nightly-review',+ 'onboarding-understanding',+ 'onboarding-task-recommender',+ 'page-agent',+ 'self-feedback-intent',+ 'self-reflection',+ 'skill-management',+ 'task-agent',+ 'verify-agent',+ 'web-onboarding',+];++/**+ * One identifier's resolved grant: `'all'` for a toolset-level grant (no+ * `apis`), or the specific `Set` of API names the grant named.+ */+export type ShareToolGrant = 'all' | Set<string>;++/**+ * Reduce `shareConfig.toolGrants` into one grant per identifier.+ *+ * `toolGrants` is expected to hold at most one entry per identifier (the+ * router rejects duplicates), but the reduction still merges defensively so a+ * hand-edited row can never widen access unexpectedly: a grant without `apis`+ * always wins over per-API ones for the same identifier, regardless of array+ * order, and two per-API grants union their API names. An explicit empty+ * `apis` array is malformed (the router rejects it) and is read fail-closed as+ * "no API granted" — never silently widened to a toolset-level grant.+ */+export const resolveShareToolGrants = (+ toolGrants: AgentShareToolGrant[] | undefined,+): Map<string, ShareToolGrant> => {+ const grants = new Map<string, ShareToolGrant>();++ for (const { identifier, apis } of toolGrants ?? []) {+ if (!identifier) continue;+ if (grants.get(identifier) === 'all') continue;++ if (!apis) {+ grants.set(identifier, 'all');+ continue;+ }+ if (apis.length === 0) continue;++ const existing = grants.get(identifier);+ const apiNames = existing instanceof Set ? existing : new Set<string>();+ for (const apiName of apis) apiNames.add(apiName);+ grants.set(identifier, apiNames);+ }++ return grants;+};++/** Whether `identifier` has any grant (toolset-level or per-API) in `grants`. */+export const hasShareToolGrant = (+ grants: Map<string, ShareToolGrant>,+ identifier: string,+): boolean => grants.has(identifier);++/** Whether `identifier`'s specific `apiName` is granted — toolset-level grants every API. */+export const isShareToolApiGranted = (+ grants: Map<string, ShareToolGrant>,+ identifier: string,+ apiName: string,+): boolean => {+ const grant = grants.get(identifier);+ if (!grant) return false;+ return grant === 'all' || grant.has(apiName);+};diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex 33b88dffe01..96fed949b27 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -179,6 +179,10 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRuleagentLabel: rw('agent:read', 'agent:write'),agentNotify: rw('agent:read', 'agent:write'),agentQuota: rw('agent:read', null),+ // share management toggles a public entry point and monthly spend caps+ // charged to the owner; restricted API keys must not flip it (full-access+ // keys still can)+ agentShare: 'blocked',agentSignal: rw('agent:read', 'agent:write'),agentSkills: rw('agent:read', 'agent:write'),// a trace snapshot is the whole inside of a run — system role, injected user@@ -253,6 +257,10 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRulesession: rw('chat:read', 'chat:write'),sessionGroup: rw('chat:read', 'chat:write'),share: rw('chat:read', 'chat:write'),+ // visitor-side chat endpoints execute under the CREATOR's identity/budget via+ // share authorization, not the caller's key scope; never reachable with a+ // restricted key+ shareChat: 'blocked',spend: 'blocked',storageOverage: 'blocked',subscription: 'blocked',diff --git a/packages/const/src/index.ts b/packages/const/src/index.tsindex 86d27a0eaa3..a11fa934c75 100644--- a/packages/const/src/index.ts+++ b/packages/const/src/index.ts@@ -1,5 +1,6 @@export * from './agentDocument';export * from './agentName';+export * from './agentShare';export * from './apiKeyScope';export * from './bot';export * from './composio';diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.tsindex 72077a6c364..40b604da2b8 100644--- a/packages/database/src/models/__tests__/agent.test.ts+++ b/packages/database/src/models/__tests__/agent.test.ts@@ -3273,6 +3273,36 @@ describe('AgentModel', () => {expect(ids).not.toContain('virtual-agent');});+ // Share-visitor topics live under the creator's userId with a non-null+ // senderId; they reflect the visitor's usage, not the creator's, so they+ // must neither inflate a count nor reorder the ranking.+ it('should not count share-visitor topics', async () => {+ await serverDB.insert(agents).values([+ { id: 'shared', title: 'Shared', userId },+ { id: 'own', title: 'Own', userId },+ { id: 'visitor-only', title: 'Visitor only', userId },+ ]);+ await serverDB.insert(topics).values([+ // `shared`: one creator topic + three visitor topics → count 1+ { agentId: 'shared', id: 'sv0', userId },+ { agentId: 'shared', id: 'sv1', senderId: userId2, userId },+ { agentId: 'shared', id: 'sv2', senderId: userId2, userId },+ { agentId: 'shared', id: 'sv3', senderId: userId2, userId },+ // `own`: two creator topics → count 2, ranks above `shared`+ { agentId: 'own', id: 'ov1', userId },+ { agentId: 'own', id: 'ov2', userId },+ // `visitor-only`: visitor topics only → excluded like a topicless agent+ { agentId: 'visitor-only', id: 'vo1', senderId: userId2, userId },+ ]);++ const result = await agentModel.rank();++ expect(result.map((r) => ({ count: r.count, id: r.id }))).toEqual([+ { count: 2, id: 'own' },+ { count: 1, id: 'shared' },+ ]);+ });+it('should only rank the current user agents', async () => {await serverDB.insert(agents).values([{ id: 'mine', title: 'Mine', userId },diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.tsindex b872699fd51..465ada5c228 100644--- a/packages/database/src/models/__tests__/agentOperation.test.ts+++ b/packages/database/src/models/__tests__/agentOperation.test.ts@@ -564,15 +564,71 @@ describe('AgentOperationModel', () => {});});+ describe('findOwnOperationById', () => {+ beforeEach(async () => {+ await serverDB.insert(topics).values([+ { id: 'own-tpc', userId },+ // Agent-share visitor topic: creator's userId + a visitor senderId.+ { id: 'own-tpc-visitor', senderId: 'visitor-user-x', userId },+ ]);+ await serverDB.insert(agentOperations).values([+ { id: 'op-own', status: 'done', topicId: 'own-tpc', userId },+ { id: 'op-own-visitor', status: 'done', topicId: 'own-tpc-visitor', userId },+ { id: 'op-own-topicless', status: 'done', userId },+ ]);+ });++ it('hides an operation recorded inside an agent-share visitor topic', async () => {+ // Visitor runs execute under the creator's identity, so the row passes+ // ownership — the creator-facing trace lookup must still read it as absent.+ const model = new AgentOperationModel(serverDB, userId);++ expect(await model.findOwnOperationById('op-own-visitor')).toBeNull();+ // The runtime lookup keeps working: it drives the visitor's own run.+ expect(await model.findById('op-own-visitor')).toMatchObject({ id: 'op-own-visitor' });+ });++ it('returns the creator own operations, topic-bound or not', async () => {+ const model = new AgentOperationModel(serverDB, userId);++ expect(await model.findOwnOperationById('op-own')).toMatchObject({ id: 'op-own' });+ expect(await model.findOwnOperationById('op-own-topicless')).toMatchObject({+ id: 'op-own-topicless',+ });+ });++ it('does not cross the ownership boundary', async () => {+ const model = new AgentOperationModel(serverDB, otherUserId);++ expect(await model.findOwnOperationById('op-own')).toBeNull();+ });+ });+describe('listByTopic', () => {beforeEach(async () => {await serverDB.insert(topics).values([{ id: 'tpc-a', userId },{ id: 'tpc-b', userId },{ id: 'tpc-foreign', userId: otherUserId },+ // Agent-share visitor topic: creator's userId + a visitor senderId.+ { id: 'tpc-visitor', senderId: 'visitor-user-x', userId },]);});+ it('excludes operations recorded inside an agent-share visitor topic', async () => {+ const model = new AgentOperationModel(serverDB, userId);++ // Visitor runs execute under the creator's identity, so their operation+ // rows pass the ownership filter — the trace panel must still not expose+ // a visitor conversation's trajectory.+ await serverDB+ .insert(agentOperations)+ .values([{ id: 'op-visitor', status: 'done', topicId: 'tpc-visitor', userId }]);++ const rows = await model.listByTopic('tpc-visitor');+ expect(rows).toEqual([]);+ });+it('returns the topic operations newest first, owner-scoped', async () => {const model = new AgentOperationModel(serverDB, userId);diff --git a/packages/database/src/models/__tests__/agentShare.test.ts b/packages/database/src/models/__tests__/agentShare.test.tsnew file mode 100644index 00000000000..7e06d75f506--- /dev/null+++ b/packages/database/src/models/__tests__/agentShare.test.ts@@ -0,0 +1,540 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import type { AgentShareConfig } from '../../schemas';+import { agents, agentShares, users, workspaces } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { AgentShareModel } from '../agentShare';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'agent-share-test-user';+const otherUserId = 'agent-share-test-other-user';+const agentId = 'agent-share-test-agent';+const otherAgentId = 'agent-share-test-other-agent';+const workspaceAgentId = 'agent-share-test-workspace-agent';+const workspaceId = 'agent-share-test-workspace';++const agentShareModel = new AgentShareModel(serverDB, userId);+const otherAgentShareModel = new AgentShareModel(serverDB, otherUserId);++describe('AgentShareModel', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.transaction(async (tx) => {+ await tx.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await tx.insert(workspaces).values({+ id: workspaceId,+ name: 'Agent Share Test Workspace',+ primaryOwnerId: userId,+ slug: 'agent-share-test-workspace',+ });+ await tx.insert(agents).values([+ {+ avatar: '🤯',+ backgroundColor: '#000000',+ description: 'Shareable agent',+ id: agentId,+ name: 'Shareable Agent',+ title: 'Shareable Agent Title',+ userId,+ },+ { id: otherAgentId, title: 'Other Agent', userId: otherUserId },+ { id: workspaceAgentId, userId, workspaceId },+ ]);+ });+ });++ afterEach(async () => {+ await serverDB.delete(users);+ });++ describe('create', () => {+ it('creates a share with conservative defaults', async () => {+ const share = await agentShareModel.create(agentId);++ expect(share).not.toBeNull();+ expect(share).toMatchObject({+ agentId,+ shareConfig: {+ allowCreatorViewSessions: false,+ allowReadMemory: false,+ maxTopicsPerVisitor: 5,+ maxTurnsPerTopic: 20,+ showErrorDetails: false,+ showModelInfo: false,+ toolGrants: [],+ },+ userViewCount: 0,+ visibility: 'private',+ });+ expect(share!.id).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,+ );+ expect(share!.shareConfig).not.toHaveProperty('guestEnabled');+ expect(share!.shareConfig).not.toHaveProperty('maxGuestTopics');+ expect(share!.shareConfig).not.toHaveProperty('filePermissionConfig');+ });++ it('preserves the first share when creation conflicts', async () => {+ const first = await agentShareModel.create(agentId, 'private');+ const second = await agentShareModel.create(agentId, 'link');++ expect(second).toEqual(first);+ const rows = await serverDB+ .select()+ .from(agentShares)+ .where(eq(agentShares.agentId, agentId));+ expect(rows).toHaveLength(1);+ expect(rows[0].visibility).toBe('private');+ });++ it('rejects missing, foreign, and workspace agents', async () => {+ await expect(agentShareModel.create('missing-agent')).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(agentShareModel.create(otherAgentId)).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(agentShareModel.create(workspaceAgentId)).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ });+ });++ describe('owner operations', () => {+ it('normalizes a legacy null config to conservative defaults', async () => {+ const [legacyShare] = await serverDB.insert(agentShares).values({ agentId }).returning();++ const ownerShare = await agentShareModel.getByAgentId(agentId);+ const resolvedShare = await AgentShareModel.findByShareId(serverDB, legacyShare.id);++ expect(ownerShare?.shareConfig).toEqual({+ allowCreatorViewSessions: false,+ allowReadMemory: false,+ maxTopicsPerVisitor: 5,+ maxTurnsPerTopic: 20,+ monthlySpendLimit: 10,+ showErrorDetails: false,+ showModelInfo: false,+ slug: undefined,+ toolGrants: [],+ });+ expect(resolvedShare?.shareConfig).toEqual(ownerShare?.shareConfig);+ });++ it('reads and updates the complete config', async () => {+ await agentShareModel.create(agentId);+ const config: AgentShareConfig = {+ allowCreatorViewSessions: true,+ allowReadMemory: true,+ maxTopicsPerVisitor: 10,+ maxTurnsPerTopic: 40,+ monthlySpendLimit: 25,+ showErrorDetails: true,+ showModelInfo: true,+ toolGrants: [{ identifier: 'search' }],+ };++ const updated = await agentShareModel.updateConfig(agentId, config);+ const readBack = await agentShareModel.getByAgentId(agentId);++ expect(updated?.shareConfig).toEqual(config);+ expect(readBack?.shareConfig).toEqual(config);+ });++ it('atomically merges stale cross-context patches without losing sibling fields', async () => {+ await agentShareModel.create(agentId);++ await agentShareModel.updateConfig(agentId, {+ maxTopicsPerVisitor: 10,+ toolGrants: [{ identifier: 'search' }],+ });+ const updated = await agentShareModel.updateConfig(agentId, {+ maxTurnsPerTopic: 40,+ showModelInfo: true,+ });++ expect(updated?.shareConfig).toMatchObject({+ maxTopicsPerVisitor: 10,+ maxTurnsPerTopic: 40,+ showModelInfo: true,+ toolGrants: [{ identifier: 'search' }],+ });+ });++ it('overwrites the spend cap, and never accepts slug via updateConfig', async () => {+ await agentShareModel.create(agentId);+ await agentShareModel.updateConfig(agentId, { monthlySpendLimit: 25 });++ const updated = await agentShareModel.updateConfig(agentId, {+ monthlySpendLimit: 0,+ showModelInfo: true,+ // smuggled past the type on purpose — must be stripped, not persisted+ ...({ slug: 'sneaky-slug' } as object),+ });++ // `0` is a real cap ("stop all visitor runs"), never a cleared one.+ expect(updated?.shareConfig.monthlySpendLimit).toBe(0);+ expect(updated?.shareConfig.showModelInfo).toBe(true);+ expect(updated?.shareConfig.slug).toBeUndefined();+ expect(await AgentShareModel.findBySlugOrId(serverDB, 'sneaky-slug')).toBeNull();+ });++ // `deleteByAgentId` is the hard-teardown path, deliberately NOT what the+ // disable flow uses (see the cycle test below).+ it('updates visibility, and hard-deletes the share on demand', async () => {+ const created = await agentShareModel.create(agentId);++ const updated = await agentShareModel.updateVisibility(agentId, 'link');+ expect(updated?.visibility).toBe('link');++ const deleted = await agentShareModel.deleteByAgentId(agentId);+ expect(deleted?.id).toBe(created?.id);+ expect(await AgentShareModel.findByShareId(serverDB, created!.id)).toBeNull();+ });++ it('returns null for missing shares', async () => {+ expect(await agentShareModel.getByAgentId(agentId)).toBeNull();+ expect(await agentShareModel.updateConfig(agentId, { maxTopicsPerVisitor: 5 })).toBeNull();+ expect(await agentShareModel.updateVisibility(agentId, 'link')).toBeNull();+ expect(await agentShareModel.deleteByAgentId(agentId)).toBeNull();+ });++ it("does not read, update, or delete another user's share", async () => {+ const otherShare = await otherAgentShareModel.create(otherAgentId);++ expect(await agentShareModel.getByAgentId(otherAgentId)).toBeNull();+ expect(+ await agentShareModel.updateConfig(otherAgentId, { maxTopicsPerVisitor: 5 }),+ ).toBeNull();+ expect(await agentShareModel.updateVisibility(otherAgentId, 'link')).toBeNull();+ expect(await agentShareModel.deleteByAgentId(otherAgentId)).toBeNull();+ expect(await otherAgentShareModel.getByAgentId(otherAgentId)).toEqual(otherShare);+ });++ // Turning sharing off is a pause, not a revocation — `updateVisibility`,+ // never a delete — so the link (share id + custom slug) survives the cycle+ // and re-enabling republishes the very same url.+ it('keeps the share id and slug across a disable → re-enable cycle', async () => {+ const first = await agentShareModel.create(agentId, 'link');+ await agentShareModel.updateSlug(agentId, 'stable-link');++ const disabled = await agentShareModel.updateVisibility(agentId, 'private');+ expect(disabled?.id).toBe(first?.id);+ expect(disabled?.shareConfig.slug).toBe('stable-link');++ // `create` falls back to the existing row rather than inserting a new one.+ const recreated = await agentShareModel.create(agentId, 'link');+ const reEnabled = await agentShareModel.updateVisibility(agentId, 'link');++ expect(recreated?.id).toBe(first?.id);+ expect(reEnabled?.id).toBe(first?.id);+ expect(reEnabled?.shareConfig.slug).toBe('stable-link');+ expect(await AgentShareModel.findByShareId(serverDB, first!.id)).not.toBeNull();+ expect(await AgentShareModel.findBySlugOrId(serverDB, 'stable-link')).not.toBeNull();+ });+ });++ describe('updateSlug', () => {+ it('persists a valid custom slug', async () => {+ await agentShareModel.create(agentId);++ const updated = await agentShareModel.updateSlug(agentId, 'my-cool-bot');++ expect(updated?.shareConfig.slug).toBe('my-cool-bot');+ expect((await agentShareModel.getByAgentId(agentId))?.shareConfig.slug).toBe('my-cool-bot');+ });++ it('clears the custom slug with null', async () => {+ await agentShareModel.create(agentId);+ await agentShareModel.updateSlug(agentId, 'short-lived');++ const cleared = await agentShareModel.updateSlug(agentId, null);++ expect(cleared?.shareConfig.slug).toBeUndefined();+ expect(await AgentShareModel.findBySlugOrId(serverDB, 'short-lived')).toBeNull();+ });++ it.each([+ ['single char', 'a'],+ ['too short', 'ab'],+ ['uppercase', 'My-Bot'],+ ['leading hyphen', '-my-bot'],+ ['trailing hyphen', 'my-bot-'],+ ['underscore', 'my_bot'],+ ['uuid-shaped (unreachable: id lookup wins)', '01234567-89ab-4cde-8f01-23456789abcd'],+ ])('rejects an invalid slug (%s)', async (_label, slug) => {+ await agentShareModel.create(agentId);++ await expect(agentShareModel.updateSlug(agentId, slug)).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ });++ it('rejects a reserved slug', async () => {+ await agentShareModel.create(agentId);++ await expect(agentShareModel.updateSlug(agentId, 'settings')).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ });++ it('rejects a slug already taken by another share', async () => {+ await agentShareModel.create(agentId);+ await otherAgentShareModel.create(otherAgentId);+ await agentShareModel.updateSlug(agentId, 'taken-slug');++ await expect(+ otherAgentShareModel.updateSlug(otherAgentId, 'taken-slug'),+ ).rejects.toMatchObject({ code: 'CONFLICT' });+ });++ it('allows re-setting the same slug on the same share', async () => {+ await agentShareModel.create(agentId);+ await agentShareModel.updateSlug(agentId, 'stable-slug');++ await expect(agentShareModel.updateSlug(agentId, 'stable-slug')).resolves.toMatchObject({+ shareConfig: { slug: 'stable-slug' },+ });+ });++ it('resolves to null (not a share) for missing, foreign, or workspace agents', async () => {+ // Ownership resolution runs through the same `withOwnedPersonalAgentLock`+ // helper `updateConfig`/`updateVisibility` use, so an unowned/missing+ // agent resolves to `null` here too — the router's `requireShare` is what+ // turns that into a `NOT_FOUND` for the caller.+ expect(await agentShareModel.updateSlug('missing-agent', 'foo-bar')).toBeNull();+ expect(await agentShareModel.updateSlug(otherAgentId, 'foo-bar')).toBeNull();+ expect(await agentShareModel.updateSlug(workspaceAgentId, 'foo-bar')).toBeNull();+ });+ });++ describe('findBySlugOrId', () => {+ it('resolves a share by its custom slug', async () => {+ const created = await agentShareModel.create(agentId, 'link');+ await agentShareModel.updateSlug(agentId, 'find-me');++ const share = await AgentShareModel.findBySlugOrId(serverDB, 'find-me');++ expect(share?.shareId).toBe(created!.id);+ });++ it('resolves a slug case-insensitively (stored slugs are lowercase)', async () => {+ const created = await agentShareModel.create(agentId, 'link');+ await agentShareModel.updateSlug(agentId, 'find-me');++ const share = await AgentShareModel.findBySlugOrId(serverDB, 'FIND-Me');++ expect(share?.shareId).toBe(created!.id);+ });++ it('resolves a share by its UUID id', async () => {+ const created = await agentShareModel.create(agentId, 'link');++ const share = await AgentShareModel.findBySlugOrId(serverDB, created!.id);++ expect(share?.shareId).toBe(created!.id);+ });++ it('resolves a share of any visibility (access check is the caller’s job)', async () => {+ const created = await agentShareModel.create(agentId, 'private');+ await agentShareModel.updateSlug(agentId, 'private-slug');++ const share = await AgentShareModel.findBySlugOrId(serverDB, 'private-slug');++ expect(share?.shareId).toBe(created!.id);+ expect(share?.visibility).toBe('private');+ });++ it('returns null for an unknown slug', async () => {+ expect(await AgentShareModel.findBySlugOrId(serverDB, 'no-such-slug')).toBeNull();+ });++ it('returns null for an unknown UUID', async () => {+ expect(+ await AgentShareModel.findBySlugOrId(serverDB, '00000000-0000-0000-0000-000000000000'),+ ).toBeNull();+ });+ });++ describe('public lookup', () => {+ it('returns the minimum public agent metadata', async () => {+ const created = await agentShareModel.create(agentId, 'link');++ const share = await AgentShareModel.findByShareId(serverDB, created!.id);++ expect(share).toMatchObject({+ agentBackgroundColor: '#000000',+ agentDescription: 'Shareable agent',+ agentId,+ agentName: 'Shareable Agent',+ agentTitle: 'Shareable Agent Title',+ ownerId: userId,+ shareConfig: expect.objectContaining({+ maxTopicsPerVisitor: 5,+ maxTurnsPerTopic: 20,+ }),+ shareId: created!.id,+ visibility: 'link',+ });+ });++ it('does not expose a workspace agent even if a share row exists', async () => {+ const [share] = await serverDB+ .insert(agentShares)+ .values({+ agentId: workspaceAgentId,+ shareConfig: { maxTopicsPerVisitor: 5, maxTurnsPerTopic: 20 },+ visibility: 'link',+ })+ .returning();++ expect(await AgentShareModel.findByShareId(serverDB, share.id)).toBeNull();+ });++ it('returns null for an unknown UUID', async () => {+ expect(+ await AgentShareModel.findByShareId(serverDB, '00000000-0000-0000-0000-000000000000'),+ ).toBeNull();+ });++ it('treats a malformed UUID as not found', async () => {+ expect(await AgentShareModel.findByShareId(serverDB, 'not-a-uuid')).toBeNull();+ await expect(+ AgentShareModel.findByShareIdWithAccessCheck(serverDB, 'not-a-uuid', userId),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });+ });++ describe('access checks', () => {+ it('allows the owner to access a private share', async () => {+ const created = await agentShareModel.create(agentId);++ const share = await AgentShareModel.findByShareIdWithAccessCheck(+ serverDB,+ created!.id,+ userId,+ );++ expect(share.shareId).toBe(created!.id);+ });++ // NOT_FOUND rather than FORBIDDEN so a stranger cannot tell a paused share+ // from a non-existent one.+ it('hides a private share from non-owners as NOT_FOUND', async () => {+ const created = await agentShareModel.create(agentId);++ await expect(+ AgentShareModel.findByShareIdWithAccessCheck(serverDB, created!.id, otherUserId),+ ).rejects.toMatchObject({ code: 'NOT_FOUND', message: 'Share not found' });+ });++ it('allows authenticated access to a link share', async () => {+ const created = await agentShareModel.create(agentId, 'link');++ const share = await AgentShareModel.findByShareIdWithAccessCheck(+ serverDB,+ created!.id,+ otherUserId,+ );++ expect(share.shareId).toBe(created!.id);+ });++ it('throws NOT_FOUND for an unknown UUID', async () => {+ await expect(+ AgentShareModel.findByShareIdWithAccessCheck(+ serverDB,+ '00000000-0000-0000-0000-000000000000',+ userId,+ ),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });+ });++ describe('isRunStillAuthorized', () => {+ it('authorizes a live link share on a personal agent', async () => {+ const created = await agentShareModel.create(agentId, 'link');++ expect(+ await AgentShareModel.isRunStillAuthorized(serverDB, { agentId, shareId: created!.id }),+ ).toBe(true);+ });++ it('revokes once the share is paused or replaced', async () => {+ const created = await agentShareModel.create(agentId, 'link');++ await agentShareModel.updateVisibility(agentId, 'private');+ expect(+ await AgentShareModel.isRunStillAuthorized(serverDB, { agentId, shareId: created!.id }),+ ).toBe(false);++ await agentShareModel.updateVisibility(agentId, 'link');+ expect(+ await AgentShareModel.isRunStillAuthorized(serverDB, {+ agentId,+ shareId: '00000000-0000-0000-0000-000000000000',+ }),+ ).toBe(false);+ });++ // `transferAgent` does not touch `agent_shares`; the per-step check must+ // notice the agent left personal scope on its own, like `findByShareId`.+ it('revokes an in-flight run once the agent is moved into a workspace', async () => {+ const created = await agentShareModel.create(agentId, 'link');+ await serverDB.update(agents).set({ workspaceId }).where(eq(agents.id, agentId));++ expect(+ await AgentShareModel.isRunStillAuthorized(serverDB, { agentId, shareId: created!.id }),+ ).toBe(false);+ });+ });++ describe('readCurrentVisitorCaps', () => {+ it('reads fresh caps and the live shareId', async () => {+ const created = await agentShareModel.create(agentId);+ await agentShareModel.updateConfig(agentId, {+ maxTopicsPerVisitor: 3,+ maxTurnsPerTopic: 8,+ monthlySpendLimit: 2.5,+ });++ await expect(AgentShareModel.readCurrentVisitorCaps(serverDB, agentId)).resolves.toEqual({+ maxTopicsPerVisitor: 3,+ maxTurnsPerTopic: 8,+ monthlySpendLimit: 2.5,+ shareId: created!.id,+ });+ });++ it('falls back to defaults and a null shareId when there is no share', async () => {+ await expect(AgentShareModel.readCurrentVisitorCaps(serverDB, agentId)).resolves.toEqual({+ maxTopicsPerVisitor: 5,+ maxTurnsPerTopic: 20,+ monthlySpendLimit: 10,+ shareId: null,+ });+ });+ });++ describe('incrementUserViewCount', () => {+ it('atomically records successful page views', async () => {+ const created = await agentShareModel.create(agentId);++ await Promise.all([+ AgentShareModel.incrementUserViewCount(serverDB, created!.id),+ AgentShareModel.incrementUserViewCount(serverDB, created!.id),+ AgentShareModel.incrementUserViewCount(serverDB, created!.id),+ ]);++ const [share] = await serverDB+ .select({ userViewCount: agentShares.userViewCount })+ .from(agentShares)+ .where(eq(agentShares.id, created!.id));+ expect(share.userViewCount).toBe(3);+ });+ });+});diff --git a/packages/database/src/models/__tests__/agentTransfer.test.ts b/packages/database/src/models/__tests__/agentTransfer.test.tsindex c5f703add9e..077d24a18f0 100644--- a/packages/database/src/models/__tests__/agentTransfer.test.ts+++ b/packages/database/src/models/__tests__/agentTransfer.test.ts@@ -9,6 +9,7 @@ import {agentDocuments,agents,agentsFiles,+ agentShares,agentsKnowledgeBases,agentsToSessions,briefs,@@ -41,7 +42,7 @@ import {workspaces,} from '../../schemas';import type { LobeChatDatabase } from '../../type';-import { AgentModel } from '../agent';+import { AGENT_SHARED_TRANSFER_BLOCKED, AgentModel } from '../agent';import { ExpertiseModel } from '../expertise';import {TOPIC_COMMENT_TOPIC_NOT_FOUND,@@ -1066,6 +1067,56 @@ describe('AgentModel.transferAgent', () => {'Agent not found',);});++ // Regression: a share carries the previous owner's tool grants, custom+ // slug, and (in Cloud) monthly spend cap, and its visitor conversations are+ // stored under (agentId, senderId) within that owner's scope — an ownership+ // transfer must be REFUSED while the share row exists. See+ // `AgentModel.transferAgents` step 1d and the `isRunStillAuthorized` doc in+ // `agentShare.ts`.+ it('should reject the transfer when the agent still carries a share row', async () => {+ const model = new AgentModel(serverDB, userId);+ const agent = await model.create({ title: 'Shared Agent', slug: 'shared-agent' });++ await serverDB+ .insert(agentShares)+ .values({ agentId: agent.id, shareConfig: { monthlySpendLimit: 5 }, visibility: 'link' });++ await expect(model.transferAgent(agent.id, null, targetUserId)).rejects.toThrow(+ AGENT_SHARED_TRANSFER_BLOCKED,+ );++ // Agent stays with the original owner: batch guard fires before any+ // mutation, so neither `agents.userId` nor the share row change.+ const [row] = await serverDB.select().from(agents).where(eq(agents.id, agent.id));+ expect(row.userId).toBe(userId);+ const remaining = await serverDB+ .select()+ .from(agentShares)+ .where(eq(agentShares.agentId, agent.id));+ expect(remaining).toHaveLength(1);+ });++ it('should keep the share row on a same-owner personal ↔ workspace round-trip', async () => {+ const model = new AgentModel(serverDB, userId);+ const agent = await model.create({ title: 'Roundtrip Agent', slug: 'roundtrip-agent' });++ await serverDB+ .insert(agentShares)+ .values({ agentId: agent.id, shareConfig: { monthlySpendLimit: 5 }, visibility: 'link' });++ // Personal → workspace (owner unchanged, share paused via workspaceId join).+ await model.transferAgent(agent.id, wsId1, userId);+ let rows = await serverDB.select().from(agentShares).where(eq(agentShares.agentId, agent.id));+ expect(rows).toHaveLength(1);++ // Workspace → personal, same owner: share resumes.+ const wsModel = new AgentModel(serverDB, userId, wsId1);+ await wsModel.transferAgent(agent.id, null, userId);+ rows = await serverDB.select().from(agentShares).where(eq(agentShares.agentId, agent.id));+ expect(rows).toHaveLength(1);+ expect(rows[0].visibility).toBe('link');+ });});describe('AgentModel.transferAgent scope riders (connectors & documents)', () => {diff --git a/packages/database/src/models/__tests__/agentTransferOwnership.test.ts b/packages/database/src/models/__tests__/agentTransferOwnership.test.tsindex eca8195cc86..916e66c49cd 100644--- a/packages/database/src/models/__tests__/agentTransferOwnership.test.ts+++ b/packages/database/src/models/__tests__/agentTransferOwnership.test.ts@@ -14,6 +14,7 @@ import {agentProviderAccounts,agents,agentsFiles,+ agentShares,agentsKnowledgeBases,chatGroups,chatGroupsAgents,@@ -34,7 +35,7 @@ import {workspaces,} from '../../schemas';import type { LobeChatDatabase } from '../../type';-import { AGENT_OWNERSHIP_STALE, AgentModel } from '../agent';+import { AGENT_OWNERSHIP_STALE, AGENT_SHARED_TRANSFER_BLOCKED, AgentModel } from '../agent';import { AGENT_TRANSFER_IN_PROGRESS, AgentTransferJobModel } from '../agentTransferJob';const serverDB: LobeChatDatabase = await getTestDB();@@ -70,6 +71,25 @@ afterEach(async () => {});describe('AgentModel.transferAgentOwnership', () => {+ it('rejects the handover while the agent still carries a share row', async () => {+ const agent = await ownerModel.create({ slug: 'shared-handover', title: 'Shared Handover' });+ await serverDB+ .insert(agentShares)+ .values({ agentId: agent.id, shareConfig: { monthlySpendLimit: 5 }, visibility: 'link' });++ await expect(+ handover({ agentId: agent.id, fromUserId: ownerId, toUserId: recipientId }),+ ).rejects.toThrow(AGENT_SHARED_TRANSFER_BLOCKED);++ // Guard fires before any mutation: the agent stays with the previous+ // owner and the share row is untouched. The block lifts only once the+ // share row itself is removed (no product entry point yet).+ const [row] = await serverDB.select().from(agents).where(eq(agents.id, agent.id));+ expect(row.userId).toBe(ownerId);+ const rows = await serverDB.select().from(agentShares).where(eq(agentShares.agentId, agent.id));+ expect(rows).toHaveLength(1);+ });+it('flips only the agent owner; scope, slug and visibility stay put', async () => {const agent = await ownerModel.create({slug: 'handover-agent',diff --git a/packages/database/src/models/__tests__/messages/message.delete.test.ts b/packages/database/src/models/__tests__/messages/message.delete.test.tsindex facb0504e0a..a022d98397e 100644--- a/packages/database/src/models/__tests__/messages/message.delete.test.ts+++ b/packages/database/src/models/__tests__/messages/message.delete.test.ts@@ -997,6 +997,166 @@ describe('MessageModel Delete Tests', () => {});});+ describe('agent-share visitor messages', () => {+ // Visitor messages live under the creator's userId but are invisible to the+ // creator, so id-less sweeps must leave them alone.+ beforeEach(async () => {+ await serverDB.transaction(async (trx) => {+ await trx.insert(agents).values([{ id: 'share-agent', userId, title: 'Shared Agent' }]);++ await trx.insert(topics).values([+ { agentId: 'share-agent', id: 'creator-topic', userId },+ { agentId: 'share-agent', id: 'visitor-topic', senderId: 'visitor-a', userId },+ ]);++ await trx.insert(messages).values([+ {+ agentId: 'share-agent',+ content: 'creator message',+ id: 'creator-msg',+ role: 'user',+ topicId: 'creator-topic',+ userId,+ },+ {+ agentId: 'share-agent',+ content: 'visitor message',+ id: 'visitor-msg',+ role: 'user',+ topicId: 'visitor-topic',+ userId,+ },+ ]);+ });+ });++ it('deleteAllMessages should keep visitor messages', async () => {+ await messageModel.deleteAllMessages();++ const remaining = await serverDB.query.messages.findMany({+ where: eq(messages.userId, userId),+ });++ expect(remaining).toHaveLength(1);+ expect(remaining[0].id).toBe('visitor-msg');+ });++ it('batchDeleteByAgentId should keep visitor messages', async () => {+ await messageModel.batchDeleteByAgentId('share-agent');++ const remaining = await serverDB.query.messages.findMany({+ where: eq(messages.userId, userId),+ });++ expect(remaining).toHaveLength(1);+ expect(remaining[0].id).toBe('visitor-msg');+ });++ it('deleteMessage should keep a visitor message', async () => {+ // The creator can obtain a raw visitor message id out of band (data+ // export), so naming the id must not be enough to destroy it.+ await messageModel.deleteMessage('visitor-msg');++ const remaining = await serverDB.query.messages.findMany({+ where: eq(messages.userId, userId),+ });++ expect(remaining.map((m) => m.id).sort()).toEqual(['creator-msg', 'visitor-msg']);+ });++ it('deleteMessage should still delete the creator own message', async () => {+ await messageModel.deleteMessage('creator-msg');++ const remaining = await serverDB.query.messages.findMany({+ where: eq(messages.userId, userId),+ });++ expect(remaining.map((m) => m.id)).toEqual(['visitor-msg']);+ });++ it('deleteMessage should delete a visitor message when the runtime opts in', async () => {+ await messageModel.deleteMessage('visitor-msg', { includeShareVisitor: true });++ const remaining = await serverDB.query.messages.findMany({+ where: eq(messages.userId, userId),+ });++ expect(remaining.map((m) => m.id)).toEqual(['creator-msg']);+ });++ it('deleteMessages should drop only the non-visitor ids of a mixed batch', async () => {+ await messageModel.deleteMessages(['creator-msg', 'visitor-msg']);++ const remaining = await serverDB.query.messages.findMany({+ where: eq(messages.userId, userId),+ });++ expect(remaining.map((m) => m.id)).toEqual(['visitor-msg']);+ });++ it('deleteMessages should delete visitor messages when the runtime opts in', async () => {+ await messageModel.deleteMessages(['visitor-msg'], { includeShareVisitor: true });++ const remaining = await serverDB.query.messages.findMany({+ where: eq(messages.userId, userId),+ });++ expect(remaining.map((m) => m.id)).toEqual(['creator-msg']);+ });++ it('deleteMessagesBySession should keep a visitor topic message', async () => {+ // `removeMessagesByAssistant`/`removeMessagesByGroup` route through this+ // sweep, so the default must exclude visitor rows just like the id-less+ // `deleteAllMessages` sweep above.+ await messageModel.deleteMessagesBySession(undefined, 'visitor-topic');++ const remaining = await serverDB.query.messages.findMany({+ where: eq(messages.userId, userId),+ });++ expect(remaining.map((m) => m.id).sort()).toEqual(['creator-msg', 'visitor-msg']);+ });++ it('deleteMessagesBySession should delete a visitor topic message when the runtime opts in', async () => {+ await messageModel.deleteMessagesBySession(undefined, 'visitor-topic', null, {+ includeShareVisitor: true,+ });++ const remaining = await serverDB.query.messages.findMany({+ where: eq(messages.userId, userId),+ });++ expect(remaining.map((m) => m.id)).toEqual(['creator-msg']);+ });++ it('findShareVisitorMessageIds should report only the visitor ids of a mixed batch', async () => {+ // Creator-facing update RPCs diff their targets against this finder, so+ // it must name visitor rows and stay silent about the creator's own.+ const visitorIds = await messageModel.findShareVisitorMessageIds([+ 'creator-msg',+ 'visitor-msg',+ ]);++ expect(visitorIds).toEqual(['visitor-msg']);+ });++ it('findShareVisitorMessageIds should ignore ids that match no row', async () => {+ const visitorIds = await messageModel.findShareVisitorMessageIds(['missing-msg']);++ expect(visitorIds).toEqual([]);+ });++ it('deleting the agent still cascades visitor messages away', async () => {+ await serverDB.delete(agents).where(eq(agents.id, 'share-agent'));++ const remaining = await serverDB.query.messages.findMany({+ where: eq(messages.userId, userId),+ });++ expect(remaining).toHaveLength(0);+ });+ });+describe('topic usage rollup', () => {const usageMsg = (id: string, totalTokens: number, cost: number) => ({id,diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.tsindex bc3c02ad160..c4fe5d3806b 100644--- a/packages/database/src/models/__tests__/messages/message.query.test.ts+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts@@ -1,4 +1,5 @@import { INBOX_SESSION_ID } from '@lobechat/const';+import { MessageGroupType } from '@lobechat/types';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -14,6 +15,7 @@ import {embeddings,fileChunks,files,+ messageGroups,messageQueries,messageQueryChunks,messages,@@ -26,7 +28,7 @@ import {users,} from '../../../schemas';import type { LobeChatDatabase } from '../../../type';-import { MessageModel } from '../../message';+import { MessageModel, toVisitorMessage } from '../../message';import { codeEmbedding } from '../fixtures/embedding';const serverDB: LobeChatDatabase = await getTestDB();@@ -1508,6 +1510,248 @@ describe('MessageModel Query Tests', () => {});});+ describe('agent-share visitor isolation', () => {+ const visitorUserId = 'message-query-visitor';+ const visitorTopicId = 'topic-visitor-direct-read';++ beforeEach(async () => {+ // A visitor topic is stored under the CREATOR's userId; only `senderId`+ // marks it as belonging to a share visitor.+ await serverDB.insert(topics).values([+ { id: visitorTopicId, senderId: visitorUserId, title: 'visitor topic', userId },+ { id: 'topic-creator-own', title: 'creator topic', userId },+ ]);+ await serverDB.insert(messages).values([+ {+ content: 'visitor secret',+ id: 'visitor-direct-msg',+ role: 'user',+ topicId: visitorTopicId,+ userId,+ },+ {+ content: 'creator message',+ id: 'creator-direct-msg',+ role: 'user',+ topicId: 'topic-creator-own',+ userId,+ },+ ]);+ });++ it('hides visitor messages when the creator reads the visitor topic by id', async () => {+ const result = await messageModel.query({ topicId: visitorTopicId });++ expect(result).toHaveLength(0);+ });++ it('still returns the creator’s own topic messages', async () => {+ const result = await messageModel.query({ topicId: 'topic-creator-own' });++ expect(result.map((item) => item.id)).toEqual(['creator-direct-msg']);+ });++ it('keeps serving the visitor through queryForVisitor', async () => {+ const result = await messageModel.queryForVisitor({ topicId: visitorTopicId });++ expect(result.map((item) => item.id)).toEqual(['visitor-direct-msg']);+ });++ it('honours an explicit allowShareVisitor opt-in (agent runtime path)', async () => {+ const result = await messageModel.query(+ { topicId: visitorTopicId },+ { allowShareVisitor: true },+ );++ expect(result.map((item) => item.id)).toEqual(['visitor-direct-msg']);+ });++ it('excludes visitor messages from queryTopicTranscript', async () => {+ const visitorTranscript = await messageModel.queryTopicTranscript({+ limit: 50,+ offset: 0,+ topicId: visitorTopicId,+ });++ expect(visitorTranscript.items).toHaveLength(0);+ expect(visitorTranscript.total).toBe(0);++ const ownTranscript = await messageModel.queryTopicTranscript({+ limit: 50,+ offset: 0,+ topicId: 'topic-creator-own',+ });++ expect(ownTranscript.items.map((item) => item.id)).toEqual(['creator-direct-msg']);+ });++ it('keeps countByTopic working for the visitor turn cap when the runtime opts in', async () => {+ // The per-topic turn cap depends on counting visitor messages, and after+ // the ownership() flip the default scope excludes visitor rows. The+ // share runtime (`reserveShareVisitorTurn` in+ // `shareVisitorAbuseGuards.ts`) constructs `MessageModel` with+ // `includeShareVisitor: true`; mirror that opt-in here.+ const defaultCount = await messageModel.countByTopic({+ role: 'user',+ topicId: visitorTopicId,+ });+ expect(defaultCount).toBe(0);++ const shareRuntimeMessageModel = new MessageModel(serverDB, userId, undefined, undefined, {+ includeShareVisitor: true,+ });+ const optedInCount = await shareRuntimeMessageModel.countByTopic({+ role: 'user',+ topicId: visitorTopicId,+ });+ expect(optedInCount).toBe(1);+ });++ it('hides synthetic message-group nodes when the creator reads a visitor topic', async () => {+ // Regression for `queryMessageGroupNodes`: a creator's default+ // `query({ topicId })` on a visitor topic returned no messages but+ // still emitted the group's `compressedGroup` node (with its `content`+ // summary) or `compareGroup` node, leaking the visitor's conversation+ // shape.+ await serverDB.insert(messageGroups).values([+ {+ content: 'visitor compression summary',+ createdAt: new Date('2024-01-01T10:00:00Z'),+ id: 'visitor-group-compress',+ topicId: visitorTopicId,+ type: MessageGroupType.Compression,+ userId,+ },+ {+ createdAt: new Date('2024-01-01T10:01:00Z'),+ id: 'visitor-group-compare',+ topicId: visitorTopicId,+ type: MessageGroupType.Parallel,+ userId,+ },+ ]);++ const creatorResult = await messageModel.query({ topicId: visitorTopicId });+ expect(creatorResult).toHaveLength(0);++ const shareRuntimeModel = new MessageModel(serverDB, userId, undefined, undefined, {+ includeShareVisitor: true,+ });+ const runtimeResult = await shareRuntimeModel.query({ topicId: visitorTopicId });+ const visitorResult = await messageModel.queryForVisitor({ topicId: visitorTopicId });++ // Both visitor-facing paths still see the group nodes — this fix+ // scopes the leak to the CREATOR's default read.+ const runtimeIds = new Set(runtimeResult.map((m) => m.id));+ expect(runtimeIds.has('visitor-group-compress')).toBe(true);+ expect(runtimeIds.has('visitor-group-compare')).toBe(true);++ const visitorIds = new Set(visitorResult.map((m) => m.id));+ expect(visitorIds.has('visitor-group-compress')).toBe(true);+ expect(visitorIds.has('visitor-group-compare')).toBe(true);+ });+ });++ describe('toVisitorMessage', () => {+ it('recursively sanitizes assistantGroup children in a compressedGroup node', async () => {+ // Regression: `children` on an assistantGroup node inside+ // `compressedMessages` carries full AssistantContentBlock data+ // (`usage`, `error`, `tools`, `metadata`, `performance`, plus nested+ // `council` messages with `sender`). The previous narrow snapshot+ // sanitize only cleared `model`/`provider`, letting the rest leak.+ const compressedGroupNode = {+ compressedMessages: [+ {+ children: [+ {+ content: 'assistant reply',+ error: {+ message: 'raw provider payload',+ type: 'ProviderBizError',+ } as any,+ id: 'assistant-child-1',+ metadata: { usage: { totalTokens: 42 } } as any,+ model: 'gpt-4o',+ performance: { latency: 100 } as any,+ provider: 'openai',+ sender: { fullName: 'Creator', id: 'creator-user-id' } as any,+ tools: [{ id: 't1', identifier: 'search' }] as any,+ usage: { totalTokens: 42 } as any,+ council: [+ {+ content: 'member reply',+ id: 'council-member-1',+ model: 'gpt-4o',+ provider: 'openai',+ role: 'assistant',+ sender: { fullName: 'Member', id: 'member-user-id' } as any,+ usage: { totalTokens: 7 } as any,+ },+ ] as any,+ } as any,+ ],+ content: '',+ id: 'assistant-group-1',+ role: 'assistantGroup',+ } as any,+ ],+ content: 'summary',+ id: 'compressed-group-1',+ role: 'compressedGroup',+ } as any;++ const stripped = toVisitorMessage(compressedGroupNode);+ const child = (stripped.compressedMessages as any[])[0].children[0];++ expect(child.sender).toBeNull();+ expect(child.usage).toBeUndefined();+ expect(child.model).toBeUndefined();+ expect(child.provider).toBeUndefined();+ expect(child.metadata?.usage).toBeUndefined();+ expect(child.error.type).not.toBe('ProviderBizError');+ // council members must be recursed, not passed through verbatim+ expect(child.council).toHaveLength(1);+ expect(child.council[0].sender).toBeNull();+ expect(child.council[0].usage).toBeUndefined();+ expect(child.council[0].model).toBeUndefined();++ // With `showModelInfo` the model snapshot survives on both the child+ // and the recursed council members, and children stay attached.+ const kept = toVisitorMessage(compressedGroupNode, { showModelInfo: true });+ const keptChild = (kept.compressedMessages as any[])[0].children[0];+ expect(keptChild.model).toBe('gpt-4o');+ expect(keptChild.usage).toEqual({ totalTokens: 42 });+ expect(keptChild.council[0].model).toBe('gpt-4o');+ expect(keptChild.council[0].usage).toEqual({ totalTokens: 7 });+ });++ it('keeps the narrow snapshot for compareGroup children in both modes', async () => {+ const compareGroupNode = {+ children: [+ {+ content: 'variant',+ createdAt: new Date('2024-01-01T10:00:00Z'),+ id: 'variant-1',+ model: 'gpt-4o',+ provider: 'openai',+ role: 'assistant',+ },+ ],+ id: 'compare-group-1',+ role: 'compareGroup',+ } as any;++ const stripped = toVisitorMessage(compareGroupNode);+ expect((stripped.children as any[])[0].model).toBeNull();+ expect((stripped.children as any[])[0].provider).toBeNull();+ expect((stripped.children as any[])[0].content).toBe('variant');++ const kept = toVisitorMessage(compareGroupNode, { showModelInfo: true });+ expect((kept.children as any[])[0].model).toBe('gpt-4o');+ expect((kept.children as any[])[0].provider).toBe('openai');+ });+ });+describe('queryAll', () => {it('should return all messages belonging to the user in descending order', async () => {// Create test data@@ -1603,6 +1847,32 @@ describe('MessageModel Query Tests', () => {expect(withoutAgent?.agentName).toBeNull();expect(withoutAgent?.agentTitle).toBeNull();});++ it('excludes messages inside an agent-share visitor topic', async () => {+ // Visitor topics keep the creator's userId, so a bare ownership filter+ // would dump visitor conversations into the creator's full export.+ await serverDB.insert(topics).values({+ id: 'topic-visitor-query-all',+ userId,+ senderId: 'visitor-user-x',+ title: 'visitor topic',+ });+ await serverDB.insert(messages).values([+ {+ id: 'visitor-msg',+ userId,+ role: 'user',+ content: 'visitor message',+ topicId: 'topic-visitor-query-all',+ },+ { id: 'creator-msg', userId, role: 'user', content: 'creator message' },+ ]);++ const result = await messageModel.queryAll();++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('creator-msg');+ });});describe('findById', () => {@@ -1710,6 +1980,32 @@ describe('MessageModel Query Tests', () => {expect(result[1].id).toBe('inbox-msg-2');});+ it('excludes agent-share visitor messages from the null-session branch', async () => {+ // Visitor messages carry no sessionId, so without the visitor predicate+ // the inbox (null-session) branch would sweep them in.+ await serverDB.insert(topics).values({+ id: 'topic-visitor-session',+ userId,+ senderId: 'visitor-user-x',+ title: 'visitor topic',+ });+ await serverDB.insert(messages).values([+ {+ id: 'visitor-inbox-msg',+ userId,+ role: 'user',+ content: 'visitor message',+ topicId: 'topic-visitor-session',+ },+ { id: 'creator-inbox-msg', userId, role: 'user', content: 'creator message' },+ ]);++ const result = await messageModel.queryBySessionId(null);++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('creator-inbox-msg');+ });+it('should query inbox messages when sessionId is undefined', async () => {await serverDB.insert(sessions).values([{ id: 'session1', userId }]);diff --git a/packages/database/src/models/__tests__/messages/message.stats.test.ts b/packages/database/src/models/__tests__/messages/message.stats.test.tsindex 4d1c926d3fc..d7194154205 100644--- a/packages/database/src/models/__tests__/messages/message.stats.test.ts+++ b/packages/database/src/models/__tests__/messages/message.stats.test.ts@@ -65,6 +65,32 @@ describe('MessageModel Statistics Tests', () => {expect(result).toBe(2);});+ it('excludes messages inside an agent-share visitor topic', async () => {+ // Agent-share visitor topics keep the creator's userId, but a non-null+ // topics.senderId marks the topic (and its messages) as visitor traffic+ // that must not count toward the creator's own analytics.+ await serverDB.insert(topics).values({+ id: 'topic-visitor-count',+ userId,+ senderId: 'visitor-user-x',+ title: 'visitor topic',+ });+ await serverDB.insert(messages).values([+ {+ id: 'visitor-msg-1',+ userId,+ role: 'user',+ content: 'visitor message',+ topicId: 'topic-visitor-count',+ },+ { id: 'creator-msg-1', userId, role: 'user', content: 'creator message' },+ ]);++ const result = await messageModel.count();++ expect(result).toBe(1);+ });+describe('count with date filters', () => {beforeEach(async () => {// Create test data with messages on different dates@@ -745,6 +771,37 @@ describe('MessageModel Statistics Tests', () => {expect(result[1]).toEqual({ id: 'claude', count: 1 });expect(result[2]).toEqual({ id: 'gpt-4', count: 1 });});++ it('excludes messages inside an agent-share visitor topic', async () => {+ await serverDB.insert(topics).values({+ id: 'topic-visitor-rank',+ userId,+ senderId: 'visitor-user-x',+ title: 'visitor topic',+ });+ await serverDB.insert(messages).values([+ {+ id: 'visitor-rank-1',+ userId,+ role: 'assistant',+ content: 'visitor message',+ model: 'gpt-4',+ topicId: 'topic-visitor-rank',+ },+ {+ id: 'creator-rank-1',+ userId,+ role: 'assistant',+ content: 'creator message',+ model: 'gpt-3.5',+ },+ ]);++ const result = await messageModel.rankModels();++ // The visitor's gpt-4 usage must not surface; only the creator's gpt-3.5 does+ expect(result).toEqual([{ id: 'gpt-3.5', count: 1 }]);+ });});describe('count with agent / topic / role filters', () => {diff --git a/packages/database/src/models/__tests__/recent.test.ts b/packages/database/src/models/__tests__/recent.test.tsindex c5274ca0410..243e08c6bb2 100644--- a/packages/database/src/models/__tests__/recent.test.ts+++ b/packages/database/src/models/__tests__/recent.test.ts@@ -165,6 +165,34 @@ describe('RecentModel', () => {expect(result[0].id).toBe('topic-real');});+ it('excludes agent-share visitor topics', async () => {+ // Agent-share visitor topics keep the creator's userId, but a non-null+ // senderId marks them as visitor traffic that must not surface in the+ // creator's own Recent feed.+ await serverDB.insert(agents).values({ id: 'agent-share-recent', userId, virtual: false });++ await serverDB.insert(topics).values([+ {+ id: 'topic-visitor-recent',+ userId,+ agentId: 'agent-share-recent',+ senderId: 'visitor-user-x',+ title: 'visitor topic',+ updatedAt: minutesAgo(1),+ },+ {+ id: 'topic-creator-recent',+ userId,+ agentId: 'agent-share-recent',+ title: 'creator topic',+ updatedAt: minutesAgo(5),+ },+ ]);++ const result = await recentModel.queryRecent();+ expect(result.map((r) => r.id)).toEqual(['topic-creator-recent']);+ });+it('excludes topics on virtual agents that are not in a group', async () => {await serverDB.insert(agents).values({ id: 'agent-virtual', userId, virtual: true });diff --git a/packages/database/src/models/__tests__/shareVisitorAbuseGuards.race.test.ts b/packages/database/src/models/__tests__/shareVisitorAbuseGuards.race.test.tsnew file mode 100644index 00000000000..c2114072a04--- /dev/null+++ b/packages/database/src/models/__tests__/shareVisitorAbuseGuards.race.test.ts@@ -0,0 +1,255 @@+import { and, count, eq } from 'drizzle-orm';+import { afterAll, beforeEach, describe, expect, it } from 'vitest';++import {+ reserveShareVisitorTopic,+ reserveShareVisitorTurn,+} from '@/server/services/aiAgent/shareVisitorAbuseGuards';++import { getTestDB } from '../../core/getTestDB';+import { agents, messages, topics, users } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { AgentShareModel } from '../agentShare';++// Real-Postgres reproduction of the agent-share visitor abuse-cap race.+//+// `shareChat.execAgent` counts a visitor's existing topics (or turns) and+// compares against the cap BEFORE dispatching to `AiAgentService.execAgent`,+// which performs the real INSERT much later — two unrelated, unlocked+// statements with nothing serializing them. A burst of concurrent requests+// from the same visitor could all read the same pre-insert count and all+// insert, exceeding `maxTopicsPerVisitor` / `maxTurnsPerTopic` by an arbitrary+// amount.+//+// `reserveShareVisitorTopicOrThrow` / `reserveShareVisitorTurnOrThrow`+// (`apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts`) close this by+// taking the SAME `agents.id FOR UPDATE` row lock every share-mutation path+// takes and re-checking the exact same counter INSIDE the same transaction as+// the INSERT, immediately before it runs.+//+// Under the client-db PGlite engine, concurrent transactions serialize on the+// single session, so the cap assertions pass trivially there; against a REAL+// node-postgres pool (`TEST_SERVER_DB=1`, separate connections → genuine+// interleave) they guard the row lock: every trial must cap the successful+// count at exactly the configured limit, never more.++const ownerId = 'share-abuse-guard-race-owner';+const visitorUserId = 'share-abuse-guard-race-visitor';+const serverDB: LobeChatDatabase = await getTestDB();++const cleanup = async () => {+ await serverDB.delete(messages).where(eq(messages.userId, ownerId));+ await serverDB.delete(topics).where(eq(topics.userId, ownerId));+ await serverDB.delete(agents).where(eq(agents.userId, ownerId));+ await serverDB.delete(users).where(eq(users.id, ownerId));+};++describe('reserveShareVisitorTopicOrThrow — visitor topic cap race (real Postgres)', () => {+ beforeEach(async () => {+ await cleanup();+ await serverDB.insert(users).values([{ id: ownerId }]);+ });++ afterAll(cleanup);++ it('never lets concurrent new-topic requests exceed maxTopicsPerVisitor', async () => {+ const TRIALS = 5;+ const CONCURRENCY = 6;+ const CAP = 3;+ let overCapTrials = 0;++ for (let i = 0; i < TRIALS; i++) {+ const agentId = `share-topic-race-agent-${i}`;+ await serverDB.insert(agents).values({ id: agentId, model: 'gpt-4o', userId: ownerId });+ // The cap is read fresh from the real `agentShares.shareConfig` inside+ // the guard's own locked transaction (`AgentShareModel+ // .readCurrentVisitorCaps`) — never a caller-supplied parameter.+ const share = await new AgentShareModel(serverDB, ownerId).create(agentId, 'link');+ await new AgentShareModel(serverDB, ownerId).updateConfig(agentId, {+ maxTopicsPerVisitor: CAP,+ });++ // Simulate CONCURRENCY visitor tabs/scripts all sending a first message+ // to a brand-new topic at the same time.+ const results = await Promise.allSettled(+ Array.from({ length: CONCURRENCY }, (_, n) =>+ reserveShareVisitorTopic(+ {+ agentId,+ db: serverDB,+ expectedShareId: share.id,+ ownerId,+ visitorUserId,+ },+ { agentId, senderId: visitorUserId, title: `visitor topic ${n}`, trigger: 'chat' },+ ),+ ),+ );++ const fulfilled = results.filter((r) => r.status === 'fulfilled').length;+ const rejected = results.filter((r) => r.status === 'rejected').length;+ expect(fulfilled + rejected).toBe(CONCURRENCY);++ const [{ value: actualTopicCount }] = await serverDB+ .select({ value: count(topics.id) })+ .from(topics)+ .where(and(eq(topics.agentId, agentId), eq(topics.senderId, visitorUserId)));++ // The reservation's own return value and the real row count must agree —+ // a lost race would show up as more rows than reservations reported, or+ // vice versa.+ if (fulfilled !== CAP || actualTopicCount !== CAP) overCapTrials++;+ }++ expect(overCapTrials).toBe(0);+ });+});++describe('reserveShareVisitorTurnOrThrow — visitor turn cap race (real Postgres)', () => {+ beforeEach(async () => {+ await cleanup();+ await serverDB.insert(users).values([{ id: ownerId }]);+ });++ afterAll(cleanup);++ it('never lets concurrent sends to the same topic exceed maxTurnsPerTopic', async () => {+ const TRIALS = 5;+ const CONCURRENCY = 6;+ const CAP = 3;+ let overCapTrials = 0;++ for (let i = 0; i < TRIALS; i++) {+ const agentId = `share-turn-race-agent-${i}`;+ const topicId = `share-turn-race-topic-${i}`;+ await serverDB.insert(agents).values({ id: agentId, model: 'gpt-4o', userId: ownerId });+ const share = await new AgentShareModel(serverDB, ownerId).create(agentId, 'link');+ await new AgentShareModel(serverDB, ownerId).updateConfig(agentId, {+ maxTurnsPerTopic: CAP,+ });+ await serverDB.insert(topics).values({+ agentId,+ id: topicId,+ senderId: visitorUserId,+ userId: ownerId,+ });++ // Simulate CONCURRENCY sends to the SAME existing topic at the same time.+ const results = await Promise.allSettled(+ Array.from({ length: CONCURRENCY }, (_, n) =>+ reserveShareVisitorTurn(+ { agentId, db: serverDB, expectedShareId: share.id, ownerId, topicId },+ { content: `turn ${n}`, role: 'user', topicId },+ ),+ ),+ );++ const fulfilled = results.filter((r) => r.status === 'fulfilled').length;+ const rejected = results.filter((r) => r.status === 'rejected').length;+ expect(fulfilled + rejected).toBe(CONCURRENCY);++ const [{ value: actualTurnCount }] = await serverDB+ .select({ value: count(messages.id) })+ .from(messages)+ .where(and(eq(messages.topicId, topicId), eq(messages.role, 'user')));++ if (fulfilled !== CAP || actualTurnCount !== CAP) overCapTrials++;+ }++ expect(overCapTrials).toBe(0);+ });+});++// Adapted from the old design's `staleAuthorization` race: the revocation+// token is the `agentShares.id` itself rather than a separate generation+// counter. Turning sharing off only flips the row to `private` (the visibility+// check covers that), while a hard delete replaces the instance outright (the+// id check covers that). `assertShareStillAuthorized` fails closed on a+// missing row, a non-`link` visibility, OR an id mismatch — all three checked+// inside the guard's own locked transaction, BEFORE any row is written.+describe('shareVisitorAbuseGuards — revoked share authorization', () => {+ beforeEach(async () => {+ await cleanup();+ await serverDB.insert(users).values([{ id: ownerId }]);+ });++ afterAll(cleanup);++ it('rejects a new-topic reservation once the owner made the link private, and inserts nothing', async () => {+ const agentId = 'revoked-share-topic-private';+ await serverDB.insert(agents).values({ id: agentId, model: 'gpt-4o', userId: ownerId });+ const shareModel = new AgentShareModel(serverDB, ownerId);+ const share = await shareModel.create(agentId, 'link');++ // Owner revokes access while the visitor's request is still resolving.+ await shareModel.updateVisibility(agentId, 'private');++ await expect(+ reserveShareVisitorTopic(+ { agentId, db: serverDB, expectedShareId: share.id, ownerId, visitorUserId },+ { agentId, senderId: visitorUserId, title: 'stale-topic' },+ ),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });++ const inserted = await serverDB+ .select({ id: topics.id })+ .from(topics)+ .where(eq(topics.agentId, agentId));+ expect(inserted.length).toBe(0);+ });++ it('rejects a reservation stamped with a superseded share instance', async () => {+ const agentId = 'revoked-share-topic-replaced';+ await serverDB.insert(agents).values({ id: agentId, model: 'gpt-4o', userId: ownerId });+ const shareModel = new AgentShareModel(serverDB, ownerId);+ const staleShare = await shareModel.create(agentId, 'link');++ // Turning sharing off only pauses it (visibility flip), so the id survives+ // that cycle. A HARD delete is what replaces the instance: the new row is+ // ALSO `link`, so a bare visibility check would pass here — only the id+ // comparison catches it.+ await shareModel.deleteByAgentId(agentId);+ const freshShare = await shareModel.create(agentId, 'link');+ expect(freshShare.id).not.toBe(staleShare.id);++ await expect(+ reserveShareVisitorTopic(+ { agentId, db: serverDB, expectedShareId: staleShare.id, ownerId, visitorUserId },+ { agentId, senderId: visitorUserId, title: 'stale-instance-topic' },+ ),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });++ const inserted = await serverDB+ .select({ id: topics.id })+ .from(topics)+ .where(eq(topics.agentId, agentId));+ expect(inserted.length).toBe(0);+ });++ it('rejects a turn reservation once the owner made the link private, and inserts no message', async () => {+ const agentId = 'revoked-share-turn-private';+ await serverDB.insert(agents).values({ id: agentId, model: 'gpt-4o', userId: ownerId });+ const shareModel = new AgentShareModel(serverDB, ownerId);+ const share = await shareModel.create(agentId, 'link');++ const [topic] = await serverDB+ .insert(topics)+ .values({ agentId, senderId: visitorUserId, userId: ownerId })+ .returning();++ await shareModel.updateVisibility(agentId, 'private');++ await expect(+ reserveShareVisitorTurn(+ { agentId, db: serverDB, expectedShareId: share.id, ownerId, topicId: topic.id },+ { content: 'stale-turn', role: 'user', topicId: topic.id },+ ),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });++ const inserted = await serverDB+ .select({ id: messages.id })+ .from(messages)+ .where(eq(messages.topicId, topic.id));+ expect(inserted.length).toBe(0);+ });+});diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.tsindex aad527f7fe5..e7187d77f42 100644--- a/packages/database/src/models/__tests__/topic.test.ts+++ b/packages/database/src/models/__tests__/topic.test.ts@@ -131,6 +131,105 @@ describe('TopicModel', () => {const found = await topicModel.findById('topic-foreign');expect(found).toBeUndefined();});++ it('does not return an agent-share visitor topic by default (creator-facing scope)', async () => {+ await serverDB.insert(topics).values({+ id: 'topic-visitor-find',+ senderId: 'visitor-user-x',+ title: 'visitor topic',+ userId,+ });++ const found = await topicModel.findById('topic-visitor-find');+ expect(found).toBeUndefined();+ });++ it('returns an agent-share visitor topic when includeShareVisitor is opted in', async () => {+ await serverDB.insert(topics).values({+ id: 'topic-visitor-find-opted',+ senderId: 'visitor-user-x',+ title: 'visitor topic',+ userId,+ });++ const shareRuntimeModel = new TopicModel(serverDB, userId, undefined, undefined, {+ includeShareVisitor: true,+ });+ const found = await shareRuntimeModel.findById('topic-visitor-find-opted');+ expect(found?.id).toBe('topic-visitor-find-opted');+ });+ });++ describe('findOwnTopicById', () => {+ it('returns the creator’s own topic', async () => {+ const topic = await topicModel.create({ title: 'own' });++ const found = await topicModel.findOwnTopicById(topic.id);+ expect(found?.id).toBe(topic.id);+ });++ it('excludes an agent-share visitor topic', async () => {+ // Visitor topics carry the creator's userId, so ownership alone would let+ // the creator read a visitor conversation from a raw topic id.+ await serverDB.insert(topics).values({+ id: 'topic-visitor-find-own',+ senderId: 'visitor-user-x',+ title: 'visitor topic',+ userId,+ });++ const found = await topicModel.findOwnTopicById('topic-visitor-find-own');+ expect(found).toBeUndefined();+ });+ });++ describe('findOwnTopicsByIds', () => {+ it('returns the creator’s own topics', async () => {+ const topic = await topicModel.create({ title: 'own' });++ const found = await topicModel.findOwnTopicsByIds([topic.id]);+ expect(found.map((t) => t.id)).toEqual([topic.id]);+ });++ it('excludes an agent-share visitor topic from a mixed batch', async () => {+ // Visitor topics carry the creator's userId, so ownership alone would let+ // the creator read a visitor conversation from a raw topic id.+ const own = await topicModel.create({ title: 'own' });+ await serverDB.insert(topics).values({+ id: 'topic-visitor-find-own-ids',+ senderId: 'visitor-user-x',+ title: 'visitor topic',+ userId,+ });++ const found = await topicModel.findOwnTopicsByIds([own.id, 'topic-visitor-find-own-ids']);++ expect(found.map((t) => t.id)).toEqual([own.id]);+ });+ });++ describe('findShareVisitorTopicIds', () => {+ it('reports only the visitor ids of a mixed batch', async () => {+ // Creator-facing update RPCs diff their targets against this finder, so+ // it must name visitor rows and stay silent about the creator's own.+ const own = await topicModel.create({ title: 'own' });+ await serverDB.insert(topics).values({+ id: 'topic-visitor-ids',+ senderId: 'visitor-user-x',+ title: 'visitor topic',+ userId,+ });++ const visitorIds = await topicModel.findShareVisitorTopicIds([own.id, 'topic-visitor-ids']);++ expect(visitorIds).toEqual(['topic-visitor-ids']);+ });++ it('ignores ids that match no row', async () => {+ const visitorIds = await topicModel.findShareVisitorTopicIds(['topic-missing']);++ expect(visitorIds).toEqual([]);+ });});describe('query', () => {@@ -181,6 +280,34 @@ describe('TopicModel', () => {expect(items.map((t) => t.id)).toEqual(['t-g1']);});+ it('excludes agent-share visitor topics from the agentId branch', async () => {+ // Agent-share visitor topics keep the CREATOR's userId (so plain+ // ownership matches them) but carry a non-null senderId. The creator's+ // own topic sidebar (`query({ agentId })`) must never surface them —+ // only the visitor-scoped `queryBySender` should.+ await serverDB.insert(agents).values({ id: 'agent-share', userId });+ await serverDB.insert(topics).values([+ { agentId: 'agent-share', id: 't-creator', title: 'creator', userId },+ {+ agentId: 'agent-share',+ id: 't-visitor',+ senderId: 'visitor-user-x',+ title: 'visitor',+ userId,+ },+ ]);++ const { items, total } = await topicModel.query({ agentId: 'agent-share' });+ expect(items.map((t) => t.id)).toEqual(['t-creator']);+ expect(total).toBe(1);++ const visitorItems = await topicModel.queryBySender({+ agentId: 'agent-share',+ senderId: 'visitor-user-x',+ });+ expect(visitorItems.map((t) => t.id)).toEqual(['t-visitor']);+ });+describe('status filtering & ordering', () => {it('excludes topics whose status is in excludeStatuses but keeps null status', async () => {await serverDB.insert(agents).values({ id: 'agent-s', userId });@@ -311,6 +438,64 @@ describe('TopicModel', () => {});});+ describe('queryBySender', () => {+ it('projects only the visitor-safe runningOperation fields, stripping the rest of metadata', async () => {+ await serverDB.insert(agents).values({ id: 'agent-share-running', userId });+ await serverDB.insert(topics).values({+ agentId: 'agent-share-running',+ id: 't-visitor-running',+ metadata: {+ // Creator-only fields that must never reach a visitor.+ model: 'gpt-4',+ runningOperation: {+ assistantMessageId: 'ast-1',+ deviceId: 'device-1',+ heteroType: 'claude-code',+ hooks: [{ event: 'onComplete', type: 'webhook', url: 'https://example.com' } as any],+ operationId: 'op-1',+ scope: 'main',+ threadId: 'thd-1',+ },+ },+ senderId: 'visitor-user-running',+ title: 'running',+ userId,+ });++ const [item] = await topicModel.queryBySender({+ agentId: 'agent-share-running',+ senderId: 'visitor-user-running',+ });++ expect(item.runningOperation).toEqual({+ assistantMessageId: 'ast-1',+ heteroType: 'claude-code',+ operationId: 'op-1',+ scope: 'main',+ threadId: 'thd-1',+ });+ expect(item).not.toHaveProperty('metadata');+ });++ it('returns a null runningOperation when the topic has no active run', async () => {+ await serverDB.insert(agents).values({ id: 'agent-share-idle', userId });+ await serverDB.insert(topics).values({+ agentId: 'agent-share-idle',+ id: 't-visitor-idle',+ senderId: 'visitor-user-idle',+ title: 'idle',+ userId,+ });++ const [item] = await topicModel.queryBySender({+ agentId: 'agent-share-idle',+ senderId: 'visitor-user-idle',+ });++ expect(item.runningOperation).toBeNull();+ });+ });+describe('queryTopics', () => {it('filters by the given statuses and is scoped to the owner', async () => {await serverDB.insert(topics).values([@@ -333,6 +518,22 @@ describe('TopicModel', () => {expect(result.map((t) => t.id).sort()).toEqual(['t1', 't2']);});+ it('excludes agent-share visitor topics', async () => {+ await serverDB.insert(topics).values([+ { id: 'qt-creator', status: 'running', title: 'creator', userId },+ {+ id: 'qt-visitor',+ senderId: 'visitor-user-x',+ status: 'running',+ title: 'visitor',+ userId,+ },+ ]);++ const result = await topicModel.queryTopics({ statuses: ['running'] });+ expect(result.map((t) => t.id)).toEqual(['qt-creator']);+ });+it('omits the last assistant message unless asked for it', async () => {await serverDB.insert(topics).values({ id: 't-lm', status: 'unread', title: 'lm', userId });await serverDB.insert(messages).values({@@ -500,6 +701,15 @@ describe('TopicModel', () => {expect(await topicModel.count()).toBe(2);expect(await topicModel.count({ agentId: 'agent-c' })).toBe(1);});++ it('excludes agent-share visitor topics', async () => {+ await serverDB.insert(topics).values([+ { id: 'count-creator', title: 'creator', userId },+ { id: 'count-visitor', senderId: 'visitor-user-x', title: 'visitor', userId },+ ]);++ expect(await topicModel.count()).toBe(1);+ });});describe('update', () => {diff --git a/packages/database/src/models/__tests__/topicSummary.test.ts b/packages/database/src/models/__tests__/topicSummary.test.tsindex 83eb5544f51..2058a854135 100644--- a/packages/database/src/models/__tests__/topicSummary.test.ts+++ b/packages/database/src/models/__tests__/topicSummary.test.ts@@ -126,6 +126,79 @@ describe('TopicSummaryModel', () => {expect(result).toEqual([]);});+ it('excludes share-visitor topics from candidates', async () => {+ // Visitor topics carry the creator's userId plus a non-null senderId so+ // they would otherwise satisfy the ownership predicate; the auto-summary+ // worker must never spend the creator's budget on them.+ await db.insert(users).values({ id: 'visitor-1' });+ await db.insert(topics).values([+ { createdAt: new Date('2026-07-31T00:00:00Z'), id: 'creator-owned', userId },+ {+ createdAt: new Date('2026-07-31T00:00:00Z'),+ id: 'visitor-topic',+ senderId: 'visitor-1',+ userId,+ },+ ]);+ await db.insert(messages).values([+ {+ content: 'own',+ id: 'm-owned',+ role: 'user',+ topicId: 'creator-owned',+ updatedAt: new Date('2026-07-31T10:00:00Z'),+ userId,+ },+ {+ content: 'visit',+ id: 'm-visitor',+ role: 'user',+ topicId: 'visitor-topic',+ updatedAt: new Date('2026-07-31T10:00:00Z'),+ userId,+ },+ ]);++ const result = await model.listCandidates({+ idleBefore: new Date('2026-07-31T11:00:00Z'),+ limit: 20,+ topicCreatedAfter: new Date('2026-07-30T12:00:00Z'),+ });++ expect(result.map(({ id }) => id)).toEqual(['creator-owned']);+ });++ it('refuses to write a summary onto a share-visitor topic', async () => {+ // The write fence guards direct callers that skipped listCandidates.+ await db.insert(users).values({ id: 'visitor-2' });+ await db.insert(topics).values({+ id: 'visitor-write',+ senderId: 'visitor-2',+ userId,+ });+ await db.insert(messages).values({+ content: 'answer',+ id: 'm-visitor-write',+ role: 'assistant',+ topicId: 'visitor-write',+ updatedAt: new Date('2026-07-31T10:00:00Z'),+ userId,+ });++ const updated = await model.updateSummaryIfCurrent({+ description: 'Should not land',+ lastMessageId: 'm-visitor-write',+ lastMessageUpdatedAt: new Date('2026-07-31T10:00:00Z'),+ summary: 'Should not land',+ topicId: 'visitor-write',+ });+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'visitor-write'));++ expect(updated).toBe(false);+ expect(topic.description).toBeNull();+ expect(topic.historySummary).toBeNull();+ });+it('excludes system-generated topics from candidates', async () => {await db.insert(topics).values([{ createdAt: new Date('2026-07-31T00:00:00Z'), id: 'regular', userId },diff --git a/packages/database/src/models/__tests__/topics/topic.delete.test.ts b/packages/database/src/models/__tests__/topics/topic.delete.test.tsindex 3fdf501155d..c9e2e81e0f3 100644--- a/packages/database/src/models/__tests__/topics/topic.delete.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.delete.test.ts@@ -329,6 +329,82 @@ describe('TopicModel - Delete', () => {});});+ describe('agent-share visitor topics', () => {+ // Visitor topics carry the creator's userId plus a non-null senderId, and+ // are hidden from every creator-facing listing — so the creator's id-less+ // sweeps must not destroy them.+ beforeEach(async () => {+ await serverDB.insert(agents).values({ id: 'share-agent', title: 'Shared', userId });+ await serverDB.insert(topics).values([+ { agentId: 'share-agent', id: 'creator-topic', userId },+ { agentId: 'share-agent', id: 'visitor-topic', senderId: 'visitor-a', userId },+ ]);+ await serverDB.insert(messages).values([+ { id: 'creator-msg', role: 'user', topicId: 'creator-topic', userId },+ { id: 'visitor-msg', role: 'user', topicId: 'visitor-topic', userId },+ ]);+ });++ const remainingTopicIds = async () =>+ (await serverDB.select().from(topics).where(eq(topics.userId, userId))).map((t) => t.id);++ it('deleteAll should keep visitor topics and their messages', async () => {+ await topicModel.deleteAll();++ expect(await remainingTopicIds()).toEqual(['visitor-topic']);+ expect(+ await serverDB.select().from(messages).where(eq(messages.userId, userId)),+ ).toHaveLength(1);+ });++ it('batchDeleteByAgentId should keep visitor topics', async () => {+ await topicModel.batchDeleteByAgentId('share-agent');++ expect(await remainingTopicIds()).toEqual(['visitor-topic']);+ });++ it('batchDeleteBySessionId with no session should keep visitor topics', async () => {+ await topicModel.batchDeleteBySessionId();++ expect(await remainingTopicIds()).toEqual(['visitor-topic']);+ });++ it('batchDeleteByGroupId with no group should keep visitor topics', async () => {+ await topicModel.batchDeleteByGroupId();++ expect(await remainingTopicIds()).toEqual(['visitor-topic']);+ });++ it('delete should keep a visitor topic even when its id is named', async () => {+ // A creator can obtain a raw visitor topic id out of band (data export),+ // so `topic.removeTopic` must not cascade-delete the conversation.+ await topicModel.delete('visitor-topic');++ expect((await remainingTopicIds()).sort()).toEqual(['creator-topic', 'visitor-topic']);+ expect(+ await serverDB.select().from(messages).where(eq(messages.userId, userId)),+ ).toHaveLength(2);+ });++ it('delete should still remove the creator own topic', async () => {+ await topicModel.delete('creator-topic');++ expect(await remainingTopicIds()).toEqual(['visitor-topic']);+ });++ it('batchDelete should drop only the non-visitor ids of a mixed batch', async () => {+ await topicModel.batchDelete(['creator-topic', 'visitor-topic']);++ expect(await remainingTopicIds()).toEqual(['visitor-topic']);+ });++ it('deleting the agent still cascades visitor topics away', async () => {+ await serverDB.delete(agents).where(eq(agents.id, 'share-agent'));++ expect(await remainingTopicIds()).toEqual([]);+ });+ });+describe('workspace mode', () => {const workspaceId = 'topic-delete-workspace';const workspaceTopicModel = new TopicModel(serverDB, userId, workspaceId);diff --git a/packages/database/src/models/__tests__/topics/topic.memoryExtractor.test.ts b/packages/database/src/models/__tests__/topics/topic.memoryExtractor.test.tsindex bfd6ba6b100..c57eeb9cd08 100644--- a/packages/database/src/models/__tests__/topics/topic.memoryExtractor.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.memoryExtractor.test.ts@@ -74,4 +74,68 @@ describe('TopicModel - countTopicsForMemoryExtractor', () => {expect(total).toBe(2);});++ it('excludes agent-share visitor topics from the count', async () => {+ await serverDB.insert(topics).values([+ // normal creator topic — kept+ {+ id: 't1',+ createdAt: new Date('2023-01-01'),+ metadata: {},+ userId,+ },+ // agent-share visitor topic: userId is still the creator, but senderId+ // marks it as a visitor conversation that must not feed memory extraction+ {+ id: 't2-visitor',+ createdAt: new Date('2023-01-02'),+ metadata: {},+ senderId: 'visitor-user-x',+ userId,+ },+ ]);++ const total = await topicModel.countTopicsForMemoryExtractor({+ ignoreExtracted: true,+ });++ expect(total).toBe(1);+ });+});++describe('TopicModel - listTopicsForMemoryExtractor', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values({ id: userId });+ });++ afterEach(async () => {+ await serverDB.delete(users);+ });++ it('excludes agent-share visitor topics from the list', async () => {+ await serverDB.insert(topics).values([+ // normal creator topic — kept+ {+ id: 't1',+ createdAt: new Date('2023-01-01'),+ metadata: {},+ userId,+ },+ // agent-share visitor topic: userId is still the creator, but senderId+ // marks it as a visitor conversation that must not feed memory extraction+ {+ id: 't2-visitor',+ createdAt: new Date('2023-01-02'),+ metadata: {},+ senderId: 'visitor-user-x',+ userId,+ },+ ]);++ const result = await topicModel.listTopicsForMemoryExtractor({ ignoreExtracted: true });++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('t1');+ });});diff --git a/packages/database/src/models/__tests__/topics/topic.stats.test.ts b/packages/database/src/models/__tests__/topics/topic.stats.test.tsindex a8bb2b70833..a4597691320 100644--- a/packages/database/src/models/__tests__/topics/topic.stats.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.stats.test.ts@@ -206,4 +206,64 @@ describe('TopicModel - Stats', () => {expect(result).toHaveLength(1);});});+ describe('countShareVisitors', () => {+ beforeEach(async () => {+ await serverDB.insert(agents).values([+ { id: 'share-agent-1', title: 'Shared', userId },+ { id: 'share-agent-2', title: 'Other shared', userId },+ { id: 'share-agent-foreign', title: 'Someone else', userId: userId2 },+ ]);+ });++ it('counts visitor conversations and distinct visitors for one shared agent', async () => {+ await serverDB.insert(topics).values([+ // two conversations from the same visitor + one from another visitor+ { agentId: 'share-agent-1', id: 'sv-1', senderId: 'visitor-a', userId },+ { agentId: 'share-agent-1', id: 'sv-2', senderId: 'visitor-a', userId },+ { agentId: 'share-agent-1', id: 'sv-3', senderId: 'visitor-b', userId },+ // a different shared agent must not leak in+ { agentId: 'share-agent-2', id: 'sv-4', senderId: 'visitor-c', userId },+ ]);++ await expect(topicModel.countShareVisitors({ agentId: 'share-agent-1' })).resolves.toEqual({+ topicCount: 3,+ visitorCount: 2,+ });+ });++ it("excludes the creator's own conversations with the same agent", async () => {+ await serverDB.insert(topics).values([+ { agentId: 'share-agent-1', id: 'sv-own-1', userId },+ { agentId: 'share-agent-1', id: 'sv-own-2', userId },+ { agentId: 'share-agent-1', id: 'sv-visitor', senderId: 'visitor-a', userId },+ ]);++ await expect(topicModel.countShareVisitors({ agentId: 'share-agent-1' })).resolves.toEqual({+ topicCount: 1,+ visitorCount: 1,+ });+ });++ it('never counts rows owned by another user', async () => {+ await serverDB.insert(topics).values([+ {+ agentId: 'share-agent-foreign',+ id: 'sv-foreign',+ senderId: 'visitor-a',+ userId: userId2,+ },+ ]);++ await expect(+ topicModel.countShareVisitors({ agentId: 'share-agent-foreign' }),+ ).resolves.toEqual({ topicCount: 0, visitorCount: 0 });+ });++ it('returns zeroes when the agent has no visitor conversations', async () => {+ await expect(topicModel.countShareVisitors({ agentId: 'share-agent-1' })).resolves.toEqual({+ topicCount: 0,+ visitorCount: 0,+ });+ });+ });});diff --git a/packages/database/src/models/__tests__/user.test.ts b/packages/database/src/models/__tests__/user.test.tsindex 50ac1dfbe82..bde374bb4e8 100644--- a/packages/database/src/models/__tests__/user.test.ts+++ b/packages/database/src/models/__tests__/user.test.ts@@ -645,6 +645,44 @@ describe('UserModel', () => {expect(user).toBeUndefined();});++ it('purges share-visitor topics and messages when the visitor is deleted', async () => {+ // Visitor conversations live under the CREATOR's userId with+ // topics.senderId = visitor. There is no FK from topics.senderId to+ // users, so the users cascade cannot reach them; deleteUser must+ // clean them up explicitly.+ const creatorId = userId;+ const visitorId = otherUserId;+ const visitorTopicId = 'topic-share-visitor';+ const creatorTopicId = 'topic-creator-own';++ await serverDB.insert(topics).values([+ { id: visitorTopicId, senderId: visitorId, title: 'visitor chat', userId: creatorId },+ { id: creatorTopicId, title: 'creator own chat', userId: creatorId },+ ]);+ await serverDB.insert(messages).values([+ {+ content: 'hello from visitor',+ id: 'msg-visitor-1',+ role: 'user',+ topicId: visitorTopicId,+ userId: creatorId,+ },+ ]);++ await UserModel.deleteUser(serverDB, visitorId);++ const remainingTopics = await serverDB.query.topics.findMany();+ expect(remainingTopics.map((t) => t.id).sort()).toEqual([creatorTopicId]);++ const remainingMessages = await serverDB.query.messages.findMany();+ expect(remainingMessages).toHaveLength(0);++ const creator = await serverDB.query.users.findFirst({+ where: eq(users.id, creatorId),+ });+ expect(creator).toBeDefined();+ });});describe('findById', () => {diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex 34459fff889..ee05b5ef7c1 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -34,6 +34,7 @@ import {agentLabelAssignments,agents,agentsFiles,+ agentShares,agentsKnowledgeBases,agentsToSessions,briefs,@@ -85,6 +86,7 @@ import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../import { resolveGroupMembershipType } from '../utils/groupMembership';import { normalizeInboxAgentMeta } from '../utils/inboxAgent';import { sanitizeAgentApiConfig } from '../utils/sanitizeAgentApiConfig';+import { notShareVisitorTopic } from '../utils/shareVisitor';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from './agentCopyJob';import {@@ -205,6 +207,25 @@ export const AGENT_OWNED_BY_GROUP = 'AGENT_OWNED_BY_GROUP';*/export const AGENT_OWNERSHIP_STALE = 'AGENT_OWNERSHIP_STALE';+/**+ * Ownership transfer refused: the agent still carries an `agent_shares` row.+ *+ * The share row is bound to the ORIGINAL owner — it carries their grants and+ * (in Cloud) their spend cap linked to their budget, and every visitor+ * conversation reached through the link is stored under (agentId, senderId)+ * within THAT owner's scope. Handing the agent to someone else would either+ * silently republish the previous owner's grants under a new identity, or+ * strand the visitor conversations under a user that no longer owns the+ * agent. Neither is a valid product state, so ownership transfer of a shared+ * agent is refused until the owner disables sharing AND deletes the share+ * row (`AgentShareModel.deleteByAgentId`).+ *+ * Same-owner personal ↔ workspace moves are unaffected: the share row is+ * paused via `isRunStillAuthorized`'s `agents.workspaceId IS NULL` join and+ * resumes on the round-trip. Only a change of `agents.userId` is blocked.+ */+export const AGENT_SHARED_TRANSFER_BLOCKED = 'AGENT_SHARED_TRANSFER_BLOCKED';+/*** Refusal to move an agent that belongs to a chat group rather than to the* user. Carries the groups so the caller can say WHICH ones, the way the@@ -248,6 +269,14 @@ export class AgentModel {* Rank the user's agents by topic count (agent usage ranking). Counts topics* directly via `topics.agentId`, so it is agent-native — no sessionId. Mirrors* the recents filter: real agents plus the inbox, excluding other virtual agents.+ *+ * Share-visitor topics are excluded from the count: they carry the creator's+ * `userId` (so the plain join would count them) but reflect visitor usage,+ * not the creator's own — same rule as `TopicModel.rank` and every other+ * creator-facing aggregate (see `notShareVisitorTopic`). Applied in the join+ * condition rather than `where` so agents whose ONLY topics are visitor ones+ * still drop out via the `count > 0` guard instead of being filtered away+ * before grouping.*/rank = async (limit: number = 10): Promise<AgentRankItem[]> => {const rows = await this.db@@ -261,7 +290,7 @@ export class AgentModel {title: agents.title,}).from(agents)- .leftJoin(topics, eq(topics.agentId, agents.id))+ .leftJoin(topics, and(eq(topics.agentId, agents.id), notShareVisitorTopic())).where(and(this.ownership(), or(eq(agents.slug, INBOX_SESSION_ID), ne(agents.virtual, true)))).groupBy(agents.id).having(({ count }) => gt(count, 0))@@ -2109,6 +2138,31 @@ export class AgentModel {const ownedGroups = await this.findOwnedGroupMemberships(trx, agentIds);if (ownedGroups.length > 0) throw new AgentOwnedByGroupError(ownedGroups);+ // 1d. Refuse to change the owner of an agent that still carries an+ // `agent_shares` row. The share is bound to the previous owner: it+ // holds their tool grants and spend cap, and every visitor conversation+ // opened through the link is stored under (agentId, senderId) within+ // THAT owner's scope. Handing the agent over would either silently+ // republish the previous owner's grants under a new identity, or leave+ // the visitor threads dangling under a user that no longer owns them.+ // Disabling sharing keeps the row as `private`, so this is a hard stop+ // until the row is removed (`AgentShareModel.deleteByAgentId`, which has+ // no product entry point yet — a deliberate follow-up). A same-owner+ // personal ↔ workspace move keeps the row (it is paused via the+ // workspaceId join in `isRunStillAuthorized`). Fail the whole batch,+ // consistent with the guards above.+ const sharedAgentIds = foundAgents+ .filter((agent) => agent.userId !== targetUserId)+ .map((agent) => agent.id);+ if (sharedAgentIds.length > 0) {+ const sharedRows = await trx+ .select({ agentId: agentShares.agentId })+ .from(agentShares)+ .where(inArray(agentShares.agentId, sharedAgentIds))+ .limit(1);+ if (sharedRows.length > 0) throw new Error(AGENT_SHARED_TRANSFER_BLOCKED);+ }+// 2. Resolve slug conflicts in the target scope with a single query:// fetch every existing slug that could collide (exact match or// `<slug>-<n>` suffix), then pick free suffixes in memory. Agents@@ -2585,6 +2639,20 @@ export class AgentModel {const ownedGroups = await this.findOwnedGroupMemberships(trx, [agentId]);if (ownedGroups.length > 0) throw new AgentOwnedByGroupError(ownedGroups);+ // Mirror of transferAgents step 1d: refuse the handover if the agent+ // still carries an `agent_shares` row. The share is bound to the previous+ // owner's grants / spend cap, and every visitor conversation reached+ // through the link is stored under (agentId, senderId) within THAT+ // owner's scope. The previous owner must turn sharing off and delete the+ // share row before their agent can change hands. Checked BEFORE any+ // mutation below so the refusal leaves the agent untouched.+ const [existingShare] = await trx+ .select({ id: agentShares.id })+ .from(agentShares)+ .where(eq(agentShares.agentId, agentId))+ .limit(1);+ if (existingShare) throw new Error(AGENT_SHARED_TRANSFER_BLOCKED);+// A PRIVATE agent stops resolving for everyone but the recipient. Groups// that reference it and are NOT the recipient's would render a silent hole// in their roster; leave those groups explicitly instead (the manifestdiff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.tsindex 781e1a9624b..2d4f724f676 100644--- a/packages/database/src/models/agentOperation.ts+++ b/packages/database/src/models/agentOperation.ts@@ -15,6 +15,7 @@ import type {} from '../schemas/agentOperations';import { agentOperations } from '../schemas/agentOperations';import type { LobeChatDatabase } from '../type';+import { notShareVisitorTopicRef } from '../utils/shareVisitor';import { buildWorkspaceWhere } from '../utils/workspace';/**@@ -396,6 +397,14 @@ export class AgentOperationModel {};}+ /**+ * Raw ownership-scoped lookup. Agent-share visitor runs execute under the+ * CREATOR's identity, so this DOES return their operations — required by the+ * agent runtime (execution, intervention, completion, verify, abandon), which+ * has to resolve the operation it is currently driving no matter who started+ * it. Creator-facing read entry points must use+ * {@link AgentOperationModel.findOwnOperationById} instead.+ */async findById(operationId: string) {const [row] = await this.db.select()@@ -414,11 +423,39 @@ export class AgentOperationModel {.where(and(inArray(agentOperations.id, operationIds), this.ownership()));}+ /**+ * Creator-facing twin of {@link AgentOperationModel.findById}: excludes+ * operations recorded inside an agent-share visitor topic, so a creator+ * handed a raw visitor operation id gets nothing back instead of reading a+ * visitor conversation's trajectory (e.g. via a pre-signed trace URL).+ *+ * Mirrors `TopicModel.findById` / `TopicModel.findOwnTopicById`.+ */+ async findOwnOperationById(operationId: string) {+ const [row] = await this.db+ .select()+ .from(agentOperations)+ .where(+ and(+ eq(agentOperations.id, operationId),+ this.ownership(),+ notShareVisitorTopicRef(agentOperations.topicId),+ ),+ )+ .limit(1);+ return row ?? null;+ }+/*** Operations recorded for one topic, newest first — the lookup that turns a* topic id (what a user actually has on hand) into the operation ids their* traces are keyed by. `traceS3Key` rides along so callers can tell "no* snapshot was recorded" apart from "snapshot exists but the fetch failed".+ *+ * Creator-facing only (the trace panel). Agent-share visitor runs execute+ * under the CREATOR's identity, so their operation rows pass `ownership()`;+ * without the visitor guard a creator could read a visitor conversation's+ * full trajectory snapshot from a raw topic id.*/async listByTopic(topicId: string, limit = 20) {return this.db@@ -438,7 +475,13 @@ export class AgentOperationModel {trigger: agentOperations.trigger,}).from(agentOperations)- .where(and(eq(agentOperations.topicId, topicId), this.ownership()))+ .where(+ and(+ eq(agentOperations.topicId, topicId),+ this.ownership(),+ notShareVisitorTopicRef(agentOperations.topicId),+ ),+ ).orderBy(sql`${agentOperations.createdAt} desc`).limit(limit);}diff --git a/packages/database/src/models/agentShare.ts b/packages/database/src/models/agentShare.tsnew file mode 100644index 00000000000..b311cfa375d--- /dev/null+++ b/packages/database/src/models/agentShare.ts@@ -0,0 +1,524 @@+import {+ AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,+ AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,+ AGENT_SHARE_DEFAULT_MONTHLY_SPEND_LIMIT,+ AGENT_SHARE_SLUG_PATTERN,+ RESERVED_AGENT_SHARE_SLUGS,+} from '@lobechat/const';+import type { ShareVisibility } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { and, eq, exists, isNull, ne, sql } from 'drizzle-orm';++import type {+ AgentShareConfig,+ AgentShareConfigPatch,+ AgentShareItem,+ NormalizedAgentShareConfig,+} from '../schemas';+import { agents, agentShares } from '../schemas';+import type { LobeChatDatabase } from '../type';+import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '../utils/inboxAgent';+import { isUuid } from '../utils/uuid';++const DEFAULT_AGENT_SHARE_CONFIG = {+ allowCreatorViewSessions: false,+ allowReadMemory: false,+ maxTopicsPerVisitor: AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,+ maxTurnsPerTopic: AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,+ monthlySpendLimit: AGENT_SHARE_DEFAULT_MONTHLY_SPEND_LIMIT,+ showErrorDetails: false,+ showModelInfo: false,+ toolGrants: [],+} satisfies AgentShareConfig;++/** Fill fields missing from rows created before a field was introduced, or never explicitly set. */+const normalizeAgentShareConfig = (+ config: AgentShareConfig | null,+): NormalizedAgentShareConfig => ({+ allowCreatorViewSessions:+ config?.allowCreatorViewSessions ?? DEFAULT_AGENT_SHARE_CONFIG.allowCreatorViewSessions,+ allowReadMemory: config?.allowReadMemory ?? DEFAULT_AGENT_SHARE_CONFIG.allowReadMemory,+ maxTopicsPerVisitor:+ config?.maxTopicsPerVisitor ?? DEFAULT_AGENT_SHARE_CONFIG.maxTopicsPerVisitor,+ maxTurnsPerTopic: config?.maxTurnsPerTopic ?? DEFAULT_AGENT_SHARE_CONFIG.maxTurnsPerTopic,+ monthlySpendLimit: config?.monthlySpendLimit ?? DEFAULT_AGENT_SHARE_CONFIG.monthlySpendLimit,+ showErrorDetails: config?.showErrorDetails ?? DEFAULT_AGENT_SHARE_CONFIG.showErrorDetails,+ showModelInfo: config?.showModelInfo ?? DEFAULT_AGENT_SHARE_CONFIG.showModelInfo,+ slug: config?.slug,+ toolGrants: config?.toolGrants ?? DEFAULT_AGENT_SHARE_CONFIG.toolGrants,+});++/** An `agentShares` row with `shareConfig` filled via `normalizeAgentShareConfig`. */+type NormalizedAgentShareItem = Omit<AgentShareItem, 'shareConfig'> & {+ shareConfig: NormalizedAgentShareConfig;+};++export type AgentShareData = NonNullable<+ Awaited<ReturnType<(typeof AgentShareModel)['findByShareId']>>+>;++/** Minimal locked-row snapshot returned by {@link AgentShareModel.lockOwnedAgentRow}. */+interface LockedAgentSnapshot {+ id: string;+}++export class AgentShareModel {+ private db: LobeChatDatabase;+ private userId: string;++ constructor(db: LobeChatDatabase, userId: string) {+ this.db = db;+ this.userId = userId;+ }++ /** Agent sharing is personal-only; workspace agents fail this predicate. */+ private ownership = () =>+ exists(+ this.db+ .select({ id: agents.id })+ .from(agents)+ .where(+ and(+ eq(agents.id, agentShares.agentId),+ eq(agents.userId, this.userId),+ isNull(agents.workspaceId),+ ),+ ),+ );++ /**+ * Take `FOR UPDATE` on the owned Agent row from an ALREADY-OPEN+ * transaction, without opening one of its own. Every instance mutation+ * below (`create`, `updateConfig`, `updateVisibility`, `deleteByAgentId`,+ * `updateSlug`) serializes on this same physical row, so two concurrent+ * writes on the same agent's share can never interleave.+ *+ * Returns `null` (never locks) when the agent does not exist, is not+ * personally owned by `ownerId`, or is workspace-scoped — callers must fail+ * closed on `null`.+ */+ static lockOwnedAgentRow = async (+ tx: LobeChatDatabase,+ agentId: string,+ ownerId: string,+ ): Promise<LockedAgentSnapshot | null> => {+ const [agent] = await tx+ .select({ id: agents.id })+ .from(agents)+ .where(and(eq(agents.id, agentId), eq(agents.userId, ownerId), isNull(agents.workspaceId)))+ .for('update');++ return agent ?? null;+ };++ private withOwnedPersonalAgentLock = async <T>(+ agentId: string,+ mutation: (tx: LobeChatDatabase, agent: LockedAgentSnapshot) => Promise<T>,+ ): Promise<T | null> =>+ this.db.transaction(async (transaction) => {+ const tx = transaction as LobeChatDatabase;+ const agent = await AgentShareModel.lockOwnedAgentRow(tx, agentId, this.userId);++ if (!agent) return null;+ return mutation(tx, agent);+ });++ /** Create a private share by default, or return the existing share for the agent. */+ create = async (agentId: string, visibility: ShareVisibility = 'private') => {+ const share = await this.withOwnedPersonalAgentLock(agentId, async (tx) => {+ // One row per agent, forever: `onConflictDoNothing` on `agentId` makes a+ // re-enable fall back to the SELECT below, returning the existing row+ // untouched. That is what keeps a share's id and custom slug — i.e. the+ // link already handed out — stable across a disable → re-enable cycle,+ // since disabling only flips `visibility` to `private`.+ const [created] = await tx+ .insert(agentShares)+ .values({ agentId, shareConfig: DEFAULT_AGENT_SHARE_CONFIG, visibility })+ .onConflictDoNothing({ target: agentShares.agentId })+ .returning();++ if (created) return created;++ const [existing] = await tx+ .select()+ .from(agentShares)+ .where(eq(agentShares.agentId, agentId))+ .limit(1);+ return existing ?? null;+ });++ if (!share) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Agent sharing is only available to personal agent owners',+ });+ }++ return { ...share, shareConfig: normalizeAgentShareConfig(share.shareConfig) };+ };++ /** Get a share by agent ID for its owner. */+ getByAgentId = async (agentId: string): Promise<NormalizedAgentShareItem | null> => {+ const [share] = await this.db+ .select()+ .from(agentShares)+ .where(and(eq(agentShares.agentId, agentId), this.ownership()))+ .limit(1);++ if (!share) return null;++ return { ...share, shareConfig: normalizeAgentShareConfig(share.shareConfig) };+ };++ /**+ * Atomically merge client-owned fields into the existing config, preserving+ * sibling keys that were not part of this patch. A flat top-level jsonb+ * merge is enough here — unlike the old branch's `filePermissionConfig`,+ * every field on the current `AgentShareConfig` is a top-level scalar/array,+ * so there is no nested object that needs its own merge branch.+ *+ * `slug` is stripped even if smuggled past the type — it has its own+ * validated write path (`updateSlug`).+ */+ updateConfig = async (+ agentId: string,+ config: AgentShareConfigPatch,+ ): Promise<NormalizedAgentShareItem | null> =>+ this.withOwnedPersonalAgentLock(agentId, async (tx) => {+ const { slug: _slug, ...patch } = config as AgentShareConfigPatch & { slug?: unknown };+ const setEntries = Object.entries(patch).filter(([, v]) => v !== undefined);++ let configExpr = sql`COALESCE(${agentShares.shareConfig}, '{}'::jsonb)`;+ if (setEntries.length > 0) {+ configExpr = sql`${configExpr} || ${JSON.stringify(Object.fromEntries(setEntries))}::jsonb`;+ }++ const [updated] = await tx+ .update(agentShares)+ .set({+ shareConfig: sql<AgentShareConfig>`${configExpr}`,+ updatedAt: new Date(),+ })+ .where(eq(agentShares.agentId, agentId))+ .returning();++ if (!updated) return null;++ return { ...updated, shareConfig: normalizeAgentShareConfig(updated.shareConfig) };+ });++ /**+ * Update share visibility for a personally owned agent. This is also the+ * "turn sharing off" path (`private`): the row, its id and its custom slug+ * are all preserved, so flipping back to `link` republishes the exact same+ * URL the owner already handed out.+ */+ updateVisibility = async (+ agentId: string,+ visibility: ShareVisibility,+ ): Promise<NormalizedAgentShareItem | null> =>+ this.withOwnedPersonalAgentLock(agentId, async (tx) => {+ const [updated] = await tx+ .update(agentShares)+ .set({ updatedAt: new Date(), visibility })+ .where(eq(agentShares.agentId, agentId))+ .returning();++ if (!updated) return null;++ return { ...updated, shareConfig: normalizeAgentShareConfig(updated.shareConfig) };+ });++ /**+ * Validate and persist a custom URL slug for this share.+ *+ * Uniqueness is checked application-side (`share_config->>'slug'` has no DB+ * index/constraint — see the field's JSDoc in the schema). The `agents.id+ * FOR UPDATE` lock only serializes writes on the SAME agent; two agents+ * racing for the same slug hold different row locks and would both pass a+ * plain conflict-check SELECT (neither sees the other's uncommitted write),+ * so the check is additionally serialized on a transaction-scoped advisory+ * lock keyed by the slug itself.+ *+ * `slug: null` clears the custom slug (removes the jsonb key) — the share+ * then resolves only by its raw id again.+ */+ updateSlug = async (+ agentId: string,+ slug: string | null,+ ): Promise<NormalizedAgentShareItem | null> => {+ if (slug === null) {+ return this.withOwnedPersonalAgentLock(agentId, async (tx) => {+ const [updated] = await tx+ .update(agentShares)+ .set({+ shareConfig: sql<AgentShareConfig>`COALESCE(${agentShares.shareConfig}, '{}'::jsonb) - 'slug'`,+ updatedAt: new Date(),+ })+ .where(eq(agentShares.agentId, agentId))+ .returning();++ if (!updated) return null;++ return { ...updated, shareConfig: normalizeAgentShareConfig(updated.shareConfig) };+ });+ }++ // A UUID-shaped slug would be unreachable: `findBySlugOrId` resolves+ // UUID-shaped input as a share id before ever trying the slug lookup.+ if (!AGENT_SHARE_SLUG_PATTERN.test(slug) || isUuid(slug)) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'INVALID_SHARE_SLUG' });+ }++ if (RESERVED_AGENT_SHARE_SLUGS.includes(slug)) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'RESERVED_SHARE_SLUG' });+ }++ return this.withOwnedPersonalAgentLock(agentId, async (tx) => {+ // Cross-agent uniqueness barrier: released automatically at commit/rollback.+ await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`agent_share_slug:${slug}`}))`);++ const [conflict] = await tx+ .select({ id: agentShares.id })+ .from(agentShares)+ .where(+ and(+ sql`${agentShares.shareConfig} ->> 'slug' = ${slug}`,+ ne(agentShares.agentId, agentId),+ ),+ )+ .limit(1);++ if (conflict) {+ throw new TRPCError({ code: 'CONFLICT', message: 'SHARE_SLUG_TAKEN' });+ }++ const [updated] = await tx+ .update(agentShares)+ .set({+ shareConfig: sql<AgentShareConfig>`COALESCE(${agentShares.shareConfig}, '{}'::jsonb) || ${JSON.stringify({ slug })}::jsonb`,+ updatedAt: new Date(),+ })+ .where(eq(agentShares.agentId, agentId))+ .returning();++ if (!updated) return null;++ return { ...updated, shareConfig: normalizeAgentShareConfig(updated.shareConfig) };+ });+ };++ /**+ * Hard-delete the agent's share record, dropping its id and custom slug for+ * good.+ *+ * NOT the "turn sharing off" path — that is `updateVisibility(agentId,+ * 'private')`, which keeps the link resumable. No product flow calls this+ * today; it stays as the model-level primitive for a genuine, irreversible+ * teardown (and lets tests build the "share row replaced" scenario that+ * `isRunStillAuthorized` guards against).+ */+ deleteByAgentId = async (agentId: string): Promise<AgentShareItem | null> =>+ this.withOwnedPersonalAgentLock(agentId, async (tx) => {+ const [deleted] = await tx+ .delete(agentShares)+ .where(eq(agentShares.agentId, agentId))+ .returning();++ return deleted ?? null;+ });++ /**+ * Read the CURRENT `maxTopicsPerVisitor` / `maxTurnsPerTopic` caps for an+ * agent's share, bypassing any snapshot a caller might already be holding —+ * intended to be called from inside the SAME locked transaction a+ * visitor-abuse guard uses to recount and insert, so a cap reduction the+ * owner just made is always the number actually enforced, not a stale value+ * read earlier in the request. `shareId` is returned alongside for the same+ * staleness reason: it identifies which live share instance a newly created+ * visitor topic should be scoped to.+ *+ * Falls back to `normalizeAgentShareConfig`'s defaults exactly like every+ * other reader of `agentShares.shareConfig`.+ */+ static readCurrentVisitorCaps = async (+ db: LobeChatDatabase,+ agentId: string,+ ): Promise<+ Required<+ Pick<AgentShareConfig, 'maxTopicsPerVisitor' | 'maxTurnsPerTopic' | 'monthlySpendLimit'>+ > & {+ shareId: string | null;+ }+ > => {+ const [row] = await db+ .select({ id: agentShares.id, shareConfig: agentShares.shareConfig })+ .from(agentShares)+ .where(eq(agentShares.agentId, agentId));++ const normalized = normalizeAgentShareConfig(row?.shareConfig ?? null);+ return {+ maxTopicsPerVisitor: normalized.maxTopicsPerVisitor!,+ maxTurnsPerTopic: normalized.maxTurnsPerTopic!,+ monthlySpendLimit: normalized.monthlySpendLimit!,+ shareId: row?.id ?? null,+ };+ };++ /**+ * Whether an in-flight visitor run is STILL authorized to continue: the+ * agent's share row must exist, still be the SAME instance the run was+ * authorized against (`shareId`), and still be `link`.+ *+ * Turning sharing off flips `visibility` to `private` and KEEPS the row, so+ * a disable → re-enable cycle deliberately resumes the same link and must+ * not invalidate anything: the visibility check alone covers the pause. The+ * id comparison still guards the cases where the row genuinely goes away and+ * comes back as a different instance — a hard delete (`deleteByAgentId`) or+ * the agent being deleted and recreated under the same id.+ *+ * The agent must ALSO still be personal (`agents.workspaceId IS NULL`) —+ * the same condition `findByShareId` resolves through. Sharing is+ * personal-only, so a creator moving the agent into a workspace mid-run+ * leaves the share row intact while every entry point stops resolving it;+ * without this join the in-flight run would keep spending under the creator+ * after the share was effectively paused. Same-owner personal ↔ workspace+ * moves preserve the row deliberately, so returning the agent to personal+ * scope resumes the same link. An OWNERSHIP TRANSFER is different:+ * `AgentModel.transferAgents` / `transferAgentOwnership` REFUSE to change+ * `agents.userId` while this row exists (`AGENT_SHARED_TRANSFER_BLOCKED`)+ * — the share carries the previous owner's grants and spend cap, and+ * visitor conversations reached through the link live under (agentId,+ * senderId) within that owner's scope. Disabling sharing keeps the row+ * (`private`), so the block lifts only once the row itself is removed;+ * a product entry point for that is a follow-up, not part of this model.+ *+ * Deliberately cheap (one indexed lookup + a primary-key join): it runs once+ * per runtime step. Returns `false` — never throws — for an ordinary+ * "no longer authorized" outcome; a THROWN error must be treated as+ * unauthorized too by the caller (fail closed, never fail open).+ */+ static isRunStillAuthorized = async (+ db: LobeChatDatabase,+ params: { agentId: string; shareId: string },+ ): Promise<boolean> => {+ const [share] = await db+ .select({ id: agentShares.id, visibility: agentShares.visibility })+ .from(agentShares)+ .innerJoin(agents, eq(agentShares.agentId, agents.id))+ .where(and(eq(agentShares.agentId, params.agentId), isNull(agents.workspaceId)))+ .limit(1);++ return !!share && share.id === params.shareId && share.visibility === 'link';+ };++ /**+ * Resolve the public metadata required by an agent share page. Workspace+ * agents never resolve here — `agentShares` rows only exist for personal+ * agents (see `create`'s ownership check), but the `isNull` guard is kept+ * as defense in depth against a row surviving some future write path that+ * does not go through this model.+ */+ static findByShareId = async (db: LobeChatDatabase, shareId: string) => {+ if (!isUuid(shareId)) return null;++ const [share] = await db+ .select({+ agentAvatar: agents.avatar,+ agentBackgroundColor: agents.backgroundColor,+ agentDescription: agents.description,+ agentId: agentShares.agentId,+ agentName: agents.name,+ agentSlug: agents.slug,+ agentTitle: agents.title,+ ownerId: agents.userId,+ shareConfig: agentShares.shareConfig,+ shareId: agentShares.id,+ userViewCount: agentShares.userViewCount,+ visibility: agentShares.visibility,+ })+ .from(agentShares)+ .innerJoin(agents, eq(agentShares.agentId, agents.id))+ .where(and(eq(agentShares.id, shareId), isNull(agents.workspaceId)))+ .limit(1);++ if (!share) return null;++ return {+ ...share,+ agentAvatar: normalizeInboxAgentAvatar(share.agentAvatar, { slug: share.agentSlug }),+ agentTitle: normalizeInboxAgentTitle(share.agentTitle, { slug: share.agentSlug }),+ shareConfig: normalizeAgentShareConfig(share.shareConfig),+ };+ };++ /**+ * Resolve a share by its custom `slug` (application-level lookup into+ * `share_config->>'slug'`, no DB index) or, failing that pattern, by its+ * `id` when the input looks like a UUID. Returns a share of ANY visibility+ * — callers must run their own access check (see+ * `findByShareIdWithAccessCheck`) before exposing the result.+ */+ static findBySlugOrId = async (db: LobeChatDatabase, slugOrId: string) => {+ if (isUuid(slugOrId)) {+ return AgentShareModel.findByShareId(db, slugOrId);+ }++ // Stored slugs are always lowercase (enforced in `updateSlug`), so+ // lowercase the input to keep share URLs case-insensitive.+ const slug = slugOrId.toLowerCase();++ const [share] = await db+ .select({ id: agentShares.id })+ .from(agentShares)+ .where(sql`${agentShares.shareConfig} ->> 'slug' = ${slug}`)+ .limit(1);++ if (!share) return null;++ return AgentShareModel.findByShareId(db, share.id);+ };++ /** Increment the successful page-view counter after access has been granted. */+ static incrementUserViewCount = async (db: LobeChatDatabase, shareId: string) => {+ await db+ .update(agentShares)+ .set({ userViewCount: sql`${agentShares.userViewCount} + 1` })+ .where(eq(agentShares.id, shareId));+ };++ /**+ * Enforce private-share owner access on an already-resolved share row.+ * Kept as the single access-check implementation so callers that already+ * hold a resolved row (e.g. via `findBySlugOrId`) don't need a second+ * lookup just to reuse the gate.+ */+ static assertShareAccess = (+ share: Pick<AgentShareData, 'ownerId' | 'visibility'>,+ viewerId: string,+ ): void => {+ const isOwner = viewerId === share.ownerId;+ // NOT_FOUND, not FORBIDDEN: a paused (private) share must be+ // indistinguishable from a share that never existed, otherwise a+ // stranger can probe custom slugs / ids to learn which private shares+ // exist. Only the owner ever sees the private row.+ if (!isOwner && share.visibility === 'private') {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Share not found' });+ }+ };++ /** Resolve a share and enforce private-share owner access. */+ static findByShareIdWithAccessCheck = async (+ db: LobeChatDatabase,+ shareId: string,+ viewerId: string,+ ): Promise<AgentShareData> => {+ const share = await AgentShareModel.findByShareId(db, shareId);++ if (!share) throw new TRPCError({ code: 'NOT_FOUND', message: 'Share not found' });++ AgentShareModel.assertShareAccess(share, viewerId);++ return share;+ };+}diff --git a/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts b/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.tsindex 7e157d42e40..09dafb9ee5f 100644--- a/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts+++ b/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts@@ -586,5 +586,75 @@ describe('AgentSignalNightlyReviewModel', () => {},]);});++ it('excludes messages inside an agent-share visitor topic from the nightly digest', async () => {+ // Agent-share visitor topics keep the creator's userId on both the topic+ // and its messages, but a non-null topics.senderId marks the topic as+ // visitor traffic that must not feed the creator's own nightly review.+ await serverDB.insert(users).values({ id: enabledUserId });+ await serverDB.insert(agents).values({+ chatConfig: { selfIteration: { enabled: true } },+ id: 'nightly-share-agent',+ title: 'Share agent',+ userId: enabledUserId,+ });+ await serverDB.insert(topics).values([+ {+ agentId: 'nightly-share-agent',+ id: 'nightly-visitor-topic',+ senderId: 'visitor-user-x',+ title: 'Visitor topic',+ userId: enabledUserId,+ },+ {+ agentId: 'nightly-share-agent',+ id: 'nightly-creator-topic',+ title: 'Creator topic',+ userId: enabledUserId,+ },+ ]);+ await serverDB.insert(messages).values([+ {+ agentId: 'nightly-share-agent',+ content: 'visitor message',+ createdAt: new Date('2026-05-03T12:00:00.000Z'),+ id: 'nightly-visitor-message',+ role: 'user',+ topicId: 'nightly-visitor-topic',+ userId: enabledUserId,+ },+ {+ agentId: 'nightly-share-agent',+ content: 'creator message',+ createdAt: new Date('2026-05-03T13:00:00.000Z'),+ id: 'nightly-creator-message',+ role: 'user',+ topicId: 'nightly-creator-topic',+ userId: enabledUserId,+ },+ ]);++ const model = new AgentSignalNightlyReviewModel(serverDB);++ const result = await model.listActiveAgentTargets(enabledUserId, {+ windowEnd: new Date('2026-05-03T23:59:59.999Z'),+ windowStart: new Date('2026-05-03T00:00:00.000Z'),+ });++ // Only the creator's own message counts; the visitor's message is excluded+ expect(result).toEqual([+ {+ agentId: 'nightly-share-agent',+ failedToolCallCount: 0,+ firstActivityAt: new Date('2026-05-03T13:00:00.000Z'),+ lastActivityAt: new Date('2026-05-03T13:00:00.000Z'),+ messageCount: 1,+ name: null,+ timezone: 'UTC',+ title: 'Share agent',+ topicCount: 1,+ },+ ]);+ });});});diff --git a/packages/database/src/models/agentSignal/__tests__/reviewContext.test.ts b/packages/database/src/models/agentSignal/__tests__/reviewContext.test.tsindex ea9e8ceea21..926909a9ea9 100644--- a/packages/database/src/models/agentSignal/__tests__/reviewContext.test.ts+++ b/packages/database/src/models/agentSignal/__tests__/reviewContext.test.ts@@ -368,6 +368,68 @@ describe('AgentSignalReviewContextModel', () => {}),]);});++ it('excludes agent-share visitor topics from the creator-facing activity window', async () => {+ const visitorTopicId = 'agent-signal-review-context-visitor-topic';++ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(agents).values([+ {+ chatConfig: { selfIteration: { enabled: true } },+ id: agentId,+ title: 'Review Context Agent',+ userId,+ },+ ]);+ await serverDB.insert(topics).values([+ {+ agentId,+ id: topicId,+ title: 'Creator topic',+ userId,+ },+ // Agent-share visitor topic: stored under the creator's userId (billing+ // attribution) but carries a visitor senderId, so it must be excluded.+ {+ agentId,+ id: visitorTopicId,+ senderId: 'visitor-user-x',+ title: 'Visitor topic',+ userId,+ },+ ]);+ await serverDB.insert(messages).values([+ {+ agentId,+ content: 'creator message',+ createdAt: new Date('2026-05-03T12:00:00.000Z'),+ id: 'agent-signal-review-context-creator-message',+ role: 'assistant',+ topicId,+ userId,+ },+ {+ agentId,+ content: 'visitor message',+ createdAt: new Date('2026-05-03T12:00:00.000Z'),+ id: 'agent-signal-review-context-visitor-message',+ role: 'assistant',+ topicId: visitorTopicId,+ userId,+ },+ ]);++ const model = new AgentSignalReviewContextModel(serverDB, userId);++ const result = await model.listTopicActivity({+ agentId,+ limit: 10,+ windowEnd: new Date('2026-05-03T23:59:59.999Z'),+ windowStart: new Date('2026-05-03T00:00:00.000Z'),+ });++ expect(result).toEqual([expect.objectContaining({ topicId })]);+ });});describe('listRelevantMemories', () => {@@ -592,5 +654,48 @@ describe('AgentSignalReviewContextModel', () => {expect(result).toEqual([]);});++ it('excludes agent-share visitor topics even when scoped by topicId', async () => {+ const visitorTopicId = 'agent-signal-review-context-reflection-visitor-topic';++ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(agents).values([+ {+ chatConfig: { selfIteration: { enabled: true } },+ id: agentId,+ title: 'Review Context Agent',+ userId,+ },+ ]);+ // Agent-share visitor topic: stored under the creator's userId (billing+ // attribution) but carries a visitor senderId, so it must be excluded.+ await serverDB.insert(topics).values({+ agentId,+ id: visitorTopicId,+ senderId: 'visitor-user-x',+ title: 'Visitor topic',+ userId,+ });+ await serverDB.insert(messages).values({+ agentId,+ content: 'visitor message',+ createdAt: new Date('2026-05-03T12:00:00.000Z'),+ id: 'agent-signal-review-context-reflection-visitor-message',+ role: 'assistant',+ topicId: visitorTopicId,+ userId,+ });++ const model = new AgentSignalReviewContextModel(serverDB, userId);++ const result = await model.listSelfReflectionTopicActivity({+ agentId,+ topicId: visitorTopicId,+ windowEnd: new Date('2026-05-03T23:59:59.999Z'),+ windowStart: new Date('2026-05-03T00:00:00.000Z'),+ });++ expect(result).toEqual([]);+ });});});diff --git a/packages/database/src/models/agentSignal/nightlyReview.ts b/packages/database/src/models/agentSignal/nightlyReview.tsindex 7f431aac78e..0cb1d077858 100644--- a/packages/database/src/models/agentSignal/nightlyReview.ts+++ b/packages/database/src/models/agentSignal/nightlyReview.ts@@ -17,6 +17,7 @@ import { alias } from 'drizzle-orm/pg-core';import { agents, messagePlugins, messages, topics, users, userSettings } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { normalizeInboxAgentTitle } from '../../utils/inboxAgent';+import { notShareVisitorMessage } from '../../utils/shareVisitor';/** Restores the cursor timestamp inside PostgreSQL so workflow JSON never truncates its precision. */const cursorUsers = alias(users, 'nightly_review_cursor_users');@@ -253,6 +254,9 @@ export class AgentSignalNightlyReviewModel {and(eq(messages.userId, userId),isNull(messages.workspaceId),+ // Share-visitor traffic bills to the creator but is not the+ // creator's own activity — keep it out of the nightly digest.+ notShareVisitorMessage(),agentFilter,gte(messages.createdAt, options.windowStart),lte(messages.createdAt, options.windowEnd),diff --git a/packages/database/src/models/agentSignal/reviewContext.ts b/packages/database/src/models/agentSignal/reviewContext.tsindex bfca1049298..83bfe1c28d9 100644--- a/packages/database/src/models/agentSignal/reviewContext.ts+++ b/packages/database/src/models/agentSignal/reviewContext.ts@@ -12,6 +12,7 @@ import {userMemories,} from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { notShareVisitorMessage } from '../../utils/shareVisitor';import { buildWorkspaceWhere } from '../../utils/workspace';const parseAggregateTimestamp = (value: Date | string) =>@@ -294,6 +295,10 @@ export class AgentSignalReviewContextModel {eq(effectiveAgentId, options.agentId),gte(messages.createdAt, options.windowStart),lte(messages.createdAt, options.windowEnd),+ // Share-visitor traffic bills to the creator but is not the+ // creator's own activity — it must never feed self-learning/expertise+ // context. See `notShareVisitorMessage` for the shared predicate rule.+ notShareVisitorMessage(),),).groupBy(topics.id, topics.title, topics.historySummary, topics.description, topics.content)@@ -356,6 +361,8 @@ export class AgentSignalReviewContextModel {gte(messages.createdAt, options.windowStart),lte(messages.createdAt, options.windowEnd),eq(messages.topicId, options.topicId),+ // See `listTopicActivity` above / `notShareVisitorMessage` for the rule.+ notShareVisitorMessage(),),).groupBy(topics.id, topics.title, topics.historySummary, topics.description, topics.content)diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex afbc4ef141a..fcd230d4bb1 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -1,9 +1,12 @@import { INBOX_SESSION_ID } from '@lobechat/const';import { parse } from '@lobechat/conversation-flow';import type {+ AssistantContentBlock,ChatAudioItem,ChatFileItem,ChatImageItem,+ ChatMessageError,+ ChatMessageExtra,ChatToolPayload,ChatTranslate,ChatTTS,@@ -21,11 +24,17 @@ import type {TaskDetail,ThreadStatus,UIChatMessage,+ UISignalCallbacksBlock,UpdateMessageParams,UpdateMessageRAGParams,WorkSummaryItem,} from '@lobechat/types';-import { MessageGroupType, ThreadType } from '@lobechat/types';+import {+ AgentRuntimeErrorType,+ ChatErrorType,+ MessageGroupType,+ ThreadType,+} from '@lobechat/types';import type { TimingSink } from '@lobechat/utils';import {getDurationMs,@@ -78,6 +87,7 @@ import {messageTranslates,messageTTS,threads,+ topics,users,} from '../schemas';import type { LobeChatDatabase, Transaction } from '../type';@@ -86,6 +96,7 @@ import { notCopiedTranscript } from '../utils/copiedTranscript';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { idGenerator } from '../utils/idGenerator';import { inJsonStringArray } from '../utils/inJsonStringArray';+import { notShareVisitorMessage, notShareVisitorTopicRef } from '../utils/shareVisitor';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';import { recomputeTopicUsage } from './topicUsage';import { WorkModel } from './work';@@ -163,6 +174,16 @@ const getMessageWorkRootId = (metadata: unknown): string | undefined => {* Options for querying messages with relations*/export interface QueryMessagesOptions {+ /**+ * Opt IN to agent-share visitor rows for this call, overriding the default+ * `ownership()` visitor exclusion. Combined via OR with the instance's+ * `includeShareVisitor` flag, so an instance already opted in stays opted+ * in and a default-scoped instance can still be widened per-call (this is+ * how {@link MessageModel.queryForVisitor} works before the share-runtime+ * routers switch to constructing the model with `{ includeShareVisitor:+ * true }`).+ */+ allowShareVisitor?: boolean;/*** Current page number (0-indexed)*/@@ -450,27 +471,520 @@ const computeTopicMessageStats = (counts: number[]): TopicMessageStats => {};};+// **************** Agent Share (visitor-scoped projections) *************** //++/**+ * Opt-in escape hatch for the write paths that legitimately act on agent-share+ * visitor rows. Visitor messages are stored under the creator's `userId`, so+ * ownership alone cannot tell a creator action apart from a runtime action;+ * mutation entry points therefore fail closed and only the agent runtime (which+ * drives visitor turns under the creator's identity) passes this.+ */+export interface ShareVisitorWriteOptions {+ includeShareVisitor?: boolean;+}++/**+ * Constructor options for {@link MessageModel} — mirrors the twin flag on+ * {@link import('./topic').TopicModelOptions}. When `includeShareVisitor` is+ * true, the instance's `ownership()` predicate no longer excludes agent-share+ * visitor messages; the escape hatch that per-call {@link ShareVisitorWriteOptions}+ * used to be the only way to grant. Share-only surfaces should set this at+ * construction and stop threading per-call opt-ins through their code.+ */+export interface MessageModelOptions {+ includeShareVisitor?: boolean;+}++/**+ * Per-share switches that relax {@link toVisitorMessage}'s default redaction.+ * Both default to `false` (strip everything), so a caller that forgets to pass+ * options gets the fail-closed projection.+ */+export interface VisitorRedactionOptions {+ /**+ * `AgentShareConfig.showErrorDetails`. When false, a run failure is+ * projected down to a generic classified `type` (see+ * {@link sanitizeVisitorError}) instead of the raw+ * message/provider/budget/upstream-body payload `formatErrorForState`+ * builds.+ */+ showErrorDetails?: boolean;+ /**+ * `AgentShareConfig.showModelInfo`. When false, the creator's model /+ * provider choice and the token/cost snapshot are stripped everywhere they+ * appear, at any nesting depth.+ */+ showModelInfo?: boolean;+}++/**+ * Fields on {@link UIChatMessage} that are safe to forward to an agent-share+ * visitor verbatim: the message's OWN presentational content (text,+ * attachments, tool activity, RAG citations) and structural links WITHIN the+ * same shared topic (thread/group/parent ids). None of these describe the+ * creator's account, billing, or model/provider choice.+ *+ * This is an ALLOWLIST, not a denylist, and that direction is deliberate:+ * `UIChatMessage` is a ~40-field DTO shared with the normal (non-share) chat+ * read path, so new fields land on it regularly as chat features ship. A+ * denylist fails OPEN on every such addition — a new field reaches visitors by+ * default until someone remembers to also strip it here. An allowlist fails+ * CLOSED: a new field is absent from the visitor DTO until a human+ * deliberately adds it below.+ *+ * Deliberately included despite being an id: `agentId` (the visitor already+ * knows which agent they are talking to — that's the whole premise of the+ * share link), `sessionId`/`traceId`/`observationId` (opaque ids scoped to+ * THIS execution of the visitor's OWN turn, reused by client actions such as+ * translate/regenerate that the share UI shares with normal chat).+ */+const VISITOR_MESSAGE_ALLOWED_KEYS = [+ 'id',+ 'role',+ 'content',+ 'createdAt',+ 'updatedAt',+ 'editorData',+ 'fileList',+ 'files',+ 'imageList',+ 'videoList',+ 'audioList',+ 'chunksList',+ 'plugin',+ 'pluginIntervention',+ 'tool_call_id',+ 'tools',+ 'reasoning',+ 'search',+ 'ragQuery',+ 'ragQueryId',+ 'ragRawQuery',+ 'parentId',+ 'threadId',+ 'topicId',+ 'groupId',+ 'targetId',+ 'agentId',+ 'sessionId',+ 'quotaId',+ 'branch',+ 'tasks',+ 'performance',+ 'observationId',+ 'traceId',+] as const satisfies readonly (keyof UIChatMessage)[];++type VisitorAllowedKey = (typeof VISITOR_MESSAGE_ALLOWED_KEYS)[number];++const pickAllowedKeys = (message: UIChatMessage): Pick<UIChatMessage, VisitorAllowedKey> => {+ const picked = {} as Pick<UIChatMessage, VisitorAllowedKey>;+ for (const key of VISITOR_MESSAGE_ALLOWED_KEYS) {+ if (key in message) (picked as Record<string, unknown>)[key] = message[key];+ }+ return picked;+};++/** Keep translate/TTS (visitor-facing rendering), drop the model snapshot. */+const sanitizeVisitorExtra = (extra: ChatMessageExtra | undefined): ChatMessageExtra | undefined =>+ extra ? { translate: extra.translate, tts: extra.tts } : extra;++/**+ * Shape shared by `pinnedMessages` entries and `compareGroup.children` entries+ * (`queryMessageGroupNodes` builds them with this exact narrow projection,+ * then casts the whole node `as unknown as UIChatMessage`, so+ * `UIChatMessage['pinnedMessages']` / `UIChatMessage['children']`'s declared+ * types do not describe them at runtime). Neither carries `sender`/`usage`,+ * only the model snapshot needs stripping.+ *+ * NOTE: on a `compressedGroup` node, `children` is NOT this narrow shape — it+ * lives inside `compressedMessages[].children` (an `AssistantContentBlock[]`+ * produced by `FlatListBuilder`) and carries `usage`, `error`, `tools`,+ * `metadata`, `performance`, and possibly nested `council` messages with+ * `sender`. See `toVisitorMessage` for the recursion that sanitizes those.+ */+interface VisitorGroupSnapshotProjection {+ content: string | null;+ createdAt: Date | number;+ id: string;+ model: string | null;+ provider: string | null;+ role: string;+}++const sanitizeVisitorGroupSnapshots = (+ items: VisitorGroupSnapshotProjection[],+): VisitorGroupSnapshotProjection[] =>+ items.map((item) => ({ ...item, model: null, provider: null }));++/** Cost/token figures are the same class of creator spend data as `usage`. */+const sanitizeVisitorTaskDetail = (taskDetail: TaskDetail | undefined): TaskDetail | undefined => {+ if (!taskDetail) return taskDetail;+ const {+ totalCost: _totalCost,+ totalTokens: _totalTokens,+ totalToolCalls: _totalToolCalls,+ ...rest+ } = taskDetail;+ return rest;+};++/**+ * Key names that identify the CREATOR's model/provider choice or spend/token+ * data wherever they occur inside an unbounded per-tool blob+ * (`pluginState`/`pluginError`, live Gateway event payloads). A builtin tool's+ * server runtime writes whatever shape it wants into `state`/error payloads —+ * e.g. `lobe-agent`'s `analyzeMedia` writes `{ model, provider, usage }`+ * straight into it — so unlike a short, fully enumerable list of top-level+ * `UIChatMessage` fields there is no finite set of "every tool's state shape"+ * to allowlist by hand: a new tool, or a new field on an existing tool's+ * `state`, must be safe BY DEFAULT. Recursing this fixed key set is the+ * fail-closed trade-off.+ */+const CREATOR_PRIVATE_BLOB_KEYS = new Set([+ 'model',+ 'provider',+ 'usage',+ 'cost',+ 'totalCost',+ 'totalTokens',+ 'promptTokens',+ 'completionTokens',+ 'inputTokens',+ 'outputTokens',+ // `AgentRuntimeService.publishSubAgentProgress`'s live `step_complete`+ // (`subagent_progress` phase) reads these off `state.usage.llm.tokens` under+ // the `total*` spelling rather than `inputTokens`/`outputTokens` — same+ // class of creator token-spend data, different key name.+ 'totalInputTokens',+ 'totalOutputTokens',+]);++/**+ * Recursively strip {@link CREATOR_PRIVATE_BLOB_KEYS} from an unbounded+ * JSON-like value at ANY nesting depth. Only descends into plain+ * objects/arrays (`isPlainRecord` already excludes `Date`/`Error`/class+ * instances) — anything else is returned as-is, since it cannot itself carry a+ * nested creator-identity field.+ *+ * Exported so `GatewayStreamNotifier`'s live Gateway-push chokepoint can apply+ * the SAME key set to `stream_start` (`model`/`provider`), `tool_end`+ * (`result`/`payload`, which can carry a tool's `state`), and `step_complete`+ * (`subagent_progress`'s sibling `model`/`totalCost`/token fields) — the live+ * WS payload equivalents of the persisted blobs this function was written for.+ */+export const redactCreatorPrivateBlob = <T>(value: T): T => {+ if (Array.isArray(value)) return value.map((item) => redactCreatorPrivateBlob(item)) as T;+ if (!isPlainRecord(value)) return value;++ const result: Record<string, unknown> = {};+ for (const [key, nested] of Object.entries(value)) {+ if (CREATOR_PRIVATE_BLOB_KEYS.has(key)) continue;+ result[key] = redactCreatorPrivateBlob(nested);+ }+ return result as T;+};++/**+ * `ChatMessageError.type` codes that are safe to forward to a visitor+ * VERBATIM, `message` included — because they are purpose-built,+ * business-level codes whose throw sites already write a clean, generic+ * `message` (never string-concatenated from a raw upstream payload) and whose+ * NAME itself says nothing about the creator's provider/model/account: "this+ * shared agent hit its per-topic turn cap", not "OpenAI rejected key sk-…".+ * Every other code — including the LEGITIMATE quota/rate-limit codes, whose+ * `message`/`body` are still built by `formatErrorForState` from the raw+ * upstream error — is projected to {@link VISITOR_PUBLIC_ERROR_TYPE}. Kept as+ * a narrow allowlist (fail closed) rather than an exclude list of "known+ * provider-identifying codes": some codes leak the provider through the TYPE+ * NAME alone (`OllamaServiceUnavailable`, `InvalidBedrockCredentials`, …), so+ * a denylist would need to enumerate those and would miss the next one a+ * model-runtime change adds.+ */+const VISITOR_SAFE_ERROR_TYPES = new Set<string>([+ ChatErrorType.ShareTurnLimitExceeded,+ ChatErrorType.ShareTopicLimitExceeded,+ ChatErrorType.ShareSpendLimitExceeded,+ ChatErrorType.ShareHeterogeneousAgentUnsupported,+ ChatErrorType.AgentShareProviderNotSupported,+]);++/**+ * Public fallback `type` for any `ChatMessageError` whose code is not in+ * {@link VISITOR_SAFE_ERROR_TYPES}. Reuses the existing generic+ * `AgentRuntimeError` bucket (already localized) rather than minting a new+ * code: the visitor only needs "the run failed, retry or contact the creator",+ * never which of the ~60 specific runtime codes fired.+ */+const VISITOR_PUBLIC_ERROR_TYPE = AgentRuntimeErrorType.AgentRuntimeError;++/**+ * Sanitize a `ChatMessageError` for a visitor — PROJECTION, not the recursive+ * {@link redactCreatorPrivateBlob} used for `pluginState`/`pluginError`.+ * `body` has no stable set of key names to strip: it is free-form per error+ * source and `formatErrorForState` deliberately copies `provider`, `budget`,+ * and the raw upstream diagnostic onto it for exactly the failures a visitor+ * can trigger on demand (bad key, exhausted quota, upstream 500) — so+ * recursing a fixed key set would miss the next shape a new error source+ * introduces. Dropping `body` wholesale and keeping only a classified `type`+ * (+ `message` for the allowlisted codes) fails closed instead: the client+ * re-derives its localized copy, alert styling, and error-card variant from+ * `type` alone.+ *+ * Bypassed entirely when the share sets `showErrorDetails` — the creator has+ * then explicitly opted into showing visitors the raw failure.+ */+export const sanitizeVisitorError = (+ error: ChatMessageError | null | undefined,+ options: VisitorRedactionOptions = {},+): ChatMessageError | null | undefined => {+ if (!error) return error;+ if (options.showErrorDetails) return error;++ const type = error.type as unknown;+ if (typeof type === 'string' && VISITOR_SAFE_ERROR_TYPES.has(type)) {+ return { message: error.message, type: error.type };+ }++ return { type: VISITOR_PUBLIC_ERROR_TYPE };+};++/**+ * `signalCallbacks[].callbacks[]` is a denormalized per-callback snapshot built+ * by `FlatListBuilder`, carrying a bare `model`/`provider` pair per callback+ * turn — same leak class as `pinnedMessages`/`children`'s group-node+ * snapshots.+ */+const sanitizeVisitorSignalCallbacks = (+ signalCallbacks: UISignalCallbacksBlock[] | undefined,+): UISignalCallbacksBlock[] | undefined =>+ signalCallbacks?.map((block) => ({+ ...block,+ callbacks: block.callbacks.map((callback) => ({+ ...callback,+ model: undefined,+ provider: undefined,+ })),+ }));++/**+ * `taskCompletions[]` blocks are denormalized post-task-summary snapshots built+ * by `FlatListBuilder`, each carrying its own `usage` — the same class of+ * creator spend data as the top-level `usage` field.+ */+const sanitizeVisitorTaskCompletions = (+ taskCompletions: AssistantContentBlock[] | undefined,+): AssistantContentBlock[] | undefined =>+ taskCompletions?.map(({ usage: _usage, ...rest }) => rest);++/**+ * `metadata.usage` / `metadata.cost` are the pre-migration duplicates of the+ * (denied) top-level `usage` field — kept on the type only so legacy rows+ * written before the dedicated `usage` column still type-check.+ * `queryWithWhere` itself falls back to `metadata.usage` for those rows, so+ * leaving `metadata` unsanitized would let the exact spend snapshot back in+ * through a legacy row's `metadata` blob. Every other `metadata` field is this+ * message's own presentational state and passes through untouched.+ */+const sanitizeVisitorMetadata = (+ metadata: MessageMetadata | null | undefined,+): MessageMetadata | null | undefined => {+ if (!metadata) return metadata;+ const { usage: _usage, cost: _cost, ...rest } = metadata;+ return rest;+};++/**+ * Strip creator-only fields from a message row before it reaches an+ * agent-share visitor. Creator account identity never crosses the share+ * boundary; the creator's model/provider/spend choices cross it only when the+ * share sets `showModelInfo`, and raw error payloads only when it sets+ * `showErrorDetails` ({@link VisitorRedactionOptions}).+ *+ * Built from {@link VISITOR_MESSAGE_ALLOWED_KEYS} plus explicit handling for+ * the fields that need transformation rather than a plain allow/deny.+ */+export const toVisitorMessage = (+ message: UIChatMessage,+ options: VisitorRedactionOptions = {},+): UIChatMessage => {+ const stripModelInfo = !options.showModelInfo;++ return {+ ...pickAllowedKeys(message),+ // `sender` is the CREATOR's account identity — never gated by any config+ // flag, since no share setting is about exposing whose account runs the+ // agent.+ sender: null,+ extra: stripModelInfo ? sanitizeVisitorExtra(message.extra) : message.extra,+ metadata: stripModelInfo ? sanitizeVisitorMetadata(message.metadata) : message.metadata,+ // Unbounded per-tool blobs: a tool runtime controls everything inside+ // them, so a fixed field allowlist can't classify their contents — the+ // creator-identity key set is recursed out instead.+ pluginError: stripModelInfo+ ? redactCreatorPrivateBlob(message.pluginError)+ : message.pluginError,+ pluginState: stripModelInfo+ ? redactCreatorPrivateBlob(message.pluginState)+ : message.pluginState,+ // Projected, not redacted — see `sanitizeVisitorError`.+ error: sanitizeVisitorError(message.error, options),+ ...(stripModelInfo+ ? {+ model: undefined,+ provider: undefined,+ signalCallbacks: sanitizeVisitorSignalCallbacks(message.signalCallbacks),+ taskCompletions: sanitizeVisitorTaskCompletions(message.taskCompletions),+ taskDetail: sanitizeVisitorTaskDetail(message.taskDetail),+ usage: undefined,+ }+ : {+ model: message.model,+ provider: message.provider,+ signalCallbacks: message.signalCallbacks,+ taskCompletions: message.taskCompletions,+ taskDetail: message.taskDetail,+ usage: message.usage,+ }),+ // Work summaries join live task/version state under the CREATOR's account+ // — never served to a visitor surface regardless of share config.+ works: undefined,+ // A compacted topic nests raw rows under the group node, and group chat+ // nests member messages, so anything less than a full recursive sanitize+ // would leave the creator's identity on everything inside it.+ ...(message.compressedMessages && {+ compressedMessages: message.compressedMessages.map((nested) =>+ toVisitorMessage(nested, options),+ ),+ }),+ ...(message.members && {+ members: message.members.map((nested) => toVisitorMessage(nested, options)),+ }),+ // `pinnedMessages` is only ever the narrow group-node projection (see+ // `queryMessageGroupNodes` in the Compression branch). Emit it in both+ // modes — sanitized when the model snapshot is not shared, otherwise+ // untouched.+ ...(message.pinnedMessages && {+ pinnedMessages: stripModelInfo+ ? (sanitizeVisitorGroupSnapshots(+ message.pinnedMessages as unknown as VisitorGroupSnapshotProjection[],+ ) as unknown as UIChatMessage['pinnedMessages'])+ : message.pinnedMessages,+ }),+ // `children` is polymorphic: a `compareGroup` node carries the same bare+ // {id, role, model, provider, content, createdAt} snapshot as+ // `pinnedMessages`; an `assistantGroup` node (produced inside+ // `compressedMessages` by `FlatListBuilder`) carries full+ // `AssistantContentBlock[]` with `usage`, `tools`, `error`, `metadata`,+ // `performance`, and possibly nested `council` messages with `sender` —+ // so a compareGroup-only narrow sanitize would let all of those through+ // for an assistantGroup child. Route by the PARENT `role` and recurse+ // assistantGroup children through `toVisitorMessage` itself so the+ // allowlist / error projection / usage & metadata stripping / council+ // recursion all apply.+ ...(message.children && {+ children:+ message.role === 'compareGroup'+ ? stripModelInfo+ ? (sanitizeVisitorGroupSnapshots(+ message.children as unknown as VisitorGroupSnapshotProjection[],+ ) as unknown as UIChatMessage['children'])+ : message.children+ : ((message.children as unknown as UIChatMessage[]).map((child) =>+ toVisitorMessage(child, options),+ ) as unknown as UIChatMessage['children']),+ }),+ // `AssistantContentBlock.council` on a nested assistantGroup child is a+ // `Message[]` of the supervisor's broadcast members, each carrying its+ // own `sender` / model / usage. `pickAllowedKeys` drops `council`+ // outright (fail closed), so re-attach a recursively sanitized copy+ // whenever the source carried one.+ ...((message as unknown as { council?: unknown }).council !== undefined &&+ ({+ council: ((message as unknown as { council?: UIChatMessage[] }).council ?? []).map(+ (member) => toVisitorMessage(member, options),+ ),+ } as unknown as Partial<UIChatMessage>)),+ } as UIChatMessage;+};+export class MessageModel {private userId: string;private db: LobeChatDatabase;private ftsSearchCandidateSource?: FtsSearchCandidateSource;private workspaceId?: string;+ /**+ * When true, {@link ownership} (and by extension every creator-scoped+ * read/write below) stops ANDing {@link notShareVisitorMessage}. Reserved+ * for surfaces that are share-runtime by design (agent-share visitor+ * router, share-scoped abuse guards) and for the agent runtime paths that+ * persist or clean up a visitor turn under the CREATOR's identity.+ * Defaults to false so every ordinary creator-facing caller fails closed.+ */+ private includeShareVisitor: boolean;constructor(db: LobeChatDatabase,userId: string,workspaceId?: string,ftsSearchCandidateSource?: FtsSearchCandidateSource,+ options: MessageModelOptions = {},) {this.userId = userId;this.db = db;this.workspaceId = workspaceId;this.ftsSearchCandidateSource = ftsSearchCandidateSource;+ this.includeShareVisitor = options.includeShareVisitor ?? false;}- private ownership = () =>+ /**+ * Raw workspace/user scope, WITHOUT the visitor exclusion. Backing store+ * for {@link ownership} and the escape hatch for methods that resolve the+ * effective visitor gate per-call ({@link deleteMessage},+ * {@link deleteMessages}, {@link query} via `allowShareVisitor`, …).+ */+ private workspaceScope = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages);+ /**+ * Default visitor exclusion applied by {@link ownership} — see+ * `notShareVisitorMessage` in `../utils/shareVisitor`. Returns `undefined`+ * when the instance was constructed with `includeShareVisitor: true`.+ */+ private notShareVisitor = () => (this.includeShareVisitor ? undefined : notShareVisitorMessage());++ private ownership = () => and(this.workspaceScope(), this.notShareVisitor());++ /**+ * One indexed lookup of a topic's `senderId` in this user/workspace scope+ * (`buildWorkspaceWhere` on `topics`). Returned once and reused: every row+ * that belongs to a topic shares that topic's visitor/creator identity, so+ * once the topic itself has been classified the per-row NOT EXISTS predicate+ * from {@link notShareVisitorMessage} is redundant for the rest of the same+ * call. Callers pass the resolved verdict downstream (as+ * `allowShareVisitor: true` for a verified creator topic) to swap the+ * relevant `ownership()` sites over to plain `workspaceScope()`.+ *+ * Fails closed: returns `'visitor'` when the topic doesn't exist under this+ * scope OR carries a non-null `senderId`, so an unauthorized topicId gets+ * the same empty result as before.+ */+ private resolveTopicVisitorScope = async (topicId: string): Promise<'creator' | 'visitor'> => {+ const rows = await this.db+ .select({ senderId: topics.senderId })+ .from(topics)+ .where(+ and(+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),+ eq(topics.id, topicId),+ ),+ )+ .limit(1);+ if (rows.length === 0) return 'visitor';+ return rows[0].senderId === null ? 'creator' : 'visitor';+ };+private pluginsOwnership = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messagePlugins);@@ -538,6 +1052,15 @@ export class MessageModel {threadId,}: QueryMessageParams = {},options: {+ /**+ * Opt IN to agent-share visitor messages. Visitor conversations persist+ * under the CREATOR's `userId` (only `topics.senderId` marks them), so+ * `this.ownership()` alone lets a creator read a visitor's full transcript+ * by passing its `topicId` — bypassing `allowCreatorViewSessions=false`.+ * Defaults to false so every creator-facing caller fails closed; only the+ * share-scoped read path ({@link MessageModel.queryForVisitor}) sets it.+ */+ allowShareVisitor?: boolean;postProcessUrl?: (path: string | null,file: { fileType: string; id?: string | null },@@ -546,7 +1069,41 @@ export class MessageModel {} = {},) => {const queryStartedAt = Date.now();+ // Effective visitor gate: per-call `allowShareVisitor` OR the instance's+ // `includeShareVisitor`. Combined so `queryForVisitor(...)` still works+ // on a default-scoped instance (its explicit param overrides), AND a+ // share-runtime instance stops needing the param at every call site.+ const includeVisitor = options.allowShareVisitor || this.includeShareVisitor;const timing = options.timing;++ // Topic-scope shortcut: when the caller pins a `topicId` and hasn't opted+ // in to visitor rows, resolve the topic's `senderId` ONCE and either fail+ // closed (visitor topic) or drop the per-row NOT EXISTS predicate that+ // `queryWithWhere` / `queryMessageGroupNodes` would otherwise re-check for+ // every message in the topic. Every row inside a topic shares its parent+ // topic's visitor/creator identity, so a single indexed topic lookup is+ // strictly stronger than the correlated subquery repeated per row.+ let topicScopeVerified = false;+ if (topicId && !includeVisitor) {+ const scope = await this.resolveTopicVisitorScope(topicId);+ if (scope === 'visitor') {+ logTiming(timing, 'db.message.query:done', {+ messageCount: 0,+ stageMs: getDurationMs(queryStartedAt),+ });+ return [];+ }+ topicScopeVerified = true;+ }+ // `queryWithWhere` already ANDs `notShareVisitorMessage()` via+ // `ownership()`, so the previous per-branch `shareVisitorCondition` in+ // the `where` was pure duplication — dropped. When `topicScopeVerified`+ // is true the predicate is redundant altogether (the topic has been+ // classified once), and we pass that verdict downstream via+ // `allowShareVisitor: effectiveIncludeVisitor` so `queryWithWhere` swaps+ // its scope from `ownership()` to `workspaceScope()` and skips the+ // per-row NOT EXISTS.+ const effectiveIncludeVisitor = includeVisitor || topicScopeVerified;logTiming(timing, 'db.message.query:start', {current,hasAgentId: !!agentId,@@ -582,6 +1139,7 @@ export class MessageModel {// scope the complete thread to it instead of filtering those replies by the parent agent.const threadScopeCondition = topicId ? this.matchTopic(topicId) : agentCondition;const messageItems = await this.queryWithWhere({+ allowShareVisitor: effectiveIncludeVisitor,current,includeFileWorks,pageSize,@@ -589,7 +1147,7 @@ export class MessageModel {skipWorks,timing,topicId: topicId ?? undefined,- where: threadScopeCondition ? and(threadScopeCondition, threadCondition) : threadCondition,+ where: and(threadScopeCondition, threadCondition),});logTiming(timing, 'db.message.query:done', {messageCount: messageItems.length,@@ -609,6 +1167,7 @@ export class MessageModel {);const messageItems = await this.queryWithWhere({+ allowShareVisitor: effectiveIncludeVisitor,current,includeFileWorks,pageSize,@@ -640,6 +1199,7 @@ export class MessageModel {);const messageItems = await this.queryWithWhere({+ allowShareVisitor: effectiveIncludeVisitor,current,includeFileWorks,pageSize,@@ -656,6 +1216,58 @@ export class MessageModel {return messageItems;};+ // **************** Agent Share (visitor-scoped) *************** //++ /**+ * Visitor-facing twin of {@link query} for agent-share reads.+ *+ * Share messages persist under the CREATOR's account (see `shareChat.ts`),+ * so `query()`'s joined `sender` and the billing/model-snapshot fields+ * describe the creator, not the visitor reading them. `redaction` carries the+ * share's own `showModelInfo` / `showErrorDetails` switches; omitting it+ * strips everything (fail closed).+ */+ queryForVisitor = async (+ params: QueryMessageParams = {},+ options: {+ postProcessUrl?: (+ path: string | null,+ file: { fileType: string; id?: string | null },+ ) => Promise<string>;+ redaction?: VisitorRedactionOptions;+ timing?: ModelTimingContext;+ } = {},+ ): Promise<UIChatMessage[]> => {+ // The only caller allowed past `query()`'s visitor guard: the topic was+ // already resolved and authorized as this visitor's own share topic.+ const messageItems = await this.query(params, { ...options, allowShareVisitor: true });+ return messageItems.map((message) => toVisitorMessage(message, options.redaction));+ };++ /**+ * Exact per-topic turn count for one role, used by `maxTurnsPerTopic`.+ *+ * MUST NOT reuse {@link MessageModel.count}: its `analyticsConditions()` ANDs+ * in `notShareVisitorMessage()`, which excludes every message whose topic has+ * a non-null `senderId` — i.e. every agent-share visitor topic. That+ * predicate is correct for personal analytics (visitor usage is reported+ * separately), but it would make `count()` return 0 forever for a share+ * topic, silently disabling the turn cap.+ *+ * Safe without a visitor/ownership check here: the caller (shareChat router /+ * `reserveShareVisitorTurn`) already resolved and authorized the topic, and+ * `this.ownership()` matches because share messages carry the creator's+ * `userId` (the model is constructed with `share.ownerId`).+ */+ countByTopic = async ({ role, topicId }: { role: string; topicId: string }): Promise<number> => {+ const result = await this.db+ .select({ count: count(messages.id) })+ .from(messages)+ .where(and(this.ownership(), eq(messages.topicId, topicId), eq(messages.role, role)));++ return result[0].count;+ };+/*** Return a lightweight, ownership-scoped transcript for a topic.*@@ -673,7 +1285,10 @@ export class MessageModel {offset: number;topicId: string;}): Promise<TopicTranscriptResult> => {- const where = and(this.ownership(), eq(messages.topicId, topicId));+ // Creator-facing only (CLI / topic transcript router): agent-share visitor+ // messages live under the creator's `userId`, so ownership alone would hand+ // the creator a visitor's full transcript from a raw topic id.+ const where = and(this.ownership(), eq(messages.topicId, topicId), notShareVisitorMessage());const [items, totalResult] = await Promise.all([this.db@@ -760,9 +1375,14 @@ export class MessageModel {skipWorks,topicId,timing,+ allowShareVisitor,} = options;const totalStartedAt = Date.now();const offset = current * pageSize;+ // See {@link QueryMessagesOptions.allowShareVisitor}. Combined with the+ // instance's `includeShareVisitor` so either widens the scope.+ const scope =+ allowShareVisitor || this.includeShareVisitor ? this.workspaceScope() : this.ownership();// 1. get basic messages with joins, excluding messages that belong to MessageGroupsconst result = await runTimedStage(@@ -835,7 +1455,7 @@ export class MessageModel {.from(messages).where(and(- this.ownership(),+ scope,// Filter out messages that belong to MessageGroupsisNull(messages.messageGroupId),where,@@ -889,6 +1509,7 @@ export class MessageModel {const messageIds = result.map((message) => message.id as string);const messageGroupNodesPromise = this.queryMessageGroupNodesForPage({+ allowShareVisitor: allowShareVisitor || this.includeShareVisitor,current,postProcessUrl,result,@@ -1062,12 +1683,23 @@ export class MessageModel {};private queryMessageGroupNodesForPage = async ({+ allowShareVisitor,current,postProcessUrl,result,timing,topicId,}: {+ /**+ * Effective visitor gate resolved by the caller (per-call+ * `allowShareVisitor` OR the instance's `includeShareVisitor`). Threaded+ * through so the underlying `messageGroups` where-clause fails closed on+ * a creator's default read of a visitor topic — otherwise a bare+ * workspace/topicId filter would still surface the group's synthetic+ * `compressedGroup`/`compareGroup` nodes (with content summaries) even+ * though the row query returned nothing.+ */+ allowShareVisitor?: boolean;current: number;postProcessUrl?: (path: string | null,@@ -1085,7 +1717,10 @@ export class MessageModel {return runTimedStage(timing,'db.message.queryWithWhere.messageGroups',- () => this.queryMessageGroupNodes(topicId, undefined, postProcessUrl, timing),+ () =>+ this.queryMessageGroupNodes(topicId, undefined, postProcessUrl, timing, {+ allowShareVisitor,+ }),{ current, hasMessages: false, topicId },);}@@ -1094,7 +1729,10 @@ export class MessageModel {return runTimedStage(timing,'db.message.queryWithWhere.messageGroups',- () => this.queryMessageGroupNodes(topicId, undefined, postProcessUrl, timing),+ () =>+ this.queryMessageGroupNodes(topicId, undefined, postProcessUrl, timing, {+ allowShareVisitor,+ }),{ current, hasMessages: true, topicId },);}@@ -1114,6 +1752,7 @@ export class MessageModel {},postProcessUrl,timing,+ { allowShareVisitor },),{ current, hasMessages: true, topicId },);@@ -1397,6 +2036,15 @@ export class MessageModel {queryByIds = async (messageIds: string[],options: {+ /**+ * Opt IN to agent-share visitor rows. Reserved for internal callers+ * (`queryMessageGroupNodes`) that already resolved and authorized the+ * parent topic via {@link resolveTopicVisitorScope}; every row shares+ * that topic's visitor/creator identity, so the per-row NOT EXISTS+ * predicate baked into `this.ownership()` is redundant once the topic+ * itself has been classified. External callers must leave this false.+ */+ allowShareVisitor?: boolean;postProcessUrl?: (path: string | null,file: { fileType: string; id?: string | null },@@ -1406,6 +2054,10 @@ export class MessageModel {if (messageIds.length === 0) return [];const { postProcessUrl } = options;+ const scope =+ options.allowShareVisitor || this.includeShareVisitor+ ? this.workspaceScope()+ : this.ownership();// 1. Query messages with joinsconst result = await this.db@@ -1470,7 +2122,7 @@ export class MessageModel {ttsVoice: messageTTS.voice,}).from(messages)- .where(and(this.ownership(), inArray(messages.id, messageIds)))+ .where(and(scope, inArray(messages.id, messageIds))).leftJoin(messagePlugins, eq(messagePlugins.id, messages.id)).leftJoin(messageTranslates, eq(messageTranslates.id, messages.id)).leftJoin(messageTTS, eq(messageTTS.id, messages.id))@@ -1717,11 +2369,20 @@ export class MessageModel {file: { fileType: string; id?: string | null },) => Promise<string>,timing?: ModelTimingContext,+ options: { allowShareVisitor?: boolean } = {},): Promise<UIChatMessage[]> => {+ // Effective visitor gate — see `queryMessageGroupNodesForPage`. Absent+ // this predicate, a creator's default `query({ topicId })` on a visitor+ // topic returns no messages but still returns the group's synthetic+ // `compressedGroup` node (with its `content` summary) or `compareGroup`+ // node, leaking the visitor conversation shape.+ const includeVisitor = options.allowShareVisitor || this.includeShareVisitor;+// 1. Query MessageGroups for this topic, optionally filtered by time rangeconst whereConditions = [buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageGroups),eq(messageGroups.topicId, topicId),+ ...(includeVisitor ? [] : [notShareVisitorTopicRef(messageGroups.topicId)]),];// Add time range filter if provided (for pagination)@@ -1761,7 +2422,17 @@ export class MessageModel {messageGroupId: messages.messageGroupId,}).from(messages)- .where(and(this.ownership(), inArray(messages.messageGroupId, groupIds)))+ .where(+ and(+ // The parent topic has already been classified by the caller+ // (via `resolveTopicVisitorScope`) or the model was constructed+ // as a share-runtime instance — either way, the per-row NOT+ // EXISTS predicate baked into `ownership()` is redundant for+ // messages that belong to a group inside a verified topic.+ includeVisitor ? this.workspaceScope() : this.ownership(),+ inArray(messages.messageGroupId, groupIds),+ ),+ ).orderBy(asc(messages.createdAt)),{ groupCount: groupIds.length },);@@ -1774,7 +2445,7 @@ export class MessageModel {const fullMessages = await runTimedStage(timing,'db.message.messageGroups.queryByIds',- () => this.queryByIds(allMessageIds, { postProcessUrl }),+ () => this.queryByIds(allMessageIds, { allowShareVisitor: includeVisitor, postProcessUrl }),{ messageCount: allMessageIds.length },);@@ -1916,6 +2587,31 @@ export class MessageModel {});};+ /**+ * Ids among `ids` that resolve to an agent-share VISITOR message under this+ * owner — the inverse of the `notShareVisitorMessage()` predicate every+ * creator-facing read applies.+ *+ * Creator-facing write entry points use this to reject visitor targets+ * (see `assertCreatorMessageTargets` in the server router helpers). Ids that+ * match no row at all are NOT reported, so callers keep their existing no-op+ * behaviour for stale/foreign ids and only fail on rows that really belong to+ * a visitor's conversation.+ */+ findShareVisitorMessageIds = async (ids: string[]): Promise<string[]> => {+ if (ids.length === 0) return [];++ const rows = await this.db+ .select({ id: messages.id })+ .from(messages)+ // Explicitly scoped visitor-inclusive: this method's whole job is to+ // return visitor ids so the router-level `assertCreatorMessageTargets`+ // can reject them, so bypass the instance's visitor exclusion.+ .where(and(inArray(messages.id, ids), this.workspaceScope(), not(notShareVisitorMessage())));++ return rows.map((row) => row.id);+ };+findByClientId = async (clientId: string) => {return this.db.query.messages.findFirst({where: and(eq(messages.clientId, clientId), this.ownership()),@@ -2038,6 +2734,13 @@ export class MessageModel {return result[0];};+ /**+ * Full creator-facing message dump (`getAllMessages` / CLI export), so+ * agent-share visitor messages must be excluded like every other+ * creator-facing listing. The exclusion rides on+ * {@link MessageModel.analyticsConditions}, which already ANDs+ * `notShareVisitorMessage()` — see `../utils/shareVisitor`.+ */queryAll = async (params?: MessageAnalyticsFilters & { current?: number; pageSize?: number }) => {const { current = 0, pageSize = 100, ...filters } = params ?? {};const offset = current * pageSize;@@ -2061,11 +2764,17 @@ export class MessageModel {})[];};+ // Plain select builder instead of `db.query...findMany`: the relational+ // query API re-qualifies raw SQL fragments to the outer table alias, which+ // breaks the `topics`-referencing NOT EXISTS inside `notShareVisitorMessage`.queryBySessionId = async (sessionId?: string | null) => {- const result = await this.db.query.messages.findMany({- orderBy: [asc(messages.createdAt)],- where: and(this.ownership(), this.matchSession(sessionId)),- });+ const result = await this.db+ .select()+ .from(messages)+ // Visitor messages have no sessionId, so the null-session (inbox) branch+ // would otherwise sweep them in.+ .where(and(this.ownership(), this.matchSession(sessionId), notShareVisitorMessage()))+ .orderBy(asc(messages.createdAt));return result as DBMessageItem[];};@@ -2089,6 +2798,7 @@ export class MessageModel {.where(and(this.ownership(),+ notShareVisitorMessage(),candidateIds? inJsonStringArray(messages.id, candidateIds): sql`${messages.content} @@@ ${bm25Query}`,@@ -2103,9 +2813,16 @@ export class MessageModel {* Ownership-scoped analytics filter conditions, shared by count /* countGroupByTopic / topicMessageStats. The first entry is always the* `userId × workspace` ownership predicate; later entries are optional.+ * Agent-share visitor messages carry the creator's `userId`, so personal+ * analytics must exclude them (visitor usage is reported separately by the+ * share usage center) — see `notShareVisitorMessage` in `../utils/shareVisitor`.+ *+ * MUST NOT be applied to {@link countByTopic} — see that method's JSDoc for+ * why exact per-topic turn counting needs the visitor topic's own messages.*/private analyticsConditions = (params?: MessageAnalyticsFilters) => [this.ownership(),+ notShareVisitorMessage(),params?.agentId ? eq(messages.agentId, params.agentId) : undefined,params?.topicId ? eq(messages.topicId, params.topicId) : undefined,params?.role ? eq(messages.role, params.role) : undefined,@@ -2204,6 +2921,7 @@ export class MessageModel {.where(genWhere([this.ownership(),+ notShareVisitorMessage(),params?.range? genRangeWhere(params.range, messages.createdAt, (date) => date.toDate()): undefined,@@ -2226,7 +2944,14 @@ export class MessageModel {id: messages.model,}).from(messages)- .where(and(this.ownership(), isNotNull(messages.model), notCopiedTranscript()))+ .where(+ and(+ this.ownership(),+ notShareVisitorMessage(),+ isNotNull(messages.model),+ notCopiedTranscript(),+ ),+ ).having(({ count }) => gt(count, 0)).groupBy(messages.model).orderBy(desc(sql`count`), asc(messages.model))@@ -2246,6 +2971,7 @@ export class MessageModel {.where(genWhere([this.ownership(),+ notShareVisitorMessage(),genRangeWhere([startDate.format('YYYY-MM-DD'), endDate.add(1, 'day').format('YYYY-MM-DD')],messages.createdAt,@@ -2313,6 +3039,7 @@ export class MessageModel {.where(genWhere([this.ownership(),+ notShareVisitorMessage(),eq(messages.role, 'assistant'),notCopiedTranscript(),genRangeWhere(@@ -3196,6 +3923,10 @@ export class MessageModel {eq(messages.topicId, params.topicId),this.ownership(),this.pluginsOwnership(),+ // A desktop-local hetero run never happens inside an agent-share+ // visitor topic, so excluding them costs nothing and stops a creator+ // from surfacing a visitor's tool calls as their own Work cards.+ notShareVisitorMessage(),),);@@ -3796,13 +4527,30 @@ export class MessageModel {}};- deleteMessage = async (id: string) => {+ /**+ * Delete one message (plus the tool messages it owns).+ *+ * Agent-share visitor messages live under the creator's `userId`, so plain+ * ownership matches them: by default this refuses to touch them, which keeps+ * the creator-facing `message.removeMessage` from destroying a visitor's+ * conversation even when the creator obtained a raw visitor message id (e.g.+ * through data export). The agent runtime — which also runs visitor turns+ * under the creator's identity and must clean up its own placeholders — opts+ * back in with `includeShareVisitor`.+ */+ deleteMessage = async (id: string, options?: ShareVisitorWriteOptions) => {+ // Effective visitor gate: per-call `true` OR the instance flag widens the+ // scope. Uses `workspaceScope()` (raw) so an instance-default caller can+ // still opt in per-call without `ownership()` re-adding the exclusion.+ const includeVisitor = options?.includeShareVisitor || this.includeShareVisitor;+ const scope = includeVisitor ? this.workspaceScope() : this.ownership();+return this.db.transaction(async (tx) => {// 1. Query the complete information of the message to be deletedconst message = await tx.select().from(messages)- .where(and(eq(messages.id, id), this.ownership()))+ .where(and(eq(messages.id, id), scope)).limit(1);// If the message to be deleted is not found, return directly@@ -3818,7 +4566,7 @@ export class MessageModel {await tx.update(messages).set({ parentId: message[0].parentId })- .where(and(eq(messages.parentId, id), this.ownership()));+ .where(and(eq(messages.parentId, id), scope));// 3. Check if the message contains toolsconst toolCallIds = (message[0].tools as ChatToolPayload[])@@ -3841,9 +4589,7 @@ export class MessageModel {const messageIdsToDelete = [id, ...relatedMessageIds];// 6. Delete all related messages- await tx- .delete(messages)- .where(and(this.ownership(), inArray(messages.id, messageIdsToDelete)));+ await tx.delete(messages).where(and(scope, inArray(messages.id, messageIdsToDelete)));await this.reconcileActiveBranchSnapshots(tx, activeBranchSnapshots);@@ -3855,15 +4601,22 @@ export class MessageModel {});};- deleteMessages = async (ids: string[]) => {+ /**+ * Batch twin of {@link MessageModel.deleteMessage} — same agent-share visitor+ * rule: visitor messages are skipped unless the caller explicitly opts in.+ */+ deleteMessages = async (ids: string[], options?: ShareVisitorWriteOptions) => {if (ids.length === 0) return;+ const includeVisitor = options?.includeShareVisitor || this.includeShareVisitor;+ const scope = includeVisitor ? this.workspaceScope() : this.ownership();+return this.db.transaction(async (tx) => {// 1. Query all messages to be deleted with their parentIdconst toDelete = await tx.select({ id: messages.id, parentId: messages.parentId, topicId: messages.topicId }).from(messages)- .where(and(this.ownership(), inArray(messages.id, ids)));+ .where(and(scope, inArray(messages.id, ids)));if (toDelete.length === 0) return;@@ -3912,9 +4665,7 @@ export class MessageModel {const children = await tx.select({ id: messages.id, parentId: messages.parentId }).from(messages)- .where(- and(this.ownership(), inArray(messages.parentId, ids), not(inArray(messages.id, ids))),- );+ .where(and(scope, inArray(messages.parentId, ids), not(inArray(messages.id, ids))));// 5. Update each child's parentId to the final ancestorfor (const child of children) {@@ -3922,11 +4673,12 @@ export class MessageModel {await tx.update(messages).set({ parentId: newParentId })- .where(and(eq(messages.id, child.id), this.ownership()));+ .where(and(eq(messages.id, child.id), scope));}- // 6. Delete the messages- await tx.delete(messages).where(and(this.ownership(), inArray(messages.id, ids)));+ // 6. Delete the messages. Deletes the ids that survived the step-1+ // filter, not the raw input, so a mixed batch drops only the visitor rows.+ await tx.delete(messages).where(and(scope, inArray(messages.id, [...deleteSet])));await this.reconcileActiveBranchSnapshots(tx, activeBranchSnapshots);@@ -3990,24 +4742,50 @@ export class MessageModel {),);+ /**+ * Creator-facing "clear this session/topic/group" sweep.+ *+ * Agent-share visitor messages live under the creator's `userId` but are+ * hidden from every creator-facing listing (see `notShareVisitorMessage` in+ * `../utils/shareVisitor`), so an id-less sweep must not destroy them —+ * same rule as {@link deleteAllMessages}. Runtime cleanup opts back in via+ * `includeShareVisitor`.+ */deleteMessagesBySession = async (sessionId?: string | null,topicId?: string | null,groupId?: string | null,- ) =>- this.db+ options?: ShareVisitorWriteOptions,+ ) => {+ const includeVisitor = options?.includeShareVisitor || this.includeShareVisitor;+ const scope = includeVisitor ? this.workspaceScope() : this.ownership();++ return this.db.delete(messages).where(and(- this.ownership(),+ scope,this.matchSession(sessionId),this.matchTopic(topicId),this.matchGroup(groupId),),);+ };+ /**+ * Creator-facing "clear all my messages".+ *+ * Agent-share visitor messages are stored under the creator's `userId` but+ * are hidden from every creator-facing listing (see `notShareVisitorMessage`+ * in `../utils/shareVisitor`), so an id-less sweep must not destroy them —+ * "clear all" can only mean the rows the creator can actually see. Id-targeted+ * deletes ({@link MessageModel.deleteMessage}, {@link MessageModel.deleteMessages})+ * apply the same guard by default — a creator can obtain visitor ids out of+ * band (data export), so "the caller named the id" is not proof the row is+ * theirs to delete. Runtime cleanup opts back in via `includeShareVisitor`.+ */deleteAllMessages = async () => {- return this.db.delete(messages).where(and(this.ownership()));+ return this.db.delete(messages).where(and(this.ownership(), notShareVisitorMessage()));};/**@@ -4015,6 +4793,11 @@ export class MessageModel {* This will delete messages that have either:* 1. Direct agentId match (new data)* 2. SessionId match via agentsToSessions lookup (legacy data)+ *+ * This is the creator's "clear this agent's messages" action, so visitor+ * messages are excluded (see {@link deleteAllMessages}). Deleting the agent+ * itself is a different path: `messages.agent_id` / `topics.agent_id` cascade+ * at the DB level, so visitor rows do go away with the agent.*/batchDeleteByAgentId = async (agentId: string) => {// Get the associated sessionId for backward compatibility with legacy data@@ -4031,7 +4814,9 @@ export class MessageModel {? or(eq(messages.agentId, agentId), eq(messages.sessionId, associatedSessionId)): eq(messages.agentId, agentId);- return this.db.delete(messages).where(and(this.ownership(), agentCondition));+ return this.db+ .delete(messages)+ .where(and(this.ownership(), agentCondition, notShareVisitorMessage()));};// **************** Helper *************** //diff --git a/packages/database/src/models/recent.ts b/packages/database/src/models/recent.tsindex 6823c1db1df..952d2b29cf6 100644--- a/packages/database/src/models/recent.ts+++ b/packages/database/src/models/recent.ts@@ -5,6 +5,7 @@ import removeMarkdown from 'remove-markdown';import { agents, DOCUMENT_FOLDER_TYPE, documents, messages, tasks, topics } from '../schemas';import type { LobeChatDatabase } from '../type';+import { notShareVisitorTopic } from '../utils/shareVisitor';import { buildWorkspaceWhere } from '../utils/workspace';export interface RecentDbItem {@@ -101,6 +102,9 @@ export class RecentModel {? sql`false`: and(buildWorkspaceWhere(scope, topics),+ // Agent-share visitor topics keep the creator's userId — never+ // surface a visitor's conversation in the creator's own Recent feed.+ notShareVisitorTopic(),mineTopicWhere,or(isNotNull(topics.groupId),diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex c3e49f46391..d5f51371628 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -1,3 +1,4 @@+import { AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT } from '@lobechat/const';import type {ChatTopicMetadata,ChatTopicStatus,@@ -17,6 +18,7 @@ import {and,asc,count,+ countDistinct,desc,eq,getTableColumns,@@ -50,6 +52,7 @@ import { markCopiedMessageMetadata } from '../utils/copyMessagesInDatabase';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { idGenerator } from '../utils/idGenerator';import { inJsonStringArray } from '../utils/inJsonStringArray';+import { notShareVisitorTopic } from '../utils/shareVisitor';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';import { recomputeTopicUsage } from './topicUsage';@@ -105,6 +108,68 @@ export interface TopicListItem extends TopicItem {runStartedAt?: Date | null;}+/**+ * Sanitized projection of `topics.metadata.runningOperation` for a visitor DTO+ * — only the fields `useGatewayReconnect`'s `RunningOperation` needs to resume+ * a streaming session on reload. Never the full `runningOperation` object: it+ * also carries device/hetero fields (`deviceId`, `deviceUserId`, `hooks`, …)+ * that describe creator-side dispatch and must not reach a visitor.+ */+export interface VisitorRunningOperation {+ assistantMessageId: string;+ heteroType?: string | null;+ operationId: string;+ scope?: string;+ threadId?: string | null;+}++/**+ * Visitor-facing topic DTO for the agent-share surface. Deliberately narrow:+ * the underlying row is CREATOR-owned and also carries the creator's userId,+ * model/provider snapshot, cost/usage and internal metadata.+ */+export interface VisitorTopicItem {+ createdAt: Date;+ id: string;+ /**+ * Sanitized `runningOperation` marker, present only while a run is active on+ * this topic. Lets the share surface reconnect a Gateway stream after a page+ * reload — see {@link VisitorRunningOperation} for why it's projected+ * instead of forwarding `topics.metadata.runningOperation` as-is.+ */+ runningOperation?: VisitorRunningOperation | null;+ title: string | null;+ updatedAt: Date;+}++/**+ * Fallback page size for {@link TopicModel.queryBySender} when a caller+ * doesn't pass one. Pinned to the package default per-visitor topic cap.+ *+ * Callers with a live share config (e.g. `shareChat.getTopics`) MUST pass the+ * share's actual resolved `maxTopicsPerVisitor` as `pageSize` instead of+ * relying on this default — a creator who raises the cap above the default+ * would otherwise have a visitor's list silently truncated below what that+ * visitor is actually allowed to create.+ */+const VISITOR_TOPIC_PAGE_SIZE = AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT;++/**+ * Projects `topics.metadata.runningOperation` down to the visitor-safe subset+ * — see {@link VisitorRunningOperation}. Used by {@link TopicModel.queryBySender}+ * so a share visitor's topic list can drive `useGatewayReconnect` without ever+ * receiving the rest of `metadata` (creator-only fields — see the module doc).+ */+const pickVisitorRunningOperation = (+ metadata: ChatTopicMetadata | null | undefined,+): VisitorRunningOperation | null => {+ const runningOperation = metadata?.runningOperation;+ if (!runningOperation) return null;++ const { assistantMessageId, operationId, scope, threadId, heteroType } = runningOperation;+ return { assistantMessageId, heteroType, operationId, scope, threadId };+};+export interface CreateTopicParams {agentId?: string | null;favorite?: boolean;@@ -114,6 +179,18 @@ export interface CreateTopicParams {/** Pinned model snapshot, persisted to the top-level `topics.model` column. */model?: string | null;provider?: string | null;+ /**+ * Agent-share visitor topics carry the CREATOR's `userId` (billing/data+ * attribution) plus the visitor's id here, so creator-facing listings+ * exclude them (`notShareVisitorTopic`, applied by `query`, `count`,+ * `queryTopics`, `queryRecent` and `rank`) while the share surface scopes+ * reads per visitor (`queryBySender` / `countBySender`).+ *+ * A future opt-in surface (`allowCreatorViewSessions`) may let a creator+ * explicitly browse visitor sessions; that is not wired up yet — every+ * creator-facing read today unconditionally excludes senderId rows.+ */+ senderId?: string | null;sessionId?: string | null;/*** Initial status. Defaults to the column default (`active`). A topic created@@ -288,37 +365,90 @@ const buildTopicOrderBy = (topicActivityAt: SQL, sortBy?: TopicQuerySortBy): SQL* tick from the day it shipped, so rate-limit continuations never once resumed).* `jsonbNullTest.test.ts` is the source-shape guard that holds the line.*/+export interface TopicModelOptions {+ /**+ * Opt IN to agent-share visitor topics. Visitor conversations persist under+ * the CREATOR's `userId` (only `topics.senderId` marks them), so every+ * creator-facing read/write is default-scoped to exclude them. Only the+ * share-runtime surfaces (share-scoped tRPC routers, share abuse guards,+ * and the agent runtime paths that persist or clean up a visitor turn+ * under the creator's identity) should set this to `true`.+ */+ includeShareVisitor?: boolean;+}+export class TopicModel {private userId: string;private db: LobeChatDatabase;private ftsSearchCandidateSource?: FtsSearchCandidateSource;private workspaceId?: string;+ /**+ * When true, {@link ownership} (and by extension every creator-scoped read+ * path below) stops ANDing {@link notShareVisitorTopic}. Reserved for+ * surfaces that are share-runtime by design (agent-share visitor router,+ * share-scoped abuse guards) and for the agent runtime paths that persist+ * or clean up a visitor turn under the CREATOR's identity. Defaults to+ * false so every ordinary creator-facing caller fails closed instead of+ * relying on a per-callsite `notShareVisitorTopic()` AND.+ */+ private includeShareVisitor: boolean;constructor(db: LobeChatDatabase,userId: string,workspaceId?: string,ftsSearchCandidateSource?: FtsSearchCandidateSource,+ options: TopicModelOptions = {},) {this.userId = userId;this.db = db;this.workspaceId = workspaceId;this.ftsSearchCandidateSource = ftsSearchCandidateSource;+ this.includeShareVisitor = options.includeShareVisitor ?? false;}- private ownership = () =>+ /**+ * Raw workspace/user scope, WITHOUT the visitor exclusion. Backing store for+ * both {@link ownership} and {@link mine}, and the escape hatch for methods+ * that must see visitor rows independent of the instance flag+ * ({@link queryBySender} / {@link countBySender} / {@link countVisitors}).+ */+ private workspaceScope = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics);+ private ownership = () => and(this.workspaceScope(), this.notShareVisitor());+/*** In workspace mode `ownership()` matches every member's topics, so a bulk* "clear all" would wipe teammates' conversations. Destructive sweeps must* additionally pin `user_id` to the caller (personal mode is unchanged —* ownership already scopes to the user there).+ *+ * `mine()` deliberately does NOT AND {@link notShareVisitor} — it is the+ * per-user variant of {@link workspaceScope} and the share-scoped methods+ * ({@link queryBySender} / {@link countBySender} / {@link countVisitors})+ * layer their own `senderId` predicate on top of it. Creator-facing+ * destructive sweeps that reach for `mine()` still get the visitor+ * exclusion by AND-ing {@link notShareVisitor} themselves.*/- private mine = () => and(this.ownership(), eq(topics.userId, this.userId));+ private mine = () => and(this.workspaceScope(), eq(topics.userId, this.userId));private messageOwnership = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages);++ /**+ * The default visitor exclusion applied by {@link ownership}: `topics.senderId IS NULL`,+ * shared with the repositories/models that query `topics` outside this+ * class (see `notShareVisitorTopic` in `../utils/shareVisitor`). Returns+ * `undefined` when the instance was constructed with `includeShareVisitor:+ * true`, so the share runtime opts in explicitly and every other caller+ * gets the visitor guard for free.+ *+ * The visitor-scoped counterparts ({@link queryBySender}, {@link countBySender})+ * intentionally do the opposite — they match on `senderId`, not exclude+ * it — and use {@link mine} (which skips this helper).+ */+ private notShareVisitor = () => (this.includeShareVisitor ? undefined : notShareVisitorTopic());// **************** Query *************** //query = async ({@@ -428,6 +558,7 @@ export class TopicModel {if (groupId) {const whereCondition = and(this.ownership(),+ this.notShareVisitor(),eq(topics.groupId, groupId),includeTriggerCondition,excludeTriggerCondition,@@ -507,6 +638,7 @@ export class TopicModel {const agentWhere = and(this.ownership(),+ this.notShareVisitor(),agentCondition,editingTargetCondition,includeTriggerCondition,@@ -578,6 +710,7 @@ export class TopicModel {// Fallback to containerId-based query (backward compatibility)const whereCondition = and(this.ownership(),+ this.notShareVisitor(),this.matchContainer(containerId),includeTriggerCondition,excludeTriggerCondition,@@ -648,12 +781,52 @@ export class TopicModel {return { items: cleanItems, total: totalResult[0].count };};+ /**+ * Ownership-scoped lookup. Agent-share visitor topics carry the CREATOR's+ * `userId` and are excluded by default; the share runtime opts in by+ * constructing the model with `{ includeShareVisitor: true }`.+ * `findVisitorTopicOrThrow` in `apps/server/src/routers/lambda/shareChat.ts`+ * relies on that opt-in and then verifies `senderId` itself.+ */findById = async (id: string) => {return this.db.query.topics.findFirst({where: and(eq(topics.id, id), this.ownership()),});};+ /**+ * Kept for readability at creator-facing router call sites; the default+ * scope already excludes agent-share visitor topics, so this is a thin+ * alias of {@link TopicModel.findById}.+ */+ findOwnTopicById = async (id: string) => {+ return this.findById(id);+ };++ /**+ * Ids among `ids` that resolve to an agent-share VISITOR topic under this+ * owner — the inverse of {@link notShareVisitorTopic}, the predicate every+ * creator-facing read applies.+ *+ * Creator-facing write entry points use this to reject visitor targets+ * (see `assertCreatorTopicTargets` in the server router helpers). Ids that+ * match no row at all are NOT reported, so callers keep their existing no-op+ * behaviour for stale/foreign ids.+ */+ findShareVisitorTopicIds = async (ids: string[]): Promise<string[]> => {+ if (ids.length === 0) return [];++ const rows = await this.db+ .select({ id: topics.id })+ .from(topics)+ // Explicitly scoped visitor-inclusive: this method's whole job is to+ // return visitor ids so the router-level `assertCreatorTopicTargets`+ // can reject them, so it must bypass the instance's visitor exclusion.+ .where(and(inArray(topics.id, ids), this.workspaceScope(), isNotNull(topics.senderId)));++ return rows.map((row) => row.id);+ };+findByIds = async (ids: string[]): Promise<TopicItem[]> => {if (ids.length === 0) return [];return this.db.query.topics.findMany({@@ -661,6 +834,15 @@ export class TopicModel {});};+ /**+ * Kept for readability at creator-facing router call sites; the default+ * scope already excludes agent-share visitor topics, so this is a thin+ * alias of {@link TopicModel.findByIds}.+ */+ findOwnTopicsByIds = async (ids: string[]): Promise<TopicItem[]> => {+ return this.findByIds(ids);+ };+/*** Minimal creator projection for router-level workspace row checks on* batch-by-ids operations (batch delete / move).@@ -722,6 +904,7 @@ export class TopicModel {} = {}): Promise<TopicListItem[]> => {const where = and(this.ownership(),+ this.notShareVisitor(),statuses && statuses.length > 0? inArray(topics.status, statuses as ChatTopicStatus[]): undefined,@@ -881,6 +1064,7 @@ export class TopicModel {.where(and(this.ownership(),+ this.notShareVisitor(),scopeCondition,topicCandidateIds? inJsonStringArray(topics.id, topicCandidateIds)@@ -900,6 +1084,7 @@ export class TopicModel {? inJsonStringArray(messages.id, messageCandidateIds): sql`${messages.content} @@@ ${bm25Query}`,this.ownership(),+ this.notShareVisitor(),scopeCondition,),)@@ -955,6 +1140,7 @@ export class TopicModel {.where(genWhere([this.ownership(),+ this.notShareVisitor(),agentCondition,params?.containerId ? this.matchContainer(params.containerId) : undefined,params?.range@@ -981,7 +1167,7 @@ export class TopicModel {title: topics.title,}).from(topics)- .where(and(this.ownership()))+ .where(and(this.ownership(), this.notShareVisitor())).leftJoin(messages, eq(topics.id, messages.topicId)).groupBy(topics.id).orderBy(desc(sql`count`))@@ -1022,6 +1208,7 @@ export class TopicModel {.where(and(this.ownership(),+ this.notShareVisitor(),or(// Group topics: has groupIdnot(isNull(topics.groupId)),@@ -1042,6 +1229,106 @@ export class TopicModel {}));};+ // **************** Agent Share (visitor-scoped) *************** //++ /**+ * Share-visitor topic list for one visitor on one shared agent. The model is+ * constructed with the CREATOR's userId (visitor topics carry it), so the+ * caller — the shareChat router — must have already authorized the visitor+ * via the share access check; `agentId` + `senderId` together are the+ * per-visitor boundary.+ *+ * `agent_shares` is 1:1 per agent (`agent_shares_agent_id_unique`), so+ * `agentId` alone identifies which share a visitor topic belongs to — there+ * is no `topics.share_id` column to scope by. Turning sharing off and back+ * on keeps the same row and the same `agentId`, so a returning visitor's+ * older conversations DO resurface under the republished share. That is the+ * accepted trade-off of not carrying a share id on the row.+ *+ * Selects a visitor-facing DTO instead of the full row: the visitor surface+ * only renders id/title/runningOperation, and the row also carries+ * creator-only fields (owning userId, model/provider snapshot, cost/usage,+ * internal status and the rest of `metadata`) that must never reach a share+ * visitor. `metadata` itself IS selected (needed to project+ * `runningOperation`), but only the sanitized projection — never the raw+ * column — leaves this method; see {@link VisitorRunningOperation}.+ */+ queryBySender = async (+ { agentId, senderId }: { agentId: string; senderId: string },+ { pageSize = VISITOR_TOPIC_PAGE_SIZE }: { pageSize?: number } = {},+ ): Promise<VisitorTopicItem[]> => {+ const rows = await this.db+ .select({+ createdAt: topics.createdAt,+ id: topics.id,+ metadata: topics.metadata,+ title: topics.title,+ updatedAt: topics.updatedAt,+ })+ .from(topics)+ .where(and(this.mine(), eq(topics.agentId, agentId), eq(topics.senderId, senderId)))+ .orderBy(desc(topics.updatedAt))+ .limit(pageSize);++ return rows.map(({ metadata, ...rest }) => ({+ ...rest,+ runningOperation: pickVisitorRunningOperation(metadata),+ }));+ };++ /**+ * Per-visitor topic count on a shared agent — drives `maxTopicsPerVisitor`.+ * Same `(agentId, senderId)` scoping as {@link queryBySender}; see that+ * method's JSDoc for why there is no share-id dimension.+ */+ countBySender = async ({+ agentId,+ senderId,+ }: {+ agentId: string;+ senderId: string;+ }): Promise<number> => {+ const result = await this.db+ .select({ count: count(topics.id) })+ .from(topics)+ .where(and(this.mine(), eq(topics.agentId, agentId), eq(topics.senderId, senderId)));++ return result[0].count;+ };++ /**+ * Creator-facing roll-up for one shared agent: how many conversations+ * visitors started, and how many distinct visitors started them.+ *+ * Counterpart to {@link countBySender}, which counts ONE visitor. Both rely+ * on `senderId` being non-null only for share-originated topics, so the+ * creator's own conversations with the same agent are excluded. Scoped by+ * `this.mine()` like every other read here, so the numbers can only ever+ * describe rows the caller owns.+ *+ * `agentShares` is 1:1 per agent, so `agentId` alone is the share dimension+ * — see {@link queryBySender} for why a disable → re-enable cycle keeps+ * counting the earlier conversations.+ */+ countShareVisitors = async ({+ agentId,+ }: {+ agentId: string;+ }): Promise<{ topicCount: number; visitorCount: number }> => {+ const [result] = await this.db+ .select({+ topicCount: count(topics.id),+ visitorCount: countDistinct(topics.senderId),+ })+ .from(topics)+ .where(and(this.mine(), eq(topics.agentId, agentId), isNotNull(topics.senderId)));++ return {+ topicCount: Number(result?.topicCount ?? 0),+ visitorCount: Number(result?.visitorCount ?? 0),+ };+ };+// **************** Create *************** //create = async (@@ -1270,16 +1557,28 @@ export class TopicModel {// **************** Delete *************** ///**- * Delete a session, also delete all messages and topics associated with it.+ * Delete one topic, cascading to the messages associated with it.+ *+ * Agent-share visitor topics carry the creator's `userId`, so ownership alone+ * would let the creator-facing `topic.removeTopic` destroy a visitor+ * conversation from a raw topic id (obtainable out of band, e.g. through data+ * export). Excluded here for the same reason the bulk sweeps exclude them —+ * see {@link deleteAll}.*/delete = async (id: string) => {- return this.db.delete(topics).where(and(eq(topics.id, id), this.ownership()));+ return this.db+ .delete(topics)+ .where(and(eq(topics.id, id), this.ownership(), this.notShareVisitor()));};/*** Deletes multiple topics based on the sessionId.* `restrictToCreator` limits the sweep to the caller's own rows (workspace* non-owner members must not clear teammates' topics).+ *+ * Visitor topics have no sessionId, so the null-session (inbox) branch would+ * otherwise sweep them in — see {@link deleteAll} for why bulk sweeps exclude+ * them.*/batchDeleteBySessionId = async (sessionId?: string | null,@@ -1291,6 +1590,7 @@ export class TopicModel {and(this.matchSession(sessionId),options?.restrictToCreator ? this.mine() : this.ownership(),+ this.notShareVisitor(),),);};@@ -1298,6 +1598,9 @@ export class TopicModel {/*** Deletes multiple topics based on the groupId.* `restrictToCreator` limits the sweep to the caller's own rows in workspace mode.+ *+ * Visitor topics have no groupId, so the null-group branch would otherwise+ * sweep them in — see {@link deleteAll}.*/batchDeleteByGroupId = async (groupId?: string | null,@@ -1306,7 +1609,11 @@ export class TopicModel {return this.db.delete(topics).where(- and(this.matchGroup(groupId), options?.restrictToCreator ? this.mine() : this.ownership()),+ and(+ this.matchGroup(groupId),+ options?.restrictToCreator ? this.mine() : this.ownership(),+ this.notShareVisitor(),+ ),);};@@ -1314,6 +1621,11 @@ export class TopicModel {* Deletes all topics matching the given agentId (`topics.agentId`).* `restrictToCreator` limits the sweep to the caller's own rows (workspace* non-owner members must not clear teammates' topics).+ *+ * This is the creator's "clear this agent's topics" action, so agent-share+ * visitor topics are excluded (see {@link deleteAll}). Deleting the agent+ * itself is a different path: `topics.agent_id` cascades at the DB level, so+ * visitor topics do go away with the agent without any call to this method.*/batchDeleteByAgentId = async (agentId: string, options?: { restrictToCreator?: boolean }) => {return this.db@@ -1322,19 +1634,37 @@ export class TopicModel {and(options?.restrictToCreator ? this.mine() : this.ownership(),eq(topics.agentId, agentId),+ this.notShareVisitor(),),);};/*** Deletes multiple topics and all messages associated with them in a transaction.+ *+ * Agent-share visitor topics are excluded — see {@link TopicModel.delete}.*/batchDelete = async (ids: string[]) => {- return this.db.delete(topics).where(and(inArray(topics.id, ids), this.ownership()));+ return this.db+ .delete(topics)+ .where(and(inArray(topics.id, ids), this.ownership(), this.notShareVisitor()));};+ /**+ * Creator-facing "clear all my topics".+ *+ * Agent-share visitor topics live under the creator's `userId` but are hidden+ * from every creator-facing listing (see `notShareVisitorTopic` in+ * `../utils/shareVisitor`), so a sweep the creator cannot see the contents of+ * must not destroy them — "clear all" can only mean the rows the creator sees.+ * The same rule applies to the other id-less sweeps here.+ *+ * Id-targeted deletes ({@link TopicModel.delete}, {@link TopicModel.batchDelete})+ * apply the same guard: a creator can obtain a visitor topic id out of band+ * (data export), so naming the id is not proof the row is theirs to delete.+ */deleteAll = async () => {- return this.db.delete(topics).where(this.mine());+ return this.db.delete(topics).where(and(this.mine(), this.notShareVisitor()));};// **************** Update *************** //@@ -2122,6 +2452,9 @@ export class TopicModel {orderBy: (fields, { asc }) => [asc(fields.createdAt), asc(fields.id)],where: and(this.ownership(),+ // Share-visitor conversations are not the creator's own speech — never+ // feed them into the creator's memory extraction.+ this.notShareVisitor(),options.startDate ? gte(topics.createdAt, options.startDate) : undefined,options.endDate ? lte(topics.createdAt, options.endDate) : undefined,options.ignoreExtracted@@ -2148,6 +2481,7 @@ export class TopicModel {.where(and(this.ownership(),+ this.notShareVisitor(),options.startDate ? gte(topics.createdAt, options.startDate) : undefined,options.endDate ? lte(topics.createdAt, options.endDate) : undefined,options.ignoreExtracteddiff --git a/packages/database/src/models/topicSummary.ts b/packages/database/src/models/topicSummary.tsindex c91e94a28bb..be904eeed87 100644--- a/packages/database/src/models/topicSummary.ts+++ b/packages/database/src/models/topicSummary.ts@@ -21,6 +21,7 @@ import {import { messages, topics, userSettings } from '../schemas';import type { LobeChatDatabase } from '../type';+import { notShareVisitorTopic } from '../utils/shareVisitor';export interface TopicSummaryCandidateCursor {id: string;@@ -96,6 +97,11 @@ export class TopicSummaryModel {topicSummaryEligibleMessage,or(isNull(topics.trigger), not(inArray(topics.trigger, SYSTEM_TOPIC_TRIGGERS))),or(isNull(topics.status), notInArray(topics.status, ['running', 'scheduled'])),+ // Visitor topics are creator-billed only through the share spend+ // gate; the auto-summary worker must never pick them, or a shared+ // agent's visitor turn would silently spend the creator's balance+ // outside the gate. See `notShareVisitorTopic` for the invariant.+ notShareVisitorTopic(),force ? undefined : isTopicAutoSummaryEnabled,),)@@ -160,7 +166,18 @@ export class TopicSummaryModel {metadata: mergeAutoSummaryMetadata(marker),updatedAt: new Date(),})- .where(and(eq(topics.id, input.topicId), exists(snapshotMessage), notExists(newerMessage)))+ .where(+ and(+ eq(topics.id, input.topicId),+ // Defense in depth against a visitor topic slipping past the+ // listCandidates filter and the service-layer guard (see+ // `notShareVisitorTopic`): the write fence itself refuses to touch+ // a share-visitor topic keyed only by id.+ notShareVisitorTopic(),+ exists(snapshotMessage),+ notExists(newerMessage),+ ),+ ).returning({ id: topics.id });return rows.length > 0;diff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.tsindex 55f0148273e..3a04e3067c9 100644--- a/packages/database/src/models/user.ts+++ b/packages/database/src/models/user.ts@@ -437,6 +437,17 @@ export class UserModel {return { duplicate: false, user };};+ /**+ * Deletes a user account and their agent-share visitor conversations.+ *+ * Agent-share visitor topics are stored under the CREATOR's userId (for+ * billing/data attribution) and linked to the visitor only via+ * `topics.senderId`, which has no FK. That means the `users` cascade cannot+ * reach them — deleting the visitor's account would otherwise orphan every+ * conversation they had inside someone else's shared agent. We explicitly+ * drop `topics` where `senderId = id`; messages, threads, and topic+ * documents cascade from `topics.id`, so the topic delete is enough.+ */static deleteUser = async (db: LobeChatDatabase, id: string) => {// A pending agent-TRANSFER backfill means message rows moved to (or from)// this user still carry the other side's scope snapshot; cascading the@@ -447,7 +458,11 @@ export class UserModel {if (await AgentTransferJobModel.hasPendingJobTouchingUser(db, id)) {throw new Error(AGENT_TRANSFER_PENDING_OWNER_DELETE);}- return db.delete(users).where(eq(users.id, id));+ return db.transaction(async (tx) => {+ // Purge share-visitor topics authored by this user under any creator.+ await tx.delete(topics).where(eq(topics.senderId, id));+ return tx.delete(users).where(eq(users.id, id));+ });};static findById = async (db: LobeChatDatabase, id: string) => {diff --git a/packages/database/src/repositories/dataExporter/index.test.ts b/packages/database/src/repositories/dataExporter/index.test.tsindex 6686c345daa..e44253d3799 100644--- a/packages/database/src/repositories/dataExporter/index.test.ts+++ b/packages/database/src/repositories/dataExporter/index.test.ts@@ -10,9 +10,11 @@ import {globalFiles,knowledgeBaseFiles,knowledgeBases,+ messagePlugins,messages,sessionGroups,sessions,+ threads,topics,users,userSettings,@@ -329,6 +331,67 @@ describe('DataExporterRepos', () => {expect(result.sessions).toHaveLength(1);});+ it('should exclude agent-share visitor rows from the creator export', async () => {+ // Agent-share visitor conversations are persisted under the creator's+ // userId with a non-null topics.senderId, so only the senderId marks them+ // as third-party data.+ const visitorUserId = 'share-visitor-user-id';++ await db.transaction(async (trx) => {+ await trx.insert(users).values({+ email: '[email protected]',+ id: visitorUserId,+ username: 'visitor',+ });+ await trx.insert(topics).values({+ id: 'visitor-topic-id',+ senderId: visitorUserId,+ sessionId: testIds.sessionId,+ title: 'Visitor Topic',+ userId,+ });+ await trx.insert(messages).values({+ content: 'Visitor message',+ id: 'visitor-message-id',+ role: 'user',+ sessionId: testIds.sessionId,+ topicId: 'visitor-topic-id',+ userId,+ });+ await trx.insert(messagePlugins).values({+ id: 'visitor-message-id',+ identifier: 'visitor-plugin',+ userId,+ });+ await trx.insert(threads).values({+ id: 'visitor-thread-id',+ title: 'Visitor Thread',+ topicId: 'visitor-topic-id',+ type: 'continuation',+ userId,+ });+ await trx.insert(threads).values({+ id: 'own-thread-id',+ title: 'Own Thread',+ topicId: testIds.topicId,+ type: 'continuation',+ userId,+ });+ await trx.insert(messagePlugins).values({+ id: testIds.messageId,+ identifier: 'own-plugin',+ userId,+ });+ });++ const result = await new DataExporterRepos(db, userId).export();++ expect(result.topics.map((topic) => topic.id)).toEqual([testIds.topicId]);+ expect(result.messages.map((message) => message.id)).toEqual([testIds.messageId]);+ expect(result.threads.map((thread) => thread.id)).toEqual(['own-thread-id']);+ expect(result.messagePlugins.map((plugin) => plugin.id)).toEqual([testIds.messageId]);+ });+it('should export data for a different user', async () => {// Create another userconst anotherUserId = 'another-user-id';diff --git a/packages/database/src/repositories/dataExporter/index.ts b/packages/database/src/repositories/dataExporter/index.tsindex 3db81b32586..41ad8b8b22f 100644--- a/packages/database/src/repositories/dataExporter/index.ts+++ b/packages/database/src/repositories/dataExporter/index.ts@@ -1,11 +1,41 @@-import { and, eq, inArray } from 'drizzle-orm';+import { and, eq, inArray, isNull, or, type SQL } from 'drizzle-orm';import pMap from 'p-map';import * as EXPORT_TABLES from '../../schemas';+import { messages } from '../../schemas';import type { LobeChatDatabase } from '../../type';+import {+ notShareVisitorMessage,+ notShareVisitorTopic,+ notShareVisitorTopicRef,+} from '../../utils/shareVisitor';import { buildWorkspaceWhere } from '../../utils/workspace';+/**+ * Agent-share visitor conversations are stored under the CREATOR's `userId`+ * with a non-null `topics.senderId`, so a plain `eq(table.userId, userId)`+ * filter would dump third-party visitor chats into the creator's data export.+ * Each conversation-carrying table therefore declares how it reaches the owning+ * topic:+ *+ * - `topicSender`: the table IS `topics` — filter on `senderId` directly.+ * - `topicRef`: the table references a topic id (messages, threads).+ * - `messageRef`: the table references a message id and has no topic column+ * (message_plugins / message_translates keyed by `id`, message_chunks keyed+ * by `messageId`), so the predicate is relayed one extra hop through+ * `messages`.+ *+ * Tables without any of these (userSettings, userInstalledPlugins, agents,+ * aiModels, aiProviders, sessionGroups, sessions, and the `agentsToSessions`+ * relation) hold creator-authored configuration only — a visitor never creates+ * rows there — so they stay unfiltered and the export shape is unchanged.+ */+type ShareVisitorRef =+ { column?: undefined; via: 'topicSender' } | { column: string; via: 'messageRef' | 'topicRef' };+interface BaseTableConfig {+ /** How this table reaches the topic that decides share-visitor ownership. */+ shareVisitorRef?: ShareVisitorRef;table: keyof typeof EXPORT_TABLES;type: 'base';userField?: string;@@ -42,13 +72,13 @@ export const DATA_EXPORT_CONFIG = {// { table: 'filesToSessions' },// { table: 'knowledgeBases' },// { table: 'knowledgeBaseFiles' },- { table: 'messageChunks' },- { table: 'messagePlugins' },+ { shareVisitorRef: { column: 'messageId', via: 'messageRef' }, table: 'messageChunks' },+ { shareVisitorRef: { column: 'id', via: 'messageRef' }, table: 'messagePlugins' },// { table: 'messageQueryChunks' },// { table: 'messageQueries' },- { table: 'messageTranslates' },+ { shareVisitorRef: { column: 'id', via: 'messageRef' }, table: 'messageTranslates' },// { table: 'messageTTS' },- { table: 'messages' },+ { shareVisitorRef: { column: 'topicId', via: 'topicRef' }, table: 'messages' },// { table: 'messagesFiles' },// next auth tables won't be included@@ -58,8 +88,8 @@ export const DATA_EXPORT_CONFIG = {// { table: 'nextauthVerificationTokens' },{ table: 'sessionGroups' },{ table: 'sessions' },- { table: 'threads' },- { table: 'topics' },+ { shareVisitorRef: { column: 'topicId', via: 'topicRef' }, table: 'threads' },+ { shareVisitorRef: { via: 'topicSender' }, table: 'topics' },] as BaseTableConfig[],relationTables: [// {@@ -92,6 +122,34 @@ export class DataExporterRepos {this.workspaceId = workspaceId;}+ /**+ * Builds the share-visitor exclusion for a base table, reusing the shared+ * predicates in `utils/shareVisitor` so the export can never drift from the+ * rest of the creator-facing surfaces.+ */+ private buildShareVisitorCondition(+ ref: ShareVisitorRef,+ tableObj: Record<string, any>,+ ): SQL | undefined {+ if (ref.via === 'topicSender') return notShareVisitorTopic();++ const column = tableObj[ref.column];+ if (!column) return undefined;++ if (ref.via === 'topicRef') return notShareVisitorTopicRef(column);++ // `messageRef`: no topic column here, so keep only rows whose parent+ // message itself survives `notShareVisitorMessage()`. A NULL message+ // reference is trivially kept, matching the shared helpers' semantics.+ return or(+ isNull(column),+ inArray(+ column,+ this.db.select({ id: messages.id }).from(messages).where(notShareVisitorMessage()),+ ),+ );+ }+private removeUserId(data: any[]) {return data.map((item) => {const { userId: _, ...rest } = item;@@ -162,13 +220,26 @@ export class DataExporterRepos {// Default to querying with userId, use userField for special casesconst userField = config.userField || 'userId';- const where =+ const ownershipWhere ='workspaceId' in tableObj? buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, tableObj): eq(tableObj[userField], this.userId);- // @ts-expect-error query- const result = await this.db.query[table].findMany({ where });+ const shareVisitorWhere = config.shareVisitorRef+ ? this.buildShareVisitorCondition(config.shareVisitorRef, tableObj)+ : undefined;++ const where = shareVisitorWhere ? and(ownershipWhere, shareVisitorWhere) : ownershipWhere;++ // Plain select builder instead of `db.query...findMany` whenever a+ // share-visitor predicate is involved: the relational query API+ // re-qualifies raw SQL fragments to the outer table alias, which breaks+ // the `topics`-referencing NOT EXISTS inside the shared helpers (same+ // caveat as `MessageModel.queryBySessionId`).+ const result = shareVisitorWhere+ ? await this.db.select().from(tableObj).where(where)+ : // @ts-expect-error query+ await this.db.query[table].findMany({ where });// Only remove userId field for tables queried with userIdconsole.info(`Successfully exported table: ${table}, count: ${result.length}`);diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.tsindex 58465cbf17a..0138803a53e 100644--- a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts@@ -28,6 +28,7 @@ import {} from '../../../schemas';import type { LobeChatDatabase } from '../../../type';import { normalizeInboxAgentMeta, normalizeInboxAgentTitle } from '../../../utils/inboxAgent';+import { notShareVisitorMessage, notShareVisitorTopic } from '../../../utils/shareVisitor';import { buildWorkspaceWhere } from '../../../utils/workspace';import type {FtsSearchAgentResult,@@ -270,6 +271,10 @@ export const hydrateTopics = async (hits.map(({ id }) => id),),buildWorkspaceWhere(scope, topics),+ // The ES index carries no `senderId`, but hydration is the only path+ // from a candidate id to real content, so filtering agent-share visitor+ // topics here is enough to keep them out of the creator's results.+ notShareVisitorTopic(),agentId ? eq(topics.agentId, agentId) : undefined,visibleParent(topics.agentId, agents.id),visibleParent(topics.groupId, chatGroups.id),@@ -373,6 +378,8 @@ export const hydrateMessages = async (),buildWorkspaceWhere(scope, messages),ne(messages.role, 'tool'),+ // Twin of the topics guard in `hydrateTopics`.+ notShareVisitorMessage(),agentId ? eq(messages.agentId, agentId) : undefined,visibleParent(messages.agentId, agents.id),visibleParent(messages.groupId, chatGroups.id),diff --git a/packages/database/src/repositories/ftsSearch/index.test.ts b/packages/database/src/repositories/ftsSearch/index.test.tsindex 2d699979d1d..122147609b1 100644--- a/packages/database/src/repositories/ftsSearch/index.test.ts+++ b/packages/database/src/repositories/ftsSearch/index.test.ts@@ -1447,6 +1447,60 @@ describe.skipIf(!isServerDB)('FtsSearchRepo', () => {});});+ // Agent-share visitor conversations are persisted under the CREATOR's+ // `userId` and are only distinguishable by `topics.senderId`, so the+ // ownership/workspace scope alone would surface them in the creator's own+ // full-text search.+ describe('search - agent share visitor isolation', () => {+ beforeEach(async () => {+ await serverDB.insert(topics).values([+ {+ content: 'Visitor asked about quantum entanglement in depth',+ id: 'fts-visitor-topic',+ senderId: 'fts-visitor-user',+ title: 'Visitor quantum session',+ userId,+ },+ {+ content: 'Creator notes about quantum entanglement',+ id: 'fts-creator-topic',+ title: 'Creator quantum session',+ userId,+ },+ ]);+ await serverDB.insert(messages).values([+ {+ content: 'my quantum password is hunter2',+ id: 'fts-visitor-message',+ role: 'user',+ topicId: 'fts-visitor-topic',+ userId,+ },+ {+ content: 'my quantum notes are public',+ id: 'fts-creator-message',+ role: 'user',+ topicId: 'fts-creator-topic',+ userId,+ },+ ]);+ });++ it('does not return an agent-share visitor topic', async () => {+ const results = await ftsSearchRepo.search({ query: 'quantum', type: 'topic' });++ expect(results.map((result) => result.id)).toContain('fts-creator-topic');+ expect(results.map((result) => result.id)).not.toContain('fts-visitor-topic');+ });++ it('does not return an agent-share visitor message', async () => {+ const results = await ftsSearchRepo.search({ query: 'quantum', type: 'message' });++ expect(results.map((result) => result.id)).toContain('fts-creator-message');+ expect(results.map((result) => result.id)).not.toContain('fts-visitor-message');+ });+ });+// Regression guard: the BM25 scans were split into an inner// single-table subquery (so ParadeDB can pick its TopN custom scan) with the// joins and — in personal mode — the `workspace_id IS NULL` check moved abovediff --git a/packages/database/src/repositories/ftsSearch/pgSearch/command-menu.ts b/packages/database/src/repositories/ftsSearch/pgSearch/command-menu.tsindex 652b5d2aa04..2fbeaeb8652 100644--- a/packages/database/src/repositories/ftsSearch/pgSearch/command-menu.ts+++ b/packages/database/src/repositories/ftsSearch/pgSearch/command-menu.ts@@ -13,6 +13,7 @@ import {} from '../../../schemas';import { sanitizeBm25Query } from '../../../utils/bm25';import { normalizeInboxAgentMeta, normalizeInboxAgentTitle } from '../../../utils/inboxAgent';+import { notShareVisitorMessage, notShareVisitorTopic } from '../../../utils/shareVisitor';import { buildWorkspaceWhere } from '../../../utils/workspace';import type {FtsSearchAgentResult,@@ -134,6 +135,10 @@ export async function searchTopics(.where(and(context.scanScopeWhere(topics),+ // Agent-share visitor topics are stored under the creator's userId, so+ // the scope predicate alone would surface a visitor's conversation in+ // the creator's command-menu search.+ notShareVisitorTopic(),agentId && !context.liftsAgentFilter ? eq(topics.agentId, agentId) : undefined,sql`(${topics.title} @@@ ${bm25Query} OR ${topics.content} @@@ ${bm25Query} OR ${topics.description} @@@ ${bm25Query})`,),@@ -242,6 +247,9 @@ export async function searchMessages(and(context.scanScopeWhere(messages),ne(messages.role, 'tool'),+ // Twin of the topics guard: visitor messages inherit the creator's+ // userId and are only identifiable through their parent topic.+ notShareVisitorMessage(),agentId && !context.liftsAgentFilter ? eq(messages.agentId, agentId) : undefined,sql`${messages.content} @@@ ${bm25Query}`,),diff --git a/packages/database/src/repositories/home/__tests__/index.test.ts b/packages/database/src/repositories/home/__tests__/index.test.tsindex cfc328014df..d1e9b92ef57 100644--- a/packages/database/src/repositories/home/__tests__/index.test.ts+++ b/packages/database/src/repositories/home/__tests__/index.test.ts@@ -347,6 +347,82 @@ describe('HomeRepository', () => {expect(result.ungrouped[0].unreadCount).toBe(1);});+ it('should not count agent-share visitor unread topics in agent sidebar badges', async () => {+ // Agent-share visitor topics keep the creator's userId, but a non-null+ // senderId marks them as visitor traffic that must not bump the+ // creator's own unread badge.+ const agentId = 'agent-with-visitor-unread';++ await clientDB.transaction(async (tx) => {+ await tx.insert(Schema.agents).values({+ id: agentId,+ pinned: false,+ title: 'Agent With Visitor Unread',+ userId,+ virtual: false,+ });+ await tx.insert(Schema.topics).values([+ {+ agentId,+ id: 'visitor-unread-topic',+ status: 'unread',+ senderId: 'visitor-user-x',+ title: 'Visitor unread topic',+ userId,+ },+ {+ agentId,+ id: 'creator-unread-topic',+ status: 'unread',+ title: 'Creator unread topic',+ userId,+ },+ ]);+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.ungrouped).toHaveLength(1);+ expect(result.ungrouped[0].id).toBe(agentId);+ expect(result.ungrouped[0].unreadCount).toBe(1);+ });++ it('should not count agent-share visitor unread topics in chat group unread badges', async () => {+ const groupId = 'group-with-visitor-unread';++ await clientDB.transaction(async (tx) => {+ await tx.insert(Schema.chatGroups).values({+ id: groupId,+ userId,+ title: 'Group With Visitor Unread',+ pinned: false,+ });+ await tx.insert(Schema.topics).values([+ {+ groupId,+ id: 'visitor-unread-group-topic',+ status: 'unread',+ senderId: 'visitor-user-x',+ title: 'Visitor unread topic',+ userId,+ },+ {+ groupId,+ id: 'creator-unread-group-topic',+ status: 'unread',+ title: 'Creator unread topic',+ userId,+ },+ ]);+ });++ const result = await homeRepo.getSidebarAgentList();++ const group = result.ungrouped.find((i) => i.id === groupId);+ expect(group).toBeDefined();+ expect(group!.unreadCount).toBe(1);+ });+describe('backward compatibility - fallback to sessions.pinned', () => {it('should fallback to sessions.pinned when agents.pinned is undefined (legacy data)', async () => {// Simulate legacy data: agents.pinned is null, but sessions.pinned is truediff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.tsindex 2393b25e233..f09fc24fa5e 100644--- a/packages/database/src/repositories/home/index.ts+++ b/packages/database/src/repositories/home/index.ts@@ -22,6 +22,7 @@ import { type LobeChatDatabase } from '../../type';import { sanitizeBm25Query } from '../../utils/bm25';import { normalizeInboxAgentMeta } from '../../utils/inboxAgent';import { inJsonStringArray } from '../../utils/inJsonStringArray';+import { notShareVisitorTopic } from '../../utils/shareVisitor';import { buildWorkspaceWhere } from '../../utils/workspace';import type { FtsSearchCandidateSource } from '../ftsSearch';@@ -251,6 +252,9 @@ export class HomeRepository {.where(and(buildWorkspaceWhere(this.scope, topics),+ // Agent-share visitor topics keep the creator's userId — never bump+ // the creator's own unread badge for a visitor's conversation.+ notShareVisitorTopic(),isUnread,isMainSidebarTopic,sql`${topics.agentId} is not null`,@@ -263,6 +267,7 @@ export class HomeRepository {.where(and(buildWorkspaceWhere(this.scope, topics),+ notShareVisitorTopic(),isUnread,isMainSidebarTopic,sql`${topics.groupId} is not null`,diff --git a/packages/database/src/schemas/agentShare.ts b/packages/database/src/schemas/agentShare.tsindex b37b6b22683..f81959c73e2 100644--- a/packages/database/src/schemas/agentShare.ts+++ b/packages/database/src/schemas/agentShare.ts@@ -1,20 +1,80 @@+import type { AgentShareToolGrant } from '@lobechat/types';import { index, integer, jsonb, pgTable, text, uniqueIndex, uuid } from 'drizzle-orm/pg-core';import { timestamps } from './_helpers';import { agents } from './agent';export interface AgentShareConfig {+ /**+ * Whether the creator may view visitor sessions/topics created against this+ * share. Defaults to `false` — visitor conversations are private to the+ * visitor unless the creator explicitly opts into oversight.+ */+ allowCreatorViewSessions?: boolean;+ /**+ * Whether visitors may read the creator's persisted long-term memory during+ * a shared conversation. Defaults to `false`.+ */allowReadMemory?: boolean;- filePermissionConfig?: {- agentFiles?: 'none' | 'read';- knowledgeBase?: 'none' | 'read';- uploadAllowed?: boolean;- };- guestEnabled?: boolean;- maxGuestTopics?: number;+ /** Maximum number of topics each signed-in visitor can create for this share. */+ maxTopicsPerVisitor?: number;+ /** Maximum number of message turns allowed in each shared topic. */+ maxTurnsPerTopic?: number;+ /**+ * Creator's monthly spend cap for this shared agent, in USD credits.+ *+ * Mandatory: `normalizeAgentShareConfig` fills a default for any row that+ * lacks one, so every read path through `AgentShareModel` sees a number —+ * see {@link NormalizedAgentShareConfig}. The creator can move the number+ * but can never clear it. A cap of `0` is a real lower bound meaning "stop+ * all visitor runs", never "unlimited".+ *+ * Billing enforcement for this cap lives in the Cloud repo (business slot);+ * the OSS schema only carries the configured value.+ */+ monthlySpendLimit?: number;+ /**+ * Whether visitors may see raw run error details (message/stack) instead of+ * a generic failure notice. Defaults to `false`.+ */+ showErrorDetails?: boolean;+ /**+ * Whether visitors may see which model/provider is powering the agent.+ * Defaults to `false` — the creator's model choice is hidden by default.+ */+ showModelInfo?: boolean;+ /**+ * Custom URL slug for this share's public link (e.g. `/agent/my-cool-bot`).+ * Uniqueness is enforced at the APPLICATION level+ * (`AgentShareModel.updateSlug`), not by a DB constraint/index — acceptable+ * at the current low slug-write volume. Add a unique index if writes ever+ * grow contentious.+ */+ slug?: string;+ /**+ * Tools visitors may invoke. A tool absent from the list is not granted, so+ * an empty/undefined list grants nothing. An entry without `apis` grants+ * every API of that tool; an entry with `apis` grants only those.+ */+ toolGrants?: AgentShareToolGrant[];// tipSplitRatio is platform-controlled, not configurable by the creator}+/**+ * `AgentShareConfig` as returned by `normalizeAgentShareConfig`: the spend cap+ * is guaranteed present, so enforcement paths never have to re-derive a+ * default (and can never mistake a missing cap for "unlimited").+ */+export type NormalizedAgentShareConfig = AgentShareConfig & { monthlySpendLimit: number };++/**+ * Client-owned config fields accepted by atomic server-side patch updates.+ *+ * `slug` is excluded — it has a dedicated validated write path+ * (`AgentShareModel.updateSlug`) and must never ride in on a generic patch.+ */+export type AgentShareConfigPatch = Omit<Partial<AgentShareConfig>, 'slug'>;+export const agentShares = pgTable('agent_shares',{@@ -28,7 +88,13 @@ export const agentShares = pgTable(shareConfig: jsonb('share_config').$type<AgentShareConfig>(),- /** Unique visitor count — incremented by the application layer on each new visitor session. */+ /**+ * Raw page-view count: incremented by `AgentShareModel.incrementUserViewCount`+ * on every non-owner page load of the shared agent page, NOT deduplicated+ * by visitor — a visitor who reloads or revisits bumps this every time.+ * For a distinct-visitor count, see `TopicModel.countShareVisitors`+ * (counts distinct `topics.senderId`), exposed as `visitorCount`.+ */userViewCount: integer('user_view_count').default(0).notNull(),...timestamps,diff --git a/packages/database/src/utils/shareVisitor.ts b/packages/database/src/utils/shareVisitor.tsnew file mode 100644index 00000000000..66950fa26d4--- /dev/null+++ b/packages/database/src/utils/shareVisitor.ts@@ -0,0 +1,39 @@+import { type AnyColumn, isNull, sql } from 'drizzle-orm';++import { messages, topics } from '../schemas';++/**+ * Agent-share visitor topics carry the creator's `userId` (billing/data+ * attribution) plus a non-null `senderId` (the visitor), so plain ownership+ * predicates surface them inside the creator's own workspace. Every+ * creator-facing listing/aggregation over `topics` must AND this in —+ * lists, unread badges, stats, memory extraction, digests. Share-scoped+ * access goes through the dedicated `*BySender` methods instead; visitor+ * usage is reported separately by the Cloud share usage center.+ */+export const notShareVisitorTopic = () => isNull(topics.senderId);++/**+ * Twin of {@link notShareVisitorTopic} for `messages`-table aggregates.+ * Messages carry no `senderId` — visitor authorship is only identifiable+ * through the parent topic, so this correlates a NOT EXISTS against `topics`+ * to keep callers join-free. Messages without a topic are trivially kept.+ */+export const notShareVisitorMessage = () => notShareVisitorTopicRef(messages.topicId);++/**+ * Generic form of {@link notShareVisitorMessage} for any table that references+ * a topic by id (messages, agent operations, …). Correlates a NOT EXISTS+ * against `topics` so the caller needs no join; rows with a NULL topic+ * reference are trivially kept.+ */+export function notShareVisitorTopicRef(topicIdColumn: AnyColumn) {+ // Drizzle's relational query builder (`db.query.<table>.findFirst/findMany`)+ // aliases the queried table to a fixed name and then rewrites references+ // inside `sql`` templates to that alias — so `${topics.id}` was rendering as+ // `"messages"."id"` inside `.findFirst({ where: ... })`, which crashed the+ // moment `ownership()` started ANDing this predicate by default. Hard-code+ // the correlated table alias with `sql.raw` so the inner reference is+ // immune to the outer alias rewriting.+ return sql`NOT EXISTS (SELECT 1 FROM ${topics} WHERE ${sql.raw('"topics"."id"')} = ${topicIdColumn} AND ${sql.raw('"topics"."sender_id"')} IS NOT NULL)`;+}diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex fca12f2b377..acfaa005fb8 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -371,6 +371,125 @@ export default {'channel.statusQueued': 'Queued','channel.statusStarting': 'Starting',+ 'share.entry': 'Share this Agent',+ 'share.settings.limits.desc':+ 'Every visitor run is billed to your account, so these caps are what keep a shared link from running up your bill. They always apply — you can change the numbers, but not turn them off.',+ 'share.settings.limits.maxTopicsPerVisitor': 'Conversations per visitor',+ 'share.settings.limits.maxTopicsPerVisitorHint':+ 'How many separate conversations each signed-in visitor can start.',+ 'share.settings.limits.maxTurnsPerTopic': 'Turns per conversation',+ 'share.settings.limits.maxTurnsPerTopicHint':+ 'How many messages a visitor can send inside one conversation.',+ 'share.settings.limits.monthlySpendLimit': 'Monthly spend cap',+ 'share.settings.limits.monthlySpendLimitHint':+ 'Visitor runs stop once this month’s spend on this Agent reaches the cap.',+ 'share.settings.limits.title': 'Limits',+ 'share.settings.link.copied': 'Link copied',+ 'share.settings.link.copy': 'Copy link',+ 'share.settings.link.desc':+ 'Anyone signed in who has the link can chat with this Agent. Runs execute on your account.',+ 'share.settings.link.disableConfirmContent':+ 'Visitors lose access to the link right away. The link itself is kept, so turning sharing back on later republishes the exact same URL.',+ 'share.settings.link.disableConfirmOk': 'Turn off sharing',+ 'share.settings.link.disableConfirmTitle': 'Turn off sharing?',+ 'share.settings.link.offHint':+ 'Sharing is off. Turn it on to get a link you can hand out — turning it off again only pauses it, and the same link resumes whenever you turn it back on.',+ 'share.settings.link.publishDisabled':+ 'Sharing is not available on your account yet. You can still turn off a share you already published.',+ 'share.settings.link.slugError.invalid':+ 'Use lowercase letters, numbers and hyphens only, and don’t start or end with a hyphen.',+ 'share.settings.link.slugError.reserved': 'This word is reserved. Please pick another one.',+ 'share.settings.link.slugError.taken': 'This custom link is already taken.',+ 'share.settings.link.slugError.tooLong': 'Custom links can be at most 64 characters.',+ 'share.settings.link.slugError.tooShort': 'Custom links need at least 3 characters.',+ 'share.settings.link.slugHint':+ '3–64 characters: lowercase letters, numbers and hyphens. Leave it empty to use the generated link.',+ 'share.settings.link.slugLabel': 'Custom link',+ 'share.settings.link.slugPlaceholder': 'my-agent',+ 'share.settings.link.slugSaved': 'Custom link updated',+ 'share.settings.link.title': 'Share link',+ 'share.settings.link.viewCount': '{{views}} views',+ 'share.settings.notice.desc':+ 'Visitors don’t just read this Agent — they run it. Every reply is generated on your account and charged to your balance, and the Agent acts with whatever access you grant below.',+ 'share.settings.notice.title': 'Visitors run this Agent on your account',+ 'share.settings.permissions.allowCreatorViewSessions': 'Let me read visitor conversations',+ 'share.settings.permissions.allowCreatorViewSessionsHint':+ 'Off by default: visitor conversations stay private to the visitor.',+ 'share.settings.permissions.allowReadMemory': 'Allow reading my memory',+ 'share.settings.permissions.allowReadMemoryHint':+ 'The Agent may draw on your long-term memory while answering a visitor.',+ 'share.settings.permissions.desc':+ 'What a visitor’s run may read, and what the visitor gets to see back.',+ 'share.settings.permissions.showErrorDetails': 'Show error details to visitors',+ 'share.settings.permissions.showErrorDetailsHint':+ 'Off by default: visitors see a generic failure notice instead of raw error text.',+ 'share.settings.permissions.showModelInfo': 'Show which model is used',+ 'share.settings.permissions.showModelInfoHint':+ 'Off by default: your model and provider choice stays hidden.',+ 'share.settings.permissions.title': 'Permissions',+ 'share.settings.title': 'Share Agent',+ 'share.settings.usage.conversations': 'Conversations',+ 'share.settings.usage.desc': 'What this share has attracted, and what it has cost you.',+ 'share.settings.usage.loadFailed': 'Usage could not be loaded',+ 'share.settings.usage.monthlySpend': 'This month’s spend',+ 'share.settings.usage.spendOfLimit': '${{spend}} of ${{limit}}',+ 'share.settings.usage.title': 'Usage',+ 'share.settings.usage.views': 'Visits',+ 'share.settings.usage.visitors': 'Visitors',+ 'share.settings.tools.desc':+ 'Only the tools you tick here can be called during a visitor run. Tools that could reach your device or local files are never offered.',+ 'share.settings.tools.apiNotAvailableToVisitors':+ 'This action can never be used in a shared run — it either needs your approval or is otherwise off-limits to visitors.',+ 'share.settings.tools.apiWritesOwnerData':+ 'Visitors can never write to your memory — this action stays off in shared runs.',+ 'share.settings.tools.availableGroup': 'Not granted · {{count}}',+ 'share.settings.tools.empty': 'This Agent has no tools that can be granted to visitors.',+ 'share.settings.tools.grantedEmpty':+ 'No tools granted yet — visitors get a plain chat. Pick from the list below to grant one.',+ 'share.settings.tools.grantedGroup': 'Granted to visitors · {{count}}',+ 'share.settings.tools.needsMemoryPermission':+ 'Also turn on “Allow reading my memory” above, or this tool stays inert for visitors.',+ 'share.settings.tools.notAvailableToVisitors':+ 'This tool can never be used in a shared run — visitor runs are blocked from your knowledge base and Agent files.',+ 'share.settings.tools.title': 'Tools visitors can use',+ 'share.settings.updateError': 'Could not save the change. Please try again.',+ 'share.visitor.access.backHome': 'Back to home',+ 'share.visitor.access.forbidden': "You don't have access to this shared agent.",+ 'share.visitor.access.notFound': 'This share link is no longer available.',+ 'share.visitor.access.signInCta': 'Sign in',+ 'share.visitor.access.signInDesc':+ 'Sign in to start chatting with this shared agent. Your conversations stay tied to your account.',+ 'share.visitor.access.signInTitle': 'Sign in to continue',+ 'share.visitor.errors.generic': 'Failed to send the message. Please try again.',+ 'share.visitor.errors.heterogeneousUnsupported':+ "This shared agent isn't available for visitor chat yet. Please contact its owner.",+ 'share.visitor.errors.insufficientBudget':+ 'This shared agent has run out of budget. Please contact its owner.',+ 'share.visitor.errors.promptTooLong':+ 'Your message is too long. Please shorten it to {{max}} characters or fewer and try again.',+ 'share.visitor.errors.providerNotSupported':+ 'This shared agent is not available right now. Please contact its owner.',+ 'share.visitor.errors.sharingPaused':+ 'The owner has paused sharing, so new messages are turned off.',+ 'share.visitor.errors.spendLimit':+ 'This shared agent has reached its monthly usage limit set by its creator. It will be available again next month.',+ 'share.visitor.errors.stopFailed': "Couldn't stop the run. Please try again.",+ 'share.visitor.errors.topicLimit':+ 'You have reached the conversation limit on this shared agent.',+ 'share.visitor.errors.turnLimit':+ 'This conversation has reached its turn limit. Start a new conversation to continue.',+ 'share.visitor.errors.unavailable':+ 'This conversation is no longer available. Try switching to another topic or starting a new one.',+ 'share.visitor.input.placeholder': 'Message this shared agent…',+ 'share.visitor.input.send': 'Send',+ 'share.visitor.input.stop': 'Stop',+ 'share.visitor.privacyNotice':+ 'This conversation runs on the owner’s account and may be visible to them. Avoid sharing sensitive information.',+ 'share.visitor.topics.empty': 'No conversations yet',+ 'share.visitor.topics.new': 'New conversation',+ 'share.visitor.topics.title': 'Conversations',+ 'share.visitor.topics.untitled': 'Untitled conversation',+'transfer.title': 'Move','transfer.copyTo': 'Copy to…','transfer.desc': 'Move this Agent to another Workspace or your personal account.',diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.tsindex d59dbb3bfd2..6a36bfbf71e 100644--- a/packages/locales/src/default/electron.ts+++ b/packages/locales/src/default/electron.ts@@ -1,4 +1,5 @@export default {+ 'navigation.agentShare': 'Share','navigation.agents': 'Agents','navigation.channels': 'Channels','navigation.chat': 'Chat',@@ -43,6 +44,7 @@ export default {'navigation.resourceVideos': 'Videos','navigation.settings': 'Settings','navigation.selfLearning': 'Self-evolving',+ 'navigation.sharedAgent': 'Shared Agent','navigation.stats': 'Statistics','navigation.task': 'Task','navigation.tasks': 'Tasks',diff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.tsindex 8513245659b..f53098c8dc0 100644--- a/packages/locales/src/default/error.ts+++ b/packages/locales/src/default/error.ts@@ -245,6 +245,7 @@ export default {'A previous copy of this agent is still duplicating its history. Try again once it finishes.','transfer.transferInProgress':'A previous move of this resource is still migrating its history. Try again once it finishes.',+ 'transfer.sharedTransferBlocked': 'This agent has a share link, so its owner cannot be changed.','transfer.sameWorkspace':'This resource is already in the selected workspace. Choose another target.','transfer.targetIsCurrentOwner': 'This agent already belongs to that member. Pick someone else.',diff --git a/packages/locales/src/default/spend.ts b/packages/locales/src/default/spend.tsindex 3c27e257e5e..141d6a3c455 100644--- a/packages/locales/src/default/spend.ts+++ b/packages/locales/src/default/spend.ts@@ -12,6 +12,7 @@ export default {'table.columns.spend': 'Credits','table.columns.time': 'Time','table.columns.totalTokens': 'Token Usage',+ 'table.columns.trigger.enums.agent_share': 'Agent Share','table.columns.trigger.enums.agent_signal': 'Agent Signal','table.columns.trigger.enums.api': 'API Call','table.columns.trigger.enums.bot': 'Bot Message',diff --git a/packages/trpc/src/lambda/context.ts b/packages/trpc/src/lambda/context.tsindex 4614c03e8b2..375054d6715 100644--- a/packages/trpc/src/lambda/context.ts+++ b/packages/trpc/src/lambda/context.ts@@ -1,5 +1,5 @@import { type Context as OtContext } from '@lobechat/observability-otel/api';-import { type ClientSecretPayload } from '@lobechat/types';+import { type ClientSecretPayload, type SpendOrigin } from '@lobechat/types';import type { ClientMetadata } from '@lobechat/utils/server';import { parseClientMetadata } from '@lobechat/utils/server';import { parse } from 'cookie';@@ -99,6 +99,17 @@ export interface AuthContext {oidcAuth?: OIDCAuth | null;oidcClientId?: string;resHeaders?: Headers;+ /**+ * Origin attribution for spend produced by this call, forwarded to the+ * billing points the procedure reaches.+ *+ * SECURITY: never derived from request headers or any other client input —+ * it decides who a charge is billed against, so a client could otherwise+ * forge another user's attribution. Populated ONLY by a server-side+ * `createCaller` (see the tool-execution server runtimes), where the values+ * come from the already-authorized run context.+ */+ spendOrigin?: SpendOrigin;traceContext?: OtContext;userAgent?: string;userId?: string | null;@@ -116,6 +127,8 @@ export const createContextInner = async (params?: {marketAccessToken?: string;oidcAuth?: OIDCAuth | null;oidcClientId?: string;+ /** See {@link AuthContext.spendOrigin} — server-side callers only. */+ spendOrigin?: SpendOrigin;traceContext?: OtContext;userAgent?: string;userId?: string | null;@@ -132,6 +145,7 @@ export const createContextInner = async (params?: {oidcAuth: params?.oidcAuth,oidcClientId: params?.oidcClientId,resHeaders: responseHeaders,+ spendOrigin: params?.spendOrigin,traceContext: params?.traceContext,userAgent: params?.userAgent,userId: params?.userId,diff --git a/packages/types/src/agent/index.ts b/packages/types/src/agent/index.tsindex dc51f28ebb1..927ca3c59f2 100644--- a/packages/types/src/agent/index.ts+++ b/packages/types/src/agent/index.ts@@ -14,4 +14,5 @@ export * from './modelSelection';export * from './pluginConfig';export * from './profile';export * from './runtimeAdditionalContext';+export * from './share';export * from './tts';diff --git a/packages/types/src/agent/share.ts b/packages/types/src/agent/share.tsnew file mode 100644index 00000000000..100c213d229--- /dev/null+++ b/packages/types/src/agent/share.ts@@ -0,0 +1,41 @@+import type { ShareVisibility } from '../topic';++/** Agent metadata exposed to signed-in visitors of an agent share. */+export interface SharedAgentData {+ agentId: string;+ agentMeta: {+ avatar: string | null;+ backgroundColor: string | null;+ description: string | null;+ name: string | null;+ title: string | null;+ };+ /**+ * True when the requesting user (`ctx.userId`) is the creator of the+ * shared agent — lets the client render owner-only affordances (e.g. an+ * "edit share" link) instead of the plain visitor UI.+ */+ isOwner: boolean;+ shareId: string;+ /** The share's custom URL slug, if the creator has set one. `null` otherwise. */+ slug: string | null;+ visibility: ShareVisibility;+}++/**+ * One tool the creator granted to share visitors.+ *+ * Lives in `@lobechat/types` (rather than next to the other agent-share+ * helpers in `@lobechat/const`) because both `@lobechat/const` and+ * `@lobechat/types`' own `AgentShareVisitorContext` need it, and `const`+ * already depends on `types` — the reverse direction would be a cycle.+ */+export interface AgentShareToolGrant {+ /**+ * Granted API names. Omitted = every API the tool offers (still subject to+ * the runtime visitor gates). Never an empty array — a tool with no granted+ * API is simply absent from the list.+ */+ apis?: string[];+ identifier: string;+}diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.tsindex 73c6335b5db..1c30cd69a2c 100644--- a/packages/types/src/agentRuntime.ts+++ b/packages/types/src/agentRuntime.ts@@ -1,3 +1,5 @@+import type { AgentShareToolGrant } from './agent/share';+/** Request-scoped pricing inputs resolved before model execution. */export interface ModelPricingContext {plan: string;@@ -11,6 +13,7 @@ export interface RouterRuntimeRequestContext {}export enum RequestTrigger {+ AgentShare = 'agent_share',AgentSignal = 'agent_signal',Api = 'api',Bot = 'bot',@@ -33,6 +36,104 @@ export enum RequestTrigger {Video = 'video',}+/**+ * Everything one shared-agent visitor run carries: WHO the run belongs to+ * (`agentId` / `shareId` / `visitorUserId`), WHAT the visitor is allowed to+ * reach (`allowReadMemory` / `toolGrants` / `knowledgeBaseIds`), and HOW+ * much of the run is shown back to them (`showErrorDetails` / `showModelInfo`).+ *+ * Single source of truth for the runtime-side share marker: it is stamped once+ * at operation creation onto `state.metadata.agentShareVisitor` and read back+ * by every later step, so no step has to re-read the share row.+ *+ * SECURITY: never derived from request headers or any other client input — its+ * fields decide both permission and billing, so a client could otherwise forge+ * another user's run. It is always built server-side from the already-resolved+ * share gate.+ *+ * Never hand this object to a billing point as a whole — the permission fields+ * have no place in spend metadata. Project it with+ * {@link toAgentShareVisitorIds} instead.+ */+export interface AgentShareVisitorContext {+ /** The shared agent (`agents.id`) this run executes. */+ agentId: string;+ /**+ * Mirrors `shareConfig.allowReadMemory` so the memory tool's dispatch-time+ * gate (`isShareBlockedDataToolCall`) can be re-applied at+ * `BuiltinToolsExecutor.execute`, the actual unbypassable chokepoint.+ */+ allowReadMemory?: boolean;+ /**+ * The agent's OWN persisted knowledge-base assignment, never derived from+ * visitor input, so `isShareBlockedDataToolCall` can id-scope+ * `viewKnowledgeBase`'s `id` argument. Always empty today (a share grants no+ * knowledge-base access).+ */+ knowledgeBaseIds?: string[];+ /**+ * The `agentShares.id` this run was authorized against — the revocation+ * token re-checked at every step boundary (see+ * `AgentShareModel.isRunStillAuthorized`).+ */+ shareId: string;+ /** `AgentShareConfig.showErrorDetails` — gates visitor-facing error redaction. */+ showErrorDetails?: boolean;+ /** `AgentShareConfig.showModelInfo` — gates visitor-facing model/provider/usage redaction. */+ showModelInfo?: boolean;+ /**+ * Mirrors `shareConfig.toolGrants` so tool runtimes that resolve their+ * target outside `toolManifestMap` (e.g. `activateSkill`,+ * `lobe-topic-reference`) can apply the same allowlist the assembled tool set+ * already enforces.+ */+ toolGrants?: AgentShareToolGrant[];+ /** The visitor's user id, under which the run's spend is attributed. */+ visitorUserId: string;+}++/**+ * The billing-safe projection of {@link AgentShareVisitorContext}: only the ids+ * needed to attribute a charge, with every permission / redaction field+ * dropped. This is the ONLY shape allowed to reach spend metadata.+ */+export type AgentShareVisitorIds = Pick<+ AgentShareVisitorContext,+ 'agentId' | 'shareId' | 'visitorUserId'+>;++/**+ * Project a runtime share marker down to its billing-safe ids. The single+ * allowed way to move an {@link AgentShareVisitorContext} into a+ * {@link SpendOrigin} — never spread the context itself, which also carries+ * permissions that have no place in billing metadata.+ */+export const toAgentShareVisitorIds = (ctx: AgentShareVisitorContext): AgentShareVisitorIds => ({+ agentId: ctx.agentId,+ shareId: ctx.shareId,+ visitorUserId: ctx.visitorUserId,+});++/**+ * Origin attribution carried alongside a request so a billing point that runs+ * outside the originating request (async task, webhook, settle-time charge) can+ * stamp the same origin the synchronous LLM path stamps.+ *+ * Always a plain projection: only the ids needed for attribution travel here,+ * never the originating runtime object, which also carries permissions that+ * have no place in billing metadata.+ */+export interface SpendOrigin {+ /**+ * Present only for a shared-agent visitor run. The JSON key `agentShare` is+ * persisted into spend-log / budget-reservation metadata and queried by+ * `SpendLogModel` — do NOT rename it.+ */+ agentShare?: AgentShareVisitorIds;+ /** Request source, see {@link RequestTrigger}. */+ trigger?: string;+}+// ******* Runtime Biz Error ******* //export const AgentRuntimeErrorType = {AgentRuntimeError: 'AgentRuntimeError', // Agent Runtime module runtime errordiff --git a/packages/types/src/asyncTask.ts b/packages/types/src/asyncTask.tsindex e2ae4ed8d60..c9362c26451 100644--- a/packages/types/src/asyncTask.ts+++ b/packages/types/src/asyncTask.ts@@ -1,3 +1,5 @@+import type { SpendOrigin } from './agentRuntime';+export enum AsyncTaskType {Chunking = 'chunk',Embedding = 'embedding',@@ -199,5 +201,14 @@ export interface HourlyUserMemoryExtractionMetadata {export interface VideoGenerationTaskMetadata {precharge?: Record<string, unknown>;+ /**+ * Origin of the submitting request, carried across the async boundary so the+ * completion charge (webhook / polling) can keep the spend attributed.+ *+ * Persisted on the async task row under this exact key. It was named+ * `spendAttribution` before Agent Share v2; no double-read is needed because+ * the feature had not shipped, so no stored row carries the old key.+ */+ spendOrigin?: SpendOrigin;webhookToken?: string;}diff --git a/packages/types/src/conversation.ts b/packages/types/src/conversation.tsindex 23576efec5c..5a20abb9dde 100644--- a/packages/types/src/conversation.ts+++ b/packages/types/src/conversation.ts@@ -128,6 +128,14 @@ export interface ConversationContext {*/agentDocumentId?: string;agentId: string;+ /**+ * Agent share id for the visitor view of a shared agent+ * (`/agent/:slugOrId`). When present the conversation is mounted for a+ * non-owner visitor: every owner-scoped read/write (agent-config fetch,+ * message persistence, topic settle, agent-signal emission) must be skipped+ * or routed through the share-authorized `shareChat` procedures instead.+ */+ agentShareId?: string;/*** Optional default assignee candidate for task manager conversations.* This is a prompt hint only; task tools still require an explicit assigneeAgentId.diff --git a/packages/types/src/fetch.ts b/packages/types/src/fetch.tsindex f1786798b6c..15013e0ca6d 100644--- a/packages/types/src/fetch.ts+++ b/packages/types/src/fetch.ts@@ -10,6 +10,11 @@ export const ChatErrorType = {WorkspaceFrozenByAdmin: 'WorkspaceFrozenByAdmin', // Workspace manually frozen by admin (reason is operator-written, safe to surface)WorkspaceFrozenByRiskControl: 'WorkspaceFrozenByRiskControl', // Workspace auto-frozen by risk control (reason is engineer debug text, hide from user)WorkspaceSubscriptionInactive: 'WorkspaceSubscriptionInactive', // Workspace's paid subscription has lapsed — view-only for non-primary members; spend blocked until renewed+ ShareTurnLimitExceeded: 'ShareTurnLimitExceeded', // Shared-agent topic hit shareConfig.maxTurnsPerTopic — visitor can start a new topic+ ShareTopicLimitExceeded: 'ShareTopicLimitExceeded', // Visitor hit shareConfig.maxTopicsPerVisitor on this shared agent+ ShareSpendLimitExceeded: 'ShareSpendLimitExceeded', // Shared agent reached shareConfig.monthlySpendLimit for the current month — recovers on the next reset+ ShareHeterogeneousAgentUnsupported: 'ShareHeterogeneousAgentUnsupported', // This agent configuration is not supported for shared visitors+ AgentShareProviderNotSupported: 'AgentShareProviderNotSupported', // This shared agent uses a provider that is not supported for shared visitorsSupervisorDecisionFailed: 'SupervisorDecisionFailed', // Supervisor decision failedInvalidUserKey: 'InvalidUserKey', // is not valid User keydiff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.tsindex 8cdec86ef82..f09cd58b712 100644--- a/packages/types/src/serverConfig.ts+++ b/packages/types/src/serverConfig.ts@@ -20,6 +20,11 @@ import type {export type IFeatureFlagsState = {enableAgentOnboarding: boolean | undefined;enableAgentSelfIteration: boolean | undefined;+ /**+ * Agent Share capability: may this user publish an Agent as a shared link AND+ * open/chat on an already-live shared agent. One allowlist gates both sides.+ */+ enableAgentShare: boolean | undefined;enableAuthCaptcha: boolean | undefined;enableCheckUpdates: boolean | undefined;enableDevDock: boolean | undefined;diff --git a/src/app/(backend)/api/agent/stream/__tests__/route.test.ts b/src/app/(backend)/api/agent/stream/__tests__/route.test.tsindex dfcae0c1884..03be7fd0e46 100644--- a/src/app/(backend)/api/agent/stream/__tests__/route.test.ts+++ b/src/app/(backend)/api/agent/stream/__tests__/route.test.ts@@ -10,10 +10,23 @@ const mockStreamEventManager = {subscribeStreamEvents: vi.fn(),};+const mockAgentStateManager = {+ getOperationMetadata: vi.fn(),+};++const mockCreateLambdaContext = vi.fn();+vi.mock('@/server/modules/AgentRuntime', () => ({+ createAgentStateManager: vi.fn(() => mockAgentStateManager),createStreamEventManager: vi.fn(() => mockStreamEventManager),}));+vi.mock('@/libs/trpc/lambda/context', () => ({+ createLambdaContext: (...args: unknown[]) => mockCreateLambdaContext(...args),+}));++const OWNER_USER_ID = 'test-user';+describe('/api/agent/stream route', () => {const MOCK_TIMESTAMP = 1758203237000;@@ -21,6 +34,11 @@ describe('/api/agent/stream route', () => {vi.resetAllMocks();// Mock Date.now to return consistent timestampvi.spyOn(Date, 'now').mockReturnValue(MOCK_TIMESTAMP);++ // Default: authenticated as the operation owner, non-share operation.+ // Individual tests override these to exercise the 401/404 paths.+ mockCreateLambdaContext.mockResolvedValue({ userId: OWNER_USER_ID });+ mockAgentStateManager.getOperationMetadata.mockResolvedValue({ userId: OWNER_USER_ID });});afterEach(() => {@@ -56,6 +74,98 @@ describe('/api/agent/stream route', () => {});});+ describe('Authorization', () => {+ it('should return 401 when the caller is not authenticated', async () => {+ mockCreateLambdaContext.mockResolvedValue({ userId: null });++ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );+ const response = await GET(request);++ expect(response.status).toBe(401);+ const data = await response.json();+ expect(data.error).toBe('unauthorized');+ expect(mockAgentStateManager.getOperationMetadata).not.toHaveBeenCalled();+ expect(mockStreamEventManager.getStreamHistory).not.toHaveBeenCalled();+ });++ it('should return 404 when the operation does not exist', async () => {+ mockAgentStateManager.getOperationMetadata.mockResolvedValue(null);++ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=unknown-operation',+ );+ const response = await GET(request);++ expect(response.status).toBe(404);+ const data = await response.json();+ expect(data.error).toBe('operation_not_found');+ expect(mockStreamEventManager.getStreamHistory).not.toHaveBeenCalled();+ });++ it('should return 404 when the operation belongs to another user', async () => {+ mockCreateLambdaContext.mockResolvedValue({ userId: 'other-user' });+ mockAgentStateManager.getOperationMetadata.mockResolvedValue({ userId: OWNER_USER_ID });++ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );+ const response = await GET(request);++ expect(response.status).toBe(404);+ const data = await response.json();+ expect(data.error).toBe('operation_not_found');+ expect(mockStreamEventManager.getStreamHistory).not.toHaveBeenCalled();+ });++ it('should return 404 for a share-visitor operation even when the caller is the visitor', async () => {+ mockCreateLambdaContext.mockResolvedValue({ userId: 'visitor-user' });+ mockAgentStateManager.getOperationMetadata.mockResolvedValue({+ streamOwnerUserId: 'visitor-user',+ userId: OWNER_USER_ID,+ });++ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=share-visitor-operation',+ );+ const response = await GET(request);++ expect(response.status).toBe(404);+ const data = await response.json();+ expect(data.error).toBe('operation_not_found');+ expect(mockStreamEventManager.getStreamHistory).not.toHaveBeenCalled();+ });++ it('should return 404 for a share-visitor operation even when the caller is the creator', async () => {+ mockCreateLambdaContext.mockResolvedValue({ userId: OWNER_USER_ID });+ mockAgentStateManager.getOperationMetadata.mockResolvedValue({+ streamOwnerUserId: 'visitor-user',+ userId: OWNER_USER_ID,+ });++ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=share-visitor-operation',+ );+ const response = await GET(request);++ expect(response.status).toBe(404);+ const data = await response.json();+ expect(data.error).toBe('operation_not_found');+ expect(mockStreamEventManager.getStreamHistory).not.toHaveBeenCalled();+ });++ it('should allow the owner to read their own operation', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );+ const response = await GET(request);++ expect(response.status).toBe(200);+ expect(mockAgentStateManager.getOperationMetadata).toHaveBeenCalledWith('test-operation');+ });+ });+describe('Stream functionality with exact data verification', () => {it('should send connection event in exact SSE format', async () => {const request = new NextRequest(diff --git a/src/app/(backend)/api/agent/stream/route.ts b/src/app/(backend)/api/agent/stream/route.tsindex 403d1687161..74c9df005f8 100644--- a/src/app/(backend)/api/agent/stream/route.ts+++ b/src/app/(backend)/api/agent/stream/route.ts@@ -3,7 +3,8 @@ import debug from 'debug';import { type NextRequest } from 'next/server';import { NextResponse } from 'next/server';-import { createStreamEventManager } from '@/server/modules/AgentRuntime';+import { createLambdaContext } from '@/libs/trpc/lambda/context';+import { createAgentStateManager, createStreamEventManager } from '@/server/modules/AgentRuntime';const log = debug('api-route:agent:stream');const timing = debug('lobe-server:agent-runtime:timing');@@ -30,6 +31,40 @@ export async function GET(request: NextRequest) {);}+ // Resolve the caller the same way the lambda tRPC context does (Better Auth+ // session cookie, `Oidc-Auth` JWT, or `X-API-Key`) so the CLI's existing+ // `getAgentStreamAuthInfo` headers keep working unchanged.+ const { userId: callerUserId } = await createLambdaContext(request);++ if (!callerUserId) {+ return NextResponse.json({ error: 'unauthorized' }, { status: 401 });+ }++ const agentStateManager = createAgentStateManager();+ const metadata = await agentStateManager.getOperationMetadata(operationId);++ if (!metadata) {+ return NextResponse.json({ error: 'operation_not_found' }, { status: 404 });+ }++ // A share-visitor run (`AgentOperationMetadata.streamOwnerUserId` set — see its+ // JSDoc in `AgentStateManager.ts`) executes as the creator but must only ever+ // be read back through the Gateway WS channel, which applies the owner-configured+ // visitor redaction (`gatewayVisitorRedaction.ts`). This raw endpoint replays+ // unredacted history with no projection, and the creator must never read a+ // visitor's transcript (visitor-isolation invariant) — so reject with 404 for+ // EVERY caller, including both the visitor and the creator.+ if (metadata.streamOwnerUserId) {+ return NextResponse.json({ error: 'operation_not_found' }, { status: 404 });+ }++ // Otherwise this is a normal (non-share) operation: only its owner may read it.+ // 404 rather than 403 so an unauthorized caller cannot distinguish "not mine"+ // from "does not exist".+ if (metadata.userId !== callerUserId) {+ return NextResponse.json({ error: 'operation_not_found' }, { status: 404 });+ }+log(`Starting SSE connection for operation ${operationId} from eventId ${lastEventId}`);// Create Server-Sent Events streamdiff --git a/src/app/robots.tsx b/src/app/robots.tsxindex c4b8f4c398d..5d386d8b03f 100644--- a/src/app/robots.tsx+++ b/src/app/robots.tsx@@ -24,7 +24,9 @@ const robots = (): MetadataRoute.Robots => {},{allow: ['/'],- disallow: ['/api/*', '/signin', '/signup', '/knowledge/*', '/share/*'],+ // `/agent/*` also hosts Agent Share visitor pages (`/agent/:slugOrId`):+ // link-visible, creator-owned content that must never be indexed.+ disallow: ['/api/*', '/signin', '/signup', '/knowledge/*', '/share/*', '/agent/*'],userAgent: '*',},],diff --git a/src/components/Skeleton/AgentShare.tsx b/src/components/Skeleton/AgentShare.tsxnew file mode 100644index 00000000000..0754d8f707a--- /dev/null+++ b/src/components/Skeleton/AgentShare.tsx@@ -0,0 +1,135 @@+'use client';++import { Block, Flexbox } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import type { ReactNode } from 'react';++import WideScreenContainer from '@/features/WideScreenContainer';+import type { RouteSkeletonProps } from '@/spa/router/routeMeta';++import SkeletonBar from './Bar';++const styles = createStaticStyles(({ css }) => ({+ header: css`+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+ notice: css`+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorFillQuaternary};+ `,+}));++/** Breadcrumb on the left, the profile tab switcher centred — same as `NavHeader` on the page. */+const NavigationSkeleton = () => (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.header}+ flex={'none'}+ height={44}+ paddingInline={16}+ style={{ position: 'relative' }}+ >+ <Flexbox horizontal align={'center'} gap={8}>+ <SkeletonBar height={20} radius={'50%'} width={20} />+ <SkeletonBar height={14} width={120} />+ </Flexbox>+ {/* Mirrors `AGENT_PROFILE_TABS_CENTER_STYLE`: centred on the header midpoint. */}+ <Flexbox style={{ left: '50%', position: 'absolute', transform: 'translateX(-50%)' }}>+ <SkeletonBar height={28} radius={14} width={280} />+ </Flexbox>+ </Flexbox>+);++const SettingRowSkeleton = ({ control, index }: { control: 'switch' | 'input'; index: number }) => (+ <Flexbox horizontal align={'center'} gap={16} justify={'space-between'}>+ <Flexbox gap={6}>+ <SkeletonBar height={14} width={96 + (index % 3) * 28} />+ <SkeletonBar height={12} width={200 + (index % 2) * 48} />+ </Flexbox>+ {control === 'switch' ? (+ <SkeletonBar height={22} radius={11} width={44} />+ ) : (+ <SkeletonBar height={32} width={120} />+ )}+ </Flexbox>+);++const SectionSkeleton = ({+ children,+ descWidth = 260,+ titleWidth,+}: {+ children: ReactNode;+ descWidth?: number;+ titleWidth: number;+}) => (+ <Block gap={16} padding={20} variant={'outlined'}>+ <Flexbox gap={6}>+ <SkeletonBar height={16} width={titleWidth} />+ <SkeletonBar height={12} width={descWidth} />+ </Flexbox>+ {children}+ </Block>+);++/**+ * Body of the share settings page: the warning notice, then the outlined+ * sections (`Section` in `AgentShareSettings/SectionLayout.tsx`) — link,+ * usage stats, permissions, limits. Reused by the page's own data-loading+ * state so the layout does not jump between route load and share fetch.+ */+export const AgentShareSettingsBodySkeleton = () => (+ <Flexbox aria-busy gap={16} paddingBlock={16}>+ <Flexbox+ horizontal+ align={'flex-start'}+ className={styles.notice}+ gap={12}+ padding={'12px 16px'}+ >+ <SkeletonBar height={18} radius={'50%'} width={18} />+ <Flexbox flex={1} gap={8}>+ <SkeletonBar height={14} width={160} />+ <SkeletonBar height={12} width={'82%'} />+ </Flexbox>+ </Flexbox>+ <SectionSkeleton titleWidth={88}>+ <SettingRowSkeleton control={'switch'} index={0} />+ <SkeletonBar height={36} width={'100%'} />+ </SectionSkeleton>+ <SectionSkeleton descWidth={200} titleWidth={72}>+ <Flexbox horizontal gap={16}>+ {Array.from({ length: 3 }).map((_, index) => (+ <Flexbox flex={1} gap={8} key={index}>+ <SkeletonBar height={12} width={64} />+ <SkeletonBar height={24} width={48 + index * 12} />+ </Flexbox>+ ))}+ </Flexbox>+ </SectionSkeleton>+ <SectionSkeleton titleWidth={104}>+ <SettingRowSkeleton control={'switch'} index={1} />+ <SettingRowSkeleton control={'switch'} index={2} />+ </SectionSkeleton>+ <SectionSkeleton titleWidth={80}>+ <SettingRowSkeleton control={'input'} index={3} />+ <SettingRowSkeleton control={'input'} index={4} />+ </SectionSkeleton>+ </Flexbox>+);++/** Route-level skeleton for `/agent/:aid/share` (see `agentShareRouteMeta`). */+const AgentShareSkeleton = ({ chrome = 'page' }: RouteSkeletonProps) => (+ <Flexbox aria-busy flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}>+ {chrome !== 'body' && <NavigationSkeleton />}+ <Flexbox flex={1} style={{ minHeight: 0, overflow: 'hidden' }}>+ <WideScreenContainer>+ <AgentShareSettingsBodySkeleton />+ </WideScreenContainer>+ </Flexbox>+ </Flexbox>+);++export default AgentShareSkeleton;diff --git a/src/features/AgentHome/ReadOnly.tsx b/src/features/AgentHome/ReadOnly.tsxnew file mode 100644index 00000000000..e433b455b8b--- /dev/null+++ b/src/features/AgentHome/ReadOnly.tsx@@ -0,0 +1,24 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { memo } from 'react';++import AgentInfo from './AgentInfo';++/**+ * Welcome surface for viewers who do not own the agent (e.g. the agent-share+ * visitor page): agent identity only, without the owner-scoped opening+ * questions and tool-authorization alert that `AgentHome` renders.+ */+const ReadOnlyAgentHome = memo(() => (+ <>+ <Flexbox flex={1} />+ <Flexbox gap={32} style={{ paddingBottom: 'max(4vh, 16px)' }} width={'100%'}>+ <AgentInfo />+ </Flexbox>+ </>+));++ReadOnlyAgentHome.displayName = 'ReadOnlyAgentHome';++export default ReadOnlyAgentHome;diff --git a/src/features/AgentProfileTabs/index.tsx b/src/features/AgentProfileTabs/index.tsxindex 4e3bda63541..788dc35484d 100644--- a/src/features/AgentProfileTabs/index.tsx+++ b/src/features/AgentProfileTabs/index.tsx@@ -4,6 +4,7 @@ import { Segmented } from '@lobehub/ui/base-ui';import { type CSSProperties, memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { useAgentShareSupported } from '@/features/AgentShareSettings/useAgentShareSupported';import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';@@ -50,11 +51,11 @@ interface AgentProfileTabsProps {/*** Segmented switcher shared by the agent profile group — Profile / Channels /- * Statistics. The three surfaces are separate routes, so a segment writes the+ * Statistics / Share. The surfaces are separate routes, so a segment writes the* URL rather than holding local state: deep links and back/forward keep working.*/const AgentProfileTabs = memo<AgentProfileTabsProps>(({ active, agentId }) => {- const { t } = useTranslation(['chat', 'spend']);+ const { t } = useTranslation(['chat', 'common', 'spend']);const navigate = useWorkspaceAwareNavigate();const heterogeneousProviderType = useAgentStore(@@ -66,6 +67,7 @@ const AgentProfileTabs = memo<AgentProfileTabsProps>(({ active, agentId }) => {const canConfigure = !!isAgentEditable && isAccessResolved && canEditContent && canEditResource;const channelsSupported = supportsMessageChannels(heterogeneousProviderType);+ const { visible: shareVisible } = useAgentShareSupported(agentId);const options = useMemo(() =>@@ -79,10 +81,12 @@ const AgentProfileTabs = memo<AgentProfileTabsProps>(({ active, agentId }) => {// so the first segment is the "basic" tab, not "Agent Profile" again —// that broader name stays on the sidebar entry that opens the group.profile: t('tab.profileBasic'),+ share: t('share', { ns: 'common' }),statistics: t('usageStats.title', { ns: 'spend' }),},+ shareSupported: shareVisible === true,}),- [active, canConfigure, channelsSupported, t],+ [active, canConfigure, channelsSupported, shareVisible, t],);// A lone segment is a label, not a switcher.diff --git a/src/features/AgentProfileTabs/tabOptions.test.ts b/src/features/AgentProfileTabs/tabOptions.test.tsindex d33d19e852a..5960b843808 100644--- a/src/features/AgentProfileTabs/tabOptions.test.ts+++ b/src/features/AgentProfileTabs/tabOptions.test.ts@@ -9,6 +9,7 @@ import {const labels = {channel: 'tab.integration',profile: 'tab.profile',+ share: 'share',statistics: 'usageStats.title',};@@ -37,9 +38,15 @@ describe('buildAgentProfileTabOptions', () => {canConfigure: true,channelsSupported: true,labels,+ shareSupported: true,});- expect(options.map((option) => option.value)).toEqual(['profile', 'channel', 'statistics']);+ expect(options.map((option) => option.value)).toEqual([+ 'profile',+ 'channel',+ 'statistics',+ 'share',+ ]);});it('drops channels when the agent cannot host them', () => {@@ -48,6 +55,7 @@ describe('buildAgentProfileTabOptions', () => {canConfigure: true,channelsSupported: false,labels,+ shareSupported: false,});expect(options.map((option) => option.value)).toEqual(['profile', 'statistics']);@@ -59,6 +67,7 @@ describe('buildAgentProfileTabOptions', () => {canConfigure: false,channelsSupported: true,labels,+ shareSupported: true,});expect(options.map((option) => option.value)).toEqual(['statistics']);@@ -70,8 +79,33 @@ describe('buildAgentProfileTabOptions', () => {canConfigure: false,channelsSupported: false,labels,+ shareSupported: false,});expect(options.map((option) => option.value)).toEqual(['channel', 'statistics']);});++ it('drops share when the agent cannot be shared at all', () => {+ const options = buildAgentProfileTabOptions({+ active: 'profile',+ canConfigure: true,+ channelsSupported: true,+ labels,+ shareSupported: false,+ });++ expect(options.map((option) => option.value)).toEqual(['profile', 'channel', 'statistics']);+ });++ it('keeps share when it owns the current page even though it is gated off', () => {+ const options = buildAgentProfileTabOptions({+ active: 'share',+ canConfigure: false,+ channelsSupported: false,+ labels,+ shareSupported: false,+ });++ expect(options.map((option) => option.value)).toEqual(['statistics', 'share']);+ });});diff --git a/src/features/AgentProfileTabs/tabOptions.ts b/src/features/AgentProfileTabs/tabOptions.tsindex 3faa2a1bb7b..45b53f075ac 100644--- a/src/features/AgentProfileTabs/tabOptions.ts+++ b/src/features/AgentProfileTabs/tabOptions.ts@@ -1,6 +1,6 @@import urlJoin from 'url-join';-export type AgentProfileTab = 'channel' | 'profile' | 'statistics';+export type AgentProfileTab = 'channel' | 'profile' | 'share' | 'statistics';export interface AgentProfileTabOption {label: string;@@ -37,18 +37,25 @@ export const buildAgentProfileTabOptions = ({canConfigure,channelsSupported,labels,+ shareSupported,}: {active: AgentProfileTab;canConfigure: boolean;channelsSupported: boolean;labels: Record<AgentProfileTab, string>;+ shareSupported: boolean;}): AgentProfileTabOption[] => {const showProfile = canConfigure || active === 'profile';const showChannel = (canConfigure && channelsSupported) || active === 'channel';+ // Sharing hands visitors real execution on the owner's account, so the+ // segment follows the same configure gate as Profile / Channels on top of the+ // capability gate (personal, non-builtin agents on deployments that allow it).+ const showShare = (canConfigure && shareSupported) || active === 'share';return [showProfile ? { label: labels.profile, value: 'profile' as const } : null,showChannel ? { label: labels.channel, value: 'channel' as const } : null,{ label: labels.statistics, value: 'statistics' as const },+ showShare ? { label: labels.share, value: 'share' as const } : null,].filter((option) => !!option);};diff --git a/src/features/AgentRoute/AgentRouteSwitch.tsx b/src/features/AgentRoute/AgentRouteSwitch.tsxnew file mode 100644index 00000000000..db790053a67--- /dev/null+++ b/src/features/AgentRoute/AgentRouteSwitch.tsx@@ -0,0 +1,55 @@+'use client';++import { memo, type ReactElement, type ReactNode } from 'react';+import { Navigate, useParams } from 'react-router';++import { resolveAgentRouteBranch, useAgentRouteResolution } from './useAgentRouteResolution';++interface AgentRouteSwitchProps {+ /** Shown while a slug is still being resolved, to avoid a not-found flash. */+ fallback?: ReactNode;+ /** The creator's own agent shell (layout + nested routes). */+ ownElement: ReactElement;+ /**+ * Where the creator lands when they open their OWN share link. Defaults to+ * the agent's share settings; a platform without that page (mobile) points+ * at the agent itself.+ */+ ownShareRedirect?: (agentId: string) => string;+ /** The agent-share visitor surface. */+ shareElement: ReactElement;+}++const defaultOwnShareRedirect = (agentId: string) => `/agent/${agentId}/share`;++/**+ * `/agent/:slugOrId` serves two surfaces: the creator's own agent (by id or by+ * agent slug) and the agent-share visitor page (by share slug or share id).+ * React Router cannot tell them apart from the pattern alone, so the branch is+ * decided here, after the param is resolved server-side.+ *+ * A not-found param renders the own-agent shell, which already owns the agent+ * not-found card — the visitor page has no better story for an unknown link.+ * The share branch does not render an `Outlet`, so the nested creator routes+ * (`/agent/:aid/docs` …) stay unmounted for a visitor.+ */+const AgentRouteSwitch = memo<AgentRouteSwitchProps>(+ ({ fallback, ownElement, ownShareRedirect = defaultOwnShareRedirect, shareElement }) => {+ const { aid } = useParams<{ aid?: string }>();+ const { error, isLoading, kind, resolvedAgentId } = useAgentRouteResolution(aid);+ const branch = resolveAgentRouteBranch({ error, isLoading, kind });++ if (branch === 'loading') return <>{fallback ?? null}</>;++ // The creator is never a visitor of their own share: `/agent/<share-slug>`+ // is what they copied from the share settings, so send them back there.+ if (branch === 'ownShare' && resolvedAgentId)+ return <Navigate replace to={ownShareRedirect(resolvedAgentId)} />;++ return branch === 'share' ? shareElement : ownElement;+ },+);++AgentRouteSwitch.displayName = 'AgentRouteSwitch';++export default AgentRouteSwitch;diff --git a/src/features/AgentRoute/useAgentRouteResolution.test.ts b/src/features/AgentRoute/useAgentRouteResolution.test.tsnew file mode 100644index 00000000000..cd9b1f30aa5--- /dev/null+++ b/src/features/AgentRoute/useAgentRouteResolution.test.ts@@ -0,0 +1,68 @@+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { describe, expect, it } from 'vitest';++import { needsAgentRouteLookup, resolveAgentRouteBranch } from './useAgentRouteResolution';++describe('needsAgentRouteLookup', () => {+ it('skips the lookup for id-shaped params', () => {+ expect(needsAgentRouteLookup('agt_123')).toBe(false);+ expect(needsAgentRouteLookup('agent_123')).toBe(false);+ });++ it('skips the lookup for builtin slugs, which the store already knows', () => {+ for (const slug of Object.values(BUILTIN_AGENT_SLUGS)) {+ expect([slug, needsAgentRouteLookup(slug)]).toEqual([slug, false]);+ }+ });++ it('looks up a user-chosen slug, which may be an agent or a share', () => {+ expect(needsAgentRouteLookup('my-bot')).toBe(true);+ });++ it('skips the lookup when there is no param at all', () => {+ expect(needsAgentRouteLookup()).toBe(false);+ expect(needsAgentRouteLookup('')).toBe(false);+ });+});++describe('resolveAgentRouteBranch', () => {+ it('waits instead of guessing a surface while the slug resolves', () => {+ expect(resolveAgentRouteBranch({ isLoading: true })).toBe('loading');+ // Even with a stale kind in hand, an in-flight resolution wins.+ expect(resolveAgentRouteBranch({ isLoading: true, kind: 'share' })).toBe('loading');+ });++ it('renders the creator surface for an own agent', () => {+ expect(resolveAgentRouteBranch({ isLoading: false, kind: 'own' })).toBe('own');+ });++ it('renders the visitor surface for a share', () => {+ expect(resolveAgentRouteBranch({ isLoading: false, kind: 'share' })).toBe('share');+ });++ it("redirects the creator's own share link instead of rendering the visitor surface", () => {+ expect(resolveAgentRouteBranch({ isLoading: false, kind: 'ownShare' })).toBe('ownShare');+ });++ it('falls back to the creator surface, which owns the not-found card', () => {+ expect(resolveAgentRouteBranch({ isLoading: false, kind: 'notFound' })).toBe('own');+ expect(resolveAgentRouteBranch({ isLoading: false })).toBe('own');+ });++ it('routes an UNAUTHORIZED lookup to the share surface, which owns the sign-in CTA', () => {+ const unauthorized = { data: { code: 'UNAUTHORIZED' } };++ expect(resolveAgentRouteBranch({ error: unauthorized, isLoading: false })).toBe('share');+ // Even with a stale/unset kind, an UNAUTHORIZED error wins over the fallback.+ expect(+ resolveAgentRouteBranch({ error: unauthorized, isLoading: false, kind: 'notFound' }),+ ).toBe('share');+ });++ it('keeps the creator fallback for a non-401 lookup failure', () => {+ const notFound = { data: { code: 'NOT_FOUND' } };++ expect(resolveAgentRouteBranch({ error: notFound, isLoading: false })).toBe('own');+ expect(resolveAgentRouteBranch({ error: new Error('network'), isLoading: false })).toBe('own');+ });+});diff --git a/src/features/AgentRoute/useAgentRouteResolution.ts b/src/features/AgentRoute/useAgentRouteResolution.tsnew file mode 100644index 00000000000..f7fb19e97f6--- /dev/null+++ b/src/features/AgentRoute/useAgentRouteResolution.ts@@ -0,0 +1,93 @@+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import useSWR from 'swr';++import type { AgentRouteResolution } from '@/server/routers/lambda/agent';+import { agentService } from '@/services/agent';+import { isTrpcErrorCode } from '@/utils/trpcError';++type AgentRouteResolutionKind = AgentRouteResolution['kind'];++const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));++/**+ * Every generated agent id carries an underscore (`agt_…`, `agent_…`) and no+ * generated slug does (`randomSlug` joins words with hyphens, and rename rejects+ * underscores). So the absence of one is what tells a slug route from an id+ * route — and a wrong guess only costs a lookup that resolves to nothing.+ */+export const looksLikeSlug = (routeAgentId?: string) =>+ !!routeAgentId && !routeAgentId.includes('_');++/** Builtin agents are addressed by a fixed slug that the store already knows. */+export const isBuiltinAgentSlug = (routeAgentId?: string) =>+ !!routeAgentId && builtinAgentSlugs.has(routeAgentId);++/**+ * A param only needs a server round trip when its shape leaves the answer open:+ * ids and builtin slugs are decided locally.+ */+export const needsAgentRouteLookup = (routeAgentId?: string) =>+ !isBuiltinAgentSlug(routeAgentId) && looksLikeSlug(routeAgentId);++export type AgentRouteBranch = 'loading' | 'own' | 'ownShare' | 'share';++/**+ * Which surface `/agent/:slugOrId` renders for a given resolution state.+ *+ * A not-found param falls back to the creator surface, which already owns the+ * agent not-found card — the visitor page has no better story for a dead link.+ *+ * An UNAUTHORIZED lookup is different: `resolveAgentRoute` is auth-gated, so+ * an anonymous visitor on a share URL fails the lookup itself, before `kind`+ * is ever known. Falling back to 'own' would show the creator's not-found+ * shell instead of a sign-in prompt, so this routes straight to 'share' and+ * lets `AgentShareVisitor`'s own `getSharedAgent` call (and its `signIn`+ * branch in `resolveShareAccessState`) render the CTA. Any other error keeps+ * the existing not-found fallback.+ */+export const resolveAgentRouteBranch = ({+ error,+ isLoading,+ kind,+}: {+ error?: unknown;+ isLoading: boolean;+ kind?: AgentRouteResolutionKind;+}): AgentRouteBranch => {+ if (isLoading) return 'loading';++ if (isTrpcErrorCode(error, 'UNAUTHORIZED')) return 'share';++ if (kind === 'share' || kind === 'ownShare') return kind;++ return 'own';+};++/**+ * Resolve a `/agent/:slugOrId` param, which serves two surfaces: the creator's+ * own agent and the agent-share visitor page.+ *+ * Id-shaped params and builtin slugs are decided locally, so an ordinary+ * `/agent/<id>` route never pays for a request. Only a user-chosen slug asks+ * the server, and that answer is shared with `useResolvedAgentRouteId` through+ * the same SWR key, so the switch and the layout resolve it exactly once.+ */+export const useAgentRouteResolution = (routeAgentId?: string) => {+ const needsLookup = needsAgentRouteLookup(routeAgentId);++ const { data, error, isLoading } = useSWR(+ needsLookup ? ['agent-route', routeAgentId] : null,+ () => agentService.resolveAgentRoute(routeAgentId!),+ { revalidateOnFocus: false },+ );++ return {+ /** The lookup's failure, if any — see `resolveAgentRouteBranch` for how UNAUTHORIZED is handled. */+ error: needsLookup ? error : undefined,+ /** True only while a slug lookup is in flight, i.e. the kind is unknown yet. */+ isLoading: needsLookup && isLoading,+ kind: needsLookup ? data?.kind : ('own' as const),+ /** The id behind a user-chosen agent slug (or the caller's own share slug), once known. */+ resolvedAgentId: data?.kind === 'own' || data?.kind === 'ownShare' ? data.agentId : undefined,+ };+};diff --git a/src/features/AgentRoute/useAgentShareVisitorRoute.test.ts b/src/features/AgentRoute/useAgentShareVisitorRoute.test.tsnew file mode 100644index 00000000000..9cbd0dcc4f4--- /dev/null+++ b/src/features/AgentRoute/useAgentShareVisitorRoute.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';++import { resolveAgentRouteParam } from './useAgentShareVisitorRoute';++describe('resolveAgentRouteParam', () => {+ it('reads the aid of a personal agent route', () => {+ expect(resolveAgentRouteParam('/agent/my-agent', null)).toBe('my-agent');+ });++ it('reads the aid of the workspace mirror', () => {+ expect(resolveAgentRouteParam('/acme/agent/my-agent', 'acme')).toBe('my-agent');+ });++ it('ignores nested creator routes, which never render the visitor surface', () => {+ expect(resolveAgentRouteParam('/agent/my-agent/docs', null)).toBeUndefined();+ expect(resolveAgentRouteParam('/acme/agent/my-agent/docs', 'acme')).toBeUndefined();+ });++ it('does not mistake a sibling three-segment route for the workspace mirror', () => {+ // `/community/agent/:slug` is a discover detail page, not an agent route.+ expect(resolveAgentRouteParam('/community/agent/some-slug', null)).toBeUndefined();+ expect(resolveAgentRouteParam('/community/agent/some-slug', 'acme')).toBeUndefined();+ });++ it('returns undefined for unrelated routes', () => {+ expect(resolveAgentRouteParam('/', null)).toBeUndefined();+ expect(resolveAgentRouteParam('/agent', null)).toBeUndefined();+ expect(resolveAgentRouteParam('/settings/common', null)).toBeUndefined();+ });+});diff --git a/src/features/AgentRoute/useAgentShareVisitorRoute.ts b/src/features/AgentRoute/useAgentShareVisitorRoute.tsnew file mode 100644index 00000000000..2a0874b831a--- /dev/null+++ b/src/features/AgentRoute/useAgentShareVisitorRoute.ts@@ -0,0 +1,54 @@+'use client';++import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { useActiveLocation } from '@/hooks/useActiveLocation';++import { resolveAgentRouteBranch, useAgentRouteResolution } from './useAgentRouteResolution';++/**+ * The `aid` of `/agent/:aid` — and of its workspace mirror+ * `/:workspaceSlug/agent/:aid` — read straight from the pathname, because the+ * main layout sits above that route and therefore has no `useParams` access to+ * it.+ *+ * Only the exact two-segment route counts: the nested creator routes+ * (`/agent/:aid/docs` …) never render the visitor surface. The workspace prefix+ * is stripped only when it equals the active slug, so sibling routes such as+ * `/community/agent/:slug` are not mistaken for an agent route — the same rule+ * `resolveNavPanelKey` uses.+ */+export const resolveAgentRouteParam = (+ pathname: string,+ activeWorkspaceSlug: string | null,+): string | undefined => {+ const segments = pathname.split('/').filter(Boolean);+ const routeSegments =+ !!activeWorkspaceSlug && segments[0] === activeWorkspaceSlug ? segments.slice(1) : segments;++ if (routeSegments.length !== 2 || routeSegments[0] !== 'agent') return undefined;++ return routeSegments[1];+};++/**+ * Whether the current route renders the agent-share visitor surface, i.e. the+ * `share` branch of `AgentRouteSwitch`.+ *+ * A visitor is not signed into the creator's workspace, so the main nav has no+ * data to show and would sit on a grey skeleton forever — the layout unmounts+ * it entirely for this branch. The branch is derived from the very same SWR key+ * as the switch itself, so this costs no extra request.+ *+ * While a slug lookup is still in flight the answer is `false`: nearly all+ * `/agent/:aid` traffic is the creator's own agent, and keeping the nav mounted+ * until proven otherwise avoids a flash on the common path.+ */+export const useIsAgentShareVisitorRoute = (): boolean => {+ const { pathname } = useActiveLocation();+ const activeWorkspaceSlug = useActiveWorkspaceSlug();+ const { error, isLoading, kind } = useAgentRouteResolution(+ resolveAgentRouteParam(pathname, activeWorkspaceSlug),+ );++ return resolveAgentRouteBranch({ error, isLoading, kind }) === 'share';+};diff --git a/src/features/AgentRoute/useResolvedAgentRouteId.ts b/src/features/AgentRoute/useResolvedAgentRouteId.tsindex 438fa952752..283a9716d60 100644--- a/src/features/AgentRoute/useResolvedAgentRouteId.ts+++ b/src/features/AgentRoute/useResolvedAgentRouteId.ts@@ -1,19 +1,13 @@import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';-import useSWR from 'swr';-import { agentService } from '@/services/agent';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';-const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));--/**- * Every generated agent id carries an underscore (`agt_…`, `agent_…`) and no- * generated slug does (`randomSlug` joins words with hyphens, and rename rejects- * underscores). So the absence of one is what tells a slug route from an id- * route — and a wrong guess only costs a lookup that resolves to null.- */-const looksLikeSlug = (routeAgentId?: string) => !!routeAgentId && !routeAgentId.includes('_');+import {+ isBuiltinAgentSlug,+ looksLikeSlug,+ useAgentRouteResolution,+} from './useAgentRouteResolution';/*** Keep the inbox route valid while its persisted agent ID is still loading.@@ -23,22 +17,18 @@ export const resolveInboxAgentRouteId = (inboxAgentId?: string) =>inboxAgentId ?? BUILTIN_AGENT_SLUGS.inbox;export const useResolvedAgentRouteId = (routeAgentId?: string) => {- const isBuiltinSlug = !!routeAgentId && builtinAgentSlugs.has(routeAgentId);+ const isBuiltinSlug = isBuiltinAgentSlug(routeAgentId);const builtinAgentId = useAgentStore(builtinAgentSelectors.getBuiltinAgentId(isBuiltinSlug ? routeAgentId! : ''),);// A user-chosen slug needs a server lookup; builtin slugs already resolve from- // the store. Gated on the shape check so an ordinary `/agent/<id>` route never- // pays for a request.+ // the store. The lookup is shared with `AgentRouteSwitch`, which asks the same+ // question one level up in the tree.const isCustomSlug = !isBuiltinSlug && looksLikeSlug(routeAgentId);- const { data: slugAgentId } = useSWR(- isCustomSlug ? ['agent-id-by-slug', routeAgentId] : null,- () => agentService.resolveAgentIdBySlug(routeAgentId!),- { revalidateOnFocus: false },- );+ const { resolvedAgentId: slugAgentId } = useAgentRouteResolution(routeAgentId);- const resolvedAgentId = isBuiltinSlug ? builtinAgentId : (slugAgentId ?? undefined);+ const resolvedAgentId = isBuiltinSlug ? builtinAgentId : slugAgentId;return {agentId: resolvedAgentId || routeAgentId,diff --git a/src/features/AgentShareSettings/Content.tsx b/src/features/AgentShareSettings/Content.tsxnew file mode 100644index 00000000000..f1ebe233744--- /dev/null+++ b/src/features/AgentShareSettings/Content.tsx@@ -0,0 +1,101 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { Alert, toast } from '@lobehub/ui/base-ui';+import { memo, useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import { AgentShareSettingsBodySkeleton } from '@/components/Skeleton/AgentShare';++import LimitsSection from './LimitsSection';+import LinkSection from './LinkSection';+import PermissionsSection from './PermissionsSection';+import ToolsSection from './ToolsSection';+import UsageSection from './UsageSection';+import { type AgentShareConfigPatch, useAgentShare } from './useAgentShare';+import { useAgentShareSupported } from './useAgentShareSupported';++interface AgentShareSettingsContentProps {+ agentId: string;+}++/**+ * Creator-side share settings for one agent, the body of `/agent/:aid/share`.+ * Every control saves immediately; the server merges each config patch+ * atomically, so a failed write leaves the other fields untouched.+ */+const AgentShareSettingsContent = memo<AgentShareSettingsContentProps>(({ agentId }) => {+ const { t } = useTranslation('agent');+ const { disable, enable, error, isLoading, mutate, share, updateConfig, updateSlug } =+ useAgentShare(agentId);+ const { publishable } = useAgentShareSupported(agentId);++ const handleConfigChange = useCallback(+ async (patch: AgentShareConfigPatch) => {+ try {+ await updateConfig(patch);+ } catch {+ toast.error(t('share.settings.updateError'));+ }+ },+ [t, updateConfig],+ );++ // Same skeleton as the route-level one so the page does not reflow between+ // the chunk load and the share fetch.+ if (isLoading && !share && !error) return <AgentShareSettingsBodySkeleton />;++ return (+ <Flexbox gap={16} paddingBlock={16}>+ {/* Sharing grants real execution on the creator's account — say so plainly. */}+ <Alert+ showIcon+ description={t('share.settings.notice.desc')}+ title={t('share.settings.notice.title')}+ type={'warning'}+ />+ {error && !share ? (+ <AsyncError error={error} variant={'block'} onRetry={() => void mutate()} />+ ) : (+ <>+ <LinkSection+ publishable={publishable}+ share={share}+ onDisable={disable}+ onEnable={enable}+ onUpdateSlug={updateSlug}+ />+ {/* Turning sharing off keeps the row (and its config) so the SAME link+ resumes on re-enable. The config stays editable while paused on+ purpose: re-enabling republishes whatever grants/limits are stored+ at that instant, so an owner must be able to tighten them BEFORE+ existing link holders regain access. */}+ {share && (+ <>+ <UsageSection+ agentId={agentId}+ monthlySpendLimit={share.shareConfig.monthlySpendLimit}+ />+ <PermissionsSection shareConfig={share.shareConfig} onChange={handleConfigChange} />+ <ToolsSection+ agentId={agentId}+ shareConfig={share.shareConfig}+ onChange={handleConfigChange}+ />+ <LimitsSection+ agentId={agentId}+ shareConfig={share.shareConfig}+ onChange={handleConfigChange}+ />+ </>+ )}+ </>+ )}+ </Flexbox>+ );+});++AgentShareSettingsContent.displayName = 'AgentShareSettingsContent';++export default AgentShareSettingsContent;diff --git a/src/features/AgentShareSettings/LimitsSection.tsx b/src/features/AgentShareSettings/LimitsSection.tsxnew file mode 100644index 00000000000..bfc8bb67662--- /dev/null+++ b/src/features/AgentShareSettings/LimitsSection.tsx@@ -0,0 +1,169 @@+'use client';++import { AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT } from '@lobechat/const';+import { Flexbox } from '@lobehub/ui';+import { InputNumber } from '@lobehub/ui/base-ui';+import { memo, useCallback, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useSWRConfig } from 'swr';++import { shareKeys } from '@/libs/swr/keys';+import { agentShareService } from '@/services/agentShare';++import { Section, SettingRow } from './SectionLayout';+import type { AgentShareConfigPatch, AgentShareConfigState } from './useAgentShare';+import {+ type AgentShareLimitPatch,+ resolveLimitCommitTarget,+ useDebouncedLimitPatch,+} from './useDebouncedLimitPatch';++type CountField = 'maxTopicsPerVisitor' | 'maxTurnsPerTopic';++interface LimitsSectionProps {+ agentId: string;+ onChange: (patch: AgentShareConfigPatch) => void;+ shareConfig: AgentShareConfigState;+}++/**+ * Visitor throughput caps and the creator's monthly spend cap. Every visitor+ * run is billed to the creator, so these are the only things standing between+ * a shared link and an unbounded bill.+ */+const LimitsSection = memo<LimitsSectionProps>(({ agentId, onChange, shareConfig }) => {+ const { t } = useTranslation('agent');+ const { mutate } = useSWRConfig();+ // Read at flush time, never closed over: `useDebouncedLimitPatch` keeps the+ // PREVIOUS render's `commit` in a ref while it drains the identity-change+ // flush, so that closure's captured `agentId` is still the old one. Only+ // this ref — assigned before the hook runs — knows which agent is current.+ const agentIdRef = useRef(agentId);+ agentIdRef.current = agentId;++ // Typing must not fire a request per keystroke: the drafts hold the raw+ // input and the debounced patch commits only valid values. A draft entry is+ // dropped once the write it belongs to has settled, so the field falls back+ // to the (now updated) server value.+ // Drafts may hold `null` (a cleared field): the input is controlled, so a+ // clear that is not mirrored locally snaps back to the saved value on blur+ // and a clear-then-type replacement gets swallowed.+ const [countDraft, setCountDraft] = useState<Partial<Record<CountField, number | null>>>({});+ const [spendDraft, setSpendDraft] = useState<number | null | undefined>();++ const settle = useCallback((patch: AgentShareLimitPatch) => {+ setCountDraft((prev) => {+ const next = { ...prev };+ for (const field of ['maxTopicsPerVisitor', 'maxTurnsPerTopic'] as CountField[]) {+ if (patch[field] !== undefined && next[field] === patch[field]) delete next[field];+ }+ return next;+ });+ if (patch.monthlySpendLimit !== undefined) {+ setSpendDraft((prev) => (prev === patch.monthlySpendLimit ? undefined : prev));+ }+ }, []);++ const commit = useCallback(+ async (patch: AgentShareLimitPatch, commitIdentity: string) => {+ // The debounced patch was scheduled for the agent this section still+ // renders: go through the shared queue so the optimistic projection and+ // the SWR cache entry stay in lockstep with every other control.+ if (resolveLimitCommitTarget(commitIdentity, agentIdRef.current) === 'current') {+ await onChange(patch);+ return;+ }++ // Flushed BECAUSE `agentId` just changed, so this patch belongs to the+ // agent that was navigated away from. `onChange` would drop it: the+ // parent `useAgentShare` already reset its refs for the new agent at+ // render time, and `updateConfig` bails out on a missing base config.+ // Send it straight to the service instead — this mirrors+ // `useAgentShare`'s existing rule that a write issued for an abandoned+ // identity is still SENT (the row it targets is unchanged), only its+ // local bookkeeping is skipped. Revalidate that agent's own status key+ // so its cached snapshot is not left behind the value just persisted.+ try {+ await agentShareService.updateShareConfig(commitIdentity, patch);+ } finally {+ void mutate(shareKeys.agentShareStatus(commitIdentity));+ }+ },+ [mutate, onChange],+ );++ const schedule = useDebouncedLimitPatch(agentId, commit, settle);++ const handleCountChange = (field: CountField, value: number | null) => {+ setCountDraft((prev) => ({ ...prev, [field]: value }));+ // The server schema only accepts positive integers; an empty or invalid+ // field just holds the draft until it becomes valid again.+ if (typeof value === 'number' && Number.isInteger(value) && value >= 1) {+ const patch: AgentShareLimitPatch = { [field]: value };+ schedule(patch);+ }+ };++ const handleSpendChange = (value: number | null) => {+ // `null` is an empty/half-typed field, NOT "no cap": the cap is mandatory,+ // so hold the (empty) draft and commit nothing until a number comes back.+ setSpendDraft(value);+ if (value !== null && value >= 0) schedule({ monthlySpendLimit: value });+ };++ return (+ <Section desc={t('share.settings.limits.desc')} title={t('share.settings.limits.title')}>+ <Flexbox gap={12}>+ <SettingRow+ desc={t('share.settings.limits.maxTopicsPerVisitorHint')}+ label={t('share.settings.limits.maxTopicsPerVisitor')}+ >+ <InputNumber+ max={AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT}+ min={1}+ step={1}+ style={{ width: 160 }}+ value={+ countDraft.maxTopicsPerVisitor !== undefined+ ? countDraft.maxTopicsPerVisitor+ : (shareConfig.maxTopicsPerVisitor ?? null)+ }+ onChange={(value) => handleCountChange('maxTopicsPerVisitor', value)}+ />+ </SettingRow>+ <SettingRow+ desc={t('share.settings.limits.maxTurnsPerTopicHint')}+ label={t('share.settings.limits.maxTurnsPerTopic')}+ >+ <InputNumber+ min={1}+ step={1}+ style={{ width: 160 }}+ value={+ countDraft.maxTurnsPerTopic !== undefined+ ? countDraft.maxTurnsPerTopic+ : (shareConfig.maxTurnsPerTopic ?? null)+ }+ onChange={(value) => handleCountChange('maxTurnsPerTopic', value)}+ />+ </SettingRow>+ <SettingRow+ desc={t('share.settings.limits.monthlySpendLimitHint')}+ label={t('share.settings.limits.monthlySpendLimit')}+ >+ <InputNumber+ min={0}+ step={1}+ style={{ width: 160 }}+ value={spendDraft !== undefined ? spendDraft : (shareConfig.monthlySpendLimit ?? null)}+ onChange={handleSpendChange}+ />+ </SettingRow>+ </Flexbox>+ </Section>+ );+});++LimitsSection.displayName = 'AgentShareLimitsSection';++export default LimitsSection;diff --git a/src/features/AgentShareSettings/LinkSection.tsx b/src/features/AgentShareSettings/LinkSection.tsxnew file mode 100644index 00000000000..3c6ae3cf978--- /dev/null+++ b/src/features/AgentShareSettings/LinkSection.tsx@@ -0,0 +1,226 @@+'use client';++import { copyToClipboard, Flexbox, Input, Tooltip } from '@lobehub/ui';+import { Button, confirmModal, Switch, Text, toast } from '@lobehub/ui/base-ui';+import { CopyIcon } from 'lucide-react';+import { memo, useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useAppOrigin } from '@/hooks/useAppOrigin';++import { Section } from './SectionLayout';+import {+ type AgentShareSlugError,+ buildAgentShareUrl,+ normalizeAgentShareSlug,+ validateAgentShareSlug,+} from './shareLink';+import type { AgentShareInfo } from './useAgentShare';+import { resolveLinkToggleState } from './useAgentShareSupported';++const SLUG_ERROR_KEY = {+ invalid: 'share.settings.link.slugError.invalid',+ reserved: 'share.settings.link.slugError.reserved',+ tooLong: 'share.settings.link.slugError.tooLong',+ tooShort: 'share.settings.link.slugError.tooShort',+} as const satisfies Record<AgentShareSlugError, string>;++interface LinkSectionProps {+ onDisable: () => Promise<void>;+ onEnable: () => Promise<void>;+ onUpdateSlug: (slug: string | null) => Promise<void>;+ /** Whether a new share may be published — see `useAgentShareSupported`. */+ publishable: boolean;+ share: AgentShareInfo | undefined;+}++/**+ * Sharing on/off, the visitor link, and the custom slug.+ *+ * Turning sharing off only PAUSES it: the share row keeps its id and custom+ * slug, so visitors are locked out while it is off and turning it back on+ * republishes the very same url — see `AgentShareModel.updateVisibility`.+ */+const LinkSection = memo<LinkSectionProps>((props) => {+ const { onDisable, onEnable, onUpdateSlug, publishable, share } = props;+ const { t } = useTranslation('agent');+ const appOrigin = useAppOrigin();++ const isShared = share?.visibility === 'link';+ const savedSlug = share?.shareConfig?.slug ?? '';+ const {+ canPublish,+ disabled: toggleDisabled,+ offHintKey,+ } = resolveLinkToggleState({+ isShared,+ publishable,+ });++ const [toggling, setToggling] = useState(false);+ const [slugDraft, setSlugDraft] = useState(savedSlug);+ const [slugError, setSlugError] = useState<string>('');+ const [savingSlug, setSavingSlug] = useState(false);++ // Re-sync the draft whenever the server value changes — a save elsewhere, or+ // the row reloading after an enable/disable (which keeps the saved slug).+ useEffect(() => {+ setSlugDraft(savedSlug);+ setSlugError('');+ }, [savedSlug, share?.id]);++ const shareUrl =+ share && isShared+ ? buildAgentShareUrl({ origin: appOrigin, shareId: share.id, slug: savedSlug || undefined })+ : '';++ const handleCopy = useCallback(async () => {+ if (!shareUrl) return;+ try {+ await copyToClipboard(shareUrl);+ toast.success(t('share.settings.link.copied'));+ } catch {+ toast.error(t('copyFail', { ns: 'common' }));+ }+ }, [shareUrl, t]);++ const handleToggle = useCallback(+ async (checked: boolean) => {+ // Publishing is gated (rollout flag / plan); turning an existing share+ // OFF must always stay available, so only the `on` direction is blocked.+ if (checked && !canPublish) return;++ const apply = async () => {+ setToggling(true);+ try {+ await (checked ? onEnable() : onDisable());+ } catch {+ toast.error(t('share.settings.updateError'));+ } finally {+ setToggling(false);+ }+ };++ if (checked) {+ void apply();+ return;+ }++ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('share.settings.link.disableConfirmContent'),+ okText: t('share.settings.link.disableConfirmOk'),+ onOk: apply,+ title: t('share.settings.link.disableConfirmTitle'),+ });+ },+ [canPublish, onDisable, onEnable, t],+ );++ const handleSaveSlug = useCallback(async () => {+ const next = normalizeAgentShareSlug(slugDraft);+ if (next === savedSlug) {+ setSlugDraft(next);+ setSlugError('');+ return;+ }++ if (next) {+ const error = validateAgentShareSlug(next);+ if (error) {+ setSlugError(t(SLUG_ERROR_KEY[error]));+ return;+ }+ }++ setSavingSlug(true);+ setSlugError('');+ try {+ // An emptied field clears the custom slug — the share then resolves by+ // its raw id again.+ await onUpdateSlug(next || null);+ toast.success(t('share.settings.link.slugSaved'));+ } catch (error: any) {+ setSlugError(+ error?.data?.code === 'CONFLICT'+ ? t('share.settings.link.slugError.taken')+ : t('share.settings.updateError'),+ );+ } finally {+ setSavingSlug(false);+ }+ }, [onUpdateSlug, savedSlug, slugDraft, t]);++ const slugDirty = normalizeAgentShareSlug(slugDraft) !== savedSlug;++ return (+ <Section+ desc={t('share.settings.link.desc')}+ title={t('share.settings.link.title')}+ extra={+ <Tooltip title={toggleDisabled ? t('share.settings.link.publishDisabled') : undefined}>+ {/* A disabled control fires no pointer events, so the wrapper carries the hover. */}+ <Flexbox>+ <Switch+ checked={isShared}+ disabled={toggleDisabled}+ loading={toggling}+ onChange={handleToggle}+ />+ </Flexbox>+ </Tooltip>+ }+ >+ {isShared ? (+ <Flexbox gap={12}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Input readOnly style={{ flex: 1 }} value={shareUrl} variant={'filled'} />+ <Button icon={CopyIcon} type={'primary'} onClick={handleCopy}>+ {t('share.settings.link.copy')}+ </Button>+ </Flexbox>++ <Flexbox gap={4}>+ <Text fontSize={12} type={'secondary'}>+ {t('share.settings.link.slugLabel')}+ </Text>+ <Flexbox horizontal align={'center'} gap={8}>+ <Input+ disabled={savingSlug}+ placeholder={t('share.settings.link.slugPlaceholder')}+ prefix={`${appOrigin}/agent/`}+ status={slugError ? 'error' : undefined}+ style={{ flex: 1 }}+ value={slugDraft}+ variant={'filled'}+ onPressEnter={handleSaveSlug}+ onChange={(e) => {+ setSlugDraft(e.target.value);+ setSlugError('');+ }}+ />+ <Button disabled={!slugDirty} loading={savingSlug} onClick={handleSaveSlug}>+ {t('save', { ns: 'common' })}+ </Button>+ </Flexbox>+ <Text fontSize={12} type={slugError ? 'danger' : 'secondary'}>+ {slugError || t('share.settings.link.slugHint')}+ </Text>+ </Flexbox>++ <Text fontSize={12} type={'secondary'}>+ {t('share.settings.link.viewCount', { views: String(share?.userViewCount ?? 0) })}+ </Text>+ </Flexbox>+ ) : (+ <Text fontSize={12} type={'secondary'}>+ {t(offHintKey)}+ </Text>+ )}+ </Section>+ );+});++LinkSection.displayName = 'AgentShareLinkSection';++export default LinkSection;diff --git a/src/features/AgentShareSettings/Page.tsx b/src/features/AgentShareSettings/Page.tsxnew file mode 100644index 00000000000..7ca1705ac66--- /dev/null+++ b/src/features/AgentShareSettings/Page.tsx@@ -0,0 +1,69 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { memo } from 'react';+import { Navigate } from 'react-router';++import AgentBreadcrumb from '@/features/AgentBreadcrumb';+import AgentProfileTabs, { AGENT_PROFILE_TABS_CENTER_STYLE } from '@/features/AgentProfileTabs';+import NavHeader from '@/features/NavHeader';+import WideScreenContainer from '@/features/WideScreenContainer';+import { useAgentStore } from '@/store/agent';+import { StyleSheet } from '@/utils/styles';++import Content from './Content';+import { useAgentShareSupported } from './useAgentShareSupported';++const styles = StyleSheet.create({+ body: {+ display: 'flex',+ overflowY: 'auto',+ position: 'relative',+ },+});++/**+ * Full-page share management for one agent, the fourth segment of the agent+ * profile group. Sharing grants visitors real execution on the creator's+ * account, so the flow gets a deliberate page (deep-linkable, back/forward+ * aware) rather than a modal that any stray click dismisses.+ */+const AgentShareSettingsPage = memo(() => {+ const activeAgentId = useAgentStore((s) => s.activeAgentId);+ const { visible: shareVisible } = useAgentShareSupported(activeAgentId);++ // A deep link on an agent that can never be shared (workspace / builtin row),+ // or by an account outside the rollout allowlist with nothing live to revoke,+ // lands on the agent instead of a settings surface whose every control would+ // fail server-side. `undefined` (lookup still resolving) keeps the page so a+ // revocable share does not flash through a redirect.+ if (activeAgentId && shareVisible === false)+ return <Navigate replace to={`/agent/${activeAgentId}`} />;++ return (+ <Flexbox height={'100%'} width={'100%'}>+ <NavHeader+ // No section title — the Segmented beside it names the current tab.+ left={activeAgentId ? <AgentBreadcrumb agentId={activeAgentId} /> : null}+ // `relative` anchors the absolutely-centered switcher below.+ style={{ position: 'relative' }}+ styles={{+ // Center on the header midpoint (equal gaps), not the leftover track.+ center: AGENT_PROFILE_TABS_CENTER_STYLE,+ left: { minWidth: 0, paddingInlineStart: 8 },+ }}+ >+ {activeAgentId && <AgentProfileTabs active={'share'} agentId={activeAgentId} />}+ </NavHeader>+ <Flexbox flex={1} style={styles.body} width={'100%'}>+ <WideScreenContainer>+ {activeAgentId && <Content agentId={activeAgentId} />}+ </WideScreenContainer>+ </Flexbox>+ </Flexbox>+ );+});++AgentShareSettingsPage.displayName = 'AgentShareSettingsPage';++export default AgentShareSettingsPage;diff --git a/src/features/AgentShareSettings/PermissionsSection.tsx b/src/features/AgentShareSettings/PermissionsSection.tsxnew file mode 100644index 00000000000..0ef9526d3f5--- /dev/null+++ b/src/features/AgentShareSettings/PermissionsSection.tsx@@ -0,0 +1,65 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { Switch } from '@lobehub/ui/base-ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { Section, SettingRow } from './SectionLayout';+import type { AgentShareConfigPatch, AgentShareConfigState } from './useAgentShare';++interface PermissionsSectionProps {+ onChange: (patch: AgentShareConfigPatch) => void;+ shareConfig: AgentShareConfigState;+}++/** What a visitor's run may read, and what the visitor is allowed to see back. */+const PermissionsSection = memo<PermissionsSectionProps>(({ onChange, shareConfig }) => {+ const { t } = useTranslation('agent');++ return (+ <Section+ desc={t('share.settings.permissions.desc')}+ title={t('share.settings.permissions.title')}+ >+ <Flexbox gap={12}>+ <SettingRow+ desc={t('share.settings.permissions.allowReadMemoryHint')}+ label={t('share.settings.permissions.allowReadMemory')}+ >+ <Switch+ checked={shareConfig.allowReadMemory ?? false}+ onChange={(checked) => onChange({ allowReadMemory: checked })}+ />+ </SettingRow>+ {/* `allowCreatorViewSessions` is persisted (zod schema + DB default false)+ but no read path honors it yet — creator reads unconditionally+ exclude visitor rows (see packages/database/src/models/topic.ts).+ Hidden here until that read path exists, so the switch is not+ surfaced as a working control. */}+ <SettingRow+ desc={t('share.settings.permissions.showModelInfoHint')}+ label={t('share.settings.permissions.showModelInfo')}+ >+ <Switch+ checked={shareConfig.showModelInfo ?? false}+ onChange={(checked) => onChange({ showModelInfo: checked })}+ />+ </SettingRow>+ <SettingRow+ desc={t('share.settings.permissions.showErrorDetailsHint')}+ label={t('share.settings.permissions.showErrorDetails')}+ >+ <Switch+ checked={shareConfig.showErrorDetails ?? false}+ onChange={(checked) => onChange({ showErrorDetails: checked })}+ />+ </SettingRow>+ </Flexbox>+ </Section>+ );+});++PermissionsSection.displayName = 'AgentSharePermissionsSection';++export default PermissionsSection;diff --git a/src/features/AgentShareSettings/SectionLayout.tsx b/src/features/AgentShareSettings/SectionLayout.tsxnew file mode 100644index 00000000000..748343837c7--- /dev/null+++ b/src/features/AgentShareSettings/SectionLayout.tsx@@ -0,0 +1,52 @@+'use client';++import { Block, Flexbox } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import type { ReactNode } from 'react';++interface SettingRowProps {+ children: ReactNode;+ /** Secondary line under the label. */+ desc?: ReactNode;+ label: string;+}++export const SettingRow = ({ children, desc, label }: SettingRowProps) => (+ <Flexbox horizontal align={'center'} gap={16} justify={'space-between'}>+ <Flexbox gap={2}>+ <Text>{label}</Text>+ {desc && (+ <Text fontSize={12} type={'secondary'}>+ {desc}+ </Text>+ )}+ </Flexbox>+ {children}+ </Flexbox>+);++interface SectionProps {+ children: ReactNode;+ desc?: ReactNode;+ extra?: ReactNode;+ title: string;+}++export const Section = ({ children, desc, extra, title }: SectionProps) => (+ <Block gap={16} padding={20} variant={'outlined'}>+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>+ <Flexbox gap={2}>+ <Text fontSize={16} weight={500}>+ {title}+ </Text>+ {desc && (+ <Text fontSize={12} type={'secondary'}>+ {desc}+ </Text>+ )}+ </Flexbox>+ {extra}+ </Flexbox>+ {children}+ </Block>+);diff --git a/src/features/AgentShareSettings/ToolRow.tsx b/src/features/AgentShareSettings/ToolRow.tsxnew file mode 100644index 00000000000..3488608da8a--- /dev/null+++ b/src/features/AgentShareSettings/ToolRow.tsx@@ -0,0 +1,164 @@+'use client';++import { Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { Checkbox, Text } from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';+import isEqual from 'fast-deep-equal';+import { ChevronDown, ChevronRight } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import PluginTag from '@/features/ProfileEditor/PluginTag';+import { useToolStore } from '@/store/tool';+import { pluginSelectors } from '@/store/tool/selectors';++import {+ getShareApiAvailability,+ getShareToolAvailability,+ getShareToolGrantForIdentifier,+ toggleShareToolApi,+ toggleShareToolsetGrant,+} from './toolVisitorAvailability';+import type { AgentShareConfigPatch, AgentShareConfigState } from './useAgentShare';++interface ToolRowProps {+ agentId: string;+ onChange: (patch: AgentShareConfigPatch) => void;+ selected: boolean;+ shareConfig: AgentShareConfigState;+ toolId: string;+}++/**+ * One toolset row in the visitor tool picker: the existing selectable+ * `PluginTag` chip — checked for a full grant, indeterminate (minus) for a+ * partial per-API one, and toggling between them via+ * {@link toggleShareToolsetGrant} — plus an expand chevron+ * — shown only when the tool has more than one visitor-grantable API — that+ * reveals a per-API checkbox list underneath.+ *+ * The API list comes from the REAL manifest (builtin registry or an installed+ * plugin/MCP manifest), the same source the server gate reads, so a tool this+ * build does not yet know the APIs of simply never expands rather than+ * offering stale/guessed entries.+ */+const ToolRow = memo<ToolRowProps>(({ agentId, toolId, selected, shareConfig, onChange }) => {+ const { t } = useTranslation('agent');+ const [expanded, setExpanded] = useState(false);++ const builtinManifest = useToolStore(+ (s) => s.builtinTools.find((tool) => tool.identifier === toolId)?.manifest,+ isEqual,+ );+ const pluginManifest = useToolStore(pluginSelectors.getToolManifestById(toolId), isEqual);+ const apis = (builtinManifest ?? pluginManifest)?.api ?? [];++ const availability = getShareToolAvailability(toolId, {+ allowReadMemory: shareConfig.allowReadMemory,+ });+ // Anything short of `available` is disabled: the gate would strip the+ // grant, so accepting the tick would only confirm a permission that never+ // takes effect. The tooltip carries the reason.+ const blocked = availability !== 'available';++ const grantableApiNames = apis+ .filter(+ (api) => getShareApiAvailability(toolId, api.name, api.humanIntervention) === 'available',+ )+ .map((api) => api.name);+ const canExpand = !blocked && grantableApiNames.length > 1;++ const grant = getShareToolGrantForIdentifier(shareConfig.toolGrants, toolId);++ const toggleTool = () => {+ onChange((current) => ({+ toolGrants: toggleShareToolsetGrant(current.toolGrants, toolId),+ }));+ };++ const toggleApi = (apiName: string) => {+ onChange((current) => ({+ toolGrants: toggleShareToolApi(current.toolGrants, toolId, apiName, grantableApiNames),+ }));+ };++ return (+ <Flexbox gap={2}>+ <Flexbox horizontal align={'center'} gap={2}>+ <Tooltip+ title={+ availability === 'needsMemoryPermission'+ ? t('share.settings.tools.needsMemoryPermission')+ : blocked+ ? t('share.settings.tools.notAvailableToVisitors')+ : undefined+ }+ >+ <PluginTag+ selectable+ useAllMetaList+ agentId={agentId}+ disabled={blocked}+ indeterminate={grant instanceof Set}+ pluginId={toolId}+ selected={selected}+ onSelect={blocked ? undefined : toggleTool}+ />+ </Tooltip>+ {canExpand && (+ <Icon+ icon={expanded ? ChevronDown : ChevronRight}+ size={14}+ style={{ color: cssVar.colorTextTertiary, cursor: 'pointer' }}+ onClick={() => setExpanded((prev) => !prev)}+ />+ )}+ </Flexbox>+ {expanded && canExpand && (+ <Flexbox gap={4} style={{ paddingInlineStart: 24 }}>+ {apis.map((api) => {+ const apiAvailability = getShareApiAvailability(+ toolId,+ api.name,+ api.humanIntervention,+ );+ const apiBlocked = apiAvailability !== 'available';+ const apiSelected = grant === 'all' || (grant instanceof Set && grant.has(api.name));++ return (+ <Tooltip+ key={api.name}+ title={+ apiAvailability === 'writesOwnerData'+ ? t('share.settings.tools.apiWritesOwnerData')+ : apiBlocked+ ? t('share.settings.tools.apiNotAvailableToVisitors')+ : undefined+ }+ >+ <Checkbox+ checked={!apiBlocked && apiSelected}+ disabled={blocked || apiBlocked}+ onChange={() => toggleApi(api.name)}+ >+ <Flexbox gap={0}>+ <Text fontSize={12}>{api.name}</Text>+ {api.description && (+ <Text ellipsis={{ rows: 1, tooltip: true }} fontSize={11} type={'secondary'}>+ {api.description}+ </Text>+ )}+ </Flexbox>+ </Checkbox>+ </Tooltip>+ );+ })}+ </Flexbox>+ )}+ </Flexbox>+ );+});++ToolRow.displayName = 'AgentShareToolRow';++export default ToolRow;diff --git a/src/features/AgentShareSettings/ToolsSection.tsx b/src/features/AgentShareSettings/ToolsSection.tsxnew file mode 100644index 00000000000..9c99b4eb8e3--- /dev/null+++ b/src/features/AgentShareSettings/ToolsSection.tsx@@ -0,0 +1,108 @@+'use client';++import { getActivePluginIds } from '@lobechat/types';+import { Flexbox } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import isEqual from 'fast-deep-equal';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';++import { Section } from './SectionLayout';+import ToolRow from './ToolRow';+import {+ getShareToolAvailability,+ getShareToolCandidateIds,+ getVisitorVisibleGrantedToolIds,+} from './toolVisitorAvailability';+import type { AgentShareConfigPatch, AgentShareConfigState } from './useAgentShare';++interface ToolsSectionProps {+ agentId: string;+ onChange: (patch: AgentShareConfigPatch) => void;+ shareConfig: AgentShareConfigState;+}++/**+ * Whitelist of tools a visitor's run may call. Default-deny: an unchecked tool+ * is stripped by the server gate even if the agent itself has it enabled.+ * High-risk identifiers (device, local system, sandbox, ...) and tools the+ * gate refuses outright (knowledge base, agent documents) are never selectable+ * — see `toolVisitorAvailability`.+ */+const ToolsSection = memo<ToolsSectionProps>(({ agentId, onChange, shareConfig }) => {+ const { t } = useTranslation('agent');++ const agentConfig = useAgentStore(agentSelectors.getAgentConfigById(agentId), isEqual);+ const candidateToolIds = getShareToolCandidateIds(getActivePluginIds(agentConfig?.plugins));+ const selectedToolIds = getVisitorVisibleGrantedToolIds(shareConfig.toolGrants);++ // Two buckets, extension-manager style: what visitors already get, then what+ // else could be granted. Toggling moves a tool between them, so the owner+ // reads the effective grant at a glance instead of scanning checkboxes.+ const enabledIds = candidateToolIds.filter(+ (toolId) =>+ selectedToolIds.includes(toolId) &&+ getShareToolAvailability(toolId, { allowReadMemory: shareConfig.allowReadMemory }) ===+ 'available',+ );+ // Includes tools the gate always refuses: they still render below as+ // disabled chips (so the owner learns why a configured tool cannot be+ // shared), and the group's count must match the chips actually rendered in+ // it — a smaller "grantable only" count reads as a rendering bug.+ const availableIds = candidateToolIds.filter((toolId) => !enabledIds.includes(toolId));++ const renderTool = (toolId: string, selected: boolean) => (+ <ToolRow+ agentId={agentId}+ key={toolId}+ selected={selected}+ shareConfig={shareConfig}+ toolId={toolId}+ onChange={onChange}+ />+ );++ return (+ <Section desc={t('share.settings.tools.desc')} title={t('share.settings.tools.title')}>+ {candidateToolIds.length === 0 ? (+ <Text fontSize={12} type={'secondary'}>+ {t('share.settings.tools.empty')}+ </Text>+ ) : (+ <Flexbox gap={16}>+ <Flexbox gap={8}>+ <Text fontSize={12} type={'secondary'}>+ {t('share.settings.tools.grantedGroup', { count: enabledIds.length })}+ </Text>+ {enabledIds.length === 0 ? (+ <Text fontSize={12} type={'secondary'}>+ {t('share.settings.tools.grantedEmpty')}+ </Text>+ ) : (+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ {enabledIds.map((toolId) => renderTool(toolId, true))}+ </Flexbox>+ )}+ </Flexbox>+ {availableIds.length > 0 && (+ <Flexbox gap={8}>+ <Text fontSize={12} type={'secondary'}>+ {t('share.settings.tools.availableGroup', { count: availableIds.length })}+ </Text>+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ {availableIds.map((toolId) => renderTool(toolId, false))}+ </Flexbox>+ </Flexbox>+ )}+ </Flexbox>+ )}+ </Section>+ );+});++ToolsSection.displayName = 'AgentShareToolsSection';++export default ToolsSection;diff --git a/src/features/AgentShareSettings/UsageSection.tsx b/src/features/AgentShareSettings/UsageSection.tsxnew file mode 100644index 00000000000..87037300fcb--- /dev/null+++ b/src/features/AgentShareSettings/UsageSection.tsx@@ -0,0 +1,110 @@+'use client';++import { Flexbox, Skeleton } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { Progress } from 'antd';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import { formatPrice } from '@/utils/format';++import { Section } from './SectionLayout';+import { useShareUsage } from './useShareUsage';++interface StatProps {+ label: string;+ value: number;+}++const Stat = memo<StatProps>(({ label, value }) => (+ <Flexbox flex={1} gap={2}>+ <Text fontSize={20} weight={600}>+ {value}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {label}+ </Text>+ </Flexbox>+));++Stat.displayName = 'AgentShareUsageStat';++interface UsageSectionProps {+ agentId: string;+ /** Live configured cap from the share-status cache; see `useShareUsage`. */+ monthlySpendLimit?: number;+}++/**+ * Read-only roll-up of what a share has actually cost and attracted: page+ * views, distinct visitors, visitor conversations, and this month's spend+ * against the cap configured in `LimitsSection`.+ *+ * Aggregates only — the creator's visibility into individual visitor+ * CONVERSATIONS stays governed by `allowCreatorViewSessions`, which these+ * counts deliberately do not bypass.+ */+const UsageSection = memo<UsageSectionProps>(({ agentId, monthlySpendLimit }) => {+ const { t } = useTranslation('agent');++ const { data, error, hasLoadError, isLoading, isValidating, limit, mutate, spend } =+ useShareUsage(agentId, monthlySpendLimit);++ return (+ <Section desc={t('share.settings.usage.desc')} title={t('share.settings.usage.title')}>+ {isLoading ? (+ <Skeleton active paragraph={{ rows: 2 }} title={false} />+ ) : hasLoadError ? (+ <AsyncError+ error={error}+ retrying={isValidating}+ title={t('share.settings.usage.loadFailed')}+ variant={'inline'}+ onRetry={() => void mutate()}+ />+ ) : (+ <Flexbox gap={16}>+ <Flexbox horizontal gap={16}>+ <Stat label={t('share.settings.usage.views')} value={data?.userViewCount ?? 0} />+ <Stat label={t('share.settings.usage.visitors')} value={data?.visitorCount ?? 0} />+ <Stat label={t('share.settings.usage.conversations')} value={data?.topicCount ?? 0} />+ </Flexbox>+ {/* `null` means this deployment does not meter share spend — show+ nothing rather than a misleading $0. */}+ {spend !== null && (+ <Flexbox gap={4}>+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Text fontSize={12} type={'secondary'}>+ {t('share.settings.usage.monthlySpend')}+ </Text>+ <Text fontSize={12}>+ {limit === undefined+ ? formatPrice(spend)+ : t('share.settings.usage.spendOfLimit', {+ limit: formatPrice(limit),+ spend: formatPrice(spend),+ })}+ </Text>+ </Flexbox>+ {limit !== undefined && (+ <Progress+ // A `0` cap ("stop all visitor runs") is special-cased so the+ // progress computation never divides by it.+ percent={limit === 0 ? 100 : Math.min(100, Math.round((spend / limit) * 100))}+ showInfo={false}+ size={'small'}+ status={spend >= limit ? 'exception' : 'normal'}+ />+ )}+ </Flexbox>+ )}+ </Flexbox>+ )}+ </Section>+ );+});++UsageSection.displayName = 'AgentShareUsageSection';++export default UsageSection;diff --git a/src/features/AgentShareSettings/shareConfigPatch.test.ts b/src/features/AgentShareSettings/shareConfigPatch.test.tsnew file mode 100644index 00000000000..f575ee99239--- /dev/null+++ b/src/features/AgentShareSettings/shareConfigPatch.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest';++import { mergeShareConfig } from './shareConfigPatch';++describe('mergeShareConfig', () => {+ const base = {+ allowReadMemory: false,+ toolGrants: [{ identifier: 'a' }],+ maxTopicsPerVisitor: 5,+ maxTurnsPerTopic: 20,+ monthlySpendLimit: 10,+ };++ it('overwrites only the patched keys', () => {+ expect(mergeShareConfig(base, { maxTurnsPerTopic: 30 })).toEqual({+ ...base,+ maxTurnsPerTopic: 30,+ });+ });++ it('overwrites the spend cap with a zero cap, mirroring the server jsonb merge', () => {+ const merged = mergeShareConfig(base, { monthlySpendLimit: 0 });++ expect(merged.monthlySpendLimit).toBe(0);+ expect(merged.maxTopicsPerVisitor).toBe(5);+ });++ it('does not mutate the base', () => {+ mergeShareConfig(base, { toolGrants: [{ identifier: 'a' }, { identifier: 'b' }] });++ expect(base.toolGrants).toEqual([{ identifier: 'a' }]);+ });+});diff --git a/src/features/AgentShareSettings/shareConfigPatch.ts b/src/features/AgentShareSettings/shareConfigPatch.tsnew file mode 100644index 00000000000..7fa74abfcf1--- /dev/null+++ b/src/features/AgentShareSettings/shareConfigPatch.ts@@ -0,0 +1,21 @@+import type { AgentShareConfigPatchInput } from '@/services/agentShare';++import type { AgentShareConfigState } from './useAgentShare';++/**+ * Client-side mirror of `AgentShareModel.updateConfig`'s jsonb merge: a key+ * present in the patch overwrites the base value, and an `undefined` value is+ * "not part of this patch" — the server skips it, so the base value stands.+ *+ * Used to keep a local copy of the config in step with writes that are still+ * in flight, so a second edit composes on top of the first instead of being+ * derived from a snapshot the server has already moved past.+ */+export const mergeShareConfig = (+ base: AgentShareConfigState,+ patch: AgentShareConfigPatchInput,+): AgentShareConfigState => {+ const patched = Object.entries(patch).filter(([, value]) => value !== undefined);++ return Object.assign({ ...base }, Object.fromEntries(patched));+};diff --git a/src/features/AgentShareSettings/shareLink.test.ts b/src/features/AgentShareSettings/shareLink.test.tsnew file mode 100644index 00000000000..853cf8a48c0--- /dev/null+++ b/src/features/AgentShareSettings/shareLink.test.ts@@ -0,0 +1,68 @@+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { describe, expect, it } from 'vitest';++import { buildAgentShareUrl, normalizeAgentShareSlug, validateAgentShareSlug } from './shareLink';++describe('normalizeAgentShareSlug', () => {+ it('trims and lowercases', () => {+ expect(normalizeAgentShareSlug(' My-Bot ')).toBe('my-bot');+ });+});++describe('validateAgentShareSlug', () => {+ it('accepts a well-formed slug', () => {+ expect(validateAgentShareSlug('my-cool-bot')).toBeNull();+ expect(validateAgentShareSlug('abc')).toBeNull();+ expect(validateAgentShareSlug('a1b')).toBeNull();+ });++ it('rejects slugs shorter than 3 or longer than 64 characters', () => {+ expect(validateAgentShareSlug('ab')).toBe('tooShort');+ expect(validateAgentShareSlug('a'.repeat(65))).toBe('tooLong');+ expect(validateAgentShareSlug('a'.repeat(64))).toBeNull();+ });++ it('rejects uppercase, underscores, spaces and edge hyphens', () => {+ expect(validateAgentShareSlug('My-Bot')).toBe('invalid');+ expect(validateAgentShareSlug('my_bot')).toBe('invalid');+ expect(validateAgentShareSlug('my bot')).toBe('invalid');+ expect(validateAgentShareSlug('-mybot')).toBe('invalid');+ expect(validateAgentShareSlug('mybot-')).toBe('invalid');+ });++ it('rejects UUID-shaped slugs, which would never resolve as a slug', () => {+ expect(validateAgentShareSlug('123e4567-e89b-12d3-a456-426614174000')).toBe('invalid');+ });++ it('rejects reserved words', () => {+ expect(validateAgentShareSlug('settings')).toBe('reserved');+ expect(validateAgentShareSlug('share')).toBe('reserved');+ });++ // Shares live at `/agent/<slug>`, where the creator's own agents always win+ // the lookup, so a share on a builtin slug would be unreachable forever.+ it('rejects every builtin agent slug', () => {+ for (const slug of Object.values(BUILTIN_AGENT_SLUGS)) {+ expect([slug, validateAgentShareSlug(slug)]).toEqual([slug, 'reserved']);+ }+ });+});++describe('buildAgentShareUrl', () => {+ const origin = 'https://app.lobehub.com';++ it('prefers the custom slug', () => {+ expect(buildAgentShareUrl({ origin, shareId: 'share-id', slug: 'my-bot' })).toBe(+ 'https://app.lobehub.com/agent/my-bot',+ );+ });++ it('falls back to the share id', () => {+ expect(buildAgentShareUrl({ origin, shareId: 'share-id' })).toBe(+ 'https://app.lobehub.com/agent/share-id',+ );+ expect(buildAgentShareUrl({ origin, shareId: 'share-id', slug: '' })).toBe(+ 'https://app.lobehub.com/agent/share-id',+ );+ });+});diff --git a/src/features/AgentShareSettings/shareLink.ts b/src/features/AgentShareSettings/shareLink.tsnew file mode 100644index 00000000000..57a6002cc07--- /dev/null+++ b/src/features/AgentShareSettings/shareLink.ts@@ -0,0 +1,46 @@+import { AGENT_SHARE_SLUG_PATTERN, RESERVED_AGENT_SHARE_SLUGS } from '@lobechat/const';++/**+ * Client mirror of `AgentShareModel.updateSlug`'s UUID rejection: a+ * UUID-shaped slug would be unreachable because `findBySlugOrId` resolves+ * UUID-shaped input as a share id before ever trying the slug lookup.+ */+const UUID_PATTERN = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;++export type AgentShareSlugError = 'invalid' | 'reserved' | 'tooLong' | 'tooShort';++/** Slugs are stored lowercase; normalize before validating so the check matches the server's. */+export const normalizeAgentShareSlug = (input: string): string => input.trim().toLowerCase();++/**+ * Client-side mirror of the server's slug rules (`AGENT_SHARE_SLUG_PATTERN` ++ * `RESERVED_AGENT_SHARE_SLUGS` + the UUID guard). The server remains the real+ * gate — this only turns an obviously-invalid slug into inline feedback+ * instead of a round trip. Uniqueness cannot be checked here; a taken slug+ * still comes back as `CONFLICT`.+ *+ * Returns `null` when the normalized slug is acceptable.+ */+export const validateAgentShareSlug = (slug: string): AgentShareSlugError | null => {+ if (slug.length < 3) return 'tooShort';+ if (slug.length > 64) return 'tooLong';+ if (!AGENT_SHARE_SLUG_PATTERN.test(slug) || UUID_PATTERN.test(slug)) return 'invalid';+ if (RESERVED_AGENT_SHARE_SLUGS.includes(slug)) return 'reserved';++ return null;+};++/**+ * Visitor URL for a share. The custom slug is preferred when set, but the raw+ * share id always resolves too — so a link handed out before a slug was chosen+ * keeps working.+ */+export const buildAgentShareUrl = ({+ origin,+ shareId,+ slug,+}: {+ origin: string;+ shareId: string;+ slug?: string;+}): string => `${origin}/agent/${slug || shareId}`;diff --git a/src/features/AgentShareSettings/toolVisitorAvailability.test.ts b/src/features/AgentShareSettings/toolVisitorAvailability.test.tsnew file mode 100644index 00000000000..99ed457bece--- /dev/null+++ b/src/features/AgentShareSettings/toolVisitorAvailability.test.ts@@ -0,0 +1,236 @@+import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';+import { KnowledgeBaseIdentifier } from '@lobechat/builtin-tool-knowledge-base';+import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';+import { MemoryApiName, MemoryIdentifier } from '@lobechat/builtin-tool-memory';+import { describe, expect, it } from 'vitest';++import {+ getShareApiAvailability,+ getShareToolAvailability,+ getVisitorVisibleGrantedToolIds,+ runtimeManagedShareCandidateToolIds,+ setShareToolGrant,+ toggleShareToolApi,+ toggleShareToolsetGrant,+} from './toolVisitorAvailability';++describe('getShareToolAvailability', () => {+ it('blocks builtins the server gate refuses outright', () => {+ // Both survive the master allowlist only to be blocked by+ // DATA_TOOL_ACCESS_RULES' unconditional `none` grant.+ expect(getShareToolAvailability(KnowledgeBaseIdentifier)).toBe('blocked');+ expect(getShareToolAvailability(AgentDocumentsIdentifier)).toBe('blocked');+ });++ it('blocks builtins outside the master allowlist', () => {+ expect(getShareToolAvailability('lobe-local-system')).toBe('blocked');+ // lobe-cloud-sandbox is now allowlisted: a share visitor's run gets its+ // own isolated per-topic sandbox session with no `lh` CLI JWT shim, so+ // it no longer belongs in the "blocked" bucket.+ expect(getShareToolAvailability('lobe-cloud-sandbox')).toBe('available');+ });++ it('leaves non-builtin identifiers to the owner picker', () => {+ expect(getShareToolAvailability('mcp-github')).toBe('available');+ });++ it('flags memory as inert until the read-memory permission is on', () => {+ expect(getShareToolAvailability(MemoryIdentifier)).toBe('needsMemoryPermission');+ expect(getShareToolAvailability(MemoryIdentifier, { allowReadMemory: true })).toBe('available');+ });+});++describe('runtimeManagedShareCandidateToolIds', () => {+ it('never suggests a tool the gate always blocks', () => {+ expect(runtimeManagedShareCandidateToolIds).not.toContain(KnowledgeBaseIdentifier);+ expect(runtimeManagedShareCandidateToolIds).not.toContain('lobe-local-system');+ });+});++describe('getVisitorVisibleGrantedToolIds', () => {+ it('hides persisted grants the gate can never honor', () => {+ expect(+ getVisitorVisibleGrantedToolIds([+ { identifier: 'mcp-github' },+ { identifier: KnowledgeBaseIdentifier },+ { identifier: 'lobe-local-system' },+ ]),+ ).toEqual(['mcp-github']);+ });++ it('tolerates an unset grant list', () => {+ expect(getVisitorVisibleGrantedToolIds(undefined)).toEqual([]);+ });++ it('renders one identifier for a toolset granted only per-API', () => {+ expect(+ getVisitorVisibleGrantedToolIds([+ {+ apis: [LobeAgentApiName.analyzeMedia, LobeAgentApiName.updatePlan],+ identifier: LobeAgentIdentifier,+ },+ ]),+ ).toEqual([LobeAgentIdentifier]);+ });+});++describe('setShareToolGrant', () => {+ it('writes an `apis`-less entry for "all"', () => {+ expect(setShareToolGrant([{ identifier: 'calculator' }], LobeAgentIdentifier, 'all')).toEqual([+ { identifier: 'calculator' },+ { identifier: LobeAgentIdentifier },+ ]);+ });++ it('writes one `apis`-scoped entry for an array grant', () => {+ expect(+ setShareToolGrant(undefined, LobeAgentIdentifier, [LobeAgentApiName.analyzeMedia]),+ ).toEqual([{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }]);+ });++ it('drops the identifier entirely on "none"', () => {+ const stored = [+ { apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier },+ { identifier: 'calculator' },+ ];++ expect(setShareToolGrant(stored, LobeAgentIdentifier, 'none')).toEqual([+ { identifier: 'calculator' },+ ]);+ });++ it('replaces a prior grant for the same identifier rather than accumulating', () => {+ const stored = [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }];++ expect(setShareToolGrant(stored, LobeAgentIdentifier, 'all')).toEqual([+ { identifier: LobeAgentIdentifier },+ ]);+ });+});++describe('toggleShareToolsetGrant', () => {+ it('grants everything when the identifier has no grant yet', () => {+ expect(toggleShareToolsetGrant(undefined, LobeAgentIdentifier)).toEqual([+ { identifier: LobeAgentIdentifier },+ ]);+ });++ it('grants everything when only a partial per-API grant exists', () => {+ const stored = [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }];++ expect(toggleShareToolsetGrant(stored, LobeAgentIdentifier)).toEqual([+ { identifier: LobeAgentIdentifier },+ ]);+ });++ it('revokes entirely when every API is already granted', () => {+ expect(+ toggleShareToolsetGrant([{ identifier: LobeAgentIdentifier }], LobeAgentIdentifier),+ ).toEqual([]);+ });++ it('leaves grants for other identifiers untouched', () => {+ const stored = [+ { apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier },+ { identifier: 'calculator' },+ ];++ expect(toggleShareToolsetGrant(stored, LobeAgentIdentifier)).toEqual([+ { identifier: 'calculator' },+ { identifier: LobeAgentIdentifier },+ ]);+ });+});++describe('toggleShareToolApi', () => {+ const available = [LobeAgentApiName.analyzeMedia, LobeAgentApiName.updatePlan];++ it('adds the first per-API grant for an ungranted identifier', () => {+ expect(+ toggleShareToolApi(undefined, LobeAgentIdentifier, LobeAgentApiName.analyzeMedia, available),+ ).toEqual([{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }]);+ });++ it('expands a toolset-level grant, then narrows it by the toggled API', () => {+ // Toggling one API off a toolset-level ("all") grant must narrow to the+ // REST of the available APIs, not wipe the whole grant.+ expect(+ toggleShareToolApi(+ [{ identifier: LobeAgentIdentifier }],+ LobeAgentIdentifier,+ LobeAgentApiName.analyzeMedia,+ available,+ ),+ ).toEqual([{ apis: [LobeAgentApiName.updatePlan], identifier: LobeAgentIdentifier }]);+ });++ it('stays an explicit `apis` list once every available API is individually selected, rather than collapsing to a toolset-level grant', () => {+ // Least privilege: an `apis`-less entry also grants any API added to this+ // tool LATER (e.g. a plugin update) that the owner never reviewed. Only+ // the toolset chip (`toggleShareToolsetGrant`) may write `'all'`.+ const stored = [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }];++ expect(+ toggleShareToolApi(stored, LobeAgentIdentifier, LobeAgentApiName.updatePlan, available),+ ).toEqual([+ {+ apis: expect.arrayContaining([LobeAgentApiName.analyzeMedia, LobeAgentApiName.updatePlan]),+ identifier: LobeAgentIdentifier,+ },+ ]);+ });++ it('removes the grant entirely once the last selected API is toggled off', () => {+ const stored = [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }];++ expect(+ toggleShareToolApi(stored, LobeAgentIdentifier, LobeAgentApiName.analyzeMedia, available),+ ).toEqual([]);+ });+});++describe('getShareApiAvailability', () => {+ it('blocks callSubAgent on lobe-agent unconditionally', () => {+ expect(getShareApiAvailability(LobeAgentIdentifier, LobeAgentApiName.callSubAgent)).toBe(+ 'blocked',+ );+ });++ it("blocks a 'required'/'always' humanIntervention API", () => {+ expect(+ getShareApiAvailability(LobeAgentIdentifier, LobeAgentApiName.createPlan, 'required'),+ ).toBe('blocked');+ expect(+ getShareApiAvailability(LobeAgentIdentifier, LobeAgentApiName.askUserQuestion, 'always'),+ ).toBe('blocked');+ });++ it('allows an API with no (or "never") humanIntervention', () => {+ expect(getShareApiAvailability(LobeAgentIdentifier, LobeAgentApiName.analyzeMedia)).toBe(+ 'available',+ );+ expect(getShareApiAvailability(LobeAgentIdentifier, LobeAgentApiName.updatePlan, 'never')).toBe(+ 'available',+ );+ });++ // A share grant is read-only at most: the server gate strips every memory+ // write API regardless of what the owner ticked, so the picker must not+ // offer them (regression: owners granted only write APIs and saw no memory+ // tool on the visitor side at all).+ it('reports memory write APIs as writesOwnerData, keeps read APIs available', () => {+ for (const apiName of [+ MemoryApiName.addPreferenceMemory,+ MemoryApiName.updateIdentityMemory,+ MemoryApiName.removeIdentityMemory,+ ]) {+ expect(getShareApiAvailability(MemoryIdentifier, apiName)).toBe('writesOwnerData');+ }+ expect(getShareApiAvailability(MemoryIdentifier, MemoryApiName.searchUserMemory)).toBe(+ 'available',+ );+ expect(getShareApiAvailability(MemoryIdentifier, MemoryApiName.queryTaxonomyOptions)).toBe(+ 'available',+ );+ });+});diff --git a/src/features/AgentShareSettings/toolVisitorAvailability.ts b/src/features/AgentShareSettings/toolVisitorAvailability.tsnew file mode 100644index 00000000000..64b5676915d--- /dev/null+++ b/src/features/AgentShareSettings/toolVisitorAvailability.ts@@ -0,0 +1,240 @@+import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';+import { MEMORY_WRITE_API_NAMES, MemoryIdentifier } from '@lobechat/builtin-tool-memory';+import {+ AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS,+ isAgentShareAllowedBuiltinIdentifier,+ runtimeManagedToolIds,+} from '@lobechat/builtin-tools';+import { resolveShareToolGrants, type ShareToolGrant } from '@lobechat/const';+import type { AgentShareToolGrant, ExtendedHumanInterventionConfig } from '@lobechat/types';++/**+ * How a tool the owner configured on the agent relates to a share visitor's run:+ *+ * - `available` — the owner can grant it and the server gate will honor it.+ * - `blocked` — the server refuses it for visitor runs no matter what is+ * stored, so the owner must not be offered the toggle at all.+ * - `needsMemoryPermission` — the server gate would strip it until the+ * separate "allow reading my memory" permission is on, so the picker keeps+ * the row disabled (with that explanation) rather than accepting a grant+ * that cannot take effect yet.+ */+export type ShareToolAvailability = 'available' | 'blocked' | 'needsMemoryPermission';++/**+ * Mirrors the two server-side gates a visitor tool call passes, in the same+ * order `isShareBlockedDataToolCall` applies them+ * (`apps/server/src/services/aiAgent/shareGate.ts`):+ *+ * 1. `isAgentShareAllowedBuiltinIdentifier` — the master default-deny+ * allowlist. Non-builtin identifiers (MCP servers, market plugins, custom+ * plugins) fall outside its jurisdiction entirely and are governed only by+ * the owner's `toolGrants` picker.+ * 2. `AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS` — tools that survive the+ * allowlist only to be blocked outright by `DATA_TOOL_ACCESS_RULES`, whose+ * grant is unconditionally `none` (knowledge base, agent documents: no such+ * grant exists in `AgentShareConfig` at all).+ *+ * Both sets are exported from `@lobechat/builtin-tools` precisely so this+ * picker reads the same source the gate enforces instead of hand-copying+ * identifiers that could drift.+ */+export const getShareToolAvailability = (+ toolId: string,+ permissions: { allowReadMemory?: boolean } = {},+): ShareToolAvailability => {+ if (!isAgentShareAllowedBuiltinIdentifier(toolId)) return 'blocked';+ if (AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS.has(toolId)) return 'blocked';+ if (toolId === MemoryIdentifier && !permissions.allowReadMemory) return 'needsMemoryPermission';++ return 'available';+};++/** Whether the owner may grant `toolId` to visitors at all (see {@link getShareToolAvailability}). */+export const isToolAvailableToVisitors = (toolId: string): boolean =>+ getShareToolAvailability(toolId) !== 'blocked';++/**+ * `shareConfig.toolGrants` reduced down to the toolset identifiers that should+ * render as an active visitor grant — one entry per identifier, whether it+ * grants every API or only some (see {@link resolveShareToolGrants}). A share+ * edited while a since-denied builtin was still allowed may keep a now-blocked+ * identifier persisted; rendering it as selected would confirm a grant no+ * visitor run can use.+ *+ * PRESENTATION ONLY. Never build a save payload from this — see+ * {@link toggleShareToolsetGrant} / {@link toggleShareToolApi}, which compose+ * over the FULL persisted list so grants this picker does not render survive+ * the write.+ */+export const getVisitorVisibleGrantedToolIds = (+ toolGrants: AgentShareToolGrant[] | undefined,+): string[] =>+ Array.from(resolveShareToolGrants(toolGrants).keys()).filter((identifier) =>+ isToolAvailableToVisitors(identifier),+ );++/**+ * Replace `identifier`'s grant in the PERSISTED list with `grant`: `'all'`+ * writes an entry with no `apis`, an array of API names writes an entry+ * scoped to them, and `'none'` drops the identifier's entry entirely. Always+ * composes over the FULL stored list, same reasoning as+ * {@link toggleShareToolsetGrant} — grants for OTHER identifiers this picker+ * does not render must survive the write.+ */+export const setShareToolGrant = (+ toolGrants: AgentShareToolGrant[] | undefined,+ identifier: string,+ grant: 'all' | 'none' | string[],+): AgentShareToolGrant[] => {+ const withoutIdentifier = (toolGrants ?? []).filter((entry) => entry.identifier !== identifier);++ if (grant === 'none') return withoutIdentifier;+ if (grant === 'all') return [...withoutIdentifier, { identifier }];++ return [...withoutIdentifier, { apis: grant, identifier }];+};++/**+ * Toggle `identifier`'s TOOLSET-level chip. The click cycle is the mature+ * checkbox convention (antd `indeterminate`, Gmail's select-all): none -> all,+ * partial -> all, all -> none. A partial per-API grant therefore always widens+ * to the full toolset on the first click rather than clearing, so one click is+ * never silently destructive of an intent the owner has to rebuild per API.+ *+ * The chip renders the matching tri-state: no grant -> empty box, partial ->+ * indeterminate (minus) box, every API -> checked box.+ */+export const toggleShareToolsetGrant = (+ toolGrants: AgentShareToolGrant[] | undefined,+ identifier: string,+): AgentShareToolGrant[] =>+ resolveShareToolGrants(toolGrants).get(identifier) === 'all'+ ? setShareToolGrant(toolGrants, identifier, 'none')+ : setShareToolGrant(toolGrants, identifier, 'all');++/**+ * Toggle a single `apiName` within `identifier`'s grant, expanding a+ * toolset-level `'all'` grant into its `availableApiNames` first so removing+ * one API narrows to the rest instead of wiping the whole grant.+ * `availableApiNames` must be the identifier's full set of visitor-grantable+ * API names (i.e. excluding ones {@link getShareApiAvailability} reports as+ * `blocked`) — the caller (which already has the manifest) is the only place+ * that set is known.+ *+ * Deliberately does NOT collapse back to a toolset-level `'all'` grant when+ * every currently-available API ends up individually ticked — least+ * privilege: a grant without `apis` also covers any API added to this tool+ * LATER (e.g. a plugin update), which the owner never explicitly reviewed.+ * Only the toolset chip / {@link toggleShareToolsetGrant} writes `'all'`.+ * Still collapses to `'none'` (dropping the identifier entirely) when no API+ * remains selected, so the toolset row's tri-state stays consistent with+ * per-API toggling.+ */+export const toggleShareToolApi = (+ toolGrants: AgentShareToolGrant[] | undefined,+ identifier: string,+ apiName: string,+ availableApiNames: string[],+): AgentShareToolGrant[] => {+ const grant = resolveShareToolGrants(toolGrants).get(identifier);+ const current = new Set(grant === 'all' ? availableApiNames : grant instanceof Set ? grant : []);++ if (current.has(apiName)) current.delete(apiName);+ else current.add(apiName);++ if (current.size === 0) return setShareToolGrant(toolGrants, identifier, 'none');++ return setShareToolGrant(toolGrants, identifier, Array.from(current));+};++/**+ * How one API of an ALREADY-visitor-available toolset relates to a share+ * visitor's run — the per-API counterpart of {@link getShareToolAvailability}.+ * Only meaningful for an identifier that is not itself `blocked` at the+ * toolset level; callers render every API of a blocked toolset as blocked+ * without consulting this.+ *+ * Mirrors two of the server's dispatch-time checks+ * (`isShareBlockedBuiltinDispatch` in `shareGate.ts`) cheaply enough to run in+ * the picker without duplicating server-only rules:+ *+ * 1. `humanIntervention` — every share run is forced onto headless approval,+ * so a `'required'`/`'always'` policy API can never honestly complete (see+ * `isApiUsableForShareVisitor`'s doc in `shareGate.ts`).+ * 2. `callSubAgent` on `lobe-agent` — sub-agent dispatch is unconditionally+ * stripped for share visitors regardless of any grant.+ *+ * 3. Memory write APIs — `DATA_TOOL_ACCESS_RULES` strips them from every+ * visitor run regardless of grant (a share grant is read-only at most).+ * Read from the same `MEMORY_WRITE_API_NAMES` the gate uses, so a new+ * write API cannot be added on one side without the other following.+ *+ * Returns `writesOwnerData` (rather than plain `blocked`) for that last case+ * so the picker can explain *why* instead of showing a generic refusal.+ */+export type ShareApiAvailability = 'available' | 'blocked' | 'writesOwnerData';++export const getShareApiAvailability = (+ identifier: string,+ apiName: string,+ humanIntervention?: ExtendedHumanInterventionConfig,+): ShareApiAvailability => {+ if (identifier === LobeAgentIdentifier && apiName === LobeAgentApiName.callSubAgent) {+ return 'blocked';+ }+ if (identifier === MemoryIdentifier && MEMORY_WRITE_API_NAMES.has(apiName as never)) {+ return 'writesOwnerData';+ }+ if (humanIntervention !== undefined && humanIntervention !== 'never') return 'blocked';++ return 'available';+};++/** Re-exported so callers building a toolset's tri-state can type against it without importing `@lobechat/const` directly. */+export type { ShareToolGrant };++/**+ * `identifier`'s resolved grant from the PERSISTED list: `'all'` for a grant+ * without `apis`, a `Set` of API names for an `apis`-scoped grant, or+ * `undefined` when the identifier has no grant at all. Drives the toolset+ * row's tri-state checkbox and which per-API checkboxes render checked once+ * expanded.+ */+export const getShareToolGrantForIdentifier = (+ toolGrants: AgentShareToolGrant[] | undefined,+ identifier: string,+): ShareToolGrant | undefined => resolveShareToolGrants(toolGrants).get(identifier);++/**+ * Runtime-managed builtin tool identifiers (Knowledge Base, Memory, Web+ * Browsing, ...) that the server's agent mode rules can enable on a run+ * independently of `agentConfig.plugins`. `getActivePluginIds` only reflects+ * the owner's plugin selection, so a picker built from that list alone could+ * never surface these ids — and `applyShareGateToToolSet` strips any tool id+ * absent from `toolGrants`, so e.g. the "allow reading memory" switch+ * would silently have no effect.+ *+ * Filtered through {@link isToolAvailableToVisitors} so tools the gate always+ * refuses (device, local system, sandbox, knowledge base, agent documents)+ * stay out of the picker instead of adding rows the owner cannot act on.+ */+export const runtimeManagedShareCandidateToolIds: string[] = runtimeManagedToolIds.filter(+ (toolId) => isToolAvailableToVisitors(toolId),+);++/**+ * Full candidate set for the share tool picker: the owner's configured+ * plugins plus the runtime-managed builtin tools a share can ever grant.+ * Deduplicated because a runtime-managed tool id may already be pinned in+ * `pluginIds` (e.g. image generation).+ *+ * An always-blocked tool the owner explicitly configured on the agent is still+ * listed — rendered disabled with an explanation, so the owner learns why it+ * cannot be shared instead of wondering where it went. Blocked tools are only+ * omitted when they would have been added by+ * {@link runtimeManagedShareCandidateToolIds}, i.e. when the owner never+ * picked them in the first place.+ */+export const getShareToolCandidateIds = (pluginIds: string[]): string[] =>+ Array.from(new Set([...pluginIds, ...runtimeManagedShareCandidateToolIds]));diff --git a/src/features/AgentShareSettings/useAgentShare.test.ts b/src/features/AgentShareSettings/useAgentShare.test.tsnew file mode 100644index 00000000000..bf93fe13477--- /dev/null+++ b/src/features/AgentShareSettings/useAgentShare.test.ts@@ -0,0 +1,642 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useAgentShare } from './useAgentShare';++const swr = vi.hoisted(() => {+ const listeners = new Set<() => void>();+ const state = { data: undefined as any, error: undefined as any };++ return {+ listeners,+ seed(data: any) {+ state.data = data;+ state.error = undefined;+ },+ seedError(error: any) {+ state.data = undefined;+ state.error = error;+ },+ set(data: any) {+ state.data = data;+ state.error = undefined;+ for (const listener of listeners) listener();+ },+ state,+ };+});++// Stand-in for `useSWR` that keeps the cached row in module scope and+// re-renders subscribers on `mutate`, so the hook's optimistic writes and the+// idle re-sync effect behave as they do in the app.+vi.mock('swr', async () => {+ const React = await import('react');++ return {+ default: () => {+ const [, force] = React.useState(0);++ React.useEffect(() => {+ const listener = () => force((version) => version + 1);+ swr.listeners.add(listener);+ return () => {+ swr.listeners.delete(listener);+ };+ }, []);++ return {+ data: swr.state.data,+ error: swr.state.error,+ isLoading: false,+ mutate: async (input?: any) => {+ // Bare `mutate()` revalidates: re-read through the (mocked) fetcher.+ if (input === undefined) {+ const fresh = await service.getShareStatus();+ if (fresh !== undefined) swr.set(fresh);+ return swr.state.data;+ }+ swr.set(typeof input === 'function' ? input(swr.state.data) : input);+ return swr.state.data;+ },+ };+ },+ };+});++const service = vi.hoisted(() => ({+ disableShare: vi.fn(),+ enableShare: vi.fn(),+ getShareStatus: vi.fn(),+ updateShareConfig: vi.fn(),+ updateSlug: vi.fn(),+ updateVisibility: vi.fn(),+}));++vi.mock('@/services/agentShare', () => ({ agentShareService: service }));++const buildShare = (config: Record<string, unknown> = {}) => ({+ id: 'share-1',+ shareConfig: {+ allowReadMemory: false,+ toolGrants: [],+ maxTopicsPerVisitor: 5,+ maxTurnsPerTopic: 20,+ ...config,+ },+ userViewCount: 0,+ visibility: 'link',+});++beforeEach(() => {+ vi.clearAllMocks();+ swr.seed(buildShare());+ service.updateShareConfig.mockImplementation(async (_agentId: string, patch: any) => ({+ ...buildShare(),+ shareConfig: { ...swr.state.data?.shareConfig, ...patch },+ }));+});++describe('useAgentShare · updateConfig', () => {+ it('composes consecutive functional patches instead of losing the first', async () => {+ // The first write stays in flight while the second is issued — the exact+ // window in which a payload built from the last rendered config would+ // overwrite the earlier toggle.+ let releaseFirst: (value: any) => void = () => {};+ service.updateShareConfig.mockImplementationOnce(+ (_agentId: string, patch: any) =>+ new Promise((resolve) => {+ releaseFirst = () =>+ resolve({ ...buildShare(), shareConfig: { ...buildShare().shareConfig, ...patch } });+ }),+ );++ const { result } = renderHook(() => useAgentShare('agent-1'));++ await act(async () => {+ void result.current.updateConfig((current) => ({+ toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-a' }],+ }));+ void result.current.updateConfig((current) => ({+ toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-b' }],+ }));+ });++ // Only the first request has been issued; the second is queued behind it.+ await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(1));++ await act(async () => {+ releaseFirst(undefined);+ });++ await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(2));++ expect(service.updateShareConfig.mock.calls[0][1]).toEqual({+ toolGrants: [{ identifier: 'tool-a' }],+ });+ expect(service.updateShareConfig.mock.calls[1][1]).toEqual({+ toolGrants: [{ identifier: 'tool-a' }, { identifier: 'tool-b' }],+ });+ });++ it('does not resend a failed write when a later queued write lands (happy-path contrast)', async () => {+ // Paired with the failure regression below: on the happy path, B's+ // outgoing payload still composes on top of A once A is confirmed to+ // have succeeded — the fix must not turn this into a diff-only send.+ let releaseFirst: (value: any) => void = () => {};+ service.updateShareConfig.mockImplementationOnce(+ (_agentId: string, patch: any) =>+ new Promise((resolve) => {+ releaseFirst = () =>+ resolve({ ...buildShare(), shareConfig: { ...buildShare().shareConfig, ...patch } });+ }),+ );++ const { result } = renderHook(() => useAgentShare('agent-1'));++ await act(async () => {+ void result.current.updateConfig((current) => ({+ toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-a' }],+ }));+ void result.current.updateConfig((current) => ({+ toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-b' }],+ }));+ });++ await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(1));++ await act(async () => {+ releaseFirst(undefined);+ });++ await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(2));++ expect(service.updateShareConfig.mock.calls[1][1]).toEqual({+ toolGrants: [{ identifier: 'tool-a' }, { identifier: 'tool-b' }],+ });+ });++ it("does not let A's failed write leak into B's outgoing payload", async () => {+ // A fails outright while B is already queued behind it. Pre-fix, B's+ // payload was baked at CALL time from the optimistic `[A, B]`+ // projection, so it silently re-persisted A's edit server-side even+ // though A's own write was reported failed — because `updateShareConfig`+ // overwrites the whole `toolGrants` array rather than diffing it.+ let rejectFirst: (reason: unknown) => void = () => {};+ service.updateShareConfig.mockImplementationOnce(+ () =>+ new Promise((_resolve, reject) => {+ rejectFirst = reject;+ }),+ );+ service.updateShareConfig.mockImplementationOnce(async (_agentId: string, patch: any) => ({+ ...buildShare(),+ shareConfig: { ...buildShare().shareConfig, ...patch },+ }));++ const { result } = renderHook(() => useAgentShare('agent-1'));++ let editingA: Promise<unknown> = Promise.resolve();+ await act(async () => {+ editingA = result.current.updateConfig((current) => ({+ toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-a' }],+ }));+ void result.current.updateConfig((current) => ({+ toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-b' }],+ }));+ });+ // The queue must not stall on A's eventual rejection.+ editingA.catch(() => undefined);++ await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(1));++ await act(async () => {+ rejectFirst(new Error('write A failed'));+ });++ await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(2));++ // B's outgoing payload must be resolved as if A never happened, not+ // against the optimistic `[A, B]` UI projection A was already baked into.+ expect(service.updateShareConfig.mock.calls[1][1]).toEqual({+ toolGrants: [{ identifier: 'tool-b' }],+ });+ });++ it('does not let an earlier response revert a later queued write before it lands (A/B/C interleaving)', async () => {+ // Reproduces the lost-update window exactly: A is in flight, B is toggled+ // while A is still pending (queued behind it), and A's response lands+ // BEFORE B's request is even sent. Pre-fix, `commitIfCurrent` would+ // unconditionally adopt A's response into `latestConfigRef`, regressing+ // the local projection from [A, B] back to just [A] — so when C is then+ // toggled off that regressed snapshot, C's whole-array write silently+ // drops B server-side once it lands, even though B's own write already+ // succeeded. With the fix, an intermediate response is only adopted once+ // it is the LAST pending write, so the projection (and what the UI reads+ // off SWR) never regresses mid-flight.+ let releaseA: (value: any) => void = () => {};+ let releaseB: (value: any) => void = () => {};+ let releaseC: (value: any) => void = () => {};++ service.updateShareConfig+ .mockImplementationOnce(+ (_agentId: string, patch: any) =>+ new Promise((resolve) => {+ releaseA = () =>+ resolve({ ...buildShare(), shareConfig: { ...buildShare().shareConfig, ...patch } });+ }),+ )+ .mockImplementationOnce(+ (_agentId: string, patch: any) =>+ new Promise((resolve) => {+ releaseB = () =>+ resolve({ ...buildShare(), shareConfig: { ...buildShare().shareConfig, ...patch } });+ }),+ )+ .mockImplementationOnce(+ (_agentId: string, patch: any) =>+ new Promise((resolve) => {+ releaseC = () =>+ resolve({ ...buildShare(), shareConfig: { ...buildShare().shareConfig, ...patch } });+ }),+ );++ const { result } = renderHook(() => useAgentShare('agent-1'));++ await act(async () => {+ void result.current.updateConfig((current) => ({+ toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-a' }],+ }));+ void result.current.updateConfig((current) => ({+ toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-b' }],+ }));+ });++ await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(1));++ await act(async () => {+ releaseA(undefined);+ });+ await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(2));++ // A's response landed while B was still queued — the projection (and the+ // SWR cache the UI reads) must not have regressed back to just A.+ expect(result.current.share?.shareConfig.toolGrants).toEqual([+ { identifier: 'tool-a' },+ { identifier: 'tool-b' },+ ]);++ await act(async () => {+ void result.current.updateConfig((current) => ({+ toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-c' }],+ }));+ });++ await act(async () => {+ releaseB(undefined);+ });+ await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(3));++ await act(async () => {+ releaseC(undefined);+ });++ expect(service.updateShareConfig.mock.calls[0][1]).toEqual({+ toolGrants: [{ identifier: 'tool-a' }],+ });+ expect(service.updateShareConfig.mock.calls[1][1]).toEqual({+ toolGrants: [{ identifier: 'tool-a' }, { identifier: 'tool-b' }],+ });+ // The final persisted patch for C must still contain B — it was never+ // reverted by A's earlier, now-stale response.+ expect(service.updateShareConfig.mock.calls[2][1]).toEqual({+ toolGrants: [{ identifier: 'tool-a' }, { identifier: 'tool-b' }, { identifier: 'tool-c' }],+ });+ expect(result.current.share?.shareConfig.toolGrants).toEqual([+ { identifier: 'tool-a' },+ { identifier: 'tool-b' },+ { identifier: 'tool-c' },+ ]);+ });++ it('keeps granted tools the picker never renders', async () => {+ swr.seed(+ buildShare({+ toolGrants: [{ identifier: 'lobe-local-system' }, { identifier: 'mcp-github' }],+ }),+ );++ const { result } = renderHook(() => useAgentShare('agent-1'));++ await act(async () => {+ await result.current.updateConfig((current) => ({+ toolGrants: [...(current.toolGrants ?? []), { identifier: 'calculator' }],+ }));+ });++ expect(service.updateShareConfig.mock.calls[0][1]).toEqual({+ toolGrants: [+ { identifier: 'lobe-local-system' },+ { identifier: 'mcp-github' },+ { identifier: 'calculator' },+ ],+ });+ });++ it('projects the patch into the cache immediately', async () => {+ const { result } = renderHook(() => useAgentShare('agent-1'));++ await act(async () => {+ await result.current.updateConfig({ maxTurnsPerTopic: 30 });+ });++ expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(30);+ });++ it('keeps the paused row in the cache instead of dropping it', async () => {+ service.disableShare.mockResolvedValue({ ...buildShare(), visibility: 'private' });++ const { result } = renderHook(() => useAgentShare('agent-1'));++ await act(async () => {+ await result.current.disable();+ });++ // Disabling only pauses the share: the row (hence its id and slug) stays,+ // so the same link resumes on the next enable.+ expect(result.current.share?.id).toBe('share-1');+ expect(result.current.share?.visibility).toBe('private');+ });++ it('still lands an edit made while a disable is in flight', async () => {+ let completeDisable: () => void = () => {};+ service.disableShare.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ completeDisable = () => resolve({ ...buildShare(), visibility: 'private' });+ }),+ );++ const { result } = renderHook(() => useAgentShare('agent-1'));++ let disabling: Promise<unknown> = Promise.resolve();+ await act(async () => {+ disabling = result.current.disable();+ });+ await waitFor(() => expect(service.disableShare).toHaveBeenCalledTimes(1));++ // A debounced limit patch flushing on unmount races the disable. The row+ // survives the disable, so the edit must be written, not dropped.+ let editing: Promise<unknown> = Promise.resolve();+ await act(async () => {+ editing = result.current.updateConfig({ maxTurnsPerTopic: 30 });+ });++ await act(async () => {+ completeDisable();+ await disabling;+ await editing;+ });++ expect(service.updateShareConfig).toHaveBeenCalledTimes(1);+ expect(service.updateShareConfig.mock.calls[0][1]).toEqual({ maxTurnsPerTopic: 30 });+ });++ it('re-reads the server after a later queued write fails so a discarded earlier response is not lost', async () => {+ // Disable succeeds but its response is discarded because a slug write is+ // already queued behind it; the slug write then fails. The cache must end+ // up showing the server truth (disabled), not the pre-disable row.+ let completeDisable: () => void = () => {};+ service.disableShare.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ completeDisable = () => resolve({ ...buildShare(), visibility: 'private' });+ }),+ );+ service.updateSlug.mockRejectedValueOnce(new Error('slug taken'));+ service.getShareStatus.mockResolvedValue({ ...buildShare(), visibility: 'private' });++ const { result } = renderHook(() => useAgentShare('agent-1'));++ let disabling: Promise<unknown> = Promise.resolve();+ await act(async () => {+ disabling = result.current.disable();+ });+ await waitFor(() => expect(service.disableShare).toHaveBeenCalledTimes(1));++ let saving: Promise<unknown> = Promise.resolve();+ await act(async () => {+ saving = result.current.updateSlug('new-slug').catch(() => undefined);+ });++ await act(async () => {+ completeDisable();+ await disabling;+ await saving;+ });++ await waitFor(() => expect(result.current.share?.visibility).toBe('private'));+ });++ it('still writes when a disable failed outright', async () => {+ service.disableShare.mockRejectedValue(new Error('nope'));++ const { result } = renderHook(() => useAgentShare('agent-1'));++ await act(async () => {+ await result.current.disable().catch(() => undefined);+ });+ await act(async () => {+ await result.current.updateConfig({ maxTurnsPerTopic: 30 });+ });++ expect(service.updateShareConfig).toHaveBeenCalledTimes(1);+ });+});++describe('useAgentShare · agent identity change', () => {+ // The settings page component is not remounted when navigating between two+ // agents' share pages — it just receives a new `agentId` prop (mirrors+ // `useDebouncedLimitPatch`'s doc). Without the identity guard, a write still+ // in flight for agent A would land its response in the SAME shared+ // `latestConfigRef` agent B's edits derive from.+ it("does not let agent A's in-flight write pollute agent B's config after navigating without unmount", async () => {+ const shareA = buildShare({ maxTurnsPerTopic: 20 });+ const shareB = buildShare({ maxTurnsPerTopic: 99 });+ swr.seed(shareA);++ let releaseA: () => void = () => {};+ service.updateShareConfig.mockImplementationOnce(+ (_agentId: string, patch: any) =>+ new Promise((resolve) => {+ releaseA = () => resolve({ ...shareA, shareConfig: { ...shareA.shareConfig, ...patch } });+ }),+ );++ const { result, rerender } = renderHook(({ agentId }) => useAgentShare(agentId), {+ initialProps: { agentId: 'agent-A' },+ });++ // Kick off an edit on A that stays in flight (server hasn't responded yet).+ let editingA: Promise<unknown> = Promise.resolve();+ await act(async () => {+ editingA = result.current.updateConfig({ maxTurnsPerTopic: 5 });+ });+ await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(1));+ expect(service.updateShareConfig).toHaveBeenNthCalledWith(1, 'agent-A', {+ maxTurnsPerTopic: 5,+ });++ // Navigate to agent B without unmounting. Simulate SWR's own key switch+ // resolving to B's row (a real key change would trigger a fresh fetch).+ act(() => {+ rerender({ agentId: 'agent-B' });+ });+ act(() => {+ swr.set(shareB);+ });++ // B's server snapshot must be adopted — not blocked behind A's pending+ // write count, which belongs to a hook instance the component reused.+ expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(99);++ // The next edit on B must derive its patch from B's config (99), not from+ // whatever `latestConfigRef` held for A.+ service.updateShareConfig.mockImplementationOnce(async (_agentId: string, patch: any) => ({+ ...shareB,+ shareConfig: { ...shareB.shareConfig, ...patch },+ }));+ await act(async () => {+ await result.current.updateConfig((current) => ({+ maxTurnsPerTopic: (current.maxTurnsPerTopic ?? 0) + 1,+ }));+ });+ expect(service.updateShareConfig).toHaveBeenNthCalledWith(2, 'agent-B', {+ maxTurnsPerTopic: 100,+ });+ expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(100);++ // A's stale write finally resolves — its response must be dropped rather+ // than clobbering the config B's edits now derive from.+ await act(async () => {+ releaseA();+ await editingA;+ });+ expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(100);+ });++ // Comparing the bare `agentId` string is not enough: after an A → B → A+ // round trip the hook tracks `agent-A` again, so a write issued under the+ // FIRST visit would pass an id-only check, decrement the second visit's+ // pending-write counter, and adopt its stale response over edits issued+ // after the return. Each write must be pinned to an identity generation.+ it("drops agent A's write from a previous visit after navigating A → B → A", async () => {+ const shareA = buildShare({ maxTurnsPerTopic: 20 });+ const shareB = buildShare({ maxTurnsPerTopic: 99 });+ swr.seed(shareA);++ let releaseFirst: () => void = () => {};+ service.updateShareConfig.mockImplementationOnce(+ (_agentId: string, patch: any) =>+ new Promise((resolve) => {+ releaseFirst = () =>+ resolve({ ...shareA, shareConfig: { ...shareA.shareConfig, ...patch } });+ }),+ );++ const { result, rerender } = renderHook(({ agentId }) => useAgentShare(agentId), {+ initialProps: { agentId: 'agent-A' },+ });++ // First visit to A: an edit that stays in flight across the round trip.+ let firstEdit: Promise<unknown> = Promise.resolve();+ await act(async () => {+ firstEdit = result.current.updateConfig({ maxTurnsPerTopic: 5 });+ });+ await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(1));++ // A → B → A without unmount; SWR resolves each key switch to its row.+ act(() => {+ rerender({ agentId: 'agent-B' });+ });+ act(() => {+ swr.set(shareB);+ });+ act(() => {+ rerender({ agentId: 'agent-A' });+ });+ act(() => {+ swr.set(shareA);+ });+ expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(20);++ // Second visit to A: a new edit whose request also stays in flight, so the+ // first visit's late response has a pending write to race against.+ let releaseSecond: () => void = () => {};+ service.updateShareConfig.mockImplementationOnce(+ (_agentId: string, patch: any) =>+ new Promise((resolve) => {+ releaseSecond = () =>+ resolve({ ...shareA, shareConfig: { ...shareA.shareConfig, ...patch } });+ }),+ );+ let secondEdit: Promise<unknown> = Promise.resolve();+ await act(async () => {+ secondEdit = result.current.updateConfig({ maxTurnsPerTopic: 8 });+ });+ await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(2));+ expect(service.updateShareConfig).toHaveBeenNthCalledWith(2, 'agent-A', {+ maxTurnsPerTopic: 8,+ });+ expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(8);++ // The FIRST visit's response lands while the second edit is still+ // pending. It must be dropped: the optimistic 8 stays, not the stale 5.+ await act(async () => {+ releaseFirst();+ await firstEdit;+ });+ expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(8);++ // The second edit's own response is still adopted normally — proving the+ // pending-write counter was not corrupted by the late first response.+ await act(async () => {+ releaseSecond();+ await secondEdit;+ });+ expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(8);++ // With the queue drained, a server re-seed is adopted again (idle path):+ // the counter is back at zero rather than negative or stuck.+ act(() => {+ swr.set(buildShare({ maxTurnsPerTopic: 42 }));+ });+ expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(42);+ service.updateShareConfig.mockImplementationOnce(async (_agentId: string, patch: any) => ({+ ...shareA,+ shareConfig: { ...shareA.shareConfig, ...patch },+ }));+ await act(async () => {+ await result.current.updateConfig((current) => ({+ maxTurnsPerTopic: (current.maxTurnsPerTopic ?? 0) + 1,+ }));+ });+ expect(service.updateShareConfig).toHaveBeenNthCalledWith(3, 'agent-A', {+ maxTurnsPerTopic: 43,+ });+ });+});++describe('useAgentShare · getShareStatus failure', () => {+ it('exposes the fetch error instead of swallowing it', () => {+ const fetchError = new Error('network down');+ swr.seedError(fetchError);++ const { result } = renderHook(() => useAgentShare('agent-1'));++ expect(result.current.error).toBe(fetchError);+ expect(result.current.share).toBeUndefined();+ });+});diff --git a/src/features/AgentShareSettings/useAgentShare.ts b/src/features/AgentShareSettings/useAgentShare.tsnew file mode 100644index 00000000000..26c7f3be512--- /dev/null+++ b/src/features/AgentShareSettings/useAgentShare.ts@@ -0,0 +1,338 @@+import { useCallback, useEffect, useRef } from 'react';+import useSWR from 'swr';++import { shareKeys } from '@/libs/swr/keys';+import type { AgentShareConfigPatchInput } from '@/services/agentShare';+import { agentShareService } from '@/services/agentShare';++import { mergeShareConfig } from './shareConfigPatch';++export type AgentShareInfo = Awaited<ReturnType<typeof agentShareService.getShareStatus>>;+/** Server-normalized share config (every optional field already defaulted). */+export type AgentShareConfigState = NonNullable<AgentShareInfo>['shareConfig'];++/**+ * A config patch, or a function producing one from the LATEST known config.+ * Use the function form for any edit derived from the current value (toggling+ * a tool in `toolGrants`, say) — a plain object captures whatever the+ * component rendered with, which is stale the moment a previous write is+ * still in flight.+ */+export type AgentShareConfigPatch =+ AgentShareConfigPatchInput | ((current: AgentShareConfigState) => AgentShareConfigPatchInput);++/**+ * Creator-side share state for one agent.+ *+ * Unlike a topic share, sharing an agent lets link holders RUN it on the+ * creator's account, so nothing is created until the owner explicitly turns+ * sharing on. `enable` mints (or republishes) the row with `link` visibility;+ * `disable` only flips it back to `private`, keeping the share id and slug so+ * the same url resumes on the next enable (see `AgentShareModel`).+ */+export const useAgentShare = (agentId: string) => {+ const {+ data: share,+ error,+ isLoading,+ mutate,+ } = useSWR(shareKeys.agentShareStatus(agentId), () => agentShareService.getShareStatus(agentId), {+ revalidateOnFocus: false,+ });++ /**+ * The config as it will be once every write issued so far has landed —+ * `undefined` while unknown, `null` once the share row is known to be gone.+ * A functional patch's UI-facing preview resolves against THIS at CALL+ * time, so two edits fired before the first response composes visually+ * rather than the second overwriting the first. It does NOT drive the+ * network payload any more — see `sendConfigRef` for why the two had to+ * split.+ */+ const latestConfigRef = useRef<AgentShareConfigState | null | undefined>(undefined);+ /**+ * Mirrors `latestConfigRef`, but only ever advances/rolls back at SEND+ * time, inside a queued `updateConfig` task — never at call time. This is+ * what a functional patch's OUTGOING payload resolves against.+ *+ * Why call-time resolution isn't enough: say two functional edits are+ * queued back to back — toggle tool A (sends `toolGrants: [A]`), then+ * toggle tool B. If B's payload were baked at call time from+ * `latestConfigRef` (which already includes A's optimistic projection),+ * it would resolve to `[A, B]` regardless of what happens to A's write.+ * If A's request then FAILS, the server never persisted A — but the queue+ * still sends B's already-baked `[A, B]`, silently re-persisting A anyway.+ * `mergeShareConfig` / `AgentShareModel.updateConfig` overwrite whole+ * jsonb keys rather than diffing them, so B's write can't just apply a+ * delta on top of whatever the server actually has; it sends the full+ * array it was told to send.+ *+ * Resolving each patch against `sendConfigRef` at SEND time instead fixes+ * this: `enqueue` serializes writes strictly (a queued task's body does+ * not start until every earlier task has fully settled), so by the time+ * B's task runs, A's outcome is already known. A success advances+ * `sendConfigRef` to include A; a failure rolls it back to exclude A+ * (see the `catch` branch in `updateConfig`) — either way B resolves its+ * patch against the config the server will actually see, so a failed A+ * never leaks into B's request.+ */+ const sendConfigRef = useRef<AgentShareConfigState | null | undefined>(undefined);+ const pendingWritesRef = useRef(0);++ /**+ * `agentId` identity this hook instance is currently tracking. The owning+ * settings page component is NOT remounted when navigating between two+ * agents' share pages (it just receives a new `agentId` prop), so every ref+ * above survives the switch unless reset here — mirrors the pattern in+ * `useDebouncedLimitPatch`.+ */+ const identityRef = useRef(agentId);+ /**+ * Monotonic counter bumped on every `agentId` change. Comparing the bare+ * `agentId` string is not enough to tell a stale write from a current one:+ * after an A → B → A round trip `identityRef` reads `A` again, so a write+ * issued under the FIRST A (still in flight, its counter already zeroed by+ * the reset below) would pass an id-only check and decrement the second+ * A's `pendingWritesRef` — possibly below zero — and `commitIfCurrent`+ * would adopt its stale response over edits issued after the return. Each+ * write captures the generation it was issued under and compares against+ * this instead, so the two A's are distinct.+ */+ const generationRef = useRef(0);+ /**+ * Every mutation replaces the whole row in the SWR cache, so two writes that+ * resolve out of order would let the older response win — see `enqueue`+ * below. Declared here (rather than next to `enqueue`) so the identity-change+ * reset can null it out too.+ */+ const queueRef = useRef<Promise<unknown> | null>(null);++ // `agentId` changed since the last render: reset adoption state right away+ // (render-time, not in an effect) so the idle-adoption effect below picks+ // up the NEW agent's server snapshot on its very next run instead of+ // staying blocked behind the OLD agent's still-in-flight write count.+ // Comparing against `identityRef` (rather than unconditionally resetting+ // every render) makes this idempotent under StrictMode's render+ // double-invocation, same as `useDebouncedLimitPatch`.+ //+ // `queueRef` is also cut loose (set to `null`, not awaited/drained): the+ // NEXT write — now for the new agent — must not queue behind whatever A+ // still has in flight, since that write targets an entirely different SWR+ // key/resource and there is no ordering to preserve across the two. A's own+ // promise chain keeps running independently; its resolution is simply+ // ignored by `commitIfCurrent` once `identityRef` no longer matches (see+ // below), so nothing is lost — the request already landed server-side.+ if (identityRef.current !== agentId) {+ identityRef.current = agentId;+ generationRef.current += 1;+ latestConfigRef.current = undefined;+ sendConfigRef.current = undefined;+ pendingWritesRef.current = 0;+ queueRef.current = null;+ }++ // Only adopt a server snapshot while idle: mid-flight it would be older than+ // the local projection above. Keep both refs in lockstep — an idle re-seed+ // is a fresh confirmed baseline, so there is no pending edit for+ // `sendConfigRef` to preserve over it either.+ useEffect(() => {+ if (pendingWritesRef.current > 0) return;+ const next = share === undefined ? undefined : (share?.shareConfig ?? null);+ latestConfigRef.current = next;+ sendConfigRef.current = next;+ }, [share]);++ /**+ * Apply a write's server response to the shared refs only if the identity+ * generation hasn't moved since the write was issued. A write started for agent A+ * can still resolve after navigating to agent B (this hook instance is+ * reused, not remounted) — its resolved value must be dropped instead of+ * clobbering `latestConfigRef`/the SWR cache entry B's edits now derive+ * from. The network write itself is never cancelled: A's request already+ * landed server-side by the time this runs; only the LOCAL bookkeeping is+ * skipped.+ *+ * Also skipped while a LATER write is still queued or in flight+ * (`pendingWritesRef.current > 1`, this write itself included). Every+ * write — from `updateConfig` to `enable`/`disable`/`updateSlug` — is+ * serialized through the same `queueRef` chain, but each one's outgoing+ * patch is computed synchronously at call time from `latestConfigRef`, not+ * re-derived when it actually sends. If an EARLIER write's response were+ * adopted here while a later write is still pending, it would regress+ * `latestConfigRef` back to a snapshot older than what the later write's+ * patch was already built from — and because `mergeShareConfig` /+ * `AgentShareModel.updateConfig` overwrite whole jsonb keys rather than+ * diffing them, the later write's request would then silently REVERT the+ * edit this response is trying to confirm once it lands. Only the LAST+ * pending write's response is guaranteed to reflect every earlier write's+ * effect (the server processes them in the same serial order they were+ * sent), so only it is allowed to update the shared refs / SWR cache.+ */+ const commitIfCurrent = useCallback(+ async (writeGeneration: number, updated: AgentShareInfo) => {+ if (generationRef.current !== writeGeneration) return;+ if (pendingWritesRef.current > 1) return;+ latestConfigRef.current = updated?.shareConfig ?? null;+ // The server response reflects every write processed so far, so it is+ // also a fresh confirmed baseline for `sendConfigRef` — any patch still+ // resolving against it from here composes on top of a value the server+ // agrees with, not a locally-mirrored guess.+ sendConfigRef.current = latestConfigRef.current;+ await mutate(updated, { revalidate: false });+ },+ [mutate],+ );++ const enqueue = useCallback(<T>(task: () => Promise<T>): Promise<T> => {+ const tail = queueRef.current ?? Promise.resolve();+ // Both handlers run `task`: a failed write must reject its own caller+ // without stalling the writes queued behind it.+ const result = tail.then(task, task);+ queueRef.current = result.catch(() => undefined);+ return result;+ }, []);++ /**+ * Wrap a queued write with pending-write accounting, shared by every write+ * (`enable`/`disable`/`updateConfig`/`updateSlug`) so `commitIfCurrent` can+ * tell whether its own response is the last one outstanding — see its+ * comment above. Increments as soon as the write is issued (covers time+ * spent queued behind an earlier write, not just its own network round+ * trip) and decrements once it settles either way.+ *+ * The task receives the identity generation it was issued under, so it can+ * hand that to `commitIfCurrent` / its own late identity checks.+ */+ const runWrite = useCallback(+ <T>(task: (generation: number) => Promise<T>): Promise<T> => {+ const generation = generationRef.current;+ pendingWritesRef.current += 1;+ return enqueue(() => task(generation))+ .finally(() => {+ // The reset on identity change already zeroed this counter for the+ // NEW generation; a write issued under an OLD one must not decrement+ // it again once it settles late.+ if (generationRef.current === generation) pendingWritesRef.current -= 1;+ })+ .catch((error) => {+ // A failed write may have been the LAST one queued, in which case+ // `commitIfCurrent` already discarded every earlier write's response+ // on the assumption that this one would carry their combined effect.+ // Nothing else will refresh the cache (focus revalidation is off), so+ // re-read the server truth here; the idle re-sync effect re-seeds+ // `latestConfigRef` once the queue drains. Skipped once the identity+ // generation has moved on — that `mutate` belongs to another agent+ // (or an earlier visit to this one).+ if (generationRef.current === generation) void mutate();+ throw error;+ });+ },+ [enqueue, mutate],+ );++ const enable = useCallback(+ () =>+ runWrite(async (generation) => {+ // `create` returns any pre-existing row untouched, so a legacy+ // `private` row still needs the explicit flip to `link`.+ const created = await agentShareService.enableShare(agentId, 'link');+ const updated =+ created.visibility === 'link'+ ? created+ : await agentShareService.updateVisibility(agentId, 'link');+ await commitIfCurrent(generation, updated);+ }),+ [agentId, commitIfCurrent, runWrite],+ );++ const updateConfig = useCallback(+ (patch: AgentShareConfigPatch) => {+ const base = latestConfigRef.current;+ // Nothing loaded yet, or this agent has no share row at all — there is+ // nothing to write against. (Turning sharing OFF does not land here: the+ // row survives as `private`, so its config stays editable.)+ if (!base) return Promise.resolve();++ const uiPatch = typeof patch === 'function' ? patch(base) : patch;+ // Project the patch locally right away, so the control reflects the edit+ // immediately AND the next patch composes on top of this one. This is a+ // UI-only preview — the outgoing network payload is resolved separately+ // below, at send time, against `sendConfigRef` (see its doc comment).+ latestConfigRef.current = mergeShareConfig(base, uiPatch);+ const optimisticConfig = latestConfigRef.current;+ void mutate(+ (current) => (current ? { ...current, shareConfig: optimisticConfig } : current),+ {+ revalidate: false,+ },+ );++ return runWrite(async (generation) => {+ // Resolve the OUTGOING payload now, not at call time: `enqueue`+ // guarantees no earlier queued write's task body is still running by+ // the time this one starts, so `sendConfigRef` already reflects every+ // earlier write's real outcome (advanced on success, rolled back on+ // failure) instead of the optimistic UI projection above, which+ // cannot un-bake a since-failed edit once composed into it.+ //+ // Skip touching the shared ref once the identity generation has moved+ // on (this task belongs to an abandoned identity, per+ // `commitIfCurrent`'s doc): fall+ // back to the call-time `base` this closure already captured, which+ // reproduces the pre-fix behavior for that edge case instead of+ // reading/mutating a ref that now belongs to a different agent.+ const forCurrentIdentity = generationRef.current === generation;+ // `sendConfigRef.current` is only ever `null`/`undefined` in lockstep+ // with `latestConfigRef` (see both refs' reset points above), and+ // `base` already proved non-null via the guard at the top of this+ // callback — so falling back to `base` here also keeps `sendBase`+ // non-null for `patch`'s functional form.+ const sendBase = forCurrentIdentity ? (sendConfigRef.current ?? base) : base;+ const resolved = typeof patch === 'function' ? patch(sendBase) : patch;+ if (forCurrentIdentity) sendConfigRef.current = mergeShareConfig(sendBase, resolved);++ try {+ const updated = await agentShareService.updateShareConfig(agentId, resolved);+ await commitIfCurrent(generation, updated);+ } catch (error) {+ // Roll back this write's contribution so the NEXT queued write's+ // send-time resolution does not see it. Re-check identity rather+ // than reusing `forCurrentIdentity`: it may have changed while the+ // request was in flight, in which case `sendConfigRef` now belongs+ // to a different agent and must be left alone.+ if (generationRef.current === generation) sendConfigRef.current = sendBase;+ // The optimistic projection is dropped by the server re-read that+ // `runWrite` issues for every failed write.+ throw error;+ }+ });+ },+ [agentId, commitIfCurrent, runWrite],+ );++ /**+ * Pause sharing. The row survives as `private`, so nothing local needs+ * invalidating: an edit issued in the same tick (a debounced limit patch+ * flushed on unmount, say) simply queues behind this write and lands on the+ * row it was always meant for.+ */+ const disable = useCallback(+ () =>+ runWrite(async (generation) => {+ const disabled = await agentShareService.disableShare(agentId);+ await commitIfCurrent(generation, disabled);+ }),+ [agentId, commitIfCurrent, runWrite],+ );++ const updateSlug = useCallback(+ (slug: string | null) =>+ runWrite(async (generation) => {+ const updated = await agentShareService.updateSlug(agentId, slug);+ await commitIfCurrent(generation, updated);+ }),+ [agentId, commitIfCurrent, runWrite],+ );++ return { disable, enable, error, isLoading, mutate, share, updateConfig, updateSlug };+};diff --git a/src/features/AgentShareSettings/useAgentShareSupported.test.ts b/src/features/AgentShareSettings/useAgentShareSupported.test.tsnew file mode 100644index 00000000000..b2c4f4f81c8--- /dev/null+++ b/src/features/AgentShareSettings/useAgentShareSupported.test.ts@@ -0,0 +1,172 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { resolveLinkToggleState, useAgentShareSupported } from './useAgentShareSupported';++const testState = vi.hoisted(() => ({+ /** What `getShareStatus` resolves to for the non-publishable lookup. */+ shareStatus: null as { visibility: 'link' | 'private' } | null,+ enableAgentShare: undefined as boolean | undefined,+ enableBusinessFeatures: true,+ hasActiveWorkspace: false,+ isBuiltinAgent: false,+}));++vi.mock('swr', () => ({+ default: (key: unknown, fetcher: () => unknown) => ({+ data: key ? fetcher() : undefined,+ }),+}));++vi.mock('@/libs/swr/keys', () => ({+ shareKeys: { agentShareStatus: (agentId: string) => ['share:agentShareStatus', agentId] },+}));++vi.mock('@/services/agentShare', () => ({+ agentShareService: { getShareStatus: () => testState.shareStatus },+}));++vi.mock('@/business/client/hooks/useHasActiveWorkspace', () => ({+ useHasActiveWorkspace: () => testState.hasActiveWorkspace,+}));++vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (state: unknown) => unknown) => selector(undefined),+}));++vi.mock('@/store/agent/selectors', () => ({+ builtinAgentSelectors: {+ isBuiltinAgent: () => () => testState.isBuiltinAgent,+ },+}));++vi.mock('@/store/serverConfig', () => ({+ useServerConfigStore: (selector: (state: typeof testState) => unknown) => selector(testState),+}));++vi.mock('@/store/serverConfig/selectors', () => ({+ featureFlagsSelectors: (state: typeof testState) => ({+ enableAgentShare: state.enableAgentShare,+ }),+ serverConfigSelectors: {+ enableBusinessFeatures: (state: typeof testState) => state.enableBusinessFeatures,+ },+}));++describe('useAgentShareSupported', () => {+ beforeEach(() => {+ testState.enableAgentShare = undefined;+ testState.enableBusinessFeatures = true;+ testState.hasActiveWorkspace = false;+ testState.isBuiltinAgent = false;+ testState.shareStatus = null;+ });++ it('is unsupported without an agentId', () => {+ const { result } = renderHook(() => useAgentShareSupported(undefined));++ expect(result.current).toEqual({ publishable: false, supported: false, visible: false });+ });++ it('is unsupported for a workspace agent, regardless of the flags', () => {+ testState.hasActiveWorkspace = true;++ const { result } = renderHook(() => useAgentShareSupported('agent-1'));++ expect(result.current).toEqual({ publishable: false, supported: false, visible: false });+ });++ it('is unsupported for a builtin agent', () => {+ testState.isBuiltinAgent = true;++ const { result } = renderHook(() => useAgentShareSupported('agent-1'));++ expect(result.current.supported).toBe(false);+ });++ // Structural: an OSS deployment has no Agent Share surface at all,+ // server-enforced by `ENABLE_BUSINESS_FEATURES` — unlike `enableAgentShare`+ // below, this must hide the whole surface, not just block publishing.+ it('is unsupported on a deployment without business features, even with the rollout flag on', () => {+ testState.enableBusinessFeatures = false;+ testState.enableAgentShare = true;++ const { result } = renderHook(() => useAgentShareSupported('agent-1'));++ expect(result.current).toEqual({ publishable: false, supported: false, visible: false });+ });++ it('is supported but not publishable while the rollout flag is unresolved', () => {+ testState.enableAgentShare = undefined;++ const { result } = renderHook(() => useAgentShareSupported('agent-1'));++ expect(result.current).toEqual({ publishable: false, supported: true, visible: false });+ });++ // Outside the allowlist with nothing live: no entry at all — the tab, the+ // header action and the settings deep link all key off `visible`.+ it('hides the entry when the rollout flag is off and no share exists', () => {+ testState.enableAgentShare = false;++ const { result } = renderHook(() => useAgentShareSupported('agent-1'));++ expect(result.current).toEqual({ publishable: false, supported: true, visible: false });+ });++ it('hides the entry when the rollout flag is off and the share is already revoked', () => {+ testState.enableAgentShare = false;+ testState.shareStatus = { visibility: 'private' };++ const { result } = renderHook(() => useAgentShareSupported('agent-1'));++ expect(result.current).toEqual({ publishable: false, supported: true, visible: false });+ });++ // An owner rolled back out of the allowlist keeps the entry for a live share+ // so it stays revocable (the server keeps `disable` open for this case).+ it('keeps the entry for a live share when the rollout flag is off', () => {+ testState.enableAgentShare = false;+ testState.shareStatus = { visibility: 'link' };++ const { result } = renderHook(() => useAgentShareSupported('agent-1'));++ expect(result.current).toEqual({ publishable: false, supported: true, visible: true });+ });++ it('is publishable and visible when every gate passes', () => {+ testState.enableAgentShare = true;++ const { result } = renderHook(() => useAgentShareSupported('agent-1'));++ expect(result.current).toEqual({ publishable: true, supported: true, visible: true });+ });+});++describe('resolveLinkToggleState', () => {+ it('allows publishing when the account has the capability', () => {+ expect(resolveLinkToggleState({ isShared: false, publishable: true })).toEqual({+ canPublish: true,+ disabled: false,+ offHintKey: 'share.settings.link.offHint',+ });+ });++ it('blocks publishing and explains why when the account may not publish', () => {+ expect(resolveLinkToggleState({ isShared: false, publishable: false })).toEqual({+ canPublish: false,+ disabled: true,+ offHintKey: 'share.settings.link.publishDisabled',+ });+ });++ // The regression this gate exists for: an owner rolled back out of the+ // rollout must still be able to revoke a share they already published, which+ // is why the server keeps `agentShare.disable` open while the flag is off.+ it('keeps an already published share togglable when publishing is blocked', () => {+ const state = resolveLinkToggleState({ isShared: true, publishable: false });++ expect(state.disabled).toBe(false);+ expect(state.canPublish).toBe(true);+ });+});diff --git a/src/features/AgentShareSettings/useAgentShareSupported.ts b/src/features/AgentShareSettings/useAgentShareSupported.tsnew file mode 100644index 00000000000..0611168009e--- /dev/null+++ b/src/features/AgentShareSettings/useAgentShareSupported.ts@@ -0,0 +1,106 @@+'use client';++import useSWR from 'swr';++import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';+import { shareKeys } from '@/libs/swr/keys';+import { agentShareService } from '@/services/agentShare';+import { useAgentStore } from '@/store/agent';+import { builtinAgentSelectors } from '@/store/agent/selectors';+import { useServerConfigStore } from '@/store/serverConfig';+import { featureFlagsSelectors, serverConfigSelectors } from '@/store/serverConfig/selectors';++export interface AgentShareSupport {+ /**+ * Whether a *new* share may be published right now. Mirrors the server gate+ * on `agentShare.enableShare` / `updateVisibility → 'link'`; every other+ * mutation (disable, config, slug) stays open server-side on purpose.+ */+ publishable: boolean;+ /** Whether the share management surface applies to this agent at all. */+ supported: boolean;+ /**+ * Whether the share entry (profile tab, header action, settings page) should+ * be shown to this account: `true` when it may publish OR already has a live+ * share to revoke, `false` when neither, `undefined` while the live-share+ * lookup for a non-publishable account is still resolving.+ */+ visible: boolean | undefined;+}++/**+ * Whether this agent can be shared as a public link at all — the capability+ * half of the gate only, deliberately excluding the caller's edit permission so+ * every entry point (header action, tab switcher, the page itself) can combine+ * it with the `canConfigure` check it already computes.+ *+ * Agent sharing is personal-only — `agentShares` rows can never exist for a+ * workspace agent (see `AgentShareModel`'s ownership check) — and a builtin row+ * (Inbox, the builders) is not the owner's to hand out.+ *+ * `supported` additionally requires `enableBusinessFeatures`: a self-hosted+ * (OSS) deployment has no Agent Share surface at all — it is structurally+ * blocked server-side by `ENABLE_BUSINESS_FEATURES`+ * (`_helpers/agentShareFeatureGate.ts`).+ *+ * `enableAgentShare` (the CLOUD grayscale rollout flag) does NOT narrow+ * `supported` either: the server keeps disable / updateConfig / updateSlug /+ * getShareStatus open when that flag is off, so an owner rolled back out of+ * the allowlist with a live share must still be able to revoke it. Instead the+ * flag drives two derived values — `publishable` (fails closed on anything+ * other than `true`, mirroring the server's `assertAgentShareCreationEnabled`)+ * and `visible` (publishable, or a live share to revoke) — so an account+ * outside the allowlist with nothing live sees no share entry at all.+ */+export const useAgentShareSupported = (agentId?: string | null): AgentShareSupport => {+ const hasActiveWorkspace = useHasActiveWorkspace();+ const isBuiltinAgent = useAgentStore(builtinAgentSelectors.isBuiltinAgent(agentId ?? undefined));+ const enableAgentShare = useServerConfigStore(featureFlagsSelectors).enableAgentShare;+ const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);++ const supported = !!agentId && !hasActiveWorkspace && !isBuiltinAgent && enableBusinessFeatures;+ const publishable = supported && enableAgentShare === true;++ // Outside the rollout allowlist the entry is hidden entirely — unless a live+ // share already exists, which the owner must still be able to reach and+ // revoke. The status lookup only runs for that non-publishable case, so the+ // allowlisted majority pays nothing extra here.+ const { data: share } = useSWR(+ supported && !publishable && agentId ? shareKeys.agentShareStatus(agentId) : null,+ () => agentShareService.getShareStatus(agentId!),+ { revalidateOnFocus: false },+ );++ let visible: boolean | undefined;+ if (!supported) visible = false;+ else if (publishable) visible = true;+ else if (share !== undefined) visible = share?.visibility === 'link';++ return { publishable, supported, visible };+};++/**+ * How the link on/off switch behaves under the publish gate.+ *+ * Only *publishing* is blocked: a share that is already live must stay+ * togglable so its owner can revoke it after losing the capability (the server+ * keeps `agentShare.disable` open for exactly that case).+ */+export const resolveLinkToggleState = ({+ isShared,+ publishable,+}: {+ isShared: boolean;+ publishable: boolean;+}) => {+ const publishBlocked = !publishable && !isShared;++ return {+ /** Blocks the `off → on` direction, never `on → off`. */+ canPublish: !publishBlocked,+ disabled: publishBlocked,+ offHintKey: publishBlocked+ ? ('share.settings.link.publishDisabled' as const)+ : ('share.settings.link.offHint' as const),+ };+};diff --git a/src/features/AgentShareSettings/useDebouncedLimitPatch.test.ts b/src/features/AgentShareSettings/useDebouncedLimitPatch.test.tsnew file mode 100644index 00000000000..f3708c34e9b--- /dev/null+++ b/src/features/AgentShareSettings/useDebouncedLimitPatch.test.ts@@ -0,0 +1,191 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { resolveLimitCommitTarget, useDebouncedLimitPatch } from './useDebouncedLimitPatch';++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+});++describe('useDebouncedLimitPatch', () => {+ it('merges both fields into one patch after the delay', () => {+ const commit = vi.fn();+ const { result } = renderHook(() => useDebouncedLimitPatch('agent-1', commit));++ act(() => {+ result.current({ maxTopicsPerVisitor: 3 });+ result.current({ maxTurnsPerTopic: 9 });+ vi.advanceTimersByTime(500);+ });++ expect(commit).toHaveBeenCalledTimes(1);+ expect(commit).toHaveBeenCalledWith({ maxTopicsPerVisitor: 3, maxTurnsPerTopic: 9 }, 'agent-1');+ });++ it('keeps the newest value for a field edited twice', () => {+ const commit = vi.fn();+ const { result } = renderHook(() => useDebouncedLimitPatch('agent-1', commit));++ act(() => {+ result.current({ maxTurnsPerTopic: 9 });+ result.current({ maxTurnsPerTopic: 11 });+ vi.advanceTimersByTime(500);+ });++ expect(commit).toHaveBeenCalledWith({ maxTurnsPerTopic: 11 }, 'agent-1');+ });++ it('flushes a pending patch on unmount so a fast close does not lose the edit', () => {+ const commit = vi.fn();+ const { result, unmount } = renderHook(() => useDebouncedLimitPatch('agent-1', commit));++ act(() => {+ result.current({ maxTopicsPerVisitor: 4 });+ });+ expect(commit).not.toHaveBeenCalled();++ act(() => {+ unmount();+ });++ expect(commit).toHaveBeenCalledWith({ maxTopicsPerVisitor: 4 }, 'agent-1');+ });++ it('does not commit again on unmount once the timer already fired', () => {+ const commit = vi.fn();+ const { result, unmount } = renderHook(() => useDebouncedLimitPatch('agent-1', commit));++ act(() => {+ result.current({ maxTopicsPerVisitor: 4 });+ vi.advanceTimersByTime(500);+ });+ act(() => {+ unmount();+ });++ expect(commit).toHaveBeenCalledTimes(1);+ });++ it('settles the caller even when the commit rejects', async () => {+ const commit = vi.fn().mockRejectedValue(new Error('save failed'));+ const settled = vi.fn();+ const { result } = renderHook(() => useDebouncedLimitPatch('agent-1', commit, settled));++ act(() => {+ result.current({ maxTurnsPerTopic: 7 });+ vi.advanceTimersByTime(500);+ });+ await act(async () => {+ await vi.runAllTimersAsync();+ });++ expect(settled).toHaveBeenCalledWith({ maxTurnsPerTopic: 7 });+ });++ it('flushes a pending patch through the previous identity onCommit when the identity changes, never through the new one', () => {+ // Regression: the share settings page is not remounted when navigating+ // agent A's share page -> agent B's, so without identity scoping A's+ // still-pending edit would flush through B's onCommit within the debounce+ // window instead of A's.+ const commitA = vi.fn();+ const commitB = vi.fn();++ const { result, rerender } = renderHook(+ ({ agentId, commit }) => useDebouncedLimitPatch(agentId, commit),+ { initialProps: { agentId: 'agent-a', commit: commitA } },+ );++ act(() => {+ result.current({ maxTopicsPerVisitor: 4 });+ });+ expect(commitA).not.toHaveBeenCalled();++ act(() => {+ rerender({ agentId: 'agent-b', commit: commitB });+ });++ expect(commitA).toHaveBeenCalledWith({ maxTopicsPerVisitor: 4 }, 'agent-a');+ expect(commitB).not.toHaveBeenCalled();++ // Nothing pending should carry over: advancing time after the identity+ // switch must not trigger anything for either agent.+ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(commitA).toHaveBeenCalledTimes(1);+ expect(commitB).not.toHaveBeenCalled();+ });++ it('reports the PREVIOUS identity to onCommit when the identity change triggers the flush', () => {+ // The caller needs the owning identity to route the write: agent A's patch+ // must not go through the shared queue that has already re-scoped to B.+ const commit = vi.fn();+ const { result, rerender } = renderHook(+ ({ agentId }) => useDebouncedLimitPatch(agentId, commit),+ {+ initialProps: { agentId: 'agent-a' },+ },+ );++ act(() => {+ result.current({ maxTurnsPerTopic: 6 });+ });+ act(() => {+ rerender({ agentId: 'agent-b' });+ });++ expect(commit).toHaveBeenCalledWith({ maxTurnsPerTopic: 6 }, 'agent-a');+ });++ it('reports the current identity for a patch scheduled after the switch', () => {+ const commit = vi.fn();+ const { result, rerender } = renderHook(+ ({ agentId }) => useDebouncedLimitPatch(agentId, commit),+ {+ initialProps: { agentId: 'agent-a' },+ },+ );++ act(() => {+ rerender({ agentId: 'agent-b' });+ });+ act(() => {+ result.current({ maxTurnsPerTopic: 8 });+ vi.advanceTimersByTime(500);+ });++ expect(commit).toHaveBeenCalledTimes(1);+ expect(commit).toHaveBeenCalledWith({ maxTurnsPerTopic: 8 }, 'agent-b');+ });++ it('reports the current identity on the unmount flush', () => {+ const commit = vi.fn();+ const { result, unmount } = renderHook(() => useDebouncedLimitPatch('agent-1', commit));++ act(() => {+ result.current({ maxTopicsPerVisitor: 2 });+ });+ act(() => {+ unmount();+ });++ expect(commit).toHaveBeenCalledWith({ maxTopicsPerVisitor: 2 }, 'agent-1');+ });+});++describe('resolveLimitCommitTarget', () => {+ it('routes a patch owned by the rendered agent through the shared queue', () => {+ expect(resolveLimitCommitTarget('agent-a', 'agent-a')).toBe('current');+ });++ it('routes a patch owned by an abandoned agent to its own write path', () => {+ expect(resolveLimitCommitTarget('agent-a', 'agent-b')).toBe('previous');+ });+});diff --git a/src/features/AgentShareSettings/useDebouncedLimitPatch.ts b/src/features/AgentShareSettings/useDebouncedLimitPatch.tsnew file mode 100644index 00000000000..ac84aae86c0--- /dev/null+++ b/src/features/AgentShareSettings/useDebouncedLimitPatch.ts@@ -0,0 +1,100 @@+import { useCallback, useEffect, useRef } from 'react';++import type { AgentShareConfigPatchInput } from '@/services/agentShare';++export type AgentShareLimitField = 'maxTopicsPerVisitor' | 'maxTurnsPerTopic' | 'monthlySpendLimit';+export type AgentShareLimitPatch = Pick<AgentShareConfigPatchInput, AgentShareLimitField>;++const LIMIT_COMMIT_DELAY = 500;++/**+ * Which write path a flushed patch belongs to, given the identity the patch was+ * scheduled under and the identity the component currently renders.+ *+ * `'previous'` means the flush was triggered BY the identity change itself, so+ * the patch belongs to the agent that was just navigated away from and must not+ * go through the (already re-scoped) shared write queue.+ */+export const resolveLimitCommitTarget = (+ commitIdentity: string,+ currentIdentity: string,+): 'current' | 'previous' => (commitIdentity === currentIdentity ? 'current' : 'previous');++/**+ * Debounces the numeric limit inputs into a single patch and flushes it on+ * unmount. One shared pending patch keeps one field from cancelling another,+ * and the unmount flush keeps closing the modal right after typing from+ * discarding the last valid edit.+ *+ * `identityKey` scopes the pending patch to whatever it was created for+ * (typically the agent id). The settings page component is not remounted when+ * navigating between two agents' share pages — it just receives new props, so+ * without this the refs below would carry agent A's still-pending edit into+ * agent B's `onCommit`. See {@link flush}'s call from the identity-change+ * check for how the previous identity's edit is drained before that happens.+ *+ * `onCommit` therefore receives the identity the patch was scheduled under as+ * its second argument — the PREVIOUS one when the flush was triggered by an+ * identity change. Callers must route such a patch to that identity's own+ * write path instead of the (already re-scoped) shared one; see+ * {@link resolveLimitCommitTarget}.+ */+export const useDebouncedLimitPatch = (+ identityKey: string,+ onCommit: (patch: AgentShareLimitPatch, commitIdentity: string) => Promise<void> | void,+ onSettled?: (patch: AgentShareLimitPatch) => void,+) => {+ const onCommitRef = useRef(onCommit);+ const onSettledRef = useRef(onSettled);+ const pendingRef = useRef<AgentShareLimitPatch>({});+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const identityRef = useRef(identityKey);++ const flush = useCallback(() => {+ if (timerRef.current) clearTimeout(timerRef.current);+ timerRef.current = null;++ const patch = pendingRef.current;+ pendingRef.current = {};+ if (Object.keys(patch).length === 0) return;++ const settle = onSettledRef.current;+ // Not `identityKey`: `flush` is called from the identity-change check+ // BEFORE `identityRef` is advanced, so this is exactly the identity the+ // pending patch was scheduled under in every call path.+ const commitIdentity = identityRef.current;+ void Promise.resolve(onCommitRef.current(patch, commitIdentity))+ .catch(() => undefined)+ .finally(() => settle?.(patch));+ }, []);++ // `identityKey` changed since the last render (e.g. navigating agent A's+ // share page -> agent B's without this component unmounting): drain+ // whatever is pending through the PREVIOUS identity's `onCommit`/`onSettled`+ // — both refs below still hold them here, since they are not reassigned+ // until right after. Comparing against `identityRef` (rather than+ // unconditionally flushing every render) makes this idempotent under+ // StrictMode's render double-invocation — the refs persist across the two+ // calls, so the second sees `identityRef.current === identityKey` already+ // and is a no-op.+ if (identityRef.current !== identityKey) {+ flush();+ identityRef.current = identityKey;+ }++ onCommitRef.current = onCommit;+ onSettledRef.current = onSettled;++ useEffect(() => flush, [flush]);++ const schedule = useCallback(+ (patch: AgentShareLimitPatch) => {+ pendingRef.current = { ...pendingRef.current, ...patch };+ if (timerRef.current) clearTimeout(timerRef.current);+ timerRef.current = setTimeout(flush, LIMIT_COMMIT_DELAY);+ },+ [flush],+ );++ return schedule;+};diff --git a/src/features/AgentShareSettings/useShareUsage.test.ts b/src/features/AgentShareSettings/useShareUsage.test.tsnew file mode 100644index 00000000000..e0bfe5b08ba--- /dev/null+++ b/src/features/AgentShareSettings/useShareUsage.test.ts@@ -0,0 +1,77 @@+/**+ * @vitest-environment happy-dom+ */+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useShareUsage } from './useShareUsage';++const swrState = vi.hoisted(() => ({+ data: undefined as any,+ error: undefined as unknown,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+}));++vi.mock('swr', () => ({ default: () => swrState }));+vi.mock('@/services/agentShare', () => ({ agentShareService: { getShareStats: vi.fn() } }));+vi.mock('@/libs/swr/keys', () => ({+ shareKeys: { agentShareStats: (agentId: string) => ['share:agentShareStats', agentId] },+}));++const stats = {+ monthlySpend: 4,+ monthlySpendLimit: 10,+ topicCount: 1,+ userViewCount: 2,+ visitorCount: 1,+};++describe('useShareUsage', () => {+ beforeEach(() => {+ swrState.data = undefined;+ swrState.error = undefined;+ swrState.isLoading = false;+ });++ // A failed roll-up used to fall through to `0 / 0 / 0`, which reads as a+ // genuine "nobody used it, nothing was spent" claim.+ it('surfaces a load error instead of zero usage when the stats request fails', () => {+ swrState.error = new Error('boom');++ const { result } = renderHook(() => useShareUsage('agent-1'));++ expect(result.current.hasLoadError).toBe(true);+ expect(result.current.data).toBeUndefined();+ });++ it('keeps showing stale stats while a revalidation fails', () => {+ swrState.data = stats;+ swrState.error = new Error('boom');++ const { result } = renderHook(() => useShareUsage('agent-1'));++ expect(result.current.hasLoadError).toBe(false);+ expect(result.current.spend).toBe(4);+ });++ // The stats payload carries its own copy of the cap under a different SWR+ // key that the owner's edits never invalidate; the live configured value+ // from the share-status cache must win so the label tracks the edit.+ it('prefers the live configured cap over the copy in the stats payload', () => {+ swrState.data = stats;++ const { result } = renderHook(() => useShareUsage('agent-1', 25));++ expect(result.current.limit).toBe(25);+ });++ it('falls back to the cap reported by the stats payload', () => {+ swrState.data = stats;++ const { result } = renderHook(() => useShareUsage('agent-1'));++ expect(result.current.limit).toBe(10);+ });+});diff --git a/src/features/AgentShareSettings/useShareUsage.ts b/src/features/AgentShareSettings/useShareUsage.tsnew file mode 100644index 00000000000..df5f526fdb9--- /dev/null+++ b/src/features/AgentShareSettings/useShareUsage.ts@@ -0,0 +1,37 @@+import useSWR from 'swr';++import { shareKeys } from '@/libs/swr/keys';+import { agentShareService } from '@/services/agentShare';++/**+ * Loads the share usage roll-up and resolves which spend cap to display.+ *+ * @param monthlySpendLimit The cap as currently configured in `LimitsSection`,+ * from the share-status cache the owner's edits write to. The stats payload+ * carries its own copy, but that lives under a different SWR key that no+ * edit invalidates, so the label and bar would keep the OLD cap until a+ * reload without it.+ */+export const useShareUsage = (agentId: string, monthlySpendLimit?: number) => {+ const { data, error, isLoading, isValidating, mutate } = useSWR(+ shareKeys.agentShareStats(agentId),+ () => agentShareService.getShareStats(agentId),+ { revalidateOnFocus: false },+ );++ return {+ data,+ error,+ // A failed roll-up must not read as "no traffic, nothing spent": zeros+ // there are a money claim, so the failure has to stay visible.+ hasLoadError: !!error && !data,+ isLoading: isLoading && !data,+ isValidating,+ // Every share carries a cap, so this is only ever absent while the stats+ // request is still in flight.+ limit: monthlySpendLimit ?? data?.monthlySpendLimit,+ mutate,+ // `null` means this deployment does not meter share spend.+ spend: data?.monthlySpend ?? null,+ };+};diff --git a/src/features/AgentShareVisitor/LegacyRedirect.tsx b/src/features/AgentShareVisitor/LegacyRedirect.tsxnew file mode 100644index 00000000000..8ad6c37275c--- /dev/null+++ b/src/features/AgentShareVisitor/LegacyRedirect.tsx@@ -0,0 +1,21 @@+'use client';++import { memo } from 'react';+import { Navigate, useLocation, useParams } from 'react-router';++/**+ * The agent-share visitor surface moved from `/share/agent/:slugOrId` to+ * `/agent/:slugOrId`. Links handed out before the move are permanent, so the+ * old pattern stays registered and forwards in-app navigations; the edge+ * middleware issues the equivalent 301 for cold loads.+ */+const AgentShareLegacyRedirect = memo(() => {+ const { slugOrId } = useParams<{ slugOrId: string }>();+ const { hash, search } = useLocation();++ return <Navigate replace to={`/agent/${slugOrId ?? ''}${search}${hash}`} />;+});++AgentShareLegacyRedirect.displayName = 'AgentShareLegacyRedirect';++export default AgentShareLegacyRedirect;diff --git a/src/features/AgentShareVisitor/Page.tsx b/src/features/AgentShareVisitor/Page.tsxnew file mode 100644index 00000000000..97345830c8a--- /dev/null+++ b/src/features/AgentShareVisitor/Page.tsx@@ -0,0 +1,173 @@+'use client';++import { agentDisplayName } from '@lobechat/types';+import { Center, Flexbox } from '@lobehub/ui';+import { ActionIcon, Avatar, Button, Drawer, Text } from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';+import { PanelLeftOpen } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate, useParams } from 'react-router';++import AsyncError from '@/components/AsyncError';+import CircleLoading from '@/components/Loading/CircleLoading';+import { useIsMobile } from '@/hooks/useIsMobile';++import { resolveShareAccessState, SHARE_ACCESS_ERROR_KEYS } from './resolveShareAccessState';+import { isShareInteractive } from './shareInteractivity';+import TopicPanel from './TopicPanel';+import { useSharedAgent } from './useSharedAgent';+import VisitorConversation from './VisitorConversation';++const SIDEBAR_WIDTH = 260;++/**+ * Visitor landing page of an agent share (`/agent/:slugOrId`): topic list on+ * the left (a drawer on mobile), the shared agent's conversation on the right.+ * Deliberately a trimmed shell — no agent switcher, task list, working sidebar,+ * terminal, or model picker.+ *+ * The share surface shares its route with the creator's own agent page, so the+ * param is the agent route's `aid`; `AgentRouteSwitch` decides which of the two+ * a given value belongs to.+ */+const AgentShareVisitorPage = memo(() => {+ const { t } = useTranslation('agent');+ const { aid: slugOrId } = useParams<{ aid: string }>();+ const navigate = useNavigate();+ const isMobile = useIsMobile();+ const [drawerOpen, setDrawerOpen] = useState(false);++ const { data, error, isLoading, mutate } = useSharedAgent(slugOrId);++ if (isLoading && !data) return <CircleLoading />;++ if (error || !data) {+ const state = resolveShareAccessState(error);++ if (state === 'signIn') {+ const signInUrl = `/signin?callbackUrl=${encodeURIComponent(`/agent/${slugOrId ?? ''}`)}`;++ return (+ <Center gap={16} height={'100%'} padding={24}>+ <Text fontSize={16} weight={600}>+ {t('share.visitor.access.signInTitle')}+ </Text>+ <Text style={{ maxWidth: 360, textAlign: 'center' }} type={'secondary'}>+ {t('share.visitor.access.signInDesc')}+ </Text>+ <Button href={signInUrl} size={'large'} type={'primary'}>+ {t('share.visitor.access.signInCta')}+ </Button>+ </Center>+ );+ }++ const title =+ state === 'generic'+ ? undefined+ : t(SHARE_ACCESS_ERROR_KEYS[state] as 'share.visitor.access.notFound');++ return (+ <Center height={'100%'} padding={24}>+ <AsyncError+ error={error}+ title={title}+ variant={'page'}+ // A missing / forbidden share never becomes available by retrying,+ // so there is no `onRetry` for those states — the `action` button+ // below is the visitor's only way out of the dead end.+ action={+ state === 'generic' ? undefined : (+ <Button size={'small'} onClick={() => navigate('/')}>+ {t('share.visitor.access.backHome')}+ </Button>+ )+ }+ onRetry={state === 'generic' ? () => void mutate() : undefined}+ />+ </Center>+ );+ }++ const interactive = isShareInteractive(data.visibility);++ return (+ <Flexbox horizontal flex={1} height={'100%'} style={{ overflow: 'hidden' }} width={'100%'}>+ {!isMobile && (+ <Flexbox+ style={{ borderInlineEnd: `1px solid ${cssVar.colorBorderSecondary}` }}+ width={SIDEBAR_WIDTH}+ >+ <TopicPanel enabled={interactive} shareId={data.shareId} />+ </Flexbox>+ )}+ <Flexbox flex={1} style={{ overflow: 'hidden' }}>+ <Flexbox+ horizontal+ align={'center'}+ gap={8}+ padding={12}+ style={{ borderBlockEnd: `1px solid ${cssVar.colorBorderSecondary}` }}+ >+ {isMobile && (+ <ActionIcon+ icon={PanelLeftOpen}+ title={t('share.visitor.topics.title')}+ onClick={() => setDrawerOpen(true)}+ />+ )}+ <Avatar+ avatar={data.agentMeta.avatar ?? undefined}+ background={data.agentMeta.backgroundColor ?? undefined}+ size={28}+ />+ <Flexbox flex={1} style={{ overflow: 'hidden' }}>+ <Text ellipsis weight={500}>+ {agentDisplayName(data.agentMeta)}+ </Text>+ {data.agentMeta.description && (+ <Text ellipsis fontSize={12} type={'secondary'}>+ {data.agentMeta.description}+ </Text>+ )}+ </Flexbox>+ </Flexbox>+ {/* Always shown, never dismissible: the visitor is chatting inside the+ creator's account, so "the creator may be able to read this" is a+ standing fact about the surface, not a one-time tip. */}+ <Flexbox+ paddingBlock={6}+ paddingInline={12}+ style={{ background: cssVar.colorFillQuaternary }}+ >+ <Text fontSize={12} type={'secondary'}>+ {t('share.visitor.privacyNotice')}+ </Text>+ </Flexbox>+ <VisitorConversation data={data} />+ </Flexbox>+ {isMobile && (+ <Drawer+ open={drawerOpen}+ placement={'left'}+ title={t('share.visitor.topics.title')}+ width={280}+ onClose={() => setDrawerOpen(false)}+ >+ {/* The Drawer already renders the title bar — skip the panel's own. */}+ <TopicPanel+ enabled={interactive}+ shareId={data.shareId}+ showTitle={false}+ onSelect={() => setDrawerOpen(false)}+ />+ </Drawer>+ )}+ </Flexbox>+ );+});++AgentShareVisitorPage.displayName = 'AgentShareVisitorPage';++export default AgentShareVisitorPage;diff --git a/src/features/AgentShareVisitor/ReadOnlyConversationArea.tsx b/src/features/AgentShareVisitor/ReadOnlyConversationArea.tsxnew file mode 100644index 00000000000..fa674410570--- /dev/null+++ b/src/features/AgentShareVisitor/ReadOnlyConversationArea.tsx@@ -0,0 +1,67 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { memo, useMemo } from 'react';++import ReadOnlyAgentHome from '@/features/AgentHome/ReadOnly';+import { ChatList, ConversationProvider } from '@/features/Conversation';+import { useOperationState } from '@/hooks/useOperationState';+import { useChatStore } from '@/store/chat';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++interface ReadOnlyConversationAreaProps {+ agentId: string;+ agentShareId: string;+ /** The visitor's currently opened share topic; absent on the new-topic surface. */+ topicId?: string | null;+}++/**+ * Read-only shared-agent message surface.+ *+ * This intentionally does not import the owner's ConversationArea: that surface+ * statically owns the composer, dispatchers, and runtime watchers. Keeping the+ * visitor path separate prevents those owner-scoped side effects (agent+ * switching, tasks, working sidebar, terminal) from mounting on a share page.+ */+const ReadOnlyConversationArea = memo<ReadOnlyConversationAreaProps>(+ ({ agentId, agentShareId, topicId }) => {+ const context = useMemo(+ () => ({ agentId, agentShareId, scope: 'main' as const, topicId: topicId ?? undefined }),+ [agentId, agentShareId, topicId],+ );+ const chatKey = useMemo(() => messageMapKey(context), [context]);+ const replaceMessages = useChatStore((state) => state.replaceMessages);+ const messages = useChatStore((state) => state.dbMessagesMap[chatKey]);+ // Same feed the owner surface uses (`ConversationArea.tsx`). Without it the+ // per-conversation store stays on the all-false default, so the list never+ // sees "generating": the assistant placeholder renders nothing and the+ // streaming fade-in (`useChatMarkdown`'s `animated`) is permanently off,+ // which is what made visitor output look choppy.+ const operationState = useOperationState(context);++ return (+ <ConversationProvider+ context={context}+ hasInitMessages={!!messages}+ messages={messages}+ operationState={operationState}+ onMessagesChange={(nextMessages, nextContext, meta) => {+ replaceMessages(nextMessages, { context: nextContext, source: meta?.source });+ }}+ >+ <Flexbox+ flex={1}+ style={{ overflowX: 'hidden', overflowY: 'auto', position: 'relative' }}+ width={'100%'}+ >+ <ChatList disableActionsBar welcome={<ReadOnlyAgentHome />} />+ </Flexbox>+ </ConversationProvider>+ );+ },+);++ReadOnlyConversationArea.displayName = 'ReadOnlyConversationArea';++export default ReadOnlyConversationArea;diff --git a/src/features/AgentShareVisitor/TopicPanel.tsx b/src/features/AgentShareVisitor/TopicPanel.tsxnew file mode 100644index 00000000000..a071184fdb2--- /dev/null+++ b/src/features/AgentShareVisitor/TopicPanel.tsx@@ -0,0 +1,125 @@+'use client';++import { Center, Flexbox, SkeletonTitle } from '@lobehub/ui';+import { ActionIcon, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { MessageSquarePlus } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import { useChatStore } from '@/store/chat';++import { getTopicPanelViewState } from './topicPanelViewState';+import { isTopicRowActivationKey } from './topicRowActivation';+import { useVisitorTopics } from './useVisitorTopics';++/** Placeholder rows shown while the visitor's topic list is loading, sized like a typical topic title. */+const LOADING_ROW_WIDTHS = ['80%', '55%', '68%'];++const styles = createStaticStyles(({ css }) => ({+ row: css`+ cursor: pointer;+ border-radius: 6px;++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: -1px;+ }+ `,+ rowActive: css`+ background: ${cssVar.colorFillSecondary};+ `,+}));++/**+ * The visitor's topic list under the current share (server-scoped by+ * senderId). Selecting a topic drives the chat store's activeTopicId — the+ * same signal the conversation surface and composer key off.+ */+const TopicPanel = memo<{+ /** Off for a non-interactive share (owner preview): skips the fetch that would only 403. */+ enabled?: boolean;+ onSelect?: () => void;+ shareId: string;+ showTitle?: boolean;+}>(({ enabled = true, onSelect, shareId, showTitle = true }) => {+ const { t } = useTranslation('agent');+ const activeTopicId = useChatStore((s) => s.activeTopicId);+ const { data: topics, error, isLoading, mutate } = useVisitorTopics(shareId, enabled);+ const viewState = getTopicPanelViewState(topics, error, isLoading);++ const selectTopic = (topicId?: string) => {+ useChatStore.setState({ activeTopicId: topicId }, false, 'AgentShareVisitor/selectTopic');+ onSelect?.();+ };++ return (+ <Flexbox gap={8} height={'100%'} padding={12} style={{ overflowY: 'auto' }}>+ <Flexbox horizontal align={'center'} justify={'space-between'}>+ {showTitle && (+ <Text fontSize={12} type={'secondary'} weight={500}>+ {t('share.visitor.topics.title')}+ </Text>+ )}+ <ActionIcon+ icon={MessageSquarePlus}+ size={'small'}+ title={t('share.visitor.topics.new')}+ onClick={() => selectTopic(undefined)}+ />+ </Flexbox>+ {viewState === 'error' ? (+ <Center flex={1}>+ <AsyncError error={error} variant={'inline'} onRetry={() => mutate()} />+ </Center>+ ) : viewState === 'loading' ? (+ <Flexbox gap={4}>+ {LOADING_ROW_WIDTHS.map((width, index) => (+ <Flexbox key={index} paddingBlock={6} paddingInline={8}>+ <SkeletonTitle style={{ marginBottom: 0, width }} />+ </Flexbox>+ ))}+ </Flexbox>+ ) : viewState === 'empty' ? (+ <Center flex={1}>+ <Text fontSize={12} type={'secondary'}>+ {t('share.visitor.topics.empty')}+ </Text>+ </Center>+ ) : (+ (topics ?? []).map((topic) => {+ const active = topic.id === activeTopicId;+ return (+ <Flexbox+ aria-current={active || undefined}+ className={cx(styles.row, active && styles.rowActive)}+ key={topic.id}+ paddingBlock={6}+ paddingInline={8}+ role={'button'}+ tabIndex={0}+ onClick={() => selectTopic(topic.id)}+ onKeyDown={(e) => {+ // Mirror native button keyboard semantics for the div-as-button row.+ if (!isTopicRowActivationKey(e.key)) return;+ // Space's default action scrolls the page; Enter has no default+ // action on a non-form div, so only Space needs suppressing.+ if (e.key === ' ') e.preventDefault();+ selectTopic(topic.id);+ }}+ >+ <Text ellipsis fontSize={13}>+ {topic.title || t('share.visitor.topics.untitled')}+ </Text>+ </Flexbox>+ );+ })+ )}+ </Flexbox>+ );+});++TopicPanel.displayName = 'ShareVisitorTopicPanel';++export default TopicPanel;diff --git a/src/features/AgentShareVisitor/VisitorComposer.tsx b/src/features/AgentShareVisitor/VisitorComposer.tsxnew file mode 100644index 00000000000..823ff78a1e6--- /dev/null+++ b/src/features/AgentShareVisitor/VisitorComposer.tsx@@ -0,0 +1,188 @@+'use client';++import { SHARE_VISITOR_PROMPT_MAX_LENGTH } from '@lobechat/const';+import { Flexbox, TextArea } from '@lobehub/ui';+import { ActionIcon, Text } from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';+import { CircleStop, SendHorizonal } from 'lucide-react';+import { memo, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import { useIMECompositionEvent } from '@/hooks/useIMECompositionEvent';+import { useChatStore } from '@/store/chat';+import { operationSelectors } from '@/store/chat/selectors';++import { shouldSubmitOnEnter } from './composerEnterGuard';+import { isTerminalVisitorError, resolveVisitorErrorKey } from './resolveVisitorErrorKey';+import { sendVisitorMessage } from './sendVisitorMessage';+import { useShareRunStop } from './useShareRunStop';++interface VisitorComposerProps {+ agentId: string;+ /**+ * Copy key of a standing block (e.g. the share is no longer link-visible).+ * When set the composer is disabled and the reason is shown persistently —+ * sending would only fail server-side anyway.+ */+ blockedKey?: string;+ /** Refresh the visitor topic list after a send created a new topic. */+ onTopicCreated?: (topicId: string) => void;+ shareId: string;+ topicId?: string | null;+}++/**+ * Lean visitor composer for shared agents. Intentionally NOT the owner+ * composer graph: no uploads (v1 rejects them server-side anyway), no+ * mentions, no model switcher, no device targets — just text in,+ * gateway-streamed answer out.+ */+const VisitorComposer = memo<VisitorComposerProps>(+ ({ agentId, blockedKey, onTopicCreated, shareId, topicId }) => {+ const { t } = useTranslation('agent');+ const [value, setValue] = useState('');+ const [errorKey, setErrorKey] = useState<string>();+ const [sending, setSending] = useState(false);+ const { stopError, stopping, stopSharedRun } = useShareRunStop(shareId, agentId, topicId);+ const { compositionProps, isComposingRef } = useIMECompositionEvent();++ const isStreaming = useChatStore(+ // messageMapKey ignores agentShareId — the running check keys off the+ // same main_<agentId>_<topicId> bucket the share run registers under.+ operationSelectors.isAgentRuntimeRunningByContext({+ agentId,+ scope: 'main',+ topicId,+ }),+ );+ // A per-attempt failure belongs to the topic it happened in — the turn-limit+ // copy even tells the visitor to start a new conversation, so it must not+ // follow them there. Share-level failures (paused / deleted) do survive:+ // they are true for every topic.+ useEffect(() => {+ setErrorKey((prev) => (prev && isTerminalVisitorError(prev) ? prev : undefined));+ }, [topicId]);++ const busy = sending || isStreaming;+ // A share that stopped accepting traffic mid-session blocks the composer the+ // same way an up-front `blockedKey` does, instead of letting the visitor+ // resend into a guaranteed rejection.+ const blocked =+ blockedKey ?? (errorKey && isTerminalVisitorError(errorKey) ? errorKey : undefined);+ const displayedErrorKey = blocked ?? errorKey;++ const send = async () => {+ const message = value.trim();+ if (!message || busy || blocked) return;++ setErrorKey(undefined);+ setSending(true);+ setValue('');+ try {+ const result = await sendVisitorMessage({ agentId, message, shareId, topicId });+ if (result.topicId && !topicId) onTopicCreated?.(result.topicId);+ } catch (error) {+ console.error('[AgentShareVisitor] send failed:', error);+ setErrorKey(resolveVisitorErrorKey(error));+ // Give the rejected input back so the visitor can retry / edit.+ setValue(message);+ } finally {+ setSending(false);+ }+ };++ return (+ <Flexbox gap={4} paddingBlock={8} paddingInline={12}>+ {displayedErrorKey && (+ <Text fontSize={12} type={'danger'}>+ {t(displayedErrorKey as any, {+ // i18next's generated interpolation types default `{{max}}` to+ // `string` (no `{{max, number}}` format specifier), so pass a+ // string even though the source constant is numeric. Ignored by+ // every other error key (i18next drops unused options).+ max: String(SHARE_VISITOR_PROMPT_MAX_LENGTH),+ })}+ </Text>+ )}+ {!!stopError && (+ <AsyncError+ error={stopError}+ retrying={stopping}+ title={t('share.visitor.errors.stopFailed')}+ variant="inline"+ onRetry={() => void stopSharedRun()}+ />+ )}+ <Flexbox+ horizontal+ // Center the single-line state (the textarea is shorter than the send+ // button, so the text would otherwise hug the bottom edge); once the+ // textarea grows it becomes the tallest child and the button pins to+ // the bottom via its own alignSelf.+ align={'center'}+ gap={8}+ style={{+ background: cssVar.colorFillQuaternary,+ border: `1px solid ${cssVar.colorBorderSecondary}`,+ borderRadius: 12,+ padding: '6px 6px 6px 12px',+ }}+ >+ <TextArea+ autoSize={{ maxRows: 6, minRows: 1 }}+ disabled={!!blocked}+ // Mirrors `SHARE_VISITOR_PROMPT_MAX_LENGTH` (the server-side gate in+ // `apps/server/src/routers/lambda/shareChat.ts`) so a legitimate+ // long paste is capped up front instead of round-tripping to a+ // rejection. Convenience only — a direct RPC caller still hits the+ // server bound, handled by `resolveVisitorErrorKey`.+ maxLength={SHARE_VISITOR_PROMPT_MAX_LENGTH}+ placeholder={t('share.visitor.input.placeholder')}+ style={{ border: 'none', boxShadow: 'none', padding: 0 }}+ value={value}+ variant={'borderless'}+ onChange={(e) => setValue(e.target.value)}+ {...compositionProps}+ onPressEnter={(e) => {+ if (!shouldSubmitOnEnter(e, isComposingRef.current)) return;+ e.preventDefault();+ void send();+ }}+ />+ {isStreaming || stopping ? (+ // A run is actually streaming (as opposed to `sending`, the brief+ // window before the server has even created the operation) — show+ // Stop instead of a plain spinner so a long or unwanted run can be+ // cut off before it keeps burning the creator's share budget.+ // `stopSharedRun` flips the operation's `isAborting` flag as soon as+ // the request goes out, which makes `isStreaming` go false before+ // the interrupt has actually resolved — keep showing Stop (loading)+ // through `stopping` so the button doesn't flicker back to Send.+ <ActionIcon+ disabled={stopping}+ icon={CircleStop}+ loading={stopping}+ style={{ alignSelf: 'flex-end' }}+ title={t('share.visitor.input.stop')}+ onClick={() => void stopSharedRun()}+ />+ ) : (+ <ActionIcon+ disabled={busy || !!blocked || !value.trim()}+ icon={SendHorizonal}+ loading={busy}+ style={{ alignSelf: 'flex-end' }}+ title={t('share.visitor.input.send')}+ onClick={() => void send()}+ />+ )}+ </Flexbox>+ </Flexbox>+ );+ },+);++VisitorComposer.displayName = 'ShareVisitorComposer';++export default VisitorComposer;diff --git a/src/features/AgentShareVisitor/VisitorConversation.tsx b/src/features/AgentShareVisitor/VisitorConversation.tsxnew file mode 100644index 00000000000..1c7832598ed--- /dev/null+++ b/src/features/AgentShareVisitor/VisitorConversation.tsx@@ -0,0 +1,62 @@+'use client';++import type { SharedAgentData } from '@lobechat/types';+import { memo } from 'react';++import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';+import { useChatStore } from '@/store/chat';++import ReadOnlyConversationArea from './ReadOnlyConversationArea';+import { resolveVisitorRunningOperation } from './resolveVisitorRunningOperation';+import { isShareInteractive } from './shareInteractivity';+import { useVisitorConversationSeed } from './useVisitorConversationSeed';+import { useVisitorTopics } from './useVisitorTopics';+import VisitorComposer from './VisitorComposer';++/**+ * The visitor-facing conversation column: mounts the lean message surface+ * after hand-seeding the stores, plus the share composer wired to the gateway+ * transport via `agentShareId`.+ */+const VisitorConversation = memo<{ data: SharedAgentData }>(({ data }) => {+ const { agentId, shareId } = data;+ const seeded = useVisitorConversationSeed(data);+ const activeTopicId = useChatStore((s) => s.activeTopicId);+ const interactive = isShareInteractive(data.visibility);+ const { data: topics, mutate: refreshVisitorTopics } = useVisitorTopics(shareId, interactive);++ // Reconnects a still-running Gateway stream after a page reload. A+ // non-interactive share (owner preview) never has a live run and its+ // `getTopics` fetch is skipped (see `useVisitorTopics`), so both args are+ // withheld rather than resolved against stale/empty data.+ useGatewayReconnect(+ interactive ? activeTopicId : undefined,+ interactive ? resolveVisitorRunningOperation(topics, activeTopicId) : undefined,+ agentId,+ shareId,+ );++ // The message surface reads the active ids on first render — mounting it+ // before the seed lands would fetch against a stale topic left by the main app.+ if (!seeded) return null;++ return (+ <>+ <ReadOnlyConversationArea agentId={agentId} agentShareId={shareId} topicId={activeTopicId} />+ <VisitorComposer+ agentId={agentId}+ // An owner previewing their own private share can view it but not chat.+ blockedKey={interactive ? undefined : 'share.visitor.errors.sharingPaused'}+ shareId={shareId}+ // The gateway transport already switched the store to the new topic+ // (`switchTopic`); refreshing the list makes it show up in the panel.+ topicId={activeTopicId}+ onTopicCreated={() => void refreshVisitorTopics()}+ />+ </>+ );+});++VisitorConversation.displayName = 'ShareVisitorConversation';++export default VisitorConversation;diff --git a/src/features/AgentShareVisitor/composerEnterGuard.test.ts b/src/features/AgentShareVisitor/composerEnterGuard.test.tsnew file mode 100644index 00000000000..37817c1a767--- /dev/null+++ b/src/features/AgentShareVisitor/composerEnterGuard.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from 'vitest';++import { shouldSubmitOnEnter } from './composerEnterGuard';++describe('shouldSubmitOnEnter', () => {+ it('submits on a plain Enter', () => {+ expect(shouldSubmitOnEnter({ shiftKey: false }, false)).toBe(true);+ });++ it('inserts a newline on Shift+Enter', () => {+ expect(shouldSubmitOnEnter({ shiftKey: true }, false)).toBe(false);+ });++ it('never submits the partial text of an in-flight IME composition', () => {+ expect(shouldSubmitOnEnter({ shiftKey: false }, true)).toBe(false);+ expect(shouldSubmitOnEnter({ shiftKey: true }, true)).toBe(false);+ });+});diff --git a/src/features/AgentShareVisitor/composerEnterGuard.ts b/src/features/AgentShareVisitor/composerEnterGuard.tsnew file mode 100644index 00000000000..69013e55011--- /dev/null+++ b/src/features/AgentShareVisitor/composerEnterGuard.ts@@ -0,0 +1,13 @@+/**+ * Decide whether a keyboard `Enter` press should submit the visitor composer.+ *+ * Extracted so the IME-composition guard is unit-testable without rendering+ * `VisitorComposer` — see `composerEnterGuard.test.ts`.+ *+ * rc-textarea's `onPressEnter` (which `@lobehub/ui`'s `TextArea` forwards)+ * fires on every `Enter` keydown with NO built-in IME-composing check — so an+ * Enter that only confirms an IME candidate (e.g. picking a Chinese/Japanese+ * character) would otherwise submit the partial composition text.+ */+export const shouldSubmitOnEnter = (event: { shiftKey: boolean }, isComposing: boolean): boolean =>+ !event.shiftKey && !isComposing;diff --git a/src/features/AgentShareVisitor/index.ts b/src/features/AgentShareVisitor/index.tsnew file mode 100644index 00000000000..8c62be55bf1--- /dev/null+++ b/src/features/AgentShareVisitor/index.ts@@ -0,0 +1,2 @@+export { default as AgentShareVisitorPage } from './Page';+export { useSharedAgent } from './useSharedAgent';diff --git a/src/features/AgentShareVisitor/resolveShareAccessState.test.ts b/src/features/AgentShareVisitor/resolveShareAccessState.test.tsnew file mode 100644index 00000000000..d95ab3d774e--- /dev/null+++ b/src/features/AgentShareVisitor/resolveShareAccessState.test.ts@@ -0,0 +1,29 @@+import { TRPCClientError } from '@trpc/client';+import { describe, expect, it } from 'vitest';++import { resolveShareAccessState } from './resolveShareAccessState';++const trpcError = (code: string) =>+ new TRPCClientError(code, {+ result: { error: { code: -32_600, data: { code }, message: code } },+ });++describe('resolveShareAccessState', () => {+ it('routes an anonymous visitor to the sign-in prompt rather than an error page', () => {+ expect(resolveShareAccessState(trpcError('UNAUTHORIZED'))).toBe('signIn');+ });++ it('maps a missing or disabled share to notFound', () => {+ expect(resolveShareAccessState(trpcError('NOT_FOUND'))).toBe('notFound');+ });++ it('maps an access rejection to forbidden', () => {+ expect(resolveShareAccessState(trpcError('FORBIDDEN'))).toBe('forbidden');+ });++ it('treats anything else as a retryable generic failure', () => {+ expect(resolveShareAccessState(trpcError('INTERNAL_SERVER_ERROR'))).toBe('generic');+ expect(resolveShareAccessState(new Error('network down'))).toBe('generic');+ expect(resolveShareAccessState(undefined)).toBe('generic');+ });+});diff --git a/src/features/AgentShareVisitor/resolveShareAccessState.ts b/src/features/AgentShareVisitor/resolveShareAccessState.tsnew file mode 100644index 00000000000..f66d6316173--- /dev/null+++ b/src/features/AgentShareVisitor/resolveShareAccessState.ts@@ -0,0 +1,32 @@+import { isTrpcErrorCode } from '@/utils/trpcError';++/**+ * How a failed `share.getSharedAgent` should be presented to the visitor.+ *+ * - `signIn` — the procedure is authed; an anonymous visitor gets+ * `UNAUTHORIZED` and needs a sign-in CTA rather than an error page. The+ * service opts out of the global 401 redirect precisely so this branch can+ * render (see `agentShareService.getSharedAgent`).+ * - `notFound` — no share resolves for this slug/id, or the creator turned+ * sharing off (`assertShareAccess` answers `NOT_FOUND` for a stranger on a+ * private share so a link cannot be used to probe for its existence).+ * - `forbidden` — the share exists but this account may not open it.+ * - `generic` — anything else (network / server fault): retryable.+ */+export type ShareAccessState = 'forbidden' | 'generic' | 'notFound' | 'signIn';++export const resolveShareAccessState = (error: unknown): ShareAccessState => {+ if (isTrpcErrorCode(error, 'UNAUTHORIZED')) return 'signIn';+ if (isTrpcErrorCode(error, 'NOT_FOUND')) return 'notFound';+ if (isTrpcErrorCode(error, 'FORBIDDEN')) return 'forbidden';+ return 'generic';+};++/** Visitor-facing copy key for a non-retryable access state. */+export const SHARE_ACCESS_ERROR_KEYS: Record<+ Exclude<ShareAccessState, 'generic' | 'signIn'>,+ string+> = {+ forbidden: 'share.visitor.access.forbidden',+ notFound: 'share.visitor.access.notFound',+};diff --git a/src/features/AgentShareVisitor/resolveVisitorErrorKey.test.ts b/src/features/AgentShareVisitor/resolveVisitorErrorKey.test.tsnew file mode 100644index 00000000000..e76c0e33100--- /dev/null+++ b/src/features/AgentShareVisitor/resolveVisitorErrorKey.test.ts@@ -0,0 +1,123 @@+import { ChatErrorType } from '@lobechat/types';+import { TRPCClientError } from '@trpc/client';+import { describe, expect, it } from 'vitest';+import { z } from 'zod';++import { isTerminalVisitorError, resolveVisitorErrorKey } from './resolveVisitorErrorKey';++describe('resolveVisitorErrorKey', () => {+ /**+ * The lambda router installs no `zodError` formatter, so tRPC surfaces the+ * ZodError's own `message` — `JSON.stringify(issues, null, 2)`. Build the+ * fixtures from a real schema rejection so the mapping is tested against the+ * shape production actually produces, not a hand-written string.+ */+ const badRequest = (message: string) =>+ new TRPCClientError(message, {+ result: { error: { code: -32_600, data: { code: 'BAD_REQUEST' }, message: 'Bad Request' } },+ });++ const zodMessage = (schema: z.ZodTypeAny, value: unknown) => {+ const parsed = z.object({ payload: schema }).safeParse({ payload: value });+ if (parsed.success) throw new Error('fixture should have failed validation');+ return parsed.error.message;+ };++ it('maps a BAD_REQUEST TRPCClientError (over-long prompt) to actionable copy', () => {+ const message = zodMessage(z.string().max(3), 'way too long').replace('payload', 'prompt');++ expect(resolveVisitorErrorKey(badRequest(message))).toBe('share.visitor.errors.promptTooLong');+ });++ it('does not blame prompt length for an unrelated BAD_REQUEST on another field', () => {+ // A malformed `clientIds.topicId` also fails the schema — telling the+ // visitor to shorten their message would be actively misleading.+ const message = zodMessage(z.string().regex(/^topic_/), 'nope').replace('payload', 'topicId');++ expect(resolveVisitorErrorKey(badRequest(message))).toBe('share.visitor.errors.generic');+ });++ const trpcError = (code: string, message = code) =>+ new TRPCClientError(message, {+ result: { error: { code: -32_600, data: { code }, message } },+ });++ it('maps a FORBIDDEN send to the paused-share copy instead of a retryable failure', () => {+ // The creator flipped visibility away from `link` mid-session:+ // `resolveLinkShareOrThrow` rejects every further send, so retrying is futile.+ expect(resolveVisitorErrorKey(trpcError('FORBIDDEN', 'This share is private'))).toBe(+ 'share.visitor.errors.sharingPaused',+ );+ });++ it('maps a topic-level NOT_FOUND send to the recoverable unavailable copy', () => {+ expect(resolveVisitorErrorKey(trpcError('NOT_FOUND', 'Topic not found'))).toBe(+ 'share.visitor.errors.unavailable',+ );+ });++ it('maps a share-level NOT_FOUND send to the paused-share copy', () => {+ // A paused share answers NOT_FOUND to a stranger (no existence probing),+ // which for a visitor mid-session means the same as "sharing paused".+ expect(resolveVisitorErrorKey(trpcError('NOT_FOUND', 'Share not found'))).toBe(+ 'share.visitor.errors.sharingPaused',+ );+ });++ it('treats share-level failures as terminal and per-attempt ones as retryable', () => {+ expect(isTerminalVisitorError('share.visitor.errors.sharingPaused')).toBe(true);+ // NOT_FOUND may describe only the current topic (deleted topic), which a+ // topic switch / new conversation recovers from — locking the composer on+ // it would strand the visitor with no way out but a reload.+ expect(isTerminalVisitorError('share.visitor.errors.unavailable')).toBe(false);+ // The turn limit is scoped to one topic — a new conversation clears it.+ expect(isTerminalVisitorError('share.visitor.errors.turnLimit')).toBe(false);+ expect(isTerminalVisitorError('share.visitor.errors.generic')).toBe(false);+ });++ it('maps ShareTurnLimitExceeded', () => {+ expect(resolveVisitorErrorKey(new Error(ChatErrorType.ShareTurnLimitExceeded))).toBe(+ 'share.visitor.errors.turnLimit',+ );+ });++ it('maps ShareTopicLimitExceeded', () => {+ expect(resolveVisitorErrorKey(new Error(ChatErrorType.ShareTopicLimitExceeded))).toBe(+ 'share.visitor.errors.topicLimit',+ );+ });++ it('maps ShareSpendLimitExceeded to non-terminal "monthly limit reached" copy', () => {+ expect(resolveVisitorErrorKey(new Error(ChatErrorType.ShareSpendLimitExceeded))).toBe(+ 'share.visitor.errors.spendLimit',+ );+ // The cap resets next month and the owner can raise it — keep the composer usable.+ expect(isTerminalVisitorError('share.visitor.errors.spendLimit')).toBe(false);+ });++ it('maps InsufficientBudgetForModel', () => {+ expect(resolveVisitorErrorKey(new Error(ChatErrorType.InsufficientBudgetForModel))).toBe(+ 'share.visitor.errors.insufficientBudget',+ );+ });++ it('maps AgentShareProviderNotSupported', () => {+ expect(resolveVisitorErrorKey(new Error(ChatErrorType.AgentShareProviderNotSupported))).toBe(+ 'share.visitor.errors.providerNotSupported',+ );+ });++ it('maps ShareHeterogeneousAgentUnsupported', () => {+ expect(+ resolveVisitorErrorKey(new Error(ChatErrorType.ShareHeterogeneousAgentUnsupported)),+ ).toBe('share.visitor.errors.heterogeneousUnsupported');+ });++ it('falls back to the generic copy for an unrecognized error', () => {+ expect(resolveVisitorErrorKey(new Error('boom'))).toBe('share.visitor.errors.generic');+ });++ it('falls back to the generic copy for a non-Error thrown value', () => {+ expect(resolveVisitorErrorKey('boom')).toBe('share.visitor.errors.generic');+ });+});diff --git a/src/features/AgentShareVisitor/resolveVisitorErrorKey.ts b/src/features/AgentShareVisitor/resolveVisitorErrorKey.tsnew file mode 100644index 00000000000..7793e9df4b1--- /dev/null+++ b/src/features/AgentShareVisitor/resolveVisitorErrorKey.ts@@ -0,0 +1,88 @@+import { ChatErrorType } from '@lobechat/types';+import { TRPCClientError } from '@trpc/client';++/**+ * Map a share-run failure to the visitor-facing copy key.+ *+ * Extracted so the mapping (including the tRPC `BAD_REQUEST` branch) is+ * unit-testable without rendering `VisitorComposer` — see+ * `resolveVisitorErrorKey.test.ts`.+ */+export const resolveVisitorErrorKey = (error: unknown): string => {+ const message = error instanceof Error ? error.message : String(error);++ // The server rejects an over-long `prompt` with a Zod-driven `BAD_REQUEST`+ // (see `SHARE_VISITOR_PROMPT_MAX_LENGTH` in `@lobechat/const`), not one of+ // the `ChatErrorType` values matched below — those are only embedded in+ // errors raised from inside the agent run itself. The client-side+ // `maxLength` mirror on the composer's `TextArea` should catch this before+ // the request goes out, but a direct RPC caller (or any future desync+ // between the two bounds) still needs actionable copy.+ //+ // Narrowed to the `prompt`/`too_big` issue rather than any `BAD_REQUEST`:+ // this procedure's schema can also reject a malformed `clientIds`/`topicId`,+ // and telling a visitor to shorten their message when the real fault is a+ // malformed id would be actively misleading. The lambda router installs no+ // `zodError` formatter, so the issue list only survives as tRPC's default+ // JSON-stringified `message`; anything that does not clearly match falls+ // through to the generic copy.+ if (+ error instanceof TRPCClientError &&+ error.data?.code === 'BAD_REQUEST' &&+ message.includes('too_big') &&+ message.includes('prompt')+ )+ return 'share.visitor.errors.promptTooLong';++ // The share itself stopped accepting traffic mid-session: the creator+ // paused it (a stranger on a private share gets NOT_FOUND 'Share not found'+ // from `assertShareAccess`, deliberately indistinguishable from a deleted+ // one), flipped it off `link` while previewing as owner+ // (`resolveLinkShareOrThrow` → FORBIDDEN), or deleted the topic+ // (NOT_FOUND 'Topic not found'). `useSharedAgent` never revalidates, so the+ // page keeps rendering the stale "everything is fine" shell — without this+ // branch the visitor only sees the generic copy and retries forever.+ if (error instanceof TRPCClientError) {+ if (error.data?.code === 'FORBIDDEN') return 'share.visitor.errors.sharingPaused';+ if (error.data?.code === 'NOT_FOUND') {+ // Share-level vs topic-level NOT_FOUND can only be told apart by the+ // server message (`shareChat.ts` / `AgentShareModel`): the share one is+ // terminal, the topic one must stay recoverable by switching / starting+ // a new topic (see `TERMINAL_VISITOR_ERROR_KEYS`).+ if (message === 'Share not found') return 'share.visitor.errors.sharingPaused';+ return 'share.visitor.errors.unavailable';+ }+ }++ if (message.includes(ChatErrorType.ShareTurnLimitExceeded))+ return 'share.visitor.errors.turnLimit';+ if (message.includes(ChatErrorType.ShareTopicLimitExceeded))+ return 'share.visitor.errors.topicLimit';+ // Deliberately NOT terminal: the cap is per calendar month and the owner can+ // raise it at any time, so the composer stays usable for a retry.+ if (message.includes(ChatErrorType.ShareSpendLimitExceeded))+ return 'share.visitor.errors.spendLimit';+ if (message.includes(ChatErrorType.InsufficientBudgetForModel))+ return 'share.visitor.errors.insufficientBudget';+ if (message.includes(ChatErrorType.AgentShareProviderNotSupported))+ return 'share.visitor.errors.providerNotSupported';+ if (message.includes(ChatErrorType.ShareHeterogeneousAgentUnsupported))+ return 'share.visitor.errors.heterogeneousUnsupported';++ return 'share.visitor.errors.generic';+};++/**+ * Failures that describe the share itself rather than one attempt, so retrying+ * (or switching topic) cannot clear them — the composer stays disabled and the+ * message survives a topic switch.+ */+const TERMINAL_VISITOR_ERROR_KEYS = new Set([+ // `unavailable` (NOT_FOUND) is intentionally absent: it may describe only the+ // current topic, so locking the composer for it would strand the visitor —+ // worst case a truly deleted share just fails again on the next send.+ 'share.visitor.errors.sharingPaused',+]);++export const isTerminalVisitorError = (errorKey: string): boolean =>+ TERMINAL_VISITOR_ERROR_KEYS.has(errorKey);diff --git a/src/features/AgentShareVisitor/resolveVisitorRunningOperation.test.ts b/src/features/AgentShareVisitor/resolveVisitorRunningOperation.test.tsnew file mode 100644index 00000000000..c4f3fedcb90--- /dev/null+++ b/src/features/AgentShareVisitor/resolveVisitorRunningOperation.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest';++import { resolveVisitorRunningOperation } from './resolveVisitorRunningOperation';++describe('resolveVisitorRunningOperation', () => {+ it('returns undefined when there is no active topic', () => {+ expect(+ resolveVisitorRunningOperation(+ [{ id: 't-1', runningOperation: { assistantMessageId: 'a', operationId: 'op' } }],+ undefined,+ ),+ ).toBeUndefined();+ });++ it('returns undefined when the topic list has not loaded yet', () => {+ expect(resolveVisitorRunningOperation(undefined, 't-1')).toBeUndefined();+ });++ it('returns undefined when the active topic has no running operation', () => {+ expect(+ resolveVisitorRunningOperation([{ id: 't-1', runningOperation: null }], 't-1'),+ ).toBeUndefined();+ });++ it('returns undefined when the active topic is not in the list', () => {+ expect(+ resolveVisitorRunningOperation(+ [{ id: 't-other', runningOperation: { assistantMessageId: 'a', operationId: 'op' } }],+ 't-1',+ ),+ ).toBeUndefined();+ });++ it('returns the matching topic runningOperation', () => {+ const runningOperation = {+ assistantMessageId: 'ast-1',+ heteroType: 'claude-code',+ operationId: 'op-1',+ scope: 'main',+ threadId: 'thd-1',+ };++ expect(+ resolveVisitorRunningOperation(+ [+ { id: 't-other', runningOperation: null },+ { id: 't-1', runningOperation },+ ],+ 't-1',+ ),+ ).toEqual(runningOperation);+ });+});diff --git a/src/features/AgentShareVisitor/resolveVisitorRunningOperation.ts b/src/features/AgentShareVisitor/resolveVisitorRunningOperation.tsnew file mode 100644index 00000000000..3a3d6a99901--- /dev/null+++ b/src/features/AgentShareVisitor/resolveVisitorRunningOperation.ts@@ -0,0 +1,31 @@+/** Sanitized `runningOperation` marker the visitor topic list carries — mirrors `VisitorRunningOperation` in `packages/database/src/models/topic.ts` (server projection) and the shape `useGatewayReconnect`'s `RunningOperation` needs. */+export interface VisitorTopicRunningOperation {+ assistantMessageId: string;+ heteroType?: string | null;+ operationId: string;+ scope?: string;+ threadId?: string | null;+}++interface VisitorTopicWithRunningOperation {+ id: string;+ runningOperation?: VisitorTopicRunningOperation | null;+}++/**+ * Finds the active topic in the visitor's topic list (from `useVisitorTopics`)+ * and returns its sanitized `runningOperation` marker, if any — what+ * `useGatewayReconnect` needs to resume a Gateway stream after a page reload.+ *+ * A pure lookup, kept separate from `VisitorConversation` so it can be+ * unit-tested without mounting the SWR-backed hook — same split as+ * `topicPanelViewState.ts`.+ */+export const resolveVisitorRunningOperation = (+ topics: VisitorTopicWithRunningOperation[] | undefined,+ topicId: string | null | undefined,+): VisitorTopicRunningOperation | undefined => {+ if (!topicId) return undefined;++ return topics?.find((topic) => topic.id === topicId)?.runningOperation ?? undefined;+};diff --git a/src/features/AgentShareVisitor/routeMeta.ts b/src/features/AgentShareVisitor/routeMeta.tsnew file mode 100644index 00000000000..bd51f8e8bf4--- /dev/null+++ b/src/features/AgentShareVisitor/routeMeta.ts@@ -0,0 +1,15 @@+import { MessageSquareShareIcon } from 'lucide-react';++import ConversationLayoutSkeleton from '@/components/Skeleton/Conversation/Layout';+import { routeMeta } from '@/spa/router/routeMeta';++/**+ * Agent-share visitor surface (`/agent/:slugOrId`). The shared agent's+ * name only becomes known after `getSharedAgent` resolves, so the tab title+ * stays on the generic share label rather than flashing a placeholder name.+ */+export const agentShareVisitorRouteMeta = routeMeta({+ icon: MessageSquareShareIcon,+ Skeleton: ConversationLayoutSkeleton,+ titleKey: 'navigation.sharedAgent',+});diff --git a/src/features/AgentShareVisitor/sendVisitorMessage.test.ts b/src/features/AgentShareVisitor/sendVisitorMessage.test.tsnew file mode 100644index 00000000000..b13c17b46e1--- /dev/null+++ b/src/features/AgentShareVisitor/sendVisitorMessage.test.ts@@ -0,0 +1,101 @@+import { LOADING_FLAT } from '@lobechat/const';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const store = vi.hoisted(() => ({+ associateMessageWithOperation: vi.fn(),+ executeGatewayAgent: vi.fn(),+ failOperation: vi.fn(),+ internal_dispatchMessage: vi.fn(),+ operations: {} as Record<string, { status: string }>,+ optimisticCreateTmpMessage: vi.fn(),+ startOperation: vi.fn(() => ({ abortController: new AbortController(), operationId: 'op-1' })),+}));++vi.mock('@/store/chat', () => ({+ useChatStore: { getState: () => store },+}));++const { sendVisitorMessage } = await import('./sendVisitorMessage');++const params = { agentId: 'agent-1', message: 'hello', shareId: 'share-1', topicId: 'topic-1' };++describe('sendVisitorMessage', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ store.operations = {};+ store.executeGatewayAgent.mockResolvedValue({+ assistantMessageId: 'a',+ operationId: 'srv-op',+ topicId: 'topic-1',+ userMessageId: 'u',+ });+ });++ // Regression: the composer used to call `executeGatewayAgent` bare, so the+ // list stayed empty until the first gateway event and nothing carried the+ // generating state.+ it('echoes the user bubble and an assistant placeholder before the gateway call, under a sendMessage op', async () => {+ await sendVisitorMessage(params);++ expect(store.startOperation).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'sendMessage' }),+ );+ const [userCall, assistantCall] = store.optimisticCreateTmpMessage.mock.calls;+ expect(userCall[0]).toMatchObject({ content: 'hello', role: 'user', topicId: 'topic-1' });+ expect(assistantCall[0]).toMatchObject({ content: LOADING_FLAT, role: 'assistant' });+ const userMessageId = userCall[1].tempMessageId;+ const assistantMessageId = assistantCall[1].tempMessageId;+ expect(store.associateMessageWithOperation).toHaveBeenCalledWith(userMessageId, 'op-1');+ expect(store.associateMessageWithOperation).toHaveBeenCalledWith(assistantMessageId, 'op-1');++ // Same ids handed to the server so the optimistic rows never re-key.+ expect(store.executeGatewayAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ clientIds: { assistantMessageId, userMessageId },+ context: { agentId: 'agent-1', agentShareId: 'share-1', scope: 'main', topicId: 'topic-1' },+ parentOperationId: 'op-1',+ tempMessageIds: [assistantMessageId],+ }),+ );+ // Existing topic: the server rows land in the same bucket, nothing to drop.+ expect(store.internal_dispatchMessage).not.toHaveBeenCalled();+ });++ it('drops the pre-topic optimistic rows after a new topic was created', async () => {+ await sendVisitorMessage({ ...params, topicId: undefined });++ expect(store.executeGatewayAgent).toHaveBeenCalledWith(+ expect.objectContaining({ context: expect.objectContaining({ topicId: undefined }) }),+ );+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'deleteMessages' }),+ { operationId: 'op-1' },+ );+ });++ it('fails the op, removes the optimistic rows and rethrows when the gateway rejects', async () => {+ const error = new Error('limit');+ store.executeGatewayAgent.mockRejectedValueOnce(error);++ await expect(sendVisitorMessage(params)).rejects.toBe(error);++ expect(store.failOperation).toHaveBeenCalledWith('op-1', {+ message: 'limit',+ type: 'GatewayError',+ });+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'deleteMessages' }),+ { operationId: 'op-1' },+ );+ });++ it('keeps a cancelled op cancelled instead of marking it failed', async () => {+ store.operations = { 'op-1': { status: 'cancelled' } };+ store.executeGatewayAgent.mockRejectedValueOnce(new Error('aborted'));++ await expect(sendVisitorMessage(params)).rejects.toThrow('aborted');++ expect(store.failOperation).not.toHaveBeenCalled();+ expect(store.internal_dispatchMessage).toHaveBeenCalled();+ });+});diff --git a/src/features/AgentShareVisitor/sendVisitorMessage.ts b/src/features/AgentShareVisitor/sendVisitorMessage.tsnew file mode 100644index 00000000000..26ce54498b9--- /dev/null+++ b/src/features/AgentShareVisitor/sendVisitorMessage.ts@@ -0,0 +1,98 @@+import { LOADING_FLAT } from '@lobechat/const';+import { generateEntityId } from '@lobechat/utils';++import { useChatStore } from '@/store/chat';++export interface SendVisitorMessageParams {+ agentId: string;+ message: string;+ shareId: string;+ /** Absent → the run creates a new visitor topic. */+ topicId?: string | null;+}++/**+ * Share-visitor send: the optimistic echo of the owner `sendMessage` path+ * (`conversationLifecycle.ts`), without its owner-only preamble.+ *+ * `sendMessage` itself cannot be reused here — it reads the full owner agent+ * config and runs `ensureAgentManagementAccess`, which a visitor fails. But+ * calling `executeGatewayAgent` bare (the previous behaviour) left the list+ * empty until the first gateway event: no user bubble, no assistant+ * placeholder, and nothing for the loading UI to attach to. This mirrors the+ * pieces that matter for the visitor:+ *+ * 1. Mint the final row ids up front — the share `execAgent` route honours+ * `clientIds` verbatim, so the optimistic rows never need re-keying.+ * 2. Insert the user bubble and a `LOADING_FLAT` assistant placeholder+ * immediately, under a `sendMessage` operation so `ContentLoading` shows+ * the generating state during the phase-1 round-trip.+ * 3. Hand the operation to `executeGatewayAgent` as `parentOperationId`, which+ * completes it once the child `execServerAgentRuntime` op is running.+ */+export const sendVisitorMessage = async ({+ agentId,+ message,+ shareId,+ topicId,+}: SendVisitorMessageParams) => {+ const store = useChatStore.getState();+ const messageContext = {+ agentId,+ agentShareId: shareId,+ scope: 'main' as const,+ topicId: topicId ?? undefined,+ };+ const userMessageId = generateEntityId('messages');+ const assistantMessageId = generateEntityId('messages');++ const { operationId } = store.startOperation({+ context: { ...messageContext, messageId: userMessageId },+ label: 'Send Message',+ type: 'sendMessage',+ });++ store.optimisticCreateTmpMessage(+ { agentId, content: message, role: 'user', topicId: messageContext.topicId },+ { operationId, tempMessageId: userMessageId },+ );+ store.optimisticCreateTmpMessage(+ { agentId, content: LOADING_FLAT, role: 'assistant', topicId: messageContext.topicId },+ { operationId, tempMessageId: assistantMessageId },+ );+ store.associateMessageWithOperation(userMessageId, operationId);+ store.associateMessageWithOperation(assistantMessageId, operationId);++ const removeOptimisticRows = () => {+ store.internal_dispatchMessage(+ { ids: [userMessageId, assistantMessageId], type: 'deleteMessages' },+ { operationId },+ );+ };++ try {+ const result = await store.executeGatewayAgent({+ clientIds: { assistantMessageId, userMessageId },+ context: messageContext,+ message,+ messageContext,+ parentOperationId: operationId,+ tempMessageIds: [assistantMessageId],+ });+ // A new topic is fetched and switched to by the gateway under its real id;+ // the optimistic rows were written to the pre-topic bucket and would+ // otherwise linger there for the next "new conversation" surface.+ if (!topicId) removeOptimisticRows();+ return result;+ } catch (error) {+ // A Stop during phase-1 already marked the op cancelled — keep that.+ if (useChatStore.getState().operations[operationId]?.status !== 'cancelled') {+ store.failOperation(operationId, {+ message: error instanceof Error ? error.message : 'Unknown error',+ type: 'GatewayError',+ });+ }+ removeOptimisticRows();+ throw error;+ }+};diff --git a/src/features/AgentShareVisitor/shareInteractivity.ts b/src/features/AgentShareVisitor/shareInteractivity.tsnew file mode 100644index 00000000000..8fedb1de6a3--- /dev/null+++ b/src/features/AgentShareVisitor/shareInteractivity.ts@@ -0,0 +1,13 @@+import type { SharedAgentData } from '@lobechat/types';++/**+ * Whether the share still accepts visitor traffic.+ *+ * Every visitor-facing `shareChat` procedure runs through+ * `resolveLinkShareOrThrow`, which rejects anything but `link` visibility with+ * `FORBIDDEN`. An owner previewing their own private share therefore reaches+ * this page (via `assertShareAccess`) but must not fire those calls — chatting+ * and the topic list alike would only render a useless error.+ */+export const isShareInteractive = (visibility: SharedAgentData['visibility']): boolean =>+ visibility === 'link';diff --git a/src/features/AgentShareVisitor/topicPanelViewState.test.ts b/src/features/AgentShareVisitor/topicPanelViewState.test.tsnew file mode 100644index 00000000000..e0419d1cd0c--- /dev/null+++ b/src/features/AgentShareVisitor/topicPanelViewState.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';++import { getTopicPanelViewState } from './topicPanelViewState';++describe('getTopicPanelViewState', () => {+ it('reports error first, even while a revalidation is in flight', () => {+ expect(getTopicPanelViewState(undefined, new Error('boom'), true)).toBe('error');+ expect(getTopicPanelViewState([{}], new Error('boom'), false)).toBe('error');+ });++ it('reports loading before falling back to empty', () => {+ expect(getTopicPanelViewState(undefined, undefined, true)).toBe('loading');+ });++ it('only reports empty for a settled, genuinely empty list', () => {+ expect(getTopicPanelViewState([], undefined, false)).toBe('empty');+ expect(getTopicPanelViewState(undefined, undefined, false)).toBe('empty');+ });++ it('reports list when topics exist', () => {+ expect(getTopicPanelViewState([{}], undefined, false)).toBe('list');+ });+});diff --git a/src/features/AgentShareVisitor/topicPanelViewState.ts b/src/features/AgentShareVisitor/topicPanelViewState.tsnew file mode 100644index 00000000000..76784fb0c3f--- /dev/null+++ b/src/features/AgentShareVisitor/topicPanelViewState.ts@@ -0,0 +1,20 @@+/**+ * The visitor topic list has four mutually-exclusive states, and an SWR fetch+ * only tells the caller two independent booleans (`isLoading`, `error`) plus+ * possibly-stale `data`. Centralizing the branch here keeps `error` and+ * `isLoading` checked *before* falling back to "no topics" — otherwise a+ * pending or failed fetch (where `data` is still `undefined`) renders the same+ * empty state as a genuinely empty list, silently misinforming the visitor.+ */+export type TopicPanelViewState = 'empty' | 'error' | 'list' | 'loading';++export const getTopicPanelViewState = (+ topics: unknown[] | undefined,+ error: unknown,+ isLoading: boolean,+): TopicPanelViewState => {+ if (error) return 'error';+ if (isLoading) return 'loading';+ if (!topics?.length) return 'empty';+ return 'list';+};diff --git a/src/features/AgentShareVisitor/topicRowActivation.test.ts b/src/features/AgentShareVisitor/topicRowActivation.test.tsnew file mode 100644index 00000000000..b2278558fd7--- /dev/null+++ b/src/features/AgentShareVisitor/topicRowActivation.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest';++import { isTopicRowActivationKey } from './topicRowActivation';++describe('isTopicRowActivationKey', () => {+ it('activates on Enter', () => {+ expect(isTopicRowActivationKey('Enter')).toBe(true);+ });++ it('activates on Space', () => {+ expect(isTopicRowActivationKey(' ')).toBe(true);+ });++ it('ignores other keys', () => {+ expect(isTopicRowActivationKey('Tab')).toBe(false);+ expect(isTopicRowActivationKey('ArrowDown')).toBe(false);+ expect(isTopicRowActivationKey('a')).toBe(false);+ });+});diff --git a/src/features/AgentShareVisitor/topicRowActivation.ts b/src/features/AgentShareVisitor/topicRowActivation.tsnew file mode 100644index 00000000000..5b93db199bb--- /dev/null+++ b/src/features/AgentShareVisitor/topicRowActivation.ts@@ -0,0 +1,8 @@+/**+ * Whether a `KeyboardEvent.key` should activate a visitor topic row.+ *+ * Extracted so the div-as-button keyboard semantics (mirroring a native+ * `<button>`: only Enter/Space activate) are unit-testable without rendering+ * `TopicPanel` — see `topicRowActivation.test.ts`.+ */+export const isTopicRowActivationKey = (key: string): boolean => key === 'Enter' || key === ' ';diff --git a/src/features/AgentShareVisitor/useShareRunStop.test.ts b/src/features/AgentShareVisitor/useShareRunStop.test.tsnew file mode 100644index 00000000000..9bffd640292--- /dev/null+++ b/src/features/AgentShareVisitor/useShareRunStop.test.ts@@ -0,0 +1,151 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { Operation } from '@/store/chat/slices/operation/types';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++const mocks = vi.hoisted(() => ({+ interruptTask: vi.fn(),+}));++vi.mock('@/services/shareChat', () => ({+ shareChatService: { interruptTask: mocks.interruptTask },+}));++const updateOperationMetadata = vi.fn();+let operations: Operation[] = [];++const contextKey = messageMapKey({ agentId: 'agent-1', scope: 'main', topicId: 'topic-1' });++// A tiny fake chat store, same shape used by `useVisitorConversationSeed.test.ts`:+// only the bits `useShareRunStop` actually touches (`operationsByContext` /+// `operations` for the real `getOperationsByContext` selector, plus+// `updateOperationMetadata`).+vi.mock('@/store/chat', () => ({+ useChatStore: {+ getState: () => ({+ operations: Object.fromEntries(operations.map((op) => [op.id, op])),+ operationsByContext: { [contextKey]: operations.map((op) => op.id) },+ updateOperationMetadata,+ }),+ },+}));++const { resolveRunningShareOperation, useShareRunStop } = await import('./useShareRunStop');++const runningOp = (overrides: Partial<Operation> = {}): Operation =>+ ({+ abortController: new AbortController(),+ context: { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },+ id: 'local-op-1',+ metadata: { serverOperationId: 'server-op-1', startTime: Date.now() },+ status: 'running',+ type: 'execServerAgentRuntime',+ ...overrides,+ }) as Operation;++describe('resolveRunningShareOperation', () => {+ it('returns undefined when nothing is running', () => {+ expect(resolveRunningShareOperation([])).toBeUndefined();+ });++ it('ignores operations that are not AI-runtime types', () => {+ const op = runningOp({ type: 'sendMessage' as Operation['type'] });+ expect(resolveRunningShareOperation([op])).toBeUndefined();+ });++ it('ignores operations missing a server-side operation id', () => {+ const op = runningOp({ metadata: { startTime: Date.now() } });+ expect(resolveRunningShareOperation([op])).toBeUndefined();+ });++ it('picks the running execServerAgentRuntime operation', () => {+ const op = runningOp();+ expect(resolveRunningShareOperation([op])).toEqual({+ localOperationId: 'local-op-1',+ serverOperationId: 'server-op-1',+ topicId: 'topic-1',+ });+ });+});++describe('useShareRunStop', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ operations = [];+ });++ it('is a no-op when nothing is running for the context', async () => {+ const { result } = renderHook(() => useShareRunStop('share-1', 'agent-1', 'topic-1'));++ await act(async () => {+ await result.current.stopSharedRun();+ });++ expect(mocks.interruptTask).not.toHaveBeenCalled();+ expect(updateOperationMetadata).not.toHaveBeenCalled();+ });++ it('flips isAborting immediately and calls shareChat.interruptTask for the running op', async () => {+ operations = [runningOp()];+ mocks.interruptTask.mockResolvedValueOnce({ success: true });+ const { result } = renderHook(() => useShareRunStop('share-1', 'agent-1', 'topic-1'));++ await act(async () => {+ await result.current.stopSharedRun();+ });++ expect(updateOperationMetadata).toHaveBeenCalledWith('local-op-1', { isAborting: true });+ expect(mocks.interruptTask).toHaveBeenCalledWith('share-1', 'topic-1', 'server-op-1');+ expect(result.current.stopping).toBe(false);+ expect(result.current.stopError).toBeUndefined();+ });++ it('surfaces an interrupt failure and restores the loading indicator instead of swallowing it', async () => {+ operations = [runningOp()];+ mocks.interruptTask.mockRejectedValueOnce(new Error('already finished'));+ const { result } = renderHook(() => useShareRunStop('share-1', 'agent-1', 'topic-1'));++ await act(async () => {+ await result.current.stopSharedRun();+ });++ await waitFor(() => {+ expect(result.current.stopError).toBeInstanceOf(Error);+ });+ // Restored to `false` — the interrupt didn't land, so the run is presumably+ // still going and the busy indicator should not stay stuck off.+ expect(updateOperationMetadata).toHaveBeenLastCalledWith('local-op-1', {+ isAborting: false,+ });+ expect(result.current.stopping).toBe(false);+ });++ it('ignores a concurrent stop while one is already in flight', async () => {+ operations = [runningOp()];+ let resolveFirst: ((value: { success: boolean }) => void) | undefined;+ mocks.interruptTask.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveFirst = resolve;+ }),+ );+ const { result } = renderHook(() => useShareRunStop('share-1', 'agent-1', 'topic-1'));++ let firstCall!: Promise<void>;+ act(() => {+ firstCall = result.current.stopSharedRun();+ });+ expect(result.current.stopping).toBe(true);++ await act(async () => {+ await result.current.stopSharedRun();+ });+ expect(mocks.interruptTask).toHaveBeenCalledTimes(1);++ resolveFirst?.({ success: true });+ await act(async () => {+ await firstCall;+ });+ });+});diff --git a/src/features/AgentShareVisitor/useShareRunStop.ts b/src/features/AgentShareVisitor/useShareRunStop.tsnew file mode 100644index 00000000000..c03339b747b--- /dev/null+++ b/src/features/AgentShareVisitor/useShareRunStop.ts@@ -0,0 +1,123 @@+import { useCallback, useEffect, useState } from 'react';++import { shareChatService } from '@/services/shareChat';+import { useChatStore } from '@/store/chat';+import { operationSelectors } from '@/store/chat/slices/operation/selectors';+import { AI_RUNTIME_OPERATION_TYPES, type Operation } from '@/store/chat/slices/operation/types';++export interface ShareRunStop {+ /** Set when the interrupt request itself failed — lets the caller offer a retry. */+ stopError: unknown;+ /** Whether an interrupt request is currently in flight. */+ stopping: boolean;+ /**+ * Ask the server to interrupt the share's currently running operation.+ * No-op if nothing is running for this (agentId, topicId) context.+ */+ stopSharedRun: () => Promise<void>;+}++/**+ * The bits `stopSharedRun` needs off the running operation: the server-side id+ * `shareChat.interruptTask` requires (distinct from the local operation id),+ * and the topic it belongs to (read off the operation itself rather than the+ * composer's `topicId` prop, which can still be stale for the first turn of a+ * brand-new topic — see `resolveRunningShareOperation`'s doc comment).+ */+export interface RunningShareOperation {+ localOperationId: string;+ serverOperationId: string;+ topicId: string;+}++/**+ * Pick the running gateway operation for a share context, if any — pure so it+ * can be unit-tested without a full zustand store mock (see+ * `useShareRunStop.test.ts`, mirroring the `topicPanelViewState.ts` precedent).+ *+ * Reads `operation.context.topicId` rather than trusting a caller-supplied+ * topicId: for a fresh share topic the operation is created (and starts+ * streaming) with the server-minted topic id before `VisitorConversation`'s+ * `activeTopicId` state has necessarily re-rendered the composer, so the prop+ * can momentarily lag. The operation's own context never does.+ */+export const resolveRunningShareOperation = (+ operations: Operation[],+): RunningShareOperation | undefined => {+ const operation = operations.find(+ (op) => AI_RUNTIME_OPERATION_TYPES.includes(op.type) && op.status === 'running',+ );+ if (!operation?.metadata.serverOperationId || !operation.context.topicId) return undefined;++ return {+ localOperationId: operation.id,+ serverOperationId: operation.metadata.serverOperationId,+ topicId: operation.context.topicId,+ };+};++/**+ * Visitor-facing counterpart of the main composer's Stop button.+ *+ * Deliberately does NOT go through `cancelOperation`/`cancelOperations`: those+ * already forward gateway-mode share runs to `shareChatService.interruptTask`+ * via the `onOperationCancel` handler registered in `gateway.ts`, but that+ * call is fire-and-forget and swallows its own errors (see+ * `operation/actions.ts` `cancelOperation`), so a failed interrupt would never+ * reach the visitor. Worse, the server's `interruptTask` route rejects with+ * `NOT_FOUND` unless the given operationId still matches the topic's recorded+ * `runningOperation` (see `shareChat.ts`), so calling it a second time+ * ourselves on top of that handler risks a spurious failure once the first+ * call has already cleared it. Instead this owns the single interrupt call+ * end-to-end and reports its outcome.+ *+ * Flips `isAborting` on the local operation immediately on request (the same+ * flag `cancelOperation` sets) so the busy indicator clears right away like+ * the main composer's, without touching `onCancelHandler` — and reverts it if+ * the interrupt request itself fails, since the run is presumably still going.+ */+export const useShareRunStop = (+ shareId: string,+ agentId: string,+ topicId?: string | null,+): ShareRunStop => {+ const [stopping, setStopping] = useState(false);+ const [stopError, setStopError] = useState<unknown>();++ // The failure belongs to the run in the topic it happened in; carrying it into+ // another topic would offer a retry that resolves no running operation there.+ useEffect(() => {+ setStopError(undefined);+ }, [topicId]);++ const stopSharedRun = useCallback(async () => {+ if (stopping) return;++ const operations = operationSelectors.getOperationsByContext({+ agentId,+ scope: 'main',+ topicId: topicId ?? undefined,+ })(useChatStore.getState());+ const target = resolveRunningShareOperation(operations);+ if (!target) return;++ const { updateOperationMetadata } = useChatStore.getState();+ setStopping(true);+ setStopError(undefined);+ updateOperationMetadata(target.localOperationId, { isAborting: true });++ try {+ await shareChatService.interruptTask(shareId, target.topicId, target.serverOperationId);+ } catch (error) {+ console.error('[AgentShareVisitor] interruptTask failed:', error);+ // The interrupt didn't land — the run is presumably still going, so+ // restore the loading indicator and let the visitor retry.+ updateOperationMetadata(target.localOperationId, { isAborting: false });+ setStopError(error);+ } finally {+ setStopping(false);+ }+ }, [agentId, shareId, stopping, topicId]);++ return { stopError, stopping, stopSharedRun };+};diff --git a/src/features/AgentShareVisitor/useSharedAgent.ts b/src/features/AgentShareVisitor/useSharedAgent.tsnew file mode 100644index 00000000000..f2ee4dd44b1--- /dev/null+++ b/src/features/AgentShareVisitor/useSharedAgent.ts@@ -0,0 +1,19 @@+import useSWR from 'swr';++import { shareKeys } from '@/libs/swr/keys';+import { agentShareService } from '@/services/agentShare';++/**+ * Fetch the visitor-facing metadata of an agent share, resolved from the URL+ * segment (a custom slug or the raw share id).+ *+ * `getSharedAgent` counts a page view server-side, so revalidation on focus /+ * reconnect is off: re-focusing the same mounted visit must not increment it+ * again.+ */+export const useSharedAgent = (slugOrId?: string) =>+ useSWR(+ slugOrId ? shareKeys.agentInfo(slugOrId) : null,+ () => agentShareService.getSharedAgent(slugOrId!),+ { revalidateOnFocus: false, revalidateOnReconnect: false },+ );diff --git a/src/features/AgentShareVisitor/useVisitorConversationSeed.ts b/src/features/AgentShareVisitor/useVisitorConversationSeed.tsnew file mode 100644index 00000000000..489f259a651--- /dev/null+++ b/src/features/AgentShareVisitor/useVisitorConversationSeed.ts@@ -0,0 +1,70 @@+'use client';++import type { SharedAgentData } from '@lobechat/types';+import { useLayoutEffect, useState } from 'react';++import { useAgentStore } from '@/store/agent';+import { useChatStore } from '@/store/chat';++type SharedAgentIdentity = Pick<SharedAgentData, 'agentId' | 'agentMeta' | 'shareId'>;++const seedAgentMap = (agentId: string, agentMeta: SharedAgentIdentity['agentMeta']) => {+ // Visitors cannot call the owner-scoped agent-config API, so seed a minimal+ // `agentMap` entry from the share metadata by hand — mere presence is what+ // flips `isAgentConfigLoading*` off for the welcome header and chat input+ // skeletons. Merged via the store's dispatcher so nulls never clobber+ // existing fields.+ useAgentStore.getState().internal_dispatchAgentMap(agentId, {+ avatar: agentMeta.avatar ?? undefined,+ backgroundColor: agentMeta.backgroundColor ?? undefined,+ name: agentMeta.name ?? undefined,+ title: agentMeta.title ?? undefined,+ });+};++/**+ * Seeds the agent/chat stores for the visitor-facing share surface and reports+ * whether the one-time destructive init has landed yet.+ *+ * Split into two effects with different dependencies on purpose:+ * - **identity effect** (`agentId`/`shareId`): the one destructive init —+ * resets chat-store selection state (`activeTopicId` and friends). Must+ * only fire when the agent/share identity actually changes.+ * - **metadata effect** (`agentMeta`): non-destructive agentMap re-seed so+ * the header avatar/name/title stay fresh. An SWR revalidation hands back a+ * brand-new `agentMeta` object even when the identity hasn't changed;+ * folding this into the identity effect would wipe `activeTopicId` on every+ * metadata refresh and yank the visitor into a new conversation mid-chat.+ */+export const useVisitorConversationSeed = ({+ agentId,+ agentMeta,+ shareId,+}: SharedAgentIdentity): boolean => {+ const [seeded, setSeeded] = useState(false);++ useLayoutEffect(() => {+ seedAgentMap(agentId, agentMeta);+ useAgentStore.setState({ activeAgentId: agentId }, false, 'AgentShareVisitor/seedSharedAgent');+ useChatStore.setState(+ {+ activeAgentId: agentId,+ activeGroupId: undefined,+ activeThreadId: undefined,+ activeTopicId: undefined,+ },+ false,+ 'AgentShareVisitor/sync',+ );+ setSeeded(true);+ // Deliberately keyed on the agent/share identity only — the metadata+ // effect below handles `agentMeta` changes without touching chat-store+ // selection state. See the doc comment above for why.+ }, [agentId, shareId]);++ useLayoutEffect(() => {+ seedAgentMap(agentId, agentMeta);+ }, [agentId, agentMeta]);++ return seeded;+};diff --git a/src/features/AgentShareVisitor/useVisitorTopics.ts b/src/features/AgentShareVisitor/useVisitorTopics.tsnew file mode 100644index 00000000000..a4e21f1f001--- /dev/null+++ b/src/features/AgentShareVisitor/useVisitorTopics.ts@@ -0,0 +1,22 @@+import useSWR from 'swr';++import { shareKeys } from '@/libs/swr/keys';+import { shareChatService } from '@/services/shareChat';++/**+ * The visitor's own topics on this shared agent (server-scoped by senderId).+ *+ * `enabled` is off for a non-interactive share (see `isShareInteractive`):+ * `shareChat.getTopics` requires `link` visibility, so an owner previewing+ * their own private share would otherwise always see a `FORBIDDEN` panel with+ * a retry that can never succeed. With the fetch skipped the panel falls+ * through to its empty state, which is the truth for a preview.+ */+export const useVisitorTopics = (shareId: string, enabled = true) =>+ useSWR(+ enabled ? shareKeys.visitorTopics(shareId) : null,+ () => shareChatService.getTopics(shareId),+ {+ revalidateOnFocus: false,+ },+ );diff --git a/src/features/Auth/SignIn/DevSeedSignIn.tsx b/src/features/Auth/SignIn/DevSeedSignIn.tsxnew file mode 100644index 00000000000..7d345a6879b--- /dev/null+++ b/src/features/Auth/SignIn/DevSeedSignIn.tsx@@ -0,0 +1,65 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { Button, Text } from '@lobehub/ui/base-ui';+import { memo, useEffect, useState } from 'react';++const SEED_SIGN_IN_PATH = '/api/dev/seed-sign-in';++/**+ * Dev-only quick login for the seeded runtime accounts (see the cloud+ * `dev:runtime` tooling). Renders nothing unless the backend exposes the+ * dev seed sign-in route, so plain OSS dev setups and production builds+ * (`import.meta.env.DEV` is compiled away) never show it. English-only on+ * purpose — it is a developer tool, not a user-facing surface.+ */+const DevSeedSignIn = memo(() => {+ const [available, setAvailable] = useState(false);++ useEffect(() => {+ if (!import.meta.env.DEV) return;++ const controller = new AbortController();+ fetch(`${SEED_SIGN_IN_PATH}?probe=1`, { signal: controller.signal })+ .then((res) => setAvailable(res.status === 204))+ .catch(() => {});++ return () => controller.abort();+ }, []);++ if (!import.meta.env.DEV || !available) return null;++ return (+ <Flexbox align={'center'} gap={8} paddingBlock={12}>+ <Text fontSize={12} type={'secondary'}>+ Dev quick login+ </Text>+ <Flexbox horizontal gap={8}>+ {(['ultimate', 'free'] as const).map((account) => (+ <Button+ key={account}+ size={'small'}+ onClick={() => {+ // The dev route is an API endpoint that sets the session cookie+ // and redirects, so this must be a full navigation — not a+ // client-side router push.+ const target = new URL(SEED_SIGN_IN_PATH, window.location.origin);+ target.searchParams.set('account', account);+ // Forward the sign-in page's callbackUrl so the quick login+ // returns to the deep link that triggered it (e.g. a share URL).+ const callbackUrl = new URLSearchParams(window.location.search).get('callbackUrl');+ if (callbackUrl) target.searchParams.set('callbackUrl', callbackUrl);+ window.location.assign(target.href);+ }}+ >+ {account === 'ultimate' ? 'Ultimate' : 'Free'}+ </Button>+ ))}+ </Flexbox>+ </Flexbox>+ );+});++DevSeedSignIn.displayName = 'DevSeedSignIn';++export default DevSeedSignIn;diff --git a/src/features/Auth/SignIn/index.tsx b/src/features/Auth/SignIn/index.tsxindex 3ce78346f2f..b6f91324c1e 100644--- a/src/features/Auth/SignIn/index.tsx+++ b/src/features/Auth/SignIn/index.tsx@@ -1,5 +1,6 @@'use client';+import DevSeedSignIn from './DevSeedSignIn';import { SignInEmailSentStep } from './SignInEmailSentStep';import { SignInEmailStep } from './SignInEmailStep';import { SignInPasswordStep } from './SignInPasswordStep';@@ -55,22 +56,25 @@ const SignIn = () => {);return (- <SignInEmailStep- disableEmailPassword={disableEmailPassword}- form={form as any}- isSocialOnly={isSocialOnly}- lastAuthProvider={lastAuthProvider}- loading={loading}- oAuthSSOProviders={oAuthSSOProviders}- serverConfigInit={serverConfigInit}- sessionExpired={sessionExpired}- socialLoading={socialLoading}- onCheckUser={handleCheckUser}- onGoToSignup={handleGoToSignup}- onResetEmail={handleBackToEmail}- onSetPassword={handleForgotPassword}- onSocialSignIn={handleSocialSignIn}- />+ <>+ <SignInEmailStep+ disableEmailPassword={disableEmailPassword}+ form={form as any}+ isSocialOnly={isSocialOnly}+ lastAuthProvider={lastAuthProvider}+ loading={loading}+ oAuthSSOProviders={oAuthSSOProviders}+ serverConfigInit={serverConfigInit}+ sessionExpired={sessionExpired}+ socialLoading={socialLoading}+ onCheckUser={handleCheckUser}+ onGoToSignup={handleGoToSignup}+ onResetEmail={handleBackToEmail}+ onSetPassword={handleForgotPassword}+ onSocialSignIn={handleSocialSignIn}+ />+ <DevSeedSignIn />+ </>);};diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsxindex 63ba38842e6..2362cc30954 100644--- a/src/features/Conversation/ChatList/index.tsx+++ b/src/features/Conversation/ChatList/index.tsx@@ -153,8 +153,9 @@ const ChatList = memo<ChatListProps>(const overlayHeight = useConversationStore(inputSelectors.chatInputOverlayHeight);const latestMessageId = displayMessageIds.at(-1);- // Skip fetching notebook and memories for share pages (they require authentication)- const isSharePage = !!context.topicShareId;+ // Skip fetching notebook and memories for share pages — topic shares may be+ // anonymous, and agent-share visitors are not the owner these APIs scope to.+ const isSharePage = !!context.topicShareId || !!context.agentShareId;// TODO: Migrate Agent Signal receipts behind a dedicated user-visible receipt capability.const canShowAgentSignalReceipts = enableAgentSelfIteration === true && !isSharePage;const { receiptsByAnchor } = useAgentSignalReceipts({@@ -172,9 +173,14 @@ const ChatList = memo<ChatListProps>(// an arbitrary author's agent; without this they render "未命名助理".// Idempotent: SWR dedupes against any route-level init by the same key,// and is gated on isLogin (no fetch for anonymous share viewers).+ // Agent-share visitors are signed in but NOT the owner: the owner-scoped+ // config API resolves to null and `markAgentNotFound` would wipe the+ // share-seeded agentMap entry, so skip the fetch entirely — the visitor+ // page already seeds the meta from `getSharedAgent`.const isLogin = useUserStore(authSelectors.isLogin);+ const isAgentShareVisitor = !!context.agentShareId;const useFetchAgentConfig = useAgentStore((s) => s.useFetchAgentConfig);- useFetchAgentConfig(isLogin, context.agentId);+ useFetchAgentConfig(isLogin && !isAgentShareVisitor, context.agentId);const messageAuthorAgentIds = useMemo(() =>[...new Set(displayMessages.map((message) => message.agentId).filter(Boolean))].filter(@@ -282,7 +288,11 @@ const ChatList = memo<ChatListProps>(return (<Flexbox style={{ height: '100%', minHeight: 0 }}>{messageAuthorAgentIds.map((agentId) => (- <MessageAuthorConfigLoader agentId={agentId} isLogin={isLogin} key={agentId} />+ <MessageAuthorConfigLoader+ agentId={agentId}+ isLogin={isLogin && !isAgentShareVisitor}+ key={agentId}+ />))}<Flexbox flex={1} style={{ minHeight: 0 }}>{content}diff --git a/src/features/Conversation/ConversationProvider.tsx b/src/features/Conversation/ConversationProvider.tsxindex 6b69522df34..962e68e0c69 100644--- a/src/features/Conversation/ConversationProvider.tsx+++ b/src/features/Conversation/ConversationProvider.tsx@@ -29,7 +29,7 @@ interface ConversationContextPrefetcherProps {}const ConversationContextPrefetcher = memo<ConversationContextPrefetcherProps>(({ context }) => {- useFetchAvailableAgents(!context.topicShareId && !!context.agentId);+ useFetchAvailableAgents(!context.topicShareId && !context.agentShareId && !!context.agentId);return null;});diff --git a/src/features/Conversation/Markdown/plugins/LocalFile/Render/index.tsx b/src/features/Conversation/Markdown/plugins/LocalFile/Render/index.tsxindex c5f45377386..63bd19aae1c 100644--- a/src/features/Conversation/Markdown/plugins/LocalFile/Render/index.tsx+++ b/src/features/Conversation/Markdown/plugins/LocalFile/Render/index.tsx@@ -15,7 +15,13 @@ interface LocalFileProps {const Render = memo<MarkdownElementProps<LocalFileProps>>(({ node }) => {// Extract properties from node.propertiesconst { name, path, isDirectory } = node?.properties || {};- const isSharePage = useConversationStore((s) => !!s.context.topicShareId);+ // Both share surfaces are read-only for the viewer. On the agent-share+ // visitor page this also matters on Electron: an interactive chip would let+ // a model/creator-controlled `<local_file path>` open a path on the+ // VISITOR's machine via `shell.openPath`.+ const isSharePage = useConversationStore(+ (s) => !!s.context.topicShareId || !!s.context.agentShareId,+ );if (!name || !path) {// If required properties are missing, render an error or nulldiff --git a/src/features/ProfileEditor/PluginTag.tsx b/src/features/ProfileEditor/PluginTag.tsxindex b5d34592a52..08aa06082c1 100644--- a/src/features/ProfileEditor/PluginTag.tsx+++ b/src/features/ProfileEditor/PluginTag.tsx@@ -7,7 +7,7 @@ import { Avatar, Tag } from '@lobehub/ui/base-ui';import { McpIcon } from '@lobehub/ui/icons';import { createStaticStyles, cssVar } from 'antd-style';import isEqual from 'fast-deep-equal';-import { AlertCircle, Loader2, Square, SquareCheckBig, X } from 'lucide-react';+import { AlertCircle, Loader2, Square, SquareCheckBig, SquareMinus, X } from 'lucide-react';import React, { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -92,6 +92,14 @@ export interface PluginTagProps {*/agentId?: string;disabled?: boolean;+ /**+ * Renders the `selectable` checkbox in the "some but not all" state (a minus+ * box instead of a tick), the antd `indeterminate` / Gmail select-all+ * convention. Only meaningful together with `selected`: the chip represents+ * a container whose children are partially selected — e.g. an agent-share+ * tool granted for some of its APIs but not all.+ */+ indeterminate?: boolean;onRemove?: (e: React.MouseEvent) => void;/** Fires when the checkbox/tag is toggled in `selectable` mode. */onSelect?: () => void;@@ -137,6 +145,7 @@ const PluginTag = memo<PluginTagProps>(pluginId,onRemove,onSelect,+ indeterminate = false,removable = true,selectable = false,selected = false,@@ -392,7 +401,7 @@ const PluginTag = memo<PluginTagProps>(selectable ? (<Flexbox horizontal align={'center'} gap={6}><Icon- icon={selected ? SquareCheckBig : Square}+ icon={selected ? (indeterminate ? SquareMinus : SquareCheckBig) : Square}size={14}style={{ color: selected ? cssVar.colorPrimary : cssVar.colorTextQuaternary }}/>diff --git a/src/features/ResourceTransferRequest/TransferRequestItem.tsx b/src/features/ResourceTransferRequest/TransferRequestItem.tsxindex b50bf195ae4..20427d43d5d 100644--- a/src/features/ResourceTransferRequest/TransferRequestItem.tsx+++ b/src/features/ResourceTransferRequest/TransferRequestItem.tsx@@ -34,6 +34,7 @@ const TRANSFER_ERROR_KEY_BY_CODE: Partial<Record<TransferErrorCode, string>> = {[TransferErrorCode.CopyInProgress]: 'error:transfer.copyInProgress',[TransferErrorCode.GroupHasInaccessibleMember]: 'error:transfer.groupHasInaccessibleMember',[TransferErrorCode.ResourceNotFound]: 'error:transfer.resourceNotFound',+ [TransferErrorCode.SharedTransferBlocked]: 'error:transfer.sharedTransferBlocked',[TransferErrorCode.TargetNoWriteAccess]: 'error:transfer.targetNoWriteAccess',[TransferErrorCode.TargetNotWorkspaceMember]: 'error:transfer.targetNotWorkspaceMember',[TransferErrorCode.TransferInProgress]: 'error:transfer.transferInProgress',diff --git a/src/features/RouteMeta/AgentDynamicMeta.tsx b/src/features/RouteMeta/AgentDynamicMeta.tsxindex 2e728e3412d..4805abb6e2e 100644--- a/src/features/RouteMeta/AgentDynamicMeta.tsx+++ b/src/features/RouteMeta/AgentDynamicMeta.tsx@@ -94,6 +94,7 @@ export const TopicsDynamicMeta = createAgentSectionDynamicMeta('navigation.topicexport const ProfileDynamicMeta = createAgentSectionDynamicMeta('navigation.profile');export const ChannelDynamicMeta = createAgentSectionDynamicMeta('navigation.channels');export const StatisticsDynamicMeta = createAgentSectionDynamicMeta('navigation.stats');+export const ShareDynamicMeta = createAgentSectionDynamicMeta('navigation.agentShare');export const SelfLearningDynamicMeta = createAgentSectionDynamicMeta('navigation.selfLearning');export const PermissionDynamicMeta = createAgentSectionDynamicMeta('navigation.permission');diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.tsindex 36dea59af4e..28183fe9feb 100644--- a/src/helpers/executionTarget.test.ts+++ b/src/helpers/executionTarget.test.ts@@ -1106,6 +1106,60 @@ describe('resolveExecutionPlan', () => {});});+ // Agent Share visitors: `canUseDevice` is always false and the creator may+ // have granted `lobe-cloud-sandbox` — the grant is honoured via the sandbox+ // instead of being dropped with `none`.+ describe('sandboxFallback — device-denied runs resolve to the sandbox', () => {+ it('sends a denied device-capable target to the sandbox', () => {+ for (const executionTarget of ['local', 'device', 'auto'] as const) {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget }),+ canUseDevice: false,+ clientExecutionAvailable: true,+ onlineDeviceIds: ['device-a'],+ sandboxFallback: true,+ }),+ ).toEqual({ kind: 'sandbox', target: 'sandbox' });+ }+ });++ it('is a no-op without the flag — the denied run still degrades to none', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ executionTarget: 'local' }),+ canUseDevice: false,+ clientExecutionAvailable: true,+ sandboxFallback: false,+ }),+ ).toEqual({ kind: 'none', target: 'none' });+ });++ it('never overrides chat mode — chat means no tools, not no device', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ executionTarget: 'local' }),+ canUseDevice: false,+ chatConfig: { enableAgentMode: false },+ clientExecutionAvailable: true,+ sandboxFallback: true,+ }),+ ).toEqual({ kind: 'none', target: 'none' });+ });++ it('does not resurrect device routing when the device is allowed', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget: 'device' }),+ canUseDevice: true,+ clientExecutionAvailable: true,+ onlineDeviceIds: ['device-a'],+ sandboxFallback: true,+ }),+ ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'device' });+ });+ });+describe('onlineDeviceIds=undefined — hetero dispatch semantics', () => {it('trusts the binding without online checks and never auto-activates', () => {expect(diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.tsindex 76c89afde09..3758d19fa14 100644--- a/src/helpers/executionTarget.ts+++ b/src/helpers/executionTarget.ts@@ -419,6 +419,16 @@ export interface ResolveExecutionPlanParams {requestedDeviceId?: string;/** See {@link ResolveExecutionTargetOptions.sandboxExecutionAvailable}. */sandboxExecutionAvailable?: boolean;+ /**+ * Resolve to the cloud sandbox instead of `none` whenever the run cannot+ * route to a device (a device-capable target denied by `canUseDevice`, or a+ * stored `none` target). Set by the aiAgent caller for Agent Share visitor+ * runs the creator granted `lobe-cloud-sandbox`: a visitor can never reach+ * the creator's device, so the sandbox is the only surface that grant can+ * mean, and it only materializes when the plan resolves to `sandbox`. Chat+ * mode still wins — it means "no tools", not "no device".+ */+ sandboxFallback?: boolean;/*** What initiated this run. Bot triggers have no UI to pick a device, so a* stored `local` target (in-process IPC, unreachable from the cloud bot@@ -441,7 +451,8 @@ export interface ResolveExecutionPlanParams {* 2. `none` / `sandbox` NEVER route to a device — no auto-activation, no* step-level re-injection, no exceptions.* 3. `canUseDevice === false` degrades any device-capable target to `none`- * (sandbox stays available — it never touches the user's machines).+ * (sandbox stays available — it never touches the user's machines). With+ * `sandboxFallback` the degraded run resolves to the sandbox instead.* 4. With online info: a bound device is used only if online (an offline* binding stays unrouted rather than guessing another machine). An UNBOUND* run auto-activates ONLY in the opt-in `auto` mode (single device → use it;@@ -463,6 +474,7 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): ExecutonlineDeviceIds,requestedDeviceId,sandboxExecutionAvailable,+ sandboxFallback,trigger,workspaceScoped,} = params;@@ -499,6 +511,10 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Execut// no device can run. Device-only providers stay pending at `none` so the// caller can require an explicit local/connected-device selection.if (isHetero && sandboxAvailable) return { kind: 'sandbox', target: 'sandbox' };+ // Share-visitor runs granted the cloud sandbox land here for every+ // device-capable target (visitors never pass `canUseDevice`); the grant+ // is honoured with the sandbox rather than dropped with `none`.+ if (sandboxFallback) return { kind: 'sandbox', target: 'sandbox' };// a device-capable target denied by the access policy degrades to plain// chat — the effective target is `none`, not the stored onereturn { kind: 'none', target: 'none' };diff --git a/src/hooks/useGatewayReconnect.ts b/src/hooks/useGatewayReconnect.tsindex e9c232cc9ea..7eb6b43d9b6 100644--- a/src/hooks/useGatewayReconnect.ts+++ b/src/hooks/useGatewayReconnect.ts@@ -36,6 +36,13 @@ export const useGatewayReconnect = (* unset — see `reconnectToGatewayOperation`.*/agentId?: string,+ /**+ * Present on the agent-share visitor surface. Routes the reconnect's token+ * refresh and cancellation through the share-authorized `shareChat`+ * procedures instead of the owner-scoped ones — see+ * `reconnectToGatewayOperation`'s param JSDoc.+ */+ agentShareId?: string,) => {const agentGatewayUrl = useServerConfigStore((s) => s.serverConfig.agentGatewayUrl);@@ -48,6 +55,7 @@ export const useGatewayReconnect = (await useChatStore.getState().reconnectToGatewayOperation({agentId,+ agentShareId,assistantMessageId: runningOperation.assistantMessageId,heteroType: runningOperation.heteroType,operationId: runningOperation.operationId,diff --git a/src/libs/next/config/define-config.test.ts b/src/libs/next/config/define-config.test.tsindex 8f4f2ca9f03..4ba4f833a48 100644--- a/src/libs/next/config/define-config.test.ts+++ b/src/libs/next/config/define-config.test.ts@@ -14,6 +14,25 @@ describe('defineConfig', () => {else process.env.NEXT_PUBLIC_ASSET_PREFIX = originalLegacyPrefix;});+ describe('headers', () => {+ // Agent Share visitor pages (`/agent/:slugOrId`) are link-visible private+ // content: the route-scoped noindex must come AFTER the global+ // `x-robots-tag: all` rule so it overrides it for that path.+ it('marks /agent/* noindex, overriding the global x-robots-tag', async () => {+ const config = defineConfig({});+ const rules = await config.headers!();++ const globalIndex = rules.findIndex((rule) => rule.source === '/:path*');+ const agentIndex = rules.findIndex((rule) => rule.source === '/agent/:path*');++ expect(globalIndex).toBeGreaterThanOrEqual(0);+ expect(agentIndex).toBeGreaterThan(globalIndex);+ expect(rules[agentIndex].headers).toEqual([+ { key: 'x-robots-tag', value: 'noindex, nofollow' },+ ]);+ });+ });+it('disables Next.js agent rule injection', () => {expect(defineConfig({}).agentRules).toBe(false);});diff --git a/src/libs/next/config/define-config.ts b/src/libs/next/config/define-config.tsindex 97ea08116fe..064e83d2bbe 100644--- a/src/libs/next/config/define-config.ts+++ b/src/libs/next/config/define-config.ts@@ -110,6 +110,15 @@ export function defineConfig(config: CustomNextConfig) {headers: securityHeaders,source: '/:path*',},+ // Agent Share visitor pages live under `/agent/:slugOrId` and are+ // reachable by anyone holding the link. Keep them out of search+ // indexes (privacy) — the SPA shell is static per variant, so a+ // per-route `<meta name="robots">` is not an option; the header is.+ // Listed after the global rule so it overrides `x-robots-tag: all`.+ {+ headers: [{ key: 'x-robots-tag', value: 'noindex, nofollow' }],+ source: '/agent/:path*',+ },{headers: [{diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex f1dab21bd6c..4812f0cb4b9 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -48,6 +48,8 @@ interface LocalFilePreviewKeyParams {// ---- message ------------------------------------------------------------export interface MessageListQueryContext {agentId?: string | null;+ /** Agent-share visitor surface — routes the read through `shareChat.getMessages`. */+ agentShareId?: string;groupId?: string | null;threadId?: string | null;topicId?: string | null;@@ -56,6 +58,7 @@ export interface MessageListQueryContext {export interface CanonicalMessageListContext {agentId: string | null;+ agentShareId?: string;groupId: string | null;threadId: string | null;topicId: string | null;@@ -76,6 +79,7 @@ export const normalizeMessageListQueryContext = (threadId: context.threadId ?? null,topicId: context.topicId ?? null,...(context.topicShareId === undefined ? {} : { topicShareId: context.topicShareId }),+ ...(context.agentShareId === undefined ? {} : { agentShareId: context.agentShareId }),});/** Previous persisted key schema, used only by the targeted v1 → v2 migration. */@@ -1148,8 +1152,18 @@ export const inboxKeys = {]),};-// ---- share (shared topic / page) ----------------------------------------+// ---- share (shared agent / topic / page) ---------------------------------export const shareKeys = {+ agentInfo: def('share:agentInfo', (slugOrId: string) => ['share:agentInfo', slugOrId]),+ // Creator-side share status keyed by agentId (visitor side uses `agentInfo`).+ agentShareStats: def('share:agentShareStats', (agentId: string) => [+ 'share:agentShareStats',+ agentId,+ ]),+ agentShareStatus: def('share:agentShareStatus', (agentId: string) => [+ 'share:agentShareStatus',+ agentId,+ ]),artifact: def('share:artifact', (id: string) => ['share:artifact', id]),pageDocument: def('share:pageDocument', (documentId: string) => ['share:pageDocument',@@ -1157,6 +1171,8 @@ export const shareKeys = {]),topic: def('share:topic', (id: string) => ['share:topic', id]),topicInfo: def('share:topicInfo', (topicId: string) => ['share:topicInfo', topicId]),+ /** The visitor's own topics under an agent share (server-scoped by senderId). */+ visitorTopics: def('share:visitorTopics', (shareId: string) => ['share:visitorTopics', shareId]),};// ---- fork source (community detail) -------------------------------------diff --git a/src/routes/(main)/_layout/index.desktop.tsx b/src/routes/(main)/_layout/index.desktop.tsxindex fa47b50993f..1d4742c7303 100644--- a/src/routes/(main)/_layout/index.desktop.tsx+++ b/src/routes/(main)/_layout/index.desktop.tsx@@ -9,6 +9,7 @@ import { Suspense } from 'react';import { HotkeysProvider } from 'react-hotkeys-hook';import WorkspaceContextSlot from '@/business/client/WorkspaceContextSlot';+import { useIsAgentShareVisitorRoute } from '@/features/AgentRoute/useAgentShareVisitorRoute';import DesktopBrowserGatewayBridge from '@/features/DesktopBrowserGatewayBridge';import DesktopFileMenuBridge from '@/features/DesktopFileMenuBridge';import DesktopLayoutContainer from '@/features/DesktopLayoutContainer';@@ -48,6 +49,12 @@ const Layout: FC = () => {const { isPWA } = usePlatform();const { showCloudPromotion } = useServerConfigStore(featureFlagsSelectors);+ // The nav lives outside `TabHost`, so it reads the active tab's location+ // (mirrored into the electron store) rather than the root router's — see+ // `useActiveLocation.desktop`. A visitor has no nav data, so the panel would+ // stay a grey skeleton; unmount it for that branch of `/agent/:aid`.+ const isShareVisitor = useIsAgentShareVisitorRoute();+useSeedTabsOnBoot();useWindowUrlMirror();useLastWorkspaceSlugSync();@@ -81,7 +88,7 @@ const Layout: FC = () => {height={`calc(100% - ${TITLE_BAR_HEIGHT}px)`}width={'100%'}>- <NavPanelShell />+ {!isShareVisitor && <NavPanelShell />}<DesktopLayoutContainer><Flexbox height={'100%'} style={tabHostContainer} width={'100%'}><TabHost />diff --git a/src/routes/(main)/_layout/index.tsx b/src/routes/(main)/_layout/index.tsxindex 3ab59dd3dae..ea91a674213 100644--- a/src/routes/(main)/_layout/index.tsx+++ b/src/routes/(main)/_layout/index.tsx@@ -12,6 +12,7 @@ import { Outlet } from 'react-router';import WorkspaceContextSlot from '@/business/client/WorkspaceContextSlot';import RouteSegmentSkeleton from '@/components/Skeleton/RouteSegment';import { isDesktop } from '@/const/version';+import { useIsAgentShareVisitorRoute } from '@/features/AgentRoute/useAgentShareVisitorRoute';import { BANNER_HEIGHT } from '@/features/AlertBanner/CloudBanner';import DesktopBrowserGatewayBridge from '@/features/DesktopBrowserGatewayBridge';import DesktopFileMenuBridge from '@/features/DesktopFileMenuBridge';@@ -45,6 +46,9 @@ const GlobalApprovalNotification = dynamic(() => import('@/features/GlobalApprovconst Layout: FC = () => {const { isPWA } = usePlatform();const { showCloudPromotion } = useServerConfigStore(featureFlagsSelectors);+ // An agent-share visitor has no access to the nav's data, so the panel would+ // stay a grey skeleton — unmount it for that branch of `/agent/:aid`.+ const isShareVisitor = useIsAgentShareVisitorRoute();return (<HotkeysProvider initiallyActiveScopes={[HotkeyScopeEnum.Global]}>@@ -78,7 +82,7 @@ const Layout: FC = () => {: '100%'}>- <NavPanelShell />+ {!isShareVisitor && <NavPanelShell />}<DesktopLayoutContainer><DesktopHomeLayout><DesktopHome />diff --git a/src/routes/(main)/agent/features/routeMeta.ts b/src/routes/(main)/agent/features/routeMeta.tsindex d4a92a0d7b0..be41c2d3521 100644--- a/src/routes/(main)/agent/features/routeMeta.ts+++ b/src/routes/(main)/agent/features/routeMeta.ts@@ -5,10 +5,12 @@ import {MessageSquare,MessagesSquareIcon,RadioTowerIcon,+ Share2Icon,UsersIcon,} from 'lucide-react';import { lazy } from 'react';+import AgentShareSkeleton from '@/components/Skeleton/AgentShare';import ConversationLayoutSkeleton from '@/components/Skeleton/Conversation/Layout';import ProfileSkeleton from '@/components/Skeleton/Profile';import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';@@ -36,6 +38,11 @@ const StatisticsDynamicMeta = lazy(() =>default: module.StatisticsDynamicMeta,})),);+const ShareDynamicMeta = lazy(() =>+ import('@/features/RouteMeta/AgentDynamicMeta').then((module) => ({+ default: module.ShareDynamicMeta,+ })),+);const SelfLearningDynamicMeta = lazy(() =>import('@/features/RouteMeta/AgentDynamicMeta').then((module) => ({default: module.SelfLearningDynamicMeta,@@ -82,6 +89,13 @@ export const agentStatisticsRouteMeta = routeMeta({titleKey: 'navigation.stats',});+export const agentShareRouteMeta = routeMeta({+ DynamicMeta: ShareDynamicMeta,+ icon: Share2Icon,+ Skeleton: AgentShareSkeleton,+ titleKey: 'navigation.agentShare',+});+export const agentSelfLearningRouteMeta = routeMeta({DynamicMeta: SelfLearningDynamicMeta,icon: GraduationCapIcon,diff --git a/src/routes/(main)/agent/profile/features/Header/index.test.tsx b/src/routes/(main)/agent/profile/features/Header/index.test.tsxindex 29308325094..6af9a32dc56 100644--- a/src/routes/(main)/agent/profile/features/Header/index.test.tsx+++ b/src/routes/(main)/agent/profile/features/Header/index.test.tsx@@ -35,6 +35,17 @@ const mocks = vi.hoisted(() => ({homeState: {removeAgent: vi.fn(),},+ hasActiveWorkspace: true,+ /** What the share-entry hook's live-share lookup resolves to. */+ shareStatus: null as { visibility: 'link' | 'private' } | null,+ serverConfigState: {+ featureFlags: { enableAgentShare: undefined as boolean | undefined },+ // Business features on by default in these tests — the Cloud-only+ // structural half of the share gate is exercised by its own describe+ // block below; everywhere else it stays open so the pre-existing+ // rollout-flag behavior remains isolated to that one variable.+ serverConfig: { enableBusinessFeatures: true },+ },navigate: vi.fn(),// The two independent halves of "may configure this agent": the workspace// role permission and this agent's General Access level.@@ -46,6 +57,16 @@ const mocks = vi.hoisted(() => ({},}));+// `useAgentShareSupported` looks the live share up (via SWR) only for an+// account that may not publish; resolve it synchronously here.+vi.mock('swr', () => ({+ default: (key: unknown, fetcher: () => unknown) => ({ data: key ? fetcher() : undefined }),+}));++vi.mock('@/services/agentShare', () => ({+ agentShareService: { getShareStatus: () => mocks.shareStatus },+}));+vi.mock('@lobechat/const', async (importOriginal) => ({...(await importOriginal<typeof LobeChatConst>()),isDesktop: false,@@ -122,6 +143,7 @@ vi.mock('lucide-react', async (importOriginal) => ({Download: () => null,MoreHorizontal: () => null,Settings2Icon: () => null,+ Share2Icon: () => <span data-testid="share-entry-icon" />,Trash: () => null,}));@@ -146,7 +168,7 @@ vi.mock('@/features/AgentBreadcrumb', () => ({}));vi.mock('@/business/client/hooks/useHasActiveWorkspace', () => ({- useHasActiveWorkspace: () => true,+ useHasActiveWorkspace: () => mocks.hasActiveWorkspace,}));vi.mock('@/features/ResourcePermission/AccessLevelTag', () => ({@@ -225,6 +247,19 @@ vi.mock('@/store/home', () => ({useHomeStore: (selector: (state: typeof mocks.homeState) => unknown) => selector(mocks.homeState),}));+vi.mock('@/store/serverConfig', () => ({+ useServerConfigStore: (selector: (state: typeof mocks.serverConfigState) => unknown) =>+ selector(mocks.serverConfigState),+}));++vi.mock('@/store/serverConfig/selectors', () => ({+ featureFlagsSelectors: (state: typeof mocks.serverConfigState) => state.featureFlags,+ serverConfigSelectors: {+ enableBusinessFeatures: (state: typeof mocks.serverConfigState) =>+ state.serverConfig.enableBusinessFeatures,+ },+}));+vi.mock('../store', () => ({selectors: {lockHolderId: (s: typeof mocks.profileState) => s.lockState.holderId,@@ -261,6 +296,85 @@ describe('Agent profile Header', () => {mocks.permission.allowed = true;mocks.resourceAccess.canEditResource = true;mocks.resourceAccess.canManageResource = true;+ mocks.hasActiveWorkspace = true;+ mocks.serverConfigState.featureFlags.enableAgentShare = undefined;+ mocks.serverConfigState.serverConfig.enableBusinessFeatures = true;+ });++ describe('share entry', () => {+ // Agent sharing is personal-only, so the entry needs a personal agent;+ // the rollout flag is on unless a case says otherwise.+ beforeEach(() => {+ mocks.hasActiveWorkspace = false;+ mocks.serverConfigState.featureFlags.enableAgentShare = true;+ mocks.shareStatus = null;+ });++ it('offers the share entry to a personal agent owner', () => {+ render(<Header />);++ expect(screen.getByTestId('share-entry-icon')).toBeInTheDocument();+ });++ // Outside the rollout allowlist the entry is hidden entirely …+ it('hides the share entry when the account may not publish and has no live share', () => {+ mocks.serverConfigState.featureFlags.enableAgentShare = false;+ mocks.shareStatus = null;++ render(<Header />);++ expect(screen.queryByTestId('share-entry-icon')).toBeNull();+ });++ // … unless a share is already live: an owner rolled back out of the+ // allowlist still needs the entry to reach (and revoke) it.+ it('keeps the share entry for a live share when the account may not publish', () => {+ mocks.serverConfigState.featureFlags.enableAgentShare = false;+ mocks.shareStatus = { visibility: 'link' };++ render(<Header />);++ expect(screen.getByTestId('share-entry-icon')).toBeInTheDocument();+ });++ it('hides the share entry while the capability is still unresolved', () => {+ mocks.serverConfigState.featureFlags.enableAgentShare = undefined;+ mocks.shareStatus = null;++ render(<Header />);++ expect(screen.queryByTestId('share-entry-icon')).toBeNull();+ });++ // Unlike the rollout flag above, `enableBusinessFeatures` is structural:+ // an OSS deployment has no Agent Share surface at all, server-enforced by+ // `ENABLE_BUSINESS_FEATURES` — there is no live share to revoke there, so+ // hiding the entry entirely (not just disabling publish) is correct.+ it('hides the share entry on a deployment without business features', () => {+ mocks.serverConfigState.serverConfig.enableBusinessFeatures = false;++ render(<Header />);++ expect(screen.queryByTestId('share-entry-icon')).toBeNull();+ });++ it('hides the share entry for a workspace agent', () => {+ mocks.hasActiveWorkspace = true;++ render(<Header />);++ expect(screen.queryByTestId('share-entry-icon')).toBeNull();+ });++ // Share settings are a sibling tab of the profile group now, so the entry+ // navigates instead of opening a modal.+ it('navigates to the share tab', () => {+ render(<Header />);++ fireEvent.click(screen.getByTestId('share-entry-icon'));++ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agent-1/share');+ });});// `ResourceConfigAccessGate` requires the role permission AND resource-leveldiff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsxindex 8ca8245ef29..0b427ce191e 100644--- a/src/routes/(main)/agent/profile/features/Header/index.tsx+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx@@ -10,6 +10,7 @@ import {Download,MoreHorizontal,Settings2Icon,+ Share2Icon,Trash,UserRound,UsersIcon,@@ -25,6 +26,7 @@ import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorksimport { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';import AgentBreadcrumb from '@/features/AgentBreadcrumb';import AgentProfileTabs, { AGENT_PROFILE_TABS_CENTER_STYLE } from '@/features/AgentProfileTabs';+import { useAgentShareSupported } from '@/features/AgentShareSettings/useAgentShareSupported';import NavHeader from '@/features/NavHeader';import { formatPageEditorInfoTime } from '@/features/PageEditor/formatPageEditorInfoTime';import AccessLevelTag from '@/features/ResourcePermission/AccessLevelTag';@@ -46,7 +48,10 @@ import AgentForkTag from './AgentForkTag';import AgentStatusTag from './AgentStatusTag';import AgentVersionReviewTag from './AgentVersionReviewTag';-type HeaderTranslation = TFunction<readonly ['setting', 'chat', 'file', 'common'], undefined>;+type HeaderTranslation = TFunction<+ readonly ['setting', 'chat', 'file', 'common', 'agent'],+ undefined+>;const buildAgentProfileMarkdown = (params: {description?: string;@@ -98,7 +103,7 @@ const buildAgentProfileMarkdown = (params: {};const Header = memo(() => {- const { i18n, t } = useTranslation(['setting', 'chat', 'file', 'common']);+ const { i18n, t } = useTranslation(['setting', 'chat', 'file', 'common', 'agent']);const dateLocale = i18n?.resolvedLanguage || i18n?.language;const navigate = useWorkspaceAwareNavigate();@@ -245,6 +250,16 @@ const Header = memo(() => {[],);+ const { visible: shareVisible } = useAgentShareSupported(activeAgentId);+ const canShareAgent = shareVisible === true && canConfigure;++ // Share settings are a sibling tab of the profile group, not a popup — the+ // shortcut just jumps to that tab.+ const handleOpenShare = useCallback(() => {+ if (!activeAgentId) return;+ navigate(`/agent/${activeAgentId}/share`);+ }, [activeAgentId, navigate]);+const menuItems = useMemo(() => {const businessTransferMenuItems = transferMenuItems ?? [];@@ -354,10 +369,33 @@ const Header = memo(() => {]);return (+ // `relative` anchors the absolutely-centered switcher below.<NavHeaderstyle={{ position: 'relative' }}+ left={+ <Flexbox horizontal align={'center'} gap={8}>+ {/* No section title — the Segmented beside it names the current tab. */}+ {activeAgentId && <AgentBreadcrumb agentId={activeAgentId} />}+ <AgentStatusTag />+ <AgentVersionReviewTag />+ <AgentForkTag />+ <AccessLevelTag+ resourceId={showPermissionsEntry ? (activeAgentId ?? undefined) : undefined}+ resourceType={'agent'}+ />+ </Flexbox>+ }right={<Flexbox horizontal align={'center'} gap={4}>+ {canShareAgent && (+ <ActionIcon+ icon={Share2Icon}+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}+ title={t('share.entry', { ns: 'agent' })}+ tooltipProps={{ placement: 'bottom' }}+ onClick={handleOpenShare}+ />+ )}<DropdownMenu items={menuItems}><ActionIcon icon={MoreHorizontal} size={DESKTOP_HEADER_ICON_SMALL_SIZE} /></DropdownMenu>@@ -371,20 +409,6 @@ const Header = memo(() => {)}</Flexbox>}- // `relative` anchors the absolutely-centered switcher below.- left={- <Flexbox horizontal align={'center'} gap={8}>- {/* No section title — the Segmented beside it names the current tab. */}- {activeAgentId && <AgentBreadcrumb agentId={activeAgentId} />}- <AgentStatusTag />- <AgentVersionReviewTag />- <AgentForkTag />- <AccessLevelTag- resourceId={showPermissionsEntry ? (activeAgentId ?? undefined) : undefined}- resourceType={'agent'}- />- </Flexbox>- }styles={{// Center the switcher on the *header* midpoint, not within the leftover// flex track between the left/right slots — those slots differ in width,diff --git a/src/routes/(main)/agent/share/index.tsx b/src/routes/(main)/agent/share/index.tsxnew file mode 100644index 00000000000..6d2de0a4f43--- /dev/null+++ b/src/routes/(main)/agent/share/index.tsx@@ -0,0 +1,31 @@+'use client';++import { memo, Suspense } from 'react';+import { useParams } from 'react-router';++import AgentShareSkeleton from '@/components/Skeleton/AgentShare';+import AgentShareSettingsPage from '@/features/AgentShareSettings/Page';+import ResourceConfigAccessGate from '@/features/ResourcePermission/ResourceConfigAccessGate';++const AgentSharePage = memo(() => {+ const { aid } = useParams<{ aid: string }>();++ const skeleton = <AgentShareSkeleton />;++ return (+ <Suspense fallback={skeleton}>+ {/* Sharing exposes real execution on the creator's account — a+ configuration action, gated exactly like Agent Profile / Channels. */}+ <ResourceConfigAccessGate+ loading={skeleton}+ redirectPath={`/agent/${aid ?? ''}`}+ resourceId={aid}+ resourceType="agent"+ >+ <AgentShareSettingsPage />+ </ResourceConfigAccessGate>+ </Suspense>+ );+});++export default AgentSharePage;diff --git a/src/services/agent.ts b/src/services/agent.tsindex 60c742bfd72..2a9897d3a3b 100644--- a/src/services/agent.ts+++ b/src/services/agent.ts@@ -264,12 +264,20 @@ class AgentService {};/**- * Resolve a url slug to its agent id. Returns `null` for an unknown slug and- * for one the caller can't see — the two are deliberately indistinguishable.+ * Resolve what a `/agent/:slugOrId` param points at: one of the caller's own+ * agents (by id or slug), an agent share, or nothing. See the+ * `resolveAgentRoute` procedure for the resolution order and its privacy+ * properties.*/- resolveAgentIdBySlug = async (slug: string): Promise<string | null> => {- const { agentId } = await lambdaClient.agent.resolveAgentIdBySlug.query({ slug });- return agentId;+ resolveAgentRoute = async (slugOrId: string) => {+ // An anonymous visitor on a share URL gets UNAUTHORIZED here (the+ // resolver is auth-gated); opt out of the global 401 handler so it does+ // not hard-redirect them to /signin before the share surface's own+ // sign-in prompt can render (mirrors `agentShareService.getSharedAgent`).+ return lambdaClient.agent.resolveAgentRoute.query(+ { slugOrId },+ { context: { showNotification: false } },+ );};/** Rename an agent's url slug (validated server-side; see `updateAgentSlug`). */diff --git a/src/services/agentShare.ts b/src/services/agentShare.tsnew file mode 100644index 00000000000..1f869238079--- /dev/null+++ b/src/services/agentShare.ts@@ -0,0 +1,53 @@+import { lambdaClient } from '@/libs/trpc/client';+import type {+ AgentShareConfigInput,+ AgentShareConfigPatchInput,+} from '@/server/routers/lambda/agentShare';++class AgentShareService {+ async disableShare(agentId: string) {+ return lambdaClient.agentShare.disableShare.mutate({ agentId });+ }++ async enableShare(agentId: string, visibility?: 'private' | 'link') {+ return lambdaClient.agentShare.enableShare.mutate({ agentId, visibility });+ }++ /** Owner-only aggregate usage (views, visitors, conversations, spend). */+ async getShareStats(agentId: string) {+ return lambdaClient.agentShare.getShareStats.query({ agentId });+ }++ async getShareStatus(agentId: string) {+ return lambdaClient.agentShare.getShareStatus.query({ agentId });+ }++ /** Resolve a share's visitor-facing metadata, by its custom slug or its raw share id. */+ async getSharedAgent(slugOrId: string) {+ // The visitor page renders its own login prompt on UNAUTHORIZED; opt out of+ // the global 401 handler so it does not hard-redirect visitors to /signin.+ return lambdaClient.share.getSharedAgent.query(+ { slugOrId },+ { context: { showNotification: false } },+ );+ }++ async updateShareConfig(agentId: string, config: AgentShareConfigPatchInput) {+ return lambdaClient.agentShare.updateShareConfig.mutate({ agentId, config });+ }++ /**+ * Update the share's custom URL slug, or clear it with `null`. Throws+ * `CONFLICT` if another share already claims it.+ */+ async updateSlug(agentId: string, slug: string | null) {+ return lambdaClient.agentShare.updateSlug.mutate({ agentId, slug });+ }++ async updateVisibility(agentId: string, visibility: 'link' | 'private') {+ return lambdaClient.agentShare.updateVisibility.mutate({ agentId, visibility });+ }+}++export const agentShareService = new AgentShareService();+export type { AgentShareConfigInput, AgentShareConfigPatchInput };diff --git a/src/services/message/index.ts b/src/services/message/index.tsindex 436b0e195b9..38a18ee5991 100644--- a/src/services/message/index.ts+++ b/src/services/message/index.ts@@ -34,6 +34,8 @@ export interface MessageQueryContext {interface MessageReadQueryContext {agentId?: string | null;+ /** Agent-share visitor surface — routes the read through `shareChat.getMessages`. */+ agentShareId?: string;groupId?: string | null;/*** Skip the Work-summary assembly on the server — set by mid-stream@@ -146,6 +148,22 @@ export class MessageService {};getMessages = async (params: MessageReadQueryContext): Promise<UIChatMessage[]> => {+ // Agent-share visitor surface: the owner-scoped query below resolves rows in+ // the CALLER's scope, so it would come back empty for a visitor (share rows+ // belong to the creator). Route through the share-authorized read instead.+ // A share context without a topic is the visitor's new-topic bucket —+ // nothing to fetch.+ if (params.agentShareId) {+ if (!params.topicId) return [];++ const shared = await lambdaClient.shareChat.getMessages.query({+ shareId: params.agentShareId,+ topicId: params.topicId,+ });++ return shared as unknown as UIChatMessage[];+ }+// Opt into `file` (and any future gated) work summaries in the message// payload. This client ships the descriptor fallback; clients that predate// the `file` type run the old service without the flag and stay on thediff --git a/src/services/shareChat.ts b/src/services/shareChat.tsnew file mode 100644index 00000000000..1882e60f939--- /dev/null+++ b/src/services/shareChat.ts@@ -0,0 +1,53 @@+import type { ExecAgentResult, UIChatMessage } from '@lobechat/types';++import { lambdaClient } from '@/libs/trpc/client';++export interface ShareChatExecParams {+ /** Client-minted ids for the rows this run creates (fresh sends only). */+ clientIds?: { assistantMessageId?: string; topicId?: string; userMessageId?: string };+ prompt: string;+ shareId: string;+ /** Absent → the server creates a new visitor topic (counted against the topic cap). */+ topicId?: string | null;+}++/**+ * Visitor-facing chat APIs for shared agents. Mirrors the slice of+ * `aiAgentService` the gateway transport needs (exec + token refresh) plus the+ * visitor-scoped topic/message reads — all keyed by shareId, authorized+ * server-side against `topics.senderId`.+ */+class ShareChatService {+ async execAgentTask(+ params: ShareChatExecParams,+ options?: { signal?: AbortSignal },+ ): Promise<ExecAgentResult> {+ return await lambdaClient.shareChat.execAgent.mutate(params, options);+ }++ async getTopics(shareId: string) {+ return await lambdaClient.shareChat.getTopics.query({ shareId });+ }++ async getMessages(shareId: string, topicId: string): Promise<UIChatMessage[]> {+ const data = await lambdaClient.shareChat.getMessages.query({ shareId, topicId });+ return data as unknown as UIChatMessage[];+ }++ /**+ * Interrupt a running share operation — the visitor counterpart of+ * `aiAgentService.interruptTask`. Visitors have no access to the owner-scoped+ * endpoint, so Stop / tab-close must go through this share-authorized one or+ * the server keeps generating (and billing the creator's share budget) after+ * the visitor walks away.+ */+ async interruptTask(shareId: string, topicId: string, operationId: string) {+ return await lambdaClient.shareChat.interruptTask.mutate({ operationId, shareId, topicId });+ }++ async refreshGatewayToken(shareId: string, topicId: string): Promise<{ token: string }> {+ return await lambdaClient.shareChat.refreshGatewayToken.query({ shareId, topicId });+ }+}++export const shareChatService = new ShareChatService();diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex a7257257830..9e3b9f42435 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -37,6 +37,9 @@ import RouteSegmentSkeleton from '@/components/Skeleton/RouteSegment';import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';import { goalDetailRouteMeta, goalsRouteMeta } from '@/features/AgentGoals/routeMeta';+import AgentRouteSwitch from '@/features/AgentRoute/AgentRouteSwitch';+import AgentShareLegacyRedirect from '@/features/AgentShareVisitor/LegacyRedirect';+import { agentShareVisitorRouteMeta } from '@/features/AgentShareVisitor/routeMeta';import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';import { agentsRouteMeta } from '@/features/AgentViewAll/routeMeta';import { pageRouteMeta } from '@/features/Pages/routeMeta';@@ -50,6 +53,7 @@ import {agentProfileRouteMeta,agentRouteMeta,agentSelfLearningRouteMeta,+ agentShareRouteMeta,agentStatisticsRouteMeta,topicsRouteMeta,} from '@/routes/(main)/agent/features/routeMeta';@@ -220,6 +224,14 @@ export const sharedMainAreaChildren: RouteObject[] = [handle: { meta: agentStatisticsRouteMeta },path: 'statistics',},+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/share'),+ 'Desktop > Chat > Share',+ ),+ handle: { meta: agentShareRouteMeta },+ path: 'share',+ },// Legacy `/agent/:aid/stats` URLs — kept for deep-links.{element: redirectElement('../statistics'),@@ -318,10 +330,25 @@ export const sharedMainAreaChildren: RouteObject[] = [path: 'task/:taskId',},],- element: dynamicLayout(- () => import('@/routes/(main)/agent/_layout'),- 'Desktop > Chat > Layout',- { preloadId: 'agent' },+ // `/agent/:aid` serves both the creator's own agent and the agent-share+ // visitor surface; the param decides which — see `AgentRouteSwitch`.+ // The switch is not a `Suspense`, so `withSegmentFallback` cannot swap+ // the branding loader for a segment skeleton here — both branches (and+ // the switch's own resolving state) carry it explicitly instead.+ element: (+ <AgentRouteSwitch+ fallback={<RouteSegmentSkeleton />}+ ownElement={dynamicLayout(+ () => import('@/routes/(main)/agent/_layout'),+ 'Desktop > Chat > Layout',+ { fallback: <RouteSegmentSkeleton />, preloadId: 'agent' },+ )}+ shareElement={dynamicElement(+ () => import('@/features/AgentShareVisitor/Page'),+ 'Desktop > Share > Agent',+ { fallback: <ConversationLayoutSkeleton /> },+ )}+ />),errorElement: <ErrorBoundary />,path: ':aid',@@ -1506,6 +1533,14 @@ export const createSharedDesktopRoutes = ({errorElement: <ErrorBoundary />,path: '/',},+ {+ // Legacy agent-share visitor links: the surface now lives at+ // `/agent/:slugOrId`, next to the creator's own agent page.+ element: <AgentShareLegacyRedirect />,+ errorElement: <ErrorBoundary />,+ handle: { meta: agentShareVisitorRouteMeta },+ path: '/share/agent/:slugOrId',+ },...BusinessDesktopRoutesWithoutMainLayout,...platformRoutes,onboardingRoute,diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsxindex 9bee048a817..48f315d5221 100644--- a/src/spa/router/desktopRouter.sync.test.tsx+++ b/src/spa/router/desktopRouter.sync.test.tsx@@ -108,6 +108,7 @@ describe('desktop router shared definition', () => {'/agent/agent-1/channel','/agent/agent-1/channel/slack','/agent/agent-1/statistics',+ '/agent/agent-1/share','/group/group-1/profile',]) {const matches = matchRoutes(createMainAreaRoutes(createMainAreaChildren), pathname);@@ -280,6 +281,11 @@ describe('desktop router shared definition', () => {// `/share/*` moved to the standalone Share app (apps/share).expect(webPaths).not.toContain('/share/t');expect(webPaths).not.toContain('/share/page');+ // …and the agent-share visitor surface moved to `/agent/:aid`, so the old+ // pattern stays registered on every platform only to redirect legacy links+ // (Web, Electron, and the mobile router — see mobileRouter.test.tsx).+ expect(webPaths).toContain('/share/agent/:slugOrId');+ expect(electronPaths).toContain('/share/agent/:slugOrId');expect(webPaths).not.toContain('/verify');expect(webPaths).toContain('/acceptance');expect(webPaths).toContain('/onboarding');@@ -491,6 +497,29 @@ describe('desktop router shared definition', () => {},);+ it.each(mainAreaVariants)(+ '%s keeps serving the creator agent surface on /agent/:aid',+ (_, factory) => {+ const matches = matchRoutes(createMainAreaRoutes(factory), '/agent/agt_1');++ // The agent-share visitor page now shares this route; the branch is+ // decided by `AgentRouteSwitch`, not by a second route pattern.+ expect(matches?.some((match) => match.route.path === ':aid')).toBe(true);+ expect(matches?.at(-1)?.params).toMatchObject({ aid: 'agt_1' });+ },+ );++ it.each([+ ['Web', webDesktopRoutes],+ ['Electron', electronDesktopRoutes],+ ])('%s redirects legacy /share/agent links to /agent', (_, routes) => {+ const matches = matchRoutes(routes, '/share/agent/my-bot');+ const element = matches?.at(-1)?.route.element as ReactElement;++ expect(matches?.at(-1)?.params).toMatchObject({ slugOrId: 'my-bot' });+ expect((element.type as { displayName?: string }).displayName).toBe('AgentShareLegacyRedirect');+ });+it('keeps business resource and task routes in the shared definition', async () => {const [sharedSource] = await readRouterSources();diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsxindex 9718898ca07..65473e56863 100644--- a/src/spa/router/mobileRouter.config.tsx+++ b/src/spa/router/mobileRouter.config.tsx@@ -7,7 +7,11 @@ import {BusinessMobileRoutesWithoutMainLayout,} from '@/business/client/BusinessMobileRoutes';import AppsSkeleton from '@/components/Skeleton/Apps';+import ConversationLayoutSkeleton from '@/components/Skeleton/Conversation/Layout';import { acceptanceRouteMeta } from '@/features/Acceptance/routeMeta';+import AgentRouteSwitch from '@/features/AgentRoute/AgentRouteSwitch';+import AgentShareLegacyRedirect from '@/features/AgentShareVisitor/LegacyRedirect';+import { agentShareVisitorRouteMeta } from '@/features/AgentShareVisitor/routeMeta';import { mobileAgentSettingsRouteMeta } from '@/features/RouteMeta/mobileRouteMeta';import WorkspaceProviderRedirect from '@/features/WorkspaceSetting/ProviderRedirect';import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';@@ -54,10 +58,24 @@ export const sharedMainAreaChildren: RouteObject[] = [path: 'settings',},],- element: dynamicLayout(- () => import('@/routes/(mobile)/chat/_layout'),- 'Mobile > Chat > Layout',- { preloadId: 'mobile-agent' },+ // `/agent/:aid` serves both the creator's own agent and the agent-share+ // visitor surface; the param decides which — see `AgentRouteSwitch`.+ element: (+ <AgentRouteSwitch+ fallback={<ConversationLayoutSkeleton />}+ // Mobile has no share settings page; the agent itself is the closest stop.+ ownShareRedirect={(agentId) => `/agent/${agentId}`}+ ownElement={dynamicLayout(+ () => import('@/routes/(mobile)/chat/_layout'),+ 'Mobile > Chat > Layout',+ { preloadId: 'mobile-agent' },+ )}+ shareElement={dynamicElement(+ () => import('@/features/AgentShareVisitor/Page'),+ 'Mobile > Share > Agent',+ { fallback: <ConversationLayoutSkeleton /> },+ )}+ />),errorElement: <ErrorBoundary />,path: ':aid',@@ -606,7 +624,17 @@ export const mobileRoutes: RouteObject[] = [},...BusinessMobileRoutesWithoutMainLayout,- // `/share/*` is served by the standalone Share app (apps/share), not this router.+ // `/share/*` is served by the standalone Share app (apps/share), not this+ // router. The agent-share visitor surface moved to `/agent/:aid` (it needs+ // the full chat runtime, so it stays in the main SPA on every platform), but+ // old links must keep working: without this entry a phone opening one falls+ // through to `*` and gets bounced home instead of redirected.+ {+ element: <AgentShareLegacyRedirect />,+ errorElement: <ErrorBoundary />,+ handle: { meta: agentShareVisitorRouteMeta },+ path: '/share/agent/:slugOrId',+ },// Messenger verify route (outside main layout){diff --git a/src/spa/router/mobileRouter.test.tsx b/src/spa/router/mobileRouter.test.tsxindex ee80a3eff53..cd8ed2ef542 100644--- a/src/spa/router/mobileRouter.test.tsx+++ b/src/spa/router/mobileRouter.test.tsx@@ -1,8 +1,31 @@import { readFile } from 'node:fs/promises';import path from 'node:path';+import type { ReactElement } from 'react';+import { matchRoutes } from 'react-router';import { describe, expect, it } from 'vitest';+import { mobileRoutes } from './mobileRouter.config';++describe('mobileRouter agent share route', () => {+ it('serves the agent-share visitor surface on mobile through the shared /agent/:aid route', () => {+ const matches = matchRoutes(mobileRoutes, '/agent/my-agent');++ // Visitor and creator surfaces share this route; `AgentRouteSwitch` picks.+ expect(matches?.some((match) => match.route.path === ':aid')).toBe(true);+ expect(matches?.at(-1)?.params).toMatchObject({ aid: 'my-agent' });+ });++ it('redirects legacy /share/agent links instead of bouncing to the catch-all', () => {+ const matches = matchRoutes(mobileRoutes, '/share/agent/my-agent');+ const element = matches?.at(-1)?.route.element as ReactElement;++ expect(matches?.at(-1)?.route.path).toBe('/share/agent/:slugOrId');+ expect(matches?.at(-1)?.params).toMatchObject({ slugOrId: 'my-agent' });+ expect((element.type as { displayName?: string }).displayName).toBe('AgentShareLegacyRedirect');+ });+});+describe('mobileRouter task routes', () => {it('registers task list and detail routes under the shared workspace layout', async () => {const source = await readFile(diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 1e54c890178..6fd0f60a21b 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type * as ConstVersion from '@/const/version';import { aiAgentService } from '@/services/aiAgent';import { messageService } from '@/services/message';+import { shareChatService } from '@/services/shareChat';import { topicService } from '@/services/topic';import { messageMapKey } from '@/store/chat/utils/messageMapKey';@@ -19,6 +20,14 @@ vi.mock('@/services/aiAgent', () => ({},}));+vi.mock('@/services/shareChat', () => ({+ shareChatService: {+ execAgentTask: vi.fn(),+ interruptTask: vi.fn(),+ refreshGatewayToken: vi.fn(),+ },+}));+vi.mock('@/services/message', () => ({messageService: {getMessages: vi.fn().mockResolvedValue([]),@@ -2158,6 +2167,120 @@ describe('GatewayActionImpl', () => {);});+ // Agent-share visitor surface: a visitor has no owner-scoped access to the+ // creator's topic/operation rows, so the reconnect must route through the+ // share-authorized `shareChat` mirror instead — mirrors the split+ // `executeGatewayAgent` already makes for share runs.+ describe('agent share visitor (agentShareId)', () => {+ function createShareReconnectTestAction(assistantMessage: any) {+ const startOperation = vi.fn(() => ({ operationId: 'gw-op-reconnect' }));+ const connectToGateway = vi.fn();+ let cancelHandler: (() => Promise<void>) | undefined;+ const onOperationCancel = vi.fn((_opId: string, handler: () => Promise<void>) => {+ cancelHandler = handler;+ });+ const state: Record<string, any> = {+ activeAgentId: 'agent-1',+ gatewayConnections: {},+ messagesMap: { 'agent-1_topic-1': assistantMessage ? [assistantMessage] : [] },+ topicDataMap: {},+ };+ const set = vi.fn((updater: any) => {+ if (typeof updater === 'function') Object.assign(state, updater(state));+ else Object.assign(state, updater);+ });+ const get = vi.fn(() => ({+ ...state,+ associateMessageWithOperation: vi.fn(),+ connectToGateway,+ onOperationCancel,+ startOperation,+ })) as any;++ (globalThis as any).window = {+ global_serverConfigStore: {+ getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),+ },+ };++ vi.mocked(shareChatService.refreshGatewayToken).mockResolvedValue({+ token: 'share-fresh-token',+ } as any);++ const action = new GatewayActionImpl(set as any, get, undefined);+ action.createClient = vi.fn(() => createMockClient());++ return { action, connectToGateway, getCancelHandler: () => cancelHandler, startOperation };+ }++ afterEach(() => {+ delete (globalThis as any).window;+ });++ it('refreshes the token through shareChatService, not the owner-scoped aiAgentService', async () => {+ const { action } = createShareReconnectTestAction({ createdAt: 1, id: 'ast-1' });+ vi.mocked(aiAgentService.refreshGatewayToken).mockClear();++ await action.reconnectToGatewayOperation({+ agentShareId: 'share-1',+ assistantMessageId: 'ast-1',+ operationId: 'server-op-1',+ topicId: 'topic-1',+ });++ expect(shareChatService.refreshGatewayToken).toHaveBeenCalledWith('share-1', 'topic-1');+ expect(aiAgentService.refreshGatewayToken).not.toHaveBeenCalled();+ });++ it('passes agentShareId into connectToGateway and the local operation context', async () => {+ const { action, connectToGateway, startOperation } = createShareReconnectTestAction({+ createdAt: 1,+ id: 'ast-1',+ });++ await action.reconnectToGatewayOperation({+ agentShareId: 'share-1',+ assistantMessageId: 'ast-1',+ operationId: 'server-op-1',+ topicId: 'topic-1',+ });++ expect(connectToGateway).toHaveBeenCalledWith(+ expect.objectContaining({ agentShareId: 'share-1', operationId: 'server-op-1' }),+ );+ expect(startOperation).toHaveBeenCalledWith(+ expect.objectContaining({+ context: expect.objectContaining({ agentShareId: 'share-1', topicId: 'topic-1' }),+ }),+ );+ });++ it('forwards cancellation through shareChatService.interruptTask, not the owner-scoped interrupt', async () => {+ const { action, getCancelHandler } = createShareReconnectTestAction({+ createdAt: 1,+ id: 'ast-1',+ });+ vi.mocked(aiAgentService.interruptTask).mockClear();+ vi.mocked(shareChatService.interruptTask).mockResolvedValue({} as any);++ await action.reconnectToGatewayOperation({+ agentShareId: 'share-1',+ assistantMessageId: 'ast-1',+ operationId: 'server-op-1',+ topicId: 'topic-1',+ });++ await getCancelHandler()?.();++ expect(shareChatService.interruptTask).toHaveBeenCalledWith(+ 'share-1',+ 'topic-1',+ 'server-op-1',+ );+ expect(aiAgentService.interruptTask).not.toHaveBeenCalled();+ });+ });+// Captures the onSessionComplete handed to connectToGateway so we can drive// both close paths directly. Provides the methods that callback reaches.function createOnSessionCompleteHarness({ activeTopicId = 'topic-1' } = {}) {diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 61fa4a201c4..17d4c396222 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -29,6 +29,7 @@ import {} from '@/services/aiAgent';import { gatewayConnectionService } from '@/services/electron/gatewayConnection';import { messageService } from '@/services/message';+import { shareChatService } from '@/services/shareChat';import { topicService } from '@/services/topic';import { getAgentStoreState } from '@/store/agent';import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';@@ -185,6 +186,12 @@ export interface GatewayConnection {}export interface ConnectGatewayParams {+ /**+ * Present on the agent-share visitor surface. Routes the `auth_expired`+ * token refresh through `shareChat.refreshGatewayToken` — the owner-scoped+ * refresh cannot see the creator-owned share topic.+ */+ agentShareId?: string;/*** Gateway WebSocket URL (e.g. https://agent-gateway.lobehub.com)*/@@ -276,8 +283,16 @@ export class GatewayActionImpl {* Creates an AgentStreamClient, manages its lifecycle, and wires up event callbacks.*/connectToGateway = (params: ConnectGatewayParams): void => {- const { operationId, gatewayUrl, token, topicId, onEvent, onSessionComplete, resumeOnConnect } =- params;+ const {+ agentShareId,+ operationId,+ gatewayUrl,+ token,+ topicId,+ onEvent,+ onSessionComplete,+ resumeOnConnect,+ } = params;// Disconnect existing connection for this operation if anythis.disconnectFromGateway(operationId);@@ -398,7 +413,9 @@ export class GatewayActionImpl {// autoReconnect would keep running past the local op's lifetime.client.on('auth_expired', async () => {try {- const { token: fresh } = await aiAgentService.refreshGatewayToken(topicId);+ const { token: fresh } = agentShareId+ ? await shareChatService.refreshGatewayToken(agentShareId, topicId)+ : await aiAgentService.refreshGatewayToken(topicId);client.updateToken(fresh);await client.reconnect();} catch (error) {@@ -658,74 +675,90 @@ export class GatewayActionImpl {throw abortSignal.reason ?? new DOMException('Aborted', 'AbortError');}+ // Agent-share visitor surface: dispatch through the share-authorized mirror.+ // It accepts only the share-safe subset (prompt / topic / clientIds) —+ // everything else (tools, devices, mentions) is decided server-side by the+ // share config, never by this client.+ const agentShareId = executionContext.agentShareId;+const result =precreatedResult ??- (await aiAgentService.execAgentTask(- {- agentId: executionContext.agentId,- // Fresh sends only — resume flows never pass this, and the server drops- // it defensively on resume-like params anyway.- clientIds,- appContext: {- agentDocumentId: executionContext.agentDocumentId,- ...(messageContext.agentId !== executionContext.agentId && {- conversationAgentId: messageContext.agentId,- }),- defaultTaskAssigneeAgentId: executionContext.defaultTaskAssigneeAgentId,- documentId: executionContext.documentId,- // When AgentBuilder runs, context.agentId is the builtin builder agent.- // The actual editing target is chatStore.activeAgentId (kept in sync by- // AgentBuilderProvider). Pass it so the server can route tool calls to- // the correct agent rather than the builder itself.- ...(executionContext.scope === 'agent_builder' && {- editingAgentId: this.#get().activeAgentId ?? undefined,- }),- // Same shape as `editingAgentId`, for the Group Agent Builder panel on- // the group Profile page. The builder conversation is keyed by the- // builtin builder agent (no groupId in its ConversationContext, so the- // message map key and the group's own chat stay separate), which left- // the server runtime with no idea which group it was editing.- // The context value wins, and every surface that opens this scope sets- // it from its own route/group: it is fixed for the run, so a mid-run- // navigation cannot make the server stamp a different group than the- // panel is reading from. The `activeGroupId` fallback is a last resort- // for a caller that forgot — it is sampled here, AFTER the async- // preflight above, so it can already be stale by this point.- ...(executionContext.scope === 'group_agent_builder' && {- editingGroupId: executionContext.editingGroupId ?? this.#get().activeGroupId,- }),- groupId: executionContext.groupId,- ...(initialTopicMetadata && { initialTopicMetadata }),- ...(newThread && { newThread }),- // Forward the group orchestration role so the server can stamp it onto- // the assistant message metadata. Without this the gateway-created- // supervisor turn loses its role on the step_start snapshot / refetch- // and renders as a generic assistant.- orchestrationRole: executionContext.orchestrationRole,- scope: executionContext.scope,- taskId,- threadId: executionContext.threadId,- topicId: executionContext.topicId,- // Goal-page side conversation: lets the server build the goal- // overview injection for gateway-run agents (mirrors the client- // streaming executor).- viewedGoal: executionContext.viewedGoal,- },- ...desktopDeviceHints,- fileIds,- replacesOperationId,- mentionedAgents,- parentMessageId,- prompt: message,- resumeApproval,- resumeApprovals,- resumeToolResult,- selectedToolIds,- trigger: metadata?.trigger,- userInterventionConfig,- },- { signal: abortSignal },- ));+ (agentShareId+ ? await shareChatService.execAgentTask(+ {+ clientIds,+ prompt: message,+ shareId: agentShareId,+ topicId: executionContext.topicId,+ },+ { signal: abortSignal },+ )+ : await aiAgentService.execAgentTask(+ {+ agentId: executionContext.agentId,+ // Fresh sends only — resume flows never pass this, and the server drops+ // it defensively on resume-like params anyway.+ clientIds,+ appContext: {+ agentDocumentId: executionContext.agentDocumentId,+ ...(messageContext.agentId !== executionContext.agentId && {+ conversationAgentId: messageContext.agentId,+ }),+ defaultTaskAssigneeAgentId: executionContext.defaultTaskAssigneeAgentId,+ documentId: executionContext.documentId,+ // When AgentBuilder runs, context.agentId is the builtin builder agent.+ // The actual editing target is chatStore.activeAgentId (kept in sync by+ // AgentBuilderProvider). Pass it so the server can route tool calls to+ // the correct agent rather than the builder itself.+ ...(executionContext.scope === 'agent_builder' && {+ editingAgentId: this.#get().activeAgentId ?? undefined,+ }),+ // Same shape as `editingAgentId`, for the Group Agent Builder panel on+ // the group Profile page. The builder conversation is keyed by the+ // builtin builder agent (no groupId in its ConversationContext, so the+ // message map key and the group's own chat stay separate), which left+ // the server runtime with no idea which group it was editing.+ // The context value wins, and every surface that opens this scope sets+ // it from its own route/group: it is fixed for the run, so a mid-run+ // navigation cannot make the server stamp a different group than the+ // panel is reading from. The `activeGroupId` fallback is a last resort+ // for a caller that forgot — it is sampled here, AFTER the async+ // preflight above, so it can already be stale by this point.+ ...(executionContext.scope === 'group_agent_builder' && {+ editingGroupId: executionContext.editingGroupId ?? this.#get().activeGroupId,+ }),+ groupId: executionContext.groupId,+ ...(initialTopicMetadata && { initialTopicMetadata }),+ ...(newThread && { newThread }),+ // Forward the group orchestration role so the server can stamp it onto+ // the assistant message metadata. Without this the gateway-created+ // supervisor turn loses its role on the step_start snapshot / refetch+ // and renders as a generic assistant.+ orchestrationRole: executionContext.orchestrationRole,+ scope: executionContext.scope,+ taskId,+ threadId: executionContext.threadId,+ topicId: executionContext.topicId,+ // Goal-page side conversation: lets the server build the goal+ // overview injection for gateway-run agents (mirrors the client+ // streaming executor).+ viewedGoal: executionContext.viewedGoal,+ },+ ...desktopDeviceHints,+ fileIds,+ replacesOperationId,+ mentionedAgents,+ parentMessageId,+ prompt: message,+ resumeApproval,+ resumeApprovals,+ resumeToolResult,+ selectedToolIds,+ trigger: metadata?.trigger,+ userInterventionConfig,+ },+ { signal: abortSignal },+ ));// Persistence is the ownership boundary. Notify before later UI synchronization awaits and// before handling a late abort so callers never delete a file already attached server-side.@@ -743,10 +776,19 @@ export class GatewayActionImpl {hasInterruptedAfterPersistence = true;// Cancel arrived after execAgentTask resolved — server task exists. Interrupt generation,// but keep reconciling the persisted message before returning to the caller.- interruptGatewayTaskOrThrow({- operationId: result.operationId,- topicId: result.topicId,- }).catch((err) => console.error('[Gateway] interruptTask after cancel failed:', err));+ // Share visitors have no access to the owner-scoped interrupt (and no+ // device runtimes to confirm), so they go through the share mirror.+ if (agentShareId)+ shareChatService+ .interruptTask(agentShareId, result.topicId, result.operationId)+ .catch((err) =>+ console.error('[Gateway] share interruptTask after cancel failed:', err),+ );+ else+ interruptGatewayTaskOrThrow({+ operationId: result.operationId,+ topicId: result.topicId,+ }).catch((err) => console.error('[Gateway] interruptTask after cancel failed:', err));}return true;@@ -839,9 +881,14 @@ export class GatewayActionImpl {// Unlike the direct-API sendMessage path (which receives topics[] in the// response and calls internal_updateTopics), the gateway path only gets a// topicId — we must explicitly refetch so the sidebar shows the new topic.- this.#get()- .refreshTopic()- .catch((err) => console.error('[Gateway] refreshTopic after topic creation failed:', err));+ // Share visitors have no owner topic sidebar — their list refreshes via+ // the share feature's own SWR hook, and refreshTopic is owner-scoped.+ if (!agentShareId)+ this.#get()+ .refreshTopic()+ .catch((err) =>+ console.error('[Gateway] refreshTopic after topic creation failed:', err),+ );}this.#get().moveQueuedMessages(@@ -862,7 +909,11 @@ export class GatewayActionImpl {return result;}- if (result.topicId) {+ // `updateTopicStatus` persists through the owner-scoped `topic.updateTopic`+ // procedure, which a share visitor is never authorized to call — firing it+ // would only produce a rejected request (and a pinned optimistic write that+ // no owner topic list ever consumes).+ if (result.topicId && !agentShareId) {void this.#get().updateTopicStatus?.({agentId: messageContext.agentId,groupId: messageContext.groupId,@@ -930,6 +981,13 @@ export class GatewayActionImpl {// depend on any metadata lookup. The returned promise preserves an// unconfirmed device shutdown so Send now can keep its queued message.this.#get().onOperationCancel(gatewayOpId, async () => {+ if (agentShareId) {+ await shareChatService+ .interruptTask(agentShareId, result.topicId, result.operationId)+ .catch((err) => console.error('[Gateway] share interruptTask failed:', err));+ return;+ }+await interruptGatewayTaskOrThrow({operationId: result.operationId,topicId: result.topicId,@@ -1010,13 +1068,16 @@ export class GatewayActionImpl {// when `lastSettledOperationId` still matches. It also remains the// backstop when `clearRunningMark` failed and left the marker in place.const viewing = this.#get().activeTopicId === result.topicId;- topicService- .settleRunningOperation(- result.topicId,- result.operationId,- viewing || !effectiveSucceeded ? 'active' : 'unread',- )- .catch(console.error);+ // Share visitors cannot settle the creator-owned topic row (the topic+ // router is owner-scoped) — the local clear below still runs.+ if (!agentShareId)+ topicService+ .settleRunningOperation(+ result.topicId,+ result.operationId,+ viewing || !effectiveSucceeded ? 'active' : 'unread',+ )+ .catch(console.error);// Also clear the local store copy — the server settle above does NOT// touch the Zustand topic map that useGatewayReconnect (and the sidebar// spinner) read. Mirror the same 'active' decision passed to the server@@ -1033,6 +1094,7 @@ export class GatewayActionImpl {}onComplete?.();},+ agentShareId,operationId: result.operationId,token: result.token || '',topicId: result.topicId,@@ -1055,6 +1117,15 @@ export class GatewayActionImpl {* renders, leaving a connected-but-frozen panel.*/agentId?: string;+ /**+ * Present on the agent-share visitor surface. Routes the token refresh and+ * cancellation through the share-authorized `shareChat` procedures instead+ * of the owner-scoped ones: a visitor has no owner-scoped access to the+ * creator's topic/operation rows, and the Gateway channel is registered+ * under the VISITOR's id, so only a visitor-signed token can reconnect it+ * — see `shareChat.refreshGatewayToken`'s JSDoc.+ */+ agentShareId?: string;assistantMessageId: string;heteroType?: string | null;operationId: string;@@ -1062,7 +1133,8 @@ export class GatewayActionImpl {threadId?: string | null;topicId: string;}): Promise<void> => {- const { assistantMessageId, heteroType, operationId, topicId, scope, threadId } = params;+ const { agentShareId, assistantMessageId, heteroType, operationId, topicId, scope, threadId } =+ params;const agentGatewayUrl =window.global_serverConfigStore?.getState()?.serverConfig?.agentGatewayUrl;@@ -1094,7 +1166,12 @@ export class GatewayActionImpl {// and does not retry the 404 forever.let token: string;try {- ({ token } = await aiAgentService.refreshGatewayToken(topicId));+ // Share visitors have no owner-scoped access to `aiAgentService.refreshGatewayToken`+ // (its TopicModel is scoped to the caller, and share topics belong to the+ // creator) — see the param JSDoc above for why the visitor mirror is used instead.+ ({ token } = agentShareId+ ? await shareChatService.refreshGatewayToken(agentShareId, topicId)+ : await aiAgentService.refreshGatewayToken(topicId));} catch (error) {if (isTrpcErrorCode(error, 'NOT_FOUND')) {this.clearLocalRunningOperation({ operationId, topicId });@@ -1111,8 +1188,15 @@ export class GatewayActionImpl {if (topicOpIdAfterRefresh && topicOpIdAfterRefresh !== operationId) return;const agentId = params.agentId ?? this.#get().activeAgentId;+ // Carry agentShareId the same way executeGatewayAgent's execution context+ // does — `createGatewayEventHandler` branches on `context.agentShareId` to+ // skip owner-only side effects (agent-signal emission, message.update on+ // error), and this context otherwise matches the one+ // ReadOnlyConversationArea.tsx builds ({ agentId, agentShareId, scope:+ // 'main', topicId }) for the visitor-rendered bucket.const context = {agentId,+ ...(agentShareId && { agentShareId }),scope: (scope ?? 'main') as ConversationContext['scope'],threadId: threadId ?? null,topicId,@@ -1150,6 +1234,16 @@ export class GatewayActionImpl {// Forward local-op cancellation to the server-side agent loop via tRPC.// See note in executeGatewayAgent for details.this.#get().onOperationCancel(gatewayOpId, async () => {+ // Share visitors have no access to the owner-scoped interrupt (and no+ // device runtimes to confirm), so they go through the share mirror —+ // same split as executeGatewayAgent's cancel path.+ if (agentShareId) {+ await shareChatService+ .interruptTask(agentShareId, topicId, operationId)+ .catch((err) => console.error('[Gateway] share interruptTask failed:', err));+ return;+ }+await interruptGatewayTaskOrThrow({ operationId });});@@ -1240,7 +1334,10 @@ export class GatewayActionImpl {// was always "still spinning after a reload" — refreshing is what moved// the run off the primary path and onto this one.const viewing = this.#get().activeTopicId === topicId;- if (!superseded) {+ // Share visitors cannot settle the creator-owned topic row (the topic+ // router is owner-scoped) — the local clear below still runs. Same+ // split as executeGatewayAgent's onSessionComplete.+ if (!superseded && !agentShareId) {topicService.settleRunningOperation(topicId,@@ -1260,6 +1357,7 @@ export class GatewayActionImpl {topicId,});},+ agentShareId,operationId,resumeOnConnect: true,token,diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.tsindex a5f6d9c474e..b49e73bc069 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -418,6 +418,16 @@ export const createGatewayEventHandler = (const gatewayOperationId = params.gatewayOperationId ?? operationId;const runtimeType = params.runtimeType ?? 'gateway';+ /**+ * Agent self-iteration signals are an owner-side feature: the agentSignal+ * lambda resolves the agent in the caller's own scope, so a share visitor's+ * emission 404s with "Agent not found". Drop them for share-visitor runs.+ */+ const emitAgentSignal: typeof emitClientAgentSignalSourceEvent = async (input) => {+ if (context.agentShareId) return undefined;+ return emitClientAgentSignalSourceEvent(input);+ };+const runScope: RunScope = context.scope === 'sub_agent' ? 'sub_agent' : 'top_level';const lifecycleEventBase = {context,@@ -736,7 +746,7 @@ export const createGatewayEventHandler = (}}- void emitClientAgentSignalSourceEvent({+ void emitAgentSignal({payload: {agentId: context.agentId,...(currentAssistantMessageId@@ -1154,7 +1164,7 @@ export const createGatewayEventHandler = (// Refresh on execution_complete to ensure final step state is consistentif (data?.phase === 'execution_complete') {enqueue(async () => {- void emitClientAgentSignalSourceEvent({+ void emitAgentSignal({payload: {agentId: context.agentId,operationId,@@ -1176,7 +1186,7 @@ export const createGatewayEventHandler = (enqueue(async () => {const data = event.data as { reason?: string; uiMessages?: UIChatMessage[] } | undefined;- void emitClientAgentSignalSourceEvent({+ void emitAgentSignal({payload: {agentId: context.agentId,...(currentAssistantMessageId@@ -1325,7 +1335,7 @@ export const createGatewayEventHandler = (const messageError = toChatMessageError(event.data);const errorMessage = messageError.message;- void emitClientAgentSignalSourceEvent({+ void emitAgentSignal({payload: {agentId: context.agentId,errorMessage,@@ -1352,14 +1362,23 @@ export const createGatewayEventHandler = (get().completeOperation(operationId);}- const updateResult = await messageService- .updateMessageError(currentAssistantMessageId, messageError, {- agentId: context.agentId,- groupId: context.groupId,- threadId: context.threadId,- topicId: context.topicId,- })- .catch(console.error);+ // Share visitors must not persist through the owner-scoped+ // `message.update`: it resolves rows in the CALLER's scope, so the+ // visitor call "succeeds" with 0 rows updated and its response+ // messages (queried as the visitor) come back empty — replacing the+ // bucket with [] and leaving the inline error overlay nothing to+ // attach to. Fall through to the share-aware refetch + overlay;+ // server-side error persistence for share runs is a known v1 gap.+ const updateResult = context.agentShareId+ ? undefined+ : await messageService+ .updateMessageError(currentAssistantMessageId, messageError, {+ agentId: context.agentId,+ groupId: context.groupId,+ threadId: context.threadId,+ topicId: context.topicId,+ })+ .catch(console.error);if (updateResult?.success && updateResult.messages) {get().replaceMessages(updateResult.messages, { context });diff --git a/src/types/transferError.ts b/src/types/transferError.tsindex e032ed00d6b..444078c4a1d 100644--- a/src/types/transferError.ts+++ b/src/types/transferError.ts@@ -17,6 +17,13 @@ export const TransferErrorCode = {OwnerOnly: 'OWNER_ONLY',ResourceNotFound: 'RESOURCE_NOT_FOUND',SameWorkspace: 'SAME_WORKSPACE',+ /**+ * The agent still carries an `agent_shares` row, and changing its owner+ * would republish the previous owner's grants / spend cap and orphan the+ * visitor threads. Disabling sharing keeps the row, so the block lifts only+ * once the share row itself is removed.+ */+ SharedTransferBlocked: 'AGENT_SHARED_TRANSFER_BLOCKED',/** Member transfer: the picked recipient already owns the resource (or is the initiator). */TargetIsCurrentOwner: 'TARGET_IS_CURRENT_OWNER',TargetNoWriteAccess: 'TARGET_NO_WRITE_ACCESS',