🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(agent-signal): gate self-iteration on the Labs switch and fix its broken learning paths (#20786)
Arvin Xuaeee141ec6ba
diff --git a/.agents/acceptance/PROJECT.md b/.agents/acceptance/PROJECT.mdindex 25e9e273a47..cbfb15e2415 100644--- a/.agents/acceptance/PROJECT.md+++ b/.agents/acceptance/PROJECT.md@@ -124,7 +124,7 @@ stale standalone install: a recently added workspace package fails to resolveDefault script env (no-`.env` bootstrap): `APP_URL=http://localhost:3010`,`DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres`,`DATABASE_DRIVER=node`, `AGENT_RUNTIME_MODE=queue`,- `REDIS_URL=redis://localhost:6380`, `FEATURE_FLAGS=-agent_self_iteration`,+ `REDIS_URL=redis://localhost:6380`, an empty `FEATURE_FLAGS`,`KEY_VAULTS_SECRET`, `AUTH_SECRET`, auth verification off, a generated`JWKS_KEY` (persisted at `.records/env/agent-testing-jwks.json`, required by everyasync-task dispatch such as image generation), `SSRF_ALLOW_PRIVATE_IP_ADDRESS=1`@@ -398,9 +398,9 @@ support is not implemented. Native Windows is unsupported. See the skill's.agents/acceptance/scripts/init-dev-env.sh preflight # non-zero exit if QStash (or Redis) is down```- `FEATURE_FLAGS=-agent_self_iteration` only drops the self-iteration workflow- (so a simple chat does not fan out); it does NOT remove QStash from the- agent-runtime dispatch path. Treat QStash as required, not an "only-for-workflow"+ Background self-iteration only runs for users who turned on Labs →+ Self-evolving (off for new users), so a simple chat does not fan out; that+ does NOT remove QStash from the agent-runtime dispatch path. Treat QStash as required, not an "only-for-workflow"nicety.- **Verify which runtime actually ran — do not assume.** Some features have twodiff --git a/.agents/acceptance/scripts/init-dev-env.sh b/.agents/acceptance/scripts/init-dev-env.shindex ebfcc6c0933..51967b97847 100755--- a/.agents/acceptance/scripts/init-dev-env.sh+++ b/.agents/acceptance/scripts/init-dev-env.sh@@ -198,7 +198,9 @@ apply_env() {export DATABASE_DRIVER="${DATABASE_DRIVER:-node}"export DATABASE_URLexport DEVICE_GATEWAY_SERVICE_TOKEN="${DEVICE_GATEWAY_SERVICE_TOKEN:-agent-testing-local-device-gateway-token}"- export FEATURE_FLAGS="${FEATURE_FLAGS:--agent_self_iteration}"+ # Background self-iteration follows each user's Labs → Self-evolving switch (off for new+ # users), so no flag is needed to keep a simple chat from fanning out.+ export FEATURE_FLAGS="${FEATURE_FLAGS:-}"export KEY_VAULTS_SECRET="${KEY_VAULTS_SECRET:-r2gbBPKyJ8ZRKCLKt+I3DImfcL+wGxaQyRC56xtm9Uk=}"export NEXT_PUBLIC_AUTH_EMAIL_VERIFICATION="${NEXT_PUBLIC_AUTH_EMAIL_VERIFICATION:-0}"export NODE_OPTIONS="${NODE_OPTIONS:---max-old-space-size=6144}"diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.tsindex 3b5e83841e3..1d0e62bf252 100644--- a/apps/server/src/modules/Redis/keys.ts+++ b/apps/server/src/modules/Redis/keys.ts@@ -15,6 +15,11 @@* When using `createRedisWithPrefix`, pass one of these as the prefix parameter.*/export const RedisKeyNamespace = {+ /**+ * Agent Signal keys — the same `agent-signal` keyspace the Agent Signal runtime+ * stores (receipts, dedupe, policy state) already use.+ */+ AGENT_SIGNAL: 'agent-signal',/*** AI generation related keys (agent welcome, placeholders, etc.)*/@@ -46,6 +51,34 @@ export const RedisKeyNamespace = {* ```*/export const RedisKeys = {+ /**+ * Agent Signal spend bounds — see {@link RedisKeyNamespace.AGENT_SIGNAL}. Per-user+ * counters and quotas that keep background self-iteration work within its limits.+ */+ agentSignal: {+ /**+ * Feedback-classifier calls one user made on one UTC day.+ * Full key: agent-signal:classifier_calls:v1:{userId}:{utcDay}+ */+ classifierCalls: (userId: string, utcDay: string): string =>+ `classifier_calls:v1:${userId}:${utcDay}`,+ /**+ * Self-feedback declarations accepted in one topic scope.+ * Full key: agent-signal:declaration_slots:v1:{scopeKey}+ */+ declarationSlots: (scopeKey: string): string => `declaration_slots:v1:${scopeKey}`,+ /**+ * Manual Agent Signal triggers one user sent in the current hourly window.+ * Full key: agent-signal:manual_triggers:v1:{userId}+ */+ manualTriggers: (userId: string): string => `manual_triggers:v1:${userId}`,+ /**+ * Distinct topics one user's nightly review covered on one local night.+ * Full key: agent-signal:nightly_topics:v1:{userId}:{localDate}+ */+ nightlyTopics: (userId: string, localDate: string): string =>+ `nightly_topics:v1:${userId}:${localDate}`,+ },/*** AI generation scope - for AI-generated content like welcome messages*/@@ -93,3 +126,21 @@ export const RedisKeys = {`workspace_rescan_claim:v1:${userId}:${pool}:${deviceId}:${cwd}`,},} as const;++/**+ * The namespace (key prefix) each {@link RedisKeys} scope lives under. A scope's keys are+ * only read and written through a client prefixed with its namespace, so a key can never+ * land under another scope's prefix. Every scope must be mapped.+ */+export const RedisKeyScopeNamespace = {+ agentSignal: RedisKeyNamespace.AGENT_SIGNAL,+ aiGeneration: RedisKeyNamespace.AI_GENERATION,+ lobechat: RedisKeyNamespace.LOBEHUB,+ sendPathCache: RedisKeyNamespace.SEND_PATH_CACHE,+} as const satisfies Record<+ keyof typeof RedisKeys,+ (typeof RedisKeyNamespace)[keyof typeof RedisKeyNamespace]+>;++/** A {@link RedisKeys} scope, e.g. `sendPathCache` or `agentSignal`. */+export type RedisKeyScope = keyof typeof RedisKeyScopeNamespace;diff --git a/apps/server/src/routers/lambda/__tests__/agentSignal.triggerSourceEvent.test.ts b/apps/server/src/routers/lambda/__tests__/agentSignal.triggerSourceEvent.test.tsnew file mode 100644index 00000000000..46c7ae48b76--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/agentSignal.triggerSourceEvent.test.ts@@ -0,0 +1,147 @@+// @vitest-environment node+import { TRPCError } from '@trpc/server';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ assertAgentSignalTriggerRateLimit: vi.fn(),+ enqueueAgentSignalSourceEvent: vi.fn(),+ invokedPermissions: [] as string[],+}));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++// Records which RBAC permission actually guarded the called procedure.+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({+ withScopedPermission: vi.fn(function (permission: string) {+ return (opts: any) => {+ mocks.invokedPermissions.push(permission);+ return opts.next({ ctx: opts.ctx });+ };+ }),+}));++vi.mock('@/server/services/agentSignal', () => ({+ enqueueAgentSignalSourceEvent: mocks.enqueueAgentSignalSourceEvent,+}));++vi.mock('@/server/services/agentSignal/triggerRateLimit', () => ({+ assertAgentSignalTriggerRateLimit: mocks.assertAgentSignalTriggerRateLimit,+}));++vi.mock('@/server/services/agentSignal/services/receiptRollbackService', () => ({+ rollbackAgentSignalReceipt: vi.fn(),+}));++vi.mock('@/server/services/agentSignal/services/receiptService', () => ({+ listAgentSignalReceipts: vi.fn(),+}));++const { agentSignalRouter } = await import('../agentSignal');++describe('agentSignalRouter.triggerSourceEvent', () => {+ const ctx: any = { userId: 'user-1', workspaceId: null };++ afterEach(() => {+ vi.useRealTimers();+ });++ beforeEach(() => {+ vi.clearAllMocks();+ mocks.invokedPermissions.length = 0;+ mocks.assertAgentSignalTriggerRateLimit.mockResolvedValue(undefined);+ mocks.enqueueAgentSignalSourceEvent.mockResolvedValue({+ accepted: true,+ scopeKey: 'scope',+ workflowRunId: 'run-1',+ });+ });++ /**+ * ROOT CAUSE:+ *+ * The procedure skipped both the RBAC gate `emitSourceEvent` and the REST route use and any+ * rate limit, so it could enqueue model-backed workflows without bound.+ */+ it('requires message:create and consumes the per-user trigger budget', async () => {+ const caller = agentSignalRouter.createCaller(ctx);++ await caller.triggerSourceEvent({+ agentId: 'agent-1',+ sourceType: 'agent.nightly_review.requested',+ });++ expect(mocks.invokedPermissions).toEqual(['message:create']);+ expect(mocks.assertAgentSignalTriggerRateLimit).toHaveBeenCalledWith('user-1');+ expect(mocks.enqueueAgentSignalSourceEvent).toHaveBeenCalledOnce();+ });++ it('does not enqueue once the rate limit rejects the call', async () => {+ mocks.assertAgentSignalTriggerRateLimit.mockRejectedValue(+ new TRPCError({ code: 'TOO_MANY_REQUESTS', message: 'limit' }),+ );+ const caller = agentSignalRouter.createCaller(ctx);++ await expect(+ caller.triggerSourceEvent({+ agentId: 'agent-1',+ sourceType: 'agent.nightly_review.requested',+ }),+ ).rejects.toMatchObject({ code: 'TOO_MANY_REQUESTS' });+ expect(mocks.enqueueAgentSignalSourceEvent).not.toHaveBeenCalled();+ });++ it('ignores caller-chosen nightly review guard inputs', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-05-31T12:00:00.000Z'));+ const caller = agentSignalRouter.createCaller(ctx);++ await caller.triggerSourceEvent({+ agentId: 'agent-1',+ payloadOverride: { localDate: '1999-01-01' },+ sourceId: 'nightly-review:user-1:agent-1:1999-01-01',+ sourceType: 'agent.nightly_review.requested',+ });++ vi.useRealTimers();+ const [sourceEvent] = mocks.enqueueAgentSignalSourceEvent.mock.calls[0]!;+ expect(sourceEvent.payload.localDate).toBe('2026-05-31');+ expect(sourceEvent.sourceId).toBe('nightly-review:user-1:agent-1:2026-05-31');+ });++ /**+ * ROOT CAUSE:+ *+ * The enqueue path authorizes only `context.agentId`, which was the request's `agentId`. For+ * source types that need no agent (`agent.user.message`, tool outcomes) a caller could leave it+ * empty and point `payloadOverride.agentId` at an agent they cannot use.+ */+ it('authorizes an agent id supplied only through payloadOverride', async () => {+ const caller = agentSignalRouter.createCaller(ctx);++ await caller.triggerSourceEvent({+ payloadOverride: { agentId: 'foreign-agent' },+ sourceType: 'agent.user.message',+ });++ expect(mocks.enqueueAgentSignalSourceEvent).toHaveBeenCalledWith(+ expect.objectContaining({ payload: expect.objectContaining({ agentId: 'foreign-agent' }) }),+ expect.objectContaining({ agentId: 'foreign-agent', userId: 'user-1' }),+ );+ });++ it.each([+ ['a different agent', { agentId: 'agent-1', payloadOverride: { agentId: 'foreign-agent' } }],+ ['a non-string agent id', { payloadOverride: { agentId: 42 } }],+ ])('rejects a payload override naming %s', async (_label, request) => {+ const caller = agentSignalRouter.createCaller(ctx);++ await expect(+ caller.triggerSourceEvent({ ...request, sourceType: 'tool.outcome.failed' } as any),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mocks.enqueueAgentSignalSourceEvent).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/agentSignal.ts b/apps/server/src/routers/lambda/agentSignal.tsindex d781c0dbec6..454b4fbca70 100644--- a/apps/server/src/routers/lambda/agentSignal.ts+++ b/apps/server/src/routers/lambda/agentSignal.ts@@ -12,9 +12,11 @@ import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';import { rollbackAgentSignalReceipt } from '@/server/services/agentSignal/services/receiptRollbackService';import { listAgentSignalReceipts } from '@/server/services/agentSignal/services/receiptService';+import { assertAgentSignalTriggerRateLimit } from '@/server/services/agentSignal/triggerRateLimit';import {AGENT_SIGNAL_TRIGGER_SOURCE_TYPES,buildTriggerSourceEvent,+ resolveTriggerSourceEventAgentId,} from '@/server/services/agentSignal/triggerSourceEvent';const log = debug('lobe-server:agent-signal:router');@@ -58,7 +60,9 @@ export const agentSignalRouter = router({workspaceId: ctx.workspaceId ?? undefined,});}),- triggerSourceEvent: agentSignalProcedure+ // Same RBAC gate as `emitSourceEvent` and the REST `/signals/trigger` route; API-key scopes+ // (`agent:write` + `model:invoke`) are enforced by the namespace guard in `@lobechat/const`.+ triggerSourceEvent: agentSignalWriteProcedure.input(z.object({agentId: z.string().optional(),@@ -82,6 +86,12 @@ export const agentSignalRouter = router({userId: ctx.userId,});+ // `payloadOverride.agentId` can name an agent the request's `agentId` never did; authorize+ // the agent the payload actually targets.+ const agentId = resolveTriggerSourceEventAgentId(sourceEvent, input.agentId);++ await assertAgentSignalTriggerRateLimit(ctx.userId);+log('Triggering source event sourceType=%s sourceId=%s',sourceEvent.sourceType,@@ -89,7 +99,7 @@ export const agentSignalRouter = router({);return enqueueAgentSignalSourceEvent(sourceEvent, {- agentId: input.agentId,+ agentId,userId: ctx.userId,workspaceId: ctx.workspaceId ?? undefined,});@@ -118,8 +128,9 @@ export const agentSignalRouter = router({.input(z.object({agentDocumentId: z.string().min(1).optional(),- documentId: z.string().min(1),- historyId: z.string().min(1),+ // Skill receipts only; memory receipts resolve their target from the stored receipt.+ documentId: z.string().min(1).optional(),+ historyId: z.string().min(1).optional(),receiptId: z.string().min(1),}),)diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex e9c09777f47..a192875524b 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -579,6 +579,38 @@ export class CompletionLifecycle {);}}+ // A memory-writer run's terminal state may not carry the tool calls that+ // name the written memory (messages live in the DB). When the receipt would+ // fall back to a generic "Memory saved" with no id, re-read the run's own+ // thread so it can name the memory and offer undo.+ const memoryTargetUnresolved = selfIteration?.mutations.some((mutation) => {+ const target = isRecord(mutation.data) ? mutation.data.target : undefined;+ return !isRecord(target) || !target.id;+ });+ if (selfIteration?.marker.kind === 'memory' && memoryTargetUnresolved && runOrigin.threadId) {+ try {+ const messages = await this.messageModel.query(+ {+ agentId: runOrigin.agentId,+ threadId: runOrigin.threadId,+ topicId: runOrigin.topicId,+ },+ { allowShareVisitor: true },+ );+ selfIteration =+ extractSelfIterationCompletionPayload({+ ...state,+ messages,+ origin: { ...runOrigin, signal: selfIteration.marker, userId: selfIteration.userId },+ }) ?? selfIteration;+ } catch (error) {+ log(+ '[completion-lifecycle] failed to load memory-writer messages op=%s: %O',+ operationId,+ error,+ );+ }+ }if (reason !== 'error') {log('[completion-lifecycle] emit agent.execution.completed op=%s userId=%s assistant=%s metaAssistant=%s selfIteration=%s',diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex f4e8413e3de..aab004c57fd 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -1719,6 +1719,69 @@ describe('CompletionLifecycle.emitSignalEvents — assistant anchor', () => {});});+ it('reads a memory-writer run thread when the terminal state carries no messages', async () => {+ const emitSpy = vi+ .spyOn(agentSignalService, 'emitAgentSignalSourceEvent')+ .mockResolvedValue(undefined as any);+ const lifecycle = buildLifecycle();+ const query = vi.spyOn(lifecycle['messageModel'], 'query').mockResolvedValue([+ {+ id: 'msg-tool-call',+ role: 'assistant',+ tools: [+ {+ apiName: 'addPreferenceMemory',+ arguments: JSON.stringify({+ summary: 'Answer in bullets',+ title: 'Prefers bullet answers',+ }),+ id: 'call_pref',+ identifier: 'lobe-user-memory',+ type: 'builtin',+ },+ ],+ },+ {+ content: 'Preference memory saved with memoryId: "mem_1" and preferenceId: "pref_1"',+ id: 'msg-tool-result',+ role: 'tool',+ tool_call_id: 'call_pref',+ },+ ] as any);++ await lifecycle.emitSignalEvents(+ 'op-memory',+ {+ messages: [],+ origin: {+ agentId: 'agent-1',+ signal: { kind: 'memory', sourceId: 'memory-source-1', topicId: 'tpc-1' },+ threadId: 'thd-memory',+ topicId: 'tpc-1',+ userId: 'user-1',+ },+ stepCount: 3,+ usage: {+ tools: {+ byTool: [{ calls: 1, errors: 0, name: 'lobe-user-memory/addPreferenceMemory' }],+ },+ },+ },+ 'done',+ );++ expect(query).toHaveBeenCalledWith(+ expect.objectContaining({ threadId: 'thd-memory', topicId: 'tpc-1' }),+ expect.anything(),+ );+ const [emission] = emitSpy.mock.calls[0];+ expect(emission.payload.selfIteration.mutations[0].data.target).toMatchObject({+ id: 'pref_1',+ memoryId: 'mem_1',+ title: 'Prefers bullet answers',+ });+ });+it('hydrates a persisted self-reflection marker when terminal state metadata lost it', async () => {const emitSpy = vi.spyOn(agentSignalService, 'emitAgentSignalSourceEvent')diff --git a/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts b/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.tsindex b36d2b41083..119bf308c74 100644--- a/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts@@ -78,9 +78,7 @@ vi.mock('@/server/services/queue/impls', () => ({isQueueAgentRuntimeEnabled: vi.fn().mockReturnValue(false),}));vi.mock('@/server/featureFlags', () => ({- getServerFeatureFlagsStateFromRuntimeConfig: vi- .fn()- .mockResolvedValue({ enableAgentSelfIteration: true }),+ getServerFeatureFlagsStateFromRuntimeConfig: vi.fn().mockResolvedValue({}),}));vi.mock('../../agentSignal/featureGate', () => ({isAgentSignalEnabledForUser: vi.fn().mockResolvedValue(true),diff --git a/apps/server/src/services/agentSignal/__tests__/budget.test.ts b/apps/server/src/services/agentSignal/__tests__/budget.test.tsnew file mode 100644index 00000000000..ebccdce9863--- /dev/null+++ b/apps/server/src/services/agentSignal/__tests__/budget.test.ts@@ -0,0 +1,133 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { acquireAgentSignalDailyBudget, describeBudgetDenial, toUtcDay } from '../budget';+import { AGENT_SIGNAL_DEFAULTS } from '../constants';++const service = vi.hoisted(() => ({+ available: true,+ countClassifierCall: vi.fn(),+ counters: new Map<string, number>(),+}));++vi.mock('@/server/services/redis', () => ({+ redisService: { agentSignal: { countClassifierCall: service.countClassifierCall } },+}));++const NOW = Date.UTC(2026, 9, 11, 23, 30);++describe('acquireAgentSignalDailyBudget', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ service.available = true;+ service.counters.clear();+ service.countClassifierCall.mockImplementation(+ async ({ userId, utcDay }: { userId: string; utcDay: string }) => {+ if (!service.available) return undefined;+ const key = `${userId}:${utcDay}`;+ const next = (service.counters.get(key) ?? 0) + 1;+ service.counters.set(key, next);+ return next;+ },+ );+ });++ /**+ * @example+ * Call 200 of the day is allowed; call 201 is denied with an `exceeded` reason.+ */+ it('allows classifier calls up to the daily limit and denies the next one', async () => {+ const limit = AGENT_SIGNAL_DEFAULTS.dailyFeedbackClassifierBudgetPerUser;+ service.counters.set('u1:2026-10-11', limit - 1);++ await expect(+ acquireAgentSignalDailyBudget({ kind: 'feedback-classifier', now: NOW, userId: 'u1' }),+ ).resolves.toEqual({ allowed: true, count: limit, kind: 'feedback-classifier', limit: 200 });+ await expect(+ acquireAgentSignalDailyBudget({ kind: 'feedback-classifier', now: NOW, userId: 'u1' }),+ ).resolves.toEqual({+ allowed: false,+ count: limit + 1,+ kind: 'feedback-classifier',+ limit,+ reason: 'exceeded',+ });+ expect(service.countClassifierCall).toHaveBeenCalledWith({+ userId: 'u1',+ utcDay: '2026-10-11',+ });+ });++ /**+ * @example+ * Budgets are per user and per UTC day.+ */+ it('keeps separate counters per user and UTC day', async () => {+ service.counters.set('u1:2026-10-11', 1000);++ await expect(+ acquireAgentSignalDailyBudget({ kind: 'feedback-classifier', now: NOW, userId: 'u2' }),+ ).resolves.toMatchObject({ allowed: true });+ await expect(+ acquireAgentSignalDailyBudget({+ kind: 'feedback-classifier',+ now: NOW + 60 * 60 * 1000,+ userId: 'u1',+ }),+ ).resolves.toMatchObject({ allowed: true, count: 1 });+ expect(toUtcDay(NOW + 60 * 60 * 1000)).toBe('2026-10-12');+ });++ /**+ * @example+ * No Redis configured: the budget cannot be enforced, so the work is skipped.+ */+ it('fails closed when Redis is not configured', async () => {+ service.available = false;++ await expect(+ acquireAgentSignalDailyBudget({ kind: 'feedback-classifier', now: NOW, userId: 'u1' }),+ ).resolves.toEqual({+ allowed: false,+ kind: 'feedback-classifier',+ limit: AGENT_SIGNAL_DEFAULTS.dailyFeedbackClassifierBudgetPerUser,+ reason: 'unavailable',+ });+ });++ /**+ * @example+ * A Redis error is logged and treated as an unavailable budget, never thrown.+ */+ it('fails closed without throwing when Redis errors', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ service.countClassifierCall.mockRejectedValueOnce(new Error('connection reset'));++ await expect(+ acquireAgentSignalDailyBudget({ kind: 'feedback-classifier', now: NOW, userId: 'u1' }),+ ).resolves.toMatchObject({ allowed: false, reason: 'unavailable' });+ expect(consoleError).toHaveBeenCalled();+ consoleError.mockRestore();+ });++ it('describes denials for skip details', () => {+ expect(+ describeBudgetDenial({+ allowed: false,+ kind: 'feedback-classifier',+ limit: 200,+ reason: 'exceeded',+ }),+ ).toBe('Daily Agent Signal feedback-classifier budget exceeded (200/day).');+ expect(+ describeBudgetDenial({+ allowed: false,+ kind: 'feedback-classifier',+ limit: 200,+ reason: 'unavailable',+ }),+ ).toBe(+ 'Daily Agent Signal feedback-classifier budget unavailable; skipped to stay within budget.',+ );+ });+});diff --git a/apps/server/src/services/agentSignal/__tests__/featureGate.test.ts b/apps/server/src/services/agentSignal/__tests__/featureGate.test.tsindex e4f2cd38284..b93ffa02229 100644--- a/apps/server/src/services/agentSignal/__tests__/featureGate.test.ts+++ b/apps/server/src/services/agentSignal/__tests__/featureGate.test.ts@@ -1,91 +1,91 @@// @vitest-environment node-import { beforeEach, describe, expect, it, vi } from 'vitest';--import {- isAgentSignalEnabledForUser,- isLobeAiAgentSlug,- resolveAgentSelfIterationCapability,-} from '../featureGate';+import { isAgentSignalEnabledForUser, resetAgentSignalUserGateCache } from '../featureGate';const mocks = vi.hoisted(() => ({getServerFeatureFlagsStateFromRuntimeConfig: vi.fn(),+ getUserPreference: vi.fn(),+ userModelConstructor: vi.fn(),}));vi.mock('@/server/featureFlags', () => ({getServerFeatureFlagsStateFromRuntimeConfig: mocks.getServerFeatureFlagsStateFromRuntimeConfig,}));+vi.mock('@/database/models/user', () => ({+ UserModel: class {+ constructor(...args: unknown[]) {+ mocks.userModelConstructor(...args);+ }++ getUserPreference = mocks.getUserPreference;+ },+}));+describe('isAgentSignalEnabledForUser', () => {+ const db = {} as never;+beforeEach(() => {vi.clearAllMocks();+ resetAgentSignalUserGateCache();+ // A stale rollout flag must no longer decide anything.mocks.getServerFeatureFlagsStateFromRuntimeConfig.mockResolvedValue({enableAgentSelfIteration: true,});});/**- * @example- * expect(result).toBe(true).+ * ROOT CAUSE: two switches gated self-evolution — the `agent_self_iteration` server flag for+ * the background pipeline and Labs → Self-evolving for expertise. The Labs switch is now the+ * single user-level gate.*/- it('uses the feature flag as the user-level Agent Signal gate', async () => {- const result = await isAgentSignalEnabledForUser({} as never, 'user-1');+ it('reads the Labs Self-evolving switch instead of the feature flag', async () => {+ mocks.getUserPreference.mockResolvedValue({ lab: { enableSelfLearning: false } });- expect(result).toBe(true);- expect(mocks.getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledWith('user-1');+ await expect(isAgentSignalEnabledForUser(db, 'user-1')).resolves.toBe(false);+ expect(mocks.userModelConstructor).toHaveBeenCalledWith(db, 'user-1');+ expect(mocks.getServerFeatureFlagsStateFromRuntimeConfig).not.toHaveBeenCalled();});-});-describe('agentSignal feature gates', () => {- it('recognizes only the inbox builtin slug as Lobe AI', () => {- expect(isLobeAiAgentSlug('inbox')).toBe(true);- expect(isLobeAiAgentSlug('task-agent')).toBe(false);- expect(isLobeAiAgentSlug('page-agent')).toBe(false);- expect(isLobeAiAgentSlug(undefined)).toBe(false);- expect(isLobeAiAgentSlug(null)).toBe(false);- expect(isLobeAiAgentSlug('')).toBe(false);+ it('enables the user when the Labs switch is on', async () => {+ mocks.getUserPreference.mockResolvedValue({ lab: { enableSelfLearning: true } });++ await expect(isAgentSignalEnabledForUser(db, 'user-1')).resolves.toBe(true);});- it('disables self-iteration when the feature flag is disabled', () => {- expect(- resolveAgentSelfIterationCapability({- agentSelfIterationEnabled: true,- isAgentSelfIterationFeatureEnabled: false,- isLobeAiAgent: true,- }),- ).toBe(false);+ it('treats a missing preference or lab section as off', async () => {+ mocks.getUserPreference.mockResolvedValue(undefined);+ await expect(isAgentSignalEnabledForUser(db, 'user-1')).resolves.toBe(false);++ mocks.getUserPreference.mockResolvedValue({});+ await expect(isAgentSignalEnabledForUser(db, 'user-2')).resolves.toBe(false);});- it('enables Lobe AI self-iteration when the feature flag is enabled', () => {- expect(- resolveAgentSelfIterationCapability({- isAgentSelfIterationFeatureEnabled: true,- isLobeAiAgent: true,+ it('uses an already loaded preference without reading the database', async () => {+ await expect(+ isAgentSignalEnabledForUser(db, 'user-1', {+ preference: { lab: { enableSelfLearning: true } },}),- ).toBe(true);+ ).resolves.toBe(true);+ await expect(+ isAgentSignalEnabledForUser(db, 'user-1', { preference: undefined }),+ ).resolves.toBe(false);+ expect(mocks.getUserPreference).not.toHaveBeenCalled();});- it('keeps non-Lobe AI agents behind agentSelfIterationEnabled', () => {- expect(- resolveAgentSelfIterationCapability({- agentSelfIterationEnabled: true,- isAgentSelfIterationFeatureEnabled: true,- isLobeAiAgent: false,- }),- ).toBe(true);+ it('reuses one read per user within the cache window', async () => {+ mocks.getUserPreference.mockResolvedValue({ lab: { enableSelfLearning: true } });- expect(- resolveAgentSelfIterationCapability({- agentSelfIterationEnabled: false,- isAgentSelfIterationFeatureEnabled: true,- isLobeAiAgent: false,- }),- ).toBe(false);+ await isAgentSignalEnabledForUser(db, 'user-1');+ await isAgentSignalEnabledForUser(db, 'user-1');- expect(- resolveAgentSelfIterationCapability({- isAgentSelfIterationFeatureEnabled: true,- isLobeAiAgent: false,- }),- ).toBe(false);+ expect(mocks.getUserPreference).toHaveBeenCalledOnce();+ });++ it('fails closed when the preference read errors', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ mocks.getUserPreference.mockRejectedValue(new Error('db down'));++ await expect(isAgentSignalEnabledForUser(db, 'user-1')).resolves.toBe(false);+ consoleError.mockRestore();});});diff --git a/apps/server/src/services/agentSignal/__tests__/index.integration.test.ts b/apps/server/src/services/agentSignal/__tests__/index.integration.test.tsindex 37b68cfb4d7..630e563b87a 100644--- a/apps/server/src/services/agentSignal/__tests__/index.integration.test.ts+++ b/apps/server/src/services/agentSignal/__tests__/index.integration.test.ts@@ -16,9 +16,16 @@ const mockRedis = {expire: vi.fn(),hgetall: vi.fn(),hset: vi.fn(),+ incr: vi.fn(),set: vi.fn(),};+// The daily classifier budget counts through the Redis business service.+const mockCountClassifierCall = vi.hoisted(() => vi.fn());+vi.mock('@/server/services/redis', () => ({+ redisService: { agentSignal: { countClassifierCall: mockCountClassifierCall } },+}));+/*** Loads the Agent Signal service entrypoint with one test-scoped module graph.*@@ -97,6 +104,8 @@ const loadIndexIntegrationModule = async (options: LoadIndexIntegrationModuleOptafterEach(() => {vi.clearAllMocks();+ vi.doUnmock('@/server/services/expertise/ingestion');+ vi.doUnmock('../services/selfIteration/completion');vi.resetModules();(globalThis as { __agentSignalRedisClient?: typeof mockRedis | undefined }@@ -301,6 +310,7 @@ describe('emitAgentSignalSourceEvent integration', () => {mockRedis.hgetall.mockResolvedValue({});mockRedis.hset.mockResolvedValue(1);mockRedis.expire.mockResolvedValue(1);+ mockCountClassifierCall.mockResolvedValue(1);const initModelRuntimeFromDB = vi.fn().mockResolvedValue({generateObject: vi.fn().mockResolvedValue({confidence: 0.91,@@ -348,4 +358,107 @@ describe('emitAgentSignalSourceEvent integration', () => {);},);+ /**+ * @example+ * The 201st feedback message of the UTC day concludes without a classifier call.+ */+ it(+ 'skips the satisfaction classifier once the daily feedback-classifier budget is spent',+ { timeout: 10_000 },+ async () => {+ (globalThis as { __agentSignalRedisClient?: typeof mockRedis }).__agentSignalRedisClient =+ mockRedis;+ mockRedis.set.mockResolvedValue('OK');+ mockRedis.del.mockResolvedValue(1);+ mockRedis.hgetall.mockResolvedValue({});+ mockRedis.hset.mockResolvedValue(1);+ mockRedis.expire.mockResolvedValue(1);+ mockCountClassifierCall.mockResolvedValue(201);+ const initModelRuntimeFromDB = vi.fn();++ const { emitAgentSignalSourceEvent } = await loadIndexIntegrationModule({+ mockInitModelRuntimeFromDB: initModelRuntimeFromDB,+ });++ const result = await emitAgentSignalSourceEvent(+ {+ payload: { message: 'That answer was wrong.', messageId: 'msg_budget' },+ sourceId: 'source_budget',+ sourceType: 'agent.user.message',+ },+ { agentId: 'agent_1', db: {} as never, userId: 'user_1' },+ );++ expect(result?.deduped).toBe(false);+ expect(mockCountClassifierCall).toHaveBeenCalledWith({+ userId: 'user_1',+ utcDay: expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/),+ });+ expect(initModelRuntimeFromDB).not.toHaveBeenCalled();+ },+ );++ /**+ * Completion-path expertise ingestion is not budgeted per day any more; the nightly pass+ * shares the review's per-night topic quota instead.+ */+ it('wires the nightly topic quota, not a daily budget, into completion-path ingestion', async () => {+ (globalThis as { __agentSignalRedisClient?: typeof mockRedis }).__agentSignalRedisClient =+ mockRedis;+ mockRedis.expire.mockResolvedValue(1);+ mockCountClassifierCall.mockResolvedValue(10_000);+ const ingestSelfReview = vi.fn().mockResolvedValue({ ingested: 0 });+ vi.doMock('@/server/services/expertise/ingestion', () => ({+ ExpertiseIngestionService: class {+ ingestSelfReview = ingestSelfReview;+ },+ }));+ vi.doMock('../services/selfIteration/completion', () => ({+ createSelfIterationCompletionHandler: () => async () => {},+ }));+ const createDefaultAgentSignalPolicies = vi.fn().mockReturnValue([]);+ const source = {+ chain: { chainId: 'chain:budget', rootSourceId: 'budget-source' },+ payload: {},+ scopeKey: 'topic:topic-1',+ sourceId: 'budget-source',+ sourceType: 'agent.execution.completed',+ timestamp: 1_710_000_000_000,+ };++ const { emitAgentSignalSourceEvent } = await loadIndexIntegrationModule({+ mockCreateDefaultAgentSignalPolicies: createDefaultAgentSignalPolicies,+ mockEmitSourceEvent: vi.fn().mockResolvedValue({+ deduped: false,+ source,+ trigger: { scopeKey: 'topic:topic-1', token: 't', windowEventCount: 1 },+ }),+ mockRuntimeFactory: vi.fn().mockReturnValue({+ emitNormalized: vi.fn().mockResolvedValue({+ status: 'completed',+ trace: { actions: [], results: [], signals: [], source },+ }),+ }),+ });++ await emitAgentSignalSourceEvent(+ {+ payload: { message: 'done', messageId: 'msg-budget' },+ sourceId: 'budget-source',+ sourceType: 'agent.user.message',+ },+ { agentId: 'agent-1', db: {} as never, userId: 'user-1' },+ );++ const policyOptions = createDefaultAgentSignalPolicies.mock.calls[0]![0];+ const completionInput = { operationId: 'op-1' };+ await policyOptions.completion.onSelfIterationCompleted(completionInput);++ const { claimNightlyReviewTopics } =+ await import('../services/selfIteration/review/topicQuota');+ expect(ingestSelfReview).toHaveBeenCalledWith(completionInput, {+ claimNightlyTopics: claimNightlyReviewTopics,+ });+ expect(mockCountClassifierCall).not.toHaveBeenCalled();+ });});diff --git a/apps/server/src/services/agentSignal/__tests__/triggerRateLimit.test.ts b/apps/server/src/services/agentSignal/__tests__/triggerRateLimit.test.tsnew file mode 100644index 00000000000..ccdd00c235d--- /dev/null+++ b/apps/server/src/services/agentSignal/__tests__/triggerRateLimit.test.ts@@ -0,0 +1,67 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ AGENT_SIGNAL_TRIGGER_RATE_LIMIT_PER_HOUR,+ assertAgentSignalTriggerRateLimit,+ consumeAgentSignalTriggerQuota,+} from '../triggerRateLimit';++const service = vi.hoisted(() => ({+ available: true,+ counters: new Map<string, number>(),+ countManualTrigger: vi.fn(),+}));++vi.mock('@/server/services/redis', () => ({+ redisService: { agentSignal: { countManualTrigger: service.countManualTrigger } },+}));++beforeEach(() => {+ service.available = true;+ service.counters.clear();+ service.countManualTrigger.mockImplementation(async (userId: string) => {+ if (!service.available) return undefined;+ const next = (service.counters.get(userId) ?? 0) + 1;+ service.counters.set(userId, next);+ return next;+ });+});++describe('consumeAgentSignalTriggerQuota', () => {+ /**+ * ROOT CAUSE:+ *+ * `triggerSourceEvent` had no rate limit, so one user could enqueue model-backed Agent Signal+ * workflows as fast as they could call the endpoint.+ */+ it(`allows ${AGENT_SIGNAL_TRIGGER_RATE_LIMIT_PER_HOUR} triggers per hour per user`, async () => {+ const results: boolean[] = [];++ for (let index = 0; index <= AGENT_SIGNAL_TRIGGER_RATE_LIMIT_PER_HOUR; index += 1) {+ results.push(await consumeAgentSignalTriggerQuota('user-1'));+ }++ expect(results.filter(Boolean)).toHaveLength(AGENT_SIGNAL_TRIGGER_RATE_LIMIT_PER_HOUR);+ expect(results.at(-1)).toBe(false);+ // Another user keeps their own budget.+ await expect(consumeAgentSignalTriggerQuota('user-2')).resolves.toBe(true);+ });++ it('allows the call when Redis is not configured', async () => {+ service.available = false;++ await expect(consumeAgentSignalTriggerQuota('user-1')).resolves.toBe(true);+ });+});++describe('assertAgentSignalTriggerRateLimit', () => {+ it('throws TOO_MANY_REQUESTS once the budget is spent', async () => {+ for (let index = 0; index < AGENT_SIGNAL_TRIGGER_RATE_LIMIT_PER_HOUR; index += 1) {+ await assertAgentSignalTriggerRateLimit('user-1');+ }++ await expect(assertAgentSignalTriggerRateLimit('user-1')).rejects.toMatchObject({+ code: 'TOO_MANY_REQUESTS',+ });+ });+});diff --git a/apps/server/src/services/agentSignal/__tests__/triggerSourceEvent.test.ts b/apps/server/src/services/agentSignal/__tests__/triggerSourceEvent.test.tsindex 36b0cad5f59..3a627e5ec9d 100644--- a/apps/server/src/services/agentSignal/__tests__/triggerSourceEvent.test.ts+++ b/apps/server/src/services/agentSignal/__tests__/triggerSourceEvent.test.ts@@ -1,5 +1,5 @@import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import {AGENT_SIGNAL_TRIGGER_SOURCE_TYPES,@@ -130,7 +130,7 @@ describe('buildTriggerSourceEvent', () => {now: NOW,scopeKey: 'agent:agent_1:user:user_1',sourceId: 'custom-source-id',- sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,timestamp: 123,userId,});@@ -139,4 +139,76 @@ describe('buildTriggerSourceEvent', () => {expect(event.scopeKey).toBe('agent:agent_1:user:user_1');expect(event.timestamp).toBe(123);});++ describe('nightly review guard key', () => {+ /**+ * ROOT CAUSE:+ *+ * The nightly review handler claims `nightly-review:{userId}:{agentId}:{localDate}` once per+ * day and only runs when `sourceId` equals that key. Letting the caller choose `localDate`+ * (with a matching `sourceId`) minted a fresh guard key per call, so one user could start an+ * unbounded number of model-backed reviews through `triggerSourceEvent`.+ */+ it('derives localDate, agentId and sourceId server-side outside development', () => {+ const event = buildTriggerSourceEvent({+ agentId,+ now: NOW,+ payloadOverride: { agentId: 'agent_other', localDate: '1999-01-01' },+ sourceId: 'nightly-review:user_1:agent_1:1999-01-01',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ userId,+ });++ const payload = event.payload as Record<string, unknown>;+ expect(payload.localDate).toBe('2026-05-31');+ expect(payload.agentId).toBe(agentId);+ expect(event.sourceId).toBe('nightly-review:user_1:agent_1:2026-05-31');+ });++ it('still allows overrides that do not feed the guard key', () => {+ const event = buildTriggerSourceEvent({+ agentId,+ now: NOW,+ payloadOverride: { reviewWindowStart: '2026-05-29T12:00:00.000Z' },+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ userId,+ });++ const payload = event.payload as Record<string, unknown>;+ expect(payload.reviewWindowStart).toBe('2026-05-29T12:00:00.000Z');+ });++ it('lets development pin a localDate and sourceId to replay one day', () => {+ const event = buildTriggerSourceEvent({+ agentId,+ allowNightlyReviewGuardOverride: true,+ now: NOW,+ payloadOverride: { localDate: '2026-05-01' },+ sourceId: 'custom-source-id',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ userId,+ });++ expect((event.payload as Record<string, unknown>).localDate).toBe('2026-05-01');+ expect(event.sourceId).toBe('custom-source-id');+ });++ it('defaults the override permission to NODE_ENV=development', () => {+ vi.stubEnv('NODE_ENV', 'development');++ try {+ const event = buildTriggerSourceEvent({+ agentId,+ now: NOW,+ payloadOverride: { localDate: '2026-05-01' },+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ userId,+ });++ expect(event.sourceId).toBe('nightly-review:user_1:agent_1:2026-05-01');+ } finally {+ vi.unstubAllEnvs();+ }+ });+ });});diff --git a/apps/server/src/services/agentSignal/budget.ts b/apps/server/src/services/agentSignal/budget.tsnew file mode 100644index 00000000000..69c7b293880--- /dev/null+++ b/apps/server/src/services/agentSignal/budget.ts@@ -0,0 +1,109 @@+import debug from 'debug';++import { redisService } from '@/server/services/redis';++import { AGENT_SIGNAL_DEFAULTS } from './constants';++const log = debug('lobe-server:agent-signal:budget');++/**+ * Per-user daily budgets Agent Signal enforces.+ *+ * Only the satisfaction classifier is metered per day; everyday background runs have no count+ * cap, and nightly review is bounded per night by its own topic quota.+ */+export type AgentSignalDailyBudgetKind = 'feedback-classifier';++/** Outcome of one budget acquisition. */+export interface AgentSignalBudgetDecision {+ allowed: boolean;+ /** Counter value after this acquisition, when the store answered. */+ count?: number;+ kind: AgentSignalDailyBudgetKind;+ limit: number;+ /** Why the acquisition was denied. */+ reason?: 'exceeded' | 'unavailable';+}++const DAILY_LIMITS: Record<AgentSignalDailyBudgetKind, number> = {+ 'feedback-classifier': AGENT_SIGNAL_DEFAULTS.dailyFeedbackClassifierBudgetPerUser,+};++/** Formats the UTC calendar day used as the budget window, e.g. `2026-10-11`. */+export const toUtcDay = (now: number) => new Date(now).toISOString().slice(0, 10);++/**+ * Takes one unit of a per-user, per-UTC-day Agent Signal budget.+ *+ * Use when:+ * - Agent Signal is about to spend the user's provider credentials on background work+ *+ * Expects:+ * - `userId` is the owner whose credentials the work bills to+ *+ * Returns:+ * - `allowed: true` while the user is within the day's limit+ * - `allowed: false` with `reason: 'exceeded'` once over the limit+ * - `allowed: false` with `reason: 'unavailable'` when Redis is missing or errors+ *+ * Fails closed on purpose: this is optional background work billed to the user, so an+ * unenforceable budget skips the work instead of running it unbounded. Without Redis the+ * source-event dedupe already drops every event, so no working setup loses anything.+ */+export const acquireAgentSignalDailyBudget = async (input: {+ kind: AgentSignalDailyBudgetKind;+ now?: number;+ userId: string;+}): Promise<AgentSignalBudgetDecision> => {+ const limit = DAILY_LIMITS[input.kind];++ let count: number | undefined;+ try {+ count = await redisService.agentSignal.countClassifierCall({+ userId: input.userId,+ utcDay: toUtcDay(input.now ?? Date.now()),+ });+ } catch (error) {+ console.error('[AgentSignal] Failed to read daily budget, skipping work:', {+ error,+ kind: input.kind,+ userId: input.userId,+ });++ return { allowed: false, kind: input.kind, limit, reason: 'unavailable' };+ }++ if (count === undefined) {+ log('budget store unavailable kind=%s user=%s', input.kind, input.userId);++ return { allowed: false, kind: input.kind, limit, reason: 'unavailable' };+ }++ if (count > limit) {+ log(+ 'budget exceeded kind=%s user=%s count=%d limit=%d',+ input.kind,+ input.userId,+ count,+ limit,+ );++ return { allowed: false, count, kind: input.kind, limit, reason: 'exceeded' };+ }++ return { allowed: true, count, kind: input.kind, limit };+};++/**+ * Describes a denied budget decision for skip details and runtime traces.+ *+ * Before:+ * - `{ kind: 'feedback-classifier', limit: 200, reason: 'exceeded' }`+ *+ * After:+ * - `"Daily Agent Signal feedback-classifier budget exceeded (200/day)."`+ */+export const describeBudgetDenial = (decision: AgentSignalBudgetDecision) =>+ decision.reason === 'exceeded'+ ? `Daily Agent Signal ${decision.kind} budget exceeded (${decision.limit}/day).`+ : `Daily Agent Signal ${decision.kind} budget unavailable; skipped to stay within budget.`;diff --git a/apps/server/src/services/agentSignal/constants.ts b/apps/server/src/services/agentSignal/constants.tsindex b2131013229..d6a60c09536 100644--- a/apps/server/src/services/agentSignal/constants.ts+++ b/apps/server/src/services/agentSignal/constants.ts@@ -18,10 +18,23 @@ export const AGENT_SIGNAL_KEYS = {/** Server-owned timing defaults for AgentSignal storage and generation. */export const AGENT_SIGNAL_DEFAULTS = {+ /**+ * Per-user, per-UTC-day ceiling on feedback satisfaction classifier calls. Each call is a+ * mini-model request billed to the user's provider credentials.+ */+ dailyFeedbackClassifierBudgetPerUser: 200,generationLockTtlSeconds: 5,+ /**+ * Most distinct topics one user's nightly review may process for one local review date, across+ * all of that user's agents: topics fed into each agent's review context plus topics the+ * nightly expertise ingestion reads. Everyday conversation has no count cap.+ */+ nightlyReviewTopicLimitPerUser: 50,receiptTtlSeconds: 3 * 24 * 60 * 60,runtimeGuardTtlSeconds: 3600,runtimeWaypointTtlSeconds: 3600,+ /** Max accepted self-feedback intent declarations per operation (or topic) scope. */+ selfFeedbackIntentDeclarationLimitPerScope: 3,signalDedupeTtlSeconds: 300,signalWindowTtlSeconds: 3600,} as const;diff --git a/apps/server/src/services/agentSignal/featureGate.ts b/apps/server/src/services/agentSignal/featureGate.tsindex 519cfd35635..e1db330f3c0 100644--- a/apps/server/src/services/agentSignal/featureGate.ts+++ b/apps/server/src/services/agentSignal/featureGate.ts@@ -1,99 +1,80 @@-import { INBOX_SESSION_ID } from '@lobechat/const';+import type { UserPreference } from '@lobechat/types';+import { UserModel } from '@/database/models/user';import type { LobeChatDatabase } from '@/database/type';-import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';/**- * Input used to resolve Agent Signal self-iteration capability.- */-export interface AgentSelfIterationCapabilityInput {- /**- * Stored agent-level self-iteration setting.- */- agentSelfIterationEnabled?: boolean;- /**- * User-level rollout result from `enableAgentSelfIteration`.- */- isAgentSelfIterationFeatureEnabled: boolean;- /**- * Whether the agent is the product-owned Lobe AI agent.- */- isLobeAiAgent: boolean;-}--/**- * Checks whether a slug belongs to Lobe AI.+ * Reads the Labs → Self-evolving switch out of a loaded user preference.** Use when:- * - Agent Signal must special-case the product-owned default assistant- * - Code must avoid treating every virtual/builtin agent as Lobe AI- *- * Expects:- * - `slug` is the persisted agent slug or `undefined` when unavailable+ * - The caller already holds `users.preference` and must not read it again** Returns:- * - `true` only for the builtin inbox agent slug+ * - `true` only when `preference.lab.enableSelfLearning` is explicitly `true`*/-export const isLobeAiAgentSlug = (slug?: string | null) => slug === INBOX_SESSION_ID;+export const isSelfLearningEnabledInPreference = (+ preference: Pick<UserPreference, 'lab'> | null | undefined,+) => preference?.lab?.enableSelfLearning === true;/**- * Resolves whether one agent may run Agent Signal self-iteration.- *- * Use when:- * - Server code has an agent context and must combine rollout with per-agent capability- * - Lobe AI should be managed by feature flag instead of stored chat config+ * How long one user's resolved switch is reused inside this process.*- * Expects:- * - `isAgentSelfIterationFeatureEnabled` already includes the user-level feature-flag result- *- * Returns:- * - `true` for Lobe AI when the feature flag is enabled- * - `true` for non-Lobe AI only when `agentSelfIterationEnabled` is true+ * Agent Signal asks on every runtime step and every enqueued source event, so an uncached read+ * would add a `users` lookup to each of them. Five seconds matches the feature-flag runtime+ * cache this gate replaced; a toggle reaches background work within that window.*/-export const resolveAgentSelfIterationCapability = (input: AgentSelfIterationCapabilityInput) => {- if (!input.isAgentSelfIterationFeatureEnabled) return false;+const USER_GATE_CACHE_TTL_MS = 5000;+/** Bounds the cache; past it the whole map is dropped rather than tracking recency. */+const USER_GATE_CACHE_MAX_ENTRIES = 5000;- if (input.isLobeAiAgent) return true;+const userGateCache = new Map<string, { expiresAt: number; value: Promise<boolean> }>();- return input.agentSelfIterationEnabled === true;-};+/** Clears the per-process switch cache. Tests only. */+export const resetAgentSignalUserGateCache = () => userGateCache.clear();-/**- * Resolves whether Agent Self-iteration is feature-flag enabled for the current user.- *- * Use when:- * - UI or server code needs to know whether Agent Self-iteration can be used- * - RuntimeConfig-backed feature flags are the source of truth for rollout eligibility- *- * Expects:- * - `userId` belongs to the current authenticated user- *- * Returns:- * - `true` only when the Agent Self-iteration feature flag is enabled for the user- */-export const isAgentSelfIterationFeatureEnabledForUser = async (userId: string) => {- const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);+const readSelfLearningSwitch = async (db: LobeChatDatabase, userId: string) => {+ try {+ const preference = await new UserModel(db, userId).getUserPreference();- return featureFlags.enableAgentSelfIteration === true;+ return isSelfLearningEnabledInPreference(preference);+ } catch (error) {+ console.error('[AgentSignal] Failed to read the Self-evolving Labs switch:', error);+ return false;+ }};/**- * Resolves whether Agent Signal execution is enabled for the current user.+ * Resolves whether Agent Signal self-iteration and Self-evolving learning may run for one user.+ *+ * The single user-level gate is the Labs → Self-evolving switch+ * (`users.preference.lab.enableSelfLearning`). It covers background memory and skill writes,+ * reflection, self-feedback intent, nightly review, and expertise lessons alike.** Use when:* - A server entrypoint needs to decide whether Agent Signal may execute- * - RuntimeConfig-backed feature flags are the source of truth for rollout eligibility** Expects:- * - `userId` belongs to the current authenticated user+ * - `userId` belongs to the user whose credentials the work bills to+ * - `options.preference`, when the caller already loaded the row, skips the read** Returns:- * - `true` only when the Agent Self-iteration feature flag is enabled for the user+ * - `true` only when the user turned the Labs switch on; read failures resolve to `false`*/-export const isAgentSignalEnabledForUser = async (_db: LobeChatDatabase, userId: string) => {- try {- return await isAgentSelfIterationFeatureEnabledForUser(userId);- } catch {- return false;- }+export const isAgentSignalEnabledForUser = async (+ db: LobeChatDatabase,+ userId: string,+ options: { preference?: Pick<UserPreference, 'lab'> | null } = {},+): Promise<boolean> => {+ if ('preference' in options) return isSelfLearningEnabledInPreference(options.preference);++ const now = Date.now();+ const cached = userGateCache.get(userId);+ if (cached && cached.expiresAt > now) return cached.value;++ if (userGateCache.size >= USER_GATE_CACHE_MAX_ENTRIES) userGateCache.clear();++ const value = readSelfLearningSwitch(db, userId);+ userGateCache.set(userId, { expiresAt: now + USER_GATE_CACHE_TTL_MS, value });++ return value;};diff --git a/apps/server/src/services/agentSignal/orchestrator.ts b/apps/server/src/services/agentSignal/orchestrator.tsindex fe1adba03f9..ba357b4f284 100644--- a/apps/server/src/services/agentSignal/orchestrator.ts+++ b/apps/server/src/services/agentSignal/orchestrator.ts@@ -12,6 +12,7 @@ import { createSourceEvent } from '@lobechat/agent-signal/source';import { ExpertiseIngestionService } from '@/server/services/expertise/ingestion';+import { acquireAgentSignalDailyBudget } from './budget';import type {AgentSignalEmitOptions,AgentSignalExecutionContext,@@ -26,6 +27,9 @@ import type { RuntimeGuardBackend } from './runtime/AgentSignalRuntime';import { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';import { persistAgentSignalReceipts, projectAgentSignalReceipts } from './services/receiptService';import { createSelfIterationCompletionHandler } from './services/selfIteration/completion';+import { createServerSelfReviewBriefWriter } from './services/selfIteration/review/brief';+import { resolveSelfReviewBriefTextTranslator } from './services/selfIteration/review/briefTextTranslator';+import { claimNightlyReviewTopics } from './services/selfIteration/review/topicQuota';import { emitSourceEvent } from './sources';import { redisPolicyStateStore } from './store/adapters/redis/policyStateStore';import type { AgentSignalReceiptStore, AgentSignalSourceEventStore } from './store/types';@@ -98,22 +102,37 @@ const createPolicyOptions = (options: ExecuteAgentSignalSourceEventOptions,procedurePolicyOptions: NonNullable<CreateDefaultAgentSignalPoliciesOptions['procedure']>,): CreateDefaultAgentSignalPoliciesOptions => {- // Nightly review writes its Daily Brief in-run via the builtin review- // serverRuntime primitive, so the orchestrator no longer injects a brief- // writer default.+ // Nightly review writes proposal Daily Briefs in-run via the builtin review+ // serverRuntime primitive; the completion handler only writes the ideas brief.const policyOptions = options.policyOptions;return {completion: {onSelfIterationCompleted: async (input) => {- await createSelfIterationCompletionHandler(- options.receiptStore ? { receiptStore: options.receiptStore } : {},- )(input);+ await createSelfIterationCompletionHandler({+ // Idea-only nightly reviews get their Daily Brief from the completion+ // path; proposal briefs are still written in-run by the review tool.+ ideasBrief: {+ resolveTranslator: () =>+ resolveSelfReviewBriefTextTranslator(context.db, context.userId),+ writer: createServerSelfReviewBriefWriter(+ context.db,+ context.userId,+ context.workspaceId,+ ),+ },+ ...(options.receiptStore ? { receiptStore: options.receiptStore } : {}),+ })(input);await new ExpertiseIngestionService(context.db,context.userId,context.workspaceId,- ).ingestSelfReview(input);+ ).ingestSelfReview(+ input,+ // The nightly expertise pass shares the night's per-user topic quota with the+ // review itself. Store-injected runs (evals, isolated tests) stay unmetered.+ options.store ? {} : { claimNightlyTopics: claimNightlyReviewTopics },+ );},},feedbackDomainJudge: {@@ -123,6 +142,17 @@ const createPolicyOptions = (workspaceId: context.workspaceId,},feedbackSatisfactionJudge: {+ // Every satisfaction call bills the user's provider; cap it per user per day.+ // Store-injected runs (evals, isolated tests) avoid ambient Redis by contract.+ ...(options.store+ ? {}+ : {+ classifierBudget: () =>+ acquireAgentSignalDailyBudget({+ kind: 'feedback-classifier',+ userId: context.userId,+ }),+ }),db: context.db,...policyOptions?.feedbackSatisfactionJudge,userId: context.userId,diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.tsindex 65d936f1ec9..f7ac9032b50 100644--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts@@ -402,4 +402,36 @@ describe('feedbackSatisfactionJudge', () => {}),);});++ /**+ * @example+ * An exhausted per-user classifier budget concludes the source without a judge call.+ */+ it('does not call the judge when the classifier budget denies the call', async () => {+ const judge = { judgeSatisfaction: vi.fn() };+ const classifierBudget = vi.fn().mockResolvedValue({+ allowed: false,+ count: 201,+ kind: 'feedback-classifier',+ limit: 200,+ reason: 'exceeded',+ });+ const ctx = createRuntimeProcessorContext({+ backend: { getGuardState: vi.fn(), touchGuardState: vi.fn() },+ scopeKey: 'topic:thread_1',+ });++ const processor = createFeedbackSatisfactionJudgeProcessor({ classifierBudget, judge });+ const result = await processor.handle(+ createUserMessageSource('source_budget', 'That was wrong.'),+ ctx,+ );++ expect(classifierBudget).toHaveBeenCalledTimes(1);+ expect(judge.judgeSatisfaction).not.toHaveBeenCalled();+ expect(result).toEqual({+ concluded: { reason: 'Daily Agent Signal feedback-classifier budget exceeded (200/day).' },+ status: 'conclude',+ });+ });});diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.seed.test.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.seed.test.tsnew file mode 100644index 00000000000..4ef6994fca9--- /dev/null+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.seed.test.ts@@ -0,0 +1,107 @@+// @vitest-environment node+import { MemoryIdentifier } from '@lobechat/builtin-tool-memory';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { runMemoryActionAgent } from '../userMemory';++const { mockCreateOperation } = vi.hoisted(() => ({+ mockCreateOperation: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(function () {+ return { createOperation: mockCreateOperation };+ }),+}));++vi.mock('@/business/client/model-bank/loadModels', () => ({+ loadModels: vi.fn().mockResolvedValue([]),+}));++vi.mock('@/server/modules/Mecha', () => ({+ createServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({+ enabledToolIds: [MemoryIdentifier],+ tools: [{ function: { name: 'memory' }, type: 'function' }],+ }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+}));++const marker = { kind: 'memory', sourceId: 'source-1' } as const;++const createOptions = () => {+ const messageModel = { create: vi.fn().mockResolvedValue({ id: 'msg-seed' }) };+ const threadModel = { create: vi.fn().mockResolvedValue({ id: 'thread-1' }) };++ return {+ messageModel,+ options: {+ agentService: {+ getAgentConfig: vi.fn().mockResolvedValue({+ chatConfig: {},+ model: 'glm-5.3-flash',+ provider: 'lobehub',+ }),+ },+ db: {} as never,+ messageModel,+ pluginModel: { query: vi.fn().mockResolvedValue([]) },+ threadModel,+ userId: 'user-1',+ userModel: { getUserSettings: vi.fn().mockResolvedValue(undefined) },+ } as never,+ threadModel,+ };+};++describe('runMemoryActionAgent seed prompt', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('persists the writer prompt in the isolation thread so a DB reload keeps it', async () => {+ const { messageModel, options } = createOptions();++ await runMemoryActionAgent(+ {+ agentId: 'agent-1',+ message: 'remember I prefer tabs',+ sourceMessageId: 'msg-assistant',+ topicId: 'topic-1',+ },+ options,+ { marker },+ );++ expect(messageModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ role: 'user',+ threadId: 'thread-1',+ topicId: 'topic-1',+ }),+ );++ const params = mockCreateOperation.mock.calls[0][0];+ expect(params.initialMessages).toEqual([+ expect.objectContaining({ id: 'msg-seed', role: 'user' }),+ ]);+ // The first assistant message hangs under the persisted seed.+ expect(params.initialContext.payload.parentMessageId).toBe('msg-seed');+ });++ it('keeps the seed in memory only when no isolation thread exists', async () => {+ const { messageModel, options } = createOptions();++ await runMemoryActionAgent({ agentId: 'agent-1', message: 'remember I prefer tabs' }, options, {+ marker,+ });++ expect(messageModel.create).not.toHaveBeenCalled();++ const params = mockCreateOperation.mock.calls[0][0];+ expect(params.initialMessages).toEqual([{ content: expect.any(String), role: 'user' }]);+ expect(params.initialContext.payload.parentMessageId).toBeUndefined();+ });+});diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.tsindex a291e4ff76e..87a0a54e126 100644--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts@@ -7,6 +7,7 @@ import {buildUserMemoryActionAgentSignalMarker,defineUserMemoryActionHandler,resolveMemoryActionTargetFromState,+ runMemoryActionAgent,} from '../userMemory';const memoryActionRunner = vi.fn();@@ -341,6 +342,85 @@ describe('defineUserMemoryActionHandler', () => {});});+describe('runMemoryActionAgent memory switch', () => {+ const PLUGIN_QUERY_REACHED = new Error('plugin query reached');++ const createOptions = (input: { agentMemoryEnabled?: boolean; userMemoryEnabled?: boolean }) => {+ const pluginModel = { query: vi.fn().mockRejectedValue(PLUGIN_QUERY_REACHED) };+ const userModel = {+ getUserSettings: vi+ .fn()+ .mockResolvedValue(+ input.userMemoryEnabled === undefined+ ? undefined+ : { memory: { enabled: input.userMemoryEnabled } },+ ),+ };++ return {+ options: {+ agentService: {+ getAgentConfig: vi.fn().mockResolvedValue({+ chatConfig:+ input.agentMemoryEnabled === undefined+ ? {}+ : { memory: { enabled: input.agentMemoryEnabled } },+ model: 'gpt-test',+ provider: 'openai',+ }),+ },+ db: {} as never,+ pluginModel,+ userId: 'user-1',+ userModel,+ } as never,+ pluginModel,+ userModel,+ };+ };++ it('skips the memory writer when the user turned memory off', async () => {+ const { options, pluginModel } = createOptions({ userMemoryEnabled: false });++ await expect(+ runMemoryActionAgent({ agentId: 'agent-1', message: 'remember this' }, options),+ ).resolves.toEqual({+ detail: 'Memory is disabled for this agent or user.',+ status: 'skipped',+ });+ expect(pluginModel.query).not.toHaveBeenCalled();+ });++ it('skips the memory writer when the agent turned memory off', async () => {+ const { options, pluginModel, userModel } = createOptions({+ agentMemoryEnabled: false,+ userMemoryEnabled: true,+ });++ await expect(+ runMemoryActionAgent({ agentId: 'agent-1', message: 'remember this' }, options),+ ).resolves.toMatchObject({ status: 'skipped' });+ expect(userModel.getUserSettings).not.toHaveBeenCalled();+ expect(pluginModel.query).not.toHaveBeenCalled();+ });++ it('lets the agent-level switch override a disabled user setting', async () => {+ const { options } = createOptions({ agentMemoryEnabled: true, userMemoryEnabled: false });++ await expect(+ runMemoryActionAgent({ agentId: 'agent-1', message: 'remember this' }, options),+ ).rejects.toBe(PLUGIN_QUERY_REACHED);+ });++ it('keeps writing when memory has never been configured', async () => {+ const { options } = createOptions({});++ await expect(+ runMemoryActionAgent({ agentId: 'agent-1', message: 'remember this' }, options),+ ).rejects.toBe(PLUGIN_QUERY_REACHED);+ });+});+describe('buildUserMemoryActionAgentSignalMarker', () => {it('keeps the user message as trigger without using it as the receipt anchor', () => {const marker = buildUserMemoryActionAgentSignalMarker({@@ -443,6 +523,7 @@ describe('resolveMemoryActionTargetFromState', () => {id: 'mem_td3XirTeX4f7',memoryId: 'mem_8gISOK6BhxGP',memoryLayer: LayersEnum.Preference,+ operation: 'create',summary: 'Arvin Xu 希望助手在输出时每个段落/模块都写得更长、更展开。',title: '偏好更详细、更长的回答段落',type: 'memory',@@ -486,6 +567,7 @@ describe('resolveMemoryActionTargetFromState', () => {expect(target).toEqual({id: 'identity-existing',memoryLayer: LayersEnum.Identity,+ operation: 'update',summary: 'The user maintains Agent Signal memory receipt behavior.',title: 'Maintains Agent Signal receipts',type: 'memory',@@ -526,6 +608,7 @@ describe('resolveMemoryActionTargetFromState', () => {id: 'pref_persisted',memoryId: 'mem_persisted',memoryLayer: LayersEnum.Preference,+ operation: 'create',summary: 'Use persisted tool metadata for receipt targets.',title: 'Persisted preference title',type: 'memory',@@ -585,6 +668,7 @@ describe('resolveMemoryActionTargetFromState', () => {id: 'pref_confirmed',memoryId: 'mem_confirmed',memoryLayer: LayersEnum.Preference,+ operation: 'create',summary: 'Fallback details for a valid confirmed target.',title: 'Valid confirmed preference',type: 'memory',@@ -646,6 +730,7 @@ describe('resolveMemoryActionTargetFromState', () => {id: 'pref_confirmed',memoryId: 'mem_confirmed',memoryLayer: LayersEnum.Preference,+ operation: 'create',summary: 'The user prefers longer, more developed answers.',title: 'Confirmed preference title',type: 'memory',diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/memoryActionResult.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/memoryActionResult.tsindex 803bd081915..953ed8c0293 100644--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/memoryActionResult.ts+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/memoryActionResult.ts@@ -14,12 +14,18 @@ import { isRecord, pickTrimmedString } from '@lobechat/utils';* env-dependent transitive imports) into its graph.*/+/** Kind of durable write the memory tool performed; only `create` writes are undoable. */+export type MemoryActionOperation = 'create' | 'remove' | 'update';+export interface MemoryActionTarget {+ /** Layer-specific row id (e.g. `preferenceId`), used to open and undo the memory. */id?: string;memoryId?: string;memoryLayer?: LayersEnum;+ operation?: MemoryActionOperation;summary?: string;- title: string;+ /** The memory's own title. Absent when the write cannot be attributed to a titled tool call. */+ title?: string;type: 'memory';}@@ -44,17 +50,47 @@ const MEMORY_WRITE_TOOL_NAMES = new Set();const MEMORY_WRITE_API_NAME_SET = new Set<string>(MEMORY_WRITE_API_NAMES);-const MEMORY_WRITE_TARGET_BY_API_NAME: Record<string, { idKey: string; layer: LayersEnum }> = {- [MemoryApiName.addActivityMemory]: { idKey: 'activityId', layer: LayersEnum.Activity },- [MemoryApiName.addContextMemory]: { idKey: 'contextId', layer: LayersEnum.Context },- [MemoryApiName.addExperienceMemory]: { idKey: 'experienceId', layer: LayersEnum.Experience },- [MemoryApiName.addIdentityMemory]: { idKey: 'identityId', layer: LayersEnum.Identity },- [MemoryApiName.addPreferenceMemory]: { idKey: 'preferenceId', layer: LayersEnum.Preference },- [MemoryApiName.removeIdentityMemory]: { idKey: 'identityId', layer: LayersEnum.Identity },- [MemoryApiName.updateIdentityMemory]: { idKey: 'identityId', layer: LayersEnum.Identity },+const MEMORY_WRITE_TARGET_BY_API_NAME: Record<+ string,+ { idKey: string; layer: LayersEnum; operation: MemoryActionOperation }+> = {+ [MemoryApiName.addActivityMemory]: {+ idKey: 'activityId',+ layer: LayersEnum.Activity,+ operation: 'create',+ },+ [MemoryApiName.addContextMemory]: {+ idKey: 'contextId',+ layer: LayersEnum.Context,+ operation: 'create',+ },+ [MemoryApiName.addExperienceMemory]: {+ idKey: 'experienceId',+ layer: LayersEnum.Experience,+ operation: 'create',+ },+ [MemoryApiName.addIdentityMemory]: {+ idKey: 'identityId',+ layer: LayersEnum.Identity,+ operation: 'create',+ },+ [MemoryApiName.addPreferenceMemory]: {+ idKey: 'preferenceId',+ layer: LayersEnum.Preference,+ operation: 'create',+ },+ [MemoryApiName.removeIdentityMemory]: {+ idKey: 'identityId',+ layer: LayersEnum.Identity,+ operation: 'remove',+ },+ [MemoryApiName.updateIdentityMemory]: {+ idKey: 'identityId',+ layer: LayersEnum.Identity,+ operation: 'update',+ },};const TOOL_NAME_SEPARATOR = '____';-const DEFAULT_MEMORY_TARGET_TITLE = 'Memory saved';const getMemoryWriteApiNameFromToolName = (name: unknown) => {const toolName = getString(name);@@ -121,11 +157,24 @@ interface MemoryToolCallSnapshot {identifier?: string;}+/**+ * Tool payloads on a message, including the flattened `assistantGroup` shape the+ * runtime rebuilds `state.messages` into, where each block under `children`+ * carries its own `tools` (with the result inlined).+ */+const getPersistedTools = (message: Record<string, unknown>): Record<string, unknown>[] => {+ const blocks = Array.isArray(message.children) ? message.children.filter(isRecord) : [];++ return [message, ...blocks].flatMap((item) =>+ Array.isArray(item.tools) ? item.tools.filter(isRecord) : [],+ );+};+const getToolCallsFromMessage = (message: unknown): MemoryToolCallSnapshot[] => {if (!isRecord(message)) return [];const toolCalls: MemoryToolCallSnapshot[] = [];- const persistedTools = Array.isArray(message.tools) ? message.tools : [];+ const persistedTools = getPersistedTools(message);for (const tool of persistedTools) {if (!isRecord(tool)) continue;@@ -212,6 +261,18 @@ const getMemoryToolResultIds = (state: AgentState) => {const ids = getMemoryIdsFromToolMessage(message);if (callId && ids) resultIds.set(callId, ids);++ // Flattened groups inline each tool's result next to its call.+ if (!isRecord(message)) continue;+ for (const tool of getPersistedTools(message)) {+ const toolCallId = getString(tool.id);+ const result = isRecord(tool.result) ? tool.result : undefined;+ const inlineIds =+ result &&+ getMemoryIdsFromToolMessage({ content: result.content, pluginState: result.state });++ if (toolCallId && inlineIds) resultIds.set(toolCallId, inlineIds);+ }}return resultIds;@@ -252,22 +313,24 @@ const createTargetFromToolArguments = (return {...((id ?? memoryId) ? { id: id ?? memoryId } : {}),...(memoryId ? { memoryId } : {}),- ...(targetConfig ? { memoryLayer: targetConfig.layer } : {}),+ ...(targetConfig ? { memoryLayer: targetConfig.layer, operation: targetConfig.operation } : {}),...(summary ? { summary } : {}),title,type: 'memory',};};-export const resolveMemoryActionTargetFromState = (- state: AgentState,-): MemoryActionTarget | undefined => {+/**+ * Every confirmed memory write in the run, in call order. A writer may save+ * several memories (e.g. a context and a preference) from one piece of feedback;+ * each gets its own receipt.+ */+export const resolveMemoryActionTargetsFromState = (state: AgentState): MemoryActionTarget[] => {const resultIds = getMemoryToolResultIds(state);+ const targets: MemoryActionTarget[] = [];- for (const message of [...(state.messages ?? [])].reverse()) {- const toolCalls = getToolCallsFromMessage(message).reverse();-- for (const toolCall of toolCalls) {+ for (const message of state.messages ?? []) {+ for (const toolCall of getToolCallsFromMessage(message)) {if (!isMemoryWriteToolCall(toolCall)) continue;if (!toolCall.id) continue;@@ -278,16 +341,27 @@ export const resolveMemoryActionTargetFromState = (if (!args) continue;const target = createTargetFromToolArguments(args, toolCall, confirmedResultIds);- if (target) return target;+ if (target) targets.push(target);}}+ return targets;+};++export const resolveMemoryActionTargetFromState = (+ state: AgentState,+): MemoryActionTarget | undefined => {+ const targets = resolveMemoryActionTargetsFromState(state);+ if (targets.length > 0) return targets.at(-1);+const targetConfig = getSuccessfulMemoryWriteTargetConfig(state);if (!targetConfig) return;+ // No titled tool call to attribute: leave the title out so clients render their localized+ // "Memory saved" fallback instead of a server-side English string.return {memoryLayer: targetConfig.layer,- title: DEFAULT_MEMORY_TARGET_TITLE,+ operation: targetConfig.operation,type: 'memory',};};diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.tsindex 6f3660a9b83..69d73858e73 100644--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts@@ -14,8 +14,10 @@ import {import { RequestTrigger, ThreadType } from '@lobechat/types';import { nanoid } from '@lobechat/utils';+import { MessageModel } from '@/database/models/message';import { PluginModel } from '@/database/models/plugin';import { ThreadModel } from '@/database/models/thread';+import { UserModel } from '@/database/models/user';import type { LobeChatDatabase } from '@/database/type';import {InMemoryAgentStateManager,@@ -73,8 +75,11 @@ export interface UserMemoryActionHandlerOptions {sourceMessageId?: string;topicId?: string;}) => Promise<MemoryAgentActionResult>;+ messageModel?: Pick<MessageModel, 'create'>;pluginModel?: Pick<PluginModel, 'query'>;+ threadModel?: Pick<ThreadModel, 'create'>;userId: string;+ userModel?: Pick<UserModel, 'getUserSettings'>;workspaceId?: string;}@@ -127,9 +132,12 @@ export const buildUserMemoryActionAgentSignalMarker = ({...(triggerMessageId ? { triggerMessageId } : {}),});-const createInitialContext = (operationId: string): AgentRuntimeContext => {+const createInitialContext = (+ operationId: string,+ parentMessageId?: string,+): AgentRuntimeContext => {return {- payload: { message: [] },+ payload: { message: [], ...(parentMessageId ? { parentMessageId } : {}) },phase: 'user_input',session: {messageCount: 1,@@ -204,6 +212,25 @@ export const runMemoryActionAgent = async (const agentConfig = await agentService.getAgentConfig(input.agentId);const memoryLanguage = input.memoryLanguage ?? 'English';+ // Same precedence as chat (`AiAgentService.execAgent`): the agent-level memory+ // switch wins, otherwise the user-level setting. A user who turned memory off+ // must not get memories written in the background either.+ const agentMemoryEnabled = agentConfig?.chatConfig?.memory?.enabled;+ let memoryEnabled = agentMemoryEnabled;+ if (memoryEnabled === undefined) {+ const userModel = options.userModel ?? new UserModel(options.db, options.userId);+ const settings = await userModel.getUserSettings();+ const memorySettings = settings?.memory as { enabled?: boolean } | undefined;+ memoryEnabled = memorySettings?.enabled !== false;+ }++ if (!memoryEnabled) {+ return {+ detail: 'Memory is disabled for this agent or user.',+ status: 'skipped',+ };+ }+if (!agentConfig?.model || !agentConfig?.provider) {return {detail: 'Missing runnable agent config for memory action.',@@ -255,7 +282,6 @@ export const runMemoryActionAgent = async (const manifestMap = toolsEngine.getEnabledPluginManifests([MemoryIdentifier]);const operationId = `agent-signal-memory-${nanoid()}`;- const initialContext = createInitialContext(operationId);// Lazy-loaded on purpose: `AgentRuntimeService` pulls the model-runtime core// (eagerly touches server-only env at module init). This policy action sits on// the light agentSignal request path imported by aiAgent, so a static import@@ -269,7 +295,8 @@ export const runMemoryActionAgent = async (let threadId: string | undefined;if (input.topicId && input.sourceMessageId) {try {- const threadModel = new ThreadModel(options.db, options.userId, options.workspaceId);+ const threadModel =+ options.threadModel ?? new ThreadModel(options.db, options.userId, options.workspaceId);const thread = await threadModel.create({agentId: input.agentId,metadata: { operationId },@@ -284,15 +311,34 @@ export const runMemoryActionAgent = async (}}+ // Persist the writer prompt as the thread's user message. The runtime+ // rebuilds `state.messages` from the DB after a tool step, so an in-memory-only+ // seed would vanish and the next LLM call would start with an assistant+ // message — which strict providers reject ("messages parameter is illegal")+ // and every model would continue without its instructions or evidence.+ const seedContent = createAgentSignalMemoryWriterPrompt({ ...input, memoryLanguage });+ let seedMessage: { content: string; id?: string; role: 'user' } = {+ content: seedContent,+ role: 'user',+ };+ if (threadId && input.topicId) {+ const messageModel =+ options.messageModel ?? new MessageModel(options.db, options.userId, options.workspaceId);+ const seedRow = await messageModel.create({+ agentId: input.agentId,+ content: seedContent,+ role: 'user',+ threadId,+ topicId: input.topicId,+ });+ seedMessage = { ...seedMessage, id: seedRow.id };+ }+ const initialContext = createInitialContext(operationId, seedMessage.id);+const createParams = {agentConfig: memoryRuntimeAgentConfig,initialContext,- initialMessages: [- {- content: createAgentSignalMemoryWriterPrompt({ ...input, memoryLanguage }),- role: 'user',- },- ],+ initialMessages: [seedMessage],modelRuntimeConfig: {model: agentConfig.model,provider: agentConfig.provider,diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.tsindex a2c8ffe7470..84700927943 100644--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts@@ -14,6 +14,7 @@ import { z } from 'zod';import type { LobeChatDatabase } from '@/database/type';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import type { AgentSignalBudgetDecision } from '../../budget';import { classifySatisfaction, transitionToSignals } from '../../processors';import { defineSourceHandler } from '../../runtime/middleware';import type { ClassifierDiagnosticsService, SatisfactionClassifierService } from '../../services';@@ -75,6 +76,12 @@ export interface FeedbackSatisfactionJudgeAgentModelConfig {* Options for constructing the feedback satisfaction source handler.*/export interface CreateFeedbackSatisfactionJudgePolicyOptions {+ /**+ * Per-user daily cap checked before each classifier call.+ *+ * @default No cap. The server orchestrator wires the Redis-backed daily budget.+ */+ classifierBudget?: () => Promise<AgentSignalBudgetDecision>;/** Optional diagnostics sink for malformed structured classifier output. */classifierDiagnostics?: ClassifierDiagnosticsService;db?: LobeChatDatabase;@@ -225,6 +232,7 @@ export const createFeedbackSatisfactionJudgeProcessor = (};const result = await classifySatisfaction(source, ctx, {diagnostics: options.classifierDiagnostics,+ satisfactionBudget: options.classifierBudget,satisfactionClassifier: classifier,});diff --git a/apps/server/src/services/agentSignal/processors/__tests__/classifiers.test.ts b/apps/server/src/services/agentSignal/processors/__tests__/classifiers.test.tsindex 8ded18f077e..91611bef995 100644--- a/apps/server/src/services/agentSignal/processors/__tests__/classifiers.test.ts+++ b/apps/server/src/services/agentSignal/processors/__tests__/classifiers.test.ts@@ -5,7 +5,7 @@ import { z } from 'zod';import type { SignalFeedbackSatisfaction } from '../../policies/types';import { createRuntimeProcessorContext } from '../../runtime/context';-import { classifyDomain, classifySatisfaction } from '../classifiers';+import { classifyDomain, classifySatisfaction, NO_PRIOR_REPLY_STOP_REASON } from '../classifiers';const context = createRuntimeProcessorContext({backend: {@@ -394,4 +394,102 @@ describe('classifier processors', () => {}),).rejects.toThrow(error);});++ describe('satisfaction pre-filters', () => {+ const createPlainSource = (+ payload: Partial<SourceAgentUserMessage['payload']> = {},+ ): SourceAgentUserMessage => {+ const source = createUserMessageSource();++ return {+ ...source,+ payload: {+ agentId: 'agent_1',+ message: 'remember that I prefer pnpm',+ messageId: 'msg:source_1',+ topicId: 'topic_1',+ ...payload,+ },+ };+ };+ const classifierOutput = {+ confidence: 0.9,+ evidence: [],+ reason: 'explicit preference',+ result: 'satisfied' as const,+ };++ /**+ * @example+ * The first message of a conversation has no earlier reply, so the classifier is not called.+ */+ it('skips the classifier for a conversation-root message', async () => {+ const classify = vi.fn().mockResolvedValue(classifierOutput);+ const satisfactionBudget = vi.fn();++ const result = await classifySatisfaction(+ createPlainSource({ isConversationRoot: true }),+ context,+ { satisfactionBudget, satisfactionClassifier: { classify } },+ );++ expect(result).toMatchObject({ reason: NO_PRIOR_REPLY_STOP_REASON, type: 'stop' });+ expect(classify).not.toHaveBeenCalled();+ expect(satisfactionBudget).not.toHaveBeenCalled();+ });++ /**+ * @example+ * "remember that I..." after an assistant reply still reaches the classifier.+ */+ it('classifies explicit memory requests that follow an earlier reply', async () => {+ const classify = vi.fn().mockResolvedValue(classifierOutput);++ const result = await classifySatisfaction(createPlainSource(), context, {+ satisfactionClassifier: { classify },+ });++ expect(classify).toHaveBeenCalledTimes(1);+ expect(result.type).toBe('continue');+ });++ it('classifies a conversation-root message that carries explicit client intents', async () => {+ const classify = vi.fn().mockResolvedValue(classifierOutput);++ await classifySatisfaction(+ createPlainSource({ intents: ['memory'], isConversationRoot: true }),+ context,+ { satisfactionClassifier: { classify } },+ );++ expect(classify).toHaveBeenCalledTimes(1);+ });++ /**+ * @example+ * Once the daily feedback-classifier budget is spent, the classifier is not called.+ */+ it('skips the classifier when the daily budget denies the call', async () => {+ const classify = vi.fn().mockResolvedValue(classifierOutput);+ const satisfactionBudget = vi.fn().mockResolvedValue({+ allowed: false,+ count: 201,+ kind: 'feedback-classifier',+ limit: 200,+ reason: 'exceeded',+ });++ const result = await classifySatisfaction(createPlainSource(), context, {+ satisfactionBudget,+ satisfactionClassifier: { classify },+ });++ expect(result).toMatchObject({+ reason: 'Daily Agent Signal feedback-classifier budget exceeded (200/day).',+ type: 'stop',+ });+ expect(satisfactionBudget).toHaveBeenCalledTimes(1);+ expect(classify).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/server/src/services/agentSignal/processors/classifiers.ts b/apps/server/src/services/agentSignal/processors/classifiers.tsindex 137a3c5f78f..6a1e60a1e23 100644--- a/apps/server/src/services/agentSignal/processors/classifiers.ts+++ b/apps/server/src/services/agentSignal/processors/classifiers.ts@@ -1,8 +1,11 @@import {type AgentSignalSourceVariants,isAgentUserMessageSource,+ type SourceAgentUserMessage,} from '@lobechat/agent-signal/source';+import type { AgentSignalBudgetDecision } from '../budget';+import { describeBudgetDenial } from '../budget';import {AGENT_SIGNAL_POLICY_SIGNAL_TYPES,type AgentSignalFeedbackDomainConflictPolicy,@@ -35,12 +38,33 @@ export interface ClassifierProcessorServices {* Optional domain classifier for routing non-neutral satisfaction signals.*/domainClassifier?: DomainClassifierService;+ /**+ * Optional per-user budget gate taken right before each satisfaction classifier call.+ * A denied decision skips the classifier for this source.+ */+ satisfactionBudget?: () => Promise<AgentSignalBudgetDecision>;/*** Optional satisfaction classifier for classifying `agent.user.message` sources.*/satisfactionClassifier?: SatisfactionClassifierService;}+/** Stop reason for user messages that cannot be feedback on an earlier reply. */+export const NO_PRIOR_REPLY_STOP_REASON = 'no prior reply to give feedback on';++/**+ * Decides whether a user message can be skipped before any model call.+ *+ * Only a message the producer marked as the conversation root qualifies: with no earlier+ * message in its topic or thread there is no reply to be (dis)satisfied with. Messages that+ * carry explicit client intent hints still go to the classifier.+ */+const cannotBeFeedback = (payload: SourceAgentUserMessage['payload']) =>+ payload.isConversationRoot === true &&+ !payload.intents?.length &&+ !payload.memoryPayload &&+ !payload.documentPayload;+/*** Feedback-domain signal variants emitted by classifier processors.*/@@ -299,6 +323,17 @@ export const classifySatisfaction = async (return stop('satisfaction classifier unavailable');}+ // Cheap checks first: neither of these spends the user's provider credentials.+ if (cannotBeFeedback(source.payload)) {+ return stop(NO_PRIOR_REPLY_STOP_REASON);+ }++ if (services.satisfactionBudget) {+ const decision = await services.satisfactionBudget();++ if (!decision.allowed) return stop(describeBudgetDenial(decision));+ }+const message = source.payload.message.trim();let payload: Awaited<ReturnType<SatisfactionClassifierService['classify']>>;diff --git a/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.ts b/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.tsindex 4e145ab9d90..ed9820d10c6 100644--- a/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.ts+++ b/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.ts@@ -1,3 +1,4 @@+import { LayersEnum } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -22,6 +23,11 @@ const mocks = vi.hoisted(() => ({}),updateDocument: vi.fn<(id: string, params: Record<string, unknown>) => Promise<unknown>>(),},+ memoryModels: {+ activityDelete: vi.fn<(id: string) => Promise<{ success: boolean }>>(),+ preferenceDelete: vi.fn<(id: string) => Promise<{ success: boolean }>>(),+ preferenceUserIds: [] as string[],+ },receiptService: {getAgentSignalReceipt:vi.fn<(receiptId: string) => Promise<Record<string, unknown> | undefined>>(),@@ -36,6 +42,19 @@ vi.mock('@/server/services/document', () => ({}),}));+vi.mock('@/database/models/userMemory', () => ({+ UserMemoryActivityModel: vi.fn(function () {+ return { delete: mocks.memoryModels.activityDelete };+ }),+ UserMemoryContextModel: vi.fn(),+ UserMemoryExperienceModel: vi.fn(),+ UserMemoryIdentityModel: vi.fn(),+ UserMemoryPreferenceModel: vi.fn(function (_db: unknown, userId: string) {+ mocks.memoryModels.preferenceUserIds.push(userId);+ return { delete: mocks.memoryModels.preferenceDelete };+ }),+}));+vi.mock('@/server/services/agentSignal/services/receiptService', () => ({getAgentSignalReceipt: mocks.receiptService.getAgentSignalReceipt,updateAgentSignalReceiptMetadata: mocks.receiptService.updateAgentSignalReceiptMetadata,@@ -58,8 +77,11 @@ describe('rollbackAgentSignalReceipt', () => {) {return fn('server:lock-owner');});+ mocks.memoryModels.preferenceUserIds.length = 0;mocks.receiptService.getAgentSignalReceipt.mockResolvedValue({id: 'receipt-1',+ kind: 'skill',+ userId: 'user-1',metadata: {documentId: 'doc-1',expectedCurrentDocumentUpdatedAt: '2026-06-29T00:00:00.000Z',@@ -189,4 +211,184 @@ describe('rollbackAgentSignalReceipt', () => {expect.objectContaining({ rollbackStatus: 'conflict' }),);});++ describe('memory receipts', () => {+ const memoryReceipt = (overrides: Record<string, unknown> = {}) => ({+ id: 'receipt-memory-1',+ kind: 'memory',+ metadata: { rollbackStatus: 'available', sourceType: 'agent.execution.completed' },+ target: {+ id: 'preference-1',+ memoryId: 'memory-1',+ memoryLayer: LayersEnum.Preference,+ operation: 'create',+ summary: 'Prefers decision-first reviews',+ title: 'Decision-first review preference',+ type: 'memory',+ },+ userId: 'user-1',+ ...overrides,+ });+ const memoryInput = { receiptId: 'receipt-memory-1' };++ /**+ * @example+ * Undo on a created memory deletes it through the caller-scoped layer model and marks the receipt.+ */+ it('deletes the created memory and marks the receipt rolled back', async () => {+ mocks.receiptService.getAgentSignalReceipt.mockResolvedValue(memoryReceipt());+ mocks.memoryModels.preferenceDelete.mockResolvedValue({ success: true });++ const result = await rollbackAgentSignalReceipt(memoryInput, { db, userId: 'user-1' });++ expect(result).toEqual({ receiptId: 'receipt-memory-1', status: 'rolled_back' });+ expect(mocks.memoryModels.preferenceUserIds).toEqual(['user-1']);+ expect(mocks.memoryModels.preferenceDelete).toHaveBeenCalledWith('preference-1');+ expect(mocks.receiptService.updateAgentSignalReceiptMetadata).toHaveBeenCalledWith(+ 'receipt-memory-1',+ expect.objectContaining({ rollbackStatus: 'rolled_back' }),+ );+ expect(mocks.documentService.runWithDocumentLock).not.toHaveBeenCalled();+ });++ /**+ * @example+ * Activity memories route to their own layer model.+ */+ it('deletes through the layer model that owns the memory', async () => {+ mocks.receiptService.getAgentSignalReceipt.mockResolvedValue(+ memoryReceipt({+ target: {+ id: 'activity-1',+ memoryLayer: LayersEnum.Activity,+ operation: 'create',+ title: 'Gym session',+ type: 'memory',+ },+ }),+ );+ mocks.memoryModels.activityDelete.mockResolvedValue({ success: true });++ const result = await rollbackAgentSignalReceipt(memoryInput, { db, userId: 'user-1' });++ expect(result.status).toBe('rolled_back');+ expect(mocks.memoryModels.activityDelete).toHaveBeenCalledWith('activity-1');+ expect(mocks.memoryModels.preferenceDelete).not.toHaveBeenCalled();+ });++ /**+ * @example+ * Another user's receipt id reads as missing and nothing is deleted.+ */+ it('refuses to undo a receipt owned by another user', async () => {+ mocks.receiptService.getAgentSignalReceipt.mockResolvedValue(+ memoryReceipt({ userId: 'user-2' }),+ );++ const result = await rollbackAgentSignalReceipt(memoryInput, { db, userId: 'user-1' });++ expect(result).toEqual({+ reason: 'Receipt not found',+ receiptId: 'receipt-memory-1',+ status: 'not_found',+ });+ expect(mocks.memoryModels.preferenceDelete).not.toHaveBeenCalled();+ expect(mocks.receiptService.updateAgentSignalReceiptMetadata).not.toHaveBeenCalled();+ });++ /**+ * @example+ * Repeating undo after success is a no-op that reports the settled state.+ */+ it('is idempotent once the receipt is rolled back', async () => {+ mocks.receiptService.getAgentSignalReceipt.mockResolvedValue(+ memoryReceipt({ metadata: { rollbackStatus: 'rolled_back' } }),+ );++ const result = await rollbackAgentSignalReceipt(memoryInput, { db, userId: 'user-1' });++ expect(result).toEqual({ receiptId: 'receipt-memory-1', status: 'already_rolled_back' });+ expect(mocks.memoryModels.preferenceDelete).not.toHaveBeenCalled();+ expect(mocks.receiptService.updateAgentSignalReceiptMetadata).not.toHaveBeenCalled();+ });++ /**+ * @example+ * A concurrent duplicate undo that finds the memory gone does not overwrite the winner's status.+ */+ it('reports already_rolled_back when a concurrent undo deleted the memory first', async () => {+ mocks.receiptService.getAgentSignalReceipt+ .mockResolvedValueOnce(memoryReceipt())+ .mockResolvedValueOnce(memoryReceipt({ metadata: { rollbackStatus: 'rolled_back' } }));+ mocks.memoryModels.preferenceDelete.mockResolvedValue({ success: false });++ const result = await rollbackAgentSignalReceipt(memoryInput, { db, userId: 'user-1' });++ expect(result.status).toBe('already_rolled_back');+ expect(mocks.receiptService.updateAgentSignalReceiptMetadata).not.toHaveBeenCalled();+ });++ /**+ * @example+ * A memory the user already deleted elsewhere cannot be undone and the receipt stops offering it.+ */+ it('returns not_found when the memory no longer exists', async () => {+ mocks.receiptService.getAgentSignalReceipt.mockResolvedValue(memoryReceipt());+ mocks.memoryModels.preferenceDelete.mockResolvedValue({ success: false });++ const result = await rollbackAgentSignalReceipt(memoryInput, { db, userId: 'user-1' });++ expect(result).toEqual({+ reason: 'Memory no longer exists',+ receiptId: 'receipt-memory-1',+ status: 'not_found',+ });+ expect(mocks.receiptService.updateAgentSignalReceiptMetadata).toHaveBeenCalledWith(+ 'receipt-memory-1',+ expect.objectContaining({ rollbackStatus: 'not_found' }),+ );+ });++ /**+ * @example+ * Updates to an existing memory carry no prior snapshot, so they are not undoable.+ */+ it('does not undo memory updates', async () => {+ mocks.receiptService.getAgentSignalReceipt.mockResolvedValue(+ memoryReceipt({+ metadata: { sourceType: 'agent.execution.completed' },+ target: {+ id: 'identity-1',+ memoryLayer: LayersEnum.Identity,+ operation: 'update',+ title: 'Senior engineer',+ type: 'memory',+ },+ }),+ );++ const result = await rollbackAgentSignalReceipt(memoryInput, { db, userId: 'user-1' });++ expect(result.status).toBe('unsupported');+ expect(mocks.memoryModels.preferenceDelete).not.toHaveBeenCalled();+ });++ /**+ * @example+ * A delete failure surfaces the reason so the client can show it.+ */+ it('returns failed with the error reason when deletion throws', async () => {+ mocks.receiptService.getAgentSignalReceipt.mockResolvedValue(memoryReceipt());+ mocks.memoryModels.preferenceDelete.mockRejectedValue(new Error('database unavailable'));+ vi.spyOn(console, 'error').mockImplementation(() => {});++ const result = await rollbackAgentSignalReceipt(memoryInput, { db, userId: 'user-1' });++ expect(result).toEqual({+ reason: 'database unavailable',+ receiptId: 'receipt-memory-1',+ status: 'failed',+ });+ });+ });});diff --git a/apps/server/src/services/agentSignal/services/__tests__/selfFeedbackIntent.test.ts b/apps/server/src/services/agentSignal/services/__tests__/selfFeedbackIntent.test.tsindex 70c94b657e0..6044d516e2d 100644--- a/apps/server/src/services/agentSignal/services/__tests__/selfFeedbackIntent.test.ts+++ b/apps/server/src/services/agentSignal/services/__tests__/selfFeedbackIntent.test.ts@@ -3,7 +3,10 @@ import { describe, expect, it, vi } from 'vitest';import type { AgentSignalSourceEventInput } from '@/server/services/agentSignal/emitter';import type { SelfFeedbackIntentAction, SelfFeedbackIntentKind } from '../selfFeedbackIntent';-import { createSelfFeedbackIntentService } from '../selfFeedbackIntent';+import {+ createInMemoryDeclarationLimiter,+ createSelfFeedbackIntentService,+} from '../selfFeedbackIntent';const createStrongIntentInput = () => ({action: 'refine' as const,@@ -342,4 +345,67 @@ describe('selfFeedbackIntent', () => {});expect(enqueueSource).not.toHaveBeenCalled();});++ /**+ * @example+ * Two service instances (two server processes) sharing one limiter enforce one limit.+ */+ it('enforces the declaration limit across service instances that share a limiter', async () => {+ const enqueueSource = createEnqueueSource();+ const declarationLimiter = createInMemoryDeclarationLimiter();+ const processA = createSelfFeedbackIntentService({+ declarationLimiter,+ enqueueSource,+ nextToolCallId: () => 'unused',+ });+ const processB = createSelfFeedbackIntentService({+ declarationLimiter,+ enqueueSource,+ nextToolCallId: () => 'unused',+ });+ const declare = (service: typeof processA, toolCallId: string) =>+ service.declareIntent({+ agentId: 'agent-1',+ input: createStrongIntentInput(),+ toolCallId,+ topicId: 'topic-shared',+ userId: 'user-1',+ });++ await declare(processA, 'call-1');+ await declare(processB, 'call-2');+ await declare(processA, 'call-3');++ await expect(declare(processB, 'call-4')).resolves.toMatchObject({+ accepted: false,+ reason: 'rate_limited',+ });+ expect(enqueueSource).toHaveBeenCalledTimes(3);+ });++ /**+ * @example+ * A declaration that failed to enqueue gives its slot back.+ */+ it('releases the declaration slot when enqueueing fails', async () => {+ const enqueueSource = createEnqueueSource();+ enqueueSource.mockRejectedValueOnce(new Error('queue down'));+ const service = createSelfFeedbackIntentService({+ enqueueSource,+ nextToolCallId: () => 'unused',+ });+ const declare = (toolCallId: string) =>+ service.declareIntent({+ agentId: 'agent-1',+ input: createStrongIntentInput(),+ toolCallId,+ topicId: 'topic-release',+ userId: 'user-1',+ });++ await expect(declare('call-failed')).rejects.toThrow('queue down');+ for (const toolCallId of ['call-1', 'call-2', 'call-3']) {+ await expect(declare(toolCallId)).resolves.toMatchObject({ accepted: true });+ }+ });});diff --git a/apps/server/src/services/agentSignal/services/receiptRollbackService.ts b/apps/server/src/services/agentSignal/services/receiptRollbackService.tsindex 85e33ae50af..c9f211b78cf 100644--- a/apps/server/src/services/agentSignal/services/receiptRollbackService.ts+++ b/apps/server/src/services/agentSignal/services/receiptRollbackService.ts@@ -1,24 +1,38 @@+import { LayersEnum } from '@lobechat/types';import { TRPCError } from '@trpc/server';+import {+ UserMemoryActivityModel,+ UserMemoryContextModel,+ UserMemoryExperienceModel,+ UserMemoryIdentityModel,+ UserMemoryPreferenceModel,+} from '@/database/models/userMemory';import type { LobeChatDatabase } from '@/database/type';import {+ type AgentSignalReceipt,getAgentSignalReceipt,updateAgentSignalReceiptMetadata,} from '@/server/services/agentSignal/services/receiptService';import { DocumentService } from '@/server/services/document';-type RollbackTerminalStatus = 'conflict' | 'failed' | 'not_found' | 'rolled_back';+type RollbackPersistedStatus = 'conflict' | 'failed' | 'not_found' | 'rolled_back' | 'unsupported';+type RollbackTerminalStatus = RollbackPersistedStatus | 'already_rolled_back';/**- * Input required to rollback one skill-refine receipt.+ * Input required to rollback one Agent Signal receipt.+ *+ * Skill receipts restore a document history snapshot; memory receipts delete the memory the run+ * created. Rollback targets are always re-read from the persisted receipt, so the optional ids+ * here are only echoed back for the client's bookkeeping.*/export interface RollbackAgentSignalReceiptInput {/** Optional managed-skill binding id kept for receipt/UI bookkeeping. */agentDocumentId?: string;- /** Backing document id that should be restored. */- documentId: string;- /** Pre-mutation history id captured before the refine write. */- historyId: string;+ /** Backing document id that should be restored (skill receipts). */+ documentId?: string;+ /** Pre-mutation history id captured before the refine write (skill receipts). */+ historyId?: string;/** Receipt whose metadata should be updated with the terminal rollback status. */receiptId: string;}@@ -27,9 +41,9 @@ export interface RollbackAgentSignalReceiptInput {* Runtime context for Agent Signal receipt rollback.*/export interface AgentSignalReceiptRollbackContext {- /** Database handle used by the document service. */+ /** Database handle used by the document / memory models. */db: LobeChatDatabase;- /** Owner user id for scoped document access. */+ /** Owner user id; the receipt and its target must belong to this user. */userId: string;/** Optional workspace scope for collaborative documents. */workspaceId?: string;@@ -41,10 +55,10 @@ export interface AgentSignalReceiptRollbackContext {export interface AgentSignalReceiptRollbackResult {/** Optional managed-skill binding id echoed back to the client. */agentDocumentId?: string;- /** Backing document id that was requested. */- documentId: string;- /** Requested history id. */- historyId: string;+ /** Backing document id that was requested (skill receipts). */+ documentId?: string;+ /** Requested history id (skill receipts). */+ historyId?: string;/** Human-readable reason for non-success terminal states. */reason?: string;/** Requested receipt id. */@@ -59,8 +73,8 @@ const toResult = (reason?: string,): AgentSignalReceiptRollbackResult => ({...(input.agentDocumentId ? { agentDocumentId: input.agentDocumentId } : {}),- documentId: input.documentId,- historyId: input.historyId,+ ...(input.documentId ? { documentId: input.documentId } : {}),+ ...(input.historyId ? { historyId: input.historyId } : {}),receiptId: input.receiptId,...(reason ? { reason } : {}),status,@@ -74,7 +88,7 @@ const toIsoString = (value: Date | string | undefined) => {const persistRollbackStatus = async (input: RollbackAgentSignalReceiptInput,- status: RollbackTerminalStatus,+ status: RollbackPersistedStatus,) => {try {const receipt = await getAgentSignalReceipt(input.receiptId);@@ -94,13 +108,102 @@ const persistRollbackStatus = async (};/**- * Restores a skill-refine receipt from the existing document history timeline.+ * Deletes one layer-specific memory row (and its base memory) owned by the user.+ *+ * Returns `false` when the row no longer exists for this user.+ */+const deleteMemoryByLayer = async (+ db: LobeChatDatabase,+ userId: string,+ layer: LayersEnum,+ id: string,+): Promise<boolean> => {+ switch (layer) {+ case LayersEnum.Activity: {+ return (await new UserMemoryActivityModel(db, userId).delete(id)).success;+ }+ case LayersEnum.Context: {+ return (await new UserMemoryContextModel(db, userId).delete(id)).success;+ }+ case LayersEnum.Experience: {+ return (await new UserMemoryExperienceModel(db, userId).delete(id)).success;+ }+ case LayersEnum.Identity: {+ return (await new UserMemoryIdentityModel(db, userId).delete(id)).success;+ }+ case LayersEnum.Preference: {+ return (await new UserMemoryPreferenceModel(db, userId).delete(id)).success;+ }+ default: {+ return false;+ }+ }+};++/**+ * Undoes a memory receipt by deleting the memory the self-iteration run created.+ *+ * Only `create` writes are undoable: update / remove writes carry no prior snapshot, so they+ * resolve to `unsupported`. A concurrent duplicate undo that loses the race reports+ * `already_rolled_back` instead of overwriting the winner's status.+ */+const rollbackMemoryReceipt = async (+ receipt: AgentSignalReceipt,+ input: RollbackAgentSignalReceiptInput,+ context: AgentSignalReceiptRollbackContext,+): Promise<AgentSignalReceiptRollbackResult> => {+ const target = receipt.target;++ if (+ receipt.metadata?.rollbackStatus !== 'available' ||+ target?.type !== 'memory' ||+ target.operation !== 'create' ||+ !target.id ||+ !target.memoryLayer+ ) {+ return toResult(input, 'unsupported', 'This memory change cannot be undone');+ }++ try {+ const deleted = await deleteMemoryByLayer(+ context.db,+ context.userId,+ target.memoryLayer,+ target.id,+ );++ if (!deleted) {+ const latest = await getAgentSignalReceipt(input.receiptId);+ if (latest?.metadata?.rollbackStatus === 'rolled_back') {+ return toResult(input, 'already_rolled_back');+ }++ await persistRollbackStatus(input, 'not_found');+ return toResult(input, 'not_found', 'Memory no longer exists');+ }++ await persistRollbackStatus(input, 'rolled_back');+ return toResult(input, 'rolled_back');+ } catch (error) {+ console.error('[AgentSignal] Failed to undo memory receipt:', {+ error,+ receiptId: input.receiptId,+ });+ await persistRollbackStatus(input, 'failed');+ return toResult(input, 'failed', error instanceof Error ? error.message : 'Undo failed');+ }+};++/**+ * Undoes one Agent Signal receipt owned by the caller.** Use when:- * - A self-iteration receipt exposes `documentId` + `historyId` for undo.+ * - A skill receipt exposes `documentId` + `historyId`: restores the document history snapshot.+ * - A memory receipt records a `create` write: deletes the created memory.** Expects:- * - The target history row belongs to the same backing document.+ * - The receipt belongs to `context.userId`; other users' receipts read as `not_found`.+ * - Repeated calls are safe: a receipt already rolled back returns `already_rolled_back`.** Returns:* - One stable terminal rollback status for the receipt UI.@@ -109,13 +212,22 @@ export const rollbackAgentSignalReceipt = async (input: RollbackAgentSignalReceiptInput,context: AgentSignalReceiptRollbackContext,): Promise<AgentSignalReceiptRollbackResult> => {- const documentService = new DocumentService(context.db, context.userId, context.workspaceId);const receipt = await getAgentSignalReceipt(input.receiptId);- if (!receipt) {+ // A receipt owned by someone else reads as missing so ids cannot be probed across users.+ if (!receipt || receipt.userId !== context.userId) {return toResult(input, 'not_found', 'Receipt not found');}+ if (receipt.metadata?.rollbackStatus === 'rolled_back') {+ return toResult(input, 'already_rolled_back');+ }++ if (receipt.kind === 'memory') {+ return rollbackMemoryReceipt(receipt, input, context);+ }++ const documentService = new DocumentService(context.db, context.userId, context.workspaceId);const expectedCurrentDocumentUpdatedAt = receipt.metadata?.expectedCurrentDocumentUpdatedAt;const resolvedInput: RollbackAgentSignalReceiptInput = {...input,@@ -126,64 +238,64 @@ export const rollbackAgentSignalReceipt = async (...(receipt.metadata?.historyId ? { historyId: receipt.metadata.historyId } : {}),};+ const { documentId, historyId } = resolvedInput;++ if (!documentId || !historyId) {+ return toResult(resolvedInput, 'unsupported', 'Receipt has no document history to restore');+ }+if (!expectedCurrentDocumentUpdatedAt) {await persistRollbackStatus(resolvedInput, 'conflict');return toResult(resolvedInput, 'conflict', 'Receipt is missing the current document marker');}try {- return await documentService.runWithDocumentLock(- resolvedInput.documentId,- async (lockOwnerId) => {- const current = await documentService.getDocumentById(resolvedInput.documentId);- if (!current) {- await persistRollbackStatus(resolvedInput, 'not_found');- return toResult(resolvedInput, 'not_found');- }+ return await documentService.runWithDocumentLock(documentId, async (lockOwnerId) => {+ const current = await documentService.getDocumentById(documentId);+ if (!current) {+ await persistRollbackStatus(resolvedInput, 'not_found');+ return toResult(resolvedInput, 'not_found');+ }- if (toIsoString(current.updatedAt) !== expectedCurrentDocumentUpdatedAt) {- await persistRollbackStatus(resolvedInput, 'conflict');- return toResult(- resolvedInput,- 'conflict',- 'Document changed since this receipt was created',- );- }+ if (toIsoString(current.updatedAt) !== expectedCurrentDocumentUpdatedAt) {+ await persistRollbackStatus(resolvedInput, 'conflict');+ return toResult(+ resolvedInput,+ 'conflict',+ 'Document changed since this receipt was created',+ );+ }- const history = await (async () => {- try {- return await documentService.getDocumentHistoryItem({- documentId: resolvedInput.documentId,- historyId: resolvedInput.historyId,- });- } catch (error) {- if (- error instanceof Error &&- error.message.startsWith('Document history item not found:')- ) {- return undefined;- }-- throw error;+ const history = await (async () => {+ try {+ return await documentService.getDocumentHistoryItem({ documentId, historyId });+ } catch (error) {+ if (+ error instanceof Error &&+ error.message.startsWith('Document history item not found:')+ ) {+ return undefined;}- })();- if (!history?.editorData) {- await persistRollbackStatus(resolvedInput, 'not_found');- return toResult(resolvedInput, 'not_found', 'Document history not found');+ throw error;}+ })();- await documentService.updateDocument(resolvedInput.documentId, {- editorData: history.editorData,- ...(lockOwnerId ? { lockOwnerId } : {}),- restoreFromHistoryId: history.id,- saveSource: 'restore',- });+ if (!history?.editorData) {+ await persistRollbackStatus(resolvedInput, 'not_found');+ return toResult(resolvedInput, 'not_found', 'Document history not found');+ }- await persistRollbackStatus(resolvedInput, 'rolled_back');- return toResult(resolvedInput, 'rolled_back');- },- );+ await documentService.updateDocument(documentId, {+ editorData: history.editorData,+ ...(lockOwnerId ? { lockOwnerId } : {}),+ restoreFromHistoryId: history.id,+ saveSource: 'restore',+ });++ await persistRollbackStatus(resolvedInput, 'rolled_back');+ return toResult(resolvedInput, 'rolled_back');+ });} catch (error) {if (error instanceof TRPCError && error.code === 'CONFLICT') {await persistRollbackStatus(resolvedInput, 'conflict');diff --git a/apps/server/src/services/agentSignal/services/receiptService.ts b/apps/server/src/services/agentSignal/services/receiptService.tsindex 454376305b7..ad2d8f154c3 100644--- a/apps/server/src/services/agentSignal/services/receiptService.ts+++ b/apps/server/src/services/agentSignal/services/receiptService.ts@@ -108,10 +108,15 @@ export interface AgentSignalReceipt {memoryId?: string;/** User memory layer used to route memory receipts to their detail page. */memoryLayer?: LayersEnum;+ /** Memory write kind; only `create` memory receipts can be undone. */+ operation?: 'create' | 'remove' | 'update';/** Short summary captured at write time. */summary?: string;- /** Human-readable resource title captured at write time. */- title: string;+ /**+ * Human-readable resource title captured at write time. Absent when the write had no+ * attributable title; clients then render a localized fallback by receipt kind.+ */+ title?: string;/** User-facing resource domain. */type: 'memory' | 'skill';};diff --git a/apps/server/src/services/agentSignal/services/selfFeedbackIntent.ts b/apps/server/src/services/agentSignal/services/selfFeedbackIntent.tsindex d4320b22f0c..d29d5b92a0f 100644--- a/apps/server/src/services/agentSignal/services/selfFeedbackIntent.ts+++ b/apps/server/src/services/agentSignal/services/selfFeedbackIntent.ts@@ -13,7 +13,9 @@ import {} from '@lobechat/builtin-tool-self-iteration';import type { AgentSignalSourceEventInput } from '@/server/services/agentSignal/emitter';+import { redisService } from '@/server/services/redis';+import { AGENT_SIGNAL_DEFAULTS } from '../constants';import { buildSelfFeedbackIntentSourceId } from './selfIteration/types';export type {@@ -31,6 +33,73 @@ type MaybePromise<TValue> = TValue | Promise<TValue>;export type SelfFeedbackIntentSourceEventInput =AgentSignalSourceEventInput<'agent.self_feedback_intent.declared'>;+/**+ * Counts accepted declarations per scope so a fast-looping agent cannot flood the queue.+ */+export interface SelfFeedbackIntentDeclarationLimiter {+ /**+ * Takes one declaration slot for the scope.+ *+ * Returns:+ * - `true` when the scope is still within `limit`, otherwise `false`+ */+ acquire: (scopeKey: string, limit: number) => Promise<boolean>;+ /** Returns a slot taken by `acquire` when the declaration was not enqueued. */+ release: (scopeKey: string) => Promise<void>;+}++/**+ * Creates a process-local declaration limiter.+ *+ * Use when:+ * - Tests or single-process tools need the declaration limit without Redis+ */+export const createInMemoryDeclarationLimiter = (): SelfFeedbackIntentDeclarationLimiter => {+ const counts = new Map<string, number>();++ return {+ acquire: async (scopeKey, limit) => {+ const next = (counts.get(scopeKey) ?? 0) + 1;+ counts.set(scopeKey, next);++ return next <= limit;+ },+ release: async (scopeKey) => {+ counts.set(scopeKey, Math.max(0, (counts.get(scopeKey) ?? 0) - 1));+ },+ };+};++/**+ * Creates the Redis-backed declaration limiter shared by every server process.+ *+ * Use when:+ * - The declaration tool runs on serverless instances that do not share memory+ *+ * Returns:+ * - A limiter that fails closed (rejects) when Redis is missing or errors, because each+ * accepted declaration can spawn a background run billed to the user+ */+export const createRedisDeclarationLimiter = (): SelfFeedbackIntentDeclarationLimiter => ({+ acquire: async (scopeKey, limit) => {+ try {+ const count = await redisService.agentSignal.takeDeclarationSlot(scopeKey);++ return count !== undefined && count <= limit;+ } catch (error) {+ console.error('[AgentSignal] Failed to read self-feedback intent limit:', error);+ return false;+ }+ },+ release: async (scopeKey) => {+ try {+ await redisService.agentSignal.releaseDeclarationSlot(scopeKey);+ } catch (error) {+ console.error('[AgentSignal] Failed to release self-feedback intent slot:', error);+ }+ },+});+/** Dependencies used by the pure self-feedback intent declaration service. */export interface SelfFeedbackIntentServiceDependencies {/**@@ -46,6 +115,12 @@ export interface SelfFeedbackIntentServiceDependencies {* @default Allows enqueueing.*/canEnqueue?: (input: SelfFeedbackIntentSourceEventInput) => MaybePromise<boolean>;+ /**+ * Per-scope declaration limiter.+ *+ * @default A process-local limiter. Production wiring passes the Redis-backed limiter.+ */+ declarationLimiter?: SelfFeedbackIntentDeclarationLimiter;/** Enqueues one self-feedback intent source event. */enqueueSource: (input: SelfFeedbackIntentSourceEventInput) => Promise<unknown>;/** Creates a stable tool-call id when the caller did not provide one. */@@ -73,7 +148,8 @@ export interface SelfFeedbackIntentService {) => Promise<DeclareSelfFeedbackIntentResult>;}-const DECLARATION_LIMIT_PER_SCOPE = 3;+const DECLARATION_LIMIT_PER_SCOPE =+ AGENT_SIGNAL_DEFAULTS.selfFeedbackIntentDeclarationLimitPerScope;const STRONG_CONFIDENCE_THRESHOLD = 0.75;const validActions = new Set<SelfFeedbackIntentAction>(SELF_FEEDBACK_INTENT_ACTIONS);@@ -114,7 +190,7 @@ const isValidConfidence = (confidence: number) =>** Expects:* - `enqueueSource` owns durable dedupe and async execution- * - The service instance owns only in-memory fast-loop rate limiting+ * - `declarationLimiter` owns fast-loop rate limiting (in-memory unless injected)** Returns:* - A service that emits accepted declarations and never mutates memory or skill resources@@ -122,7 +198,7 @@ const isValidConfidence = (confidence: number) =>export const createSelfFeedbackIntentService = (deps: SelfFeedbackIntentServiceDependencies,): SelfFeedbackIntentService => {- const acceptedCounts = new Map<string, number>();+ const limiter = deps.declarationLimiter ?? createInMemoryDeclarationLimiter();return {declareIntent: async (input) => {@@ -145,9 +221,9 @@ export const createSelfFeedbackIntentService = (}const rateLimitScopeKey = getRateLimitScopeKey(input);- const acceptedCount = acceptedCounts.get(rateLimitScopeKey) ?? 0;- if (acceptedCount >= DECLARATION_LIMIT_PER_SCOPE) {+ if (!(await limiter.acquire(rateLimitScopeKey, DECLARATION_LIMIT_PER_SCOPE))) {+ await limiter.release(rateLimitScopeKey);return { accepted: false, reason: 'rate_limited', strength };}@@ -181,12 +257,18 @@ export const createSelfFeedbackIntentService = (sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,};- if (deps.canEnqueue && !(await deps.canEnqueue(sourceEvent))) {- return { accepted: false, reason: 'enqueue_gate_rejected', sourceId, strength };- }+ // Only accepted declarations keep their slot; rejected or failed ones give it back.+ try {+ if (deps.canEnqueue && !(await deps.canEnqueue(sourceEvent))) {+ await limiter.release(rateLimitScopeKey);+ return { accepted: false, reason: 'enqueue_gate_rejected', sourceId, strength };+ }- await deps.enqueueSource(sourceEvent);- acceptedCounts.set(rateLimitScopeKey, acceptedCount + 1);+ await deps.enqueueSource(sourceEvent);+ } catch (error) {+ await limiter.release(rateLimitScopeKey);+ throw error;+ }return { accepted: true, sourceId, strength };},diff --git a/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/buildSelfIterationReceipts.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/buildSelfIterationReceipts.test.tsindex e05ac5d0006..9f57d57bfc0 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/buildSelfIterationReceipts.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/buildSelfIterationReceipts.test.ts@@ -45,6 +45,50 @@ describe('buildSelfIterationReceipts', () => {expect(summary.metadata?.actionCount).toBe(0);});+ it('describes an ideas-only run by its captured ideas, not as zero writes', () => {+ const [summary] = buildSelfIterationReceipts({+ ...baseInput,+ artifacts: [+ {+ apiName: 'recordSelfReviewIdea',+ data: { idempotencyKey: 'a', rationale: 'A' },+ kind: 'artifact',+ },+ {+ apiName: 'recordSelfReviewIdea',+ data: { idempotencyKey: 'b', rationale: 'B' },+ kind: 'artifact',+ },+ ],+ });++ expect(summary.detail).toBe('Captured 2 idea(s).');+ expect(summary.metadata?.selfIteration?.ideas).toHaveLength(2);+ });++ it('keeps the write count in the detail when the run also applied writes', () => {+ const [summary] = buildSelfIterationReceipts({+ ...baseInput,+ artifacts: [+ {+ apiName: 'recordSelfReviewIdea',+ data: { idempotencyKey: 'a', rationale: 'A' },+ kind: 'artifact',+ },+ ],+ mutations: [+ {+ apiName: 'writeMemory',+ data: { resourceId: 'mem_1' },+ kind: 'mutation',+ toolCallId: 'c1',+ },+ ],+ });++ expect(summary.detail).toBe('Captured 1 idea(s) and applied 1 write(s).');+ });+it('projects a memory mutation into an applied memory receipt with a target', () => {const [, memory] = buildSelfIterationReceipts({...baseInput,@@ -70,14 +114,100 @@ describe('buildSelfIterationReceipts', () => {localDate: '2026-05-30',sourceType: 'agent.execution.completed',});+ // The summary is the description, not a stand-in title: an untitled target leaves the title+ // to the client's localized fallback.expect(memory.target).toEqual({id: 'mem_1',summary: 'Saved tone preference',- title: 'Saved tone preference',type: 'memory',});});+ it('never writes the English default title into an untitled memory target', () => {+ const [, memory] = buildSelfIterationReceipts({+ ...baseInput,+ mutations: [+ {+ apiName: 'writeMemory',+ data: {+ kind: 'mutation',+ status: 'applied',+ target: { memoryLayer: LayersEnum.Preference, operation: 'create', type: 'memory' },+ },+ kind: 'mutation',+ toolCallId: 'call_untitled',+ },+ ],+ });++ expect(memory.title).toBe('Memory saved');+ expect(memory.target).toEqual({+ memoryLayer: LayersEnum.Preference,+ operation: 'create',+ type: 'memory',+ });+ // No layer row id to delete, so undo is not offered.+ expect(memory.metadata?.rollbackStatus).toBeUndefined();+ });++ it('offers undo for a memory the run created', () => {+ const [, memory] = buildSelfIterationReceipts({+ ...baseInput,+ mutations: [+ {+ apiName: 'writeMemory',+ data: {+ kind: 'mutation',+ resourceId: 'pref_1',+ status: 'applied',+ summary: 'Use concise implementation notes.',+ target: {+ id: 'pref_1',+ memoryId: 'mem_1',+ memoryLayer: LayersEnum.Preference,+ operation: 'create',+ title: 'Prefers concise implementation notes',+ type: 'memory',+ },+ },+ kind: 'mutation',+ toolCallId: 'call_create',+ },+ ],+ });++ expect(memory.metadata?.rollbackStatus).toBe('available');+ expect(memory.target).toMatchObject({ id: 'pref_1', operation: 'create' });+ });++ it('does not offer undo for a memory update', () => {+ const [, memory] = buildSelfIterationReceipts({+ ...baseInput,+ mutations: [+ {+ apiName: 'writeMemory',+ data: {+ kind: 'mutation',+ resourceId: 'identity_1',+ status: 'applied',+ target: {+ id: 'identity_1',+ memoryLayer: LayersEnum.Identity,+ operation: 'update',+ title: 'Senior engineer',+ type: 'memory',+ },+ },+ kind: 'mutation',+ toolCallId: 'call_update',+ },+ ],+ });++ expect(memory.metadata?.rollbackStatus).toBeUndefined();+ expect(memory.target?.operation).toBe('update');+ });+it('preserves structured memory target metadata for layer-specific navigation', () => {const [, memory] = buildSelfIterationReceipts({...baseInput,diff --git a/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/completionLoop.integration.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/completionLoop.integration.test.tsindex 05ea71a7125..31952ba6a2c 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/completionLoop.integration.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/completionLoop.integration.test.ts@@ -207,4 +207,128 @@ describe('S2 completion loop (policy → handler → projection → persist)', (expect(appended).toHaveLength(0);});++ describe('nightly ideas Daily Brief', () => {+ const ideasOnly = (overrides: Partial<SelfIterationCompletionPayload> = {}) => ({+ agentId: BUILTIN_AGENT_SLUGS.nightlyReview,+ operationId: 'op_ideas',+ selfIteration: {+ artifacts: [+ {+ apiName: 'recordSelfReviewIdea',+ data: {+ apiName: 'recordSelfReviewIdea',+ idempotencyKey: 'idea:tone',+ kind: 'artifact',+ rationale: 'User keeps asking for shorter answers',+ risk: 'low',+ title: 'Shorter answers',+ },+ kind: 'artifact',+ toolCallId: 'call_idea',+ },+ ],+ marker: {+ agentId: 'agent_user_1',+ kind: 'nightly-review',+ localDate: '2026-05-30',+ reviewWindowEnd: '2026-05-30T15:59:59.000Z',+ reviewWindowStart: '2026-05-29T16:00:00.000Z',+ sourceId: 'nightly-review:user_1:agent_user_1:2026-05-30',+ },+ mutations: [],+ userId: 'user_1',+ ...overrides,+ } satisfies SelfIterationCompletionPayload,+ });++ const setup = () => {+ const { appended, store } = makeInMemoryReceiptStore();+ const writeDailyBrief = vi.fn().mockResolvedValue({ id: 'brief_1' });+ const [handler] = installAndCapture(+ createCompletionPolicy({+ onSelfIterationCompleted: createSelfIterationCompletionHandler({+ ideasBrief: { writer: { writeDailyBrief } },+ receiptStore: store,+ }),+ }),+ );+ return { appended, handler, writeDailyBrief };+ };++ it('writes one ideas brief for the reviewed agent when the run only recorded ideas', async () => {+ const { appended, handler, writeDailyBrief } = setup();++ await handler.handle({ payload: ideasOnly() });++ expect(appended[0].detail).toBe('Captured 1 idea(s).');+ expect(writeDailyBrief).toHaveBeenCalledTimes(1);+ const brief = writeDailyBrief.mock.calls[0][0];+ expect(brief).toMatchObject({+ agentId: 'agent_user_1',+ summary: 'User keeps asking for shorter answers',+ title: 'Dream note: Shorter answers',+ trigger: 'agent-signal:nightly-review',+ type: 'insight',+ });+ expect(brief.metadata.agentSignal.nightlySelfReview).toMatchObject({+ ideas: [+ {+ idempotencyKey: 'idea:tone',+ rationale: 'User keeps asking for shorter answers',+ risk: 'low',+ title: 'Shorter answers',+ },+ ],+ localDate: '2026-05-30',+ outcome: 'ideas',+ receiptIds: ['nightly-review:user_1:agent_user_1:2026-05-30:self-iteration-summary'],+ sourceId: 'nightly-review:user_1:agent_user_1:2026-05-30',+ });+ });++ it('does not write an ideas brief when the run already wrote a proposal brief', async () => {+ const { handler, writeDailyBrief } = setup();++ await handler.handle({+ payload: ideasOnly({+ mutations: [+ {+ apiName: 'createSelfReviewProposal',+ data: { proposalId: 'brf_1', summary: 'Refine skill X' },+ kind: 'mutation',+ toolCallId: 'call_prop',+ },+ ],+ }),+ });++ expect(writeDailyBrief).not.toHaveBeenCalled();+ });++ it('does not write an ideas brief for non-nightly runs or runs without ideas', async () => {+ const { handler, writeDailyBrief } = setup();+ const base = ideasOnly().selfIteration;++ await handler.handle({+ payload: ideasOnly({ marker: { ...base.marker, kind: 'self-reflection' } }),+ });+ await handler.handle({ payload: ideasOnly({ artifacts: [] }) });++ expect(writeDailyBrief).not.toHaveBeenCalled();+ });++ it('keeps receipts persisted when the brief write fails', async () => {+ const { appended, store } = makeInMemoryReceiptStore();+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const onSelfIterationCompleted = createSelfIterationCompletionHandler({+ ideasBrief: { writer: { writeDailyBrief: vi.fn().mockRejectedValue(new Error('db')) } },+ receiptStore: store,+ });++ await expect(onSelfIterationCompleted(ideasOnly() as never)).resolves.toBeUndefined();+ expect(appended).toHaveLength(1);+ consoleError.mockRestore();+ });+ });});diff --git a/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.tsindex 70d7dc8352f..9a2f30dfe9c 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.ts@@ -122,12 +122,167 @@ describe('extractSelfIterationCompletionPayload', () => {id: 'pref_1',memoryId: 'mem_1',memoryLayer: LayersEnum.Preference,+ operation: 'create',summary: 'Prefer direct implementation with focused tests.',title: 'Prefers direct implementation',type: 'memory',});});+ it('emits one writeMemory mutation per confirmed memory write in the run', () => {+ const persistedTool = (id: string, apiName: string, title: string) => ({+ apiName,+ arguments: JSON.stringify({ summary: `${title} summary`, title }),+ id,+ identifier: MemoryIdentifier,+ type: 'builtin',+ });+ const result = extractSelfIterationCompletionPayload(+ buildState(+ {+ agentId: 'agent_user_1',+ signal: { kind: 'memory', sourceId: 'mem-src_2' },+ userId: 'user_1',+ },+ {+ messages: [+ {+ id: 'msg_a',+ role: 'assistant',+ tools: [+ persistedTool(+ 'call_ctx',+ MemoryApiName.addContextMemory,+ 'Training for a half marathon',+ ),+ ],+ },+ {+ content: 'Context memory saved with memoryId: "mem_ctx" and contextId: "ctx_1"',+ role: 'tool',+ tool_call_id: 'call_ctx',+ },+ {+ id: 'msg_b',+ role: 'assistant',+ tools: [+ persistedTool(+ 'call_pref',+ MemoryApiName.addPreferenceMemory,+ 'Three sessions per week',+ ),+ ],+ },+ {+ content:+ 'Preference memory saved with memoryId: "mem_pref" and preferenceId: "pref_2"',+ role: 'tool',+ tool_call_id: 'call_pref',+ },+ ],+ status: 'finished',+ usage: {+ tools: {+ byTool: [+ {+ calls: 1,+ errors: 0,+ name: `${MemoryIdentifier}/${MemoryApiName.addContextMemory}`,+ },+ {+ calls: 1,+ errors: 0,+ name: `${MemoryIdentifier}/${MemoryApiName.addPreferenceMemory}`,+ },+ ],+ },+ },+ },+ ),+ );++ const targets = result?.mutations.map(+ (mutation) => (mutation.data as { target?: Record<string, unknown> }).target,+ );+ expect(targets).toEqual([+ expect.objectContaining({+ id: 'ctx_1',+ memoryId: 'mem_ctx',+ title: 'Training for a half marathon',+ }),+ expect.objectContaining({+ id: 'pref_2',+ memoryId: 'mem_pref',+ title: 'Three sessions per week',+ }),+ ]);+ });++ it('reads the memory written in a flattened assistantGroup state', () => {+ const result = extractSelfIterationCompletionPayload(+ buildState(+ {+ agentId: 'agent_user_1',+ signal: { kind: 'memory', sourceId: 'mem-src_3' },+ userId: 'user_1',+ },+ {+ messages: [+ { content: 'User feedback to analyze', id: 'msg_seed', role: 'user' },+ {+ children: [+ {+ content: '',+ id: 'blk_1',+ tools: [+ {+ apiName: MemoryApiName.addPreferenceMemory,+ arguments: JSON.stringify({+ summary: 'Use one pot',+ title: 'One-pot recipes',+ }),+ id: 'call_flat',+ identifier: MemoryIdentifier,+ result: {+ content:+ 'Preference memory saved with memoryId: "mem_flat" and preferenceId: "pref_flat"',+ id: 'tool_msg_1',+ },+ type: 'builtin',+ },+ ],+ },+ ],+ content: '',+ id: 'grp_1',+ role: 'assistantGroup',+ },+ ],+ status: 'finished',+ usage: {+ tools: {+ byTool: [+ {+ calls: 1,+ errors: 0,+ name: `${MemoryIdentifier}/${MemoryApiName.addPreferenceMemory}`,+ },+ ],+ },+ },+ },+ ),+ );++ expect(+ (result?.mutations[0].data as { target?: Record<string, unknown> }).target,+ ).toMatchObject({+ id: 'pref_flat',+ memoryId: 'mem_flat',+ title: 'One-pot recipes',+ });+ });+it('falls back to the successful memory tool api when finalState lacks tool call details', () => {const result = extractSelfIterationCompletionPayload(buildState(@@ -156,7 +311,7 @@ describe('extractSelfIterationCompletionPayload', () => {expect(result?.mutations).toHaveLength(1);expect((result?.mutations[0].data as { target?: Record<string, unknown> }).target).toEqual({memoryLayer: LayersEnum.Preference,- title: 'Memory saved',+ operation: 'create',type: 'memory',});});diff --git a/apps/server/src/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts b/apps/server/src/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.tsindex aed56e51ebe..9210a10a1b9 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts@@ -36,6 +36,11 @@ const SUCCESS_STATUS_BY_API: Record<string, AgentSignalReceipt['status']> = {writeMemory: 'applied',};+/**+ * English fallback copy for the receipt's top-level `title` (API / CLI consumers). The web+ * client never renders it for known kinds: it localizes by `kind` and shows the resource's own+ * `target.title` when one was captured, so none of these strings leak into `target`.+ */const DEFAULT_TITLE_BY_API: Record<string, string> = {closeSelfReviewProposal: 'Self-review proposal closed',createSelfReviewProposal: 'Self-review proposal created',@@ -48,13 +53,19 @@ const DEFAULT_TITLE_BY_API: Record<string, string> = {const ROLLBACK_CAPABLE_APIS = new Set(['replaceSkillContentCAS']);+const MEMORY_OPERATIONS = new Set(['create', 'remove', 'update']);++const isMemoryOperation = (value: unknown): value is 'create' | 'remove' | 'update' =>+ typeof value === 'string' && MEMORY_OPERATIONS.has(value);+const isRecord = (value: unknown): value is Record<string, unknown> =>typeof value === 'object' && value !== null && !Array.isArray(value);const str = (value: unknown): string | undefined =>typeof value === 'string' && value.length > 0 ? value : undefined;-const getIdeas = (artifacts: ToolResultWithKind[]): Idea[] =>+/** Reads the valid `recordSelfReviewIdea` ideas echoed into a run's artifact outputs. */+export const getIdeas = (artifacts: ToolResultWithKind[]): Idea[] =>artifacts.flatMap((artifact) => {if (artifact.apiName !== 'recordSelfReviewIdea' || !isRecord(artifact.data)) return [];const value = isRecord(artifact.data.idea) ? artifact.data.idea : artifact.data;@@ -64,7 +75,7 @@ const getIdeas = (artifacts: ToolResultWithKind[]): Idea[] =>});/** A `skipped_unsupported` / `skipped_stale` tool status collapses to `skipped`. */-const isSkippedStatus = (status: unknown): boolean =>+export const isSkippedStatus = (status: unknown): boolean =>typeof status === 'string' && status.startsWith('skipped');const isMemoryLayer = (value: unknown): value is LayersEnum =>@@ -146,7 +157,12 @@ export const buildSelfIterationReceipts = (const summary: AgentSignalReceipt = {...base,- detail: `Captured ${artifacts.length} idea(s) and applied ${mutations.length} write(s).`,+ // An ideas-only run (no durable writes) must not read as "0 actions": surface+ // what it did capture instead.+ detail:+ mutations.length === 0 && artifacts.length > 0+ ? `Captured ${artifacts.length} idea(s).`+ : `Captured ${artifacts.length} idea(s) and applied ${mutations.length} write(s).`,id: `${sourceId}:self-iteration-summary`,kind: 'review',metadata: {@@ -184,6 +200,8 @@ export const buildSelfIterationReceipts = (const memoryId = kind === 'memory' ? str(target?.memoryId) : undefined;const memoryLayer =kind === 'memory' && isMemoryLayer(target?.memoryLayer) ? target.memoryLayer : undefined;+ const memoryOperation =+ kind === 'memory' && isMemoryOperation(target?.operation) ? target.operation : undefined;const rollbackAgentDocumentId = str(data.agentDocumentId);const rollbackDocumentId = str(data.documentId);const rollbackExpectedCurrentDocumentUpdatedAt = str(data.expectedCurrentDocumentUpdatedAt);@@ -192,12 +210,21 @@ export const buildSelfIterationReceipts = (const targetTitle = str(target?.title);const title =targetTitle ?? summaryText ?? DEFAULT_TITLE_BY_API[apiName] ?? 'Agent Signal action';- const rollbackAvailable =+ const skillRollbackAvailable =rollbackDocumentId &&rollbackExpectedCurrentDocumentUpdatedAt &&rollbackHistoryId &&status === 'applied' &&ROLLBACK_CAPABLE_APIS.has(apiName);+ // Undo deletes the memory the run created. Updates / removals have no prior snapshot to+ // restore, so they stay non-undoable.+ const memoryRollbackAvailable =+ kind === 'memory' &&+ status === 'applied' &&+ memoryOperation === 'create' &&+ Boolean(targetId) &&+ Boolean(memoryLayer);+ const rollbackAvailable = skillRollbackAvailable || memoryRollbackAvailable;return [{@@ -228,8 +255,10 @@ export const buildSelfIterationReceipts = (...(targetId ? { id: targetId } : {}),...(memoryId ? { memoryId } : {}),...(memoryLayer ? { memoryLayer } : {}),+ ...(memoryOperation ? { operation: memoryOperation } : {}),...(summaryText ? { summary: summaryText } : {}),- title,+ // Only the resource's own title: a missing one is localized by the client.+ ...(targetTitle ? { title: targetTitle } : {}),type: kind,},}),diff --git a/apps/server/src/services/agentSignal/services/selfIteration/completion/extractCompletionPayload.ts b/apps/server/src/services/agentSignal/services/selfIteration/completion/extractCompletionPayload.tsindex bac5ebb25f5..24febc7585e 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/completion/extractCompletionPayload.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/completion/extractCompletionPayload.ts@@ -4,7 +4,10 @@ import {type AgentSignalOperationMarker,parseAgentSignalMarker,} from '@/server/services/agentSignal/operationMarker';-import { resolveMemoryActionResultFromState } from '@/server/services/agentSignal/policies/analyzeIntent/actions/memoryActionResult';+import {+ resolveMemoryActionResultFromState,+ resolveMemoryActionTargetsFromState,+} from '@/server/services/agentSignal/policies/analyzeIntent/actions/memoryActionResult';import {extractArtifacts,@@ -44,6 +47,21 @@ const extractMemoryMutations = (finalState: AgentState): ToolResultWithKind[] =>const result = resolveMemoryActionResultFromState(finalState);if (result.status !== 'applied') return [];+ const targets = resolveMemoryActionTargetsFromState(finalState);+ if (targets.length > 1) {+ return targets.map((target) => ({+ apiName: 'writeMemory',+ data: {+ kind: 'mutation',+ resourceId: target.id ?? target.memoryId,+ status: 'applied',+ summary: target.summary,+ target,+ },+ kind: 'mutation',+ }));+ }+return [{apiName: 'writeMemory',diff --git a/apps/server/src/services/agentSignal/services/selfIteration/completion/selfIterationCompletionHandler.ts b/apps/server/src/services/agentSignal/services/selfIteration/completion/selfIterationCompletionHandler.tsindex edaf57d1753..cf12f1a6017 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/completion/selfIterationCompletionHandler.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/completion/selfIterationCompletionHandler.ts@@ -3,28 +3,129 @@ import debug from 'debug';import type { CompletionCallbackParams } from '../../../policies/completionPolicy';import { type AgentSignalReceiptStore, persistAgentSignalReceipts } from '../../receiptService';-import { buildSelfIterationReceipts } from './buildSelfIterationReceipts';+import type { SelfReviewBriefProjection } from '../review/brief';+import { createBriefSelfReviewService } from '../review/brief';+import type { SelfReviewBriefTextTranslator } from '../review/briefText';+import type { SelfReviewIdea } from '../review/proposal';+import type { Idea } from '../types';+import { ReviewRunStatus, Risk } from '../types';+import {+ buildSelfIterationReceipts,+ getIdeas,+ isSkippedStatus,+} from './buildSelfIterationReceipts';+import type { SelfIterationCompletionPayload } from './extractCompletionPayload';const log = debug('lobe-server:completion-lifecycle');+/** Daily Brief deps for nightly reviews that only recorded ideas. */+export interface SelfIterationIdeasBriefOptions {+ /** Resolves the brief owner's `home` translator; omitted → English resources. */+ resolveTranslator?: () => Promise<SelfReviewBriefTextTranslator | undefined>;+ /** Writer that persists (and dedupes) nightly self-review Daily Briefs. */+ writer: { writeDailyBrief: (brief: SelfReviewBriefProjection) => Promise<unknown> };+}+export interface SelfIterationCompletionHandlerOptions {+ /** Writes an `ideas` Daily Brief for idea-only nightly reviews. Omitted → no brief. */+ ideasBrief?: SelfIterationIdeasBriefOptions;/** Receipt store override (defaults to the Redis store). Injected in tests. */receiptStore?: AgentSignalReceiptStore;}+const RISKS = new Set<string>(Object.values(Risk));++const toSelfReviewIdea = (idea: Idea): SelfReviewIdea => ({+ evidenceRefs: Array.isArray(idea.evidenceRefs) ? idea.evidenceRefs : [],+ idempotencyKey: idea.idempotencyKey,+ rationale: idea.rationale,+ risk: RISKS.has(idea.risk) ? (idea.risk as Risk) : Risk.Low,+ ...(idea.target+ ? {+ target: {+ ...(idea.target.memoryId ? { memoryId: idea.target.memoryId } : {}),+ ...(idea.target.skillDocumentId ? { skillDocumentId: idea.target.skillDocumentId } : {}),+ ...(idea.target.skillName ? { skillName: idea.target.skillName } : {}),+ ...(idea.target.taskIds ? { taskIds: idea.target.taskIds } : {}),+ ...(idea.target.topicIds ? { topicIds: idea.target.topicIds } : {}),+ },+ }+ : {}),+ ...(idea.title ? { title: idea.title } : {}),+});++/** True when the run already wrote its own proposal Daily Brief in-run. */+const hasWrittenProposalBrief = (mutations: SelfIterationCompletionPayload['mutations']) =>+ mutations.some((mutation) => {+ if (mutation.apiName !== 'createSelfReviewProposal') return false;+ const data = mutation.data as { status?: unknown } | undefined;++ return !isSkippedStatus(data?.status);+ });++/**+ * Projects one `ideas` Daily Brief for a nightly review that recorded ideas but+ * wrote no proposal brief — otherwise those ideas only live on the receipt and+ * the user never sees the night's outcome.+ */+const writeNightlyIdeasBrief = async ({+ ideasBrief,+ selfIteration,+ sourceId,+}: {+ ideasBrief: SelfIterationIdeasBriefOptions;+ selfIteration: SelfIterationCompletionPayload;+ sourceId: string;+}) => {+ const { artifacts, marker, mutations, userId } = selfIteration;+ if (marker.kind !== 'nightly-review') return;+ // The run executes as the builtin reviewer; the brief belongs to the reviewed agent.+ if (!marker.agentId) return;+ if (hasWrittenProposalBrief(mutations)) return;++ const ideas = getIdeas(artifacts).map(toSelfReviewIdea);+ if (ideas.length === 0) return;++ const reviewWindowEnd = marker.reviewWindowEnd ?? new Date().toISOString();+ const reviewWindowStart = marker.reviewWindowStart ?? reviewWindowEnd;++ const brief = createBriefSelfReviewService().projectNightlyReviewBrief({+ agentId: marker.agentId,+ ideas,+ localDate: marker.localDate ?? reviewWindowEnd.slice(0, 10),+ result: {+ actions: [],+ sourceId,+ status: ReviewRunStatus.Completed,+ summaryReceiptId: `${sourceId}:self-iteration-summary`,+ },+ reviewWindowEnd,+ reviewWindowStart,+ t: await ideasBrief.resolveTranslator?.(),+ timezone: 'UTC',+ userId,+ });+ if (!brief) return;++ await ideasBrief.writer.writeDailyBrief(brief);+ log('[completion-handler] wrote ideas brief (%d idea(s)) for source=%s', ideas.length, sourceId);+};+/*** Builds the `onSelfIterationCompleted` callback wired into the completion* policy. After a background self-iteration run finishes, it projects the run's* finalState tool outcomes (carried on the completion source payload) into* user-visible receipts and persists them — the execAgent replacement for the- * old in-runtime receipt accumulator.+ * old in-runtime receipt accumulator. A nightly review that only recorded ideas+ * additionally gets one `ideas` Daily Brief.** Idempotent: `buildSelfIterationReceipts` derives deterministic receipt ids* from the source id + tool call ids, and the receipt store dedupes by id, so a- * replayed completion event re-projects to the same receipts.+ * replayed completion event re-projects to the same receipts. The brief writer+ * reuses an unresolved ideas brief for the same agent + local date.*/export const createSelfIterationCompletionHandler =- ({ receiptStore }: SelfIterationCompletionHandlerOptions = {}) =>+ ({ ideasBrief, receiptStore }: SelfIterationCompletionHandlerOptions = {}) =>async (params: CompletionCallbackParams): Promise<void> => {const { agentId, operationId, selfIteration, topicId } = params;if (!selfIteration) return;@@ -58,4 +159,18 @@ export const createSelfIterationCompletionHandler =await persistAgentSignalReceipts(receipts, receiptStore ? { store: receiptStore } : {});log('[completion-handler] persisted %d receipt(s) for op=%s', receipts.length, operationId);++ if (!ideasBrief) return;++ try {+ await writeNightlyIdeasBrief({ ideasBrief, selfIteration, sourceId });+ } catch (error) {+ // Non-fatal: receipts are already persisted and downstream completion work+ // (expertise ingestion) must still run.+ console.error('[completion-handler] failed to write nightly ideas brief', {+ error,+ operationId,+ sourceId,+ });+ }};diff --git a/apps/server/src/services/agentSignal/services/selfIteration/feedback/handler.ts b/apps/server/src/services/agentSignal/services/selfIteration/feedback/handler.tsindex f2c57f09e8b..ce5d9ebef8a 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/feedback/handler.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/feedback/handler.ts@@ -16,11 +16,7 @@ export type SelfFeedbackIntentSourceScopeType = 'operation' | 'topic';/** Actions that an agent may declare as self-feedback intent. */export type SelfFeedbackIntentDeclaredAction =- | 'write'- | 'create'- | 'refine'- | 'consolidate'- | 'proposal';+ 'write' | 'create' | 'refine' | 'consolidate' | 'proposal';/** Self-feedback target category declared by the running agent. */export type SelfFeedbackIntentDeclaredKind = 'memory' | 'skill' | 'gap';diff --git a/apps/server/src/services/agentSignal/services/selfIteration/reflection/__test__/handler.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/reflection/__test__/handler.test.tsindex 1332988a1e5..5c702c3e70d 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/reflection/__test__/handler.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/reflection/__test__/handler.test.ts@@ -22,6 +22,15 @@ import {createSelfReflectionSourcePolicyHandler,} from '../handler';+const { mockEnqueueSelfIterationRun } = vi.hoisted(() => ({+ mockEnqueueSelfIterationRun: vi.fn(),+}));++vi.mock('../../dispatch/enqueueSelfIterationRun', () => ({+ enqueueSelfIterationRun: mockEnqueueSelfIterationRun,+}));++// Every Redis counter reads as far past any daily limit; dispatch must not care.const reflectionPayload = {agentId: 'agent-1',operationId: 'operation-1',@@ -86,6 +95,23 @@ const createDependencies = (});describe('self-reflection source handler', () => {+ it('dispatches through the self-iteration enqueue by default', async () => {+ mockEnqueueSelfIterationRun.mockResolvedValue({+ operationId: 'op-default',+ topicId: 'topic-1',+ });+ const { dispatch: _dispatch, ...deps } = createDependencies();+ const handler = createSelfReflectionSourceHandler(deps);++ const result = await handler.handle(createReflectionSource());++ expect(mockEnqueueSelfIterationRun).toHaveBeenCalledOnce();+ expect(result).toMatchObject({+ operationId: 'op-default',+ status: ReviewRunStatus.Dispatched,+ });+ });+it('dispatches an async self-iteration run under the builtin self-reflection slug', async () => {const deps = createDependencies();const handler = createSelfReflectionSourceHandler(deps);diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/brief.test.tsindex ac25598f9dd..814c92769ad 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts@@ -299,9 +299,9 @@ describe('briefSelfReviewService', () => {});expect(projected?.actions).toEqual([- { key: 'approve', label: 'Apply', type: 'resolve' },+ { key: 'approve', label: 'Approve', type: 'resolve' },{ key: 'dismiss', label: 'Dismiss', type: 'resolve' },- { key: 'feedback', label: 'Request changes', type: 'comment' },+ { key: 'feedback', label: 'Feedback', type: 'comment' },]);const nightlySelfReview = projected?.metadata.agentSignal?.nightlySelfReview;@@ -393,7 +393,9 @@ describe('briefSelfReviewService', () => {});expect(getNightlySelfReview(projected)?.actionCounts.proposed).toBe(1);- expect(projected?.summary).toContain('1 dream suggestion needs your review.');+ expect(projected?.summary).toBe(+ 'Refine the managed skill instead of creating duplicate skill drafts.',+ );expect(projected?.summary).not.toContain('No self-iteration change is needed.');expect(getSelfReviewProposal(projected)?.actions).toHaveLength(1);expect(getSelfReviewProposal(projected)?.actions[0]).toMatchObject({@@ -402,6 +404,176 @@ describe('briefSelfReviewService', () => {});});+ describe('specific proposal and ideas text', () => {+ const createSkillPlanAction = (index: number) => ({+ actionType: 'create_skill' as const,+ applyMode: ApplyMode.ProposalOnly,+ baseSnapshot: {+ absent: true,+ skillName: `pr-checklist-${index}`,+ targetType: 'skill' as const,+ },+ confidence: 0.9,+ dedupeKey: `skill:pr-checklist-${index}`,+ evidenceRefs: [{ id: 'topic-1', type: 'topic' as const }],+ idempotencyKey: `source:create_skill:${index}`,+ operation: {+ domain: 'skill' as const,+ input: {+ bodyMarkdown: '# PR checklist',+ description: 'Checklist for reviewing pull requests.',+ name: `pr-checklist-${index}`,+ title: index === 1 ? 'PR checklist' : `Skill ${index}`,+ userId: 'user-1',+ },+ operation: 'create' as const,+ },+ rationale:+ index === 1+ ? 'The user asked for the same PR review steps three times.'+ : `Rationale ${index}.`,+ risk: Risk.Low,+ target: { skillName: `pr-checklist-${index}` },+ });++ const projectCreateSkillProposal = (+ count: number,+ options: { summary?: string; t?: SelfReviewBriefTextTranslator } = {},+ ) => {+ const actions = Array.from({ length: count }, (_, index) => createSkillPlanAction(index + 1));++ return createBriefSelfReviewService().projectNightlyReviewBrief({+ agentId: 'agent-1',+ localDate: '2026-05-09',+ plan: {+ actions,+ plannerVersion: 'test-planner',+ reviewScope: Scope.Nightly,+ summary: options.summary ?? 'Self-review tool-first runtime completed.',+ },+ result: {+ actions: actions.map((action) => ({+ idempotencyKey: action.idempotencyKey,+ receiptId: 'proposal-receipt',+ status: ActionStatus.Proposed,+ ...(options.summary ? { summary: options.summary } : {}),+ })),+ sourceId: 'source',+ status: ReviewRunStatus.Completed,+ },+ reviewWindowEnd: '2026-05-09T20:00:00.000Z',+ reviewWindowStart: '2026-05-09T18:00:00.000Z',+ t: options.t,+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ });+ };++ /**+ * @example+ * A create_skill proposal brief names the skill and says why, not "a suggestion needs review".+ */+ it('names the proposed skill and uses the proposal summary as the body', () => {+ const brief = projectCreateSkillProposal(1, {+ summary: 'Save the PR review steps as a reusable skill.',+ });++ expect(brief?.title).toBe('New skill: PR checklist');+ expect(brief?.summary).toBe('Save the PR review steps as a reusable skill.');+ expect(getSelfReviewProposal(brief)?.summary).toBe(+ 'Save the PR review steps as a reusable skill.',+ );+ });++ /**+ * @example+ * Without a proposal summary the body falls back to the action rationale.+ */+ it('falls back to the action rationale when the proposal has no summary', () => {+ const brief = projectCreateSkillProposal(1);++ expect(brief?.title).toBe('New skill: PR checklist');+ expect(brief?.summary).toBe('The user asked for the same PR review steps three times.');+ expect(getSelfReviewProposal(brief)).not.toHaveProperty('summary');+ });++ /**+ * @example+ * Multi-action proposals count the rest in the title and list every action in the body.+ */+ it('lists each action of a multi-action proposal', () => {+ const brief = projectCreateSkillProposal(2, { summary: 'Two skills would save time.' });++ expect(brief?.title).toBe('New skill: PR checklist (+1 more)');+ expect(brief?.summary).toBe(+ [+ 'Two skills would save time.',+ '',+ '- **New skill: PR checklist** — The user asked for the same PR review steps three times.',+ '- **New skill: Skill 2** — Rationale 2.',+ ].join('\n'),+ );+ });++ /**+ * @example+ * Specific proposal text is rendered through the owner's translator.+ */+ it('renders the specific title through the supplied translator', () => {+ const brief = projectCreateSkillProposal(2, {+ t: createTranslator({+ ...zhCNBriefText,+ 'brief.agentSignal.selfReview.kind.create_skill.withTarget': '新建技能:{{target}}',+ 'brief.agentSignal.selfReview.title.more': '{{title}}(另有 {{count}} 项)',+ }),+ });++ expect(brief?.title).toBe('新建技能:PR checklist(另有 1 项)');+ expect(brief?.title).not.toBe('有夜间回顾建议需要确认');+ });++ /**+ * @example+ * Ideas-only briefs list their ideas instead of "saved dream notes".+ */+ it('lists the ideas of an ideas-only brief', () => {+ const brief = createBriefSelfReviewService().projectNightlyReviewBrief({+ agentId: 'agent-1',+ ideas: [+ {+ evidenceRefs: [],+ idempotencyKey: 'idea-1',+ rationale: 'Users often ask for weekly summaries.',+ risk: Risk.Low,+ title: 'Weekly digest',+ },+ {+ evidenceRefs: [],+ idempotencyKey: 'idea-2',+ rationale: 'Release notes keep missing the migration section.',+ risk: Risk.Low,+ target: { skillName: 'release-notes' },+ },+ ],+ localDate: '2026-05-09',+ result: { actions: [], sourceId: 'source', status: ReviewRunStatus.Completed },+ reviewWindowEnd: '2026-05-09T20:00:00.000Z',+ reviewWindowStart: '2026-05-09T18:00:00.000Z',+ timezone: 'UTC',+ userId: 'user-1',+ });++ expect(brief?.type).toBe('insight');+ expect(brief?.title).toBe('Dream note: Weekly digest (+1 more)');+ expect(brief?.summary).toBe(+ [+ '- **Dream note: Weekly digest** — Users often ask for weekly summaries.',+ '- **Dream note: release-notes** — Release notes keep missing the migration section.',+ ].join('\n'),+ );+ });+ });+/*** @example* Failed nightly runs produce an error brief when there is a user-actionable failure.@@ -537,6 +709,72 @@ describe('briefSelfReviewService', () => {expect(create).toHaveBeenCalledWith(brief);});+ describe('ideas brief dedupe', () => {+ const projectIdeasBrief = (localDate: string) => {+ const brief = createBriefSelfReviewService().projectNightlyReviewBrief({+ agentId: 'agent-1',+ ideas: [{ evidenceRefs: [], idempotencyKey: 'idea-1', rationale: 'Try X', risk: Risk.Low }],+ localDate,+ result: {+ actions: [],+ sourceId: `nightly:${localDate}`,+ status: ReviewRunStatus.Completed,+ },+ reviewWindowEnd: `${localDate}T14:30:00.000Z`,+ reviewWindowStart: `${localDate}T00:00:00.000Z`,+ timezone: 'UTC',+ userId: 'user-1',+ });+ if (!brief) throw new Error('Expected projected ideas brief');+ return brief;+ };++ /**+ * @example+ * A replayed idea-only completion for the same agent + local date reuses the existing brief.+ */+ it('reuses an unresolved ideas brief for the same agent and local date', async () => {+ const existing = projectIdeasBrief('2026-05-04');+ const existingRow = { ...existing, id: 'brief-ideas-1' } as unknown as Awaited<+ ReturnType<BriefModel['create']>+ >;+ const list = vi+ .spyOn(BriefModel.prototype, 'listUnresolvedByAgentAndTrigger')+ .mockResolvedValue([existingRow]);+ const create = vi.spyOn(BriefModel.prototype, 'create');+ const writer = createServerSelfReviewBriefWriter({} as never, 'user-1');++ await expect(writer.writeDailyBrief(projectIdeasBrief('2026-05-04'))).resolves.toBe(+ existingRow,+ );+ expect(list).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agent-1', trigger: 'agent-signal:nightly-review' }),+ );+ expect(create).not.toHaveBeenCalled();+ });++ /**+ * @example+ * An ideas brief from another local date does not block today's ideas brief.+ */+ it('creates a new ideas brief when only another local date has one', async () => {+ const existingRow = {+ ...projectIdeasBrief('2026-05-03'),+ id: 'brief-old',+ } as unknown as Awaited<ReturnType<BriefModel['create']>>;+ vi.spyOn(BriefModel.prototype, 'listUnresolvedByAgentAndTrigger').mockResolvedValue([+ existingRow,+ ]);+ const created = { id: 'brief-new' } as Awaited<ReturnType<BriefModel['create']>>;+ const create = vi.spyOn(BriefModel.prototype, 'create').mockResolvedValue(created);+ const writer = createServerSelfReviewBriefWriter({} as never, 'user-1');+ const brief = projectIdeasBrief('2026-05-04');++ await expect(writer.writeDailyBrief(brief)).resolves.toBe(created);+ expect(create).toHaveBeenCalledWith(brief);+ });+ });+/*** @example* A compatible pending proposal refreshes the old brief instead of creating a duplicate.diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/collect.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/collect.test.tsindex 368fa6a9594..aad4dbb3b5c 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/collect.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/collect.test.ts@@ -317,6 +317,55 @@ describe('nightlyReviewService', () => {expect(context.topics.at(-1)?.id).toBe('topic-29');});+ /**+ * At most 50 topics per user per night: the collector claims its ranked topics against the+ * shared nightly quota and drops the ones it refuses.+ */+ it('feeds only the topics the nightly topic quota admits', async () => {+ const claimTopics = vi.fn().mockResolvedValue({+ admitted: ['topic-0', 'topic-1'],+ reason: 'exhausted',+ });+ const deps = createDeps({+ claimTopics,+ listTopicActivity: vi.fn().mockResolvedValue(+ Array.from({ length: 4 }, (_, index) => ({+ id: `topic-${index}`,+ messageCount: 10 - index,+ })),+ ),+ });+ const service = createSelfReviewContextService(deps);++ const context = await service.collect({ ...REVIEW_INPUT, localDate: '2026-05-04' });++ expect(claimTopics).toHaveBeenCalledWith({+ localDate: '2026-05-04',+ topicIds: ['topic-0', 'topic-1', 'topic-2', 'topic-3'],+ userId: 'user-1',+ });+ expect(context.topics.map((topic) => topic.id)).toEqual(['topic-0', 'topic-1']);+ expect(context.topicQuota).toEqual({+ admittedTopicCount: 2,+ reason: 'exhausted',+ refusedTopicCount: 2,+ });+ });++ it('does not claim topics without a review date', async () => {+ const claimTopics = vi.fn();+ const deps = createDeps({+ claimTopics,+ listTopicActivity: vi.fn().mockResolvedValue([{ id: 'topic-0', messageCount: 1 }]),+ });++ const context = await createSelfReviewContextService(deps).collect(REVIEW_INPUT);++ expect(claimTopics).not.toHaveBeenCalled();+ expect(context.topics).toHaveLength(1);+ expect(context).not.toHaveProperty('topicQuota');+ });+it('keeps high-signal topics before huge ordinary topics', async () => {/*** @examplediff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/handler.test.tsindex 42baa0f6663..5b6134cbf3a 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts@@ -152,6 +152,42 @@ describe('nightly review source handler', () => {);});+ /**+ * Once earlier agents used up the user's 50 nightly topics, a later agent whose topics were+ * all refused is skipped instead of reviewing an empty context.+ */+ it('skips the review when the nightly topic quota refused every topic', async () => {+ const deps = createDependencies({+ collectContext: vi.fn(async () => ({+ ...reviewContext,+ topicQuota: { admittedTopicCount: 0, reason: 'exhausted' as const, refusedTopicCount: 3 },+ })),+ });++ const result = await createNightlyReviewSourceHandler(deps).handle(createReviewSource());++ expect(deps.dispatch).not.toHaveBeenCalled();+ expect(result).toMatchObject({+ detail: 'Nightly review topic limit reached (50 topics per night).',+ reason: 'topic_quota_exhausted',+ status: ReviewRunStatus.Skipped,+ });+ });++ it('still dispatches when the quota admitted some of the topics', async () => {+ const deps = createDependencies({+ collectContext: vi.fn(async () => ({+ ...reviewContext,+ topicQuota: { admittedTopicCount: 1, reason: 'exhausted' as const, refusedTopicCount: 2 },+ })),+ });++ const result = await createNightlyReviewSourceHandler(deps).handle(createReviewSource());++ expect(deps.dispatch).toHaveBeenCalledOnce();+ expect(result).toMatchObject({ status: ReviewRunStatus.Dispatched });+ });+it('returns skipped without acquiring the guard when gates reject the review', async () => {const deps = createDependencies({canRunReview: vi.fn(async () => false),diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.tsindex d29f55867d3..60a819150c8 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.ts@@ -232,10 +232,67 @@ describe('nightlyReviewScheduleService', () => {expect(deps.listEligibleUsers).toHaveBeenCalledWith({activeSince: new Date('2026-05-02T12:05:00.000Z'),limit: 50,+ // The SQL prefilter is the 02:00-04:00 window widened by one hour on each side.+ localHourWindow: { at: requestedAt, endHourExclusive: 5, startHour: 1 },requestedAt,});});+ /**+ * ROOT CAUSE:+ *+ * Pagination fanned every recently active user out to its own QStash execute workflow, and+ * ~22 of 24 of those runs exited after discovering the user was outside the local 02:00-04:00+ * window. The exact window now runs in the paginate step (and the Labs → Self-evolving switch+ * in the SQL scan), so ineligible users never cost a message or a workflow run.+ *+ * At 2026-05-03T18:30Z: Shanghai is 02:30 (in), Tokyo is 03:30 (in), Bangkok is 01:30 (passes+ * the widened SQL prefilter, out of the exact window), New York is 14:30 (out).+ */+ it('drops users outside the exact night window', async () => {+ const deps = createDeps();+ const createdAt = new Date('2026-01-01T00:00:00.000Z');+ deps.listEligibleUsers.mockResolvedValue([+ { createdAt, id: 'shanghai', timezone: 'Asia/Shanghai' },+ { createdAt, id: 'tokyo', timezone: 'Asia/Tokyo' },+ { createdAt, id: 'bangkok', timezone: 'Asia/Bangkok' },+ { createdAt, id: 'new-york', timezone: 'America/New_York' },+ ]);+ const service = createSelfReviewScheduleService(deps);++ const page = await service.listEligibleUsersPage({+ limit: 50,+ requestedAt: new Date('2026-05-03T18:30:00.000Z'),+ });++ expect(page.users.map((user) => user.id)).toEqual(['shanghai', 'tokyo']);+ expect(page.nextCursor).toBeUndefined();+ });++ /**+ * Filtering must never truncate the traversal: the cursor follows the scanned rows, so a full+ * page whose users were all filtered out still continues to the next page.+ *+ * @example+ * expect(page).toEqual({ nextCursor: { createdAt, id: 'user-2' }, users: [] });+ */+ it('keeps the next cursor when every scanned user is filtered out', async () => {+ const deps = createDeps();+ const createdAt = new Date('2026-01-01T00:00:00.000Z');+ deps.listEligibleUsers.mockResolvedValue([+ { createdAt, id: 'user-1', timezone: 'America/New_York' },+ { createdAt, id: 'user-2', timezone: 'Europe/London' },+ ]);+ const service = createSelfReviewScheduleService(deps);++ const page = await service.listEligibleUsersPage({+ limit: 2,+ requestedAt: new Date('2026-05-03T18:30:00.000Z'),+ });++ expect(page).toEqual({ nextCursor: { createdAt, id: 'user-2' }, users: [] });+ });+/*** @example* expect(deps.listEligibleUsers).toHaveBeenCalledWith({ limit: 50 });diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/server.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/server.test.tsindex a8506eac7fe..6a593a98709 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/server.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/server.test.ts@@ -158,4 +158,85 @@ describe('createReviewRuntimePrimitives', () => {},});});++ /**+ * @example+ * Production nightly reviews send the action kind as `type`; the proposal must+ * still project to a Daily Brief instead of failing with "no brief".+ */+ it('creates a proposal brief when the model names the action kind `type`', async () => {+ const writeDailyBrief = vi.fn().mockResolvedValue({ id: 'brief-1' });+ const service = createReviewRuntimePrimitives({+ agentId: 'agent-1',+ briefModel: {} as never,+ db: {} as unknown as LobeChatDatabase,+ localDate: '2026-10-10',+ proposalBriefWriter: { writeDailyBrief } as never,+ reviewWindowEnd: '2026-10-10T14:00:00.000Z',+ reviewWindowStart: '2026-10-09T14:00:00.000Z',+ skillDocumentService: {+ listSkills: vi.fn().mockResolvedValue([]),+ } as unknown as SkillManagementDocumentService,+ sourceId: 'nightly-review:user-1:agent-1:2026-10-10',+ userId: 'user-1',+ });++ const result = await service.createSelfReviewProposal?.(+ {+ actions: [+ {+ operation: {+ domain: 'skill',+ input: {+ bodyMarkdown: '# Release notes\n\nSteps...',+ description: 'Draft release notes from merged PRs.',+ name: 'release-notes',+ title: 'Release notes',+ },+ operation: 'create',+ },+ rationale: 'Repeated release-note workflow across topics.',+ target: { skillName: 'release-notes' },+ type: 'create_skill',+ },+ ],+ idempotencyKey: 'proposal-1',+ proposalKey: 'skill:release-notes',+ summary: 'Create a release-notes skill.',+ userId: 'user-1',+ },+ {},+ );++ expect(result).toMatchObject({ proposalId: 'brief-1' });+ expect(writeDailyBrief).toHaveBeenCalledTimes(1);+ });++ it('rejects proposal actions without a recognizable actionType with a recoverable error', async () => {+ const service = createReviewRuntimePrimitives({+ agentId: 'agent-1',+ briefModel: {} as never,+ db: {} as unknown as LobeChatDatabase,+ localDate: '2026-10-10',+ proposalBriefWriter: { writeDailyBrief: vi.fn() } as never,+ reviewWindowEnd: '2026-10-10T14:00:00.000Z',+ reviewWindowStart: '2026-10-09T14:00:00.000Z',+ skillDocumentService: { listSkills: vi.fn().mockResolvedValue([]) } as never,+ sourceId: 'nightly-review:user-1:agent-1:2026-10-10',+ userId: 'user-1',+ });++ await expect(+ service.createSelfReviewProposal?.(+ {+ actions: [{ target: { skillName: 'x' } }],+ idempotencyKey: 'proposal-2',+ proposalKey: 'skill:x',+ summary: 'Missing kind.',+ userId: 'user-1',+ },+ {},+ ),+ ).rejects.toThrow('actions[0] has no actionType');+ });});diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/topicQuota.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/topicQuota.test.tsnew file mode 100644index 00000000000..e9229d8d219--- /dev/null+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/topicQuota.test.ts@@ -0,0 +1,123 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AGENT_SIGNAL_DEFAULTS } from '../../../../constants';+import { claimNightlyReviewTopics } from '../topicQuota';++const sets = new Map<string, Set<string>>();++const service = vi.hoisted(() => ({ available: true, claimNightlyTopics: vi.fn() }));++vi.mock('@/server/services/redis', () => ({+ redisService: { agentSignal: { claimNightlyTopics: service.claimNightlyTopics } },+}));++/**+ * Applies the domain's claim semantics to an in-memory set, the way Redis runs the Lua+ * atomically: ids already in the night's set are admitted for free, new ids only while+ * under the limit.+ */+const claimInMemory = async (scope: {+ limit: number;+ localDate: string;+ topicIds: string[];+ userId: string;+}) => {+ if (!service.available) return undefined;+ const key = `${scope.userId}:${scope.localDate}`;+ const set = sets.get(key) ?? new Set<string>();+ sets.set(key, set);+ const admitted: string[] = [];+ for (const id of scope.topicIds) {+ if (set.has(id)) admitted.push(id);+ else if (set.size < scope.limit) {+ set.add(id);+ admitted.push(id);+ }+ }+ return admitted;+};++const topics = (prefix: string, count: number) =>+ Array.from({ length: count }, (_, index) => `${prefix}-${index}`);++describe('claimNightlyReviewTopics', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ sets.clear();+ service.available = true;+ service.claimNightlyTopics.mockImplementation(claimInMemory);+ });++ it('caps one user at 50 distinct topics per night across agents', async () => {+ expect(AGENT_SIGNAL_DEFAULTS.nightlyReviewTopicLimitPerUser).toBe(50);++ const first = await claimNightlyReviewTopics({+ localDate: '2026-10-11',+ topicIds: topics('agent-a', 30),+ userId: 'u1',+ });+ const second = await claimNightlyReviewTopics({+ localDate: '2026-10-11',+ topicIds: topics('agent-b', 30),+ userId: 'u1',+ });+ const third = await claimNightlyReviewTopics({+ localDate: '2026-10-11',+ topicIds: topics('agent-c', 5),+ userId: 'u1',+ });++ expect(first).toEqual({ admitted: topics('agent-a', 30) });+ expect(second).toEqual({ admitted: topics('agent-b', 20), reason: 'exhausted' });+ expect(third).toEqual({ admitted: [], reason: 'exhausted' });+ expect(service.claimNightlyTopics).toHaveBeenLastCalledWith({+ limit: 50,+ localDate: '2026-10-11',+ topicIds: topics('agent-c', 5),+ userId: 'u1',+ });+ });++ it('does not double-count topics on a replay or a second pass', async () => {+ const input = { localDate: '2026-10-11', topicIds: topics('t', 50), userId: 'u1' };++ await claimNightlyReviewTopics(input);+ const replay = await claimNightlyReviewTopics(input);++ expect(replay).toEqual({ admitted: topics('t', 50) });+ });++ it('keeps separate quotas per user and per night', async () => {+ await claimNightlyReviewTopics({+ localDate: '2026-10-11',+ topicIds: topics('t', 50),+ userId: 'u1',+ });++ await expect(+ claimNightlyReviewTopics({ localDate: '2026-10-12', topicIds: ['n'], userId: 'u1' }),+ ).resolves.toEqual({ admitted: ['n'] });+ await expect(+ claimNightlyReviewTopics({ localDate: '2026-10-11', topicIds: ['o'], userId: 'u2' }),+ ).resolves.toEqual({ admitted: ['o'] });+ });++ it('fails closed when Redis is not configured', async () => {+ service.available = false;++ await expect(+ claimNightlyReviewTopics({ localDate: '2026-10-11', topicIds: ['t'], userId: 'u1' }),+ ).resolves.toEqual({ admitted: [], reason: 'unavailable' });+ });++ it('fails closed without throwing when Redis errors', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ service.claimNightlyTopics.mockRejectedValueOnce(new Error('connection reset'));++ await expect(+ claimNightlyReviewTopics({ localDate: '2026-10-11', topicIds: ['t'], userId: 'u1' }),+ ).resolves.toEqual({ admitted: [], reason: 'unavailable' });+ consoleError.mockRestore();+ });+});diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/brief.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/brief.tsindex de7b7ae6f16..a39e2605aa3 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/brief.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/brief.ts@@ -1,3 +1,4 @@+import { getSelfReviewBriefDetails } from '@lobechat/agent-signal/brief';import { SpanStatusCode } from '@lobechat/observability-otel/api';import { tracer } from '@lobechat/observability-otel/modules/agent-signal';import type { BriefArtifactDocument, BriefMetadata } from '@lobechat/types';@@ -185,6 +186,35 @@ const findExistingProposalBrief = async ({});};+/**+ * Finds an unresolved ideas-only nightly brief already written for the same agent+ * and user-local date, so a replayed completion reuses it instead of adding a+ * duplicate. Mirrors {@link findExistingProposalBrief}'s bounded unresolved read.+ */+const findExistingIdeasBrief = async ({+ agentId,+ localDate,+ model,+ trigger,+}: {+ agentId: string;+ localDate: string;+ model: BriefModel;+ trigger: typeof NIGHTLY_REVIEW_BRIEF_TRIGGER;+}) => {+ const rows = await model.listUnresolvedByAgentAndTrigger({+ agentId,+ limit: 20,+ trigger,+ });++ return rows.find((row) => {+ const metadata = getNightlySelfReviewBriefMetadata(row.metadata);++ return metadata?.outcome === 'ideas' && metadata.localDate === localDate;+ });+};+const updateProposalMetadata = async (model: BriefModel,brief: BriefItem,@@ -386,6 +416,17 @@ const collectActionSummaries = (return summaries;};+/**+ * A proposal-level summary exists only when every proposed action carries the+ * same one (the `createSelfReviewProposal` tool stamps its summary on each+ * action). Distinct per-action summaries describe actions, not the proposal.+ */+const getSharedProposalSummary = (summaries: string[]) => {+ const unique = new Set(summaries);++ return unique.size === 1 ? [...unique][0] : undefined;+};+const collectBriefArtifactDocuments = ({ideas = [],proposal,@@ -505,12 +546,7 @@ export const createBriefSelfReviewService = () => ({if (!outcome) return;- const copy = createSelfReviewBriefText({- actionCounts,- actionSummaries: collectActionSummaries(input.result, input.plan),- outcome,- t: input.t,- });+ const actionSummaries = collectActionSummaries(input.result, input.plan);const proposal =outcome === 'proposal' && input.plan? buildSelfReviewProposalFromPlan({@@ -520,21 +556,32 @@ export const createBriefSelfReviewService = () => ({now: input.reviewWindowEnd,plan: input.plan,results: input.result.actions,+ summary: getSharedProposalSummary(actionSummaries.proposed),}): undefined;+ const metadata = createNightlySelfReviewBriefMetadata({+ actionCounts,+ evidenceRefs: input.evidenceRefs ?? [],+ input,+ outcome,+ proposal,+ });+ // Read the details back from the metadata the card will also read, so the+ // persisted text and the inline card describe the proposal identically.+ const copy = createSelfReviewBriefText({+ actionCounts,+ actionSummaries,+ details: getSelfReviewBriefDetails(metadata),+ outcome,+ t: input.t,+ });const artifacts = createBriefArtifacts({ ideas: input.ideas, proposal });return {...(proposal ? { actions: AGENT_SIGNAL_PROPOSAL_BRIEF_ACTIONS } : {}),agentId: input.agentId,...(artifacts ? { artifacts } : {}),- metadata: createNightlySelfReviewBriefMetadata({- actionCounts,- evidenceRefs: input.evidenceRefs ?? [],- input,- outcome,- proposal,- }),+ metadata,priority: copy.priority,summary: copy.summary,title: copy.title,@@ -555,7 +602,8 @@ export const createBriefSelfReviewService = () => ({* - `db` and `userId` belong to the source-event owner** Returns:- * - A writer whose `writeDailyBrief` method creates or refreshes proposal briefs+ * - A writer whose `writeDailyBrief` method creates or refreshes proposal briefs, and+ * reuses an existing ideas brief for the same agent + local date*/export const createServerSelfReviewBriefWriter = (db: LobeChatDatabase,@@ -585,7 +633,28 @@ export const createServerSelfReviewBriefWriter = (},async (span) => {try {- if (!incomingProposal || !brief.agentId) return model.create(brief);+ if (!brief.agentId) return model.create(brief);++ if (!incomingProposal) {+ const incomingMetadata = brief.metadata.agentSignal.nightlySelfReview;+ if (incomingMetadata.outcome !== 'ideas') return model.create(brief);++ // Ideas briefs are one per agent + local date: a replayed completion+ // reuses the existing row instead of writing a duplicate.+ const existingIdeasBrief = await findExistingIdeasBrief({+ agentId: brief.agentId,+ localDate: incomingMetadata.localDate,+ model,+ trigger: brief.trigger,+ });+ if (existingIdeasBrief) {+ span.setAttribute('agent.signal.brief.deduped', true);++ return existingIdeasBrief;+ }++ return model.create(brief);+ }const now = incomingProposal.updatedAt;const existingBrief = await findExistingProposalBrief({diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/briefText.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/briefText.tsindex e7880fbeea9..115a641738e 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/briefText.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/briefText.ts@@ -1,3 +1,9 @@+import {+ formatSelfReviewBriefSummary,+ formatSelfReviewBriefTitle,+ type SelfReviewBriefDetails,+} from '@lobechat/agent-signal/brief';+import home from '@/locales/default/home';/**@@ -42,6 +48,12 @@ export interface SelfReviewBriefTextInput {actionCounts: SelfReviewBriefTextActionCounts;/** User-visible action summaries grouped by outcome status. */actionSummaries: SelfReviewBriefTextActionSummaries;+ /**+ * Proposal actions or ideas read back from the brief metadata. When present,+ * the title names the main change and the summary describes it instead of+ * the generic count copy.+ */+ details?: SelfReviewBriefDetails;/** Coarse outcome selected by the projection service. */outcome: 'applied' | 'error' | 'ideas' | 'proposal';/** Locale-aware translator for the `home` namespace. Defaults to English resources. */@@ -106,6 +118,24 @@ const withDetails = (summary: string, heading: string, details: string[] = []) =export const createSelfReviewBriefText = (input: SelfReviewBriefTextInput): SelfReviewBriefText => {const t = input.t ?? defaultTranslate;+ const details = input.details;++ if (input.outcome === 'proposal' && details?.kind === 'proposal') {+ return {+ priority: 'normal',+ summary:+ formatSelfReviewBriefSummary(details, t) ||+ actionCountKey({+ count: input.actionCounts.proposed,+ pluralKey: 'brief.agentSignal.selfReview.proposal.summary_plural',+ singularKey: 'brief.agentSignal.selfReview.proposal.summary',+ t,+ }),+ title: formatSelfReviewBriefTitle(details, t),+ type: 'decision',+ };+ }+if (input.outcome === 'proposal') {const summary = actionCountKey({count: input.actionCounts.proposed,@@ -141,6 +171,16 @@ export const createSelfReviewBriefText = (input: SelfReviewBriefTextInput): Self};}+ if (input.outcome === 'ideas' && details?.kind === 'ideas') {+ return {+ priority: 'info',+ summary:+ formatSelfReviewBriefSummary(details, t) || t('brief.agentSignal.selfReview.ideas.summary'),+ title: formatSelfReviewBriefTitle(details, t),+ type: 'insight',+ };+ }+if (input.outcome === 'ideas') {return {priority: 'info',diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/briefTextTranslator.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/briefTextTranslator.tsnew file mode 100644index 00000000000..b4b13d82e9a--- /dev/null+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/briefTextTranslator.ts@@ -0,0 +1,26 @@+import { UserModel } from '@/database/models/user';+import type { LobeChatDatabase } from '@/database/type';+import { translation } from '@/libs/i18n/serverTranslation';++import type { SelfReviewBriefTextTranslator } from './briefText';++/**+ * Resolves the `home` namespace translator used to render persisted nightly+ * self-review Daily Brief text in the brief owner's response language.+ *+ * Use when:+ * - A server path projects a nightly self-review Daily Brief (in-run proposal+ * tool, or the completion-side ideas brief)+ *+ * Returns:+ * - A translator for the user's response language, defaulting to en-US+ */+export const resolveSelfReviewBriefTextTranslator = async (+ db: LobeChatDatabase,+ userId: string,+): Promise<SelfReviewBriefTextTranslator> => {+ const userInfo = await UserModel.getInfoForAIGeneration(db, userId);+ const { t } = await translation('home', userInfo.responseLanguage ?? 'en-US');++ return t;+};diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/collect.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/collect.tsindex 91083948bc3..f9e53336200 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/collect.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/collect.ts@@ -13,6 +13,7 @@ import {} from './intentPolicy';import type { SelfReviewProposalStatus } from './proposal';import { deriveSelfReviewSignals } from './signals';+import type { ClaimNightlyReviewTopics } from './topicQuota';const DEFAULT_MAX_TOPICS = 30;const DEFAULT_MAX_MANAGED_SKILLS = 20;@@ -443,6 +444,13 @@ export interface NightlyReviewTopicDigest extends Omit</** Read adapters used by the pure nightly review collector service. */export interface NightlyReviewReadAdapters {+ /**+ * Claims the ranked topics against the user's per-night topic quota. Refused topics are+ * dropped from the context. Applied only when the input carries a `localDate`.+ *+ * @default No quota (tests and evals)+ */+ claimTopics?: ClaimNightlyReviewTopics;/** Lists review-window document activity grouped by later server adapters. */listDocumentActivity?: (input: NightlyReviewReadInput) => Promise<DocumentActivityDigest>;/** Lists existing satisfaction judgements for this agent and review window. */@@ -527,6 +535,15 @@ export interface NightlyReviewContext {selfReviewSignals: SelfReviewSignal[];/** Ranked topic digests with evidence refs and no raw messages. */toolActivity: ToolActivityDigest[];+ /**+ * Outcome of the nightly topic quota claim, present when the quota refused any topic.+ * `admittedTopicCount` counts topics with an id that the quota let through.+ */+ topicQuota?: {+ admittedTopicCount: number;+ reason: 'exhausted' | 'unavailable';+ refusedTopicCount: number;+ };/** Ranked topic digests with evidence refs and no raw messages. */topics: NightlyReviewTopicDigest[];/** Stable user id owning the agent. */@@ -910,6 +927,49 @@ const getSelfFeedbackReviewCandidates = (receiptActivity: ReceiptActivityDigest)return rankSelfFeedbackCandidates(groupSelfFeedbackIntents(intents));};+const getTopicDigestId = (topic: NightlyReviewTopicDigest) => topic.topicId ?? topic.id;++/**+ * Keeps only the ranked topics the user's nightly topic quota admits.+ *+ * Rows without a topic id (loose messages) are not topics and pass through uncounted.+ */+const applyNightlyTopicQuota = async (+ rankedTopics: NightlyReviewTopicDigest[],+ claimTopics: ClaimNightlyReviewTopics | undefined,+ input: CollectNightlyReviewContextInput,+): Promise<{+ topicQuota?: NightlyReviewContext['topicQuota'];+ topics: NightlyReviewTopicDigest[];+}> => {+ const topicIds = rankedTopics.map(getTopicDigestId).filter((id): id is string => !!id);+ if (!claimTopics || !input.localDate || topicIds.length === 0) return { topics: rankedTopics };++ const claim = await claimTopics({+ localDate: input.localDate,+ topicIds,+ userId: input.userId,+ });+ const admitted = new Set(claim.admitted);+ const topics = rankedTopics.filter((topic) => {+ const id = getTopicDigestId(topic);++ return !id || admitted.has(id);+ });+ const admittedTopicCount = topicIds.filter((id) => admitted.has(id)).length;++ if (!claim.reason) return { topics };++ return {+ topicQuota: {+ admittedTopicCount,+ reason: claim.reason,+ refusedTopicCount: topicIds.length - admittedTopicCount,+ },+ topics,+ };+};+/*** Creates a pure nightly review collector service from digest read adapters.*@@ -988,7 +1048,15 @@ export const createSelfReviewContextService = (readAdapters.listProposalActivity?.(readInput) ??Promise.resolve(createEmptyProposalActivity()),]);- const topics = topicRows.map(normalizeTopic).sort(compareTopics).slice(0, maxTopics);+ const rankedTopics = topicRows+ .map(normalizeTopic)+ .sort(compareTopics)+ .slice(0, maxTopics);+ const { topicQuota, topics } = await applyNightlyTopicQuota(+ rankedTopics,+ readAdapters.claimTopics,+ input,+ );const selfReviewSignals = deriveSelfReviewSignals({documentActivity,feedbackActivity,@@ -1000,6 +1068,12 @@ export const createSelfReviewContextService = (span.setAttribute('agent.signal.nightly.raw_topic_count', topicRows.length);span.setAttribute('agent.signal.nightly.topic_count', topics.length);+ if (topicQuota) {+ span.setAttribute(+ 'agent.signal.nightly.topic_quota_refused_count',+ topicQuota.refusedTopicCount,+ );+ }span.setAttribute('agent.signal.nightly.high_signal_topic_count',topics.filter((topic) => topic.highSignalReasons.length > 0).length,@@ -1070,6 +1144,7 @@ export const createSelfReviewContextService = (relevantMemories: relevantMemories.slice(0, maxRelevantMemories),toolActivity,topics,+ ...(topicQuota ? { topicQuota } : {}),selfFeedbackCandidates,};} catch (error) {diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/handler.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/handler.tsindex e26d5a815d1..701dd21d48b 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/handler.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/handler.ts@@ -5,14 +5,32 @@ import { SpanStatusCode } from '@lobechat/observability-otel/api';import { tracer } from '@lobechat/observability-otel/modules/agent-signal';import { createAgentSignalSelfIterationPrompt } from '@lobechat/prompts';import { isNonEmptyString } from '@lobechat/utils';+import debug from 'debug';import type { LobeChatDatabase } from '@/database/type';+import { AGENT_SIGNAL_DEFAULTS } from '../../../constants';import { defineSourceHandler } from '../../../runtime/middleware';import { enqueueSelfIterationRun } from '../dispatch/enqueueSelfIterationRun';import { buildNightlyReviewSourceId, ReviewRunStatus } from '../types';import type { CollectNightlyReviewContextInput, NightlyReviewContext } from './collect';+const log = debug('lobe-server:agent-signal:nightly-review');++/**+ * Describes a refused nightly topic claim for skip details and logs.+ *+ * Before:+ * - `'exhausted'`+ *+ * After:+ * - `"Nightly review topic limit reached (50 topics per night)."`+ */+export const describeNightlyTopicQuotaDenial = (reason: 'exhausted' | 'unavailable') =>+ reason === 'exhausted'+ ? `Nightly review topic limit reached (${AGENT_SIGNAL_DEFAULTS.nightlyReviewTopicLimitPerUser} topics per night).`+ : 'Nightly review topic limit unavailable; skipped to stay within the limit.';+/*** Validated nightly review request payload consumed by the handler.*/@@ -49,6 +67,8 @@ export interface NightlyReviewSourceGuardInput extends NightlyReviewSourcePayloaexport interface NightlyReviewSourceHandlerResult extends Record<string, unknown> {/** Stable agent id being reviewed when payload validation succeeds. */agentId?: string;+ /** Human-readable skip detail, e.g. when the nightly topic quota is used up. */+ detail?: string;/** Stable guard key used for idempotency when payload validation succeeds. */guardKey?: string;/** User-local date in YYYY-MM-DD form when payload validation succeeds. */@@ -56,7 +76,8 @@ export interface NightlyReviewSourceHandlerResult extends Record<string, unknown/** Operation id of the enqueued background self-iteration run, when dispatched. */operationId?: string;/** Machine-readable skip reason for non-dispatched runs. */- reason?: 'gate_disabled' | 'invalid_payload';+ reason?:+ 'gate_disabled' | 'invalid_payload' | 'topic_quota_exhausted' | 'topic_quota_unavailable';/** Review window end as an ISO string when payload validation succeeds. */reviewWindowEnd?: string;/** Review window start as an ISO string when payload validation succeeds. */@@ -306,6 +327,29 @@ export const createNightlyReviewSourceHandler = (},);+ // Every topic this agent had was refused by the user's nightly topic quota: the night's+ // topic limit is used up by earlier agents, so this review is skipped.+ if (context.topicQuota && context.topicQuota.admittedTopicCount === 0) {+ const detail = describeNightlyTopicQuotaDenial(context.topicQuota.reason);+ log(+ 'skip nightly review user=%s agent=%s date=%s: %s',+ payload.userId,+ payload.agentId,+ payload.localDate,+ detail,+ );++ return {+ ...baseResult,+ detail,+ reason:+ context.topicQuota.reason === 'exhausted'+ ? 'topic_quota_exhausted'+ : 'topic_quota_unavailable',+ status: ReviewRunStatus.Skipped,+ };+ }+const prompt = createAgentSignalSelfIterationPrompt({agentId: payload.agentId,context,diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/proposal.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/proposal.tsindex 897db771aa8..6cbc19d50a3 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/proposal.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/proposal.ts@@ -219,6 +219,8 @@ export interface SelfReviewProposalMetadata {proposalKey: string;/** Current proposal lifecycle state. */status: SelfReviewProposalStatus;+ /** Reviewer-written one-line summary of what the proposal changes and why. */+ summary?: string;/** Proposal key or brief id that superseded this proposal. */supersededBy?: string;/** ISO timestamp for the last proposal lifecycle update. */@@ -238,10 +240,14 @@ export interface SelfReviewProposalBriefMetadata {};}+/**+ * Stored labels mirror the en-US `home` copy for each key (`brief.action.*`):+ * the card renders the localized key and only falls back to these strings.+ */export const AGENT_SIGNAL_PROPOSAL_BRIEF_ACTIONS = [- { key: 'approve', label: 'Apply', type: 'resolve' },+ { key: 'approve', label: 'Approve', type: 'resolve' },{ key: 'dismiss', label: 'Dismiss', type: 'resolve' },- { key: 'feedback', label: 'Request changes', type: 'comment' },+ { key: 'feedback', label: 'Feedback', type: 'comment' },] satisfies BriefAction[];/** Daily Brief actions for nightly self-review proposal cards. */@@ -308,6 +314,7 @@ const SelfReviewProposalMetadataSchema = zexpiresAt: z.string(),proposalKey: z.string(),status: z.enum(SELF_REVIEW_PROPOSAL_STATUSES),+ summary: z.string().optional(),supersededBy: z.string().optional(),updatedAt: z.string(),version: z.literal(SELF_REVIEW_PROPOSAL_VERSION),@@ -483,6 +490,8 @@ export interface BuildSelfReviewProposalFromPlanInput {plan: SelfReviewProposalPlan;/** Execution results that identify which actions stayed proposed. */results: ActionResult[];+ /** Reviewer-written proposal summary shown as the brief lead line. */+ summary?: string;}/**@@ -506,6 +515,7 @@ export const buildSelfReviewProposalFromPlan = ({now,plan,results,+ summary,}: BuildSelfReviewProposalFromPlanInput): SelfReviewProposalMetadata | undefined => {const proposedResultKeys = new Set(results@@ -560,6 +570,7 @@ export const buildSelfReviewProposalFromPlan = ({expiresAt: getNextProposalExpiry({ createdAt: now, now }),proposalKey,status: 'pending',+ ...(summary?.trim() ? { summary: summary.trim() } : {}),updatedAt: now,version: SELF_REVIEW_PROPOSAL_VERSION,};@@ -721,6 +732,7 @@ export const refreshSelfReviewProposal = ({evidenceWindowStart: incoming.evidenceWindowStart,expiresAt: getNextProposalExpiry({ createdAt: existing.createdAt, now }),status: 'pending',+ summary: incoming.summary ?? existing.summary,updatedAt: now,});diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.tsindex 4f24253a84c..e96c3de4847 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.ts@@ -30,6 +30,16 @@ const ACTIVITY_LOOKBACK_HOURS = 30;const HOUR_IN_MS = 60 * 60 * 1000;+/**+ * Hours added on each side of the night window for the SQL local-hour prefilter.+ *+ * PostgreSQL resolves timezones with its own tzdata build, which can lag `Intl` by an offset+ * change. Widening the SQL window keeps it a strict superset of the exact `Intl` window that+ * {@link getLocalNightWindow} re-applies, so a tzdata disagreement can cost a skipped row in this+ * page but never a missed review.+ */+const SQL_PREFILTER_SLACK_HOURS = 1;+/** Active agent target returned by the nightly review scheduler data boundary. */export interface NightlyReviewAgentTarget {/** Agent id that should receive one nightly review source event. */@@ -62,6 +72,19 @@ export interface ListNightlyReviewEligibleUsersInput {cursor?: NightlyReviewScheduleCursor;/** Maximum eligible users to return. */limit?: number;+ /**+ * Coarse local-hour prefilter pushed into the user scan.+ *+ * Always a superset of the exact night window; the service re-checks the exact window after.+ */+ localHourWindow?: {+ /** UTC instant whose local hour is evaluated. */+ at: Date;+ /** Exclusive local hour upper bound. */+ endHourExclusive: number;+ /** Inclusive local hour lower bound. */+ startHour: number;+ };/** Optional allowlist for targeted backfills or tests. */whitelist?: string[];}@@ -162,11 +185,13 @@ export interface NightlyReviewScheduleService {* Expects:* - `limit` is a positive, externally bounded page size* - The adapter sorts users by `createdAt, id`- * - `requestedAt` narrows the scan to users with recent activity;- * {@link dispatchNightlyReviewForUser} remains the only authority on the local window+ * - `requestedAt` narrows the scan to users with recent activity whose local clock is inside+ * the night window; {@link dispatchNightlyReviewForUser} re-checks the window as a second gate** Returns:- * - The current users and a next cursor only when the page is full+ * - Only users inside their night window (the adapter already dropped users whose Labs →+ * Self-evolving switch is off), and a next cursor whenever the scanned page was full (even if+ * every scanned user was filtered out)*/listEligibleUsersPage: (options: ListNightlyReviewEligibleUsersPageOptions,@@ -316,24 +341,43 @@ export const createSelfReviewScheduleService = (},async (span) => {try {- const users = await adapters.listEligibleUsers({+ const { requestedAt } = options;+ const scannedUsers = await adapters.listEligibleUsers({...options,// Without `requestedAt` the caller is a test or a legacy path; fall back to the// unnarrowed scan rather than inventing a floor from wall-clock time.- ...(options.requestedAt+ ...(requestedAt? {activeSince: new Date(- options.requestedAt.getTime() - ACTIVITY_LOOKBACK_HOURS * HOUR_IN_MS,+ requestedAt.getTime() - ACTIVITY_LOOKBACK_HOURS * HOUR_IN_MS,),+ localHourWindow: {+ at: requestedAt,+ endHourExclusive: NIGHT_WINDOW_END_HOUR_EXCLUSIVE + SQL_PREFILTER_SLACK_HOURS,+ startHour: NIGHT_WINDOW_START_HOUR - SQL_PREFILTER_SLACK_HOURS,+ },}: {}),});- const lastUser = users.at(-1);+ // The cursor follows the scanned rows, not the filtered ones: a page whose users are+ // all filtered out must still hand the traversal on to the next page.+ const lastUser = scannedUsers.at(-1);const nextCursor =- users.length === options.limit && lastUser+ scannedUsers.length === options.limit && lastUser? { createdAt: lastUser.createdAt, id: lastUser.id }: undefined;+ const users = requestedAt+ ? scannedUsers.filter(+ (user) => getLocalNightWindow(requestedAt, user.timezone).withinWindow,+ )+ : scannedUsers;++ span.setAttribute('agent.signal.nightly.scanned_user_count', scannedUsers.length);+ span.setAttribute(+ 'agent.signal.nightly.outside_window_count',+ scannedUsers.length - users.length,+ );span.setAttribute('agent.signal.nightly.user_count', users.length);span.setAttribute('agent.signal.nightly.has_next_page', Boolean(nextCursor));span.setStatus({ code: SpanStatusCode.OK });@@ -394,6 +438,7 @@ export const createServerNightlyReviewScheduleService = (activeSince: input?.activeSince,cursor: input?.cursor,limit: input?.limit,+ localHourWindow: input?.localHourWindow,whitelist: input?.whitelist,}),});diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/server.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/server.tsindex 6214191e255..5eebd7ab09a 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/server.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/server.ts@@ -60,6 +60,7 @@ import {listNightlyReceiptLocalDates,resolveReviewedLocalDate,} from './receiptActivity';+import { claimNightlyReviewTopics } from './topicQuota';interface ProposalBriefReader {listUnresolvedByAgentAndTrigger: (options: {@@ -189,6 +190,55 @@ const getProposalActionSnapshotInput = (action: Record<string, unknown>) => {};};+/** Action types a `createSelfReviewProposal` action may carry. */+export const SELF_REVIEW_PROPOSAL_ACTION_TYPES = [+ 'create_skill',+ 'refine_skill',+ 'consolidate_skill',+ 'refine_prompt',+ 'write_memory',+ 'proposal_only',+] as const;++const SELF_REVIEW_PROPOSAL_ACTION_TYPE_ALIASES: Record<string, string> = {+ record_idea: 'proposal_only',+};++/**+ * Normalizes model-authored proposal actions before projection.+ *+ * Models routinely send the action kind as `type` (and the legacy prompt named+ * ideas `record_idea`); the projection only reads `actionType`, so those+ * proposals silently projected to nothing and every nightly review ended+ * without a brief. Unknown action types fail loudly so the model can retry.+ */+export const normalizeSelfReviewProposalInput = (+ input: CreateSelfReviewProposalInput,+): CreateSelfReviewProposalInput => {+ if (!Array.isArray(input.actions)) return input;++ const actions = input.actions.map((rawAction, index) => {+ const action = toRecordOrEmpty(rawAction);+ const rawType = pickTrimmedString(action.actionType) ?? pickTrimmedString(action.type);+ const actionType = rawType+ ? (SELF_REVIEW_PROPOSAL_ACTION_TYPE_ALIASES[rawType] ?? rawType)+ : undefined;++ if (+ !actionType ||+ !(SELF_REVIEW_PROPOSAL_ACTION_TYPES as readonly string[]).includes(actionType)+ ) {+ throw new Error(+ `actions[${index}] has ${rawType ? `unsupported actionType "${rawType}"` : 'no actionType'}; expected one of: ${SELF_REVIEW_PROPOSAL_ACTION_TYPES.join(', ')}.`,+ );+ }++ return { ...action, actionType };+ });++ return { ...input, actions } as CreateSelfReviewProposalInput;+};+const withCompleteProposalSnapshots = async ({agentId,input,@@ -514,7 +564,9 @@ export const createReviewRuntimePrimitives = (});},createSelfReviewProposal: async (rawInput) => {- const input = rawInput as unknown as CreateSelfReviewProposalInput;+ const input = normalizeSelfReviewProposalInput(+ rawInput as unknown as CreateSelfReviewProposalInput,+ );const projectionInput = await withCompleteProposalSnapshots({agentId,input,@@ -542,7 +594,11 @@ export const createReviewRuntimePrimitives = (userId,});- if (!brief) throw new Error('Self-review proposal projection produced no brief');+ if (!brief) {+ throw new Error(+ `Self-review proposal has no applicable action. Each action needs actionType set to one of: ${SELF_REVIEW_PROPOSAL_ACTION_TYPES.join(', ')}.`,+ );+ }const result = await proposalBriefWriter.writeDailyBrief(brief);@@ -791,6 +847,9 @@ export const createServerSelfReviewPolicyOptions = ({const briefModel = new BriefModel(db, userId, workspaceId);const skillDocumentService = new SkillManagementDocumentService(db, userId, workspaceId);const collector = createSelfReviewContextService({+ // One Redis set per user and local review date bounds the topics every agent's review+ // (and the nightly expertise pass) may process that night.+ claimTopics: claimNightlyReviewTopics,listDocumentActivity: async ({ agentId: targetAgentId, reviewWindowEnd, reviewWindowStart }) =>tracer.startActiveSpan('agent_signal.nightly_review.collector.list_document_activity',diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/topicQuota.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/topicQuota.tsnew file mode 100644index 00000000000..e9c1a5004e1--- /dev/null+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/topicQuota.ts@@ -0,0 +1,85 @@+import debug from 'debug';++import { redisService } from '@/server/services/redis';++import { AGENT_SIGNAL_DEFAULTS } from '../../../constants';++const log = debug('lobe-server:agent-signal:nightly-topic-quota');++/** Input for claiming nightly review topics against the per-user nightly quota. */+export interface ClaimNightlyReviewTopicsInput {+ /** User-local review date (`YYYY-MM-DD`) shared by every agent reviewed that night. */+ localDate: string;+ /** Candidate topic ids, in priority order. Duplicates are ignored. */+ topicIds: string[];+ /** User whose nightly review is being bounded. */+ userId: string;+}++/** Outcome of one nightly topic claim. */+export interface ClaimNightlyReviewTopicsResult {+ /** Topic ids that may be processed: already counted for this night, or newly counted. */+ admitted: string[];+ /** Why some candidates were refused, when any were. */+ reason?: 'exhausted' | 'unavailable';+}++/** Claims topics against the per-user nightly quota. Injected so collectors stay pure. */+export type ClaimNightlyReviewTopics = (+ input: ClaimNightlyReviewTopicsInput,+) => Promise<ClaimNightlyReviewTopicsResult>;++/**+ * Claims topics against the user's nightly review quota in Redis.+ *+ * Use when:+ * - A nightly review is about to feed topics to an agent's review context, or the nightly+ * expertise pass is about to ingest topics+ *+ * Expects:+ * - Every caller for the same user and night passes the same `localDate`+ *+ * Returns:+ * - The admitted subset in input order; `reason: 'exhausted'` when the night's+ * {@link AGENT_SIGNAL_DEFAULTS.nightlyReviewTopicLimitPerUser} distinct topics are used up+ * - Nothing admitted with `reason: 'unavailable'` when Redis is missing or errors: nightly+ * review is optional work billed to the user, so an unenforceable cap skips it+ */+export const claimNightlyReviewTopics: ClaimNightlyReviewTopics = async (input) => {+ const topicIds = [...new Set(input.topicIds.filter(Boolean))];+ if (topicIds.length === 0) return { admitted: [] };++ try {+ const admitted = await redisService.agentSignal.claimNightlyTopics({+ limit: AGENT_SIGNAL_DEFAULTS.nightlyReviewTopicLimitPerUser,+ localDate: input.localDate,+ topicIds,+ userId: input.userId,+ });++ if (!admitted) {+ log('nightly topic quota unavailable user=%s date=%s', input.userId, input.localDate);+ return { admitted: [], reason: 'unavailable' };+ }++ if (admitted.length < topicIds.length) {+ log(+ 'nightly topic quota exhausted user=%s date=%s admitted=%d refused=%d limit=%d',+ input.userId,+ input.localDate,+ admitted.length,+ topicIds.length - admitted.length,+ AGENT_SIGNAL_DEFAULTS.nightlyReviewTopicLimitPerUser,+ );+ return { admitted, reason: 'exhausted' };+ }++ return { admitted };+ } catch (error) {+ console.error('[AgentSignal] Failed to claim nightly review topics, skipping:', {+ error,+ userId: input.userId,+ });+ return { admitted: [], reason: 'unavailable' };+ }+};diff --git a/apps/server/src/services/agentSignal/services/selfIteration/server.ts b/apps/server/src/services/agentSignal/services/selfIteration/server.tsindex d38a601ffc2..57e52560a7a 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/server.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/server.ts@@ -55,7 +55,7 @@ export interface CreateServerSelfIterationPolicyOptions {* - `reviewContextModel` is scoped to the current user** Returns:- * - `true` only when feature gate, workflow agent scope, and agent-level DB gate all pass+ * - `true` only when feature gate, workflow agent scope, and agent ownership all pass*/export const canRunSelfIterationSource = async (input: {agentId: string;diff --git a/apps/server/src/services/agentSignal/sources/__tests__/index.test.ts b/apps/server/src/services/agentSignal/sources/__tests__/index.test.tsindex 4382e475c1a..b26837e1af9 100644--- a/apps/server/src/services/agentSignal/sources/__tests__/index.test.ts+++ b/apps/server/src/services/agentSignal/sources/__tests__/index.test.ts@@ -87,6 +87,22 @@ describe('agent signal sources', () => {expect(built.payload.selfIteration).toEqual(selfIteration);});+ it('keeps the conversation-root marker on agent user messages through normalization', async () => {+ const { buildSource } = await import('..');++ const build = (payload: Record<string, unknown>) =>+ buildSource({+ payload: { agentId: 'agent_1', message: 'Hi', messageId: 'user_1', ...payload },+ scopeKey: 'topic:topic_1',+ sourceId: 'user_1',+ sourceType: 'agent.user.message',+ timestamp: 1_710_000_000_000,+ });++ expect(build({ isConversationRoot: true }).payload.isConversationRoot).toBe(true);+ expect(build({}).payload).not.toHaveProperty('isConversationRoot');+ });+it('preserves agent user message display and trigger anchors through normalization', async () => {const { buildSource } = await import('..');diff --git a/apps/server/src/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts b/apps/server/src/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.tsindex 46aa6c58e14..77ef58271a5 100644--- a/apps/server/src/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts+++ b/apps/server/src/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts@@ -83,6 +83,7 @@ describe('resolveClientRuntimeCompleteFeedbackSource', () => {payload: {agentId: 'client-agent',anchorMessageId: assistantMessageId,+ isConversationRoot: true,message: 'Please remember this workflow.',messageId: parentMessageId,threadId: 'client-thread',diff --git a/apps/server/src/services/agentSignal/sources/hydration/__tests__/clientRuntimeStart.test.ts b/apps/server/src/services/agentSignal/sources/hydration/__tests__/clientRuntimeStart.test.tsindex 1b2d2cfc007..2d538aae85b 100644--- a/apps/server/src/services/agentSignal/sources/hydration/__tests__/clientRuntimeStart.test.ts+++ b/apps/server/src/services/agentSignal/sources/hydration/__tests__/clientRuntimeStart.test.ts@@ -109,6 +109,53 @@ describe('resolveClientRuntimeStartFeedbackSource', { timeout: 15_000 }, () => {expect(result.source?.payload.serializedContext).toBeUndefined();});+ /**+ * @example+ * A user message that opens its topic is marked as the conversation root; a reply is not.+ */+ it('marks only a parentless, threadless user message as the conversation root', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;+ const topicId = `topic_${uuid()}`;+ const rootId = `msg_${uuid()}`;+ const assistantId = `msg_${uuid()}`;+ const replyId = `msg_${uuid()}`;++ await db.insert(users).values({ id: userId });+ await db.insert(topics).values({ id: topicId, title: 'Root Topic', userId });+ await db.insert(messages).values([+ { content: 'Remember that I use pnpm.', id: rootId, role: 'user', topicId, userId },+ {+ content: 'Noted.',+ id: assistantId,+ parentId: rootId,+ role: 'assistant',+ topicId,+ userId,+ },+ {+ content: 'Remember that I also use bun.',+ id: replyId,+ parentId: assistantId,+ role: 'user',+ topicId,+ userId,+ },+ ]);++ const root = await resolveClientRuntimeStartFeedbackSource(+ createStartSource({ parentMessageId: rootId, topicId }),+ { db, userId },+ );+ const reply = await resolveClientRuntimeStartFeedbackSource(+ createStartSource({ parentMessageId: replyId, topicId }),+ { db, userId },+ );++ expect(root.source?.payload.isConversationRoot).toBe(true);+ expect(reply.source?.payload.isConversationRoot).toBeUndefined();+ });+/*** @example* client.runtime.start({ triggerMessageId }) keeps the explicit trigger instead of replacing it.diff --git a/apps/server/src/services/agentSignal/sources/hydration/clientRuntimeComplete.ts b/apps/server/src/services/agentSignal/sources/hydration/clientRuntimeComplete.tsindex 0bf1d1002fe..311691bbcd5 100644--- a/apps/server/src/services/agentSignal/sources/hydration/clientRuntimeComplete.ts+++ b/apps/server/src/services/agentSignal/sources/hydration/clientRuntimeComplete.ts@@ -146,6 +146,7 @@ export const resolveClientRuntimeCompleteFeedbackSource = async (payload: {agentId: parentMessage.agentId ?? assistantMessage.agentId ?? sourceEvent.payload.agentId,anchorMessageId: sourceEvent.payload.anchorMessageId ?? assistantMessage.id,+ ...(!parentMessage.parentId && !parentMessage.threadId ? { isConversationRoot: true } : {}),message: parentMessage.content,messageId: parentMessage.id,threadId:diff --git a/apps/server/src/services/agentSignal/sources/hydration/clientRuntimeStart.ts b/apps/server/src/services/agentSignal/sources/hydration/clientRuntimeStart.tsindex 1473eaba224..b628a24be9e 100644--- a/apps/server/src/services/agentSignal/sources/hydration/clientRuntimeStart.ts+++ b/apps/server/src/services/agentSignal/sources/hydration/clientRuntimeStart.ts@@ -9,10 +9,7 @@ import type { LobeChatDatabase } from '@/database/type';/** Reason a `client.runtime.start` event could not become a feedback source. */export type ClientRuntimeStartHydrationSkipReason =- | 'empty-content'- | 'message-not-found'- | 'missing-parent-message-id'- | 'non-user-parent';+ 'empty-content' | 'message-not-found' | 'missing-parent-message-id' | 'non-user-parent';/** Diagnostic emitted while hydrating a client runtime-start source. */export interface ClientRuntimeStartHydrationDiagnostic {@@ -84,6 +81,7 @@ export const resolveClientRuntimeStartFeedbackSource = async (source: {payload: {agentId: parentMessage.agentId ?? sourceEvent.payload.agentId,+ ...(!parentMessage.parentId && !parentMessage.threadId ? { isConversationRoot: true } : {}),message: parentMessage.content,messageId: parentMessage.id,threadId: parentMessage.threadId ?? sourceEvent.payload.threadId,diff --git a/apps/server/src/services/agentSignal/sources/renderers/agentUserMessage.ts b/apps/server/src/services/agentSignal/sources/renderers/agentUserMessage.tsindex 6920b347965..a0f7ff4cb0f 100644--- a/apps/server/src/services/agentSignal/sources/renderers/agentUserMessage.ts+++ b/apps/server/src/services/agentSignal/sources/renderers/agentUserMessage.ts@@ -27,6 +27,9 @@ export const agentUserMessageRenderer = {intent === 'skill',): undefined,+ // Lets the feedback classifier skip a topic's first message; dropping it here+ // made the conversation-root pre-filter a no-op on every path.+ ...(input.payload.isConversationRoot === true ? { isConversationRoot: true } : {}),memoryPayload:input.payload.memoryPayload && typeof input.payload.memoryPayload === 'object'? (input.payload.memoryPayload as Record<string, unknown>)diff --git a/apps/server/src/services/agentSignal/store/adapters/redis/receiptStore.ts b/apps/server/src/services/agentSignal/store/adapters/redis/receiptStore.tsindex 2ef3da9eba5..a6655c13c01 100644--- a/apps/server/src/services/agentSignal/store/adapters/redis/receiptStore.ts+++ b/apps/server/src/services/agentSignal/store/adapters/redis/receiptStore.ts@@ -37,7 +37,6 @@ const parseReceiptTarget = (value?: string): AgentSignalReceipt['target'] | undeconst target = JSON.parse(value) as Record<string, unknown>;if (target.type !== 'memory' && target.type !== 'skill') return;- if (typeof target.title !== 'string' || target.title.length === 0) return;return {...(typeof target.agentDocumentId === 'string' && target.agentDocumentId.length > 0@@ -55,10 +54,18 @@ const parseReceiptTarget = (value?: string): AgentSignalReceipt['target'] | unde...(target.type === 'memory' && isMemoryLayer(target.memoryLayer)? { memoryLayer: target.memoryLayer }: {}),+ ...(target.type === 'memory' &&+ (target.operation === 'create' ||+ target.operation === 'remove' ||+ target.operation === 'update')+ ? { operation: target.operation }+ : {}),...(typeof target.summary === 'string' && target.summary.length > 0? { summary: target.summary }: {}),- title: target.title,+ ...(typeof target.title === 'string' && target.title.length > 0+ ? { title: target.title }+ : {}),type: target.type,};} catch {diff --git a/apps/server/src/services/agentSignal/triggerRateLimit.ts b/apps/server/src/services/agentSignal/triggerRateLimit.tsnew file mode 100644index 00000000000..6914a64b6a9--- /dev/null+++ b/apps/server/src/services/agentSignal/triggerRateLimit.ts@@ -0,0 +1,46 @@+import { TRPCError } from '@trpc/server';++import { redisService } from '@/server/services/redis';++/**+ * Manual Agent Signal triggers one user may enqueue per rolling-hour bucket.+ *+ * `triggerSourceEvent` exists for CLI / local testing; every accepted call can start a+ * model-backed workflow (a nightly review is a full agent run), so it is bounded per user.+ */+export const AGENT_SIGNAL_TRIGGER_RATE_LIMIT_PER_HOUR = 10;++/**+ * Consumes one manual trigger from the user's hourly budget.+ *+ * Use when:+ * - `triggerSourceEvent` (tRPC or REST) is about to synthesise and enqueue a source event+ *+ * Expects:+ * - `userId` comes from the authenticated context+ *+ * Returns:+ * - `true` when the call is within budget; `false` once the hourly budget is spent+ * - `true` when Redis is not configured: Agent Signal dedupe and review guards cannot run+ * without Redis either, so there is no model spend for this limit to protect+ */+export const consumeAgentSignalTriggerQuota = async (userId: string): Promise<boolean> => {+ const count = await redisService.agentSignal.countManualTrigger(userId);+ if (count === undefined) return true;++ return count <= AGENT_SIGNAL_TRIGGER_RATE_LIMIT_PER_HOUR;+};++/**+ * Rejects a manual trigger once the user's hourly budget is spent.+ *+ * Throws a `TOO_MANY_REQUESTS` {@link TRPCError}; the REST controller maps it to HTTP 429.+ */+export const assertAgentSignalTriggerRateLimit = async (userId: string) => {+ if (await consumeAgentSignalTriggerQuota(userId)) return;++ throw new TRPCError({+ code: 'TOO_MANY_REQUESTS',+ message: `Agent Signal trigger limit reached (${AGENT_SIGNAL_TRIGGER_RATE_LIMIT_PER_HOUR} per hour)`,+ });+};diff --git a/apps/server/src/services/agentSignal/triggerSourceEvent.ts b/apps/server/src/services/agentSignal/triggerSourceEvent.tsindex edec490da10..d37d43bd910 100644--- a/apps/server/src/services/agentSignal/triggerSourceEvent.ts+++ b/apps/server/src/services/agentSignal/triggerSourceEvent.ts@@ -2,6 +2,7 @@ import {AGENT_SIGNAL_SOURCE_TYPES,type AgentSignalSourcePayloadMap,} from '@lobechat/agent-signal/source';+import { TRPCError } from '@trpc/server';import type { AgentSignalSourceEventInput } from './emitter';import {@@ -35,17 +36,47 @@ export const isAgentSignalTriggerSourceType = (value: string,): value is AgentSignalTriggerSourceType => TRIGGER_SOURCE_TYPE_SET.has(value);+/**+ * Payload keys that feed the nightly review guard key (`nightly-review:{userId}:{agentId}:{localDate}`).+ *+ * The handler only runs a review whose `sourceId` equals that key and then claims it once per+ * day, so a caller who may pick `localDate` (or the source id) mints a fresh guard key per call and+ * gets an unbounded number of model-backed reviews.+ */+const NIGHTLY_REVIEW_GUARD_OVERRIDE_KEYS = ['agentId', 'localDate'] as const;++/**+ * Whether manual triggers may override nightly-review guard inputs by default.+ *+ * Only local development (`NODE_ENV=development`) may pin `localDate` / `sourceId` to replay a+ * specific day; every deployed environment derives them server-side.+ */+const isNightlyReviewGuardOverrideAllowedByDefault = () => process.env.NODE_ENV === 'development';+/** One manual-trigger build request, before defaults are filled in. */export interface BuildTriggerSourceEventInput {/** Agent the signal targets. Required for every source type except runtime debug ones. */agentId?: string;+ /**+ * Lets `payloadOverride.localDate` / `payloadOverride.agentId` and `sourceId` change the nightly+ * review guard key. Ignored for every other source type.+ *+ * @default `true` only when `NODE_ENV === 'development'`+ */+ allowNightlyReviewGuardOverride?: boolean;/** Injected clock, overridable for deterministic tests. Defaults to `Date.now()`. */now?: number;- /** Shallow override merged over the derived default payload (`userId` is ignored). */+ /**+ * Shallow override merged over the derived default payload. `userId` is always ignored; nightly+ * review guard inputs are ignored unless {@link allowNightlyReviewGuardOverride} is set.+ */payloadOverride?: Record<string, unknown>;/** Explicit scope key. Defaults to payload-derived routing in `createSourceEvent`. */scopeKey?: string;- /** Stable dedupe id. Defaults to a source-type specific deterministic id. */+ /**+ * Stable dedupe id. Defaults to a source-type specific deterministic id. Ignored for nightly+ * review unless {@link allowNightlyReviewGuardOverride} is set.+ */sourceId?: string;sourceType: AgentSignalTriggerSourceType;/** Event timestamp in ms. Defaults to `now` inside `createSourceEvent`. */@@ -66,6 +97,46 @@ const requireAgentId = (sourceType: AgentSignalTriggerSourceType, agentId?: strireturn agentId;};+/**+ * Resolves the agent id the enqueue path must authorize for one manual trigger.+ *+ * Use when:+ * - A trigger caller passes the built event to `enqueueAgentSignalSourceEvent`, which only checks+ * `context.agentId` with `assertAgentUsableBy`+ *+ * Expects:+ * - `event` comes from {@link buildTriggerSourceEvent}; `payloadOverride.agentId` may have put an+ * agent id in the payload that the request's `agentId` never named+ *+ * Returns:+ * - The payload agent id (or the requested one when the payload has none), so the agent the+ * handlers act on is the one that gets authorized+ *+ * Throws:+ * - `BAD_REQUEST` when the payload agent id is not a non-empty string or differs from `agentId`+ */+export const resolveTriggerSourceEventAgentId = (+ event: Pick<AgentSignalSourceEventInput<AgentSignalTriggerSourceType>, 'payload'>,+ requestedAgentId?: string,+): string | undefined => {+ const payloadAgentId = (event.payload as Record<string, unknown>).agentId;++ if (payloadAgentId === undefined || payloadAgentId === null) return requestedAgentId;++ if (typeof payloadAgentId !== 'string' || payloadAgentId.length === 0) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'payload agentId must be a string' });+ }++ if (requestedAgentId && payloadAgentId !== requestedAgentId) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'payload agentId must match the requested agentId',+ });+ }++ return payloadAgentId;+};+/*** Builds a fully-formed source event input for one manually triggered source type.*@@ -92,6 +163,17 @@ export const buildTriggerSourceEvent = (const override = { ...input.payloadOverride };delete override.userId;+ const isNightlyReview = sourceType === AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested;+ const allowGuardOverride =+ input.allowNightlyReviewGuardOverride ?? isNightlyReviewGuardOverrideAllowedByDefault();+ const lockNightlyReviewGuard = isNightlyReview && !allowGuardOverride;++ // The guard key is derived server-side from the authenticated user, the requested agent and the+ // current date, so repeated manual triggers for one agent collapse onto one review per day.+ if (lockNightlyReviewGuard) {+ for (const key of NIGHTLY_REVIEW_GUARD_OVERRIDE_KEYS) delete override[key];+ }+let payload: AgentSignalSourcePayloadMap[AgentSignalTriggerSourceType];let defaultSourceId: string;@@ -231,7 +313,7 @@ export const buildTriggerSourceEvent = (return {payload: mergedPayload,scopeKey: input.scopeKey,- sourceId: input.sourceId ?? defaultSourceId,+ sourceId: lockNightlyReviewGuard ? defaultSourceId : (input.sourceId ?? defaultSourceId),sourceType,timestamp: input.timestamp,} as AgentSignalSourceEventInput<AgentSignalTriggerSourceType>;diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.tsindex 3d1d234645b..55ccdf88216 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts@@ -7,6 +7,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { createServerAgentToolsEngine } from '@/server/modules/Mecha';import { AgentRuntimeService } from '@/server/services/agentRuntime';+import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';import { AiAgentService } from '../index';@@ -16,6 +17,7 @@ const {mockGetBuiltinAgent,mockGetInfoForAIGeneration,mockGetModelMetadata,+ mockGetUserPreference,mockIsAgentSignalEnabledForUser,mockMessageCreate,mockMessageQuery,@@ -27,6 +29,7 @@ const {mockGetBuiltinAgent: vi.fn(),mockGetInfoForAIGeneration: vi.fn(),mockGetModelMetadata: vi.fn(),+ mockGetUserPreference: vi.fn(),mockIsAgentSignalEnabledForUser: vi.fn(),mockMessageCreate: vi.fn(),mockMessageQuery: vi.fn(),@@ -85,18 +88,11 @@ vi.mock('@/server/services/agent', () => ({}),}));-vi.mock('@/server/services/agentSignal/featureGate', () => ({+// Keep the real per-agent opt-in rule so these tests exercise the same Lobe AI+// default-on / opt-out logic production uses; only the user rollout is mocked.+vi.mock('@/server/services/agentSignal/featureGate', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),isAgentSignalEnabledForUser: mockIsAgentSignalEnabledForUser,- isLobeAiAgentSlug: (slug?: string | null) => slug === 'inbox',- resolveAgentSelfIterationCapability: ({- agentSelfIterationEnabled,- isAgentSelfIterationFeatureEnabled,- isLobeAiAgent,- }: {- agentSelfIterationEnabled?: boolean;- isAgentSelfIterationFeatureEnabled: boolean;- isLobeAiAgent: boolean;- }) => isAgentSelfIterationFeatureEnabled && (isLobeAiAgent || agentSelfIterationEnabled === true),}));vi.mock('@/server/services/agentSignal', () => ({@@ -152,8 +148,9 @@ vi.mock('@/database/models/thread', () => ({}));vi.mock('@/database/models/user', () => ({- UserModel: {- getInfoForAIGeneration: mockGetInfoForAIGeneration,+ UserModel: class {+ static getInfoForAIGeneration = mockGetInfoForAIGeneration;+ getUserPreference = mockGetUserPreference;},}));@@ -564,7 +561,32 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {expect(callArgs.toolSet.sourceMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBe('builtin');});- it('should not inject self-feedback intent tool for custom agents without agent self-iteration', async () => {+ /**+ * The Labs → Self-evolving switch is the user gate. The run already reads `users.preference`+ * for expertise injection, so tool exposure must reuse that row instead of reading it again.+ */+ it('decides the self-feedback intent tool from the preference the run already loaded', async () => {+ mockGetUserPreference.mockResolvedValue({ lab: { enableSelfLearning: true } });+ mockGetAgentConfig.mockResolvedValue({+ chatConfig: {},+ id: 'agent-inbox',+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ slug: 'inbox',+ systemRole: '',+ });++ await service.execAgent({ agentId: 'agent-inbox', prompt: 'Hello' });++ expect(mockIsAgentSignalEnabledForUser).toHaveBeenCalledWith(expect.anything(), userId, {+ preference: { lab: { enableSelfLearning: true } },+ });+ expect(mockGetUserPreference).toHaveBeenCalledOnce();+ });++ // No per-agent switch: Labs → Self-evolving covers every agent.+ it('should inject self-feedback intent tool for custom agents without any per-agent setting', async () => {mockGetAgentConfig.mockResolvedValue({chatConfig: {},id: 'agent-custom',@@ -580,10 +602,72 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {prompt: 'Hello',});+ const callArgs = mockCreateOperation.mock.calls[0][0];+ expect(callArgs.toolSet.enabledToolIds).toContain(SELF_FEEDBACK_INTENT_IDENTIFIER);+ expect(callArgs.toolSet.manifestMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBeDefined();+ });++ it('should not inject self-feedback intent tool for any agent when Labs Self-evolving is off', async () => {+ mockIsAgentSignalEnabledForUser.mockResolvedValue(false);+ mockGetAgentConfig.mockResolvedValue({+ chatConfig: { selfIteration: { enabled: true } },+ id: 'agent-custom',+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ slug: 'custom-agent',+ systemRole: '',+ });++ await service.execAgent({ agentId: 'agent-custom', prompt: 'Hello' });+const callArgs = mockCreateOperation.mock.calls[0][0];expect(callArgs.toolSet.enabledToolIds).not.toContain(SELF_FEEDBACK_INTENT_IDENTIFIER);expect(callArgs.toolSet.manifestMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBeUndefined();- expect(callArgs.toolSet.sourceMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBeUndefined();+ });++ // `getAgentConfig` merges DEFAULT_AGENT_CHAT_CONFIG, so a real Lobe AI run sees+ // `selfIteration.enabled: false` even though the user never chose it.+ it('should inject self-feedback intent tool for Lobe AI when the merged config reports enabled: false', async () => {+ mockGetAgentConfig.mockResolvedValue({+ chatConfig: { selfIteration: { enabled: false } },+ id: 'agent-inbox',+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ slug: 'inbox',+ systemRole: '',+ });++ await service.execAgent({+ agentId: 'agent-inbox',+ prompt: 'Hello',+ });++ const callArgs = mockCreateOperation.mock.calls[0][0];+ expect(callArgs.toolSet.enabledToolIds).toContain(SELF_FEEDBACK_INTENT_IDENTIFIER);+ expect(callArgs.toolSet.manifestMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBeDefined();+ });++ it('should ignore a legacy per-agent opt-out on Lobe AI', async () => {+ mockGetAgentConfig.mockResolvedValue({+ chatConfig: { selfIteration: { enabled: false, optedOut: true } },+ id: 'agent-inbox',+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ slug: 'inbox',+ systemRole: '',+ });++ await service.execAgent({+ agentId: 'agent-inbox',+ prompt: 'Hello',+ });++ const callArgs = mockCreateOperation.mock.calls[0][0];+ expect(callArgs.toolSet.enabledToolIds).toContain(SELF_FEEDBACK_INTENT_IDENTIFIER);+ expect(callArgs.toolSet.manifestMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBeDefined();});it('should inject self-feedback intent tool for custom agents with agent self-iteration', async () => {@@ -608,6 +692,79 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {expect(callArgs.toolSet.sourceMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBe('builtin');});+ describe('agent.user.message signal gate', () => {+ const runWithAgent = async (agent: { chatConfig: Record<string, unknown>; slug: string }) => {+ mockGetAgentConfig.mockResolvedValue({+ ...agent,+ id: 'agent-gate',+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: '',+ });++ await service.execAgent({ agentId: 'agent-gate', prompt: 'Hello' });++ return vi+ .mocked(enqueueAgentSignalSourceEvent)+ .mock.calls.filter(([input]) => input.sourceType === 'agent.user.message');+ };++ // No per-agent switch: every agent feeds the channel; the Labs switch is checked downstream.+ it('feeds the signal channel for custom agents without any per-agent setting', async () => {+ const calls = await runWithAgent({ chatConfig: {}, slug: 'custom-agent' });++ expect(calls).toHaveLength(1);+ });++ it('feeds the signal channel for custom agents with self-iteration on', async () => {+ const calls = await runWithAgent({+ chatConfig: { selfIteration: { enabled: true } },+ slug: 'custom-agent',+ });++ expect(calls).toHaveLength(1);+ });++ it('feeds the signal channel for Lobe AI', async () => {+ const calls = await runWithAgent({ chatConfig: {}, slug: 'inbox' });++ expect(calls).toHaveLength(1);+ });++ it('marks the first message of a conversation as the conversation root', async () => {+ const calls = await runWithAgent({ chatConfig: {}, slug: 'inbox' });++ expect(calls[0][0].payload).toMatchObject({ isConversationRoot: true });+ });++ it('does not mark a message that follows an earlier turn as the conversation root', async () => {+ mockMessageCreate.mockResolvedValue({ id: 'msg-1', parentId: 'msg-assistant-prev' });++ const calls = await runWithAgent({ chatConfig: {}, slug: 'inbox' });++ expect(calls[0][0].payload).not.toHaveProperty('isConversationRoot');+ });++ it('feeds the signal channel for Lobe AI when the merged config reports enabled: false', async () => {+ const calls = await runWithAgent({+ chatConfig: { selfIteration: { enabled: false } },+ slug: 'inbox',+ });++ expect(calls).toHaveLength(1);+ });++ it('ignores a legacy per-agent opt-out on Lobe AI', async () => {+ const calls = await runWithAgent({+ chatConfig: { selfIteration: { enabled: false, optedOut: true } },+ slug: 'inbox',+ });++ expect(calls).toHaveLength(1);+ });+ });+it('should inject page-agent runtime for regular agents in page scope', async () => {mockGetAgentConfig.mockResolvedValue({chatConfig: { enableHistoryCount: true },diff --git a/apps/server/src/services/aiAgent/__tests__/runFacts.test.ts b/apps/server/src/services/aiAgent/__tests__/runFacts.test.tsindex a74774ee8f2..8844fcda01e 100644--- a/apps/server/src/services/aiAgent/__tests__/runFacts.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/runFacts.test.ts@@ -3,7 +3,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { createRunFacts, DEVICE_SYSTEM_INFO_MAX_AGE_MS } from '../runFacts';-const { getUserSettings, queryDeviceSystemInfo } = vi.hoisted(() => ({+const { getUserPreference, getUserSettings, queryDeviceSystemInfo } = vi.hoisted(() => ({+ getUserPreference: vi.fn(),getUserSettings: vi.fn(),queryDeviceSystemInfo: vi.fn(),}));@@ -14,6 +15,7 @@ vi.mock('@/database/models/user', () => ({_db: unknown,readonly userId: string,) {}+ getUserPreference = () => getUserPreference(this.userId);getUserSettings = () => getUserSettings(this.userId);},}));@@ -31,6 +33,21 @@ beforeEach(() => {});describe('createRunFacts', () => {+ /**+ * The Labs → Self-evolving switch gates both expertise injection and the self-feedback intent+ * tool of one turn; both read it through this fact so the turn pays one `users` read.+ */+ it('reads the run user preference once per turn', async () => {+ getUserPreference.mockResolvedValue({ lab: { enableSelfLearning: true } });+ const runFacts = facts();++ const [a, b] = await Promise.all([runFacts.userPreference(), runFacts.userPreference()]);++ expect(getUserPreference).toHaveBeenCalledOnce();+ expect(getUserPreference).toHaveBeenCalledWith('owner-1');+ expect(a).toBe(b);+ });+it('asks a routed device for its system info once per turn', async () => {const runFacts = facts();diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 0427f7f3273..20fdec54177 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -1373,7 +1373,7 @@ export class AiAgentService {log('execAgent: failed to fetch user settings: %O', error);}try {- const preference = await new UserModel(this.db, this.userId).getUserPreference();+ const preference = await runFacts.userPreference();enableExpertise = preference?.lab?.enableSelfLearning === true;} catch (error) {console.error('Failed to resolve expertise injection Lab preference:', error);diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.tsindex 83a2150ef09..59d73402983 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts@@ -70,11 +70,7 @@ import type { ServerAgentToolsContext } from '@/server/modules/Mecha';import { createServerAgentToolsEngine } from '@/server/modules/Mecha';import { createServerModelParamsProviders } from '@/server/modules/Mecha/ModelParams/providers';import type { AgentDocumentsService } from '@/server/services/agentDocuments';-import {- isAgentSignalEnabledForUser,- isLobeAiAgentSlug,- resolveAgentSelfIterationCapability,-} from '@/server/services/agentSignal/featureGate';+import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';import { resolveUnsupportedMessageApis } from '@/server/services/bot/platforms/messageCapabilities';import type { ComposioService } from '@/server/services/composio';import {@@ -279,7 +275,6 @@ export const discoverTools = async (} = ctx;const {additionalPluginIds,- agentSlug,attachedFileIds,botContext,disableLocalSystem,@@ -1237,8 +1232,6 @@ export const discoverTools = async (composioManifests.length,);- 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`@@ -1250,19 +1243,18 @@ export const discoverTools = async (// 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 =- !shareGate && !disableSelfFeedbackIntentTool && (agentSelfIterationEnabled || isLobeAiAgent);- if (shouldCheckUserSelfIterationGate) {- const featureUserEnabled = await isAgentSignalEnabledForUser(deps.db, deps.userId);- const effectiveAgentSelfIterationEnabled = resolveAgentSelfIterationCapability({- agentSelfIterationEnabled,- isAgentSelfIterationFeatureEnabled: featureUserEnabled,- isLobeAiAgent,+ //+ // There is no per-agent switch: Labs → Self-evolving covers every agent.+ if (!shareGate && !disableSelfFeedbackIntentTool) {+ // The run already reads `users.preference` for expertise injection; reuse that row.+ // A failed read leaves the tool off (fail closed).+ const featureUserEnabled = await isAgentSignalEnabledForUser(deps.db, deps.userId, {+ preference: await ctx.runFacts.userPreference().catch(() => undefined),});if (shouldExposeSelfFeedbackIntentTool({- agentSelfIterationEnabled: effectiveAgentSelfIterationEnabled,+ agentSelfIterationEnabled: featureUserEnabled,disableSelfFeedbackIntentTool,featureUserEnabled,})diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.tsindex 3c1d792ec77..ec2bcbbfb4b 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -976,6 +976,9 @@ export const setupTurn = async (// 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.+ //+ // There is no per-agent gate: every agent feeds this channel, and the user's+ // Labs → Self-evolving switch is checked inside the enqueue.if (userMessageRecord &&!isHeteroAgent &&@@ -986,6 +989,11 @@ export const setupTurn = async ({payload: {agentId: resolvedAgentId,+ // Lets the feedback classifier skip a first message: nothing came before+ // it in the topic, so it cannot be feedback on an earlier reply.+ ...(!userMessageRecord.parentId && !appContext?.threadId+ ? { isConversationRoot: true }+ : {}),message: prompt,messageId: userMessageRecord.id,threadId: appContext?.threadId ?? undefined,diff --git a/apps/server/src/services/aiAgent/runFacts.ts b/apps/server/src/services/aiAgent/runFacts.tsindex 0e8176eb2e2..be7ce1180a4 100644--- a/apps/server/src/services/aiAgent/runFacts.ts+++ b/apps/server/src/services/aiAgent/runFacts.ts@@ -7,6 +7,7 @@ import { deviceGateway, type DeviceSystemInfo } from '@/server/services/deviceGaconst log = debug('lobe-server:ai-agent-service');type UserSettings = Awaited<ReturnType<UserModel['getUserSettings']>>;+type UserPreferenceRow = Awaited<ReturnType<UserModel['getUserPreference']>>;export interface RunFactsSource {db: LobeChatDatabase;@@ -33,6 +34,13 @@ export interface RunFacts {deviceId: string,scope?: 'personal' | 'workspace',) => Promise<DeviceSystemInfo | undefined>;+ /**+ * The run user's `users.preference`. Read for the Labs → Self-evolving switch, which gates+ * both expertise injection and the self-feedback intent tool of the same turn.+ *+ * Rejects when the read fails; the failure is remembered, not retried.+ */+ userPreference: () => Promise<UserPreferenceRow>;/*** A user's settings row. Asked for the market access token when resolving* LobeHub skills and for the memory / timezone settings of the turn.@@ -94,9 +102,23 @@ export const createRunFacts = ({ db, userId, workspaceId }: RunFactsSource): Run}});+ let userPreference: Promise<UserPreferenceRow> | undefined;+ const readUserPreference = () => {+ userPreference ??= (async () => {+ try {+ return await new UserModel(db, userId).getUserPreference();+ } catch (error) {+ log('runFacts: failed to read preference for %s: %O', userId, error);+ throw error;+ }+ })();+ return userPreference;+ };+return {deviceSystemInfo: (deviceId, scope) =>readDeviceSystemInfo([deviceId, scope ?? 'personal'].join(KEY_SEPARATOR)),+ userPreference: readUserPreference,userSettings: (targetUserId) => readUserSettings(targetUserId ?? userId),};};diff --git a/apps/server/src/services/expertise/ingestion.test.ts b/apps/server/src/services/expertise/ingestion.test.tsindex 001a9ee2b1d..4bcafc75c55 100644--- a/apps/server/src/services/expertise/ingestion.test.ts+++ b/apps/server/src/services/expertise/ingestion.test.ts@@ -14,6 +14,13 @@ const dueForConsolidation = vi.fn();const consolidate = vi.fn();const listDomainsForAgent = vi.fn();const listLessons = vi.fn();+const listTopicActivity = vi.fn();++vi.mock('@/database/models/agentSignal/reviewContext', () => ({+ AgentSignalReviewContextModel: class {+ listTopicActivity = listTopicActivity;+ },+}));vi.mock('@/database/models/expertise', () => ({ExpertiseModel: class {@@ -88,6 +95,70 @@ describe('ExpertiseIngestionService.ingestSelfReview', () => {});});+describe('ExpertiseIngestionService.ingestSelfReview nightly topic quota', () => {+ const nightlyCompletion = () =>+ completion({+ artifacts: [],+ marker: {+ agentId: 'agent_1',+ kind: 'nightly-review',+ localDate: '2026-10-11',+ reviewWindowEnd: '2026-10-12T00:00:00.000Z',+ reviewWindowStart: '2026-10-11T00:00:00.000Z',+ sourceId: 'nightly_1',+ },+ mutations: [],+ userId: 'user_1',+ });++ /**+ * The nightly expertise pass shares the user's 50-topics-per-night quota with the review:+ * only admitted topics are ingested.+ */+ it('ingests only the topics the nightly topic quota admits', async () => {+ const service = new ExpertiseIngestionService({} as never, 'user_1');+ const ingestCompletion = vi+ .spyOn(service, 'ingestCompletion')+ .mockResolvedValue({ ingested: 1, reason: 'matched' } as never);+ listTopicActivity.mockResolvedValue([+ { topicId: 'topic_1' },+ { topicId: 'topic_2' },+ { topicId: 'topic_3' },+ ]);+ const claimNightlyTopics = vi+ .fn()+ .mockResolvedValue({ admitted: ['topic_1'], reason: 'exhausted' });++ await service.ingestSelfReview(nightlyCompletion(), { claimNightlyTopics });++ expect(claimNightlyTopics).toHaveBeenCalledWith({+ localDate: '2026-10-11',+ topicIds: ['topic_1', 'topic_2', 'topic_3'],+ userId: 'user_1',+ });+ expect(ingestCompletion.mock.calls.map(([input]) => input.topicId)).toEqual(['topic_1']);+ });++ it('does not meter self-reflection ingestion', async () => {+ const service = new ExpertiseIngestionService({} as never, 'user_1');+ vi.spyOn(service, 'ingestCompletion').mockResolvedValue({ ingested: 1 } as never);+ const claimNightlyTopics = vi.fn();++ await service.ingestSelfReview(+ completion({+ artifacts: [],+ marker: { agentId: 'agent_1', kind: 'self-reflection', sourceId: 'r', topicId: 'topic_1' },+ mutations: [],+ userId: 'user_1',+ }),+ { claimNightlyTopics },+ );++ expect(claimNightlyTopics).not.toHaveBeenCalled();+ expect(service.ingestCompletion).toHaveBeenCalledOnce();+ });+});+describe('ExpertiseIngestionService historical ingestion', () => {it('uses a stable topic key instead of inventing an operation id', async () => {const service = new ExpertiseIngestionService({} as never, 'user_1');diff --git a/apps/server/src/services/expertise/ingestion.ts b/apps/server/src/services/expertise/ingestion.tsindex 4a2fcba0358..39ef052808d 100644--- a/apps/server/src/services/expertise/ingestion.ts+++ b/apps/server/src/services/expertise/ingestion.ts@@ -37,6 +37,7 @@ import { notShareVisitorMessage, notShareVisitorTopic } from '@/database/utils/simport { notTrashed } from '@/database/utils/softDelete';import { buildWorkspaceWhere } from '@/database/utils/workspace';import type { CompletionCallbackParams } from '@/server/services/agentSignal/policies/completionPolicy';+import type { ClaimNightlyReviewTopics } from '@/server/services/agentSignal/services/selfIteration/review/topicQuota';import { AiGenerationService } from '@/server/services/aiGeneration';import { FileService } from '@/server/services/file';import { resolveModelReadableFrameUrl } from '@/server/services/verify/modelFrames';@@ -157,6 +158,17 @@ const matchLesson = <T>(return lessons.byTitle.get(normalizeLessonTitle(observation.title));};+/** Options for ingestions triggered by Agent Signal's completion path. */+export interface ExpertiseSelfReviewIngestionOptions {+ /**+ * Claims a nightly review's topics against the user's per-night topic quota before they are+ * ingested; refused topics are skipped. Self-reflection ingestion is not metered.+ *+ * @default No quota: tests and evals ingest every topic in the window+ */+ claimNightlyTopics?: ClaimNightlyReviewTopics;+}+interface ExpertiseCompletionInput {agentId: string;hadHumanInLoop?: boolean;@@ -242,7 +254,10 @@ export class ExpertiseIngestionService {* Nightly review batches every active topic in its window; fast self-reflection reuses its* single topic scope. Other self-iteration modes are deliberately ignored.*/- ingestSelfReview = async (input: CompletionCallbackParams) => {+ ingestSelfReview = async (+ input: CompletionCallbackParams,+ options: ExpertiseSelfReviewIngestionOptions = {},+ ) => {const marker = input.selfIteration?.marker;const agentId = marker?.agentId;if (!marker || !agentId) return { ingested: 0, reason: 'missing-review-agent' } as const;@@ -266,14 +281,36 @@ export class ExpertiseIngestionService {windowEnd: new Date(marker.reviewWindowEnd),windowStart: new Date(marker.reviewWindowStart),});+ let topicIds = topics.flatMap((topic) => (topic.topicId ? [topic.topicId] : []));++ // Topics the night's review already took are admitted again without counting twice.+ if (options.claimNightlyTopics && marker.localDate && topicIds.length > 0) {+ const claim = await options.claimNightlyTopics({+ localDate: marker.localDate,+ topicIds,+ userId: this.userId,+ });+ if (claim.reason) {+ log(+ 'nightly expertise ingestion agent=%s date=%s: %d of %d topics refused (%s)',+ agentId,+ marker.localDate,+ topicIds.length - claim.admitted.length,+ topicIds.length,+ claim.reason,+ );+ }+ const admitted = new Set(claim.admitted);+ topicIds = topicIds.filter((topicId) => admitted.has(topicId));+ }+const results = [];- for (const topic of topics) {- if (!topic.topicId) continue;+ for (const topicId of topicIds) {results.push(await this.ingestCompletion({agentId,operationId: input.operationId,- topicId: topic.topicId,+ topicId,}),);}diff --git a/apps/server/src/services/redis/README.md b/apps/server/src/services/redis/README.mdindex e0362cd5c82..2a1365e6c66 100644--- a/apps/server/src/services/redis/README.md+++ b/apps/server/src/services/redis/README.md@@ -7,10 +7,19 @@ callers do not choose a provider, prefix, key, SET options or claim lifetime.callers may request a freshness bound through the existing gateway API.- `skillTools.remember`: connection scoped tool lists, ten minutes; empty/failed results are not cached.- `workspaceRescan.claim`: one background scan per principal/device/directory for 45 seconds.+- `agentSignal`: spend bounds for background self-iteration — classifier calls per user per UTC+ day, self-feedback declaration slots per topic, manual triggers per user per hour, and the+ distinct topics one nightly review may cover. Its keys live in the `agent-signal` namespace+ next to the Agent Signal runtime stores. Each count returns `undefined` without Redis; the+ Agent Signal caller decides whether that fails open or closed.-`client.ts` is the connection seam. All current domains share the existing `sendPathCache`-connection and keyspace, preserving deployed cache/claim compatibility. A namespace is a key-partition, not a reason to open another connection. Add a separate connection only for a+`client.ts` is the connection seam. `getRedisServiceClient(scope)` takes the `RedisKeys` scope a+domain reads its keys from; `RedisKeyScopeNamespace` maps every scope to the namespace that becomes+the client's key prefix under `REDIS_PREFIX`. A domain therefore names the scope it uses+(`sendPathCache`, `agentSignal`, ...) and can never write a scope's keys under another scope's+prefix. The send-path domains keep `sendPathCache`, preserving deployed cache/claim compatibility;+`agentSignal` maps to `agent-signal`. Each scope has its own cooldown, so one domain's Redis+failures do not switch off another's. Add a separate connection only for atransport requirement such as pub/sub or blocking commands. Client/provider code and its tests live in `apps/server/src/modules/Redis`.The service composes this infrastructure through domain methods.`cache.ts` holds the generic cache/claim policy (read-through caching, the atomic claim with itsdiff --git a/apps/server/src/services/redis/agentSignal.test.ts b/apps/server/src/services/redis/agentSignal.test.tsnew file mode 100644index 00000000000..25e940ba76b--- /dev/null+++ b/apps/server/src/services/redis/agentSignal.test.ts@@ -0,0 +1,106 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { redisService } from './index';++const client = vi.hoisted(() => ({+ current: undefined as Record<string, ReturnType<typeof vi.fn>> | null | undefined,+}));+const getRedisServiceClient = vi.hoisted(() => vi.fn());+vi.mock('./client', () => ({ getRedisServiceClient }));++const createClient = () => ({+ decr: vi.fn().mockResolvedValue(0),+ eval: vi.fn().mockResolvedValue(['t1']),+ expire: vi.fn().mockResolvedValue(1),+ incr: vi.fn().mockResolvedValue(1),+ set: vi.fn().mockResolvedValue('OK'),+});++describe('redisService.agentSignal', () => {+ beforeEach(() => {+ client.current = createClient();+ getRedisServiceClient.mockReset();+ getRedisServiceClient.mockImplementation(async () => client.current ?? null);+ });++ it('reads and writes through the agentSignal key scope', async () => {+ await redisService.agentSignal.countClassifierCall({ userId: 'u', utcDay: '2026-10-11' });++ expect(getRedisServiceClient).toHaveBeenCalledWith('agentSignal');+ });++ it('counts classifier calls per user and UTC day, outliving the day', async () => {+ await expect(+ redisService.agentSignal.countClassifierCall({ userId: 'u', utcDay: '2026-10-11' }),+ ).resolves.toBe(1);++ expect(client.current!.incr).toHaveBeenCalledWith('classifier_calls:v1:u:2026-10-11');+ expect(client.current!.expire).toHaveBeenCalledWith(+ 'classifier_calls:v1:u:2026-10-11',+ 2 * 24 * 60 * 60,+ );+ });++ it('takes and releases declaration slots in one topic scope', async () => {+ await redisService.agentSignal.takeDeclarationSlot('topic:t1');+ await redisService.agentSignal.releaseDeclarationSlot('topic:t1');++ expect(client.current!.incr).toHaveBeenCalledWith('declaration_slots:v1:topic:t1');+ expect(client.current!.expire).toHaveBeenCalledWith(+ 'declaration_slots:v1:topic:t1',+ 24 * 60 * 60,+ );+ expect(client.current!.decr).toHaveBeenCalledWith('declaration_slots:v1:topic:t1');+ });++ it('opens the manual-trigger window with its expiry before counting', async () => {+ await redisService.agentSignal.countManualTrigger('u');++ expect(client.current!.set).toHaveBeenCalledWith('manual_triggers:v1:u', '0', {+ ex: 3600,+ nx: true,+ });+ expect(client.current!.set.mock.invocationCallOrder[0]).toBeLessThan(+ client.current!.incr.mock.invocationCallOrder[0],+ );+ });++ it('claims nightly topics atomically against the limit for one user and night', async () => {+ await expect(+ redisService.agentSignal.claimNightlyTopics({+ limit: 50,+ localDate: '2026-10-11',+ topicIds: ['t1', 't2'],+ userId: 'u',+ }),+ ).resolves.toEqual(['t1']);++ expect(client.current!.eval).toHaveBeenCalledWith(+ expect.stringContaining('SISMEMBER'),+ 1,+ 'nightly_topics:v1:u:2026-10-11',+ 50,+ 3 * 24 * 60 * 60,+ 't1',+ 't2',+ );+ });++ it('answers undefined for every count when Redis is unavailable', async () => {+ client.current = null;++ await expect(+ redisService.agentSignal.countClassifierCall({ userId: 'u', utcDay: '2026-10-11' }),+ ).resolves.toBeUndefined();+ await expect(redisService.agentSignal.takeDeclarationSlot('s')).resolves.toBeUndefined();+ await expect(redisService.agentSignal.countManualTrigger('u')).resolves.toBeUndefined();+ await expect(+ redisService.agentSignal.claimNightlyTopics({+ limit: 50,+ localDate: '2026-10-11',+ topicIds: ['t1'],+ userId: 'u',+ }),+ ).resolves.toBeUndefined();+ });+});diff --git a/apps/server/src/services/redis/agentSignal.ts b/apps/server/src/services/redis/agentSignal.tsnew file mode 100644index 00000000000..0f3613d4933--- /dev/null+++ b/apps/server/src/services/redis/agentSignal.ts@@ -0,0 +1,106 @@+import { RedisKeys } from '@/server/modules/Redis';++import { getRedisServiceClient } from './client';++const getClient = () => getRedisServiceClient('agentSignal');++// Every count returns `undefined` when Redis is unavailable: the Agent Signal callers decide+// whether that fails open or closed, since each one guards different spend.++const CLASSIFIER_CALLS_TTL_SECONDS = 2 * 24 * 60 * 60;+const DECLARATION_SLOTS_TTL_SECONDS = 24 * 60 * 60;+const MANUAL_TRIGGER_WINDOW_SECONDS = 60 * 60;+const NIGHTLY_TOPICS_TTL_SECONDS = 3 * 24 * 60 * 60;++/**+ * Admits candidate topic ids into the night's set while it holds fewer than `limit` members.+ * Ids already in the set are admitted without counting again, so a replayed run never+ * double-counts.+ *+ * KEYS[1] = set key; ARGV[1] = limit; ARGV[2] = ttl seconds; ARGV[3..] = topic ids+ */+const CLAIM_NIGHTLY_TOPICS_SCRIPT = `+local admitted = {}+local count = redis.call('SCARD', KEYS[1])+local limit = tonumber(ARGV[1])+for i = 3, #ARGV do+ local id = ARGV[i]+ if redis.call('SISMEMBER', KEYS[1], id) == 1 then+ table.insert(admitted, id)+ elseif count < limit then+ redis.call('SADD', KEYS[1], id)+ count = count + 1+ table.insert(admitted, id)+ end+end+redis.call('EXPIRE', KEYS[1], ARGV[2])+return admitted+`;++const count = async (key: string, ttlSeconds: number) => {+ const redis = await getClient();+ if (!redis) return;++ const value = await redis.incr(key);+ await redis.expire(key, ttlSeconds);+ return value;+};++export const agentSignal = {+ /** Counts one feedback-classifier call against the user's UTC day. */+ async countClassifierCall(scope: { userId: string; utcDay: string }) {+ return count(+ RedisKeys.agentSignal.classifierCalls(scope.userId, scope.utcDay),+ CLASSIFIER_CALLS_TTL_SECONDS,+ );+ },++ /** Takes one self-feedback declaration slot in a topic scope. */+ async takeDeclarationSlot(scopeKey: string) {+ return count(RedisKeys.agentSignal.declarationSlots(scopeKey), DECLARATION_SLOTS_TTL_SECONDS);+ },++ /** Returns a slot whose declaration was rejected or failed to enqueue. */+ async releaseDeclarationSlot(scopeKey: string) {+ const redis = await getClient();+ if (!redis) return;++ await redis.decr(RedisKeys.agentSignal.declarationSlots(scopeKey));+ },++ /**+ * Counts one manual trigger in the user's fixed hourly window. The window is created with+ * its expiry before the increment, so a crash between the two never leaves it without one.+ */+ async countManualTrigger(userId: string) {+ const redis = await getClient();+ if (!redis) return;++ const key = RedisKeys.agentSignal.manualTriggers(userId);+ await redis.set(key, '0', { ex: MANUAL_TRIGGER_WINDOW_SECONDS, nx: true });+ return redis.incr(key);+ },++ /**+ * Claims topics for one user's nightly review, atomically, up to `limit` distinct topics+ * per local night. Returns the admitted ids in input order.+ */+ async claimNightlyTopics(scope: {+ limit: number;+ localDate: string;+ topicIds: string[];+ userId: string;+ }) {+ const redis = await getClient();+ if (!redis) return;++ return redis.eval<string[]>(+ CLAIM_NIGHTLY_TOPICS_SCRIPT,+ 1,+ RedisKeys.agentSignal.nightlyTopics(scope.userId, scope.localDate),+ scope.limit,+ NIGHTLY_TOPICS_TTL_SECONDS,+ ...scope.topicIds,+ );+ },+};diff --git a/apps/server/src/services/redis/client.test.ts b/apps/server/src/services/redis/client.test.tsindex dd6f500d56c..48d968a44e1 100644--- a/apps/server/src/services/redis/client.test.ts+++ b/apps/server/src/services/redis/client.test.ts@@ -37,7 +37,7 @@ describe('getRedisServiceClient', () => {mockGetRedisConfig.mockReturnValue({ enabled: false, prefix: 'lobe', tls: false, url: '' });const { getRedisServiceClient } = await loadClient();- await expect(getRedisServiceClient()).resolves.toBeNull();+ await expect(getRedisServiceClient('sendPathCache')).resolves.toBeNull();expect(mockTryInitializeRedisWithPrefix).not.toHaveBeenCalled();});@@ -47,7 +47,7 @@ describe('getRedisServiceClient', () => {mockTryInitializeRedisWithPrefix.mockResolvedValue(provider);const { getRedisServiceClient } = await loadClient();- const client = await getRedisServiceClient();+ const client = await getRedisServiceClient('sendPathCache');expect(client).not.toBeNull();await expect(client!.get('k')).resolves.toBe('value');@@ -61,9 +61,9 @@ describe('getRedisServiceClient', () => {mockTryInitializeRedisWithPrefix.mockResolvedValue({ get: vi.fn(), set: vi.fn() });mockGetRedisConfig.mockReturnValue({ ...enabledConfig, prefix: 'staging' });- await (await loadClient()).getRedisServiceClient();+ await (await loadClient()).getRedisServiceClient('sendPathCache');mockGetRedisConfig.mockReturnValue({ ...enabledConfig, prefix: 'production' });- await (await loadClient()).getRedisServiceClient();+ await (await loadClient()).getRedisServiceClient('sendPathCache');expect(mockTryInitializeRedisWithPrefix.mock.calls.map(([, prefix]) => prefix)).toEqual(['staging:sendPathCache',@@ -76,8 +76,8 @@ describe('getRedisServiceClient', () => {mockTryInitializeRedisWithPrefix.mockResolvedValue(null);const { getRedisServiceClient } = await loadClient();- await expect(getRedisServiceClient()).resolves.toBeNull();- await expect(getRedisServiceClient()).resolves.toBeNull();+ await expect(getRedisServiceClient('sendPathCache')).resolves.toBeNull();+ await expect(getRedisServiceClient('sendPathCache')).resolves.toBeNull();expect(mockTryInitializeRedisWithPrefix).toHaveBeenCalledTimes(1);});@@ -89,11 +89,11 @@ describe('getRedisServiceClient', () => {mockTryInitializeRedisWithPrefix.mockReturnValue(new Promise(() => {}));const { getRedisServiceClient } = await loadClient();- const pending = getRedisServiceClient();+ const pending = getRedisServiceClient('sendPathCache');await vi.advanceTimersByTimeAsync(1500);await expect(pending).resolves.toBeNull();- await expect(getRedisServiceClient()).resolves.toBeNull();+ await expect(getRedisServiceClient('sendPathCache')).resolves.toBeNull();expect(mockTryInitializeRedisWithPrefix).toHaveBeenCalledTimes(1);} finally {vi.useRealTimers();@@ -111,11 +111,35 @@ describe('getRedisServiceClient', () => {mockTryInitializeRedisWithPrefix.mockResolvedValue(provider);const { getRedisServiceClient } = await loadClient();- const client = await getRedisServiceClient();+ const client = await getRedisServiceClient('sendPathCache');expect(client).not.toBeNull();await expect(client!.get('k')).rejects.toThrow('redis down');- await expect(getRedisServiceClient()).resolves.toBeNull();+ await expect(getRedisServiceClient('sendPathCache')).resolves.toBeNull();expect(mockTryInitializeRedisWithPrefix).toHaveBeenCalledTimes(1);});++ it('prefixes each key scope with its mapped namespace under REDIS_PREFIX', async () => {+ mockGetRedisConfig.mockReturnValue(enabledConfig);+ mockTryInitializeRedisWithPrefix.mockResolvedValue({ get: vi.fn(), set: vi.fn() });+ const { getRedisServiceClient } = await loadClient();++ await getRedisServiceClient('agentSignal');++ expect(mockTryInitializeRedisWithPrefix).toHaveBeenCalledWith(+ expect.anything(),+ 'lobe:agent-signal',+ );+ });++ it('keeps one scope serving while another scope is cooling down', async () => {+ mockGetRedisConfig.mockReturnValue(enabledConfig);+ mockTryInitializeRedisWithPrefix.mockImplementation(async (_config, prefix: string) =>+ prefix === 'lobe:sendPathCache' ? null : { get: vi.fn(), set: vi.fn() },+ );+ const { getRedisServiceClient } = await loadClient();++ await expect(getRedisServiceClient('sendPathCache')).resolves.toBeNull();+ await expect(getRedisServiceClient('agentSignal')).resolves.not.toBeNull();+ });});diff --git a/apps/server/src/services/redis/client.ts b/apps/server/src/services/redis/client.tsindex 7a2d109f8d4..562f599d272 100644--- a/apps/server/src/services/redis/client.ts+++ b/apps/server/src/services/redis/client.ts@@ -1,5 +1,9 @@import { getRedisConfig } from '@/envs/redis';-import { RedisKeyNamespace, tryInitializeRedisWithPrefix } from '@/server/modules/Redis';+import {+ type RedisKeyScope,+ RedisKeyScopeNamespace,+ tryInitializeRedisWithPrefix,+} from '@/server/modules/Redis';import type { BaseRedisProvider } from '@/server/modules/Redis/types';// The send-path caches are an optimization layered on a hot path, so a send@@ -12,11 +16,14 @@ const CONNECT_TIMEOUT_MS = 1000;const COMMAND_TIMEOUT_MS = 1000;const COOLDOWN_MS = 30_000;-/** `Date.now()` until which the circuit stays open; 0 means closed. */-let cooldownUntil = 0;+/**+ * `Date.now()` until which a scope's circuit stays open. Kept per scope so an outage seen+ * by one domain does not switch off another domain's Redis.+ */+const cooldownUntil = new Map<RedisKeyScope, number>();-const openCircuit = () => {- cooldownUntil = Date.now() + COOLDOWN_MS;+const openCircuit = (scope: RedisKeyScope) => {+ cooldownUntil.set(scope, Date.now() + COOLDOWN_MS);};const withDeadline = async <T>(work: Promise<T>, ms: number): Promise<T | null> => {@@ -39,7 +46,7 @@ const withDeadline = async <T>(work: Promise<T>, ms: number): Promise<T | null>* connect — nothing would trip the cooldown, so each send would pay the* command timeout before falling back to its live read.*/-const observeFailures = (client: BaseRedisProvider): BaseRedisProvider =>+const observeFailures = (client: BaseRedisProvider, scope: RedisKeyScope): BaseRedisProvider =>new Proxy(client, {get(target, property, receiver) {const value = Reflect.get(target, property, receiver);@@ -49,7 +56,7 @@ const observeFailures = (client: BaseRedisProvider): BaseRedisProvider =>const result = value.apply(target, args);return result instanceof Promise? result.catch((error) => {- openCircuit();+ openCircuit(scope);throw error;}): result;@@ -58,35 +65,37 @@ const observeFailures = (client: BaseRedisProvider): BaseRedisProvider =>});/**- * The shared send-path-cache client, or `null` when Redis is unavailable and- * the caller should fall back to its live read.+ * The Redis service client for one {@link RedisKeys} scope, or `null` when Redis is+ * unavailable and the caller should fall back.*- * Never blocks for long: acquiring the client is bounded by- * {@link ACQUIRE_TIMEOUT_MS}, and any failure (or a disabled Redis) returns- * `null`. A failed acquisition, or a command that fails later on the memoized- * client, opens the circuit for {@link COOLDOWN_MS} so concurrent and later- * sends degrade straight to their live read.+ * The client's key prefix is the scope's namespace from {@link RedisKeyScopeNamespace},+ * composed under REDIS_PREFIX, so a domain reading `RedisKeys.<scope>` always writes under+ * that scope's own prefix. Never blocks for long: acquiring the client is bounded by+ * {@link ACQUIRE_TIMEOUT_MS}, and any failure (or a disabled Redis) returns `null`. A failed+ * acquisition, or a command that fails later on the memoized client, opens that scope's+ * circuit for {@link COOLDOWN_MS} so concurrent and later callers degrade to their fallback.*/-export const getRedisServiceClient = async (): Promise<BaseRedisProvider | null> => {+export const getRedisServiceClient = async (+ scope: RedisKeyScope,+): Promise<BaseRedisProvider | null> => {const config = getRedisConfig();- if (!config.enabled || Date.now() < cooldownUntil) return null;+ if (!config.enabled || Date.now() < (cooldownUntil.get(scope) ?? 0)) return null;+ const namespace = RedisKeyScopeNamespace[scope];const client = await withDeadline(tryInitializeRedisWithPrefix({ ...config, commandTimeoutMs: COMMAND_TIMEOUT_MS, connectTimeoutMs: CONNECT_TIMEOUT_MS },// Compose with REDIS_PREFIX rather than replace it: deployments sharing// one Redis isolate by prefix, and their user/device ids can collide.- config.prefix- ? `${config.prefix}:${RedisKeyNamespace.SEND_PATH_CACHE}`- : RedisKeyNamespace.SEND_PATH_CACHE,+ config.prefix ? `${config.prefix}:${namespace}` : namespace,),ACQUIRE_TIMEOUT_MS,);if (!client) {- openCircuit();+ openCircuit(scope);return null;}- return observeFailures(client);+ return observeFailures(client, scope);};diff --git a/apps/server/src/services/redis/deviceSystemInfo.ts b/apps/server/src/services/redis/deviceSystemInfo.tsindex 4f94cccb0da..6f9fbbd8be1 100644--- a/apps/server/src/services/redis/deviceSystemInfo.ts+++ b/apps/server/src/services/redis/deviceSystemInfo.ts@@ -12,7 +12,7 @@ export const deviceSystemInfo = {maxAgeMs = 3 * 60 * 1000,) {return readThroughRedis(- await getRedisServiceClient(),+ await getRedisServiceClient('sendPathCache'),RedisKeys.sendPathCache.deviceSystemInfo(scope.userId,scope.workspaceId ?? 'personal',diff --git a/apps/server/src/services/redis/index.ts b/apps/server/src/services/redis/index.tsindex b94da093ac5..b47e3163d53 100644--- a/apps/server/src/services/redis/index.ts+++ b/apps/server/src/services/redis/index.ts@@ -1,6 +1,7 @@+import { agentSignal } from './agentSignal';import { deviceSystemInfo } from './deviceSystemInfo';import { skillTools } from './skillTools';import { workspaceRescan } from './workspaceRescan';/** Business Redis API. Providers, keys and expiry policy stay inside each domain. */-export const redisService = { deviceSystemInfo, skillTools, workspaceRescan };+export const redisService = { agentSignal, deviceSystemInfo, skillTools, workspaceRescan };diff --git a/apps/server/src/services/redis/skillTools.ts b/apps/server/src/services/redis/skillTools.tsindex 95d90c87c94..45ca5875c25 100644--- a/apps/server/src/services/redis/skillTools.ts+++ b/apps/server/src/services/redis/skillTools.ts@@ -16,7 +16,7 @@ export const skillTools = {'|',);return readThroughRedis(- await getRedisServiceClient(),+ await getRedisServiceClient('sendPathCache'),RedisKeys.sendPathCache.lobehubSkillTools(scope.userId, scope.providerId, identity),fetch,{diff --git a/apps/server/src/services/redis/workspaceRescan.ts b/apps/server/src/services/redis/workspaceRescan.tsindex 4a6a2ef4b86..36dc7116a88 100644--- a/apps/server/src/services/redis/workspaceRescan.ts+++ b/apps/server/src/services/redis/workspaceRescan.ts@@ -7,7 +7,7 @@ import { getRedisServiceClient } from './client';export const workspaceRescan = {async claim(scope: { cwd: string; deviceId: string; userId: string; workspaceId?: string }) {return claimRedisOnce(- await getRedisServiceClient(),+ await getRedisServiceClient('sendPathCache'),RedisKeys.sendPathCache.workspaceRescanClaim(scope.userId,scope.workspaceId ?? 'personal',diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/selfFeedbackIntent.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/selfFeedbackIntent.test.tsindex 5117327dcc6..aa20a925f77 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/selfFeedbackIntent.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/selfFeedbackIntent.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';@@ -8,6 +8,22 @@ vi.mock('@/server/services/agentSignal', () => ({enqueueAgentSignalSourceEvent: vi.fn(),}));+const service = vi.hoisted(() => ({+ available: true,+ counters: new Map<string, number>(),+ releaseDeclarationSlot: vi.fn(),+ takeDeclarationSlot: vi.fn(),+}));++vi.mock('@/server/services/redis', () => ({+ redisService: {+ agentSignal: {+ releaseDeclarationSlot: service.releaseDeclarationSlot,+ takeDeclarationSlot: service.takeDeclarationSlot,+ },+ },+}));+const createInput = () => ({action: 'refine' as const,confidence: 0.91,@@ -18,8 +34,22 @@ const createInput = () => ({});describe('selfFeedbackIntentRuntime', () => {+ afterEach(() => {+ service.available = true;+ });+beforeEach(() => {vi.clearAllMocks();+ service.counters.clear();+ service.takeDeclarationSlot.mockImplementation(async (scopeKey: string) => {+ if (!service.available) return undefined;+ const next = (service.counters.get(scopeKey) ?? 0) + 1;+ service.counters.set(scopeKey, next);+ return next;+ });+ service.releaseDeclarationSlot.mockImplementation(async (scopeKey: string) => {+ service.counters.set(scopeKey, (service.counters.get(scopeKey) ?? 0) - 1);+ });vi.mocked(enqueueAgentSignalSourceEvent).mockResolvedValue({accepted: true,scopeKey: 'topic:topic-1',@@ -151,4 +181,44 @@ describe('selfFeedbackIntentRuntime', () => {});expect(enqueueAgentSignalSourceEvent).toHaveBeenCalledTimes(3);});++ /**+ * @example+ * The declaration limit is read from Redis, so it holds across server processes.+ */+ it('enforces the declaration limit from the shared Redis counter', async () => {+ service.counters.set('user-1:agent-1:topic:topic-shared', 3);+ const runtime = selfFeedbackIntentRuntime.factory({ toolManifestMap: {} });++ const result = await runtime.declareSelfFeedbackIntent(createInput(), {+ agentId: 'agent-1',+ toolCallId: 'tool-call-from-another-process',+ toolManifestMap: {},+ topicId: 'topic-shared',+ userId: 'user-1',+ });++ expect(JSON.parse(result.content)).toMatchObject({ accepted: false, reason: 'rate_limited' });+ expect(enqueueAgentSignalSourceEvent).not.toHaveBeenCalled();+ });++ /**+ * @example+ * Without Redis the limit cannot be enforced, so declarations are rejected (fail closed).+ */+ it('rejects declarations when Redis is unavailable', async () => {+ service.available = false;+ const runtime = selfFeedbackIntentRuntime.factory({ toolManifestMap: {} });++ const result = await runtime.declareSelfFeedbackIntent(createInput(), {+ agentId: 'agent-1',+ toolCallId: 'tool-call-no-redis',+ toolManifestMap: {},+ topicId: 'topic-no-redis',+ userId: 'user-1',+ });++ expect(JSON.parse(result.content)).toMatchObject({ accepted: false, reason: 'rate_limited' });+ expect(enqueueAgentSignalSourceEvent).not.toHaveBeenCalled();+ });});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReview.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReview.tsindex 34269c56bfb..23a4eea9a8e 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReview.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReview.ts@@ -6,23 +6,14 @@ import { AgentSignalToolExecutionRuntime } from '@lobechat/builtin-tool-agent-siimport { AgentOperationModel } from '@/database/models/agentOperation';import { BriefModel } from '@/database/models/brief';-import { UserModel } from '@/database/models/user';-import type { LobeChatDatabase } from '@/database/type';-import { translation } from '@/libs/i18n/serverTranslation';import { readAgentSignalMarker } from '@/server/services/agentSignal/operationMarker';import { createServerSelfReviewBriefWriter } from '@/server/services/agentSignal/services/selfIteration/review/brief';+import { resolveSelfReviewBriefTextTranslator } from '@/server/services/agentSignal/services/selfIteration/review/briefTextTranslator';import { createReviewRuntimePrimitives } from '@/server/services/agentSignal/services/selfIteration/review/server';import { SkillManagementDocumentService } from '@/server/services/skillManagement';import type { ServerRuntimeRegistration } from './types';-const resolveBriefTextTranslator = async (db: LobeChatDatabase, userId: string) => {- const userInfo = await UserModel.getInfoForAIGeneration(db, userId);- const { t } = await translation('home', userInfo.responseLanguage ?? 'en-US');-- return t;-};-/*** Registers the nightly-review self-iteration builtin server runtime, so an* `execAgent` run with `plugins: ['agent-signal-review']` can execute its tools.@@ -53,7 +44,7 @@ export const agentSignalReviewRuntime: ServerRuntimeRegistration = {const service = createReviewRuntimePrimitives({agentId,briefModel: new BriefModel(serverDB, userId, workspaceId),- briefTextTranslator: await resolveBriefTextTranslator(serverDB, userId),+ briefTextTranslator: await resolveSelfReviewBriefTextTranslator(serverDB, userId),db: serverDB,localDate,proposalBriefWriter: createServerSelfReviewBriefWriter(serverDB, userId, workspaceId),diff --git a/apps/server/src/services/toolExecution/serverRuntimes/selfFeedbackIntent.ts b/apps/server/src/services/toolExecution/serverRuntimes/selfFeedbackIntent.tsindex cf96cee7098..6f58cbadaab 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/selfFeedbackIntent.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/selfFeedbackIntent.ts@@ -3,11 +3,17 @@ import { SelfFeedbackIntentExecutionRuntime } from '@lobechat/builtin-tool-self-import { nanoid } from '@lobechat/utils';import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';-import { createSelfFeedbackIntentService } from '@/server/services/agentSignal/services/selfFeedbackIntent';+import {+ createRedisDeclarationLimiter,+ createSelfFeedbackIntentService,+} from '@/server/services/agentSignal/services/selfFeedbackIntent';import type { ServerRuntimeRegistration } from './types';const sharedSelfFeedbackIntentService = createSelfFeedbackIntentService({+ // Serverless instances do not share memory, so the per-scope declaration+ // limit lives in Redis to hold across processes.+ declarationLimiter: createRedisDeclarationLimiter(),enqueueSource: (sourceEvent) =>enqueueAgentSignalSourceEvent(sourceEvent, {agentId: sourceEvent.payload.agentId,@@ -30,7 +36,7 @@ const runtime = new SelfFeedbackIntentExecutionRuntime({** Expects:* - The package ExecutionRuntime validates per-call `agentId`, `userId`, and `topicId`- * - The shared service preserves fast-loop declaration rate limits+ * - The shared service enforces the per-scope declaration limit through Redis** Returns:* - A shared runtime instance backed by the server Agent Signal enqueue boundarydiff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 916226eae3d..1fa4b67e27d 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -47,14 +47,21 @@"agentProfile.skills_other": "{{count}} skills","agentSignal.receipts.agentSignalLabel": "Agent Signal","agentSignal.receipts.memory.detail": "Saved this for future replies",+ "agentSignal.receipts.memory.openInMemory": "Open in Memory","agentSignal.receipts.memory.title": "Memory saved","agentSignal.receipts.recentActivity": "Recent activity","agentSignal.receipts.revert.conflict": "Newer version",+ "agentSignal.receipts.revert.error.conflict": "Can't undo: it was changed after this update",+ "agentSignal.receipts.revert.error.failed": "Undo failed: {{reason}}",+ "agentSignal.receipts.revert.error.generic": "Undo failed. Please try again later",+ "agentSignal.receipts.revert.error.not_found": "Can't undo: it no longer exists",+ "agentSignal.receipts.revert.error.unsupported": "This change can't be undone","agentSignal.receipts.revert.failed": "Failed","agentSignal.receipts.revert.not_found": "Cannot undo","agentSignal.receipts.revert.pending": "Rolling back","agentSignal.receipts.revert.rolled_back": "Reverted","agentSignal.receipts.revert.undo": "Undo",+ "agentSignal.receipts.revert.undone": "Undone","agentSignal.receipts.revert.unsupported": "Unsupported","agentSignal.receipts.skill.detail": "Self-refined how this agent handles similar requests","agentSignal.receipts.skill.title": "Auto-learned a new skill",diff --git a/locales/en-US/home.json b/locales/en-US/home.jsonindex 8cca7f97fa7..de436fcafd8 100644--- a/locales/en-US/home.json+++ b/locales/en-US/home.json@@ -8,6 +8,7 @@"brief.action.approve": "Approve","brief.action.confirm": "Confirm","brief.action.confirmDone": "Confirm complete",+ "brief.action.dismiss": "Dismiss","brief.action.fail": "Fail goal","brief.action.feedback": "Feedback","brief.action.ignore": "Ignore",@@ -24,15 +25,31 @@"brief.agentSignal.selfReview.applied.summary": "{{count}} dream update was applied.","brief.agentSignal.selfReview.applied.summary_plural": "{{count}} dream updates were applied.","brief.agentSignal.selfReview.applied.title": "Dream updated resources",+ "brief.agentSignal.selfReview.details.forAgent": "For {{agent}}","brief.agentSignal.selfReview.error.heading": "Issue","brief.agentSignal.selfReview.error.summary": "Some work could not be completed during this dream.","brief.agentSignal.selfReview.error.title": "Dream ran into an issue","brief.agentSignal.selfReview.ideas.summary": "Saved dream notes for future review.","brief.agentSignal.selfReview.ideas.title": "Dream notes",+ "brief.agentSignal.selfReview.kind.consolidate_skill.plain": "Merge skills",+ "brief.agentSignal.selfReview.kind.consolidate_skill.withTarget": "Merge skills into {{target}}",+ "brief.agentSignal.selfReview.kind.create_skill.plain": "New skill",+ "brief.agentSignal.selfReview.kind.create_skill.withTarget": "New skill: {{target}}",+ "brief.agentSignal.selfReview.kind.idea.plain": "Dream note",+ "brief.agentSignal.selfReview.kind.idea.withTarget": "Dream note: {{target}}",+ "brief.agentSignal.selfReview.kind.other.plain": "Suggestion",+ "brief.agentSignal.selfReview.kind.other.withTarget": "Suggestion: {{target}}",+ "brief.agentSignal.selfReview.kind.refine_prompt.plain": "Refine system prompt",+ "brief.agentSignal.selfReview.kind.refine_skill.plain": "Refine skill",+ "brief.agentSignal.selfReview.kind.refine_skill.withTarget": "Refine skill: {{target}}",+ "brief.agentSignal.selfReview.kind.write_memory.plain": "Save memory",+ "brief.agentSignal.selfReview.kind.write_memory.withTarget": "Save memory: {{target}}",+ "brief.agentSignal.selfReview.list.more": "{{count}} more","brief.agentSignal.selfReview.proposal.heading": "Suggestion","brief.agentSignal.selfReview.proposal.summary": "{{count}} dream suggestion needs your review.","brief.agentSignal.selfReview.proposal.summary_plural": "{{count}} dream suggestions need your review.","brief.agentSignal.selfReview.proposal.title": "Dream suggestion needs review",+ "brief.agentSignal.selfReview.title.more": "{{title}} (+{{count}} more)","brief.collapse": "Show less","brief.commentPlaceholder": "Share your feedback...","brief.commentSubmit": "Submit feedback",diff --git a/locales/en-US/labs.json b/locales/en-US/labs.jsonindex b102bb598eb..e2c5980994d 100644--- a/locales/en-US/labs.json+++ b/locales/en-US/labs.json@@ -40,7 +40,7 @@"features.persistentSandbox.title": "Persistent Sandbox","features.projects.desc": "Organize long-running goals into dedicated workspaces with their own agents, knowledge bases, and tasks.","features.projects.title": "Project Workspaces",- "features.selfLearning.desc": "Learn from practice: the rounds you send back become rules, and each agent picks up lessons from its own runs — both go with the agent into every run. See them all under Memory → Self-evolving.",+ "features.selfLearning.desc": "Let every agent learn from your conversations in the background: it remembers facts, refines skills, collects lessons, and reviews its day each night. Rounds you send back become rules. Each nightly review covers at most 50 conversations. See it all under Memory → Self-evolving.","features.selfLearning.title": "Self-evolving","features.taskVerify.desc": "Add an Acceptance section to the task detail: describe acceptance in one sentence and let AI generate editable verify criteria.","features.taskVerify.title": "Acceptance",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 297b08eed45..38e97040c8c 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -219,7 +219,6 @@"agentTab.opening": "Opening Settings","agentTab.plugin": "Skill Settings","agentTab.prompt": "Agent Profile",- "agentTab.selfIteration": "Self-Iteration","agentTab.tts": "Voice Service","analytics.telemetry.desc": "Help us improve {{appName}} with anonymous usage data","analytics.telemetry.title": "Send Anonymous Usage Data",@@ -1431,10 +1430,6 @@"settingOpening.openingQuestions.title": "Opening Questions","settingOpening.title": "Opening Settings","settingPlugin.title": "Skill List",- "settingSelfIteration.enabled.desc": "Allow this assistant to review recent signals and improve its own skills when the self-iteration workflow runs.",- "settingSelfIteration.enabled.managedDesc": "Always on for Lobe AI while Self-Iteration is available.",- "settingSelfIteration.enabled.title": "Enable Self-Iteration",- "settingSelfIteration.title": "Self-Iteration","settingSystem.oauth.info.desc": "Logged in","settingSystem.oauth.info.title": "Account Information","settingSystem.oauth.signin.action": "Sign In",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 543d21c9f8c..d8e2c1b2ac8 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -47,14 +47,21 @@"agentProfile.skills_other": "{{count}} 项技能","agentSignal.receipts.agentSignalLabel": "代理信号","agentSignal.receipts.memory.detail": "已保存以供未来回复使用",+ "agentSignal.receipts.memory.openInMemory": "在记忆中打开","agentSignal.receipts.memory.title": "记忆已保存","agentSignal.receipts.recentActivity": "最近活动","agentSignal.receipts.revert.conflict": "已有新版本",+ "agentSignal.receipts.revert.error.conflict": "无法撤销:之后已有新的修改",+ "agentSignal.receipts.revert.error.failed": "撤销失败:{{reason}}",+ "agentSignal.receipts.revert.error.generic": "撤销失败,请稍后重试",+ "agentSignal.receipts.revert.error.not_found": "无法撤销:内容已不存在",+ "agentSignal.receipts.revert.error.unsupported": "此变更不支持撤销","agentSignal.receipts.revert.failed": "撤销失败","agentSignal.receipts.revert.not_found": "无法撤销","agentSignal.receipts.revert.pending": "正在撤销","agentSignal.receipts.revert.rolled_back": "已还原","agentSignal.receipts.revert.undo": "撤销",+ "agentSignal.receipts.revert.undone": "已撤销","agentSignal.receipts.revert.unsupported": "不支持撤销","agentSignal.receipts.skill.detail": "已自主优化处理相似请求的方式","agentSignal.receipts.skill.title": "已自动习得新技能",diff --git a/locales/zh-CN/home.json b/locales/zh-CN/home.jsonindex 3db71a0a707..e81fcafd9c4 100644--- a/locales/zh-CN/home.json+++ b/locales/zh-CN/home.json@@ -8,6 +8,7 @@"brief.action.approve": "批准","brief.action.confirm": "已阅","brief.action.confirmDone": "确认完成",+ "brief.action.dismiss": "不采纳","brief.action.fail": "判定失败","brief.action.feedback": "反馈","brief.action.ignore": "忽略",@@ -24,15 +25,31 @@"brief.agentSignal.selfReview.applied.summary": "已应用 {{count}} 条夜间回顾更新。","brief.agentSignal.selfReview.applied.summary_plural": "已应用 {{count}} 条夜间回顾更新。","brief.agentSignal.selfReview.applied.title": "夜间回顾已更新资源",+ "brief.agentSignal.selfReview.details.forAgent": "适用于助理「{{agent}}」","brief.agentSignal.selfReview.error.heading": "问题","brief.agentSignal.selfReview.error.summary": "部分夜间回顾内容未能完成。","brief.agentSignal.selfReview.error.title": "夜间回顾遇到了问题","brief.agentSignal.selfReview.ideas.summary": "已保存夜间回顾记录,供后续查看。","brief.agentSignal.selfReview.ideas.title": "夜间回顾记录",+ "brief.agentSignal.selfReview.kind.consolidate_skill.plain": "合并技能",+ "brief.agentSignal.selfReview.kind.consolidate_skill.withTarget": "合并技能到「{{target}}」",+ "brief.agentSignal.selfReview.kind.create_skill.plain": "新建技能",+ "brief.agentSignal.selfReview.kind.create_skill.withTarget": "新建技能:{{target}}",+ "brief.agentSignal.selfReview.kind.idea.plain": "夜间回顾记录",+ "brief.agentSignal.selfReview.kind.idea.withTarget": "夜间回顾记录:{{target}}",+ "brief.agentSignal.selfReview.kind.other.plain": "建议",+ "brief.agentSignal.selfReview.kind.other.withTarget": "建议:{{target}}",+ "brief.agentSignal.selfReview.kind.refine_prompt.plain": "优化系统提示词",+ "brief.agentSignal.selfReview.kind.refine_skill.plain": "优化技能",+ "brief.agentSignal.selfReview.kind.refine_skill.withTarget": "优化技能:{{target}}",+ "brief.agentSignal.selfReview.kind.write_memory.plain": "保存记忆",+ "brief.agentSignal.selfReview.kind.write_memory.withTarget": "保存记忆:{{target}}",+ "brief.agentSignal.selfReview.list.more": "另有 {{count}} 项","brief.agentSignal.selfReview.proposal.heading": "建议","brief.agentSignal.selfReview.proposal.summary": "有 {{count}} 条夜间回顾建议需要你确认。","brief.agentSignal.selfReview.proposal.summary_plural": "有 {{count}} 条夜间回顾建议需要你确认。","brief.agentSignal.selfReview.proposal.title": "有夜间回顾建议需要确认",+ "brief.agentSignal.selfReview.title.more": "{{title}}(另有 {{count}} 项)","brief.collapse": "收起","brief.commentPlaceholder": "分享你的反馈…","brief.commentSubmit": "提交反馈",diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.jsonindex ac6d86595f3..ffeec583e6c 100644--- a/locales/zh-CN/labs.json+++ b/locales/zh-CN/labs.json@@ -40,7 +40,7 @@"features.persistentSandbox.title": "持久化沙箱","features.projects.desc": "将长期目标组织到独立工作空间中,并集中管理相关智能体、资料库与任务。","features.projects.title": "项目工作空间",- "features.selfLearning.desc": "从实践中学习:你打回的验收会沉淀成规矩,每个 Agent 也会从自己的运行里学到经验,运行时都会带给 Agent。在「记忆 → 自进化」里统一查看。",+ "features.selfLearning.desc": "让所有 Agent 在后台从对话中学习:记住信息、完善技能、积累经验,并在每晚复盘。你打回的验收会沉淀成规矩。每晚复盘最多覆盖 50 个话题。在「记忆 → 自进化」里统一查看。","features.selfLearning.title": "自进化","features.taskVerify.desc": "在任务详情里增加「交付验收」模块:一句话描述验收要求,AI 自动生成可编辑的验收项。","features.taskVerify.title": "任务交付验收",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 376a808f8b4..43ba296b50c 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -219,7 +219,6 @@"agentTab.opening": "开场设置","agentTab.plugin": "技能设置","agentTab.prompt": "助理档案",- "agentTab.selfIteration": "自我迭代","agentTab.tts": "语音服务","analytics.telemetry.desc": "通过匿名使用数据帮助我们改进 {{appName}}","analytics.telemetry.title": "发送匿名使用数据",@@ -1431,10 +1430,6 @@"settingOpening.openingQuestions.title": "开场问题","settingOpening.title": "开场设置","settingPlugin.title": "技能列表",- "settingSelfIteration.enabled.desc": "允许此助手在自我迭代工作流程运行时审查最近的信号并改进其自身技能。",- "settingSelfIteration.enabled.managedDesc": "当自我迭代功能可用时,Lobe AI 始终启用。",- "settingSelfIteration.enabled.title": "启用自我迭代",- "settingSelfIteration.title": "自我迭代","settingSystem.oauth.info.desc": "已登录","settingSystem.oauth.info.title": "账户信息","settingSystem.oauth.signin.action": "登录",diff --git a/packages/agent-signal/package.json b/packages/agent-signal/package.jsonindex fd11895eb62..6e0335af2fb 100644--- a/packages/agent-signal/package.json+++ b/packages/agent-signal/package.json@@ -9,6 +9,10 @@"types": "./src/index.ts","default": "./src/index.ts"},+ "./brief": {+ "types": "./src/brief/index.ts",+ "default": "./src/brief/index.ts"+ },"./source": {"types": "./src/source/index.ts","default": "./src/source/index.ts"diff --git a/packages/agent-signal/src/brief/index.ts b/packages/agent-signal/src/brief/index.tsnew file mode 100644index 00000000000..7b33eebbccf--- /dev/null+++ b/packages/agent-signal/src/brief/index.ts@@ -0,0 +1 @@+export * from './selfReviewBriefDetails';diff --git a/packages/agent-signal/src/brief/selfReviewBriefDetails.test.ts b/packages/agent-signal/src/brief/selfReviewBriefDetails.test.tsnew file mode 100644index 00000000000..c29787a5d4e--- /dev/null+++ b/packages/agent-signal/src/brief/selfReviewBriefDetails.test.ts@@ -0,0 +1,160 @@+import { describe, expect, it } from 'vitest';++import {+ formatSelfReviewBriefSummary,+ formatSelfReviewBriefTitle,+ getSelfReviewBriefDetails,+ type SelfReviewBriefDetailsTranslator,+} from './selfReviewBriefDetails';++const en: Record<string, string> = {+ 'brief.agentSignal.selfReview.kind.create_skill.plain': 'New skill',+ 'brief.agentSignal.selfReview.kind.create_skill.withTarget': 'New skill: {{target}}',+ 'brief.agentSignal.selfReview.kind.idea.plain': 'Dream note',+ 'brief.agentSignal.selfReview.kind.idea.withTarget': 'Dream note: {{target}}',+ 'brief.agentSignal.selfReview.kind.refine_prompt.plain': 'Refine system prompt',+ 'brief.agentSignal.selfReview.kind.refine_skill.withTarget': 'Refine skill: {{target}}',+ 'brief.agentSignal.selfReview.list.more': '{{count}} more',+ 'brief.agentSignal.selfReview.title.more': '{{title}} (+{{count}} more)',+};++const t: SelfReviewBriefDetailsTranslator = (key, options = {}) =>+ Object.entries(options).reduce(+ (content, [name, value]) => content.replace(`{{${name}}}`, value),+ en[key] ?? key,+ );++const createSkillAction = {+ actionType: 'create_skill',+ baseSnapshot: { absent: true, skillName: 'pr-checklist', targetType: 'skill' },+ evidenceRefs: [],+ idempotencyKey: 'a1',+ operation: {+ domain: 'skill',+ input: {+ bodyMarkdown: '# PR checklist',+ description: 'Checklist for reviewing pull requests.',+ name: 'pr-checklist',+ title: 'PR checklist',+ },+ operation: 'create',+ },+ rationale: 'The user asked for the same PR review steps three times.',+ risk: 'low',+ target: { skillName: 'pr-checklist' },+};++const proposalMetadata = (actions: unknown[], summary?: string) => ({+ agentSignal: {+ nightlySelfReview: {+ outcome: 'proposal',+ selfReviewProposal: { actions, status: 'pending', ...(summary ? { summary } : {}) },+ },+ },+});++describe('selfReviewBriefDetails', () => {+ it('names a single create_skill proposal by its skill title', () => {+ const details = getSelfReviewBriefDetails(+ proposalMetadata([createSkillAction], 'Save the PR review steps as a skill.'),+ );++ expect(details).toEqual({+ items: [+ {+ description: 'The user asked for the same PR review steps three times.',+ kind: 'create_skill',+ target: 'PR checklist',+ },+ ],+ kind: 'proposal',+ summary: 'Save the PR review steps as a skill.',+ });+ expect(formatSelfReviewBriefTitle(details!, t)).toBe('New skill: PR checklist');+ expect(formatSelfReviewBriefSummary(details!, t)).toBe('Save the PR review steps as a skill.');+ });++ it('falls back to the rationale when the proposal has no summary', () => {+ const details = getSelfReviewBriefDetails(proposalMetadata([createSkillAction]));++ expect(formatSelfReviewBriefSummary(details!, t)).toBe(+ 'The user asked for the same PR review steps three times.',+ );+ });++ it('lists every action of a multi-action proposal', () => {+ const details = getSelfReviewBriefDetails(+ proposalMetadata([+ createSkillAction,+ {+ actionType: 'refine_skill',+ baseSnapshot: { targetTitle: 'Release notes' },+ rationale: 'Release notes keep missing the migration section.',+ },+ { actionType: 'refine_prompt', rationale: 'Answer in the user language.' },+ { actionType: 'noop', rationale: 'Nothing to do.' },+ ]),+ );++ expect(details?.items.map((item) => item.kind)).toEqual([+ 'create_skill',+ 'refine_skill',+ 'refine_prompt',+ ]);+ expect(formatSelfReviewBriefTitle(details!, t)).toBe('New skill: PR checklist (+2 more)');+ expect(formatSelfReviewBriefSummary(details!, t)).toBe(+ [+ '- **New skill: PR checklist** — The user asked for the same PR review steps three times.',+ '- **Refine skill: Release notes** — Release notes keep missing the migration section.',+ '- **Refine system prompt** — Answer in the user language.',+ ].join('\n'),+ );+ });++ it('caps the persisted list and counts the rest', () => {+ const actions = Array.from({ length: 7 }, (_, index) => ({+ ...createSkillAction,+ operation: { ...createSkillAction.operation, input: { title: `Skill ${index + 1}` } },+ }));+ const summary = formatSelfReviewBriefSummary(+ getSelfReviewBriefDetails(proposalMetadata(actions))!,+ t,+ );++ expect(summary.split('\n')).toHaveLength(6);+ expect(summary).toContain('- **New skill: Skill 5**');+ expect(summary).not.toContain('Skill 6');+ expect(summary.endsWith('- 2 more')).toBe(true);+ });++ it('lists ideas of an ideas-only brief', () => {+ const details = getSelfReviewBriefDetails({+ agentSignal: {+ nightlySelfReview: {+ ideas: [+ { rationale: 'Users often ask for weekly summaries.', title: 'Weekly digest' },+ { rationale: 'A deploy checklist could prevent rollbacks.' },+ ],+ outcome: 'ideas',+ },+ },+ });++ expect(details?.kind).toBe('ideas');+ expect(formatSelfReviewBriefTitle(details!, t)).toBe('Dream note: Weekly digest (+1 more)');+ expect(formatSelfReviewBriefSummary(details!, t)).toBe(+ [+ '- **Dream note: Weekly digest** — Users often ask for weekly summaries.',+ '- **Dream note: A deploy checklist could prevent rollbacks.**',+ ].join('\n'),+ );+ });++ it('returns undefined for briefs without proposal actions or ideas', () => {+ expect(getSelfReviewBriefDetails(undefined)).toBeUndefined();+ expect(getSelfReviewBriefDetails({ goal: { goalId: 'g' } })).toBeUndefined();+ expect(+ getSelfReviewBriefDetails(proposalMetadata([{ actionType: 'noop', rationale: 'x' }])),+ ).toBeUndefined();+ });+});diff --git a/packages/agent-signal/src/brief/selfReviewBriefDetails.ts b/packages/agent-signal/src/brief/selfReviewBriefDetails.tsnew file mode 100644index 00000000000..636ec14c69a--- /dev/null+++ b/packages/agent-signal/src/brief/selfReviewBriefDetails.ts@@ -0,0 +1,284 @@+/**+ * Display model for Agent Signal nightly self-review Daily Briefs.+ *+ * The persisted brief metadata (`metadata.agentSignal.nightlySelfReview`) already+ * holds the frozen proposal actions and ideas. This module reads that payload+ * into a small, locale-free display model and formats it with a caller-supplied+ * translator, so the server (persisted brief text) and the client (home card)+ * describe the same proposal with the same words.+ */++/** Kind of change one detail row describes. */+export type SelfReviewBriefDetailKind =+ | 'consolidate_skill'+ | 'create_skill'+ | 'idea'+ | 'other'+ | 'refine_prompt'+ | 'refine_skill'+ | 'write_memory';++/** One proposed action or recorded idea, reduced to what a reader needs. */+export interface SelfReviewBriefDetailItem {+ /** One-line explanation: the rationale, or the skill description when no rationale exists. */+ description?: string;+ /** What kind of change this row proposes. */+ kind: SelfReviewBriefDetailKind;+ /** Human-readable target: skill title/name, memory text, or idea title. */+ target?: string;+}++/** Locale-free display model of one nightly self-review brief. */+export interface SelfReviewBriefDetails {+ /** Proposed actions or recorded ideas, in proposal order. */+ items: SelfReviewBriefDetailItem[];+ /** Whether the brief asks for a decision or only records ideas. */+ kind: 'ideas' | 'proposal';+ /** Reviewer-written proposal summary, when one was stored. */+ summary?: string;+}++/** Translator resolving `home` namespace keys with string interpolation. */+export type SelfReviewBriefDetailsTranslator = (+ key: string,+ options?: Record<string, string>,+) => string;++const KEY_PREFIX = 'brief.agentSignal.selfReview';++/** Longest target shown inside a title before it is cut with an ellipsis. */+export const SELF_REVIEW_TITLE_TARGET_MAX_LENGTH = 60;+/** Longest one-line description kept in persisted brief text. */+export const SELF_REVIEW_DESCRIPTION_MAX_LENGTH = 160;+/** Rows listed in persisted brief text before the rest collapse into "+N more". */+export const SELF_REVIEW_LIST_MAX_ITEMS = 5;++const KNOWN_KINDS = new Set<SelfReviewBriefDetailKind>([+ 'consolidate_skill',+ 'create_skill',+ 'refine_prompt',+ 'refine_skill',+ 'write_memory',+]);++const asRecord = (value: unknown): Record<string, unknown> =>+ value && typeof value === 'object' && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};++const pickString = (...values: unknown[]) => {+ for (const value of values) {+ if (typeof value !== 'string') continue;+ const trimmed = value.trim();+ if (trimmed) return trimmed;+ }+};++/**+ * Collapses whitespace to a single line and cuts it to `maxLength` characters.+ *+ * Use when:+ * - Model-written text (rationale, memory content) is shown in a one-line slot+ *+ * Returns:+ * - The trimmed single-line text, ending in `…` when it was cut+ */+export const toSelfReviewOneLine = (text: string, maxLength: number) => {+ const line = text.replaceAll(/\s+/g, ' ').trim();+ const chars = [...line];++ return chars.length > maxLength ? `${chars.slice(0, maxLength - 1).join('')}…` : line;+};++const getActionTarget = (kind: SelfReviewBriefDetailKind, action: Record<string, unknown>) => {+ const target = asRecord(action.target);+ const snapshot = asRecord(action.baseSnapshot);+ const input = asRecord(asRecord(action.operation).input);++ switch (kind) {+ case 'create_skill': {+ return pickString(input.title, input.name, target.skillName, snapshot.skillName);+ }+ case 'refine_skill':+ case 'consolidate_skill': {+ return pickString(snapshot.targetTitle, target.skillName, input.title, snapshot.skillName);+ }+ case 'write_memory': {+ return pickString(input.content);+ }+ case 'refine_prompt': {+ return;+ }+ default: {+ return pickString(snapshot.targetTitle, target.skillName, input.title, input.name);+ }+ }+};++const toActionItem = (value: unknown): SelfReviewBriefDetailItem | undefined => {+ const action = asRecord(value);+ const actionType = pickString(action.actionType);+ if (!actionType || actionType === 'noop' || actionType === 'proposal_only') return;++ const kind = KNOWN_KINDS.has(actionType as SelfReviewBriefDetailKind)+ ? (actionType as SelfReviewBriefDetailKind)+ : 'other';+ const target = getActionTarget(kind, action);+ const description = pickString(+ action.rationale,+ asRecord(asRecord(action.operation).input).description,+ );++ return {+ ...(description ? { description } : {}),+ kind,+ ...(target ? { target } : {}),+ };+};++const toIdeaItem = (value: unknown): SelfReviewBriefDetailItem | undefined => {+ const idea = asRecord(value);+ const target = pickString(idea.title, asRecord(idea.target).skillName);+ const description = pickString(idea.rationale);+ if (!target && !description) return;++ return {+ ...(description ? { description } : {}),+ kind: 'idea',+ ...(target ? { target } : {}),+ };+};++/**+ * Reads the nightly self-review display model from Daily Brief metadata.+ *+ * Use when:+ * - The server projects persisted title/summary text for a nightly review brief+ * - A client card renders proposal details inline, including briefs stored+ * before the persisted text named the change+ *+ * Expects:+ * - `metadata` is the brief's raw `metadata` JSON (any shape is tolerated)+ *+ * Returns:+ * - The display model for proposal or ideas briefs, or `undefined` when the+ * metadata carries no proposal actions or ideas to describe+ */+export const getSelfReviewBriefDetails = (+ metadata: unknown,+): SelfReviewBriefDetails | undefined => {+ const nightly = asRecord(asRecord(asRecord(metadata).agentSignal).nightlySelfReview);+ const proposal = asRecord(nightly.selfReviewProposal);++ if (Array.isArray(proposal.actions)) {+ const items = proposal.actions.flatMap((action) => toActionItem(action) ?? []);+ const summary = pickString(proposal.summary);++ if (items.length > 0) return { items, kind: 'proposal', ...(summary ? { summary } : {}) };+ }++ if (nightly.outcome === 'ideas' && Array.isArray(nightly.ideas)) {+ const items = nightly.ideas.flatMap((idea) => toIdeaItem(idea) ?? []);++ if (items.length > 0) return { items, kind: 'ideas' };+ }+};++/**+ * Formats the short kind label of one row, e.g. `New skill`.+ */+export const formatSelfReviewKindLabel = (+ kind: SelfReviewBriefDetailKind,+ t: SelfReviewBriefDetailsTranslator,+) => t(`${KEY_PREFIX}.kind.${kind}.plain`);++/**+ * Formats one row as a headline naming its target, e.g. `New skill: PR checklist`.+ */+export const formatSelfReviewItemHeadline = (+ item: SelfReviewBriefDetailItem,+ t: SelfReviewBriefDetailsTranslator,+) => {+ // An idea without a title still has something to say; its rationale is the headline.+ const target = item.target ?? (item.kind === 'idea' ? item.description : undefined);++ return target && item.kind !== 'refine_prompt'+ ? t(`${KEY_PREFIX}.kind.${item.kind}.withTarget`, {+ target: toSelfReviewOneLine(target, SELF_REVIEW_TITLE_TARGET_MAX_LENGTH),+ })+ : formatSelfReviewKindLabel(item.kind, t);+};++/**+ * Formats a brief title that names the main proposed change or idea.+ *+ * Returns:+ * - `New skill: PR checklist`, or `New skill: PR checklist (+2 more)` when the+ * brief carries several rows+ */+export const formatSelfReviewBriefTitle = (+ details: SelfReviewBriefDetails,+ t: SelfReviewBriefDetailsTranslator,+) => {+ const items = details.items ?? [];+ const headline = formatSelfReviewItemHeadline(items[0], t);+ const rest = items.length - 1;++ return rest > 0+ ? t(`${KEY_PREFIX}.title.more`, { count: String(rest), title: headline })+ : headline;+};++/**+ * Picks the one- or two-line lead under the title: the proposal summary, else+ * the first row's rationale.+ */+export const getSelfReviewBriefLead = (details: SelfReviewBriefDetails) => {+ if (details.summary) return details.summary;+ const items = details.items ?? [];+ if (items.length !== 1) return;++ const [item] = items;+ // A titleless idea already used its rationale as the headline.+ if (item.kind === 'idea' && !item.target) return;++ return item.description;+};++/**+ * Formats the persisted Markdown summary for a nightly self-review brief.+ *+ * Use when:+ * - The server persists brief text read by surfaces that only render `summary`+ * (news list, notifications, brief tools)+ *+ * Returns:+ * - The lead line, followed by a bounded bullet list when there are several rows+ */+export const formatSelfReviewBriefSummary = (+ details: SelfReviewBriefDetails,+ t: SelfReviewBriefDetailsTranslator,+) => {+ const lead = getSelfReviewBriefLead(details);+ const parts = lead ? [toSelfReviewOneLine(lead, SELF_REVIEW_DESCRIPTION_MAX_LENGTH)] : [];++ const items = details.items ?? [];+ if (items.length > 1) {+ const shown = items.slice(0, SELF_REVIEW_LIST_MAX_ITEMS);+ const lines = shown.map((item) => {+ const headline = formatSelfReviewItemHeadline(item, t);+ const description =+ item.description && !(item.kind === 'idea' && !item.target)+ ? ` — ${toSelfReviewOneLine(item.description, SELF_REVIEW_DESCRIPTION_MAX_LENGTH)}`+ : '';++ return `- **${headline}**${description}`;+ });+ const hidden = items.length - shown.length;+ if (hidden > 0) lines.push(`- ${t(`${KEY_PREFIX}.list.more`, { count: String(hidden) })}`);++ parts.push(lines.join('\n'));+ }++ return parts.join('\n\n');+};diff --git a/packages/agent-signal/src/source/sourceTypes.ts b/packages/agent-signal/src/source/sourceTypes.tsindex 3f9d397f2e2..838261ca973 100644--- a/packages/agent-signal/src/source/sourceTypes.ts+++ b/packages/agent-signal/src/source/sourceTypes.ts@@ -110,6 +110,12 @@ export interface AgentSignalSourcePayloadMap {anchorMessageId?: string;documentPayload?: Record<string, unknown>;intents?: Array<'document' | 'memory' | 'persona' | 'prompt' | 'skill'>;+ /**+ * `true` when the producer knows the user message opens its conversation: it has no+ * parent message and no thread, so there is no earlier reply it could give feedback on.+ * `undefined` means unknown; consumers must treat it as possibly having a prior reply.+ */+ isConversationRoot?: boolean;memoryPayload?: Record<string, unknown>;message: string;/** Legacy source message identifier kept for compatibility. */@@ -350,8 +356,7 @@ export type SourceEventAgentSelfFeedbackIntentDeclared =/** Normalized tool outcome source event. */export type SourceEventToolOutcome =- | AgentSignalSourceEvent<'tool.outcome.completed'>- | AgentSignalSourceEvent<'tool.outcome.failed'>;+ AgentSignalSourceEvent<'tool.outcome.completed'> | AgentSignalSourceEvent<'tool.outcome.failed'>;/** Source types accepted by browser producers through the authenticated edge. */export const AGENT_SIGNAL_CLIENT_SOURCE_TYPES = [diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.tsindex 0fbd3f891b6..889d3a6b4d6 100644--- a/packages/app-config/src/featureFlags/schema.test.ts+++ b/packages/app-config/src/featureFlags/schema.test.ts@@ -8,6 +8,17 @@ import {} from './schema';describe('FeatureFlagsSchema', () => {+ /**+ * A published runtime-config snapshot may still hold a flag that was since removed;+ * it must neither fail validation nor reach the mapped client state.+ */+ it('drops unknown flags instead of failing validation', () => {+ const result = FeatureFlagsSchema.safeParse({ dashboard: true, some_removed_flag: ['user-1'] });++ expect(result.success).toBe(true);+ expect(result.data).toEqual({ dashboard: true });+ });+it('should validate correct feature flags with boolean values', () => {const result = FeatureFlagsSchema.safeParse({provider_settings: false,@@ -205,7 +216,6 @@ describe('mapFeatureFlagsEnvToState', () => {welcome_suggest: true,knowledge_base: false,rag_eval: true,- agent_self_iteration: true,agent_onboarding: true,auth_captcha: true,market: true,@@ -233,7 +243,6 @@ describe('mapFeatureFlagsEnvToState', () => {showWelcomeSuggest: true,enableKnowledgeBase: false,enableRAGEval: true,- enableAgentSelfIteration: true,enableAgentOnboarding: true,enableAuthCaptcha: true,enableStorageOverage: false,@@ -250,7 +259,6 @@ describe('mapFeatureFlagsEnvToState', () => {const userId = 'user-123';const config = {edit_agent: ['user-123', 'user-456'],- agent_self_iteration: ['user-123'],agent_onboarding: ['user-123'],auth_captcha: ['user-123'],storage_overage: ['user-123'],@@ -262,8 +270,6 @@ describe('mapFeatureFlagsEnvToState', () => {const mappedState = mapFeatureFlagsEnvToState(config, userId);expect(mappedState.isAgentEditable).toBe(true); // user-123 is in allowlist-- expect(mappedState.enableAgentSelfIteration).toBe(true); // user-123 is in allowlistexpect(mappedState.enableAgentOnboarding).toBe(true); // user-123 is in allowlistexpect(mappedState.enableAuthCaptcha).toBe(true); // user-123 is in allowlistexpect(mappedState.enableStorageOverage).toBe(true); // user-123 is in allowlist@@ -285,15 +291,12 @@ describe('mapFeatureFlagsEnvToState', () => {it('should return false for array flags when no user ID provided', () => {const config = {- agent_self_iteration: ['user-1'],agent_onboarding: ['user-1'],edit_agent: ['user-123', 'user-456'],create_session: true,};const mappedState = mapFeatureFlagsEnvToState(config);-- expect(mappedState.enableAgentSelfIteration).toBe(false);expect(mappedState.enableAgentOnboarding).toBe(false);expect(mappedState.isAgentEditable).toBe(false);});@@ -302,7 +305,6 @@ describe('mapFeatureFlagsEnvToState', () => {const userId = 'user-123';const config = {edit_agent: ['user-123'],- agent_self_iteration: ['user-123'],agent_onboarding: ['user-123'],create_session: true,dalle: false,@@ -314,8 +316,6 @@ describe('mapFeatureFlagsEnvToState', () => {const mappedState = mapFeatureFlagsEnvToState(config, userId);expect(mappedState.isAgentEditable).toBe(true);-- expect(mappedState.enableAgentSelfIteration).toBe(true);expect(mappedState.enableAgentOnboarding).toBe(true);expect(mappedState.showAiImage).toBe(false);expect(mappedState.enableKnowledgeBase).toBe(true);diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.tsindex 5a203f96fbc..3faca6445b2 100644--- a/packages/app-config/src/featureFlags/schema.ts+++ b/packages/app-config/src/featureFlags/schema.ts@@ -69,7 +69,6 @@ export const FeatureFlagsSchema = z.object({dashboard: FeatureFlagValue.optional(),// internal flag- agent_self_iteration: FeatureFlagValue.optional(),agent_onboarding: FeatureFlagValue.optional(),dev_dock: FeatureFlagValue.optional(),dev_dock_workspaces: z.array(z.string()).optional(),@@ -141,7 +140,6 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {// Off until an admin publishes a user allowlist or flips it to true.dashboard: false,- agent_self_iteration: isDev,agent_onboarding: isDev,dev_dock: isDev,auth_captcha: true,@@ -191,7 +189,6 @@ export const mapFeatureFlagsEnvToState = (enableKnowledgeBase: evaluateFeatureFlag(config.knowledge_base, userId),enableRAGEval: evaluateFeatureFlag(config.rag_eval, userId),- enableAgentSelfIteration: evaluateFeatureFlag(config.agent_self_iteration, userId),enableAgentOnboarding: evaluateFeatureFlag(config.agent_onboarding, userId),enableDevDock: evaluateFeatureFlag(config.dev_dock, userId),enableAuthCaptcha: evaluateFeatureFlag(config.auth_captcha, userId),diff --git a/packages/app-config/src/featureFlags/utils/parser.test.ts b/packages/app-config/src/featureFlags/utils/parser.test.tsindex 02f5977f664..c522ab8483e 100644--- a/packages/app-config/src/featureFlags/utils/parser.test.ts+++ b/packages/app-config/src/featureFlags/utils/parser.test.ts@@ -57,6 +57,13 @@ describe('parseFeatureFlag', () => {expect(parseFeatureFlag(input)).toEqual({});});+ it('ignores unknown flag names while keeping known ones', () => {+ expect(parseFeatureFlag('-some_removed_flag')).toEqual({});+ expect(parseFeatureFlag('+some_removed_flag,+api_key_manage')).toEqual({+ api_key_manage: true,+ });+ });+it('ignores +/- on array-only flags like dev_dock_workspaces', () => {expect(parseFeatureFlag('+dev_dock_workspaces')).toEqual({});expect(parseFeatureFlag('-dev_dock_workspaces,+api_key_manage')).toEqual({diff --git a/packages/builtin-tool-agent-signal/src/review/systemRole.ts b/packages/builtin-tool-agent-signal/src/review/systemRole.tsindex c823eac6ad8..bfed06d1c3d 100644--- a/packages/builtin-tool-agent-signal/src/review/systemRole.ts+++ b/packages/builtin-tool-agent-signal/src/review/systemRole.ts@@ -6,4 +6,6 @@ Read evidence first (getEvidenceDigest, listManagedSkills, getManagedSkill, list- createSelfReviewProposal / refreshSelfReviewProposal / supersedeSelfReviewProposal / closeSelfReviewProposal: user-visible proposals for changes that need approval.- recordSelfReviewIdea: non-actionable ideas or open questions to surface in the Daily Brief without a proposal.+Each createSelfReviewProposal action must set the field \`actionType\` (not \`type\`) to create_skill, refine_skill, consolidate_skill, refine_prompt, write_memory or proposal_only, plus its target and operation — e.g. create_skill: target { skillName }, operation { domain: "skill", operation: "create", input: { name, title, description, bodyMarkdown } }.+Always pass a stable idempotencyKey on writes. Cite evidenceRefs you actually read. Be concise and conservative — prefer recording an idea or proposal over a direct mutation when confidence or sensitivity is borderline.`;diff --git a/packages/builtin-tool-agent-signal/src/shared/schemas.ts b/packages/builtin-tool-agent-signal/src/shared/schemas.tsindex dbf0ebb4a01..c6390fa6c6c 100644--- a/packages/builtin-tool-agent-signal/src/shared/schemas.ts+++ b/packages/builtin-tool-agent-signal/src/shared/schemas.ts@@ -22,6 +22,41 @@ const obj = (required: readonly string[] = [],): Record<string, unknown> => ({ properties, required: [...required], type: 'object' });+const selfReviewProposalActionsSchema = {+ items: {+ additionalProperties: true,+ properties: {+ actionType: {+ description:+ 'Kind of change. proposal_only records an idea without a change. Use the field name actionType, not type.',+ enum: [+ 'create_skill',+ 'refine_skill',+ 'consolidate_skill',+ 'refine_prompt',+ 'write_memory',+ 'proposal_only',+ ],+ type: 'string',+ },+ operation: {+ ...freeObj,+ description:+ 'Domain operation, e.g. { domain: "skill", operation: "create", input: { name, title, description, bodyMarkdown } }.',+ },+ rationale: str,+ target: {+ ...freeObj,+ description: 'Target such as { skillName }, { skillDocumentId } or { agentId }.',+ },+ },+ required: ['actionType'],+ type: 'object',+ },+ minItems: 1,+ type: 'array',+} as const;+const evidenceRefsSchema = {items: {properties: {@@ -161,7 +196,13 @@ export const REVIEW_TOOL_APIS: ToolApiSpec[] = [description: 'Create one user-visible self-review proposal for later approval.',name: 'createSelfReviewProposal',parameters: obj(- { actions: freeArr, idempotencyKey: str, metadata: freeObj, proposalKey: str, summary: str },+ {+ actions: selfReviewProposalActionsSchema,+ idempotencyKey: str,+ metadata: freeObj,+ proposalKey: str,+ summary: str,+ },['idempotencyKey', 'proposalKey', 'summary', 'actions'],),},diff --git a/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts b/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.tsindex 09dafb9ee5f..04750e8960e 100644--- a/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts+++ b/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts@@ -1,6 +1,6 @@// @vitest-environment nodeimport { INBOX_SESSION_ID } from '@lobechat/const';-import { sql } from 'drizzle-orm';+import { eq, sql } from 'drizzle-orm';import { beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';@@ -23,27 +23,48 @@ const enabledUserWithoutTimezoneId = 'nightly-review-enabled-user-utc';const disabledUserId = 'nightly-review-disabled-user';const otherUserId = 'nightly-review-other-user';+/** Users the nightly scan may list: Labs → Self-evolving is the user-level gate. */+const SELF_LEARNING_ON = { lab: { enableSelfLearning: true } };++const withSelfLearning = <T extends object>(rows: T | T[]) =>+ (Array.isArray(rows) ? rows : [rows]).map((row) => ({ preference: SELF_LEARNING_ON, ...row }));+beforeEach(async () => {await serverDB.delete(users);});describe('AgentSignalNightlyReviewModel', () => {describe('listEligibleUsers', () => {- it('lists all users regardless of the lab opt-in preference', async () => {- await serverDB.insert(users).values([- {- createdAt: new Date('2026-05-01T00:00:00.000Z'),- id: enabledUserId,- },- {- createdAt: new Date('2026-05-02T00:00:00.000Z'),- id: enabledUserWithoutTimezoneId,- },- {- createdAt: new Date('2026-05-03T00:00:00.000Z'),- id: disabledUserId,- },- ]);+ /**+ * The Labs → Self-evolving switch replaced the per-user `agent_self_iteration` flag lookup+ * that ran after the scan; filtering in SQL keeps opted-out users out of the fan-out.+ *+ * @example+ * expect(result.map((user) => user.id)).toEqual([enabledUserId, enabledUserWithoutTimezoneId]);+ */+ it('lists only users who turned Self-evolving on in Labs', async () => {+ await serverDB.insert(users).values(+ withSelfLearning([+ {+ createdAt: new Date('2026-05-01T00:00:00.000Z'),+ id: enabledUserId,+ },+ {+ createdAt: new Date('2026-05-02T00:00:00.000Z'),+ id: enabledUserWithoutTimezoneId,+ },+ {+ createdAt: new Date('2026-05-03T00:00:00.000Z'),+ id: disabledUserId,+ preference: { lab: { enableSelfLearning: false } },+ },+ {+ createdAt: new Date('2026-05-04T00:00:00.000Z'),+ id: otherUserId,+ preference: {},+ },+ ]),+ );await serverDB.insert(userSettings).values({general: { timezone: 'Asia/Shanghai' },id: enabledUserId,@@ -64,25 +85,32 @@ describe('AgentSignalNightlyReviewModel', () => {id: enabledUserWithoutTimezoneId,timezone: 'UTC',},- {- createdAt: new Date('2026-05-03T00:00:00.000Z'),- id: disabledUserId,- timezone: 'UTC',- },]);});+ it('drops whitelisted users whose Self-evolving switch is off', async () => {+ await serverDB+ .insert(users)+ .values([{ createdAt: new Date('2026-05-01T00:00:00.000Z'), id: disabledUserId }]);++ const model = new AgentSignalNightlyReviewModel(serverDB);++ expect(await model.listEligibleUsers({ whitelist: [disabledUserId] })).toEqual([]);+ });+it('uses cursor and whitelist filters for targeted scheduling pages', async () => {- await serverDB.insert(users).values([- {- createdAt: new Date('2026-05-01T00:00:00.000Z'),- id: enabledUserId,- },- {- createdAt: new Date('2026-05-02T00:00:00.000Z'),- id: enabledUserWithoutTimezoneId,- },- ]);+ await serverDB.insert(users).values(+ withSelfLearning([+ {+ createdAt: new Date('2026-05-01T00:00:00.000Z'),+ id: enabledUserId,+ },+ {+ createdAt: new Date('2026-05-02T00:00:00.000Z'),+ id: enabledUserWithoutTimezoneId,+ },+ ]),+ );const model = new AgentSignalNightlyReviewModel(serverDB);@@ -115,10 +143,10 @@ describe('AgentSignalNightlyReviewModel', () => {// Before: created_at .000123 > replayed cursor .000, so the same user was returned again.// After: the cursor id restores the exact (created_at, id) tuple inside PostgreSQL.await serverDB.execute(sql`- INSERT INTO users (id, created_at, updated_at, last_active_at)+ INSERT INTO users (id, created_at, updated_at, last_active_at, preference)VALUES- ('nightly-review-microsecond-cursor', '2026-05-01T00:00:00.000123Z', NOW(), NOW()),- ('nightly-review-microsecond-next', '2026-05-02T00:00:00.000456Z', NOW(), NOW())+ ('nightly-review-microsecond-cursor', '2026-05-01T00:00:00.000123Z', NOW(), NOW(), ${JSON.stringify(SELF_LEARNING_ON)}::jsonb),+ ('nightly-review-microsecond-next', '2026-05-02T00:00:00.000456Z', NOW(), NOW(), ${JSON.stringify(SELF_LEARNING_ON)}::jsonb)`);const model = new AgentSignalNightlyReviewModel(serverDB);@@ -144,16 +172,18 @@ describe('AgentSignalNightlyReviewModel', () => {* review time — drifted later every day.** The activity floor is a strict superset of every per-user review window, so narrowing on- * it can only skip a dispatch the local-window check would have skipped anyway. The window- * itself stays in the service layer, which resolves timezones through `Intl`; pushing it- * into SQL would make the scan depend on the database's tzdata build agreeing with `Intl`,- * and it buys little at the busiest hour anyway.+ * it can only skip a dispatch the local-window check would have skipped anyway. The local+ * window is also prefiltered here (see `listEligibleUsers local-hour prefilter`), but only as+ * a widened superset: the exact window stays in the service layer, which resolves timezones+ * through `Intl` and does not depend on the database's tzdata build.*/const seedActivity = async () => {- await serverDB.insert(users).values([- { createdAt: new Date('2026-05-01T00:00:00.000Z'), id: enabledUserId },- { createdAt: new Date('2026-05-02T00:00:00.000Z'), id: otherUserId },- ]);+ await serverDB.insert(users).values(+ withSelfLearning([+ { createdAt: new Date('2026-05-01T00:00:00.000Z'), id: enabledUserId },+ { createdAt: new Date('2026-05-02T00:00:00.000Z'), id: otherUserId },+ ]),+ );await serverDB.insert(userSettings).values([{ general: { timezone: 'Asia/Shanghai' }, id: enabledUserId },{ general: { timezone: 'America/New_York' }, id: otherUserId },@@ -215,10 +245,12 @@ describe('AgentSignalNightlyReviewModel', () => {* expect(result).toEqual([]);*/it('ignores workspace activity when deciding who is a candidate', async () => {- await serverDB.insert(users).values({- createdAt: new Date('2026-05-01T00:00:00.000Z'),- id: enabledUserId,- });+ await serverDB.insert(users).values(+ withSelfLearning({+ createdAt: new Date('2026-05-01T00:00:00.000Z'),+ id: enabledUserId,+ }),+ );const [workspace] = await serverDB.insert(workspaces).values({@@ -277,12 +309,97 @@ describe('AgentSignalNightlyReviewModel', () => {});});+ describe('listEligibleUsers local-hour prefilter', () => {+ /**+ * ROOT CAUSE:+ *+ * Every hourly fire dispatched one QStash execute workflow per recently active user, and ~22+ * of every 24 of those runs only discovered inside the workflow that the user's local clock+ * was outside 02:00-04:00. The prefilter drops those rows before pagination fans out.+ *+ * At 2026-05-03T18:30Z it is 02:30 in Shanghai, 14:30 in New York and 18:30 in UTC.+ */+ const at = new Date('2026-05-03T18:30:00.000Z');+ const shanghaiUserId = 'nightly-tz-shanghai';+ const newYorkUserId = 'nightly-tz-new-york';+ const missingTimezoneUserId = 'nightly-tz-missing';+ const invalidTimezoneUserId = 'nightly-tz-invalid';++ const seedTimezones = async () => {+ await serverDB.insert(users).values(+ withSelfLearning([+ { createdAt: new Date('2026-05-01T00:00:00.000Z'), id: shanghaiUserId },+ { createdAt: new Date('2026-05-02T00:00:00.000Z'), id: newYorkUserId },+ { createdAt: new Date('2026-05-03T00:00:00.000Z'), id: missingTimezoneUserId },+ { createdAt: new Date('2026-05-04T00:00:00.000Z'), id: invalidTimezoneUserId },+ ]),+ );+ await serverDB.insert(userSettings).values([+ { general: { timezone: 'Asia/Shanghai' }, id: shanghaiUserId },+ { general: { timezone: 'America/New_York' }, id: newYorkUserId },+ { general: { timezone: 'Invalid/Zone' }, id: invalidTimezoneUserId },+ ]);+ };++ it('keeps only users whose local hour is inside the window', async () => {+ await seedTimezones();+ const model = new AgentSignalNightlyReviewModel(serverDB);++ const result = await model.listEligibleUsers({+ localHourWindow: { at, endHourExclusive: 5, startHour: 1 },+ });++ // Shanghai is in-window; an unrecognised zone passes through for the exact check upstream;+ // New York (14:30) and the UTC fallback (18:30) are dropped.+ expect(result.map((item) => item.id)).toEqual([shanghaiUserId, invalidTimezoneUserId]);+ });++ it('evaluates a missing timezone as UTC', async () => {+ await seedTimezones();+ const model = new AgentSignalNightlyReviewModel(serverDB);++ const result = await model.listEligibleUsers({+ localHourWindow: {+ at: new Date('2026-05-03T02:30:00.000Z'),+ endHourExclusive: 4,+ startHour: 2,+ },+ });++ expect(result.map((item) => item.id)).toEqual([missingTimezoneUserId, invalidTimezoneUserId]);+ });++ it('keeps pagination stable across filtered rows', async () => {+ await seedTimezones();+ const model = new AgentSignalNightlyReviewModel(serverDB);++ const firstPage = await model.listEligibleUsers({+ limit: 1,+ localHourWindow: { at, endHourExclusive: 5, startHour: 1 },+ });+ const secondPage = await model.listEligibleUsers({+ cursor: firstPage[0],+ limit: 1,+ localHourWindow: { at, endHourExclusive: 5, startHour: 1 },+ });+ const thirdPage = await model.listEligibleUsers({+ cursor: secondPage[0],+ limit: 1,+ localHourWindow: { at, endHourExclusive: 5, startHour: 1 },+ });++ expect(firstPage.map((item) => item.id)).toEqual([shanghaiUserId]);+ expect(secondPage.map((item) => item.id)).toEqual([invalidTimezoneUserId]);+ expect(thirdPage).toEqual([]);+ });+ });+describe('listActiveAgentTargets', () => {const chatConfigForSelfIteration = (enabled?: boolean) =>enabled === undefined ? {} : { selfIteration: { enabled } };const seedNightlyCapabilityTargets = async (caseName: string, blockedEnabled?: boolean) => {- await serverDB.insert(users).values({ id: enabledUserId });+ await serverDB.insert(users).values(withSelfLearning({ id: enabledUserId }));const [lobeAiAgent, blockedAgent, enabledAgent] = await serverDB.insert(agents)@@ -336,14 +453,18 @@ describe('AgentSignalNightlyReviewModel', () => {};/**- * @example- * expect(result.map((item) => item.agentId)).toEqual(['nightly-lobe-ai-disabled']).+ * There is no per-agent switch any more: Labs → Self-evolving is the only control, so legacy+ * `selfIteration.enabled: false` / `optedOut: true` values left in stored configs are ignored.*/- it('includes Lobe AI when the agent switch is disabled and excludes non-Lobe disabled agents', async () => {+ it('targets every active agent regardless of legacy per-agent self-iteration values', async () => {const { blockedAgent, enabledAgent, lobeAiAgent } = await seedNightlyCapabilityTargets(- 'disabled',+ 'legacy',false,);+ await serverDB+ .update(agents)+ .set({ chatConfig: { selfIteration: { enabled: false, optedOut: true } } })+ .where(eq(agents.id, lobeAiAgent.id));const model = new AgentSignalNightlyReviewModel(serverDB);@@ -352,31 +473,17 @@ describe('AgentSignalNightlyReviewModel', () => {windowStart: new Date('2026-05-03T00:00:00.000Z'),});- expect(result.map((item) => item.agentId)).toEqual([enabledAgent.id, lobeAiAgent.id]);- expect(result.map((item) => item.agentId)).not.toContain(blockedAgent.id);- });-- /**- * @example- * expect(result.map((item) => item.agentId)).toEqual(['nightly-lobe-ai-implicit']).- */- it('includes Lobe AI when the agent switch is missing and excludes non-Lobe implicit agents', async () => {- const { blockedAgent, enabledAgent, lobeAiAgent } =- await seedNightlyCapabilityTargets('implicit');-- 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'),- });-- expect(result.map((item) => item.agentId)).toEqual([enabledAgent.id, lobeAiAgent.id]);- expect(result.map((item) => item.agentId)).not.toContain(blockedAgent.id);+ expect(result.map((item) => item.agentId)).toEqual([+ enabledAgent.id,+ blockedAgent.id,+ lobeAiAgent.id,+ ]);});it('returns non-virtual agents with activity and failure counts inside the review window', async () => {- await serverDB.insert(users).values([{ id: enabledUserId }, { id: otherUserId }]);+ await serverDB+ .insert(users)+ .values(withSelfLearning([{ id: enabledUserId }, { id: otherUserId }]));await serverDB.insert(userSettings).values({general: { timezone: 'America/New_York' },id: enabledUserId,@@ -497,7 +604,7 @@ describe('AgentSignalNightlyReviewModel', () => {},{agentId: disabledAgent.id,- content: 'disabled agent should not schedule',+ content: 'a legacy per-agent off value no longer blocks scheduling',createdAt: new Date('2026-05-03T14:30:00.000Z'),id: 'nightly-message-disabled',role: 'user',@@ -537,6 +644,17 @@ describe('AgentSignalNightlyReviewModel', () => {});expect(result).toEqual([+ {+ agentId: disabledAgent.id,+ failedToolCallCount: 0,+ firstActivityAt: new Date('2026-05-03T14:30:00.000Z'),+ lastActivityAt: new Date('2026-05-03T14:30:00.000Z'),+ messageCount: 1,+ name: null,+ timezone: 'America/New_York',+ title: 'Disabled agent',+ topicCount: 1,+ },{agentId: legacyAgent.id,failedToolCallCount: 0,@@ -561,7 +679,6 @@ describe('AgentSignalNightlyReviewModel', () => {},]);expect(result.map((item) => item.agentId)).not.toContain(inactiveAgent.id);- expect(result.map((item) => item.agentId)).not.toContain(disabledAgent.id);expect(result.map((item) => item.agentId)).not.toContain(virtualAgent.id);expect(result.map((item) => item.agentId)).not.toContain(otherUserAgent.id);@@ -591,7 +708,7 @@ describe('AgentSignalNightlyReviewModel', () => {// 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(users).values(withSelfLearning({ id: enabledUserId }));await serverDB.insert(agents).values({chatConfig: { selfIteration: { enabled: true } },id: 'nightly-share-agent',diff --git a/packages/database/src/models/agentSignal/__tests__/reviewContext.test.ts b/packages/database/src/models/agentSignal/__tests__/reviewContext.test.tsindex 926909a9ea9..fcffb4f6b54 100644--- a/packages/database/src/models/agentSignal/__tests__/reviewContext.test.ts+++ b/packages/database/src/models/agentSignal/__tests__/reviewContext.test.ts@@ -49,6 +49,27 @@ describe('AgentSignalReviewContextModel', () => {).resolves.toBe(true);});+ /**+ * Labs → Self-evolving is the only control; legacy per-agent values are ignored.+ */+ it('ignores legacy per-agent opt-out values on inbox Lobe AI', async () => {+ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(agents).values({+ chatConfig: { selfIteration: { enabled: false, optedOut: true } } as never,+ id: 'agent-signal-review-context-inbox-off',+ slug: INBOX_SESSION_ID,+ title: 'Lobe AI',+ userId,+ virtual: true,+ });++ const model = new AgentSignalReviewContextModel(serverDB, userId);++ await expect(+ model.canAgentRunSelfIteration('agent-signal-review-context-inbox-off'),+ ).resolves.toBe(true);+ });+/*** @example* await expect(model.canAgentRunSelfIteration('agent-signal-review-context-task')).resolves.toBe(false).@@ -70,11 +91,7 @@ describe('AgentSignalReviewContextModel', () => {).resolves.toBe(false);});- /**- * @example- * await expect(model.canAgentRunSelfIteration('agent-signal-review-context-enabled')).resolves.toBe(true).- */- it('keeps non-Lobe AI agents behind chatConfig.selfIteration.enabled', async () => {+ it('allows every owned non-virtual agent, ignoring legacy selfIteration.enabled', async () => {await serverDB.insert(users).values({ id: userId });await serverDB.insert(agents).values([{@@ -91,16 +108,23 @@ describe('AgentSignalReviewContextModel', () => {title: 'Custom disabled',userId,},+ {+ id: 'agent-signal-review-context-implicit',+ slug: 'custom-implicit',+ title: 'Custom implicit',+ userId,+ },]);const model = new AgentSignalReviewContextModel(serverDB, userId);- await expect(- model.canAgentRunSelfIteration('agent-signal-review-context-enabled'),- ).resolves.toBe(true);- await expect(- model.canAgentRunSelfIteration('agent-signal-review-context-disabled'),- ).resolves.toBe(false);+ for (const id of [+ 'agent-signal-review-context-enabled',+ 'agent-signal-review-context-disabled',+ 'agent-signal-review-context-implicit',+ ]) {+ await expect(model.canAgentRunSelfIteration(id)).resolves.toBe(true);+ }});});diff --git a/packages/database/src/models/agentSignal/nightlyReview.ts b/packages/database/src/models/agentSignal/nightlyReview.tsindex 31232d5fd5d..4bb6259fbdb 100644--- a/packages/database/src/models/agentSignal/nightlyReview.ts+++ b/packages/database/src/models/agentSignal/nightlyReview.ts@@ -36,6 +36,25 @@ const cursorUsers = alias(users, 'nightly_review_cursor_users');const parseAggregateTimestamp = (value: Date | string) =>value instanceof Date ? value : new Date(value);+/**+ * Builds the SQL predicate that keeps users whose local hour at `at` is inside the window.+ *+ * `AT TIME ZONE` raises on an unknown zone name, which would fail the whole page, so the zone is+ * checked against `pg_timezone_names` first and unknown zones pass through to the caller's exact+ * check. Missing or empty timezones evaluate as UTC, matching the service-side fallback.+ */+const buildLocalHourCondition = (window: ListAgentSignalNightlyReviewUsersLocalHourWindow) => {+ const timezone = sql`COALESCE(NULLIF(${userSettings.general}->>'timezone', ''), 'UTC')`;+ const at = window.at.toISOString();++ return sql`CASE+ WHEN lower(${timezone}) IN (SELECT lower(name) FROM pg_timezone_names)+ THEN EXTRACT(HOUR FROM (${at}::timestamptz AT TIME ZONE ${timezone})) >= ${window.startHour}+ AND EXTRACT(HOUR FROM (${at}::timestamptz AT TIME ZONE ${timezone})) < ${window.endHourExclusive}+ ELSE true+ END`;+};+/** Cursor for stable user pagination in AgentSignal nightly review scheduling. */export interface ListAgentSignalNightlyReviewUsersCursor {/** User creation time retained in the serialized checkpoint for observability. */@@ -59,10 +78,30 @@ export interface ListAgentSignalNightlyReviewUsersOptions {cursor?: ListAgentSignalNightlyReviewUsersCursor;/** Maximum users to return. */limit?: number;+ /**+ * Coarse local-hour prefilter evaluated in each user's stored timezone.+ *+ * Callers must pass a window that is a superset of the exact window they enforce afterwards:+ * PostgreSQL's tzdata build can disagree with `Intl` by an offset change, so this is only a+ * cheap way to drop the users who are clearly not in their night, never the final authority.+ * A timezone PostgreSQL does not recognise is kept rather than evaluated, so a bad stored value+ * can neither fail the page nor be decided here.+ */+ localHourWindow?: ListAgentSignalNightlyReviewUsersLocalHourWindow;/** Optional user allowlist for backfills, tests, and targeted runs. */whitelist?: string[];}+/** Local-hour range used to prefilter nightly review candidates inside SQL. */+export interface ListAgentSignalNightlyReviewUsersLocalHourWindow {+ /** UTC instant whose local hour is evaluated for each user. */+ at: Date;+ /** Exclusive local hour upper bound, `startHour < endHourExclusive <= 24`. */+ endHourExclusive: number;+ /** Inclusive local hour lower bound, `0 <= startHour`. */+ startHour: number;+}+/** One user candidate for AgentSignal nightly review scheduling. */export interface AgentSignalNightlyReviewUserCandidate {/** Creation time used for cursor pagination. */@@ -113,8 +152,8 @@ export interface AgentSignalNightlyReviewTarget {* - Nightly review needs active agent targets for a local-day window** Expects:- * - Global feature gates are checked by the service layer- * - Agent-level opt-in is stored on `agents.chatConfig.selfIteration.enabled`+ * - The user-level Labs → Self-evolving switch is applied by `listEligibleUsers`+ * - There is no agent-level opt-in; every active non-virtual agent (and Lobe AI) is a target** Returns:* - Candidate users and active agent targets without emitting source events@@ -134,10 +173,13 @@ export class AgentSignalNightlyReviewModel {* - Backfills need to restrict scheduling to a user allowlist** Expects:- * - Global feature gates are checked by the service layer+ * - Only users with Labs → Self-evolving on (`preference.lab.enableSelfLearning = true`) are+ * listed, whitelist runs included; the enqueue path re-checks the same switch* - Missing user timezone falls back to UTC* - `activeSince` is supplied by the scheduler; it is a superset of the per-user review* window re-applied downstream, and it is skipped for whitelist runs+ * - `localHourWindow`, when supplied, is a superset of the exact local window the scheduler+ * re-checks; it applies to whitelist runs too, because those users would be skipped anyway** Returns:* - Users sorted by `createdAt, id` for deterministic pagination@@ -183,6 +225,10 @@ export class AgentSignalNightlyReviewModel {.as('nightly_review_active_users'): undefined;+ const localHourCondition = options.localHourWindow+ ? buildLocalHourCondition(options.localHourWindow)+ : undefined;+let query = this.db.select({createdAt: users.createdAt,@@ -198,7 +244,16 @@ export class AgentSignalNightlyReviewModel {query = query.leftJoin(userSettings, eq(users.id, userSettings.id))- .where(and(cursorCondition, whitelistCondition))+ .where(+ and(+ // Labs → Self-evolving is the user-level gate for all background self-iteration.+ // Filtering here keeps users who never turned it on out of the fan-out entirely.+ sql`${users.preference}->'lab'->>'enableSelfLearning' = 'true'`,+ cursorCondition,+ whitelistCondition,+ localHourCondition,+ ),+ ).orderBy(asc(users.createdAt), asc(users.id));return options.limit !== undefined ? query.limit(options.limit) : query;@@ -283,10 +338,6 @@ export class AgentSignalNightlyReviewModel {gte(messages.createdAt, options.windowStart),lte(messages.createdAt, options.windowEnd),or(eq(agents.virtual, false), isNull(agents.virtual), eq(agents.slug, INBOX_SESSION_ID)),- or(- eq(agents.slug, INBOX_SESSION_ID),- sql`COALESCE((${agents.chatConfig}->'selfIteration'->>'enabled')::boolean, false) = true`,- ),),).groupBy(agents.id, agents.title, agents.name, agents.slug, userSettings.general)diff --git a/packages/database/src/models/agentSignal/reviewContext.ts b/packages/database/src/models/agentSignal/reviewContext.tsindex 132dc1c91f2..d675d5de543 100644--- a/packages/database/src/models/agentSignal/reviewContext.ts+++ b/packages/database/src/models/agentSignal/reviewContext.ts@@ -114,7 +114,10 @@ export class AgentSignalReviewContextModel {private ws = (cols: { userId: AnyPgColumn; workspaceId: AnyPgColumn }) =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, cols);- /** Checks agent ownership, virtual status, and self-iteration opt-in. */+ /**+ * Checks agent ownership and virtual status. There is no per-agent switch: every owned agent+ * (plus the Lobe AI inbox) may self-iterate once the user's Labs → Self-evolving switch is on.+ */canAgentRunSelfIteration = async (agentId: string) => {const [agent] = await this.db.select({ id: agents.id })@@ -124,10 +127,6 @@ export class AgentSignalReviewContextModel {eq(agents.id, agentId),this.ws(agents),or(eq(agents.virtual, false), isNull(agents.virtual), eq(agents.slug, INBOX_SESSION_ID)),- or(- eq(agents.slug, INBOX_SESSION_ID),- sql`COALESCE((${agents.chatConfig}->'selfIteration'->>'enabled')::boolean, false) = true`,- ),),).limit(1);diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex f74bd1de4fa..de9b4fe3ac6 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -237,14 +237,21 @@ export default {'agentProfile.skills_other': '{{count}} skills','agentSignal.receipts.agentSignalLabel': 'Agent Signal','agentSignal.receipts.memory.detail': 'Saved this for future replies',+ 'agentSignal.receipts.memory.openInMemory': 'Open in Memory','agentSignal.receipts.memory.title': 'Memory saved','agentSignal.receipts.recentActivity': 'Recent activity','agentSignal.receipts.revert.conflict': 'Newer version',+ 'agentSignal.receipts.revert.error.conflict': "Can't undo: it was changed after this update",+ 'agentSignal.receipts.revert.error.failed': 'Undo failed: {{reason}}',+ 'agentSignal.receipts.revert.error.generic': 'Undo failed. Please try again later',+ 'agentSignal.receipts.revert.error.not_found': "Can't undo: it no longer exists",+ 'agentSignal.receipts.revert.error.unsupported': "This change can't be undone",'agentSignal.receipts.revert.failed': 'Failed','agentSignal.receipts.revert.not_found': 'Cannot undo','agentSignal.receipts.revert.pending': 'Rolling back','agentSignal.receipts.revert.rolled_back': 'Reverted','agentSignal.receipts.revert.undo': 'Undo',+ 'agentSignal.receipts.revert.undone': 'Undone','agentSignal.receipts.revert.unsupported': 'Unsupported','agentSignal.receipts.skill.detail': 'Self-refined how this agent handles similar requests','agentSignal.receipts.skill.title': 'Auto-learned a new skill',diff --git a/packages/locales/src/default/home.ts b/packages/locales/src/default/home.tsindex 5a3aad746f9..7ff008dd57d 100644--- a/packages/locales/src/default/home.ts+++ b/packages/locales/src/default/home.ts@@ -19,6 +19,7 @@ export default {'brief.action.requestChanges': 'Request changes','brief.action.openGoal': 'Open goal','brief.action.answer': 'Answer',+ 'brief.action.dismiss': 'Dismiss','brief.goal.decision.title': 'Goal "{{goal}}" needs your decision','brief.goal.clarify.title': 'Goal "{{goal}}" has questions before it starts','brief.goal.signOff.title': 'Goal "{{goal}}" is done. Sign it off',@@ -34,6 +35,22 @@ export default {'brief.agentSignal.selfReview.error.summary':'Some work could not be completed during this dream.','brief.agentSignal.selfReview.error.title': 'Dream ran into an issue',+ 'brief.agentSignal.selfReview.details.forAgent': 'For {{agent}}',+ 'brief.agentSignal.selfReview.kind.consolidate_skill.plain': 'Merge skills',+ 'brief.agentSignal.selfReview.kind.consolidate_skill.withTarget': 'Merge skills into {{target}}',+ 'brief.agentSignal.selfReview.kind.create_skill.plain': 'New skill',+ 'brief.agentSignal.selfReview.kind.create_skill.withTarget': 'New skill: {{target}}',+ 'brief.agentSignal.selfReview.kind.idea.plain': 'Dream note',+ 'brief.agentSignal.selfReview.kind.idea.withTarget': 'Dream note: {{target}}',+ 'brief.agentSignal.selfReview.kind.other.plain': 'Suggestion',+ 'brief.agentSignal.selfReview.kind.other.withTarget': 'Suggestion: {{target}}',+ 'brief.agentSignal.selfReview.kind.refine_prompt.plain': 'Refine system prompt',+ 'brief.agentSignal.selfReview.kind.refine_skill.plain': 'Refine skill',+ 'brief.agentSignal.selfReview.kind.refine_skill.withTarget': 'Refine skill: {{target}}',+ 'brief.agentSignal.selfReview.kind.write_memory.plain': 'Save memory',+ 'brief.agentSignal.selfReview.kind.write_memory.withTarget': 'Save memory: {{target}}',+ 'brief.agentSignal.selfReview.list.more': '{{count}} more',+ 'brief.agentSignal.selfReview.title.more': '{{title}} (+{{count}} more)','brief.agentSignal.selfReview.ideas.summary': 'Saved dream notes for future review.','brief.agentSignal.selfReview.ideas.title': 'Dream notes','brief.agentSignal.selfReview.proposal.heading': 'Suggestion',diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.tsindex 6ffc2912362..023fe7d70e1 100644--- a/packages/locales/src/default/labs.ts+++ b/packages/locales/src/default/labs.ts@@ -64,7 +64,7 @@ export default {'Add an Acceptance section to the task detail: describe acceptance in one sentence and let AI generate editable verify criteria.','features.taskVerify.title': 'Acceptance','features.selfLearning.desc':- 'Learn from practice: the rounds you send back become rules, and each agent picks up lessons from its own runs — both go with the agent into every run. See them all under Memory → Self-evolving.',+ 'Let every agent learn from your conversations in the background: it remembers facts, refines skills, collects lessons, and reviews its day each night. Rounds you send back become rules. Each nightly review covers at most 50 conversations. See it all under Memory → Self-evolving.','features.selfLearning.title': 'Self-evolving','group.desktop': 'Desktop','group.general': 'General',diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 70fa7f3e11c..b5f7ac97916 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -325,7 +325,6 @@ export default {'agentTab.opening': 'Opening Settings','agentTab.plugin': 'Skill Settings','agentTab.prompt': 'Agent Profile',- 'agentTab.selfIteration': 'Self-Iteration','agentTab.tts': 'Voice Service','permission.accessTag.useOnlyTip':'Your member permission here is "Can use" — you can view and use it, but not edit. Ask the creator or a workspace owner for edit access.',@@ -1438,12 +1437,6 @@ export default {'settingGraphRuntime.validation.required':'A graph snapshot is required before enabling graph runtime.','settingGraphRuntime.validation.unknown': 'Unknown graph validation error',- 'settingSelfIteration.enabled.desc':- 'Allow this assistant to review recent signals and improve its own skills when the self-iteration workflow runs.',- 'settingSelfIteration.enabled.managedDesc':- 'Always on for Lobe AI while Self-Iteration is available.',- 'settingSelfIteration.enabled.title': 'Enable Self-Iteration',- 'settingSelfIteration.title': 'Self-Iteration','settingsSearch.empty': 'No settings found for "{{keyword}}"','settingsSearch.placeholder': 'Search settings...','settingsSearch.tabKeywords.about': 'about, version, changelog, feedback, help',diff --git a/packages/openapi/src/services/__tests__/agent-signal.service.test.ts b/packages/openapi/src/services/__tests__/agent-signal.service.test.tsnew file mode 100644index 00000000000..87f1d8bb748--- /dev/null+++ b/packages/openapi/src/services/__tests__/agent-signal.service.test.ts@@ -0,0 +1,101 @@+// @vitest-environment node+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { LobeChatDatabase } from '@/database/type';++const mocks = vi.hoisted(() => ({+ assertAgentSignalTriggerRateLimit: vi.fn(),+ enqueueAgentSignalSourceEvent: vi.fn(),+}));++vi.mock('@/database/models/rbac', () => ({+ RbacModel: class {},+}));++vi.mock('@/server/services/agentSignal', () => ({+ enqueueAgentSignalSourceEvent: mocks.enqueueAgentSignalSourceEvent,+}));++vi.mock('@/server/services/agentSignal/triggerRateLimit', () => ({+ assertAgentSignalTriggerRateLimit: mocks.assertAgentSignalTriggerRateLimit,+}));++vi.mock('@/server/services/agentSignal/services/receiptService', () => ({+ listAgentSignalReceipts: vi.fn(),+}));++const { AgentSignalRestService } = await import('../agent-signal.service');++describe('AgentSignalRestService.triggerSourceEvent', () => {+ const service = new AgentSignalRestService({} as LobeChatDatabase, 'user-1');++ beforeEach(() => {+ vi.clearAllMocks();+ mocks.assertAgentSignalTriggerRateLimit.mockResolvedValue(undefined);+ mocks.enqueueAgentSignalSourceEvent.mockResolvedValue({ accepted: true });+ });++ /**+ * ROOT CAUSE:+ *+ * `POST /api/v1/signals/trigger` shares the tRPC trigger path and had no per-user rate limit,+ * so an API key could enqueue model-backed workflows without bound.+ */+ it('stops at the per-user trigger rate limit before enqueueing', async () => {+ mocks.assertAgentSignalTriggerRateLimit.mockRejectedValue(+ new TRPCError({ code: 'TOO_MANY_REQUESTS', message: 'limit' }),+ );++ await expect(+ service.triggerSourceEvent({+ agentId: 'agent-1',+ sourceType: 'agent.nightly_review.requested',+ }),+ ).rejects.toMatchObject({ code: 'TOO_MANY_REQUESTS' });+ expect(mocks.assertAgentSignalTriggerRateLimit).toHaveBeenCalledWith('user-1');+ expect(mocks.enqueueAgentSignalSourceEvent).not.toHaveBeenCalled();+ });++ it('enqueues with a server-derived nightly review guard key', async () => {+ await service.triggerSourceEvent({+ agentId: 'agent-1',+ payloadOverride: { localDate: '1999-01-01' },+ sourceId: 'nightly-review:user-1:agent-1:1999-01-01',+ sourceType: 'agent.nightly_review.requested',+ });++ const [sourceEvent] = mocks.enqueueAgentSignalSourceEvent.mock.calls[0]!;+ expect(sourceEvent.payload.localDate).not.toBe('1999-01-01');+ expect(sourceEvent.sourceId).not.toContain('1999-01-01');+ });++ /**+ * ROOT CAUSE:+ *+ * The REST route shares the trigger path, so an agent id set only through+ * `payloadOverride.agentId` reached the handlers without `assertAgentUsableBy` ever seeing it.+ */+ it('authorizes an agent id supplied only through payloadOverride', async () => {+ await service.triggerSourceEvent({+ payloadOverride: { agentId: 'foreign-agent' },+ sourceType: 'agent.user.message',+ });++ expect(mocks.enqueueAgentSignalSourceEvent).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ agentId: 'foreign-agent', userId: 'user-1' }),+ );+ });++ it('rejects a payload agent id that differs from the requested agent', async () => {+ await expect(+ service.triggerSourceEvent({+ agentId: 'agent-1',+ payloadOverride: { agentId: 'foreign-agent' },+ sourceType: 'tool.outcome.failed',+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mocks.enqueueAgentSignalSourceEvent).not.toHaveBeenCalled();+ });+});diff --git a/packages/openapi/src/services/agent-signal.service.ts b/packages/openapi/src/services/agent-signal.service.tsindex 66526ed6632..01acc8fe590 100644--- a/packages/openapi/src/services/agent-signal.service.ts+++ b/packages/openapi/src/services/agent-signal.service.ts@@ -6,7 +6,11 @@ import type {import type { LobeChatDatabase } from '@/database/type';import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';import { listAgentSignalReceipts } from '@/server/services/agentSignal/services/receiptService';-import { buildTriggerSourceEvent } from '@/server/services/agentSignal/triggerSourceEvent';+import { assertAgentSignalTriggerRateLimit } from '@/server/services/agentSignal/triggerRateLimit';+import {+ buildTriggerSourceEvent,+ resolveTriggerSourceEventAgentId,+} from '@/server/services/agentSignal/triggerSourceEvent';import { BaseService } from '../common/base.service';import type { ServiceResult } from '../types';@@ -51,8 +55,13 @@ export class AgentSignalRestService extends BaseService {userId: this.userId,});+ // Authorize the agent the payload targets, including one set via `payloadOverride.agentId`.+ const agentId = resolveTriggerSourceEventAgentId(sourceEvent, input.agentId);++ await assertAgentSignalTriggerRateLimit(this.userId);+return enqueueAgentSignalSourceEvent(sourceEvent, {- agentId: input.agentId,+ agentId,userId: this.userId,workspaceId: this.workspaceId,});diff --git a/packages/types/src/agent/chatConfig.ts b/packages/types/src/agent/chatConfig.tsindex ade51378114..b2fa64c1a1d 100644--- a/packages/types/src/agent/chatConfig.ts+++ b/packages/types/src/agent/chatConfig.ts@@ -20,6 +20,10 @@ export interface AgentMemoryChatConfig {export interface AgentSelfIterationChatConfig {selfIteration?: {+ /**+ * Legacy per-agent switch, kept so stored configs still parse. Ignored: Labs →+ * Self-evolving (`preference.lab.enableSelfLearning`) is the only self-iteration control.+ */enabled?: boolean;};}diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.tsindex b9a8d5c2d14..1b9a780cf4e 100644--- a/packages/types/src/serverConfig.ts+++ b/packages/types/src/serverConfig.ts@@ -19,7 +19,6 @@ 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.diff --git a/src/features/AgentSetting/AgentCategory/useCategory.tsx b/src/features/AgentSetting/AgentCategory/useCategory.tsxindex 2ad6f1e0a3b..29bf2b7aae9 100644--- a/src/features/AgentSetting/AgentCategory/useCategory.tsx+++ b/src/features/AgentSetting/AgentCategory/useCategory.tsx@@ -1,5 +1,5 @@import { Icon } from '@lobehub/ui';-import { Activity, Bot, Handshake, LinkIcon } from 'lucide-react';+import { Bot, Handshake, LinkIcon } from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -7,7 +7,6 @@ import { type MenuProps } from '@/components/Menu';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';import { ChatSettingsTabs } from '@/store/global/initialState';-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';interface UseCategoryOptions {mobile?: boolean;@@ -17,7 +16,6 @@ export const useCategory = ({ mobile }: UseCategoryOptions = {}) => {const { t } = useTranslation('setting');const iconSize = mobile ? 20 : undefined;const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);- const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);const cateItems: MenuProps['items'] = useMemo(() =>@@ -32,18 +30,13 @@ export const useCategory = ({ mobile }: UseCategoryOptions = {}) => {key: ChatSettingsTabs.Opening,label: t('agentTab.opening'),},- enableAgentSelfIteration && {- icon: <Icon icon={Activity} size={iconSize} />,- key: ChatSettingsTabs.SelfIteration,- label: t('agentTab.selfIteration'),- },{icon: <Icon icon={LinkIcon} size={iconSize} />,key: ChatSettingsTabs.Connector,label: t('agentTab.connector', 'Connectors'),},].filter(Boolean) as MenuProps['items'],- [t, isInbox, iconSize, enableAgentSelfIteration],+ [t, isInbox, iconSize],);return cateItems;diff --git a/src/features/AgentSetting/AgentSelfIteration/index.test.tsx b/src/features/AgentSetting/AgentSelfIteration/index.test.tsxdeleted file mode 100644index 4b775afadcf..00000000000--- a/src/features/AgentSetting/AgentSelfIteration/index.test.tsx+++ /dev/null@@ -1,63 +0,0 @@-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';-import { afterEach, describe, expect, it, vi } from 'vitest';--import type { LobeAgentChatConfig } from '@/types/agent';--import type { Store } from '../store/action';-import AgentSelfIteration from './index';--const testStore = await vi.hoisted(async () => {- const { createWithEqualityFn } = await import('zustand/traditional');- const { shallow } = await import('zustand/shallow');-- return createWithEqualityFn<- Pick<Store, 'disabled' | 'setChatConfig'> & {- config: Pick<Store['config'], 'chatConfig'>;- }- >(() => ({ config: { chatConfig: {} }, disabled: false, setChatConfig: vi.fn() }), shallow);-});--vi.mock('@/store/agent', () => ({ useAgentStore: () => false }));-vi.mock('@/store/agent/selectors', () => ({- builtinAgentSelectors: { isInboxAgent: () => false },-}));--vi.mock('../store', () => ({- selectors: {- currentChatConfig: (state: ReturnType<typeof testStore.getState>) => state.config.chatConfig,- },- useStore: testStore,-}));--afterEach(cleanup);--describe('AgentSelfIteration', () => {- it.each([false, true])(- 'saves only selfIteration when changing enabled from %s',- async (enabled) => {- const setChatConfig = vi.fn().mockResolvedValue(undefined);- const chatConfig: LobeAgentChatConfig = {- enableHistoryCount: false,- historyCount: 5,- selfIteration: { enabled },- };- testStore.setState({ config: { chatConfig }, disabled: false, setChatConfig });-- const { container } = render(<AgentSelfIteration />);-- // Another settings surface updates the config after the form took its snapshot.- act(() => {- testStore.setState({- config: { chatConfig: { ...chatConfig, enableHistoryCount: true, historyCount: 20 } },- });- });-- fireEvent.click(screen.getByRole('switch'));- expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', String(!enabled));- fireEvent.submit(container.querySelector('form')!);-- await waitFor(() => expect(setChatConfig).toHaveBeenCalledTimes(1));- expect(setChatConfig).toHaveBeenCalledWith({ selfIteration: { enabled: !enabled } });- },- );-});diff --git a/src/features/AgentSetting/AgentSelfIteration/index.tsx b/src/features/AgentSetting/AgentSelfIteration/index.tsxdeleted file mode 100644index 936375fdda1..00000000000--- a/src/features/AgentSetting/AgentSelfIteration/index.tsx+++ /dev/null@@ -1,59 +0,0 @@-'use client';--import { Switch } from '@lobehub/ui/base-ui';-import { Form, type FormFieldProps, useForm } from '@lobehub/ui/base-ui/form';-import isEqual from 'fast-deep-equal';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { FORM_STYLE } from '@/const/layoutTokens';-import { useAgentStore } from '@/store/agent';-import { builtinAgentSelectors } from '@/store/agent/selectors';-import { type LobeAgentChatConfig } from '@/types/agent';--import { selectors, useStore } from '../store';--const AgentSelfIteration = memo(() => {- const { t } = useTranslation('setting');- const [disabled, updateConfig] = useStore((s) => [s.disabled, s.setChatConfig]);- const config = useStore(selectors.currentChatConfig, isEqual);- const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);- const form = useForm<LobeAgentChatConfig>({- initialValues: config,- onSubmit: (values) => {- if (disabled) return;-- updateConfig({ selfIteration: values.selfIteration });- },- });-- const selfIterationItem: FormFieldProps<LobeAgentChatConfig> = isInbox- ? {- children: <Switch checked disabled />,- desc: t('settingSelfIteration.enabled.managedDesc'),- label: t('settingSelfIteration.enabled.title'),- layout: 'horizontal',- minWidth: undefined,- }- : {- children: <Switch disabled={disabled} />,- desc: t('settingSelfIteration.enabled.desc'),- label: t('settingSelfIteration.enabled.title'),- layout: 'horizontal',- minWidth: undefined,- name: 'selfIteration.enabled',- };-- return (- <Form- footer={isInbox ? undefined : <Form.SubmitFooter />}- form={form}- items={[selfIterationItem]}- itemsType={'flat'}- variant={'borderless'}- {...FORM_STYLE}- />- );-});--export default AgentSelfIteration;diff --git a/src/features/AgentSetting/AgentSettingsContent.tsx b/src/features/AgentSetting/AgentSettingsContent.tsxindex 53f59289a6e..01bcb34765e 100644--- a/src/features/AgentSetting/AgentSettingsContent.tsx+++ b/src/features/AgentSetting/AgentSettingsContent.tsx@@ -4,14 +4,12 @@ import { memo } from 'react';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { ChatSettingsTabs } from '@/store/global/initialState';-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';import { useUserStore } from '@/store/user';import { labPreferSelectors } from '@/store/user/selectors';import AgentConnectors from './AgentConnectors';import AgentGraphRuntime from './AgentGraphRuntime';import AgentOpening from './AgentOpening';-import AgentSelfIteration from './AgentSelfIteration';export interface AgentSettingsContentProps {loadingSkeleton: ReactNode;@@ -20,7 +18,6 @@ export interface AgentSettingsContentProps {const AgentSettingsContent = memo<AgentSettingsContentProps>(({ tab, loadingSkeleton }) => {const loading = useAgentStore(agentSelectors.isAgentConfigLoading);- const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);const enableAgentGraphConfigLab = useUserStore(labPreferSelectors.enableAgentGraphConfig);if (loading) return loadingSkeleton;@@ -28,7 +25,6 @@ const AgentSettingsContent = memo<AgentSettingsContentProps>(({ tab, loadingSkelreturn (<>{tab === ChatSettingsTabs.Opening && <AgentOpening />}- {enableAgentSelfIteration && tab === ChatSettingsTabs.SelfIteration && <AgentSelfIteration />}{enableAgentGraphConfigLab && tab === ChatSettingsTabs.Graph && <AgentGraphRuntime />}{tab === ChatSettingsTabs.Connector && <AgentConnectors />}</>diff --git a/src/features/AgentSidebar/Header/Nav.test.tsx b/src/features/AgentSidebar/Header/Nav.test.tsxindex a3770306b7f..f43a9514644 100644--- a/src/features/AgentSidebar/Header/Nav.test.tsx+++ b/src/features/AgentSidebar/Header/Nav.test.tsx@@ -102,17 +102,20 @@ vi.mock('@/store/global', () => ({selector({ toggleCommandMenu: toggleCommandMenuMock }),}));+interface ServerConfigTestState {+ featureFlags: { isAgentEditable: boolean };+ serverConfigInit: boolean;+}+vi.mock('@/store/serverConfig', () => ({- featureFlagsSelectors: (state: { featureFlags: { isAgentEditable: boolean } }) =>- state.featureFlags,- useServerConfigStore: (- selector: (state: { featureFlags: { isAgentEditable: boolean } }) => unknown,- ) => selector({ featureFlags: { isAgentEditable: true } }),+ featureFlagsSelectors: (state: ServerConfigTestState) => state.featureFlags,+ useServerConfigStore: (selector: (state: ServerConfigTestState) => unknown) =>+ selector({ featureFlags: { isAgentEditable: true }, serverConfigInit: true }),}));vi.mock('@/store/user', () => ({useUserStore: (selector: (state: unknown) => unknown) =>- selector({ preference: { lab: labMock } }),+ selector({ isUserStateInit: true, preference: { lab: labMock } }),}));vi.mock('@/store/user/selectors', () => ({diff --git a/src/features/AgentSidebar/Header/Nav.tsx b/src/features/AgentSidebar/Header/Nav.tsxindex 324aec4051e..2556968d038 100644--- a/src/features/AgentSidebar/Header/Nav.tsx+++ b/src/features/AgentSidebar/Header/Nav.tsx@@ -16,6 +16,7 @@ import urlJoin from 'url-join';import NavItem from '@/features/NavPanel/components/NavItem';import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';+import { useSelfLearningSurface } from '@/features/SelfLearning/SurfaceGate/useSelfLearningSurface';import { useActiveLocation } from '@/hooks/useActiveLocation';import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import { usePermission } from '@/hooks/usePermission';@@ -61,7 +62,7 @@ const Nav = memo(() => {const [openNewTopicOrSaveTopic] = useChatStore((s) => [s.openNewTopicOrSaveTopic]);const isNewTopicSendInFlight = useChatStore(topicSelectors.isNewTopicSendInFlight);const enableGoals = useUserStore(labPreferSelectors.enableGoals);- const enableSelfLearning = useUserStore(labPreferSelectors.enableSelfLearning);+ const { enabled: enableSelfLearning } = useSelfLearningSurface();const { mutate } = useActionSWR(topicActionKeys.openNewOrSave(), openNewTopicOrSaveTopic);const handleNewTopic = () => {diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsxindex 83feb6ff7f8..276858cd265 100644--- a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx@@ -7,9 +7,37 @@ import { agentSignalService } from '@/services/agentSignal';import AgentSignalReceiptList from './AgentSignalReceiptList';const mocks = vi.hoisted(() => ({+ mutate: vi.fn(),navigate: vi.fn(),openDocument: vi.fn(),+ openMemoryDetail: vi.fn(),rollbackReceipt: vi.fn(),+ toastError: vi.fn(),+}));++vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ toast: { error: mocks.toastError },+}));++// Like the global passthrough mock, but interpolates `{{vars}}` so toast copy carries the reason.+vi.mock('react-i18next', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useTranslation: () => ({+ t: (key: string, defaultValueOrOptions?: unknown) => {+ if (typeof defaultValueOrOptions === 'string') return defaultValueOrOptions;+ const options = defaultValueOrOptions as Record<string, unknown> | undefined;+ if (typeof options?.defaultValue !== 'string') return key;++ return options.defaultValue.replaceAll(/\{\{(\w+)\}\}/g, (_, name: string) =>+ String(options[name] ?? ''),+ );+ },+ }),+}));++vi.mock('@/libs/swr', () => ({+ mutate: mocks.mutate,}));vi.mock('@/hooks/useStableNavigate', () => ({@@ -17,8 +45,12 @@ vi.mock('@/hooks/useStableNavigate', () => ({}));vi.mock('@/store/chat', () => ({- useChatStore: (selector: (state: { openDocument: (documentId: string) => void }) => unknown) =>- selector({ openDocument: mocks.openDocument }),+ useChatStore: (+ selector: (state: {+ openDocument: typeof mocks.openDocument;+ openMemoryDetail: typeof mocks.openMemoryDetail;+ }) => unknown,+ ) => selector({ openDocument: mocks.openDocument, openMemoryDetail: mocks.openMemoryDetail }),}));vi.mock('@/services/agentSignal', () => ({@@ -29,9 +61,12 @@ vi.mock('@/services/agentSignal', () => ({describe('AgentSignalReceiptList', () => {afterEach(() => {+ mocks.mutate.mockReset();mocks.navigate.mockReset();mocks.openDocument.mockReset();+ mocks.openMemoryDetail.mockReset();mocks.rollbackReceipt.mockReset();+ mocks.toastError.mockReset();});it('renders visible memory and skill receipts', () => {@@ -80,8 +115,10 @@ describe('AgentSignalReceiptList', () => {);expect(screen.getByText('Decision-first PR review preference')).toBeInTheDocument();+ // A memory's description is its own content summary, not the generic "Memory saved".+ expect(screen.getByText('Use decision-first PR reviews in future chats')).toBeInTheDocument();+ expect(screen.queryByText('Memory saved')).not.toBeInTheDocument();expect(screen.getByText('GitHub PR review workflow')).toBeInTheDocument();- expect(screen.getByText('Memory saved')).toBeInTheDocument();expect(screen.getByText('Skill updated')).toBeInTheDocument();});@@ -308,7 +345,7 @@ describe('AgentSignalReceiptList', () => {expect(mocks.navigate).toHaveBeenCalledWith('/memory/preferences');});- it('opens memory receipts on their layer detail route when target metadata is available', () => {+ it('opens memory receipts in the Portal when layer metadata is available', () => {render(<AgentSignalReceiptListreceipts={[@@ -336,9 +373,157 @@ describe('AgentSignalReceiptList', () => {/>,);- fireEvent.click(screen.getByText('Open'));+ fireEvent.click(screen.getByText('Decision-first PR review preference'));++ expect(mocks.openMemoryDetail).toHaveBeenCalledWith({+ id: 'preference-1',+ layer: LayersEnum.Preference,+ });+ expect(mocks.navigate).not.toHaveBeenCalled();+ });++ describe('memory receipt title, description and undo', () => {+ const memoryReceipt = (overrides: Record<string, unknown> = {}) => ({+ agentId: 'agent-1',+ createdAt: 1,+ detail: 'Saved this for future replies',+ id: 'receipt-memory',+ kind: 'memory' as const,+ metadata: { rollbackStatus: 'available' as const },+ sourceId: 'source-1',+ sourceType: 'agent.execution.completed',+ status: 'applied' as const,+ target: {+ id: 'preference-1',+ memoryId: 'memory-1',+ memoryLayer: LayersEnum.Preference,+ operation: 'create' as const,+ summary: 'Lead code reviews with the decision, then the evidence',+ title: 'Decision-first PR review preference',+ type: 'memory' as const,+ },+ title: 'Memory saved',+ topicId: 'topic-1',+ userId: 'user-1',+ ...overrides,+ });++ it('renders the memory title, its summary and an undo action', () => {+ render(<AgentSignalReceiptList receipts={[memoryReceipt()]} />);++ expect(screen.getByText('Decision-first PR review preference')).toBeInTheDocument();+ expect(+ screen.getByText('Lead code reviews with the decision, then the evidence'),+ ).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Undo' })).toBeInTheDocument();+ });++ it('falls back to the localized kind title only when the memory has no title', () => {+ render(+ <AgentSignalReceiptList+ receipts={[+ memoryReceipt({+ metadata: {},+ target: { memoryLayer: LayersEnum.Preference, type: 'memory' },+ }),+ ]}+ />,+ );++ expect(screen.getByText('Memory saved')).toBeInTheDocument();+ expect(screen.getByText('Saved this for future replies')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Undo' })).not.toBeInTheDocument();+ });++ it('hides undo for memory updates', () => {+ render(+ <AgentSignalReceiptList+ receipts={[+ memoryReceipt({+ target: {+ id: 'identity-1',+ memoryLayer: LayersEnum.Identity,+ operation: 'update',+ title: 'Senior engineer',+ type: 'memory',+ },+ }),+ ]}+ />,+ );++ expect(screen.queryByRole('button', { name: 'Undo' })).not.toBeInTheDocument();+ });++ it('undoes the memory by receipt id and shows the cancelled state', async () => {+ mocks.rollbackReceipt.mockResolvedValueOnce({+ receiptId: 'receipt-memory',+ status: 'rolled_back',+ });++ render(<AgentSignalReceiptList receipts={[memoryReceipt()]} />);++ fireEvent.click(screen.getByRole('button', { name: 'Undo' }));++ await waitFor(() => {+ expect(agentSignalService.rollbackReceipt).toHaveBeenCalledWith({+ receiptId: 'receipt-memory',+ });+ });+ expect(await screen.findByText('Undone')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Undo' })).not.toBeInTheDocument();+ expect(mocks.openMemoryDetail).not.toHaveBeenCalled();+ expect(mocks.mutate).toHaveBeenCalledWith([+ 'userMemory:memoryDetail',+ LayersEnum.Preference,+ 'preference-1',+ ]);+ expect(mocks.toastError).not.toHaveBeenCalled();+ });++ it('shows a toast with the reason when undo fails', async () => {+ mocks.rollbackReceipt.mockResolvedValueOnce({+ reason: 'database unavailable',+ receiptId: 'receipt-memory',+ status: 'failed',+ });++ render(<AgentSignalReceiptList receipts={[memoryReceipt()]} />);++ fireEvent.click(screen.getByRole('button', { name: 'Undo' }));++ await waitFor(() => {+ expect(mocks.toastError).toHaveBeenCalledWith('Undo failed: database unavailable');+ });+ });++ it('shows a toast when the memory no longer exists', async () => {+ mocks.rollbackReceipt.mockResolvedValueOnce({+ reason: 'Memory no longer exists',+ receiptId: 'receipt-memory',+ status: 'not_found',+ });++ render(<AgentSignalReceiptList receipts={[memoryReceipt()]} />);- expect(mocks.navigate).toHaveBeenCalledWith('/memory/preferences?preferenceId=preference-1');+ fireEvent.click(screen.getByRole('button', { name: 'Undo' }));++ await waitFor(() => {+ expect(mocks.toastError).toHaveBeenCalledWith("Can't undo: it no longer exists");+ });+ });++ it('shows a toast with the request error when undo throws', async () => {+ mocks.rollbackReceipt.mockRejectedValueOnce(new Error('Network error'));++ render(<AgentSignalReceiptList receipts={[memoryReceipt()]} />);++ fireEvent.click(screen.getByRole('button', { name: 'Undo' }));++ await waitFor(() => {+ expect(mocks.toastError).toHaveBeenCalledWith('Undo failed: Network error');+ });+ });});it('shows undo only when skill rollback history metadata exists', () => {diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsxindex ea98e71f933..342ba5708d2 100644--- a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx@@ -2,6 +2,7 @@import { LayersEnum } from '@lobechat/types';import { Icon } from '@lobehub/ui';+import { toast } from '@lobehub/ui/base-ui';import { SkillsIcon } from '@lobehub/ui/icons';import { createStaticStyles } from 'antd-style';import type { LucideIcon } from 'lucide-react';@@ -10,23 +11,18 @@ import { memo, useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import PortalResourceCard from '@/features/Conversation/components/PortalResourceCard';+import {+ getMemoryDetailPath,+ hasMemoryDetailView,+} from '@/features/Portal/MemoryDetail/memoryDetailRoutes';import { useStableNavigate } from '@/hooks/useStableNavigate';+import { mutate } from '@/libs/swr';+import { userMemoryKeys } from '@/libs/swr/keys';import { agentSignalService } from '@/services/agentSignal';import { useChatStore } from '@/store/chat';import type { AgentSignalReceiptView } from '../hooks/useAgentSignalReceipts';-/**- * The experience layer has no page any more — nothing writes one and its surface is gone — so a- * receipt that still points at one lands on the memory home rather than a dead route.- */-const MEMORY_ROUTE_BY_LAYER: Partial<Record<LayersEnum, { idParam: string; path: string }>> = {- [LayersEnum.Activity]: { idParam: 'activityId', path: '/memory/activities' },- [LayersEnum.Context]: { idParam: 'contextId', path: '/memory/contexts' },- [LayersEnum.Identity]: { idParam: 'identityId', path: '/memory/identities' },- [LayersEnum.Preference]: { idParam: 'preferenceId', path: '/memory/preferences' },-};-const styles = createStaticStyles(({ css }) => ({list: css`display: flex;@@ -66,6 +62,12 @@ const RECEIPT_ROLLBACK_LABEL_BY_STATUS = {unsupported: 'Unsupported',} as const satisfies Record<ReceiptRollbackStatus, string>;+const RECEIPT_ROLLBACK_ERROR_FALLBACK = {+ conflict: "Can't undo: it was changed after this update",+ not_found: "Can't undo: it no longer exists",+ unsupported: "This change can't be undone",+} as const;+const renderReceiptIcon = (kind: AgentSignalReceiptView['kind']) => {if (kind === 'skill') return <SkillsIcon size={28} />;const LucideIconComponent = RECEIPT_LUCIDE_ICON_BY_KIND[kind];@@ -82,35 +84,50 @@ interface AgentSignalReceiptItemProps {rollbackStatus?: ReceiptRollbackStatus;}-const getMemoryRoute = (target?: AgentSignalReceiptView['target']) => {+/**+ * Resolves where a memory receipt opens. Receipts carrying a layer + row id open that memory's+ * detail in the Portal; older receipts without that metadata fall back to the memory page.+ */+const getMemoryOpenTarget = (+ target?: AgentSignalReceiptView['target'],+):+ | { id: string; layer: LayersEnum; type: 'portal' }+ | { path: string; type: 'route' }+ | undefined => {if (target?.type !== 'memory') return;- const hasLayerMetadata = Boolean(target.memoryLayer);+ if (target.memoryLayer && target.id && hasMemoryDetailView(target.memoryLayer)) {+ return { id: target.id, layer: target.memoryLayer, type: 'portal' };+ }+const memoryLayer =target.memoryLayer ??- (LEGACY_PREFERENCE_MEMORY_PATTERN.test(`${target.title} ${target.summary ?? ''}`)+ (LEGACY_PREFERENCE_MEMORY_PATTERN.test(`${target.title ?? ''} ${target.summary ?? ''}`)? LayersEnum.Preference: undefined);- if (!memoryLayer) return '/memory';-- const route = MEMORY_ROUTE_BY_LAYER[memoryLayer];- if (!route) return '/memory';-- const layerSpecificId = hasLayerMetadata ? target.id : undefined;-- return layerSpecificId- ? `${route.path}?${route.idParam}=${encodeURIComponent(layerSpecificId)}`- : route.path;+ return { path: memoryLayer ? getMemoryDetailPath(memoryLayer) : '/memory', type: 'route' };};-const getRollbackStatusLabelKey = (status: ReceiptRollbackStatus) => {+const getRollbackStatusLabelKey = (+ status: ReceiptRollbackStatus,+ kind: AgentSignalReceiptView['kind'],+) => {if (status === 'available') return 'agentSignal.receipts.revert.undo';+ // An undone memory is deleted, not restored to an earlier version.+ if ((status === 'already_rolled_back' || status === 'rolled_back') && kind === 'memory') {+ return 'agentSignal.receipts.revert.undone';+ }if (status === 'already_rolled_back') return 'agentSignal.receipts.revert.rolled_back';return `agentSignal.receipts.revert.${status}`;};+const ROLLBACK_SUCCESS_STATUSES = new Set<ReceiptRollbackStatus>([+ 'already_rolled_back',+ 'rolled_back',+]);+const normalizeRollbackStatus = (status: string): ReceiptRollbackStatus => {if (status === 'already_rolled_back' ||@@ -130,33 +147,48 @@ const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(const { t } = useTranslation(['chat', 'common']);const navigate = useStableNavigate();const openDocument = useChatStore((s) => s.openDocument);+ const openMemoryDetail = useChatStore((s) => s.openMemoryDetail);const rollbackInFlightRef = useRef(false);const iconNode = renderReceiptIcon(receipt.kind);- const fallbackTitle = t(`agentSignal.receipts.${receipt.kind}.title`, receipt.title);- const detail = t(`agentSignal.receipts.${receipt.kind}.detail`, receipt.detail);- const title = receipt.target?.title ?? fallbackTitle;- const description = receipt.target ? fallbackTitle : detail;- const summary = receipt.target?.summary ?? detail;- const tooltip = `${fallbackTitle}: ${summary}`;const target = receipt.target;+ // Titles are localized by receipt kind; `receipt.title` is only the server's English fallback.+ const kindTitle = t(`agentSignal.receipts.${receipt.kind}.title`, receipt.title);+ const kindDetail = t(`agentSignal.receipts.${receipt.kind}.detail`, receipt.detail);+ const title = target?.title ?? kindTitle;+ // A memory reads as its own title + content summary; a skill keeps its kind label beneath.+ const description =+ receipt.kind === 'memory'+ ? (target?.summary ?? kindDetail)+ : target?.title+ ? kindTitle+ : kindDetail;+ const tooltip = `${kindTitle}: ${target?.summary ?? kindDetail}`;const documentId = target?.type === 'skill' ? (target.documentId ?? target.id) : undefined;const agentDocumentId =target?.type === 'skill' && typeof target.agentDocumentId === 'string'? target.agentDocumentId: undefined;- const memoryRoute = getMemoryRoute(target);- const canOpen = Boolean(memoryRoute) || Boolean(documentId);+ const memoryOpenTarget = getMemoryOpenTarget(target);+ const canOpen = Boolean(memoryOpenTarget) || Boolean(documentId);const rollbackDocumentId = receipt.metadata?.documentId;const rollbackHistoryId = receipt.metadata?.historyId;const rollbackAgentDocumentId = receipt.metadata?.agentDocumentId;const effectiveRollbackStatus = rollbackStatus ?? receipt.metadata?.rollbackStatus;- const canRollback =- Boolean(rollbackDocumentId) &&- Boolean(rollbackHistoryId) &&- effectiveRollbackStatus === 'available';+ const isMemoryUndo =+ receipt.kind === 'memory' &&+ target?.type === 'memory' &&+ target.operation === 'create' &&+ Boolean(target.id);+ const hasRollbackTarget =+ isMemoryUndo || (Boolean(rollbackDocumentId) && Boolean(rollbackHistoryId));+ const canRollback = hasRollbackTarget && effectiveRollbackStatus === 'available';const handleOpen = useCallback(() => {- if (memoryRoute) {- navigate(memoryRoute);+ if (memoryOpenTarget?.type === 'portal') {+ openMemoryDetail({ id: memoryOpenTarget.id, layer: memoryOpenTarget.layer });+ return;+ }+ if (memoryOpenTarget?.type === 'route') {+ navigate(memoryOpenTarget.path);return;}@@ -164,39 +196,93 @@ const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(if (!documentId) return;openDocument(documentId, agentDocumentId);- }, [agentDocumentId, documentId, memoryRoute, navigate, openDocument, target]);+ }, [+ agentDocumentId,+ documentId,+ memoryOpenTarget,+ navigate,+ openDocument,+ openMemoryDetail,+ target,+ ]);const handleRollback = useCallback(async () => {- if (!rollbackDocumentId || !rollbackHistoryId || rollbackInFlightRef.current) return;+ if (!canRollback || rollbackInFlightRef.current) return;rollbackInFlightRef.current = true;onRollbackStatusChange(receipt.id, 'pending');try {const result = await agentSignalService.rollbackReceipt({...(rollbackAgentDocumentId ? { agentDocumentId: rollbackAgentDocumentId } : {}),- documentId: rollbackDocumentId,- historyId: rollbackHistoryId,+ ...(rollbackDocumentId ? { documentId: rollbackDocumentId } : {}),+ ...(rollbackHistoryId ? { historyId: rollbackHistoryId } : {}),receiptId: receipt.id,});- onRollbackStatusChange(receipt.id, normalizeRollbackStatus(result.status));- } catch {+ const status = normalizeRollbackStatus(result.status);++ onRollbackStatusChange(receipt.id, status);++ if (ROLLBACK_SUCCESS_STATUSES.has(status)) {+ // Drop the cached detail so an open Portal / memory page shows the memory is gone.+ if (target?.type === 'memory' && target.memoryLayer && target.id) {+ void mutate(userMemoryKeys.memoryDetail(target.memoryLayer, target.id));+ }+ return;+ }++ if (status === 'failed') {+ toast.error(+ result.reason+ ? t('agentSignal.receipts.revert.error.failed', {+ defaultValue: 'Undo failed: {{reason}}',+ reason: result.reason,+ })+ : t(+ 'agentSignal.receipts.revert.error.generic',+ 'Undo failed. Please try again later',+ ),+ );+ return;+ }++ toast.error(+ t(+ `agentSignal.receipts.revert.error.${status as keyof typeof RECEIPT_ROLLBACK_ERROR_FALLBACK}`,+ RECEIPT_ROLLBACK_ERROR_FALLBACK[status as keyof typeof RECEIPT_ROLLBACK_ERROR_FALLBACK],+ ),+ );+ } catch (error) {onRollbackStatusChange(receipt.id, 'failed');+ const reason = error instanceof Error ? error.message : undefined;+ toast.error(+ reason+ ? t('agentSignal.receipts.revert.error.failed', {+ defaultValue: 'Undo failed: {{reason}}',+ reason,+ })+ : t('agentSignal.receipts.revert.error.generic', 'Undo failed. Please try again later'),+ );} finally {rollbackInFlightRef.current = false;}}, [+ canRollback,onRollbackStatusChange,receipt.id,rollbackAgentDocumentId,rollbackDocumentId,rollbackHistoryId,+ t,+ target,]);const shouldShowRollbackStatus =effectiveRollbackStatus === 'available' ? canRollback : Boolean(effectiveRollbackStatus);const rollbackLabel =shouldShowRollbackStatus && effectiveRollbackStatus? t(- getRollbackStatusLabelKey(effectiveRollbackStatus),- RECEIPT_ROLLBACK_LABEL_BY_STATUS[effectiveRollbackStatus],+ getRollbackStatusLabelKey(effectiveRollbackStatus, receipt.kind),+ receipt.kind === 'memory' && ROLLBACK_SUCCESS_STATUSES.has(effectiveRollbackStatus)+ ? 'Undone'+ : RECEIPT_ROLLBACK_LABEL_BY_STATUS[effectiveRollbackStatus],): undefined;diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsxindex ba99f6f2701..d739249639d 100644--- a/src/features/Conversation/ChatList/index.tsx+++ b/src/features/Conversation/ChatList/index.tsx@@ -16,9 +16,8 @@ import {hasPendingInterventions,INTERVENTION_REFRESH_INTERVAL,} from '@/store/chat/utils/interventionSync';-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';import { useUserStore } from '@/store/user';-import { authSelectors, settingsSelectors } from '@/store/user/selectors';+import { authSelectors, labPreferSelectors, settingsSelectors } from '@/store/user/selectors';import WideScreenContainer from '../../WideScreenContainer';import SkeletonList from '../components/SkeletonList';@@ -146,7 +145,7 @@ const ChatList = memo<ChatListProps>(const isCreatingTopic = useChatStore((s) => !!context.topicId && s.creatingTopicIds.includes(context.topicId),);- const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);+ const enableSelfLearning = useUserStore(labPreferSelectors.enableSelfLearning);const messagesSWR = useFetchMessages(context, {refreshInterval: hasPendingApproval ? INTERVENTION_REFRESH_INTERVAL : 0,revalidateOnFocus: hasPendingApproval || !isStreaming,@@ -194,7 +193,7 @@ const ChatList = memo<ChatListProps>(// 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 canShowAgentSignalReceipts = enableSelfLearning && !isSharePage;const { receiptsByAnchor } = useAgentSignalReceipts({agentId: canShowAgentSignalReceipts ? activeAgentId : undefined,displayMessages,diff --git a/src/features/Conversation/ConversationProvider.test.tsx b/src/features/Conversation/ConversationProvider.test.tsxindex 12ca9fc6567..fcabd6fc958 100644--- a/src/features/Conversation/ConversationProvider.test.tsx+++ b/src/features/Conversation/ConversationProvider.test.tsx@@ -108,11 +108,15 @@ vi.mock('@/store/chat/selectors', () => ({vi.mock('@/store/serverConfig', () => ({featureFlagsSelectors: vi.fn(),- useServerConfigStore: () => ({ enableAgentSelfIteration: false }),+ useServerConfigStore: () => ({}),}));vi.mock('@/store/user', () => ({ useUserStore: () => false }));-vi.mock('@/store/user/selectors', () => ({ authSelectors: {}, settingsSelectors: {} }));+vi.mock('@/store/user/selectors', () => ({+ authSelectors: {},+ labPreferSelectors: {},+ settingsSelectors: {},+}));const oldContext = {agentId: 'agt_old',diff --git a/src/features/DailyBrief/SelfReviewBriefDetails.tsx b/src/features/DailyBrief/SelfReviewBriefDetails.tsxnew file mode 100644index 00000000000..00203af0008--- /dev/null+++ b/src/features/DailyBrief/SelfReviewBriefDetails.tsx@@ -0,0 +1,128 @@+import {+ formatSelfReviewKindLabel,+ getSelfReviewBriefLead,+ type SelfReviewBriefDetails as SelfReviewBriefDetailsModel,+} from '@lobechat/agent-signal/brief';+import { Flexbox } from '@lobehub/ui';+import { Button, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { homeType } from '@/features/Home/components/homeType';++import { useSelfReviewTranslator } from './useSelfReviewBriefView';++/** Rows shown before the rest fold behind "N more". */+export const SELF_REVIEW_VISIBLE_ROWS = 3;++const styles = createStaticStyles(({ css, cssVar }) => ({+ kind: css`+ flex: none;++ padding-block: 0;+ padding-inline: 6px;+ border-radius: ${cssVar.borderRadiusXS};++ font-size: 12px;+ line-height: 20px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillTertiary};+ `,+ more: css`+ align-self: flex-start;+ height: auto;+ padding: 0;+ color: ${cssVar.colorTextTertiary};+ `,+ rowDescription: css`+ color: ${cssVar.colorTextTertiary};+ `,+ rowTarget: css`+ font-weight: 500;+ color: ${cssVar.colorTextSecondary};+ `,+}));++interface SelfReviewBriefDetailsProps {+ /** Display name of the agent the proposal is for. */+ agentName?: string;+ details: SelfReviewBriefDetailsModel;+}++/**+ * What a nightly self-review brief proposes, inline on the card: which agent it+ * is for, a one- or two-line lead, and — when it holds several changes or+ * ideas — one row per change (kind · target — why), folded past three rows.+ */+const SelfReviewBriefDetails = ({ agentName, details }: SelfReviewBriefDetailsProps) => {+ const { t } = useTranslation('home');+ const [expanded, setExpanded] = useState(false);+ const translate = useSelfReviewTranslator();++ // The title line is cut to one line, so a lone titleless idea still repeats+ // its full rationale here.+ const items = details.items ?? [];+ const lead =+ getSelfReviewBriefLead(details) ?? (items.length === 1 ? items[0].description : undefined);+ const showRows = items.length > 1;+ const rows = expanded || !showRows ? items : items.slice(0, SELF_REVIEW_VISIBLE_ROWS);+ const hidden = items.length - rows.length;++ return (+ <Flexbox gap={6}>+ {agentName && (+ <span className={homeType.meta}>+ {t('brief.agentSignal.selfReview.details.forAgent', { agent: agentName })}+ </span>+ )}+ {lead && (+ <Text className={homeType.supporting} ellipsis={{ rows: 2 }}>+ {lead}+ </Text>+ )}+ {showRows && (+ <Flexbox as={'ul'} gap={4} style={{ listStyle: 'none', margin: 0, padding: 0 }}>+ {rows.map((item, index) => {+ // A titleless idea is all rationale: show it once, as the row's text.+ const target = item.target ?? (item.kind === 'idea' ? item.description : undefined);+ const description = target === item.description ? undefined : item.description;++ return (+ <Flexbox+ horizontal+ align={'center'}+ as={'li'}+ gap={8}+ key={index}+ style={{ minWidth: 0 }}+ >+ <span className={styles.kind}>+ {formatSelfReviewKindLabel(item.kind, translate)}+ </span>+ <Text ellipsis className={homeType.supporting} style={{ flex: 1, minWidth: 0 }}>+ {target && <span className={styles.rowTarget}>{target}</span>}+ {target && description && ' — '}+ {description && <span className={styles.rowDescription}>{description}</span>}+ </Text>+ </Flexbox>+ );+ })}+ </Flexbox>+ )}+ {hidden > 0 && (+ <Button+ className={styles.more}+ size={'small'}+ type={'text'}+ onClick={() => setExpanded(true)}+ >+ {t('brief.agentSignal.selfReview.list.more', { count: String(hidden) })}+ </Button>+ )}+ </Flexbox>+ );+};++export default SelfReviewBriefDetails;diff --git a/src/features/DailyBrief/useSelfReviewBriefView.ts b/src/features/DailyBrief/useSelfReviewBriefView.tsnew file mode 100644index 00000000000..acdd0a6bfe4--- /dev/null+++ b/src/features/DailyBrief/useSelfReviewBriefView.ts@@ -0,0 +1,48 @@+import {+ formatSelfReviewBriefTitle,+ getSelfReviewBriefDetails,+ type SelfReviewBriefDetails,+ type SelfReviewBriefDetailsTranslator,+} from '@lobechat/agent-signal/brief';+import { useTranslation } from 'react-i18next';++import { type BriefItem } from './types';++export interface SelfReviewBriefView {+ details: SelfReviewBriefDetails;+ /** Title naming the main proposed change, in the reader's language. */+ title: string;+}++/**+ * Reads a nightly self-review brief (Agent Signal "dream") into its inline+ * display model.+ *+ * The details come from the frozen proposal / ideas in the brief metadata, not+ * from the persisted `title` / `summary`: briefs stored before those named the+ * change only say "a suggestion needs review", and reading the metadata gives+ * every such brief the same specific card.+ *+ * Returns `undefined` for any other brief, which keeps its stored text.+ */+export const useSelfReviewBriefView = (+ metadata: BriefItem['metadata'],+): SelfReviewBriefView | undefined => {+ const translate = useSelfReviewTranslator();++ const details = getSelfReviewBriefDetails(metadata);+ if (!details) return;++ return { details, title: formatSelfReviewBriefTitle(details, translate) };+};++/**+ * The `home` translator in the shape the shared self-review formatters take.+ * Their keys are composed at runtime (`…kind.${kind}.plain`), so the typed key+ * union is widened here, once.+ */+export const useSelfReviewTranslator = (): SelfReviewBriefDetailsTranslator => {+ const { t } = useTranslation('home');++ return (key, options) => t(key as 'brief.title', options);+};diff --git a/src/features/HomeInbox/InboxBriefCard.tsx b/src/features/HomeInbox/InboxBriefCard.tsxindex 0599a40e0af..5d57cc71362 100644--- a/src/features/HomeInbox/InboxBriefCard.tsx+++ b/src/features/HomeInbox/InboxBriefCard.tsx@@ -12,8 +12,10 @@ import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';import BriefCardActions from '@/features/DailyBrief/BriefCardActions';import BriefCardArtifacts from '@/features/DailyBrief/BriefCardArtifacts';import BriefCardSummary from '@/features/DailyBrief/BriefCardSummary';+import SelfReviewBriefDetails from '@/features/DailyBrief/SelfReviewBriefDetails';import { styles as briefStyles } from '@/features/DailyBrief/style';import { type BriefItem } from '@/features/DailyBrief/types';+import { useSelfReviewBriefView } from '@/features/DailyBrief/useSelfReviewBriefView';import { homeType } from '@/features/Home/components/homeType';import Time from '@/features/Home/components/Time';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';@@ -52,6 +54,12 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ bare, brief }) => {const agent = brief.agent;const isInbox = agent?.id === INBOX_SESSION_ID;+ const agentName = agent+ ? agentDisplayName(agent, isInbox ? t('inbox.title', { ns: 'chat' }) : t('defaultSession'))+ : undefined;+ // A nightly self-review proposal describes itself from its frozen actions, so+ // the card says what would change instead of "a suggestion needs review".+ const selfReview = useSelfReviewBriefView(brief.metadata);const canNavigate = Boolean(brief.taskId);// Error briefs carry their title + human, localized summary from the server@@ -126,20 +134,21 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ bare, brief }) => {shape={'circle'}size={28}style={{ flex: 'none' }}- title={agentDisplayName(- agent,- isInbox ? t('inbox.title', { ns: 'chat' }) : t('defaultSession'),- )}+ title={agentName}/>)}<Flexbox flex={1} gap={6} style={{ minWidth: 0 }}><Flexbox horizontal align={'center'} gap={8}><Text ellipsis className={homeType.itemTitle} style={{ flex: 1, minWidth: 0 }}>- {brief.title}+ {selfReview?.title ?? brief.title}</Text>{!hasTaskMeta && !goal && <Time date={brief.createdAt} />}</Flexbox>- <BriefCardSummary summary={brief.summary} />+ {selfReview ? (+ <SelfReviewBriefDetails agentName={agentName} details={selfReview.details} />+ ) : (+ <BriefCardSummary summary={brief.summary} />+ )}<BriefCardArtifacts artifacts={brief.artifacts} /></Flexbox></Flexbox>diff --git a/src/features/HomeInbox/NewsList.tsx b/src/features/HomeInbox/NewsList.tsxindex 8efb42f4402..0ef43f8051d 100644--- a/src/features/HomeInbox/NewsList.tsx+++ b/src/features/HomeInbox/NewsList.tsx@@ -8,7 +8,9 @@ import { useTranslation } from 'react-i18next';import BriefCardArtifacts from '@/features/DailyBrief/BriefCardArtifacts';import BriefIcon from '@/features/DailyBrief/BriefIcon';+import SelfReviewBriefDetails from '@/features/DailyBrief/SelfReviewBriefDetails';import { type BriefItem } from '@/features/DailyBrief/types';+import { useSelfReviewBriefView } from '@/features/DailyBrief/useSelfReviewBriefView';import { homeType } from '@/features/Home/components/homeType';import Time from '@/features/Home/components/Time';import { useBriefStore } from '@/store/brief';@@ -87,6 +89,8 @@ interface NewsItemProps {*/const NewsItem = memo<NewsItemProps>(({ bare, brief, showTime }) => {const markBriefRead = useBriefStore((s) => s.markBriefRead);+ // Nightly self-review ideas list themselves from metadata, like proposals do.+ const selfReview = useSelfReviewBriefView(brief.metadata);const [expanded, setExpanded] = useState(false);const [localRead, setLocalRead] = useState(false);@@ -141,7 +145,7 @@ const NewsItem = memo<NewsItemProps>(({ bare, brief, showTime }) => {minWidth: 0,}}>- {brief.title}+ {selfReview?.title ?? brief.title}</Text>{showTime && <Time date={brief.createdAt} />}<Icon@@ -154,12 +158,16 @@ const NewsItem = memo<NewsItemProps>(({ bare, brief, showTime }) => {{expanded && (brief.summary || brief.artifacts || hasTopicChat) && (<Flexbox className={bare ? styles.bareBody : styles.body} gap={8}>- {brief.summary && (- <Suspense fallback={null}>- <Markdown style={{ overflow: 'unset' }} variant={'chat'}>- {brief.summary}- </Markdown>- </Suspense>+ {selfReview ? (+ <SelfReviewBriefDetails details={selfReview.details} />+ ) : (+ brief.summary && (+ <Suspense fallback={null}>+ <Markdown style={{ overflow: 'unset' }} variant={'chat'}>+ {brief.summary}+ </Markdown>+ </Suspense>+ ))}<BriefCardArtifacts artifacts={brief.artifacts} />{agentId && topicId && (diff --git a/src/features/MemoryRules/index.tsx b/src/features/MemoryRules/index.tsxindex 0d7e7c65ae4..d49b5a32c36 100644--- a/src/features/MemoryRules/index.tsx+++ b/src/features/MemoryRules/index.tsx@@ -1,20 +1,18 @@'use client';-import { Block, Empty, Flexbox, Icon, SortableList } from '@lobehub/ui';+import { Block, Flexbox, Icon, SortableList } from '@lobehub/ui';import { Button, Text, toast } from '@lobehub/ui/base-ui';import { cx } from 'antd-style';-import { ArrowDownIcon, ArrowUpIcon, FileSearchIcon, FlaskConicalIcon, PencilIcon, PlusIcon } from 'lucide-react';+import { ArrowDownIcon, ArrowUpIcon, FileSearchIcon, PencilIcon, PlusIcon } from 'lucide-react';import { useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import AsyncBoundary from '@/components/AsyncBoundary';import Loading from '@/components/Loading/BrandTextLoading';import NavHeader from '@/features/NavHeader';+import { SelfLearningLabOff, useSelfLearningSurface } from '@/features/SelfLearning/SurfaceGate';import WideScreenContainer from '@/features/WideScreenContainer';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { expertiseService, type RuleItem, type UpdateRuleInput } from '@/services/expertise';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/slices/preference/selectors/labPrefer';import { createComposeRuleModal } from './ComposeModal';import DetailPanel from './DetailPanel';@@ -37,24 +35,6 @@ import RulesOnboarding, { type RulesOnboardingAgents } from './RulesOnboarding';import { styles } from './styles';import { useJudgeDirections } from './useJudgeDirections';-const LabOff = () => {- const { t } = useTranslation('memory');- const navigate = useWorkspaceAwareNavigate();- return (- <Flexbox align={'center'} flex={1} justify={'center'}>- <Empty- description={t('rules.labOff.description')}- icon={FlaskConicalIcon}- title={t('rules.labOff.title')}- >- <Button size={'small'} onClick={() => navigate('/settings/labs')}>- {t('rules.labOff.open')}- </Button>- </Empty>- </Flexbox>- );-};-/*** Self-evolving, as one sheet per part: a switcher above it picks the reviewer's own rules (the* default) or what one agent learned by itself. Within the part, groups are full-width section@@ -70,7 +50,7 @@ const LabOff = () => {*/const MemoryRules = () => {const { t } = useTranslation('memory');- const enabled = useUserStore(labPreferSelectors.enableSelfLearning);+ const { enabled, ready } = useSelfLearningSurface();const { data, error, isLoading, mutate } = useRules();const [selectedId, setSelectedId] = useState<string>();const [titleEditing, setTitleEditing] = useState(false);@@ -354,7 +334,8 @@ const MemoryRules = () => {return (<Flexbox height={'100%'} width={'100%'}><NavHeader />- <LabOff />+ {/* The Labs preference arrives with the user state; wait for it instead of flashing Labs. */}+ {ready && <SelfLearningLabOff />}</Flexbox>);}diff --git a/src/features/Portal/MemoryDetail/Body.tsx b/src/features/Portal/MemoryDetail/Body.tsxnew file mode 100644index 00000000000..309cca1e42f--- /dev/null+++ b/src/features/Portal/MemoryDetail/Body.tsx@@ -0,0 +1,54 @@+'use client';++import { LayersEnum } from '@lobechat/types';+import { Flexbox } from '@lobehub/ui';+import { memo } from 'react';++import ActivityDetail from '@/routes/(main)/memory/activities/features/ActivityDetail';+import ContextDetail from '@/routes/(main)/memory/contexts/features/ContextDetail';+import DetailNotFound from '@/routes/(main)/memory/features/DetailNotFound';+import IdentityDetail from '@/routes/(main)/memory/identities/features/IdentityDetail';+import PreferenceDetail from '@/routes/(main)/memory/preferences/features/PreferenceDetail';+import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';++const renderDetail = (layer: LayersEnum, id: string) => {+ switch (layer) {+ case LayersEnum.Activity: {+ return <ActivityDetail id={id} />;+ }+ case LayersEnum.Context: {+ return <ContextDetail id={id} />;+ }+ case LayersEnum.Identity: {+ return <IdentityDetail id={id} />;+ }+ case LayersEnum.Preference: {+ return <PreferenceDetail id={id} />;+ }+ default: {+ return <DetailNotFound />;+ }+ }+};++const Body = memo(() => {+ const view = useChatStore(chatPortalSelectors.memoryDetailView);++ if (!view) return null;++ return (+ <Flexbox+ flex={1}+ gap={16}+ paddingInline={16}+ style={{ overflowY: 'auto', paddingBottom: 64, paddingTop: 16 }}+ >+ {renderDetail(view.layer, view.id)}+ </Flexbox>+ );+});++Body.displayName = 'MemoryDetailBody';++export default Body;diff --git a/src/features/Portal/MemoryDetail/Header.tsx b/src/features/Portal/MemoryDetail/Header.tsxnew file mode 100644index 00000000000..b7b0cb976e6--- /dev/null+++ b/src/features/Portal/MemoryDetail/Header.tsx@@ -0,0 +1,46 @@+'use client';++import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@lobechat/const';+import { ActionIcon } from '@lobehub/ui/base-ui';+import { Maximize2Icon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import PortalChromeHeader from '@/features/Portal/components/Header';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';++import { getMemoryDetailPath } from './memoryDetailRoutes';+import Title from './Title';++const Header = memo<{ onClose?: () => void }>(({ onClose }) => {+ const { t } = useTranslation('chat');+ const view = useChatStore(chatPortalSelectors.memoryDetailView);+ const navigate = useWorkspaceAwareNavigate();+ const clearPortalStack = useChatStore((s) => s.clearPortalStack);++ return (+ <PortalChromeHeader+ title={<Title />}+ rightExtra={+ view ? (+ <ActionIcon+ icon={Maximize2Icon}+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}+ title={t('agentSignal.receipts.memory.openInMemory')}+ onClick={() => {+ navigate(getMemoryDetailPath(view.layer, view.id));+ clearPortalStack();+ }}+ />+ ) : undefined+ }+ onClose={onClose}+ />+ );+});++Header.displayName = 'MemoryDetailHeader';++export default Header;diff --git a/src/features/Portal/MemoryDetail/Title.tsx b/src/features/Portal/MemoryDetail/Title.tsxnew file mode 100644index 00000000000..d4910882b25--- /dev/null+++ b/src/features/Portal/MemoryDetail/Title.tsx@@ -0,0 +1,32 @@+'use client';++import { LayersEnum } from '@lobechat/types';+import { Text } from '@lobehub/ui/base-ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';++const TAB_KEY_BY_LAYER = {+ [LayersEnum.Activity]: 'tab.activities',+ [LayersEnum.Context]: 'tab.contexts',+ [LayersEnum.Identity]: 'tab.identities',+ [LayersEnum.Preference]: 'tab.preferences',+} as const satisfies Partial<Record<LayersEnum, string>>;++const Title = memo(() => {+ const { t } = useTranslation('memory');+ const layer = useChatStore((s) => chatPortalSelectors.memoryDetailView(s)?.layer);+ const tabKey = layer ? TAB_KEY_BY_LAYER[layer as keyof typeof TAB_KEY_BY_LAYER] : undefined;++ return (+ <Text ellipsis weight={500}>+ {tabKey ? t(tabKey) : t('tab.home')}+ </Text>+ );+});++Title.displayName = 'MemoryDetailTitle';++export default Title;diff --git a/src/features/Portal/MemoryDetail/index.ts b/src/features/Portal/MemoryDetail/index.tsnew file mode 100644index 00000000000..b865fb5e4c9--- /dev/null+++ b/src/features/Portal/MemoryDetail/index.ts@@ -0,0 +1,10 @@+import type { PortalImpl } from '../type';+import Body from './Body';+import Header from './Header';+import Title from './Title';++export const MemoryDetail: PortalImpl = {+ Body,+ Header,+ Title,+};diff --git a/src/features/Portal/MemoryDetail/memoryDetailRoutes.ts b/src/features/Portal/MemoryDetail/memoryDetailRoutes.tsnew file mode 100644index 00000000000..5ba6b44a743--- /dev/null+++ b/src/features/Portal/MemoryDetail/memoryDetailRoutes.ts@@ -0,0 +1,25 @@+import { LayersEnum } from '@lobechat/types';++/**+ * Memory layers that have a detail surface (memory page right panel + chat Portal view). The+ * experience layer has no surface any more, so it is intentionally absent.+ */+export const MEMORY_DETAIL_ROUTE_BY_LAYER: Partial<+ Record<LayersEnum, { idParam: string; path: string }>+> = {+ [LayersEnum.Activity]: { idParam: 'activityId', path: '/memory/activities' },+ [LayersEnum.Context]: { idParam: 'contextId', path: '/memory/contexts' },+ [LayersEnum.Identity]: { idParam: 'identityId', path: '/memory/identities' },+ [LayersEnum.Preference]: { idParam: 'preferenceId', path: '/memory/preferences' },+};++export const hasMemoryDetailView = (layer?: LayersEnum): layer is LayersEnum =>+ Boolean(layer && MEMORY_DETAIL_ROUTE_BY_LAYER[layer]);++/** Full-page memory route for one layer, optionally focused on a layer-specific row id. */+export const getMemoryDetailPath = (layer: LayersEnum, id?: string) => {+ const route = MEMORY_DETAIL_ROUTE_BY_LAYER[layer];+ if (!route) return '/memory';++ return id ? `${route.path}?${route.idParam}=${encodeURIComponent(id)}` : route.path;+};diff --git a/src/features/Portal/router.tsx b/src/features/Portal/router.tsxindex b6700ab2b21..c3deae1a76d 100644--- a/src/features/Portal/router.tsx+++ b/src/features/Portal/router.tsx@@ -22,6 +22,7 @@ import { GoalReport, GoalReportChapter } from './GoalReport';import { GroupThread } from './GroupThread';import { HomeBody, HomeTitle } from './Home';import { LocalFile } from './LocalFile';+import { MemoryDetail } from './MemoryDetail';import { MessageDetail } from './MessageDetail';import { Notebook } from './Notebook';import { Plugins } from './Plugins';@@ -54,6 +55,7 @@ const VIEW_COMPONENTS: Record<PortalViewType, PortalImpl> = {[PortalViewType.GoalReport]: GoalReport,[PortalViewType.GoalReportChapter]: GoalReportChapter,[PortalViewType.LocalFile]: LocalFile,+ [PortalViewType.MemoryDetail]: MemoryDetail,[PortalViewType.MessageDetail]: MessageDetail,[PortalViewType.ToolUI]: Plugins,[PortalViewType.TaskDetail]: TaskDetail,diff --git a/src/features/SelfLearning/SurfaceGate/LabOff.tsx b/src/features/SelfLearning/SurfaceGate/LabOff.tsxnew file mode 100644index 00000000000..1e88256bd00--- /dev/null+++ b/src/features/SelfLearning/SurfaceGate/LabOff.tsx@@ -0,0 +1,27 @@+'use client';++import { Empty, Flexbox } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { FlaskConicalIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';++/** Empty state for a review surface the user has not unlocked: points at the Labs switch. */+const LabOff = () => {+ const { t } = useTranslation('memory');+ const navigate = useWorkspaceAwareNavigate();+ return (+ <Flexbox align={'center'} flex={1} justify={'center'}>+ <Empty+ description={t('rules.labOff.description')}+ icon={FlaskConicalIcon}+ title={t('rules.labOff.title')}+ >+ <Button onClick={() => navigate('/settings/labs')}>{t('rules.labOff.open')}</Button>+ </Empty>+ </Flexbox>+ );+};++export default LabOff;diff --git a/src/features/SelfLearning/SurfaceGate/index.tsx b/src/features/SelfLearning/SurfaceGate/index.tsxnew file mode 100644index 00000000000..4ea66a2b4b8--- /dev/null+++ b/src/features/SelfLearning/SurfaceGate/index.tsx@@ -0,0 +1,33 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import type { ReactNode } from 'react';++import NavHeader from '@/features/NavHeader';++import LabOff from './LabOff';+import { useSelfLearningSurface } from './useSelfLearningSurface';++export { default as SelfLearningLabOff } from './LabOff';+export { useSelfLearningSurface } from './useSelfLearningSurface';++/**+ * Route-level gate for the Self-evolving pages, matching My rules: a deep link opens the page+ * only when the review surfaces are on, and otherwise lands on the "turn on in Labs" state.+ */+const SelfLearningSurfaceGate = ({ children }: { children: ReactNode }) => {+ const { enabled, ready } = useSelfLearningSurface();++ if (enabled) return children;+ // The Labs preference arrives with the user state; wait for it instead of flashing Labs.+ if (!ready) return null;++ return (+ <Flexbox height={'100%'} width={'100%'}>+ <NavHeader />+ <LabOff />+ </Flexbox>+ );+};++export default SelfLearningSurfaceGate;diff --git a/src/features/SelfLearning/SurfaceGate/useSelfLearningSurface.test.ts b/src/features/SelfLearning/SurfaceGate/useSelfLearningSurface.test.tsnew file mode 100644index 00000000000..587eb11ee14--- /dev/null+++ b/src/features/SelfLearning/SurfaceGate/useSelfLearningSurface.test.ts@@ -0,0 +1,50 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useSelfLearningSurface } from './useSelfLearningSurface';++const state = vi.hoisted(() => ({+ enableSelfLearning: false,+ isUserStateInit: true,+}));++vi.mock('@/store/user', () => ({+ useUserStore: (selector: (s: typeof state) => unknown) => selector(state),+}));++vi.mock('@/store/user/selectors', () => ({+ labPreferSelectors: { enableSelfLearning: (s: typeof state) => s.enableSelfLearning },+}));++beforeEach(() => {+ state.enableSelfLearning = false;+ state.isUserStateInit = true;+});++describe('useSelfLearningSurface', () => {+ it('turns the review surfaces on with the Labs switch', () => {+ state.enableSelfLearning = true;++ const { result } = renderHook(() => useSelfLearningSurface());++ expect(result.current).toEqual({ enabled: true, ready: true });+ });++ it('stays off while the Labs switch is off', () => {+ const { result } = renderHook(() => useSelfLearningSurface());++ expect(result.current).toEqual({ enabled: false, ready: true });+ });++ /**+ * The Labs preference arrives with the user state, not the server config; gated pages must+ * not flash the "turn on in Labs" state before it loads.+ */+ it('reports not ready until the user state has loaded', () => {+ state.isUserStateInit = false;++ const { result } = renderHook(() => useSelfLearningSurface());++ expect(result.current.ready).toBe(false);+ });+});diff --git a/src/features/SelfLearning/SurfaceGate/useSelfLearningSurface.ts b/src/features/SelfLearning/SurfaceGate/useSelfLearningSurface.tsnew file mode 100644index 00000000000..d461de39a21--- /dev/null+++ b/src/features/SelfLearning/SurfaceGate/useSelfLearningSurface.ts@@ -0,0 +1,18 @@+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';++/**+ * Whether the surfaces for reviewing what agents learned (Self-evolving page, My rules) are on.+ *+ * Labs → Self-evolving is the single switch for everything agents learn in the background, so+ * the review surfaces follow it exactly.+ *+ * `ready` is false until the user state (and so the Labs preference) has loaded; gated pages+ * should not show the "turn on in Labs" state before then.+ */+export const useSelfLearningSurface = () => {+ const ready = useUserStore((s) => s.isUserStateInit);+ const enabled = useUserStore(labPreferSelectors.enableSelfLearning);++ return { enabled, ready };+};diff --git a/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx b/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsxindex 253f696191d..62ba73a7c13 100644--- a/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx+++ b/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx@@ -16,11 +16,7 @@ const mocks = vi.hoisted(() => ({optimisticUpdateAgentConfig: vi.fn(),optimisticUpdateAgentMeta: vi.fn(),},- serverState: {- featureFlags: {- enableAgentSelfIteration: true,- },- },+ userState: { preference: { lab: { enableAgentGraphConfig: false } } },}));vi.mock('@/features/AgentSetting', () => ({@@ -66,63 +62,53 @@ vi.mock('@/store/agent/selectors', () => ({},}));-vi.mock('@/store/serverConfig', () => ({- featureFlagsSelectors: (state: typeof mocks.serverState) => state.featureFlags,- useServerConfigStore: (selector: (state: typeof mocks.serverState) => unknown) =>- selector(mocks.serverState),+vi.mock('@/store/user', () => ({+ useUserStore: (selector: (state: typeof mocks.userState) => unknown) => selector(mocks.userState),+}));++vi.mock('@/store/user/selectors', () => ({+ labPreferSelectors: {+ enableAgentGraphConfig: (state: typeof mocks.userState) =>+ state.preference.lab.enableAgentGraphConfig,+ },}));describe('AgentSettings Content', () => {beforeEach(() => {mocks.agentState.isInbox = true;- mocks.serverState.featureFlags.enableAgentSelfIteration = true;+ mocks.agentState.isCurrentAgentHeterogeneous = false;+ mocks.userState.preference.lab.enableAgentGraphConfig = false;});- it('exposes both tabs for inbox when feature is on', () => {+ it('opens on the opening tab', () => {render(<Content />);const layout = screen.getByTestId('layout');expect(layout).toHaveAttribute('data-active', ChatSettingsTabs.Opening);- expect(layout).toHaveAttribute(- 'data-tabs',- `${ChatSettingsTabs.Opening},${ChatSettingsTabs.SelfIteration}`,- );+ expect(layout).toHaveAttribute('data-tabs', ChatSettingsTabs.Opening);expect(screen.getByTestId('agent-settings-content')).toHaveAttribute('data-tab',ChatSettingsTabs.Opening,);});- it('exposes both tabs when not inbox and feature is on', () => {+ it('adds the graph tab for custom agents when its Labs switch is on', () => {mocks.agentState.isInbox = false;+ mocks.userState.preference.lab.enableAgentGraphConfig = true;render(<Content />);- const layout = screen.getByTestId('layout');- expect(layout).toHaveAttribute('data-active', ChatSettingsTabs.Opening);- expect(layout).toHaveAttribute(+ expect(screen.getByTestId('layout')).toHaveAttribute('data-tabs',- `${ChatSettingsTabs.Opening},${ChatSettingsTabs.SelfIteration}`,+ `${ChatSettingsTabs.Opening},${ChatSettingsTabs.Graph}`,);});- it('falls back to opening when feature flag is off (inbox)', () => {- mocks.serverState.featureFlags.enableAgentSelfIteration = false;-- render(<Content />);-- const layout = screen.getByTestId('layout');- expect(layout).toHaveAttribute('data-active', ChatSettingsTabs.Opening);- expect(layout).toHaveAttribute('data-tabs', ChatSettingsTabs.Opening);- });-- it('exposes only opening when feature flag is off', () => {- mocks.agentState.isInbox = false;- mocks.serverState.featureFlags.enableAgentSelfIteration = false;+ it('keeps the graph tab off for inbox even with its Labs switch on', () => {+ mocks.userState.preference.lab.enableAgentGraphConfig = true;render(<Content />);- const layout = screen.getByTestId('layout');- expect(layout).toHaveAttribute('data-tabs', ChatSettingsTabs.Opening);+ expect(screen.getByTestId('layout')).toHaveAttribute('data-tabs', ChatSettingsTabs.Opening);});});diff --git a/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx b/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsxindex d4bf69c99f3..5f8c1f5cd49 100644--- a/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx+++ b/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx@@ -1,7 +1,7 @@'use client';import isEqual from 'fast-deep-equal';-import { ActivityIcon, GitBranchIcon, MessageSquareHeartIcon } from 'lucide-react';+import { GitBranchIcon, MessageSquareHeartIcon } from 'lucide-react';import { memo, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { shallow } from 'zustand/shallow';@@ -16,17 +16,12 @@ import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';import { ChatSettingsTabs } from '@/store/global/initialState';-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';import { useUserStore } from '@/store/user';import { labPreferSelectors } from '@/store/user/selectors';const TAB_META = {[ChatSettingsTabs.Graph]: { icon: GitBranchIcon, labelKey: 'agentTab.graph' },[ChatSettingsTabs.Opening]: { icon: MessageSquareHeartIcon, labelKey: 'agentTab.opening' },- [ChatSettingsTabs.SelfIteration]: {- icon: ActivityIcon,- labelKey: 'agentTab.selfIteration',- },} as const;const Content = memo(() => {@@ -39,19 +34,16 @@ const Content = memo(() => {const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);- const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);const enableAgentGraphConfigLab = useUserStore(labPreferSelectors.enableAgentGraphConfig);const [tab, setTab] = useState(ChatSettingsTabs.Opening);const showGraphTab = enableAgentGraphConfigLab && !isInbox && !isHeterogeneous;const availableTabs = useMemo(() =>- [- ChatSettingsTabs.Opening,- enableAgentSelfIteration ? ChatSettingsTabs.SelfIteration : null,- showGraphTab ? ChatSettingsTabs.Graph : null,- ].filter(Boolean) as ChatSettingsTabs[],- [enableAgentSelfIteration, showGraphTab],+ [ChatSettingsTabs.Opening, showGraphTab ? ChatSettingsTabs.Graph : null].filter(+ Boolean,+ ) as ChatSettingsTabs[],+ [showGraphTab],);const activeTab = availableTabs.includes(tab) ? tab : availableTabs[0];diff --git a/src/routes/(main)/agent/self-learning/[domainId]/experience/[lessonId]/index.tsx b/src/routes/(main)/agent/self-learning/[domainId]/experience/[lessonId]/index.tsxindex bfc5121efea..33311d3b7c8 100644--- a/src/routes/(main)/agent/self-learning/[domainId]/experience/[lessonId]/index.tsx+++ b/src/routes/(main)/agent/self-learning/[domainId]/experience/[lessonId]/index.tsx@@ -3,7 +3,12 @@import { memo } from 'react';import LessonDetail from '@/features/SelfLearning/LessonDetail';+import SelfLearningSurfaceGate from '@/features/SelfLearning/SurfaceGate';-const AgentSelfLearningLessonPage = memo(() => <LessonDetail />);+const AgentSelfLearningLessonPage = memo(() => (+ <SelfLearningSurfaceGate>+ <LessonDetail />+ </SelfLearningSurfaceGate>+));export default AgentSelfLearningLessonPage;diff --git a/src/routes/(main)/agent/self-learning/[domainId]/experience/index.tsx b/src/routes/(main)/agent/self-learning/[domainId]/experience/index.tsxindex 0d39a90f630..9c3e459771c 100644--- a/src/routes/(main)/agent/self-learning/[domainId]/experience/index.tsx+++ b/src/routes/(main)/agent/self-learning/[domainId]/experience/index.tsx@@ -3,8 +3,13 @@import { memo } from 'react';import ExperienceList from '@/features/SelfLearning/ExperienceList';+import SelfLearningSurfaceGate from '@/features/SelfLearning/SurfaceGate';/** The complete lesson list of one direction — every habit, nothing folded. */-const AgentSelfLearningExperiencePage = memo(() => <ExperienceList />);+const AgentSelfLearningExperiencePage = memo(() => (+ <SelfLearningSurfaceGate>+ <ExperienceList />+ </SelfLearningSurfaceGate>+));export default AgentSelfLearningExperiencePage;diff --git a/src/routes/(main)/agent/self-learning/[domainId]/index.tsx b/src/routes/(main)/agent/self-learning/[domainId]/index.tsxindex f5a3e95a301..86017ff2587 100644--- a/src/routes/(main)/agent/self-learning/[domainId]/index.tsx+++ b/src/routes/(main)/agent/self-learning/[domainId]/index.tsx@@ -3,8 +3,13 @@import { memo } from 'react';import SelfLearning from '@/features/SelfLearning';+import SelfLearningSurfaceGate from '@/features/SelfLearning/SurfaceGate';/** The domain page is the same growth portrait, scoped to one direction via :domainId. */-const AgentSelfLearningDomainPage = memo(() => <SelfLearning />);+const AgentSelfLearningDomainPage = memo(() => (+ <SelfLearningSurfaceGate>+ <SelfLearning />+ </SelfLearningSurfaceGate>+));export default AgentSelfLearningDomainPage;diff --git a/src/routes/(main)/agent/self-learning/index.tsx b/src/routes/(main)/agent/self-learning/index.tsxindex 40fee24cb12..50748c85622 100644--- a/src/routes/(main)/agent/self-learning/index.tsx+++ b/src/routes/(main)/agent/self-learning/index.tsx@@ -3,7 +3,12 @@import { memo } from 'react';import SelfLearning from '@/features/SelfLearning';+import SelfLearningSurfaceGate from '@/features/SelfLearning/SurfaceGate';-const AgentSelfLearningPage = memo(() => <SelfLearning />);+const AgentSelfLearningPage = memo(() => (+ <SelfLearningSurfaceGate>+ <SelfLearning />+ </SelfLearningSurfaceGate>+));export default AgentSelfLearningPage;diff --git a/src/routes/(main)/agent/self-learning/new/index.tsx b/src/routes/(main)/agent/self-learning/new/index.tsxindex 295f0bc7a0e..d0f04878065 100644--- a/src/routes/(main)/agent/self-learning/new/index.tsx+++ b/src/routes/(main)/agent/self-learning/new/index.tsx@@ -3,8 +3,13 @@import { memo } from 'react';import CreateDomainPage from '@/features/SelfLearning/CreateDomainPage';+import SelfLearningSurfaceGate from '@/features/SelfLearning/SurfaceGate';-const AgentSelfLearningCreatePage = memo(() => <CreateDomainPage />);+const AgentSelfLearningCreatePage = memo(() => (+ <SelfLearningSurfaceGate>+ <CreateDomainPage />+ </SelfLearningSurfaceGate>+));AgentSelfLearningCreatePage.displayName = 'AgentSelfLearningCreatePage';diff --git a/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsx b/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsxindex f623025fd5d..8a311769283 100644--- a/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsx+++ b/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsx@@ -16,11 +16,10 @@ import { Link } from 'react-router';import { type NavItemProps } from '@/features/NavPanel/components/NavItem';import NavItem from '@/features/NavPanel/components/NavItem';+import { useSelfLearningSurface } from '@/features/SelfLearning/SurfaceGate/useSelfLearningSurface';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useActiveLocation } from '@/hooks/useActiveLocation';import { useGlobalStore } from '@/store/global';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/slices/preference/selectors/labPrefer';import { isModifierClick } from '@/utils/navigation';interface Item {@@ -51,7 +50,7 @@ const Nav = memo(() => {const navigate = useWorkspaceAwareNavigate();const { t } = useTranslation('memory');const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);- const enableSelfLearning = useUserStore(labPreferSelectors.enableSelfLearning);+ const { enabled: enableSelfLearning } = useSelfLearningSurface();/*** Four groups, separated by space rather than rules: what the whole section is (home), what it@@ -79,8 +78,8 @@ const Nav = memo(() => {url: '/memory',},],- // Self-evolving is still an alpha lab: the group disappears with the flag rather than- // sitting there disabled, so the sidebar of everyone else reads exactly as before.+ // Shown to the self-iteration rollout and to Labs opt-ins; for everyone else the group+ // disappears rather than sitting there disabled, so their sidebar reads exactly as before....(enableSelfLearning? [[diff --git a/src/routes/(main)/memory/activities/features/ActivityDetail.tsx b/src/routes/(main)/memory/activities/features/ActivityDetail.tsxnew file mode 100644index 00000000000..6959df39de5--- /dev/null+++ b/src/routes/(main)/memory/activities/features/ActivityDetail.tsx@@ -0,0 +1,129 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { Tag, Text } from '@lobehub/ui/base-ui';+import dayjs from 'dayjs';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncBoundary from '@/components/AsyncBoundary';+import CateTag from '@/routes/(main)/memory/features/CateTag';+import DetailLoading from '@/routes/(main)/memory/features/DetailLoading';+import DetailNotFound from '@/routes/(main)/memory/features/DetailNotFound';+import HashTags from '@/routes/(main)/memory/features/HashTags';+import HighlightedContent from '@/routes/(main)/memory/features/HighlightedContent';+import SourceLink from '@/routes/(main)/memory/features/SourceLink';+import Time from '@/routes/(main)/memory/features/Time';+import { useUserMemoryStore } from '@/store/userMemory';+import { LayersEnum } from '@/types/userMemory';++const formatTime = (value?: Date | string | null) => {+ if (!value) return null;+ const time = dayjs(value);+ if (!time.isValid()) return null;+ return time.format('YYYY-MM-DD HH:mm');+};++interface ActivityDetailProps {+ /** Layer-specific row id (`activityId`). */+ id: string;+}++/**+ * The activity memory detail body, shared by the memory page's right panel and the chat Portal.+ */+const ActivityDetail = memo<ActivityDetailProps>(({ id: activityId }) => {+ const { t } = useTranslation('memory');+ const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);++ const {+ data: activity,+ isLoading,+ error,+ mutate,+ } = useFetchMemoryDetail(activityId, LayersEnum.Activity);++ const schedule = useMemo(() => {+ if (!activity) return null;+ const start = formatTime(activity.startsAt);+ const end = formatTime(activity.endsAt);+ if (!start && !end) return null;+ if (start && end) return `${start} → ${end}`;+ return start || end;+ }, [activity]);++ let content;+ if (activity) {+ const capturedAt =+ activity.startsAt ||+ activity.capturedAt ||+ activity.updatedAt ||+ activity.createdAt ||+ undefined;++ content = (+ <>+ <CateTag cate={activity.type} />+ <Text+ as={'h1'}+ fontSize={20}+ weight={'bold'}+ style={{+ lineHeight: 1.4,+ marginBottom: 0,+ }}+ >+ {activity.title || t('activity.defaultType')}+ </Text>+ <Flexbox horizontal align="center" gap={16} justify="space-between">+ {activity.status && <Tag>{activity.status}</Tag>}+ <SourceLink source={activity.source} />+ </Flexbox>+ <Flexbox horizontal align="center" gap={16} justify="space-between">+ <Time capturedAt={capturedAt} />+ {activity.timezone && (+ <Text fontSize={12} type="secondary">+ {activity.timezone}+ </Text>+ )}+ </Flexbox>++ {schedule && <HighlightedContent>{schedule}</HighlightedContent>}+ {activity.narrative && (+ <HighlightedContent title={t('activity.narrative')}>+ {activity.narrative}+ </HighlightedContent>+ )}+ {activity.notes && (+ <HighlightedContent title={t('activity.notes')}>{activity.notes}</HighlightedContent>+ )}+ {activity.feedback && (+ <HighlightedContent title={t('activity.feedback')}>+ {activity.feedback}+ </HighlightedContent>+ )}++ <HashTags hashTags={activity.tags} />+ </>+ );+ }++ return (+ <AsyncBoundary+ data={activity}+ empty={<DetailNotFound />}+ error={error}+ errorVariant={'page'}+ isEmpty={!activity}+ isLoading={isLoading}+ loading={<DetailLoading />}+ onRetry={() => mutate()}+ >+ {content}+ </AsyncBoundary>+ );+});++ActivityDetail.displayName = 'ActivityDetail';++export default ActivityDetail;diff --git a/src/routes/(main)/memory/activities/features/ActivityRightPanel.tsx b/src/routes/(main)/memory/activities/features/ActivityRightPanel.tsxindex e69e4544461..c3eb9fd57d9 100644--- a/src/routes/(main)/memory/activities/features/ActivityRightPanel.tsx+++ b/src/routes/(main)/memory/activities/features/ActivityRightPanel.tsx@@ -1,133 +1,26 @@'use client';-import { Flexbox } from '@lobehub/ui';-import { Tag, Text } from '@lobehub/ui/base-ui';-import dayjs from 'dayjs';-import { memo, useMemo } from 'react';-import { useTranslation } from 'react-i18next';+import { memo } from 'react';-import AsyncBoundary from '@/components/AsyncBoundary';import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';import { useQueryState } from '@/hooks/useQueryParam';-import CateTag from '@/routes/(main)/memory/features/CateTag';-import DetailLoading from '@/routes/(main)/memory/features/DetailLoading';-import DetailNotFound from '@/routes/(main)/memory/features/DetailNotFound';import DetailPanel from '@/routes/(main)/memory/features/DetailPanel';-import HashTags from '@/routes/(main)/memory/features/HashTags';-import HighlightedContent from '@/routes/(main)/memory/features/HighlightedContent';-import SourceLink from '@/routes/(main)/memory/features/SourceLink';-import Time from '@/routes/(main)/memory/features/Time';-import { useUserMemoryStore } from '@/store/userMemory';-import { LayersEnum } from '@/types/userMemory';+import ActivityDetail from './ActivityDetail';import ActivityDropdown from './ActivityDropdown';-const formatTime = (value?: Date | string | null) => {- if (!value) return null;- const time = dayjs(value);- if (!time.isValid()) return null;- return time.format('YYYY-MM-DD HH:mm');-};-const ActivityRightPanel = memo(() => {- const { t } = useTranslation('memory');const [activityId] = useQueryState('activityId', { clearOnDefault: true });- const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);-- const {- data: activity,- isLoading,- error,- mutate,- } = useFetchMemoryDetail(activityId, LayersEnum.Activity);-- const schedule = useMemo(() => {- if (!activity) return null;- const start = formatTime(activity.startsAt);- const end = formatTime(activity.endsAt);- if (!start && !end) return null;- if (start && end) return `${start} → ${end}`;- return start || end;- }, [activity]);if (!activityId) return null;- let content;- if (activity) {- const capturedAt =- activity.startsAt ||- activity.capturedAt ||- activity.updatedAt ||- activity.createdAt ||- undefined;-- content = (- <>- <CateTag cate={activity.type} />- <Text- as={'h1'}- fontSize={20}- weight={'bold'}- style={{- lineHeight: 1.4,- marginBottom: 0,- }}- >- {activity.title || t('activity.defaultType')}- </Text>- <Flexbox horizontal align="center" gap={16} justify="space-between">- {activity.status && <Tag>{activity.status}</Tag>}- <SourceLink source={activity.source} />- </Flexbox>- <Flexbox horizontal align="center" gap={16} justify="space-between">- <Time capturedAt={capturedAt} />- {activity.timezone && (- <Text fontSize={12} type="secondary">- {activity.timezone}- </Text>- )}- </Flexbox>-- {schedule && <HighlightedContent>{schedule}</HighlightedContent>}- {activity.narrative && (- <HighlightedContent title={t('activity.narrative')}>- {activity.narrative}- </HighlightedContent>- )}- {activity.notes && (- <HighlightedContent title={t('activity.notes')}>{activity.notes}</HighlightedContent>- )}- {activity.feedback && (- <HighlightedContent title={t('activity.feedback')}>- {activity.feedback}- </HighlightedContent>- )}-- <HashTags hashTags={activity.tags} />- </>- );- }-return (<DetailPanelheader={{- right: activityId ? (- <ActivityDropdown id={activityId} size={DESKTOP_HEADER_ICON_SIZE} />- ) : undefined,+ right: <ActivityDropdown id={activityId} size={DESKTOP_HEADER_ICON_SIZE} />,}}>- <AsyncBoundary- data={activity}- empty={<DetailNotFound />}- error={error}- errorVariant={'page'}- isEmpty={!activity}- isLoading={isLoading}- loading={<DetailLoading />}- onRetry={() => mutate()}- >- {content}- </AsyncBoundary>+ <ActivityDetail id={activityId} /></DetailPanel>);});diff --git a/src/routes/(main)/memory/contexts/features/ContextDetail.tsx b/src/routes/(main)/memory/contexts/features/ContextDetail.tsxnew file mode 100644index 00000000000..e31bee9f4f7--- /dev/null+++ b/src/routes/(main)/memory/contexts/features/ContextDetail.tsx@@ -0,0 +1,98 @@+'use client';++import { Center, Flexbox, Tooltip } from '@lobehub/ui';+import { Badge, Text } from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncBoundary from '@/components/AsyncBoundary';+import CateTag from '@/routes/(main)/memory/features/CateTag';+import DetailLoading from '@/routes/(main)/memory/features/DetailLoading';+import DetailNotFound from '@/routes/(main)/memory/features/DetailNotFound';+import HashTags from '@/routes/(main)/memory/features/HashTags';+import HighlightedContent from '@/routes/(main)/memory/features/HighlightedContent';+import ProgressIcon from '@/routes/(main)/memory/features/ProgressIcon';+import SourceLink from '@/routes/(main)/memory/features/SourceLink';+import Time from '@/routes/(main)/memory/features/Time';+import { useUserMemoryStore } from '@/store/userMemory';+import { LayersEnum } from '@/types/userMemory';++interface ContextDetailProps {+ /** Layer-specific row id (`contextId`). */+ id: string;+}++/**+ * The context memory detail body, shared by the memory page's right panel and the chat Portal.+ */+const ContextDetail = memo<ContextDetailProps>(({ id: contextId }) => {+ const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);+ const { t } = useTranslation('memory');+ const {+ data: context,+ isLoading,+ error,+ mutate,+ } = useFetchMemoryDetail(contextId, LayersEnum.Context);++ const content = context && (+ <>+ <CateTag cate={context.type} />+ <Text+ as={'h1'}+ fontSize={20}+ weight={'bold'}+ style={{+ lineHeight: 1.4,+ marginBottom: 0,+ }}+ >+ {context.title}+ <Tooltip title={context.currentStatus}>+ <Center flex={'none'} height={20} style={{ display: 'inline-flex' }} width={20}>+ <Badge status="processing" style={{ marginLeft: 8 }} />+ </Center>+ </Tooltip>+ </Text>+ <Flexbox horizontal align="center" gap={16}>+ <ProgressIcon+ showInfo+ format={(percent) => `${t('filter.sort.scoreImpact')}: ${percent}%`}+ percent={(context.scoreImpact ?? 0) * 100}+ />+ <ProgressIcon+ showInfo+ format={(percent) => `${t('filter.sort.scoreUrgency')}: ${percent}%`}+ percent={(context.scoreUrgency ?? 0) * 100}+ strokeColor={(context.scoreUrgency ?? 0) >= 0.7 ? cssVar.colorError : cssVar.colorWarning}+ />+ </Flexbox>+ <Flexbox horizontal align="center" gap={16} justify="space-between">+ <SourceLink source={context.source} />+ <Time capturedAt={context.capturedAt || context.updatedAt || context.createdAt} />+ </Flexbox>+ <HighlightedContent>{context.description}</HighlightedContent>+ <HashTags hashTags={context.tags} />+ </>+ );++ return (+ <AsyncBoundary+ data={context}+ empty={<DetailNotFound />}+ error={error}+ errorVariant={'page'}+ isEmpty={!context}+ isLoading={isLoading}+ loading={<DetailLoading />}+ onRetry={() => mutate()}+ >+ {content}+ </AsyncBoundary>+ );+});++ContextDetail.displayName = 'ContextDetail';++export default ContextDetail;diff --git a/src/routes/(main)/memory/contexts/features/ContextRightPanel.tsx b/src/routes/(main)/memory/contexts/features/ContextRightPanel.tsxindex 7f3bdc400e9..164b8f42a67 100644--- a/src/routes/(main)/memory/contexts/features/ContextRightPanel.tsx+++ b/src/routes/(main)/memory/contexts/features/ContextRightPanel.tsx@@ -1,102 +1,26 @@'use client';-import { Center, Flexbox, Tooltip } from '@lobehub/ui';-import { Badge, Text } from '@lobehub/ui/base-ui';-import { cssVar } from 'antd-style';import { memo } from 'react';-import { useTranslation } from 'react-i18next';-import AsyncBoundary from '@/components/AsyncBoundary';import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';import { useQueryState } from '@/hooks/useQueryParam';-import CateTag from '@/routes/(main)/memory/features/CateTag';-import DetailLoading from '@/routes/(main)/memory/features/DetailLoading';-import DetailNotFound from '@/routes/(main)/memory/features/DetailNotFound';import DetailPanel from '@/routes/(main)/memory/features/DetailPanel';-import HashTags from '@/routes/(main)/memory/features/HashTags';-import HighlightedContent from '@/routes/(main)/memory/features/HighlightedContent';-import ProgressIcon from '@/routes/(main)/memory/features/ProgressIcon';-import SourceLink from '@/routes/(main)/memory/features/SourceLink';-import Time from '@/routes/(main)/memory/features/Time';-import { useUserMemoryStore } from '@/store/userMemory';-import { LayersEnum } from '@/types/userMemory';+import ContextDetail from './ContextDetail';import ContextDropdown from './ContextDropdown';const ContextRightPanel = memo(() => {const [contextId] = useQueryState('contextId', { clearOnDefault: true });- const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);- const { t } = useTranslation('memory');- const {- data: context,- isLoading,- error,- mutate,- } = useFetchMemoryDetail(contextId, LayersEnum.Context);if (!contextId) return null;- const content = context && (- <>- <CateTag cate={context.type} />- <Text- as={'h1'}- fontSize={20}- weight={'bold'}- style={{- lineHeight: 1.4,- marginBottom: 0,- }}- >- {context.title}- <Tooltip title={context.currentStatus}>- <Center flex={'none'} height={20} style={{ display: 'inline-flex' }} width={20}>- <Badge status="processing" style={{ marginLeft: 8 }} />- </Center>- </Tooltip>- </Text>- <Flexbox horizontal align="center" gap={16}>- <ProgressIcon- showInfo- format={(percent) => `${t('filter.sort.scoreImpact')}: ${percent}%`}- percent={(context.scoreImpact ?? 0) * 100}- />- <ProgressIcon- showInfo- format={(percent) => `${t('filter.sort.scoreUrgency')}: ${percent}%`}- percent={(context.scoreUrgency ?? 0) * 100}- strokeColor={(context.scoreUrgency ?? 0) >= 0.7 ? cssVar.colorError : cssVar.colorWarning}- />- </Flexbox>- <Flexbox horizontal align="center" gap={16} justify="space-between">- <SourceLink source={context.source} />- <Time capturedAt={context.capturedAt || context.updatedAt || context.createdAt} />- </Flexbox>- <HighlightedContent>{context.description}</HighlightedContent>- <HashTags hashTags={context.tags} />- </>- );-return (<DetailPanelheader={{- right: contextId ? (- <ContextDropdown id={contextId} size={DESKTOP_HEADER_ICON_SIZE} />- ) : undefined,+ right: <ContextDropdown id={contextId} size={DESKTOP_HEADER_ICON_SIZE} />,}}>- <AsyncBoundary- data={context}- empty={<DetailNotFound />}- error={error}- errorVariant={'page'}- isEmpty={!context}- isLoading={isLoading}- loading={<DetailLoading />}- onRetry={() => mutate()}- >- {content}- </AsyncBoundary>+ <ContextDetail id={contextId} /></DetailPanel>);});diff --git a/src/routes/(main)/memory/identities/features/IdentityDetail.tsx b/src/routes/(main)/memory/identities/features/IdentityDetail.tsxnew file mode 100644index 00000000000..ea8e657bdc7--- /dev/null+++ b/src/routes/(main)/memory/identities/features/IdentityDetail.tsx@@ -0,0 +1,72 @@+'use client';++import { Text } from '@lobehub/ui/base-ui';+import { memo } from 'react';++import AsyncBoundary from '@/components/AsyncBoundary';+import CateTag from '@/routes/(main)/memory/features/CateTag';+import DetailLoading from '@/routes/(main)/memory/features/DetailLoading';+import DetailNotFound from '@/routes/(main)/memory/features/DetailNotFound';+import HashTags from '@/routes/(main)/memory/features/HashTags';+import HighlightedContent from '@/routes/(main)/memory/features/HighlightedContent';+import Time from '@/routes/(main)/memory/features/Time';+import { useUserMemoryStore } from '@/store/userMemory';+import { LayersEnum } from '@/types/userMemory';++interface IdentityDetailProps {+ /** Layer-specific row id (`identityId`). */+ id: string;+}++/**+ * The identity memory detail body, shared by the memory page's right panel and the chat Portal.+ */+const IdentityDetail = memo<IdentityDetailProps>(({ id: identityId }) => {+ const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);++ const {+ data: identity,+ isLoading,+ error,+ mutate,+ } = useFetchMemoryDetail(identityId, LayersEnum.Identity);++ const content = identity && (+ <>+ <CateTag cate={identity.type} />+ <Text+ as={'h1'}+ fontSize={20}+ weight={'bold'}+ style={{+ lineHeight: 1.4,+ marginBottom: 0,+ }}+ >+ {identity.title}+ </Text>+ <Time capturedAt={identity.capturedAt || identity.updatedAt || identity.createdAt} />+ {identity.description && <HighlightedContent>{identity.description}</HighlightedContent>}+ <HashTags hashTags={identity.tags} />+ </>+ );++ return (+ <AsyncBoundary+ data={identity}+ empty={<DetailNotFound />}+ error={error}+ errorVariant={'page'}+ isEmpty={!identity}+ isLoading={isLoading}+ loading={<DetailLoading />}+ onRetry={() => mutate()}+ >+ {content}+ </AsyncBoundary>+ );+});++IdentityDetail.displayName = 'IdentityDetail';++export default IdentityDetail;diff --git a/src/routes/(main)/memory/identities/features/IdentityRightPanel.tsx b/src/routes/(main)/memory/identities/features/IdentityRightPanel.tsxindex 68be08747a8..09d905346b2 100644--- a/src/routes/(main)/memory/identities/features/IdentityRightPanel.tsx+++ b/src/routes/(main)/memory/identities/features/IdentityRightPanel.tsx@@ -1,76 +1,26 @@'use client';-import { Text } from '@lobehub/ui/base-ui';import { memo } from 'react';-import AsyncBoundary from '@/components/AsyncBoundary';import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';import { useQueryState } from '@/hooks/useQueryParam';-import CateTag from '@/routes/(main)/memory/features/CateTag';-import DetailLoading from '@/routes/(main)/memory/features/DetailLoading';-import DetailNotFound from '@/routes/(main)/memory/features/DetailNotFound';import DetailPanel from '@/routes/(main)/memory/features/DetailPanel';-import HashTags from '@/routes/(main)/memory/features/HashTags';-import HighlightedContent from '@/routes/(main)/memory/features/HighlightedContent';-import Time from '@/routes/(main)/memory/features/Time';-import { useUserMemoryStore } from '@/store/userMemory';-import { LayersEnum } from '@/types/userMemory';+import IdentityDetail from './IdentityDetail';import IdentityDropdown from './IdentityDropdown';const IdentityRightPanel = memo(() => {const [identityId] = useQueryState('identityId', { clearOnDefault: true });- const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);-- const {- data: identity,- isLoading,- error,- mutate,- } = useFetchMemoryDetail(identityId, LayersEnum.Identity);if (!identityId) return null;- const content = identity && (- <>- <CateTag cate={identity.type} />- <Text- as={'h1'}- fontSize={20}- weight={'bold'}- style={{- lineHeight: 1.4,- marginBottom: 0,- }}- >- {identity.title}- </Text>- <Time capturedAt={identity.capturedAt || identity.updatedAt || identity.createdAt} />- {identity.description && <HighlightedContent>{identity.description}</HighlightedContent>}- <HashTags hashTags={identity.tags} />- </>- );-return (<DetailPanelheader={{- right: identityId ? (- <IdentityDropdown id={identityId} size={DESKTOP_HEADER_ICON_SIZE} />- ) : undefined,+ right: <IdentityDropdown id={identityId} size={DESKTOP_HEADER_ICON_SIZE} />,}}>- <AsyncBoundary- data={identity}- empty={<DetailNotFound />}- error={error}- errorVariant={'page'}- isEmpty={!identity}- isLoading={isLoading}- loading={<DetailLoading />}- onRetry={() => mutate()}- >- {content}- </AsyncBoundary>+ <IdentityDetail id={identityId} /></DetailPanel>);});diff --git a/src/routes/(main)/memory/preferences/features/PreferenceDetail.tsx b/src/routes/(main)/memory/preferences/features/PreferenceDetail.tsxnew file mode 100644index 00000000000..d86071b8f2b--- /dev/null+++ b/src/routes/(main)/memory/preferences/features/PreferenceDetail.tsx@@ -0,0 +1,111 @@+'use client';++import { Block, Flexbox, Icon } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { BotIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncBoundary from '@/components/AsyncBoundary';+import CateTag from '@/routes/(main)/memory/features/CateTag';+import DetailLoading from '@/routes/(main)/memory/features/DetailLoading';+import DetailNotFound from '@/routes/(main)/memory/features/DetailNotFound';+import HashTags from '@/routes/(main)/memory/features/HashTags';+import HighlightedContent from '@/routes/(main)/memory/features/HighlightedContent';+import ProgressIcon from '@/routes/(main)/memory/features/ProgressIcon';+import SourceLink from '@/routes/(main)/memory/features/SourceLink';+import Time from '@/routes/(main)/memory/features/Time';+import { useUserMemoryStore } from '@/store/userMemory';+import { LayersEnum } from '@/types/userMemory';++const styles = createStaticStyles(({ css, cssVar }) => ({+ suggestionsTitle: css`+ font-size: 12px;+ font-weight: 500;+ color: ${cssVar.colorTextSecondary};+ `,+}));++interface PreferenceDetailProps {+ /** Layer-specific row id (`preferenceId`). */+ id: string;+}++/**+ * The preference memory detail body, shared by the memory page's right panel and the chat Portal.+ */+const PreferenceDetail = memo<PreferenceDetailProps>(({ id: preferenceId }) => {+ const { t } = useTranslation('memory');+ const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);++ const {+ data: preference,+ isLoading,+ error,+ mutate,+ } = useFetchMemoryDetail(preferenceId, LayersEnum.Preference);++ const content = preference && (+ <>+ <CateTag cate={preference.type} />+ <Text+ as={'h1'}+ fontSize={20}+ weight={'bold'}+ style={{+ lineHeight: 1.4,+ marginBottom: 0,+ }}+ >+ {preference.title || preference.type || t('preference.defaultType')}+ </Text>+ <Flexbox horizontal align="center" gap={16} justify="space-between">+ <ProgressIcon+ showInfo+ format={(percent) => `${t('filter.sort.scorePriority')}: ${percent}%`}+ percent={(preference.scorePriority ?? 0) * 100}+ />+ </Flexbox>+ <Flexbox horizontal align="center" gap={16} justify="space-between">+ <SourceLink source={preference.source} />+ <Time capturedAt={preference.capturedAt || preference.updatedAt || preference.createdAt} />+ </Flexbox>++ {preference.conclusionDirectives && (+ <HighlightedContent>{preference.conclusionDirectives}</HighlightedContent>+ )}++ {preference.suggestions && (+ <Block gap={8} padding={16} variant={'filled'}>+ <Flexbox horizontal align={'center'} className={styles.suggestionsTitle} gap={6}>+ <Icon icon={BotIcon} size={16} />+ <span>{t('preference.suggestions')}</span>+ </Flexbox>+ <HighlightedContent>{preference.suggestions}</HighlightedContent>+ </Block>+ )}++ <HashTags hashTags={preference.tags} />+ </>+ );++ return (+ <AsyncBoundary+ data={preference}+ empty={<DetailNotFound />}+ error={error}+ errorVariant={'page'}+ isEmpty={!preference}+ isLoading={isLoading}+ loading={<DetailLoading />}+ onRetry={() => mutate()}+ >+ {content}+ </AsyncBoundary>+ );+});++PreferenceDetail.displayName = 'PreferenceDetail';++export default PreferenceDetail;diff --git a/src/routes/(main)/memory/preferences/features/PreferenceRightPanel.tsx b/src/routes/(main)/memory/preferences/features/PreferenceRightPanel.tsxindex 98d2eea32a3..05aceb6ef5d 100644--- a/src/routes/(main)/memory/preferences/features/PreferenceRightPanel.tsx+++ b/src/routes/(main)/memory/preferences/features/PreferenceRightPanel.tsx@@ -1,115 +1,26 @@'use client';-import { Block, Flexbox, Icon } from '@lobehub/ui';-import { Text } from '@lobehub/ui/base-ui';-import { createStaticStyles } from 'antd-style';-import { BotIcon } from 'lucide-react';import { memo } from 'react';-import { useTranslation } from 'react-i18next';-import AsyncBoundary from '@/components/AsyncBoundary';import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';import { useQueryState } from '@/hooks/useQueryParam';-import CateTag from '@/routes/(main)/memory/features/CateTag';-import DetailLoading from '@/routes/(main)/memory/features/DetailLoading';-import DetailNotFound from '@/routes/(main)/memory/features/DetailNotFound';import DetailPanel from '@/routes/(main)/memory/features/DetailPanel';-import HashTags from '@/routes/(main)/memory/features/HashTags';-import HighlightedContent from '@/routes/(main)/memory/features/HighlightedContent';-import ProgressIcon from '@/routes/(main)/memory/features/ProgressIcon';-import SourceLink from '@/routes/(main)/memory/features/SourceLink';-import Time from '@/routes/(main)/memory/features/Time';-import { useUserMemoryStore } from '@/store/userMemory';-import { LayersEnum } from '@/types/userMemory';+import PreferenceDetail from './PreferenceDetail';import PreferenceDropdown from './PreferenceDropdown';-const styles = createStaticStyles(({ css, cssVar }) => ({- suggestionsTitle: css`- font-size: 12px;- font-weight: 500;- color: ${cssVar.colorTextSecondary};- `,-}));-const PreferenceRightPanel = memo(() => {- const { t } = useTranslation('memory');const [preferenceId] = useQueryState('preferenceId', { clearOnDefault: true });- const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);-- const {- data: preference,- isLoading,- error,- mutate,- } = useFetchMemoryDetail(preferenceId, LayersEnum.Preference);if (!preferenceId) return null;- const content = preference && (- <>- <CateTag cate={preference.type} />- <Text- as={'h1'}- fontSize={20}- weight={'bold'}- style={{- lineHeight: 1.4,- marginBottom: 0,- }}- >- {preference.title || preference.type || t('preference.defaultType')}- </Text>- <Flexbox horizontal align="center" gap={16} justify="space-between">- <ProgressIcon- showInfo- format={(percent) => `${t('filter.sort.scorePriority')}: ${percent}%`}- percent={(preference.scorePriority ?? 0) * 100}- />- </Flexbox>- <Flexbox horizontal align="center" gap={16} justify="space-between">- <SourceLink source={preference.source} />- <Time capturedAt={preference.capturedAt || preference.updatedAt || preference.createdAt} />- </Flexbox>-- {preference.conclusionDirectives && (- <HighlightedContent>{preference.conclusionDirectives}</HighlightedContent>- )}-- {preference.suggestions && (- <Block gap={8} padding={16} variant={'filled'}>- <Flexbox horizontal align={'center'} className={styles.suggestionsTitle} gap={6}>- <Icon icon={BotIcon} size={16} />- <span>{t('preference.suggestions')}</span>- </Flexbox>- <HighlightedContent>{preference.suggestions}</HighlightedContent>- </Block>- )}-- <HashTags hashTags={preference.tags} />- </>- );-return (<DetailPanelheader={{- right: preferenceId ? (- <PreferenceDropdown id={preferenceId} size={DESKTOP_HEADER_ICON_SIZE} />- ) : undefined,+ right: <PreferenceDropdown id={preferenceId} size={DESKTOP_HEADER_ICON_SIZE} />,}}>- <AsyncBoundary- data={preference}- empty={<DetailNotFound />}- error={error}- errorVariant={'page'}- isEmpty={!preference}- isLoading={isLoading}- loading={<DetailLoading />}- onRetry={() => mutate()}- >- {content}- </AsyncBoundary>+ <PreferenceDetail id={preferenceId} /></DetailPanel>);});diff --git a/src/services/agentSignal.ts b/src/services/agentSignal.tsindex cd710c3570a..f6900aa2c96 100644--- a/src/services/agentSignal.ts+++ b/src/services/agentSignal.ts@@ -20,8 +20,10 @@ export interface ListAgentSignalReceiptsParams {export interface RollbackAgentSignalReceiptParams {agentDocumentId?: string;- documentId: string;- historyId: string;+ /** Skill receipts only. */+ documentId?: string;+ /** Skill receipts only. */+ historyId?: string;receiptId: string;}diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge.test.tsindex 834f8a76bac..dd73d35c337 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge.test.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge.test.ts@@ -17,7 +17,7 @@ vi.mock('@/store/chat/store', () => ({describe('emitClientAgentSignalSourceEvent', () => {beforeEach(() => {vi.clearAllMocks();-+ // The retired rollout flag may still sit in a cached server config; it must not decide.vi.stubGlobal('window', {global_serverConfigStore: {getState: () => ({@@ -35,6 +35,7 @@ describe('emitClientAgentSignalSourceEvent', () => {vi.mocked(getUserStoreState).mockReturnValue({isUserStateInit: true,+ preference: { lab: { enableSelfLearning: true } },} as never);await emitClientAgentSignalSourceEvent({@@ -75,6 +76,7 @@ describe('emitClientAgentSignalSourceEvent', () => {vi.mocked(getUserStoreState).mockReturnValue({isUserStateInit: true,+ preference: { lab: { enableSelfLearning: true } },} as never);await emitClientAgentSignalSourceEvent({@@ -110,21 +112,14 @@ describe('emitClientAgentSignalSourceEvent', () => {});});- it('skips emitting when the rollout feature flag is disabled after server config init', async () => {+ it('skips emitting once the user state says Labs Self-evolving is off', async () => {const { agentSignalService } = await import('@/services/agentSignal');const { getUserStoreState } = await import('@/store/user/store');const { emitClientAgentSignalSourceEvent } = await import('./agentSignalBridge');- vi.stubGlobal('window', {- global_serverConfigStore: {- getState: () => ({- featureFlags: { enableAgentSelfIteration: false },- serverConfigInit: true,- }),- },- });vi.mocked(getUserStoreState).mockReturnValue({isUserStateInit: true,+ preference: { lab: { enableSelfLearning: false } },} as never);await emitClientAgentSignalSourceEvent({@@ -142,13 +137,14 @@ describe('emitClientAgentSignalSourceEvent', () => {expect(agentSignalService.emitClientGatewaySourceEvent).not.toHaveBeenCalled();});- it('emits when the feature flag is enabled and user state is initialized', async () => {+ it('emits when Labs Self-evolving is on and user state is initialized', async () => {const { agentSignalService } = await import('@/services/agentSignal');const { getUserStoreState } = await import('@/store/user/store');const { emitClientAgentSignalSourceEvent } = await import('./agentSignalBridge');vi.mocked(getUserStoreState).mockReturnValue({isUserStateInit: true,+ preference: { lab: { enableSelfLearning: true } },} as never);await emitClientAgentSignalSourceEvent({@@ -171,14 +167,6 @@ describe('emitClientAgentSignalSourceEvent', () => {const { getUserStoreState } = await import('@/store/user/store');const { emitClientAgentSignalSourceEvent } = await import('./agentSignalBridge');- vi.stubGlobal('window', {- global_serverConfigStore: {- getState: () => ({- featureFlags: { enableAgentSelfIteration: false },- serverConfigInit: false,- }),- },- });vi.mocked(getUserStoreState).mockReturnValue({isUserStateInit: false,} as never);diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge.ts b/src/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge.tsindex 62eba03bafe..e03365d0b57 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge.ts@@ -4,6 +4,8 @@ import type {} from '@lobechat/agent-signal/source';import { agentSignalService } from '@/services/agentSignal';+import { labPreferSelectors } from '@/store/user/selectors';+import { getUserStoreState } from '@/store/user/store';type ClientAgentSignalSourceType = Extract<AgentSignalSourceType, `client.${string}`>;@@ -22,15 +24,14 @@ const createSourceId = (sourceType: string, timestamp: number) => {return `${sourceType}:${timestamp}:${Math.random().toString(36).slice(2, 10)}`;};+/**+ * Skips the round trip once the user state says Labs → Self-evolving is off. Before the user+ * state loads, the event is sent and the server gate decides.+ */const shouldEmitClientAgentSignalSourceEvent = () => {- const serverConfigStore =- typeof window === 'undefined' ? undefined : window.global_serverConfigStore;- const serverConfigState = serverConfigStore?.getState();+ const userState = getUserStoreState();- if (- serverConfigState?.serverConfigInit &&- serverConfigState.featureFlags.enableAgentSelfIteration !== true- ) {+ if (userState?.isUserStateInit && !labPreferSelectors.enableSelfLearning(userState)) {return false;}diff --git a/src/store/chat/slices/portal/action.test.ts b/src/store/chat/slices/portal/action.test.tsindex 4cafcb612c3..c650daf4997 100644--- a/src/store/chat/slices/portal/action.test.ts+++ b/src/store/chat/slices/portal/action.test.ts@@ -1,3 +1,4 @@+import { LayersEnum } from '@lobechat/types';import { act, renderHook } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';@@ -465,6 +466,26 @@ describe('chatDockSlice', () => {});});+ describe('openMemoryDetail', () => {+ it('should push MemoryDetail view and expose it through the selector', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.openMemoryDetail({ id: 'preference-1', layer: LayersEnum.Preference });+ });++ expect(result.current.portalStack).toEqual([+ { id: 'preference-1', layer: LayersEnum.Preference, type: PortalViewType.MemoryDetail },+ ]);+ expect(result.current.showPortal).toBe(true);+ expect(chatPortalSelectors.memoryDetailView(result.current)).toEqual({+ id: 'preference-1',+ layer: LayersEnum.Preference,+ type: PortalViewType.MemoryDetail,+ });+ });+ });+describe('goal drill-down', () => {it('preserves experiment history and returns to an already visited node without cycles', () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.tsindex 3db02e5a1e7..71993893af1 100644--- a/src/store/chat/slices/portal/action.ts+++ b/src/store/chat/slices/portal/action.ts@@ -1,4 +1,4 @@-import type { TopicCommentItem } from '@lobechat/types';+import type { LayersEnum, TopicCommentItem } from '@lobechat/types';import { projectFileService } from '@/services/projectFile';import { type ChatStore } from '@/store/chat/store';@@ -513,6 +513,10 @@ export class ChatPortalActionImpl {this.#get().pushPortalView({ agentDocumentId, documentId, type: PortalViewType.Document });};+ openMemoryDetail = (params: { id: string; layer: LayersEnum }): void => {+ this.#get().pushPortalView({ ...params, type: PortalViewType.MemoryDetail });+ };+openFilePreview = (file: PortalFile): void => {this.#get().pushPortalView({ file, type: PortalViewType.FilePreview });};diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.tsindex 8844097b74f..b1036d5d57b 100644--- a/src/store/chat/slices/portal/initialState.ts+++ b/src/store/chat/slices/portal/initialState.ts@@ -1,4 +1,4 @@-import type { TopicCommentItem } from '@lobechat/types';+import type { LayersEnum, TopicCommentItem } from '@lobechat/types';import { type PortalArtifact } from '@/types/artifact';@@ -25,6 +25,7 @@ export enum PortalViewType {GroupThread = 'groupThread',Home = 'home',LocalFile = 'localFile',+ MemoryDetail = 'memoryDetail',MessageDetail = 'messageDetail',Notebook = 'notebook',TaskDetail = 'taskDetail',@@ -103,6 +104,8 @@ export type PortalViewData =| { type: PortalViewType.Notebook }| { file: PortalFile; type: PortalViewType.FilePreview }| { type: PortalViewType.LocalFile }+ /** `id` is the layer-specific row id (e.g. a preference id), not the base memory id. */+ | { id: string; layer: LayersEnum; type: PortalViewType.MemoryDetail }| { messageId: string; type: PortalViewType.MessageDetail }| {identifier: string;diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.tsindex b9e321443e6..6ea80d2af44 100644--- a/src/store/chat/slices/portal/selectors.ts+++ b/src/store/chat/slices/portal/selectors.ts@@ -81,6 +81,8 @@ const agentDetailId = (s: ChatStoreState): string | undefined => {return view?.agentId;};+const memoryDetailView = (s: ChatStoreState) => getViewData(s, PortalViewType.MemoryDetail);+// Artifact selectorsconst currentArtifact = (s: ChatStoreState): PortalArtifact | undefined => {const view = getViewData(s, PortalViewType.Artifact);@@ -374,6 +376,9 @@ export const chatPortalSelectors = {localFileWorkingDirectory,openLocalFiles,+ // Memory detail data+ memoryDetailView,+// Message detail datamessageDetailId,diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex a8b30d3ddb2..d3b50604e37 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -27,7 +27,6 @@ export enum ChatSettingsTabs {Opening = 'opening',Plugin = 'plugin',Prompt = 'prompt',- SelfIteration = 'selfIteration',}export enum GroupSettingsTabs {