🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(server): add business slots for thread archive, change request settle and task settle (#23609)
Arvin Xuc1e789dc8054
diff --git a/apps/server/src/services/channel/ChannelService.test.ts b/apps/server/src/services/channel/ChannelService.test.tsindex 4b4456e3649..3eafeb468fb 100644--- a/apps/server/src/services/channel/ChannelService.test.ts+++ b/apps/server/src/services/channel/ChannelService.test.ts@@ -3,20 +3,33 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { ChannelService } from './ChannelService';-const { remove, removeThread, wake, notify, notifyMentions, notifyDirect, send, routing } =- vi.hoisted(() => ({- remove: vi.fn(),- send: vi.fn(),- routing: vi.fn(),- removeThread: vi.fn(),- wake: vi.fn(),- notify: vi.fn(),- notifyMentions: vi.fn(),- notifyDirect: vi.fn(),- }));+const {+ archiveThread,+ onThreadArchived,+ remove,+ removeThread,+ wake,+ notify,+ notifyMentions,+ notifyDirect,+ send,+ routing,+} = vi.hoisted(() => ({+ archiveThread: vi.fn(),+ onThreadArchived: vi.fn(),+ remove: vi.fn(),+ send: vi.fn(),+ routing: vi.fn(),+ removeThread: vi.fn(),+ wake: vi.fn(),+ notify: vi.fn(),+ notifyMentions: vi.fn(),+ notifyDirect: vi.fn(),+}));vi.mock('@/database/repositories/channel', async (original) => ({...(await original<object>()),ChannelRepository: class {+ archiveThread = archiveThread;remove = remove;send = send;removeThread = removeThread;@@ -31,6 +44,44 @@ vi.mock('./directMessage', () => ({ notifyChannelDirectMessages: notifyDirect })vi.mock('./notify', () => ({ notifyChannel: notify }));vi.mock('./routingConfig', () => ({ resolveChannelRoutingConfig: routing }));vi.mock('./queue', () => ({ wakeChannel: wake }));+vi.mock('@/business/server/channel/onThreadArchived', () => ({ onThreadArchived }));++describe('Channel thread archive', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ archiveThread.mockResolvedValue([]);+ wake.mockResolvedValue(undefined);+ notify.mockResolvedValue(undefined);+ onThreadArchived.mockResolvedValue(undefined);+ });+ const service = () => new ChannelService({} as never, 'owner', 'workspace');++ it('hands the archived thread to the follow-up after the archive commits', async () => {+ await service().archiveThread('channel', 'thread');+ expect(onThreadArchived).toHaveBeenCalledWith({+ channelId: 'channel',+ threadId: 'thread',+ userId: 'owner',+ workspaceId: 'workspace',+ });+ expect(archiveThread.mock.invocationCallOrder[0]).toBeLessThan(+ onThreadArchived.mock.invocationCallOrder[0],+ );+ });++ it('skips the follow-up when the archive is refused', async () => {+ archiveThread.mockRejectedValueOnce(new Error('Forbidden'));+ await expect(service().archiveThread('channel', 'thread')).rejects.toThrow('Forbidden');+ expect(onThreadArchived).not.toHaveBeenCalled();+ });++ it('keeps the archive when the follow-up fails', async () => {+ onThreadArchived.mockRejectedValueOnce(new Error('queue down'));+ vi.spyOn(console, 'error').mockImplementation(() => undefined);+ await expect(service().archiveThread('channel', 'thread')).resolves.toBeUndefined();+ expect(wake).toHaveBeenCalledWith('channel');+ });+});describe('Channel deletion scheduling', () => {beforeEach(() => {diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.tsindex d0125d2a8b8..9d58a4088b6 100644--- a/apps/server/src/services/channel/ChannelService.ts+++ b/apps/server/src/services/channel/ChannelService.ts@@ -12,6 +12,7 @@ import {import { eq } from 'drizzle-orm';import pMap from 'p-map';+import { onThreadArchived } from '@/business/server/channel/onThreadArchived';import { getAddressBook } from '@/business/server/contact/addressBook';import { AgentShareModel } from '@/database/models/agentShare';import { DeviceModel } from '@/database/models/device';@@ -582,7 +583,20 @@ export class ChannelService {archiveThread = async (channelId: string, threadId: string) => {await this.repository.archiveThread(channelId, threadId);- await Promise.all([wakeChannel(channelId), this.changed(channelId)]);+ await Promise.all([+ wakeChannel(channelId),+ this.changed(channelId),+ // Through the `@/business` slot (default impl is a no-op); a failure is+ // logged and never fails the archive.+ onThreadArchived({+ channelId,+ threadId,+ userId: this.userId,+ workspaceId: this.workspaceId,+ }).catch((error) =>+ console.error('[ChannelService] thread-archived follow-up failed (non-fatal):', error),+ ),+ ]);};unarchiveThread = async (channelId: string, threadId: string) => {diff --git a/apps/server/src/services/scm/ScmIngestService.ts b/apps/server/src/services/scm/ScmIngestService.tsindex b5cb68a0f21..7a1ffa9e33c 100644--- a/apps/server/src/services/scm/ScmIngestService.ts+++ b/apps/server/src/services/scm/ScmIngestService.ts@@ -1,6 +1,7 @@import { BRANDING_NAME } from '@lobechat/business-const';import debug from 'debug';+import { onChangeRequestSettled } from '@/business/server/scm/onChangeRequestSettled';import { isFailingCheck, ScmChangeRequestModel, ScmInstallationModel } from '@/database/models/scm';import type { ScmChangeRequestItem, ScmInstallationItem } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';@@ -215,9 +216,30 @@ export class ScmIngestService {);await this.onChangeRequestEvent({ event, kind: event.kind, row });+ await this.notifySettled(row);return { detail: `${row.id} ${event.kind}`, status: 'processed' };};+ /**+ * Merged / closed follow-up through the `@/business` slot (default impl is+ * a no-op). A failure is logged and never fails the ingest.+ */+ private notifySettled = async (row: ScmChangeRequestItem) => {+ if (row.state !== 'merged' && row.state !== 'closed') return;+ try {+ await onChangeRequestSettled({+ changeRequestId: row.id,+ settledAt: (row.state === 'merged' ? row.mergedAt : row.closedAt) ?? new Date(),+ state: row.state,+ userId: row.userId,+ workId: row.workId,+ workspaceId: row.workspaceId,+ });+ } catch (error) {+ console.error('[ScmIngestService] change-request settled follow-up failed:', error);+ }+ };+private applyChecks = async (event: Extract<ScmInboundEvent, { type: 'checks' }>,): Promise<ScmIngestOutcome> => {diff --git a/apps/server/src/services/scm/__tests__/ScmIngestService.test.ts b/apps/server/src/services/scm/__tests__/ScmIngestService.test.tsindex c82a50bb843..a3b78c58d27 100644--- a/apps/server/src/services/scm/__tests__/ScmIngestService.test.ts+++ b/apps/server/src/services/scm/__tests__/ScmIngestService.test.ts@@ -18,6 +18,11 @@ import * as fx from '../github/__tests__/fixtures';import { normalizeGitHubEvent } from '../github/normalize';import { ScmIngestService } from '../ScmIngestService';+const { onChangeRequestSettled } = vi.hoisted(() => ({+ onChangeRequestSettled: vi.fn(async () => {}),+}));+vi.mock('@/business/server/scm/onChangeRequestSettled', () => ({ onChangeRequestSettled }));+const serverDB = await getTestDB();const userId = 'scm-ingest-user';const acceptanceId = '0f1e2d3c-4b5a-4c6d-8e9f-0a1b2c3d4e5f';@@ -44,6 +49,7 @@ beforeEach(async () => {});afterEach(async () => {+ onChangeRequestSettled.mockClear();await serverDB.delete(scmWebhookDeliveries);await serverDB.delete(users);});@@ -146,6 +152,15 @@ describe('ScmIngestService', () => {state: 'merged',});expect(hook).toHaveBeenLastCalledWith(expect.objectContaining({ kind: 'merged' }));+ expect(onChangeRequestSettled).toHaveBeenCalledTimes(1);+ expect(onChangeRequestSettled).toHaveBeenCalledWith(+ expect.objectContaining({+ changeRequestId: row!.id,+ settledAt: new Date('2026-09-20T07:00:00Z'),+ state: 'merged',+ userId,+ }),+ );});it('drops a review the same reviewer has already superseded', async () => {diff --git a/apps/server/src/services/task/index.statusCompletion.test.ts b/apps/server/src/services/task/index.statusCompletion.test.tsindex 7896e3e0bfe..c4411472bd0 100644--- a/apps/server/src/services/task/index.statusCompletion.test.ts+++ b/apps/server/src/services/task/index.statusCompletion.test.ts@@ -12,9 +12,12 @@ const mocks = vi.hoisted(() => ({cascadeOnCompletion: vi.fn(),findById: vi.fn(),shouldPauseAfterComplete: vi.fn(),+ onTaskSettled: vi.fn(),updateStatus: vi.fn(),}));+vi.mock('@/business/server/task/onTaskSettled', () => ({ onTaskSettled: mocks.onTaskSettled }));+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));vi.mock('@/database/models/project', () => ({ ProjectModel: vi.fn() }));vi.mock('@/database/models/topic', () => ({ TopicModel: vi.fn() }));@@ -103,6 +106,37 @@ describe('TaskService.updateStatus completion', () => {expect(result).toMatchObject({ paused: ['T-9'], unlocked: ['T-3'] });});+ it('hands the newly completed task to the settled follow-up', async () => {+ mocks.shouldPauseAfterComplete.mockReturnValue(false);+ mocks.areAllSubtasksCompleted.mockResolvedValue(false);++ await new TaskService(db as any, 'user-1', 'ws-1').updateStatus({+ id: 'task-2',+ status: 'completed',+ });++ expect(mocks.onTaskSettled).toHaveBeenCalledWith({+ status: 'completed',+ taskIds: ['task-2'],+ userId: 'user-1',+ workspaceId: 'ws-1',+ });+ });++ it('keeps the transition when the settled follow-up fails', async () => {+ mocks.shouldPauseAfterComplete.mockReturnValue(false);+ mocks.areAllSubtasksCompleted.mockResolvedValue(false);+ mocks.onTaskSettled.mockRejectedValueOnce(new Error('queue down'));+ vi.spyOn(console, 'error').mockImplementation(() => undefined);++ const result = await new TaskService(db as any, 'user-1').updateStatus({+ id: 'task-2',+ status: 'completed',+ });++ expect(result).toMatchObject({ unlocked: ['T-3'] });+ });+it('rejects an error message on a non-failed status before reading the task', async () => {await expect(new TaskService(db as any, 'user-1').updateStatus({diff --git a/apps/server/src/services/task/statusTransitions.ts b/apps/server/src/services/task/statusTransitions.tsindex f7a0a6ea79e..7c6549fe6ab 100644--- a/apps/server/src/services/task/statusTransitions.ts+++ b/apps/server/src/services/task/statusTransitions.ts@@ -5,6 +5,7 @@ import type { TaskContext, TaskItem, TaskSchedulerContext, TaskStatus } from '@limport { TRPCError } from '@trpc/server';import pMap from 'p-map';+import { onTaskSettled } from '@/business/server/task/onTaskSettled';import { taskActivityActor, TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';@@ -43,6 +44,23 @@ export interface UpdateStatusCascadeResult {updatedSubtaskTasks?: { id: string; identifier: string }[];}+/**+ * Completed / canceled follow-up through the `@/business` slot (default impl+ * is a no-op). A failure is logged and never fails the transition.+ */+const notifyTaskSettled = async (+ deps: TaskServiceDeps,+ status: TaskStatus,+ taskIds: string[],+): Promise<void> => {+ if ((status !== 'completed' && status !== 'canceled') || taskIds.length === 0) return;+ try {+ await onTaskSettled({ status, taskIds, userId: deps.userId, workspaceId: deps.workspaceId });+ } catch (error) {+ console.error('[TaskService] task-settled follow-up failed (non-fatal):', error);+ }+};+/*** Transition a task to a new status, cascading the side effects:* - leaving `running`: interrupt + cancel still-running topics@@ -152,6 +170,7 @@ export async function updateStatus(if (startedMeanwhile) {return { paused: [], skippedRunning: true, task: startedMeanwhile, unlocked: [] };}+ if (resolved.status !== status) await notifyTaskSettled(deps, status, [task.id]);// Stamp the schedule run-count window each time the user (re)starts a// scheduled task. The cron dispatcher itself flips a task running →@@ -375,6 +394,11 @@ export async function updateStatusCascade(const task = updatedTasks.find(({ id }) => id === resolved.id);if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });+ await notifyTaskSettled(+ deps,+ input.status,+ targetTasks.filter((before) => before.status !== input.status).map(({ id }) => id),+ );const unlocked: string[] = [];const paused: string[] = [];diff --git a/packages/business-server/src/channel/onThreadArchived.ts b/packages/business-server/src/channel/onThreadArchived.tsnew file mode 100644index 00000000000..566883d8ddd--- /dev/null+++ b/packages/business-server/src/channel/onThreadArchived.ts@@ -0,0 +1,14 @@+export interface OnThreadArchivedParams {+ channelId: string;+ threadId: string;+ /** The person who archived the Thread. */+ userId: string;+ workspaceId?: string;+}++/**+ * Follow-up for a channel Thread that was just archived, called after the+ * archive has been written. It must not slow the archive down, so an+ * implementation only enqueues its work. The default does nothing.+ */+export async function onThreadArchived(_params: OnThreadArchivedParams): Promise<void> {}diff --git a/packages/business-server/src/scm/onChangeRequestSettled.ts b/packages/business-server/src/scm/onChangeRequestSettled.tsnew file mode 100644index 00000000000..c33f3951618--- /dev/null+++ b/packages/business-server/src/scm/onChangeRequestSettled.ts@@ -0,0 +1,19 @@+export interface OnChangeRequestSettledParams {+ changeRequestId: string;+ /** When the provider recorded the merge or close. */+ settledAt: Date;+ state: 'closed' | 'merged';+ userId: string;+ /** The `external` Work registered for the change request, when there is one. */+ workId?: string | null;+ workspaceId?: string | null;+}++/**+ * Follow-up for a change request the provider reported as merged or closed,+ * called after the row has been persisted. Webhook deliveries replay, so an+ * implementation must be idempotent. The default does nothing.+ */+export async function onChangeRequestSettled(+ _params: OnChangeRequestSettledParams,+): Promise<void> {}diff --git a/packages/business-server/src/task/onTaskSettled.ts b/packages/business-server/src/task/onTaskSettled.tsnew file mode 100644index 00000000000..9e69c1042e5--- /dev/null+++ b/packages/business-server/src/task/onTaskSettled.ts@@ -0,0 +1,13 @@+export interface OnTaskSettledParams {+ status: 'canceled' | 'completed';+ /** Every task that moved into `status` in this one transition. */+ taskIds: string[];+ userId: string;+ workspaceId?: string;+}++/**+ * Follow-up for tasks a status transition just moved into `completed` or+ * `canceled`, called after the write. The default does nothing.+ */+export async function onTaskSettled(_params: OnTaskSettledParams): Promise<void> {}