π€― 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
import { TRASH_EMPTY_BATCH_SIZE, TRASH_PURGE_BATCH_SIZE } from '@lobechat/const';
import type {
TrashCountByType,
TrashItem,
TrashListParams,
TrashListResult,
TrashRestoreErrorCode,
TrashRootFilter,
} from '@lobechat/types';
import debug from 'debug';
import { TopicModel } from '@/database/models/topic';
import { TrashModel } from '@/database/models/trash';
import type { TrashItemRow } from '@/database/schemas';
import type { LobeChatDatabase, Transaction } from '@/database/type';
import type { SoftDeleteOptions } from '@/database/utils/softDelete';
import { FileService } from '@/server/services/file';
import { removeByAgent, removeByTopics } from '@/server/services/inboundWebhook/lifecycle';
import { scheduleWorktreeCleanup } from '@/server/services/worktreeCleanup';
import {
resolveTrashHandler,
softDeleteAgent,
softDeleteMessages,
softDeleteTasks,
type TaskTrashTarget,
topicCascades,
type TrashCascade,
type TrashHandlerContext,
TrashPurgeBlockedError,
TrashRestoreError,
} from './handlers';
const log = debug('lobe-server:trash');
export { TrashRestoreError } from './handlers';
export interface TrashOptions {
/** Workspace non-owner members may only sweep their own rows. */
restrictToCreator?: boolean;
}
export interface TrashRestoreOutcome {
failed: { code: TrashRestoreErrorCode; id: string }[];
restored: TrashItem[];
}
export interface TrashPurgeOutcome {
/** Registry ids whose handler refused for now; they stay in the bin. */
blocked: string[];
purged: number;
}
export interface TrashSweepOutcome {
/** Roots that threw during purge β left in place for the next tick. */
failed: number;
/** Registry rows dropped because their resource was already gone. */
pruned: number;
/** Roots hard-deleted this tick. */
purged: number;
}
/**
* Trash tasks inside a transaction the caller already holds β the task delete
* paths decide under their own row locks (a run recording a topic takes the
* same lock) and must stamp + register before releasing them. Returns the ids
* actually moved to the bin; a task whose status changed since the caller
* decided is not among them.
*/
export const trashTasksInTransaction = async (
tx: Transaction,
scope: { userId: string; workspaceId?: string },
targets: TaskTrashTarget[],
): Promise<string[]> => {
const db = tx as unknown as LobeChatDatabase;
const deletedAt = new Date();
const cascades = await softDeleteTasks(
{ db, userId: scope.userId, workspaceId: scope.workspaceId },
targets,
{ deletedAt },
);
await new TrashModel(db, scope.userId, scope.workspaceId).registerMany(
{ cascades, deletedAt },
tx,
);
log('trashed %d task(s)', cascades.length);
return cascades.map((cascade) => cascade.root.resourceId);
};
/**
* Recycle-bin orchestrator. Every user-facing "delete" of a trash-aware entity
* funnels through `trashXxx` here: the handler stamps the rows (and their
* cascade), and the registry gets one root row plus a child row per cascaded
* resource. Restore / purge walk the registry the other way.
*
* Stamp + register run in one transaction, so a failure between the two can
* never leave rows hidden but unlisted.
*/
export class TrashService {
private readonly db: LobeChatDatabase;
private readonly userId: string;
private readonly workspaceId?: string;
private readonly trashModel: TrashModel;
private fileServiceInstance?: FileService;
constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
this.db = db;
this.userId = userId;
this.workspaceId = workspaceId;
this.trashModel = new TrashModel(db, userId, workspaceId);
}
/**
* Built on first use: the storage client reads S3 env at construction, and
* the service is instantiated in router middleware for every request β
* only purge paths ever need it.
*/
private get fileService(): FileService {
this.fileServiceInstance ??= new FileService(this.db, this.userId, this.workspaceId);
return this.fileServiceInstance;
}
private ctx = (db: LobeChatDatabase = this.db): TrashHandlerContext => {
const getFileService = () => this.fileService;
return {
db,
get fileService() {
return getFileService();
},
userId: this.userId,
workspaceId: this.workspaceId,
};
};
private stampOptions = (options?: TrashOptions): SoftDeleteOptions => ({
deletedAt: new Date(),
restrictToCreator: options?.restrictToCreator,
});
/** Run a soft delete and register whatever it produced, atomically. */
private async commit(
run: (ctx: TrashHandlerContext) => Promise<TrashCascade[] | TrashCascade | null>,
deletedAt: Date,
): Promise<TrashItemRow[]> {
const removedTopics: string[] = [];
const removedAgents: string[] = [];
const result = await this.db.transaction(async (tx) => {
const db = tx as unknown as LobeChatDatabase;
const produced = await run(this.ctx(db));
const cascades = (Array.isArray(produced) ? produced : produced ? [produced] : []).filter(
Boolean,
);
for (const cascade of cascades) {
for (const entry of [cascade.root, ...cascade.children]) {
if (entry.resourceType === 'topic') removedTopics.push(entry.resourceId);
if (entry.resourceType === 'agent') removedAgents.push(entry.resourceId);
}
}
// One chunked bulk write for the whole batch: a "clear all topics" over
// hundreds of rows must not hold the transaction open for one registry
// round trip per topic.
const roots = await new TrashModel(db, this.userId, this.workspaceId).registerMany(
{ cascades, deletedAt },
tx,
);
log(
'trashed %d root(s): %o',
roots.length,
roots.map((r) => `${r.resourceType}:${r.resourceId}`),
);
return roots;
});
// Do remote teardown after commit, for the actual rows stamped (including cascades).
// A rollback never removes live subscriptions; a missing remote cannot undo the trash operation.
// The worktrees the app created for these topics go with them; the branch
// stays, so a restore can check it out again.
scheduleWorktreeCleanup({
db: this.db,
topicIds: removedTopics,
trigger: 'trashed',
userId: this.userId,
workspaceId: this.workspaceId,
});
if (removedTopics.length || removedAgents.length) {
try {
const scope = { userId: this.userId, workspaceId: this.workspaceId };
for (const agentId of removedAgents) await removeByAgent(this.db, scope, agentId);
await removeByTopics(this.db, scope, removedTopics);
} catch (error) {
console.error('[trash] Inbound webhook cleanup failed', error);
}
}
return result;
}
// βββββββββββββββββββββββββββ trash (soft delete) βββββββββββββββββββββββββββ
trashTopics = async (ids: string[], options?: TrashOptions & { removeFiles?: boolean }) => {
const stamp = this.stampOptions(options);
return this.commit(async (ctx) => {
const topics = await new TopicModel(ctx.db, this.userId, this.workspaceId).softDelete(
ids,
stamp,
);
return topicCascades(topics, options?.removeFiles);
}, stamp.deletedAt);
};
trashTopicsBySession = async (sessionId: string | null | undefined, options?: TrashOptions) => {
const stamp = this.stampOptions(options);
return this.commit(async (ctx) => {
const topics = await new TopicModel(
ctx.db,
this.userId,
this.workspaceId,
).softDeleteBySessionId(sessionId, stamp);
return topicCascades(topics);
}, stamp.deletedAt);
};
trashTopicsByAgent = async (
agentId: string,
options?: TrashOptions & { legacySessionId?: string | null },
) => {
const stamp = this.stampOptions(options);
return this.commit(async (ctx) => {
const topics = await new TopicModel(
ctx.db,
this.userId,
this.workspaceId,
).softDeleteByAgentId(agentId, { ...stamp, legacySessionId: options?.legacySessionId });
return topicCascades(topics);
}, stamp.deletedAt);
};
trashTopicsByGroup = async (groupId: string | null | undefined, options?: TrashOptions) => {
const stamp = this.stampOptions(options);
return this.commit(async (ctx) => {
const topics = await new TopicModel(
ctx.db,
this.userId,
this.workspaceId,
).softDeleteByGroupId(groupId, stamp);
return topicCascades(topics);
}, stamp.deletedAt);
};
trashAllTopics = async () => {
const stamp = this.stampOptions();
return this.commit(async (ctx) => {
const topics = await new TopicModel(ctx.db, this.userId, this.workspaceId).softDeleteAll(
stamp,
);
return topicCascades(topics);
}, stamp.deletedAt);
};
trashAgent = async (agentId: string, options?: TrashOptions) => {
const stamp = this.stampOptions(options);
const [root] = await this.commit(
(ctx) => softDeleteAgent(ctx, agentId, stamp),
stamp.deletedAt,
);
return root ?? null;
};
trashMessages = async (ids: string[], options?: TrashOptions) => {
const stamp = this.stampOptions(options);
return this.commit((ctx) => softDeleteMessages(ctx, ids, stamp), stamp.deletedAt);
};
// βββββββββββββββββββββββββββ list βββββββββββββββββββββββββββ
list = (params?: TrashListParams): Promise<TrashListResult> => this.trashModel.list(params);
countByType = (filter?: Omit<TrashRootFilter, 'resourceType'>): Promise<TrashCountByType> =>
this.trashModel.countByType(filter);
/** Registry ids among `ids` on the private side of the workspace bin. */
findPrivateIds = (ids: string[]): Promise<Set<string>> => this.trashModel.findPrivateIds(ids);
findByIds = async (ids: string[]): Promise<TrashItem[]> =>
(await this.trashModel.findByIds(ids)).map(this.toItem);
// βββββββββββββββββββββββββββ restore βββββββββββββββββββββββββββ
/**
* Restore roots by registry id. Each root is its own unit of work: one that
* cannot come back (parent still in the bin, resource already gone) is
* reported in `failed` and does not block the others.
*/
restore = async (itemIds: string[]): Promise<TrashRestoreOutcome> => {
const outcome: TrashRestoreOutcome = { failed: [], restored: [] };
const roots = await this.trashModel.findByIds(itemIds);
const known = new Set(roots.map((row) => row.id));
for (const id of itemIds) {
if (!known.has(id)) outcome.failed.push({ code: 'notFound', id });
}
// Roots restored in one call may depend on each other (a message and its
// trashed ancestor, a topic and its agent) and come back in whatever order
// the registry hands them over. A root blocked on a trashed parent is
// retried as long as the previous pass brought something back.
let pending = roots;
while (pending.length > 0) {
const blocked: typeof roots = [];
let progressed = false;
for (const root of pending) {
if (root.rootId) {
// Children are restored through their root, never on their own.
outcome.failed.push({ code: 'parentTrashed', id: root.id });
continue;
}
try {
await this.db.transaction(async (tx) => {
const db = tx as unknown as LobeChatDatabase;
const registry = new TrashModel(db, this.userId, this.workspaceId);
const children = await registry.findChildren(root.id, tx);
await resolveTrashHandler(root.resourceType).restore(this.ctx(db), root, children);
await registry.removeByIds([root.id], tx);
});
outcome.restored.push(this.toItem(root));
progressed = true;
} catch (error) {
if (error instanceof TrashRestoreError) {
if (error.code === 'parentTrashed') {
blocked.push(root);
continue;
}
if (error.code === 'notFound') {
// Nothing to bring back β drop the stale registry row so the bin
// stops advertising it.
await this.trashModel.removeByIds([root.id]);
}
outcome.failed.push({ code: error.code, id: root.id });
continue;
}
throw error;
}
}
if (!progressed) {
for (const root of blocked) outcome.failed.push({ code: 'parentTrashed', id: root.id });
break;
}
pending = blocked;
}
return outcome;
};
// βββββββββββββββββββββββββββ purge (hard delete) βββββββββββββββββββββββββββ
/**
* Permanently delete roots by registry id (their cascade goes with them). A
* root its handler cannot delete yet is reported in `blocked` and left in the
* bin; it does not stop the others.
*/
purge = async (itemIds: string[]): Promise<TrashPurgeOutcome> => {
const roots = (await this.trashModel.findByIds(itemIds)).filter((row) => !row.rootId);
const outcome: TrashPurgeOutcome = { blocked: [], purged: 0 };
for (const root of roots) {
try {
await this.purgeRoot(root);
outcome.purged += 1;
} catch (error) {
if (!(error instanceof TrashPurgeBlockedError)) throw error;
log('purge blocked for %s:%s β %s', root.resourceType, root.resourceId, error.message);
outcome.blocked.push(root.id);
}
}
return outcome;
};
/**
* Permanently delete one bounded batch of the roots a recycle-bin view
* covers (type / project / actor). Each purge is serial and may call
* storage, so a bin of thousands must not ride a single HTTP request: the
* caller repeats with the same filter while `hasMore` is true, and every
* call commits only what it finished. A matched root takes its whole
* cascade with it, whatever its children were recorded under.
*/
emptyTrash = async (
/**
* `deletedByUserId` restricts the sweep to roots this user trashed and
* `visibility` to one side of a workspace bin β filtered in the query,
* not on a page of results, so "empty trash" really does empty
* everything it is allowed to.
*/
filter?: TrashRootFilter,
): Promise<{ blocked: number; hasMore: boolean; purged: number }> => {
const ids = await this.trashModel.listAllRootIds({
...filter,
limit: TRASH_EMPTY_BATCH_SIZE + 1,
});
const { blocked, purged } = await this.purge(ids.slice(0, TRASH_EMPTY_BATCH_SIZE));
// `purged === 0` with rows left means nothing in reach could be purged;
// stop instead of letting the client spin. Blocked roots stay listed, so a
// later batch sees them again and only counts what it actually removed.
return {
blocked: blocked.length,
hasMore: ids.length > TRASH_EMPTY_BATCH_SIZE && purged > 0,
purged,
};
};
private purgeRoot = async (root: TrashItemRow) => {
const children = await this.trashModel.findChildren(root.id);
// Side effects (S3) and hard deletes are not transactional with each
// other by nature; run them, then drop the registry rows. If the handler
// throws, the root stays listed and the sweep retries next tick.
await resolveTrashHandler(root.resourceType).purge(this.ctx(), root, children);
await this.trashModel.removeByIds([root.id]);
log('purged %s:%s (+%d children)', root.resourceType, root.resourceId, children.length);
};
private toItem = (row: TrashItemRow): TrashItem => ({
deletedAt: row.deletedAt,
deletedByUserId: row.deletedByUserId,
expiresAt: row.expiresAt,
id: row.id,
meta: row.meta ?? null,
resourceId: row.resourceId,
resourceType: row.resourceType,
rootId: row.rootId,
title: row.title,
userId: row.userId,
workspaceId: row.workspaceId,
});
// βββββββββββββββββββββββββββ sweep (cron) βββββββββββββββββββββββββββ
/**
* Hard-delete every root past its `expiresAt`, across all users. Runs as a
* QStash schedule (see `router-hono/workflows/trash`). Each root is purged
* under its owner's scope; one failure is logged and skipped so a single
* poisoned row cannot stall the sweep.
*/
static sweepExpired = async (
db: LobeChatDatabase,
options?: { limit?: number; now?: Date },
): Promise<TrashSweepOutcome> => {
const outcome: TrashSweepOutcome = { failed: 0, pruned: 0, purged: 0 };
const roots = await TrashModel.listExpiredRoots(db, {
limit: options?.limit ?? TRASH_PURGE_BATCH_SIZE,
now: options?.now,
});
for (const root of roots) {
const service = new TrashService(db, root.userId, root.workspaceId ?? undefined);
try {
await service.purgeRoot(root);
outcome.purged += 1;
} catch (error) {
outcome.failed += 1;
log('purge failed for %s:%s β %O', root.resourceType, root.resourceId, error);
}
}
outcome.pruned = await TrashModel.pruneOrphans(db);
return outcome;
};
}