Skip to content

🤯 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.

✨ feat(agent-signal): add receipt revert (#16423)

Nekofc4e6b333449
diff --git a/apps/server/src/routers/lambda/agentSignal.test.ts b/apps/server/src/routers/lambda/agentSignal.test.ts
index 29395abc5dc..9afc767ecfc 100644
--- a/apps/server/src/routers/lambda/agentSignal.test.ts
+++ b/apps/server/src/routers/lambda/agentSignal.test.ts
@@ -5,12 +5,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createCallerFactory } from '@/libs/trpc/lambda';
import { type AuthContext } from '@/libs/trpc/lambda/context';
import { createContextInner } from '@/libs/trpc/lambda/context';
+import { rollbackAgentSignalReceipt } from '@/server/services/agentSignal/services/receiptRollbackService';
import { listAgentSignalReceipts } from '@/server/services/agentSignal/services/receiptService';
import { agentSignalRouter } from './agentSignal';
+const mockServerDB = vi.hoisted(() => ({}));
+
vi.mock('@/database/core/db-adaptor', () => ({
- getServerDB: vi.fn().mockResolvedValue({}),
+ getServerDB: vi.fn().mockResolvedValue(mockServerDB),
}));
vi.mock('@/server/services/agentSignal', () => ({
@@ -41,6 +44,16 @@ vi.mock('@/server/services/agentSignal/services/receiptService', () => ({
}),
}));
+vi.mock('@/server/services/agentSignal/services/receiptRollbackService', () => ({
+ rollbackAgentSignalReceipt: vi.fn().mockResolvedValue({
+ agentDocumentId: 'adoc-1',
+ documentId: 'doc-1',
+ historyId: 'history-1',
+ receiptId: 'receipt-1',
+ status: 'rolled_back',
+ }),
+}));
+
const createCaller = createCallerFactory(agentSignalRouter);
describe('agentSignalRouter', () => {
@@ -49,7 +62,7 @@ describe('agentSignalRouter', () => {
beforeEach(async () => {
vi.clearAllMocks();
- ctx = await createContextInner({ userId: 'user-1' });
+ ctx = await createContextInner({ userId: 'user-1', workspaceId: 'workspace-1' });
router = createCaller(ctx);
});
@@ -113,4 +126,35 @@ describe('agentSignalRouter', () => {
userId: 'user-1',
});
});
+
+ it('rolls back a receipt for the current user workspace', async () => {
+ await expect(
+ router.rollbackReceipt({
+ agentDocumentId: 'adoc-1',
+ documentId: 'doc-1',
+ historyId: 'history-1',
+ receiptId: 'receipt-1',
+ }),
+ ).resolves.toEqual({
+ agentDocumentId: 'adoc-1',
+ documentId: 'doc-1',
+ historyId: 'history-1',
+ receiptId: 'receipt-1',
+ status: 'rolled_back',
+ });
+
+ expect(rollbackAgentSignalReceipt).toHaveBeenCalledWith(
+ {
+ agentDocumentId: 'adoc-1',
+ documentId: 'doc-1',
+ historyId: 'history-1',
+ receiptId: 'receipt-1',
+ },
+ {
+ db: mockServerDB,
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ },
+ );
+ });
});
diff --git a/apps/server/src/routers/lambda/agentSignal.ts b/apps/server/src/routers/lambda/agentSignal.ts
index cb2d51760b9..d781c0dbec6 100644
--- a/apps/server/src/routers/lambda/agentSignal.ts
+++ b/apps/server/src/routers/lambda/agentSignal.ts
@@ -8,7 +8,9 @@ import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
import { router } from '@/libs/trpc/lambda';
+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 {
AGENT_SIGNAL_TRIGGER_SOURCE_TYPES,
@@ -19,6 +21,10 @@ const log = debug('lobe-server:agent-signal:router');
const agentSignalProcedure = wsCompatProcedure;
const agentSignalWriteProcedure = agentSignalProcedure.use(withScopedPermission('message:create'));
+const agentSignalAgentWriteProcedure = agentSignalProcedure.use(
+ withScopedPermission('agent:update'),
+);
+const agentSignalAgentDatabaseWriteProcedure = agentSignalAgentWriteProcedure.use(serverDatabase);
const clientSourceTypes = AGENT_SIGNAL_CLIENT_SOURCE_TYPES;
type ClientSourceType = (typeof clientSourceTypes)[number];
@@ -108,4 +114,20 @@ export const agentSignalRouter = router({
userId: ctx.userId,
});
}),
+ rollbackReceipt: agentSignalAgentDatabaseWriteProcedure
+ .input(
+ z.object({
+ agentDocumentId: z.string().min(1).optional(),
+ documentId: z.string().min(1),
+ historyId: z.string().min(1),
+ receiptId: z.string().min(1),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ return rollbackAgentSignalReceipt(input, {
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ }),
});
diff --git a/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.ts b/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.ts
new file mode 100644
index 00000000000..7e202f49709
--- /dev/null
+++ b/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.ts
@@ -0,0 +1,187 @@
+import { TRPCError } from '@trpc/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { LobeChatDatabase } from '@/database/type';
+
+import { rollbackAgentSignalReceipt } from '../receiptRollbackService';
+
+const mocks = vi.hoisted(() => ({
+ documentService: {
+ getDocumentById: vi.fn<(id: string) => Promise<unknown>>(),
+ getDocumentHistoryItem: vi.fn<
+ (params: { documentId: string; historyId: string }) => Promise<
+ | {
+ editorData: Record<string, unknown> | null;
+ id: string;
+ }
+ | undefined
+ >
+ >(),
+ runWithDocumentLock: vi.fn(<T>(_id: string, fn: (lockOwnerId?: string) => Promise<T>) =>
+ fn('server:lock-owner'),
+ ),
+ updateDocument: vi.fn<(id: string, params: Record<string, unknown>) => Promise<unknown>>(),
+ },
+ receiptService: {
+ getAgentSignalReceipt:
+ vi.fn<(receiptId: string) => Promise<Record<string, unknown> | undefined>>(),
+ updateAgentSignalReceiptMetadata:
+ vi.fn<(receiptId: string, metadata: Record<string, unknown>) => Promise<unknown>>(),
+ },
+}));
+
+vi.mock('@/server/services/document', () => ({
+ DocumentService: vi.fn(() => mocks.documentService),
+}));
+
+vi.mock('@/server/services/agentSignal/services/receiptService', () => ({
+ getAgentSignalReceipt: mocks.receiptService.getAgentSignalReceipt,
+ updateAgentSignalReceiptMetadata: mocks.receiptService.updateAgentSignalReceiptMetadata,
+}));
+
+const db = {} as LobeChatDatabase;
+const baseInput = {
+ agentDocumentId: 'adoc-1',
+ documentId: 'doc-1',
+ historyId: 'history-1',
+ receiptId: 'receipt-1',
+};
+
+describe('rollbackAgentSignalReceipt', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.documentService.runWithDocumentLock.mockImplementation(
+ <T>(_id: string, fn: (lockOwnerId?: string) => Promise<T>) => fn('server:lock-owner'),
+ );
+ mocks.receiptService.getAgentSignalReceipt.mockResolvedValue({
+ id: 'receipt-1',
+ metadata: {
+ documentId: 'doc-1',
+ expectedCurrentDocumentUpdatedAt: '2026-06-29T00:00:00.000Z',
+ historyId: 'history-1',
+ rollbackStatus: 'available',
+ },
+ });
+ });
+
+ /**
+ * @example
+ * A missing current document returns not_found without trying to update anything.
+ */
+ it('returns not_found when the target document is missing', async () => {
+ mocks.documentService.getDocumentById.mockResolvedValue(undefined);
+
+ const result = await rollbackAgentSignalReceipt(baseInput, { db, userId: 'user-1' });
+
+ expect(result).toEqual({
+ agentDocumentId: 'adoc-1',
+ documentId: 'doc-1',
+ historyId: 'history-1',
+ receiptId: 'receipt-1',
+ status: 'not_found',
+ });
+ expect(mocks.documentService.updateDocument).not.toHaveBeenCalled();
+ expect(mocks.receiptService.updateAgentSignalReceiptMetadata).toHaveBeenCalledWith(
+ 'receipt-1',
+ expect.objectContaining({ rollbackStatus: 'not_found' }),
+ );
+ });
+
+ /**
+ * @example
+ * A valid history restore writes the prior editor snapshot back to the document.
+ */
+ it('restores the document from the captured history item', async () => {
+ const editorData = { root: { children: [], type: 'root' } };
+ mocks.documentService.getDocumentById.mockResolvedValue({
+ id: 'doc-1',
+ updatedAt: new Date('2026-06-29T00:00:00.000Z'),
+ });
+ mocks.documentService.getDocumentHistoryItem.mockResolvedValue({
+ editorData,
+ id: 'history-1',
+ });
+
+ const result = await rollbackAgentSignalReceipt(baseInput, {
+ db,
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ });
+
+ expect(result.status).toBe('rolled_back');
+ expect(mocks.documentService.runWithDocumentLock).toHaveBeenCalledWith(
+ 'doc-1',
+ expect.any(Function),
+ );
+ expect(mocks.documentService.getDocumentHistoryItem).toHaveBeenCalledWith({
+ documentId: 'doc-1',
+ historyId: 'history-1',
+ });
+ expect(mocks.documentService.updateDocument).toHaveBeenCalledWith('doc-1', {
+ editorData,
+ lockOwnerId: 'server:lock-owner',
+ restoreFromHistoryId: 'history-1',
+ saveSource: 'restore',
+ });
+ expect(mocks.receiptService.updateAgentSignalReceiptMetadata).toHaveBeenCalledWith(
+ 'receipt-1',
+ expect.objectContaining({ rollbackStatus: 'rolled_back' }),
+ );
+ });
+
+ /**
+ * @example
+ * A collaborative lock conflict returns conflict so the receipt can stop offering undo.
+ */
+ it('returns conflict when the document lock rejects the restore', async () => {
+ mocks.documentService.runWithDocumentLock.mockRejectedValue(
+ new TRPCError({ code: 'CONFLICT', message: 'Document is being edited by another user' }),
+ );
+
+ const result = await rollbackAgentSignalReceipt(baseInput, {
+ db,
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ });
+
+ expect(result).toEqual({
+ agentDocumentId: 'adoc-1',
+ documentId: 'doc-1',
+ historyId: 'history-1',
+ receiptId: 'receipt-1',
+ reason: 'Document is being edited by another user',
+ status: 'conflict',
+ });
+ });
+
+ /**
+ * @example
+ * A stale receipt whose expected document marker no longer matches returns conflict and does not overwrite later edits.
+ */
+ it('returns conflict when the document changed after the receipt was created', async () => {
+ mocks.documentService.getDocumentById.mockResolvedValue({
+ id: 'doc-1',
+ updatedAt: new Date('2026-06-29T01:00:00.000Z'),
+ });
+
+ const result = await rollbackAgentSignalReceipt(baseInput, {
+ db,
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ });
+
+ expect(result).toEqual({
+ agentDocumentId: 'adoc-1',
+ documentId: 'doc-1',
+ historyId: 'history-1',
+ receiptId: 'receipt-1',
+ reason: 'Document changed since this receipt was created',
+ status: 'conflict',
+ });
+ expect(mocks.documentService.updateDocument).not.toHaveBeenCalled();
+ expect(mocks.receiptService.updateAgentSignalReceiptMetadata).toHaveBeenCalledWith(
+ 'receipt-1',
+ expect.objectContaining({ rollbackStatus: 'conflict' }),
+ );
+ });
+});
diff --git a/apps/server/src/services/agentSignal/services/receiptRollbackService.ts b/apps/server/src/services/agentSignal/services/receiptRollbackService.ts
new file mode 100644
index 00000000000..85e33ae50af
--- /dev/null
+++ b/apps/server/src/services/agentSignal/services/receiptRollbackService.ts
@@ -0,0 +1,200 @@
+import { TRPCError } from '@trpc/server';
+
+import type { LobeChatDatabase } from '@/database/type';
+import {
+ getAgentSignalReceipt,
+ updateAgentSignalReceiptMetadata,
+} from '@/server/services/agentSignal/services/receiptService';
+import { DocumentService } from '@/server/services/document';
+
+type RollbackTerminalStatus = 'conflict' | 'failed' | 'not_found' | 'rolled_back';
+
+/**
+ * Input required to rollback one skill-refine receipt.
+ */
+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;
+ /** Receipt whose metadata should be updated with the terminal rollback status. */
+ receiptId: string;
+}
+
+/**
+ * Runtime context for Agent Signal receipt rollback.
+ */
+export interface AgentSignalReceiptRollbackContext {
+ /** Database handle used by the document service. */
+ db: LobeChatDatabase;
+ /** Owner user id for scoped document access. */
+ userId: string;
+ /** Optional workspace scope for collaborative documents. */
+ workspaceId?: string;
+}
+
+/**
+ * Stable rollback result returned to the router and UI.
+ */
+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;
+ /** Human-readable reason for non-success terminal states. */
+ reason?: string;
+ /** Requested receipt id. */
+ receiptId: string;
+ /** Terminal rollback result status. */
+ status: RollbackTerminalStatus;
+}
+
+const toResult = (
+ input: RollbackAgentSignalReceiptInput,
+ status: RollbackTerminalStatus,
+ reason?: string,
+): AgentSignalReceiptRollbackResult => ({
+ ...(input.agentDocumentId ? { agentDocumentId: input.agentDocumentId } : {}),
+ documentId: input.documentId,
+ historyId: input.historyId,
+ receiptId: input.receiptId,
+ ...(reason ? { reason } : {}),
+ status,
+});
+
+const toIsoString = (value: Date | string | undefined) => {
+ if (!value) return undefined;
+
+ return value instanceof Date ? value.toISOString() : value;
+};
+
+const persistRollbackStatus = async (
+ input: RollbackAgentSignalReceiptInput,
+ status: RollbackTerminalStatus,
+) => {
+ try {
+ const receipt = await getAgentSignalReceipt(input.receiptId);
+ if (!receipt) return;
+
+ await updateAgentSignalReceiptMetadata(input.receiptId, {
+ ...receipt.metadata,
+ rollbackStatus: status,
+ });
+ } catch (error) {
+ console.error('[AgentSignal] Failed to persist rollback receipt status:', {
+ error,
+ receiptId: input.receiptId,
+ status,
+ });
+ }
+};
+
+/**
+ * Restores a skill-refine receipt from the existing document history timeline.
+ *
+ * Use when:
+ * - A self-iteration receipt exposes `documentId` + `historyId` for undo.
+ *
+ * Expects:
+ * - The target history row belongs to the same backing document.
+ *
+ * Returns:
+ * - One stable terminal rollback status for the receipt UI.
+ */
+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) {
+ return toResult(input, 'not_found', 'Receipt not found');
+ }
+
+ const expectedCurrentDocumentUpdatedAt = receipt.metadata?.expectedCurrentDocumentUpdatedAt;
+ const resolvedInput: RollbackAgentSignalReceiptInput = {
+ ...input,
+ ...(receipt.metadata?.agentDocumentId
+ ? { agentDocumentId: receipt.metadata.agentDocumentId }
+ : {}),
+ ...(receipt.metadata?.documentId ? { documentId: receipt.metadata.documentId } : {}),
+ ...(receipt.metadata?.historyId ? { historyId: receipt.metadata.historyId } : {}),
+ };
+
+ 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');
+ }
+
+ 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;
+ }
+ })();
+
+ if (!history?.editorData) {
+ await persistRollbackStatus(resolvedInput, 'not_found');
+ return toResult(resolvedInput, 'not_found', 'Document history not found');
+ }
+
+ await documentService.updateDocument(resolvedInput.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');
+ return toResult(resolvedInput, 'conflict', error.message);
+ }
+
+ await persistRollbackStatus(resolvedInput, 'failed');
+ return toResult(
+ resolvedInput,
+ 'failed',
+ error instanceof Error ? error.message : 'Rollback failed',
+ );
+ }
+};
diff --git a/apps/server/src/services/agentSignal/services/receiptService.ts b/apps/server/src/services/agentSignal/services/receiptService.ts
index 1f936b84e9e..54179a9d11e 100644
--- a/apps/server/src/services/agentSignal/services/receiptService.ts
+++ b/apps/server/src/services/agentSignal/services/receiptService.ts
@@ -24,12 +24,28 @@ export interface AgentSignalReceiptMetadata {
actionStatus?: ActionStatus;
/** Agent Signal action type for action receipts. */
actionType?: ActionType;
+ /** Agent document binding id used when reopening or auditing a rolled-back skill refinement. */
+ agentDocumentId?: string;
+ /** Backing document id used by the rollback endpoint. */
+ documentId?: string;
/** Evidence refs used by the reviewer/planner. */
evidenceRefs?: EvidenceRef[];
+ /** Current-document timestamp the rollback expects to still be present before restoring history. */
+ expectedCurrentDocumentUpdatedAt?: string;
+ /** Document history id captured immediately before the skill refinement. */
+ historyId?: string;
/** User-local date for nightly receipts. */
localDate?: string;
/** SelfIteration review scope that produced the receipt. */
reviewScope?: Scope;
+ /** Rollback availability/status for the linked mutation. */
+ rollbackStatus?:
+ | 'available'
+ | 'conflict'
+ | 'failed'
+ | 'not_found'
+ | 'rolled_back'
+ | 'unsupported';
/** Scoped self-reflection id for non-nightly review receipts. */
scopeId?: string;
/** Scoped self-reflection namespace for non-nightly review receipts. */
@@ -140,8 +156,17 @@ export interface AgentSignalReceiptListResult {
/** Storage contract for user-visible Agent Signal receipt history. */
export interface AgentSignalReceiptStore {
+ /** Persists a new receipt payload into the recent-history store. */
appendReceipt: (receipt: AgentSignalReceipt, ttlSeconds: number) => Promise<boolean>;
+ /** Reads one persisted receipt payload by id when the store supports direct lookup. */
+ getReceipt?: (receiptId: string) => Promise<AgentSignalReceipt | undefined>;
+ /** Lists recent receipts for one scoped topic surface. */
listReceipts: (input: AgentSignalReceiptListInput) => Promise<AgentSignalReceiptListResult>;
+ /** Rewrites the persisted metadata envelope for one receipt when the store supports in-place updates. */
+ updateReceiptMetadata?: (
+ receiptId: string,
+ metadata: AgentSignalReceiptMetadata,
+ ) => Promise<AgentSignalReceipt | undefined>;
}
interface ProjectAgentSignalReceiptsInput {
@@ -615,3 +640,44 @@ export const listAgentSignalReceipts = async (
) => {
return (options.store ?? redisReceiptStore).listReceipts(input);
};
+
+/**
+ * Reads one persisted Agent Signal receipt by id.
+ *
+ * Use when:
+ * - A server-side flow needs receipt metadata for a follow-up mutation
+ * - A rollback path must validate the original target before restoring history
+ *
+ * Expects:
+ * - The configured receipt store supports direct receipt lookup
+ *
+ * Returns:
+ * - The persisted receipt payload, or `undefined` when unavailable
+ */
+export const getAgentSignalReceipt = async (
+ receiptId: string,
+ options: { store?: AgentSignalReceiptStore } = {},
+) => {
+ return (options.store ?? redisReceiptStore).getReceipt?.(receiptId);
+};
+
+/**
+ * Rewrites one persisted Agent Signal receipt metadata envelope.
+ *
+ * Use when:
+ * - A follow-up operation reaches a terminal state that should survive refresh
+ * - The UI should stop offering stale actions like rollback/undo
+ *
+ * Expects:
+ * - The configured receipt store supports metadata updates
+ *
+ * Returns:
+ * - The updated receipt payload, or `undefined` when the store cannot update it
+ */
+export const updateAgentSignalReceiptMetadata = async (
+ receiptId: string,
+ metadata: AgentSignalReceiptMetadata,
+ options: { store?: AgentSignalReceiptStore } = {},
+) => {
+ return (options.store ?? redisReceiptStore).updateReceiptMetadata?.(receiptId, metadata);
+};
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.ts
index 911637c8897..e05ac5d0006 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
@@ -51,7 +51,11 @@ describe('buildSelfIterationReceipts', () => {
mutations: [
{
apiName: 'writeMemory',
- data: { kind: 'mutation', resourceId: 'mem_1', summary: 'Saved tone preference' },
+ data: {
+ kind: 'mutation',
+ resourceId: 'mem_1',
+ summary: 'Saved tone preference',
+ },
kind: 'mutation',
toolCallId: 'call_1',
},
@@ -62,6 +66,10 @@ describe('buildSelfIterationReceipts', () => {
expect(memory.status).toBe('applied');
expect(memory.id).toBe(`${marker.sourceId}:call_1:memory`);
expect(memory.title).toBe('Saved tone preference');
+ expect(memory.metadata).toEqual({
+ localDate: '2026-05-30',
+ sourceType: 'agent.execution.completed',
+ });
expect(memory.target).toEqual({
id: 'mem_1',
summary: 'Saved tone preference',
@@ -139,6 +147,115 @@ describe('buildSelfIterationReceipts', () => {
expect(skill.kind).toBe('skill');
expect(skill.status).toBe('skipped');
+ expect(skill.metadata?.rollbackStatus).toBeUndefined();
+ });
+
+ it('does not mark skill creation rollback available without a mutation id', () => {
+ const [, skill] = buildSelfIterationReceipts({
+ ...baseInput,
+ mutations: [
+ {
+ apiName: 'createSkillIfAbsent',
+ data: {
+ resourceId: 'adoc_created',
+ summary: 'Created support skill',
+ target: {
+ agentDocumentId: 'adoc_created',
+ documentId: 'doc_created',
+ id: 'adoc_created',
+ title: 'Support skill',
+ type: 'skill',
+ },
+ },
+ kind: 'mutation',
+ toolCallId: 'call_create_skill',
+ },
+ ],
+ });
+
+ expect(skill.kind).toBe('skill');
+ expect(skill.status).toBe('applied');
+ expect(skill.metadata).toEqual({
+ localDate: '2026-05-30',
+ sourceType: 'agent.execution.completed',
+ });
+ });
+
+ it('does not mark skill creation rollback available when only resource metadata exists', () => {
+ const [, skill] = buildSelfIterationReceipts({
+ ...baseInput,
+ mutations: [
+ {
+ apiName: 'createSkillIfAbsent',
+ data: {
+ resourceId: 'adoc_created',
+ summary: 'Created support skill',
+ target: {
+ agentDocumentId: 'adoc_created',
+ documentId: 'doc_created',
+ id: 'adoc_created',
+ title: 'Support skill',
+ type: 'skill',
+ },
+ },
+ kind: 'mutation',
+ toolCallId: 'call_create_skill_with_mutation',
+ },
+ ],
+ });
+
+ expect(skill.kind).toBe('skill');
+ expect(skill.metadata).toEqual({
+ localDate: '2026-05-30',
+ sourceType: 'agent.execution.completed',
+ });
+ });
+
+ it('projects a skill rollback history ref and target document refs into an applied skill receipt', () => {
+ const [, skill] = buildSelfIterationReceipts({
+ ...baseInput,
+ mutations: [
+ {
+ apiName: 'replaceSkillContentCAS',
+ data: {
+ agentDocumentId: 'adoc_1',
+ documentId: 'doc_1',
+ expectedCurrentDocumentUpdatedAt: '2026-06-29T00:00:00.000Z',
+ historyId: 'history_1',
+ resourceId: 'adoc_1',
+ summary: 'Refined support skill',
+ target: {
+ agentDocumentId: 'adoc_1',
+ documentId: 'doc_1',
+ id: 'adoc_1',
+ title: 'Support skill',
+ type: 'skill',
+ },
+ },
+ kind: 'mutation',
+ toolCallId: 'call_skill',
+ },
+ ],
+ });
+
+ expect(skill.kind).toBe('skill');
+ expect(skill.metadata).toEqual({
+ agentDocumentId: 'adoc_1',
+ documentId: 'doc_1',
+ expectedCurrentDocumentUpdatedAt: '2026-06-29T00:00:00.000Z',
+ historyId: 'history_1',
+ localDate: '2026-05-30',
+ rollbackStatus: 'available',
+ sourceType: 'agent.execution.completed',
+ });
+ expect(skill.target).toEqual({
+ agentDocumentId: 'adoc_1',
+ documentId: 'doc_1',
+ id: 'adoc_1',
+ summary: 'Refined support skill',
+ title: 'Support skill',
+ type: 'skill',
+ });
});
it('is idempotent: re-projecting the same run yields the same receipt ids', () => {
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts b/apps/server/src/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts
index f1ddaf93445..51fe8e5f1a0 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts
@@ -45,6 +45,8 @@ const DEFAULT_TITLE_BY_API: Record<string, string> = {
writeMemory: 'Memory saved',
};
+const ROLLBACK_CAPABLE_APIS = new Set(['replaceSkillContentCAS']);
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -158,13 +160,25 @@ export const buildSelfIterationReceipts = (
const target = isRecord(data.target) ? data.target : undefined;
const targetId = str(target?.id) ?? str(data.resourceId);
+ const agentDocumentId = kind === 'skill' ? str(target?.agentDocumentId) : undefined;
+ const documentId = kind === 'skill' ? str(target?.documentId) : undefined;
const memoryId = kind === 'memory' ? str(target?.memoryId) : undefined;
const memoryLayer =
kind === 'memory' && isMemoryLayer(target?.memoryLayer) ? target.memoryLayer : undefined;
+ const rollbackAgentDocumentId = str(data.agentDocumentId);
+ const rollbackDocumentId = str(data.documentId);
+ const rollbackExpectedCurrentDocumentUpdatedAt = str(data.expectedCurrentDocumentUpdatedAt);
+ const rollbackHistoryId = str(data.historyId);
const summaryText = str(data.summary);
const targetTitle = str(target?.title);
const title =
targetTitle ?? summaryText ?? DEFAULT_TITLE_BY_API[apiName] ?? 'Agent Signal action';
+ const rollbackAvailable =
+ rollbackDocumentId &&
+ rollbackExpectedCurrentDocumentUpdatedAt &&
+ rollbackHistoryId &&
+ status === 'applied' &&
+ ROLLBACK_CAPABLE_APIS.has(apiName);
return [
{
@@ -174,7 +188,14 @@ export const buildSelfIterationReceipts = (
id: `${sourceId}:${mutation.toolCallId ?? `${apiName}:${index}`}:${kind}`,
kind,
metadata: {
+ ...(rollbackAgentDocumentId ? { agentDocumentId: rollbackAgentDocumentId } : {}),
+ ...(rollbackDocumentId ? { documentId: rollbackDocumentId } : {}),
+ ...(rollbackExpectedCurrentDocumentUpdatedAt
+ ? { expectedCurrentDocumentUpdatedAt: rollbackExpectedCurrentDocumentUpdatedAt }
+ : {}),
+ ...(rollbackHistoryId ? { historyId: rollbackHistoryId } : {}),
...(marker.localDate ? { localDate: marker.localDate } : {}),
+ ...(rollbackAvailable ? { rollbackStatus: 'available' as const } : {}),
sourceType,
},
status,
@@ -183,6 +204,8 @@ export const buildSelfIterationReceipts = (
? {}
: {
target: {
+ ...(agentDocumentId ? { agentDocumentId } : {}),
+ ...(documentId ? { documentId } : {}),
...(targetId ? { id: targetId } : {}),
...(memoryId ? { memoryId } : {}),
...(memoryLayer ? { memoryLayer } : {}),
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/tools/__test__/runtimePrimitives.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/tools/__test__/runtimePrimitives.test.ts
new file mode 100644
index 00000000000..ed95a3f801e
--- /dev/null
+++ b/apps/server/src/services/agentSignal/services/selfIteration/tools/__test__/runtimePrimitives.test.ts
@@ -0,0 +1,185 @@
+import { LayersEnum } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { LobeChatDatabase } from '@/database/type';
+import type { SkillManagementDocumentService } from '@/server/services/skillManagement';
+
+import { createResourceRuntimePrimitives } from '../runtimePrimitives';
+import type {
+ CreateSkillIfAbsentInput,
+ ReplaceSkillContentCASInput,
+ WriteMemoryInput,
+} from '../shared';
+
+const mocks = vi.hoisted(() => ({
+ runMemoryActionAgent: vi.fn(),
+}));
+
+vi.mock('@/server/services/agentSignal/policies/analyzeIntent/actions/userMemory', () => ({
+ runMemoryActionAgent: mocks.runMemoryActionAgent,
+}));
+
+interface TestResourceRuntime {
+ createSkillIfAbsent: (input: CreateSkillIfAbsentInput) => Promise<{
+ resourceId?: string;
+ summary?: string;
+ }>;
+ replaceSkillContentCAS: (input: ReplaceSkillContentCASInput) => Promise<{
+ agentDocumentId?: string;
+ documentId?: string;
+ historyId?: string;
+ resourceId?: string;
+ summary?: string;
+ }>;
+ writeMemory: (input: WriteMemoryInput) => Promise<{
+ resourceId?: string;
+ summary?: string;
+ }>;
+}
+
+const createSkillDocumentService = (
+ overrides: Partial<SkillManagementDocumentService> = {},
+): SkillManagementDocumentService =>
+ ({
+ createSkill: vi.fn().mockResolvedValue({
+ bundle: {
+ agentDocumentId: 'adoc_created',
+ documentId: 'doc_bundle_created',
+ },
+ index: {
+ agentDocumentId: 'adoc_index_created',
+ documentId: 'doc_index_created',
+ },
+ name: 'support-skill',
+ title: 'Support Skill',
+ }),
+ getSkill: vi.fn(),
+ listSkills: vi.fn().mockResolvedValue([]),
+ readSkillTargetSnapshot: vi.fn(),
+ replaceSkillIndex: vi.fn().mockResolvedValue({
+ bundle: {
+ agentDocumentId: 'adoc_1',
+ documentId: 'doc_bundle_1',
+ },
+ index: {
+ agentDocumentId: 'adoc_index_1',
+ documentId: 'doc_index_1',
+ },
+ name: 'support-skill',
+ preMutationHistoryId: 'history_1',
+ title: 'Support Skill',
+ }),
+ ...overrides,
+ }) as unknown as SkillManagementDocumentService;
+
+describe('createResourceRuntimePrimitives', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('preserves writeMemory target metadata without creating rollback mutations', async () => {
+ mocks.runMemoryActionAgent.mockResolvedValue({
+ detail: 'Saved tone preference',
+ status: 'applied',
+ target: {
+ id: 'pref_1',
+ memoryId: 'mem_1',
+ memoryLayer: LayersEnum.Preference,
+ summary: 'Use concise implementation notes.',
+ title: 'Prefers concise implementation notes',
+ type: 'memory',
+ },
+ });
+ const service = createResourceRuntimePrimitives({
+ agentId: 'agent_1',
+ db: {} as LobeChatDatabase,
+ memoryReason: (count) => `reason ${count}`,
+ operationId: 'op_1',
+ sourceId: 'source_1',
+ skillDocumentService: createSkillDocumentService(),
+ topicId: 'topic_1',
+ userId: 'user_1',
+ workspaceId: 'workspace_1',
+ }) as unknown as TestResourceRuntime;
+
+ const result = await service.writeMemory({
+ content: 'Prefers concise notes.',
+ evidenceRefs: [],
+ idempotencyKey: 'mem_key_1',
+ userId: 'user_1',
+ });
+
+ expect(result).toEqual({
+ resourceId: 'pref_1',
+ summary: 'Saved tone preference',
+ target: {
+ id: 'pref_1',
+ memoryId: 'mem_1',
+ memoryLayer: LayersEnum.Preference,
+ summary: 'Use concise implementation notes.',
+ title: 'Prefers concise implementation notes',
+ type: 'memory',
+ },
+ });
+ });
+
+ it('does not create rollback metadata for skill creation', async () => {
+ const service = createResourceRuntimePrimitives({
+ agentId: 'agent_1',
+ db: {} as LobeChatDatabase,
+ memoryReason: (count) => `reason ${count}`,
+ operationId: 'op_1',
+ sourceId: 'source_1',
+ skillDocumentService: createSkillDocumentService(),
+ topicId: 'topic_1',
+ userId: 'user_1',
+ workspaceId: 'workspace_1',
+ }) as unknown as TestResourceRuntime;
+
+ const result = await service.createSkillIfAbsent({
+ bodyMarkdown: 'Use concise support steps.',
+ idempotencyKey: 'skill_create_1',
+ name: 'support-skill',
+ userId: 'user_1',
+ });
+
+ expect(result.resourceId).toBe('adoc_created');
+ });
+
+ it('returns replaceSkillContentCAS rollback refs from document history', async () => {
+ const readSkillTargetSnapshot = vi.fn().mockResolvedValue({
+ agentDocumentId: 'adoc_1',
+ contentHash: 'sha256:before',
+ documentId: 'doc_bundle_1',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ });
+ const service = createResourceRuntimePrimitives({
+ agentId: 'agent_1',
+ db: {} as LobeChatDatabase,
+ memoryReason: (count) => `reason ${count}`,
+ operationId: 'op_1',
+ sourceId: 'source_1',
+ skillDocumentService: createSkillDocumentService({ readSkillTargetSnapshot }),
+ topicId: 'topic_1',
+ userId: 'user_1',
+ workspaceId: 'workspace_1',
+ }) as unknown as TestResourceRuntime;
+
+ const result = await service.replaceSkillContentCAS({
+ bodyMarkdown: 'Updated skill body.',
+ idempotencyKey: 'skill_replace_1',
+ skillDocumentId: 'adoc_1',
+ userId: 'user_1',
+ });
+
+ expect(result).toMatchObject({
+ agentDocumentId: 'adoc_1',
+ documentId: 'doc_index_1',
+ historyId: 'history_1',
+ resourceId: 'adoc_1',
+ summary: 'Refined managed skill support-skill.',
+ });
+ });
+});
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/tools/runtimePrimitives.ts b/apps/server/src/services/agentSignal/services/selfIteration/tools/runtimePrimitives.ts
index 59890faaffd..0c4d0e8dace 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/tools/runtimePrimitives.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/tools/runtimePrimitives.ts
@@ -19,7 +19,13 @@ export interface ResourceRuntimePrimitiveDeps {
db: LobeChatDatabase;
/** Builds the memory-candidate reason; lets each mode tag its origin. */
memoryReason: (evidenceCount: number) => string;
+ /** Agent runtime operation id, when the tool context exposes it. */
+ operationId?: string;
skillDocumentService: SkillManagementDocumentService;
+ /** Agent Signal source id that started the self-iteration run. */
+ sourceId?: string;
+ /** Topic id associated with the tool execution, when available. */
+ topicId?: string;
userId: string;
/** Workspace id, so memory-write operations target the correct workspace. */
workspaceId?: string;
@@ -79,6 +85,13 @@ export const createResourceRuntimePrimitives = ({
return {
skillDocumentId: result.bundle.agentDocumentId,
summary: `Created managed skill ${result.name}.`,
+ target: {
+ agentDocumentId: result.bundle.agentDocumentId,
+ documentId: result.bundle.documentId,
+ id: result.bundle.agentDocumentId,
+ title: result.title,
+ type: 'skill',
+ },
};
},
refineSkill: async ({ input }) => {
@@ -91,8 +104,19 @@ export const createResourceRuntimePrimitives = ({
if (!result) throw new Error('Skill target not found');
return {
+ agentDocumentId: result.bundle.agentDocumentId,
+ documentId: result.index.documentId,
+ expectedCurrentDocumentUpdatedAt: result.expectedCurrentDocumentUpdatedAt,
+ historyId: result.preMutationHistoryId,
skillDocumentId: result.bundle.agentDocumentId,
summary: `Refined managed skill ${result.name}.`,
+ target: {
+ agentDocumentId: result.bundle.agentDocumentId,
+ documentId: result.bundle.documentId,
+ id: result.bundle.agentDocumentId,
+ title: result.title,
+ type: 'skill',
+ },
};
},
});
@@ -106,7 +130,17 @@ export const createResourceRuntimePrimitives = ({
input,
});
- return { resourceId: result.skillDocumentId, summary: result.summary };
+ return {
+ resourceId: result.skillDocumentId,
+ summary: result.summary,
+ target: result.target,
+ ...(result.agentDocumentId ? { agentDocumentId: result.agentDocumentId } : {}),
+ ...(result.documentId ? { documentId: result.documentId } : {}),
+ ...(result.expectedCurrentDocumentUpdatedAt
+ ? { expectedCurrentDocumentUpdatedAt: result.expectedCurrentDocumentUpdatedAt }
+ : {}),
+ ...(result.historyId ? { historyId: result.historyId } : {}),
+ };
},
getManagedSkill: async (rawInput) => {
const { agentId: targetAgentId, skillDocumentId } = rawInput as {
@@ -173,12 +207,19 @@ export const createResourceRuntimePrimitives = ({
input: enriched,
});
- return { resourceId: result.skillDocumentId, summary: result.summary };
+ return {
+ resourceId: result.skillDocumentId,
+ summary: result.summary,
+ target: result.target,
+ ...(result.agentDocumentId ? { agentDocumentId: result.agentDocumentId } : {}),
+ ...(result.documentId ? { documentId: result.documentId } : {}),
+ ...(result.historyId ? { historyId: result.historyId } : {}),
+ };
},
writeMemory: async (rawInput) => {
const input = rawInput as unknown as WriteMemoryInput;
const memoryService = createMemoryService({
- writeMemory: async ({ content, evidenceRefs, idempotencyKey }) => {
+ writeMemory: async ({ content, evidenceRefs }) => {
const result = await runMemoryActionAgent(
{ agentId, message: content, reason: memoryReason(evidenceRefs.length) },
{ db, userId, workspaceId },
@@ -190,7 +231,20 @@ export const createResourceRuntimePrimitives = ({
);
}
- return { memoryId: idempotencyKey, summary: result.detail ?? content };
+ return {
+ memoryId: result.target?.memoryId ?? result.target?.id,
+ summary: result.detail ?? result.target?.summary ?? content,
+ target: result.target
+ ? {
+ id: result.target.id,
+ memoryId: result.target.memoryId,
+ memoryLayer: result.target.memoryLayer,
+ summary: result.target.summary ?? result.detail,
+ title: result.target.title,
+ type: 'memory',
+ }
+ : undefined,
+ };
},
});
const result = await memoryService.writeMemory({
@@ -199,7 +253,11 @@ export const createResourceRuntimePrimitives = ({
input: { content: input.content, userId: input.userId },
});
- return { resourceId: result.memoryId, summary: result.summary };
+ return {
+ resourceId: result.target?.id ?? result.memoryId,
+ summary: result.summary,
+ target: result.target,
+ };
},
};
};
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/tools/shared.ts b/apps/server/src/services/agentSignal/services/selfIteration/tools/shared.ts
index 6473bd8c8d4..aa745cc2e41 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/tools/shared.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/tools/shared.ts
@@ -1,5 +1,6 @@
import { SpanStatusCode } from '@lobechat/observability-otel/api';
import { tracer } from '@lobechat/observability-otel/modules/agent-signal';
+import type { LayersEnum } from '@lobechat/types';
import type { SelfReviewProposalBaseSnapshot } from '../review/proposal';
import type { EvidenceRef } from '../types';
@@ -37,9 +38,11 @@ export interface MemoryWriteRequest {
/** Result returned after a memory write adapter applies a candidate. */
export interface MemoryWriteResult {
/** Durable memory id. */
- memoryId: string;
+ memoryId?: string;
/** Optional short persistence summary. */
summary?: string;
+ /** Snapshot of the memory target returned by the memory writer. */
+ target?: ToolWriteResult['target'];
}
/** Persistence adapter for memory writes. */
@@ -102,6 +105,8 @@ export interface SkillCreateInput extends SkillBaseInput {
/** Input for refining an existing managed skill. */
export interface SkillRefineInput extends SkillBaseInput {
+ /** Complete target snapshot captured before replacement for mutation logging. */
+ baseSnapshot?: SelfReviewProposalBaseSnapshot;
/** Full replacement Markdown body without YAML frontmatter. */
bodyMarkdown?: string;
/** Human-readable proposal patch text, not executable replacement content. */
@@ -177,10 +182,20 @@ export interface SkillConsolidateRequest {
/** Result returned by skill adapters. */
export interface SkillResult {
+ /** Agent document binding id used by skill-refine rollback receipts. */
+ agentDocumentId?: string;
+ /** Backing document id used by skill-refine rollback receipts. */
+ documentId?: string;
+ /** Expected post-refine document timestamp used to keep Undo from overwriting later edits. */
+ expectedCurrentDocumentUpdatedAt?: string;
+ /** Pre-mutation document history id used by skill-refine rollback receipts. */
+ historyId?: string;
/** Affected writable managed skill document id. */
skillDocumentId: string;
/** Optional short persistence summary. */
summary?: string;
+ /** Snapshot of the managed skill target touched by the adapter. */
+ target?: ToolWriteResult['target'];
}
/** Persistence adapters for managed skill operations. */
@@ -305,6 +320,14 @@ export type ToolWriteStatus =
/** Public result returned by safe write tools. */
export interface ToolWriteResult {
+ /** Agent document binding id used by skill-refine rollback receipts. */
+ agentDocumentId?: string;
+ /** Backing document id used by skill-refine rollback receipts. */
+ documentId?: string;
+ /** Post-mutation current-document marker used to reject stale rollback attempts. */
+ expectedCurrentDocumentUpdatedAt?: string;
+ /** Pre-mutation document history id used by skill-refine rollback receipts. */
+ historyId?: string;
/** Receipt written for the terminal tool outcome. */
receiptId?: string;
/** Resource touched or considered by the tool. */
@@ -313,6 +336,25 @@ export interface ToolWriteResult {
status: ToolWriteStatus;
/** Bounded human-readable tool result. */
summary?: string;
+ /** Snapshot of the resource target touched by the write. */
+ target?: {
+ /** Agent-document binding id for managed skill targets. */
+ agentDocumentId?: string;
+ /** Backing document id for document-backed targets. */
+ documentId?: string;
+ /** Stable resource id for receipt projection. */
+ id?: string;
+ /** User memory base id for memory targets. */
+ memoryId?: string;
+ /** User memory layer used for layer-specific navigation. */
+ memoryLayer?: LayersEnum;
+ /** Short persisted summary. */
+ summary?: string;
+ /** Human-readable target title. */
+ title?: string;
+ /** Target resource domain. */
+ type?: 'memory' | 'skill';
+ };
}
/** Successful preflight result for an existing-resource write targeting an existing resource. */
@@ -444,10 +486,20 @@ export interface CloseSelfReviewProposalInput extends ToolWriteInput {
/** Result returned by mutation adapters before receipt persistence. */
export interface ToolMutationResult {
+ /** Agent document binding id used by skill-refine rollback receipts. */
+ agentDocumentId?: string;
+ /** Backing document id used by skill-refine rollback receipts. */
+ documentId?: string;
+ /** Post-mutation current-document marker used to reject stale rollback attempts. */
+ expectedCurrentDocumentUpdatedAt?: string;
+ /** Pre-mutation document history id used by skill-refine rollback receipts. */
+ historyId?: string;
/** Resource created or updated by the adapter. */
resourceId?: string;
/** Short adapter summary. */
summary?: string;
+ /** Snapshot of the resource target touched by the adapter. */
+ target?: ToolWriteResult['target'];
}
/** Receipt write request emitted after every terminal write outcome. */
@@ -733,9 +785,13 @@ const runWriteTool = async <TInput extends ToolWriteInput>({
if (!reservation.reserved) {
return {
+ agentDocumentId: reservation.existing.agentDocumentId,
+ documentId: reservation.existing.documentId,
+ historyId: reservation.existing.historyId,
resourceId: reservation.existing.resourceId,
status: 'deduped',
summary: reservation.existing.summary,
+ target: reservation.existing.target,
};
}
@@ -775,9 +831,14 @@ const runWriteTool = async <TInput extends ToolWriteInput>({
const mutationResult = await mutate();
return {
+ agentDocumentId: mutationResult.agentDocumentId,
+ documentId: mutationResult.documentId,
+ expectedCurrentDocumentUpdatedAt: mutationResult.expectedCurrentDocumentUpdatedAt,
+ historyId: mutationResult.historyId,
resourceId: mutationResult.resourceId ?? resourceId,
status: successStatus,
summary: mutationResult.summary ?? input.summary,
+ target: mutationResult.target,
};
} catch (error) {
recordConvertedException(error);
diff --git a/apps/server/src/services/agentSignal/store/__tests__/redisReceiptStore.test.ts b/apps/server/src/services/agentSignal/store/__tests__/redisReceiptStore.test.ts
index 8087c3403d3..32088a39db7 100644
--- a/apps/server/src/services/agentSignal/store/__tests__/redisReceiptStore.test.ts
+++ b/apps/server/src/services/agentSignal/store/__tests__/redisReceiptStore.test.ts
@@ -165,6 +165,42 @@ describe('redis receipt store', () => {
});
});
+ it('updates persisted receipt metadata so refetches reuse the terminal rollback status', async () => {
+ const store = await loadStore();
+
+ await store.appendReceipt(
+ {
+ ...receipt,
+ id: 'receipt-skill-rollback-1',
+ kind: 'skill',
+ metadata: {
+ documentId: 'doc-1',
+ expectedCurrentDocumentUpdatedAt: '2026-06-29T00:00:00.000Z',
+ historyId: 'history-1',
+ rollbackStatus: 'available',
+ },
+ status: 'updated',
+ },
+ 259_200,
+ );
+
+ await store.updateReceiptMetadata?.('receipt-skill-rollback-1', {
+ documentId: 'doc-1',
+ expectedCurrentDocumentUpdatedAt: '2026-06-29T00:00:00.000Z',
+ historyId: 'history-1',
+ rollbackStatus: 'rolled_back',
+ });
+
+ await expect(store.getReceipt?.('receipt-skill-rollback-1')).resolves.toMatchObject({
+ metadata: {
+ documentId: 'doc-1',
+ expectedCurrentDocumentUpdatedAt: '2026-06-29T00:00:00.000Z',
+ historyId: 'history-1',
+ rollbackStatus: 'rolled_back',
+ },
+ });
+ });
+
it('lists receipts created after a known timestamp for refresh polling', async () => {
const store = await loadStore();
diff --git a/apps/server/src/services/agentSignal/store/adapters/redis/receiptStore.ts b/apps/server/src/services/agentSignal/store/adapters/redis/receiptStore.ts
index 2e5bcb6396d..2ef3da9eba5 100644
--- a/apps/server/src/services/agentSignal/store/adapters/redis/receiptStore.ts
+++ b/apps/server/src/services/agentSignal/store/adapters/redis/receiptStore.ts
@@ -1,7 +1,10 @@
import { LayersEnum } from '@lobechat/types';
-import { AGENT_SIGNAL_KEYS } from '../../../constants';
-import type { AgentSignalReceipt } from '../../../services/receiptService';
+import { AGENT_SIGNAL_DEFAULTS, AGENT_SIGNAL_KEYS } from '../../../constants';
+import type {
+ AgentSignalReceipt,
+ AgentSignalReceiptMetadata,
+} from '../../../services/receiptService';
import type { AgentSignalReceiptStore } from '../../types';
import { getRedisClient, readHash, trySetNx, writeHash } from './shared';
@@ -119,6 +122,17 @@ const fromReceiptHash = (payload: Record<string, string>): AgentSignalReceipt |
};
};
+const readReceipt = async (receiptId: string): Promise<AgentSignalReceipt | undefined> => {
+ try {
+ const payload = await readHash(AGENT_SIGNAL_KEYS.receipt(receiptId));
+
+ return payload ? fromReceiptHash(payload) : undefined;
+ } catch (error) {
+ console.error('[AgentSignal] Failed to read receipt payload:', { error, receiptId });
+ return undefined;
+ }
+};
+
/** Appends one deduped receipt payload and its scoped topic index entry. */
export const appendReceipt: AgentSignalReceiptStore['appendReceipt'] = async (
receipt,
@@ -140,6 +154,59 @@ export const appendReceipt: AgentSignalReceiptStore['appendReceipt'] = async (
return true;
};
+/**
+ * Reads one persisted receipt payload by id.
+ *
+ * Use when:
+ * - A server-side follow-up needs the original receipt metadata
+ * - The rollback flow must validate one specific stored receipt
+ *
+ * Expects:
+ * - The receipt payload still exists in Redis
+ *
+ * Returns:
+ * - The parsed receipt, or `undefined` when it is missing or unreadable
+ */
+export const getReceipt: NonNullable<AgentSignalReceiptStore['getReceipt']> = async (receiptId) => {
+ return readReceipt(receiptId);
+};
+
+/**
+ * Updates the metadata envelope for one persisted receipt payload.
+ *
+ * Use when:
+ * - A follow-up server action needs to persist a new terminal receipt status
+ * - The UI should reflect the stored receipt state after refresh or remount
+ *
+ * Expects:
+ * - The target receipt still exists in Redis
+ *
+ * Returns:
+ * - The updated receipt payload, or `undefined` when the receipt no longer exists
+ */
+export const updateReceiptMetadata: NonNullable<
+ AgentSignalReceiptStore['updateReceiptMetadata']
+> = async (receiptId, metadata) => {
+ const redis = getRedisClient();
+ if (!redis) return undefined;
+
+ const existing = await readReceipt(receiptId);
+ if (!existing) return undefined;
+
+ const nextMetadata: AgentSignalReceiptMetadata | undefined =
+ Object.keys(metadata).length > 0 ? metadata : undefined;
+
+ await writeHash(
+ AGENT_SIGNAL_KEYS.receipt(receiptId),
+ nextMetadata ? { metadata: JSON.stringify(nextMetadata) } : { metadata: '' },
+ AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds,
+ );
+
+ return nextMetadata
+ ? { ...existing, metadata: nextMetadata }
+ : { ...existing, metadata: undefined };
+};
+
/**
* Lists newest receipts from one scoped topic index and prunes expired payload references.
*/
@@ -200,5 +267,7 @@ export const listReceipts: AgentSignalReceiptStore['listReceipts'] = async (inpu
/** Redis-backed Agent Signal receipt store. */
export const redisReceiptStore: AgentSignalReceiptStore = {
appendReceipt,
+ getReceipt,
listReceipts,
+ updateReceiptMetadata,
};
diff --git a/apps/server/src/services/document/__tests__/index.test.ts b/apps/server/src/services/document/__tests__/index.test.ts
index f651bb3c08b..42d61e994b8 100644
--- a/apps/server/src/services/document/__tests__/index.test.ts
+++ b/apps/server/src/services/document/__tests__/index.test.ts
@@ -110,7 +110,7 @@ describe('DocumentService', () => {
mockDocumentHistoryService = {
compareDocumentHistoryItems: vi.fn(),
- createHistory: vi.fn(),
+ createHistory: vi.fn().mockResolvedValue({ id: 'history-default', savedAt: new Date() }),
getDocumentHistoryItem: vi.fn(),
listDocumentHistory: vi.fn(),
};
@@ -912,6 +912,23 @@ describe('DocumentService', () => {
);
});
+ it('passes the acquired ownerId into the callback', async () => {
+ const wsService = new DocumentService(mockDb, userId, 'ws-1');
+ vi.spyOn(EditLockService.prototype, 'getActiveLock').mockResolvedValue(undefined);
+ vi.spyOn(EditLockService.prototype, 'acquire').mockResolvedValue({
+ expiresAt: new Date(),
+ holderId: userId,
+ lockedByOther: false,
+ ownerId: 'server-owner',
+ });
+ vi.spyOn(EditLockService.prototype, 'release').mockResolvedValue(true);
+ const fn = vi.fn().mockResolvedValue('written');
+
+ await wsService.runWithDocumentLock('doc-1', fn);
+
+ expect(fn).toHaveBeenCalledWith(expect.stringMatching(/^server:/));
+ });
+
it('rejects when the same user already holds the lease in another edit session', async () => {
const wsService = new DocumentService(mockDb, userId, 'ws-1');
vi.spyOn(EditLockService.prototype, 'getActiveLock').mockResolvedValue({
@@ -1142,7 +1159,10 @@ describe('DocumentService', () => {
describe('saveDocumentHistory', () => {
it('should create a history entry for an existing document', async () => {
mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', editorData: { blocks: [] } });
- mockDocumentHistoryService.createHistory.mockResolvedValue(undefined);
+ mockDocumentHistoryService.createHistory.mockResolvedValue({
+ id: 'history-1',
+ savedAt: new Date(),
+ });
const result = await service.saveDocumentHistory('doc-1', { blocks: [] }, 'llm_call');
@@ -1154,12 +1174,16 @@ describe('DocumentService', () => {
savedAt: expect.any(Date),
}),
);
+ expect(result.historyId).toBe('history-1');
expect(result.savedAt).toBeInstanceOf(Date);
});
it('should create history with diff nodes normalized to their origin content', async () => {
mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', editorData: { blocks: [] } });
- mockDocumentHistoryService.createHistory.mockResolvedValue(undefined);
+ mockDocumentHistoryService.createHistory.mockResolvedValue({
+ id: 'history-1',
+ savedAt: new Date(),
+ });
await service.saveDocumentHistory('doc-1', createEditorDataWithDiffNode(), 'llm_call');
@@ -1229,7 +1253,10 @@ describe('DocumentService', () => {
root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },
};
mockDocumentModel.findById.mockResolvedValue({ editorData, id: 'doc-1' });
- mockDocumentHistoryService.createHistory.mockResolvedValue(undefined);
+ mockDocumentHistoryService.createHistory.mockResolvedValue({
+ id: 'history-1',
+ savedAt: new Date(),
+ });
const result = await service.trySaveCurrentDocumentHistory('doc-1', 'llm_call');
@@ -1241,6 +1268,7 @@ describe('DocumentService', () => {
savedAt: expect.any(Date),
}),
);
+ expect(result?.historyId).toBe('history-1');
expect(result?.savedAt).toBeInstanceOf(Date);
});
@@ -1249,7 +1277,10 @@ describe('DocumentService', () => {
editorData: createEditorDataWithDiffNode(),
id: 'doc-1',
});
- mockDocumentHistoryService.createHistory.mockResolvedValue(undefined);
+ mockDocumentHistoryService.createHistory.mockResolvedValue({
+ id: 'history-1',
+ savedAt: new Date(),
+ });
const result = await service.trySaveCurrentDocumentHistory('doc-1', 'llm_call');
@@ -1260,6 +1291,7 @@ describe('DocumentService', () => {
saveSource: 'llm_call',
}),
);
+ expect(result?.historyId).toBe('history-1');
expect(result?.savedAt).toBeInstanceOf(Date);
});
diff --git a/apps/server/src/services/document/history.ts b/apps/server/src/services/document/history.ts
index 98189f7d94b..088188f83c5 100644
--- a/apps/server/src/services/document/history.ts
+++ b/apps/server/src/services/document/history.ts
@@ -85,20 +85,25 @@ export class DocumentHistoryService {
.set({ editorData: params.editorData, savedAt: params.savedAt })
.where(and(eq(documentHistories.id, latest.id), this.historiesOwnership()));
- return;
+ return { id: latest.id, savedAt: params.savedAt };
}
}
- await this.db.insert(documentHistories).values({
- documentId: params.documentId,
- editorData: params.editorData,
- saveSource: params.saveSource,
- savedAt: params.savedAt,
- userId: this.userId,
- workspaceId: this.workspaceId ?? null,
- });
+ const [history] = await this.db
+ .insert(documentHistories)
+ .values({
+ documentId: params.documentId,
+ editorData: params.editorData,
+ saveSource: params.saveSource,
+ savedAt: params.savedAt,
+ userId: this.userId,
+ workspaceId: this.workspaceId ?? null,
+ })
+ .returning({ id: documentHistories.id });
await this.trimHistoryBySource(params.documentId, params.saveSource);
+
+ return { id: history!.id, savedAt: params.savedAt };
};
compareDocumentHistoryItems = async (
diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.ts
index 404e47e19ad..0302aef1181 100644
--- a/apps/server/src/services/document/index.ts
+++ b/apps/server/src/services/document/index.ts
@@ -309,7 +309,7 @@ export class DocumentService {
* Redis is down the underlying lock degrades to "unlocked" (fail-open), so
* this never blocks a write.
*/
- async runWithDocumentLock<T>(id: string, fn: () => Promise<T>): Promise<T> {
+ async runWithDocumentLock<T>(id: string, fn: (lockOwnerId?: string) => Promise<T>): Promise<T> {
if (!this.workspaceId) {
// Diagnostic: distinguishes "no-op because workspaceId is
// missing at runtime" from "lock actually evaluated".
@@ -348,7 +348,7 @@ export class DocumentService {
}
try {
- return await fn();
+ return await fn(ownerId);
} finally {
// Only release a lease we freshly claimed. When the same user already
// held it, leave their session alive — releasing would briefly flip
@@ -412,14 +412,14 @@ export class DocumentService {
const normalizedEditorData = normalizeEditorDataDiffNodes(editorData);
const savedAt = new Date();
- await this.documentHistoryService.createHistory({
+ const history = await this.documentHistoryService.createHistory({
documentId,
editorData: normalizedEditorData,
saveSource,
savedAt,
});
- return { savedAt };
+ return { historyId: history.id, savedAt };
}
/**
@@ -436,14 +436,14 @@ export class DocumentService {
const normalizedEditorData = normalizeEditorDataDiffNodes(editorData);
const savedAt = new Date();
- await this.documentHistoryService.createHistory({
+ const history = await this.documentHistoryService.createHistory({
documentId,
editorData: normalizedEditorData,
saveSource,
savedAt,
});
- return { savedAt };
+ return { historyId: history.id, savedAt };
} catch (error) {
console.error('[DocumentService] Failed to save current document history:', error);
return undefined;
diff --git a/apps/server/src/services/document/types.ts b/apps/server/src/services/document/types.ts
index b7389187e8b..e6662da7abe 100644
--- a/apps/server/src/services/document/types.ts
+++ b/apps/server/src/services/document/types.ts
@@ -74,6 +74,7 @@ export interface UpdateDocumentResult {
}
export interface SaveDocumentHistoryResult {
+ historyId: string;
savedAt: Date;
}
diff --git a/apps/server/src/services/skillManagement/SkillManagementDocumentService.test.ts b/apps/server/src/services/skillManagement/SkillManagementDocumentService.test.ts
index de96eeff566..cb92075fccc 100644
--- a/apps/server/src/services/skillManagement/SkillManagementDocumentService.test.ts
+++ b/apps/server/src/services/skillManagement/SkillManagementDocumentService.test.ts
@@ -10,6 +10,7 @@ import {
} from '@/database/models/agentDocuments';
import type { AgentDocumentEditorSnapshot } from '../agentDocuments/headlessEditor';
+import type { DocumentService } from '../document';
import {
AGENT_SKILL_TEMPLATE_ID,
SKILL_BUNDLE_FILE_TYPE,
@@ -23,6 +24,7 @@ import { SkillManagementDocumentService } from './SkillManagementDocumentService
import type { SkillAgentDocument } from './types';
const now = new Date('2026-05-02T00:00:00.000Z');
+const backingDocumentUpdatedAt = new Date('2026-05-03T00:00:00.000Z');
const createSnapshot = vi.fn(
async (content: string): Promise<AgentDocumentEditorSnapshot> => ({
@@ -264,7 +266,11 @@ const createAgentDocument = (
const createService = () => {
const agentDocumentModel = new InMemoryAgentDocumentModel();
const documentService = {
- trySaveCurrentDocumentHistory: vi.fn(async () => ({ savedAt: now })),
+ getDocumentById: vi.fn(async () => ({ updatedAt: backingDocumentUpdatedAt })),
+ trySaveCurrentDocumentHistory: vi.fn(async () => ({
+ historyId: 'history-exact-1',
+ savedAt: now,
+ })),
};
const service = new SkillManagementDocumentService(
{
@@ -276,7 +282,10 @@ const createService = () => {
{
agentDocumentModel,
createMarkdownEditorSnapshot: createSnapshot,
- documentService,
+ documentService: documentService as unknown as Pick<
+ DocumentService,
+ 'getDocumentById' | 'trySaveCurrentDocumentHistory'
+ >,
},
);
@@ -477,6 +486,9 @@ describe('SkillManagementDocumentService', () => {
created.index.documentId,
'llm_call',
);
+ expect(detail?.preMutationHistoryId).toBe('history-exact-1');
+ expect(detail?.expectedCurrentDocumentUpdatedAt).toBe(backingDocumentUpdatedAt.toISOString());
+ expect(detail?.expectedCurrentDocumentUpdatedAt).not.toBe(now.toISOString());
expect(detail?.content).toBe(skillContent('researcher', 'Researches docs better', '# Better'));
expect(detail?.frontmatter).toEqual({
description: 'Researches docs better',
diff --git a/apps/server/src/services/skillManagement/SkillManagementDocumentService.ts b/apps/server/src/services/skillManagement/SkillManagementDocumentService.ts
index 9ce8753caf1..d563787943d 100644
--- a/apps/server/src/services/skillManagement/SkillManagementDocumentService.ts
+++ b/apps/server/src/services/skillManagement/SkillManagementDocumentService.ts
@@ -57,7 +57,7 @@ interface SkillManagementDocumentServiceDeps {
/** Markdown-to-editor snapshot projector. */
createMarkdownEditorSnapshot?: (content: string) => Promise<AgentDocumentEditorSnapshot>;
/** Document history service dependency. */
- documentService: Pick<DocumentService, 'trySaveCurrentDocumentHistory'>;
+ documentService: Pick<DocumentService, 'getDocumentById' | 'trySaveCurrentDocumentHistory'>;
}
const createEmptyEditorData = (): Record<string, unknown> => ({
@@ -94,7 +94,10 @@ const buildSkillMetadata = (
export class SkillManagementDocumentService {
private agentDocumentModel: SkillManagementAgentDocumentModel;
private createMarkdownEditorSnapshot: (content: string) => Promise<AgentDocumentEditorSnapshot>;
- private documentService: Pick<DocumentService, 'trySaveCurrentDocumentHistory'>;
+ private documentService: Pick<
+ DocumentService,
+ 'getDocumentById' | 'trySaveCurrentDocumentHistory'
+ >;
constructor(
private db: LobeChatDatabase,
@@ -359,7 +362,10 @@ export class SkillManagementDocumentService {
// Removal condition: only if document history can snapshot Markdown content directly.
const editorSnapshot = await this.createMarkdownEditorSnapshot(normalizedContent);
- await this.documentService.trySaveCurrentDocumentHistory(index.documentId, 'llm_call');
+ const preMutationHistory = await this.documentService.trySaveCurrentDocumentHistory(
+ index.documentId,
+ 'llm_call',
+ );
const updatedBundle =
(await this.agentDocumentModel.updateDocumentIdentity(resolved.id, {
metadata,
@@ -373,8 +379,17 @@ export class SkillManagementDocumentService {
const updated = await this.agentDocumentModel.findById(index.id);
if (!updated) throw new Error(`Skill index disappeared during replace: ${index.id}`);
+ const updatedDocument = await this.documentService.getDocumentById(index.documentId);
- return this.toSkillDetail(updatedBundle, updated, { includeContent: true });
+ return {
+ ...this.toSkillDetail(updatedBundle, updated, { includeContent: true }),
+ ...(updatedDocument?.updatedAt
+ ? { expectedCurrentDocumentUpdatedAt: updatedDocument.updatedAt.toISOString() }
+ : {}),
+ ...(preMutationHistory?.historyId
+ ? { preMutationHistoryId: preMutationHistory.historyId }
+ : {}),
+ };
}
/**
diff --git a/apps/server/src/services/skillManagement/types.ts b/apps/server/src/services/skillManagement/types.ts
index 2ef59e5d784..3263e9083a1 100644
--- a/apps/server/src/services/skillManagement/types.ts
+++ b/apps/server/src/services/skillManagement/types.ts
@@ -48,8 +48,12 @@ export interface SkillSummary {
export interface SkillDetail extends SkillSummary {
/** Raw SKILL.md content when requested by callers. */
content?: string;
+ /** UpdatedAt marker captured from the post-refine backing document for receipt rollback freshness checks. */
+ expectedCurrentDocumentUpdatedAt?: string;
/** Parsed index frontmatter. */
frontmatter: SkillFrontmatter;
+ /** Document history id captured immediately before a mutating skill write. */
+ preMutationHistoryId?: string;
}
/** Current managed skill target snapshot used by proposal merge preflight checks. */
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts
index 22ceb1b4118..38264f4c66d 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts
@@ -204,7 +204,7 @@ const withEditor = async (
// workspace members and rejected (CONFLICT) when someone else is actively
// editing, instead of silently clobbering their work. Read-only invocations
// (persist: false) never write, so they skip the lock.
- const run = async (): Promise<HandlerOutput> => {
+ const run = async (lockOwnerId?: string): Promise<HandlerOutput> => {
const snapshot = await loadSnapshot(documentModel, documentId);
const env = buildEnv(snapshot, documentId);
@@ -254,6 +254,7 @@ const withEditor = async (
await documentService.updateDocument(documentId, {
content: patch.content,
editorData: patch.editorData,
+ ...(lockOwnerId ? { lockOwnerId } : {}),
saveSource: 'llm_call',
title: patch.title,
});
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 4c7563368f7..61c7fef18d9 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -33,6 +33,13 @@
"agentSignal.receipts.memory.detail": "Saved this for future replies",
"agentSignal.receipts.memory.title": "Memory saved",
"agentSignal.receipts.recentActivity": "Recent activity",
+ "agentSignal.receipts.revert.conflict": "Newer version",
+ "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.unsupported": "Unsupported",
"agentSignal.receipts.skill.detail": "Self-refined how this agent handles similar requests",
"agentSignal.receipts.skill.title": "Auto-learned a new skill",
"agents": "Agents",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index bdd8a7f44ef..8a06258dc1e 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -33,6 +33,13 @@
"agentSignal.receipts.memory.detail": "已保存以供未来回复使用",
"agentSignal.receipts.memory.title": "记忆已保存",
"agentSignal.receipts.recentActivity": "最近活动",
+ "agentSignal.receipts.revert.conflict": "已有新版本",
+ "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.unsupported": "不支持撤销",
"agentSignal.receipts.skill.detail": "已自主优化处理相似请求的方式",
"agentSignal.receipts.skill.title": "已自动习得新技能",
"agents": "助理",
@@ -192,21 +199,14 @@
"gatewayMode.cardTitle": "Agent Gateway 模式",
"gatewayMode.desc": "通过 LobeHub 的 Agent Gateway 在云端执行 Agent,即使关闭网页,任务也会继续运行。",
"globalApproval.collapse": "收起",
- "globalApproval.collapse": "收起",
- "globalApproval.goToConversation": "打开会话",
"globalApproval.goToConversation": "打开会话",
"globalApproval.moreCount_one": "还有 {{count}} 个待审批",
"globalApproval.moreCount_other": "还有 {{count}} 个待审批",
"globalApproval.pendingCount_one": "{{count}} 项待审批",
- "globalApproval.pendingCount_one": "{{count}} 项待审批",
- "globalApproval.pendingCount_other": "{{count}} 项待审批",
"globalApproval.pendingCount_other": "{{count}} 项待审批",
"globalApproval.subtitle": "等待你的审批",
- "globalApproval.subtitle": "等待你的审批",
- "globalApproval.title": "需要审批",
"globalApproval.title": "需要审批",
"globalApproval.userRequestLabel": "用户请求",
- "globalApproval.userRequestLabel": "用户请求",
"group.desc": "在同一对话空间,让多个助理一起推进任务",
"group.memberTooltip": "群组内有 {{count}} 名成员",
"group.orchestratorThinking": "主持人思考中…",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 804a13dbb6f..e652de6e16b 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -43,6 +43,13 @@ export default {
'agentSignal.receipts.memory.detail': 'Saved this for future replies',
'agentSignal.receipts.memory.title': 'Memory saved',
'agentSignal.receipts.recentActivity': 'Recent activity',
+ 'agentSignal.receipts.revert.conflict': 'Newer version',
+ '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.unsupported': 'Unsupported',
'agentSignal.receipts.skill.detail': 'Self-refined how this agent handles similar requests',
'agentSignal.receipts.skill.title': 'Auto-learned a new skill',
'agents': 'Agents',
diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx
index 4c016c9b362..83feb6ff7f8 100644
--- a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx
+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx
@@ -1,12 +1,15 @@
import { LayersEnum } from '@lobechat/types';
-import { fireEvent, render, screen } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { agentSignalService } from '@/services/agentSignal';
+
import AgentSignalReceiptList from './AgentSignalReceiptList';
const mocks = vi.hoisted(() => ({
navigate: vi.fn(),
openDocument: vi.fn(),
+ rollbackReceipt: vi.fn(),
}));
vi.mock('@/hooks/useStableNavigate', () => ({
@@ -18,10 +21,17 @@ vi.mock('@/store/chat', () => ({
selector({ openDocument: mocks.openDocument }),
}));
+vi.mock('@/services/agentSignal', () => ({
+ agentSignalService: {
+ rollbackReceipt: mocks.rollbackReceipt,
+ },
+}));
+
describe('AgentSignalReceiptList', () => {
afterEach(() => {
mocks.navigate.mockReset();
mocks.openDocument.mockReset();
+ mocks.rollbackReceipt.mockReset();
});
it('renders visible memory and skill receipts', () => {
@@ -330,4 +340,306 @@ describe('AgentSignalReceiptList', () => {
expect(mocks.navigate).toHaveBeenCalledWith('/memory/preferences?preferenceId=preference-1');
});
+
+ it('shows undo only when skill rollback history metadata exists', () => {
+ render(
+ <AgentSignalReceiptList
+ receipts={[
+ {
+ agentId: 'agent-1',
+ createdAt: 1,
+ detail: 'Improved how this assistant handles similar requests',
+ id: 'receipt-1',
+ kind: 'skill',
+ metadata: {
+ agentDocumentId: 'agent-document-1',
+ documentId: 'document-1',
+ historyId: 'history-1',
+ rollbackStatus: 'available',
+ },
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'updated',
+ target: {
+ id: 'document-1',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ },
+ title: 'Skill updated',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ {
+ agentId: 'agent-1',
+ createdAt: 2,
+ detail: 'Saved this for future replies',
+ id: 'receipt-2',
+ kind: 'memory',
+ metadata: {
+ documentId: 'memory-document-1',
+ historyId: 'history-2',
+ },
+ sourceId: 'source-2',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'applied',
+ target: {
+ title: 'Future reply preference',
+ type: 'memory',
+ },
+ title: 'Memory saved',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ {
+ agentId: 'agent-1',
+ createdAt: 3,
+ detail: 'Improved how this assistant handles similar requests',
+ id: 'receipt-3',
+ kind: 'skill',
+ metadata: {
+ rollbackStatus: 'available',
+ },
+ sourceId: 'source-3',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'updated',
+ target: {
+ id: 'document-3',
+ title: 'Issue triage workflow',
+ type: 'skill',
+ },
+ title: 'Skill updated',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ ]}
+ />,
+ );
+
+ expect(screen.getAllByText('Undo')).toHaveLength(1);
+ });
+
+ it('calls rollback service and updates visible status after undo', async () => {
+ mocks.rollbackReceipt.mockResolvedValueOnce({
+ agentDocumentId: 'agent-document-1',
+ documentId: 'document-1',
+ historyId: 'history-1',
+ status: 'rolled_back',
+ });
+
+ render(
+ <AgentSignalReceiptList
+ receipts={[
+ {
+ agentId: 'agent-1',
+ createdAt: 1,
+ detail: 'Improved how this assistant handles similar requests',
+ id: 'receipt-1',
+ kind: 'skill',
+ metadata: {
+ agentDocumentId: 'agent-document-1',
+ documentId: 'document-1',
+ historyId: 'history-1',
+ rollbackStatus: 'available',
+ },
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'updated',
+ target: {
+ id: 'document-1',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ },
+ title: 'Skill updated',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ ]}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Undo' }));
+
+ await waitFor(() => {
+ expect(agentSignalService.rollbackReceipt).toHaveBeenCalledWith({
+ agentDocumentId: 'agent-document-1',
+ documentId: 'document-1',
+ historyId: 'history-1',
+ receiptId: 'receipt-1',
+ });
+ });
+ expect(mocks.openDocument).not.toHaveBeenCalled();
+ expect(await screen.findByText('Rolled back')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Undo' })).not.toBeInTheDocument();
+ });
+
+ it('ignores duplicate undo clicks while rollback is pending', async () => {
+ let resolveRollback!: (value: {
+ agentDocumentId: string;
+ documentId: string;
+ historyId: string;
+ status: string;
+ }) => void;
+ mocks.rollbackReceipt.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveRollback = resolve;
+ }),
+ );
+
+ render(
+ <AgentSignalReceiptList
+ receipts={[
+ {
+ agentId: 'agent-1',
+ createdAt: 1,
+ detail: 'Improved how this assistant handles similar requests',
+ id: 'receipt-1',
+ kind: 'skill',
+ metadata: {
+ agentDocumentId: 'agent-document-1',
+ documentId: 'document-1',
+ historyId: 'history-1',
+ rollbackStatus: 'available',
+ },
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'updated',
+ target: {
+ id: 'document-1',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ },
+ title: 'Skill updated',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ ]}
+ />,
+ );
+
+ const undo = screen.getByRole('button', { name: 'Undo' });
+ fireEvent.click(undo);
+ fireEvent.click(undo);
+
+ expect(screen.getByText('Rolling back')).toBeInTheDocument();
+ await waitFor(() => {
+ expect(agentSignalService.rollbackReceipt).toHaveBeenCalledTimes(1);
+ });
+ expect(mocks.openDocument).not.toHaveBeenCalled();
+
+ resolveRollback({
+ agentDocumentId: 'agent-document-1',
+ documentId: 'document-1',
+ historyId: 'history-1',
+ status: 'rolled_back',
+ });
+
+ expect(await screen.findByText('Rolled back')).toBeInTheDocument();
+ });
+
+ it('uses the server receipt metadata on remount so refreshed receipts no longer show undo', () => {
+ const availableReceipt = {
+ agentId: 'agent-1',
+ createdAt: 1,
+ detail: 'Improved how this assistant handles similar requests',
+ id: 'receipt-1',
+ kind: 'skill' as const,
+ metadata: {
+ agentDocumentId: 'agent-document-1',
+ documentId: 'document-1',
+ historyId: 'history-1',
+ rollbackStatus: 'available' as const,
+ },
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'updated' as const,
+ target: {
+ id: 'document-1',
+ title: 'GitHub PR review workflow',
+ type: 'skill' as const,
+ },
+ title: 'Skill updated',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ };
+ const rolledBackReceipt = {
+ ...availableReceipt,
+ metadata: {
+ ...availableReceipt.metadata,
+ rollbackStatus: 'rolled_back' as const,
+ },
+ };
+
+ const { rerender } = render(<AgentSignalReceiptList receipts={[availableReceipt]} />);
+
+ expect(screen.getByText('Undo')).toBeInTheDocument();
+
+ rerender(<AgentSignalReceiptList receipts={[rolledBackReceipt]} />);
+
+ expect(screen.queryByText('Undo')).not.toBeInTheDocument();
+ expect(screen.getByText('Rolled back')).toBeInTheDocument();
+ });
+
+ it('shows the not found rollback label from the server status', () => {
+ render(
+ <AgentSignalReceiptList
+ receipts={[
+ {
+ agentId: 'agent-1',
+ createdAt: 1,
+ detail: 'Improved how this assistant handles similar requests',
+ id: 'receipt-1',
+ kind: 'skill',
+ metadata: {
+ documentId: 'document-1',
+ historyId: 'history-1',
+ rollbackStatus: 'not_found',
+ },
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'updated',
+ target: {
+ id: 'document-1',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ },
+ title: 'Skill updated',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ ]}
+ />,
+ );
+
+ expect(screen.getByText('Not found')).toBeInTheDocument();
+ expect(screen.queryByText('Undo')).not.toBeInTheDocument();
+ });
+
+ it('does not show undo for missing rollback metadata', () => {
+ render(
+ <AgentSignalReceiptList
+ receipts={[
+ {
+ agentId: 'agent-1',
+ createdAt: 1,
+ detail: 'Improved how this assistant handles similar requests',
+ id: 'receipt-1',
+ kind: 'skill',
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'updated',
+ target: {
+ id: 'document-1',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ },
+ title: 'Skill updated',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ ]}
+ />,
+ );
+
+ expect(screen.queryByRole('button', { name: 'Undo' })).not.toBeInTheDocument();
+ });
});
diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx
index 7966b81a00d..315e2c25d39 100644
--- a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx
+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx
@@ -6,11 +6,12 @@ import { SkillsIcon } from '@lobehub/ui/icons';
import { createStaticStyles } from 'antd-style';
import type { LucideIcon } from 'lucide-react';
import { Brain, ClipboardCheck } from 'lucide-react';
-import { memo, useCallback } from 'react';
+import { memo, useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import PortalResourceCard from '@/features/Conversation/components/PortalResourceCard';
import { useStableNavigate } from '@/hooks/useStableNavigate';
+import { agentSignalService } from '@/services/agentSignal';
import { useChatStore } from '@/store/chat';
import type { AgentSignalReceiptView } from '../hooks/useAgentSignalReceipts';
@@ -41,6 +42,27 @@ const RECEIPT_LUCIDE_ICON_BY_KIND = {
const LEGACY_PREFERENCE_MEMORY_PATTERN = /\bprefer(?:s|red|ence)?\b|偏好|喜好/i;
+type ReceiptRollbackStatus =
+ | 'already_rolled_back'
+ | 'available'
+ | 'conflict'
+ | 'failed'
+ | 'not_found'
+ | 'pending'
+ | 'rolled_back'
+ | 'unsupported';
+
+const RECEIPT_ROLLBACK_LABEL_BY_STATUS = {
+ already_rolled_back: 'Rolled back',
+ available: 'Undo',
+ conflict: 'Conflict',
+ failed: 'Failed',
+ not_found: 'Not found',
+ pending: 'Rolling back',
+ rolled_back: 'Rolled back',
+ unsupported: 'Unsupported',
+} as const satisfies Record<ReceiptRollbackStatus, string>;
+
const renderReceiptIcon = (kind: AgentSignalReceiptView['kind']) => {
if (kind === 'skill') return <SkillsIcon size={28} />;
const LucideIconComponent = RECEIPT_LUCIDE_ICON_BY_KIND[kind];
@@ -52,7 +74,9 @@ interface AgentSignalReceiptListProps {
}
interface AgentSignalReceiptItemProps {
+ onRollbackStatusChange: (receiptId: string, status: ReceiptRollbackStatus) => void;
receipt: AgentSignalReceiptView;
+ rollbackStatus?: ReceiptRollbackStatus;
}
const getMemoryRoute = (target?: AgentSignalReceiptView['target']) => {
@@ -77,59 +101,142 @@ const getMemoryRoute = (target?: AgentSignalReceiptView['target']) => {
: route.path;
};
-const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(({ receipt }) => {
- const { t } = useTranslation(['chat', 'common']);
- const navigate = useStableNavigate();
- const openDocument = useChatStore((s) => s.openDocument);
- 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;
- 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 handleOpen = useCallback(() => {
- if (memoryRoute) {
- navigate(memoryRoute);
- return;
- }
-
- if (target?.type !== 'skill') return;
- if (!documentId) return;
-
- openDocument(documentId, agentDocumentId);
- }, [agentDocumentId, documentId, memoryRoute, navigate, openDocument, target]);
+const getRollbackStatusLabelKey = (status: ReceiptRollbackStatus) => {
+ if (status === 'available') return 'agentSignal.receipts.revert.undo';
+ if (status === 'already_rolled_back') return 'agentSignal.receipts.revert.rolled_back';
- return (
- <PortalResourceCard
- description={description}
- icon={iconNode}
- openLabel={canOpen ? t('common:cmdk.toOpen', 'Open') : undefined}
- title={title}
- tooltip={tooltip}
- onOpen={canOpen ? handleOpen : undefined}
- />
- );
-});
+ return `agentSignal.receipts.revert.${status}`;
+};
+
+const normalizeRollbackStatus = (status: string): ReceiptRollbackStatus => {
+ if (
+ status === 'already_rolled_back' ||
+ status === 'conflict' ||
+ status === 'not_found' ||
+ status === 'rolled_back' ||
+ status === 'unsupported'
+ ) {
+ return status;
+ }
+
+ return 'failed';
+};
+
+const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(
+ ({ receipt, rollbackStatus, onRollbackStatusChange }) => {
+ const { t } = useTranslation(['chat', 'common']);
+ const navigate = useStableNavigate();
+ const openDocument = useChatStore((s) => s.openDocument);
+ 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;
+ 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 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 handleOpen = useCallback(() => {
+ if (memoryRoute) {
+ navigate(memoryRoute);
+ return;
+ }
+
+ if (target?.type !== 'skill') return;
+ if (!documentId) return;
+
+ openDocument(documentId, agentDocumentId);
+ }, [agentDocumentId, documentId, memoryRoute, navigate, openDocument, target]);
+ const handleRollback = useCallback(async () => {
+ if (!rollbackDocumentId || !rollbackHistoryId || rollbackInFlightRef.current) return;
+
+ rollbackInFlightRef.current = true;
+ onRollbackStatusChange(receipt.id, 'pending');
+ try {
+ const result = await agentSignalService.rollbackReceipt({
+ ...(rollbackAgentDocumentId ? { agentDocumentId: rollbackAgentDocumentId } : {}),
+ documentId: rollbackDocumentId,
+ historyId: rollbackHistoryId,
+ receiptId: receipt.id,
+ });
+ onRollbackStatusChange(receipt.id, normalizeRollbackStatus(result.status));
+ } catch {
+ onRollbackStatusChange(receipt.id, 'failed');
+ } finally {
+ rollbackInFlightRef.current = false;
+ }
+ }, [
+ onRollbackStatusChange,
+ receipt.id,
+ rollbackAgentDocumentId,
+ rollbackDocumentId,
+ rollbackHistoryId,
+ ]);
+ const shouldShowRollbackStatus =
+ effectiveRollbackStatus === 'available' ? canRollback : Boolean(effectiveRollbackStatus);
+ const rollbackLabel =
+ shouldShowRollbackStatus && effectiveRollbackStatus
+ ? t(
+ getRollbackStatusLabelKey(effectiveRollbackStatus),
+ RECEIPT_ROLLBACK_LABEL_BY_STATUS[effectiveRollbackStatus],
+ )
+ : undefined;
+
+ return (
+ <PortalResourceCard
+ description={description}
+ icon={iconNode}
+ openLabel={canOpen ? t('common:cmdk.toOpen', 'Open') : undefined}
+ secondaryActionLabel={rollbackLabel}
+ title={title}
+ tooltip={tooltip}
+ onOpen={canOpen ? handleOpen : undefined}
+ onSecondaryAction={canRollback ? handleRollback : undefined}
+ />
+ );
+ },
+);
AgentSignalReceiptItem.displayName = 'AgentSignalReceiptItem';
const AgentSignalReceiptList = memo<AgentSignalReceiptListProps>(({ receipts }) => {
+ const [rollbackStatuses, setRollbackStatuses] = useState<Record<string, ReceiptRollbackStatus>>(
+ {},
+ );
+ const handleRollbackStatusChange = useCallback(
+ (receiptId: string, status: ReceiptRollbackStatus) => {
+ setRollbackStatuses((current) => ({ ...current, [receiptId]: status }));
+ },
+ [],
+ );
+
if (receipts.length === 0) return null;
// TODO: Migrate this temporary receipt UI into the final Agent Signal feedback surface.
return (
<div className={styles.list}>
{receipts.map((receipt) => (
- <AgentSignalReceiptItem key={receipt.id} receipt={receipt} />
+ <AgentSignalReceiptItem
+ key={receipt.id}
+ receipt={receipt}
+ rollbackStatus={rollbackStatuses[receipt.id]}
+ onRollbackStatusChange={handleRollbackStatusChange}
+ />
))}
</div>
);
diff --git a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts
index 9a76a26c91d..f6c31d7509b 100644
--- a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts
+++ b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts
@@ -198,9 +198,11 @@ const mergeReceiptRefresh = (
) => {
if (newReceipts.length === 0) return currentReceipts;
- const existingIds = new Set(currentReceipts.map((receipt) => receipt.id));
+ const mergedById = new Map(currentReceipts.map((receipt) => [receipt.id, receipt]));
- return [...newReceipts.filter((receipt) => !existingIds.has(receipt.id)), ...currentReceipts]
- .sort((a, b) => b.createdAt - a.createdAt)
- .slice(0, 20);
+ for (const receipt of newReceipts) {
+ mergedById.set(receipt.id, receipt);
+ }
+
+ return [...mergedById.values()].sort((a, b) => b.createdAt - a.createdAt).slice(0, 20);
};
diff --git a/src/features/Conversation/components/PortalResourceCard/index.tsx b/src/features/Conversation/components/PortalResourceCard/index.tsx
index 389f9870f35..1080c65f66c 100644
--- a/src/features/Conversation/components/PortalResourceCard/index.tsx
+++ b/src/features/Conversation/components/PortalResourceCard/index.tsx
@@ -3,7 +3,7 @@
import { Center, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cx } from 'antd-style';
import { FileText } from 'lucide-react';
-import type { KeyboardEvent, ReactNode } from 'react';
+import type { KeyboardEvent, MouseEvent, ReactNode } from 'react';
import { memo } from 'react';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -41,6 +41,30 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
background: ${cssVar.colorBgContainer};
`,
+ actionButton: css`
+ cursor: pointer;
+
+ height: 28px;
+ padding-inline: 12px;
+ border: 1px solid ${cssVar.colorBorder};
+ border-radius: 6px;
+
+ font-size: 13px;
+ line-height: 1;
+ color: ${cssVar.colorText};
+ white-space: nowrap;
+
+ background: ${cssVar.colorBgContainer};
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimary};
+ outline-offset: 2px;
+ }
+ `,
container: css`
overflow: hidden;
@@ -66,6 +90,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
font-weight: 500;
line-height: 1.35;
`,
+ trigger: css`
+ overflow: hidden;
+ min-width: 0;
+ height: 100%;
+ `,
}));
export interface PortalResourceCardProps {
@@ -73,13 +102,27 @@ export interface PortalResourceCardProps {
description?: ReactNode;
icon?: ReactNode;
onOpen?: () => void;
+ onSecondaryAction?: () => void;
openLabel?: ReactNode;
+ secondaryAction?: ReactNode;
+ secondaryActionLabel?: ReactNode;
title: ReactNode;
tooltip?: ReactNode;
}
const PortalResourceCard = memo<PortalResourceCardProps>(
- ({ className, description, icon, openLabel, title, tooltip, onOpen }) => {
+ ({
+ className,
+ description,
+ icon,
+ openLabel,
+ secondaryAction,
+ secondaryActionLabel,
+ title,
+ tooltip,
+ onOpen,
+ onSecondaryAction,
+ }) => {
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (!onOpen) return;
if (event.key !== 'Enter' && event.key !== ' ') return;
@@ -87,36 +130,64 @@ const PortalResourceCard = memo<PortalResourceCardProps>(
event.preventDefault();
onOpen();
};
+ const handleSecondaryActionClick = (event: MouseEvent<HTMLButtonElement>) => {
+ event.stopPropagation();
+ onSecondaryAction?.();
+ };
// Mirrors the inline artifact card shell, while keeping portal-open behavior owned by callers.
const card = (
- <Flexbox
- horizontal
- align={'center'}
- className={cx(styles.container, onOpen && styles.actionable, className)}
- role={onOpen ? 'button' : undefined}
- tabIndex={onOpen ? 0 : undefined}
- onClick={onOpen}
- onKeyDown={onOpen ? handleKeyDown : undefined}
- >
- <Center horizontal className={styles.avatar} width={64}>
- {icon ?? <Icon icon={FileText} size={28} />}
- </Center>
- <Flexbox className={styles.content} flex={1} gap={4} paddingInline={12}>
- <Text ellipsis className={styles.title}>
- {title}
- </Text>
- {description && (
- <Text ellipsis className={styles.desc}>
- {description}
+ <Flexbox horizontal align={'center'} className={cx(styles.container, className)}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={cx(styles.trigger, onOpen && styles.actionable)}
+ flex={1}
+ role={onOpen ? 'button' : undefined}
+ tabIndex={onOpen ? 0 : undefined}
+ onClick={onOpen}
+ onKeyDown={onOpen ? handleKeyDown : undefined}
+ >
+ <Center horizontal className={styles.avatar} width={64}>
+ {icon ?? <Icon icon={FileText} size={28} />}
+ </Center>
+ <Flexbox className={styles.content} flex={1} gap={4} paddingInline={12}>
+ <Text ellipsis className={styles.title}>
+ {title}
</Text>
+ {description && (
+ <Text ellipsis className={styles.desc}>
+ {description}
+ </Text>
+ )}
+ </Flexbox>
+ {onOpen && openLabel && (
+ <Flexbox flex={'none'} style={{ paddingInlineEnd: 10 }}>
+ <div aria-hidden className={styles.openLabel}>
+ {openLabel}
+ </div>
+ </Flexbox>
)}
</Flexbox>
- {onOpen && openLabel && (
+ {(secondaryAction || secondaryActionLabel) && (
<Flexbox flex={'none'} style={{ paddingInlineEnd: 10 }}>
- <div aria-hidden className={styles.openLabel}>
- {openLabel}
- </div>
+ {secondaryAction ?? (
+ <>
+ {onSecondaryAction ? (
+ <button
+ className={styles.actionButton}
+ type={'button'}
+ onClick={handleSecondaryActionClick}
+ >
+ {secondaryActionLabel}
+ </button>
+ ) : (
+ <div aria-hidden className={styles.openLabel}>
+ {secondaryActionLabel}
+ </div>
+ )}
+ </>
+ )}
</Flexbox>
)}
</Flexbox>
diff --git a/src/services/agentSignal.ts b/src/services/agentSignal.ts
index a6ff0365686..cd710c3570a 100644
--- a/src/services/agentSignal.ts
+++ b/src/services/agentSignal.ts
@@ -18,11 +18,22 @@ export interface ListAgentSignalReceiptsParams {
topicId: string;
}
+export interface RollbackAgentSignalReceiptParams {
+ agentDocumentId?: string;
+ documentId: string;
+ historyId: string;
+ receiptId: string;
+}
+
class AgentSignalService {
listReceipts = async (params: ListAgentSignalReceiptsParams) => {
return lambdaClient.agentSignal.listReceipts.query(params);
};
+ rollbackReceipt = async (params: RollbackAgentSignalReceiptParams) => {
+ return lambdaClient.agentSignal.rollbackReceipt.mutate(params);
+ };
+
emitSourceEvent = async (payload: ClientGatewaySourceEventInput<ClientGatewaySourceType>) => {
return lambdaClient.agentSignal.emitSourceEvent.mutate(payload);
};