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-group): async history backfill for group transfer & copy (#18082)

Rdmclin2d7db40d244ed
diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.ts
index ecbb31697be..443cc87ff09 100644
--- a/apps/server/src/routers/lambda/agent.ts
+++ b/apps/server/src/routers/lambda/agent.ts
@@ -728,6 +728,15 @@ export const agentRouter = router({
message: 'A previous copy of this agent is still duplicating its history',
});
}
+ // A backfill still maps this agent's message rows — deleting it now
+ // would strand the job on a dangling `messages.agent_id`.
+ if (error instanceof Error && error.message === AGENT_TRANSFER_IN_PROGRESS) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.TransferInProgress } },
+ code: 'CONFLICT',
+ message: "A previous transfer of this agent's history is still migrating",
+ });
+ }
throw error;
}
if (ctx.workspaceId) {
diff --git a/apps/server/src/routers/lambda/agentGroup.ts b/apps/server/src/routers/lambda/agentGroup.ts
index a5e2ff05117..6cd36076ae9 100644
--- a/apps/server/src/routers/lambda/agentGroup.ts
+++ b/apps/server/src/routers/lambda/agentGroup.ts
@@ -2,11 +2,15 @@ import { AgentPluginEntrySchema, InsertChatGroupSchema } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
+import { startAgentTransferJob } from '@/business/server/agent-transfer/jobRunner';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
import { AgentModel } from '@/database/models/agent';
import { AGENT_COPY_IN_PROGRESS } from '@/database/models/agentCopyJob';
-import { AGENT_TRANSFER_IN_PROGRESS } from '@/database/models/agentTransferJob';
+import {
+ AGENT_TRANSFER_IN_PROGRESS,
+ AgentTransferJobModel,
+} from '@/database/models/agentTransferJob';
import { ChatGroupModel } from '@/database/models/chatGroup';
import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS } from '@/database/models/topicComment';
@@ -240,6 +244,52 @@ export const agentGroupRouter = router({
* Check agents before removal to identify virtual agents that will be permanently deleted.
* This allows the frontend to show a confirmation dialog.
*/
+ /**
+ * Progress of the async history backfill after a heavy group transfer/copy,
+ * plus the topic ids still awaiting their turn (the UI's gray-out set).
+ * Returns null when no backfill is running for the group.
+ *
+ * The group twin of `agent.getTransferJobStatus`. Only the lookup key
+ * differs: a group's job is found through the group junction, not the member
+ * agents — a group with an empty roster registers no agent rows at all.
+ * Queue-jumping stays on `agent.prioritizeTransferTopic`, which is keyed by
+ * topic and authorizes by topic visibility, so it already serves both.
+ */
+ getTransferJobStatus: agentGroupProcedure
+ .input(
+ z.object({
+ groupId: z.string(),
+ /**
+ * Topics the client currently shows (sidebar rows + active topic).
+ * `pendingTopicIds` is the intersection with the job's queue, keeping
+ * the poll payload bounded however large the backfill is.
+ */
+ topicIds: z.array(z.string()).max(1000),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ // Scope check: only report migration state for groups visible to the
+ // caller's current personal/workspace scope (group ids are guessable).
+ const group = await ctx.chatGroupModel.findById(input.groupId);
+ if (!group) return null;
+
+ const job = await AgentTransferJobModel.findPendingJobForGroup(ctx.serverDB, input.groupId);
+ if (!job) return null;
+ const pendingTopicIds = await AgentTransferJobModel.getPendingTopicIds(
+ ctx.serverDB,
+ job.id,
+ input.topicIds,
+ );
+ return {
+ completedTopics: job.completedTopics,
+ jobId: job.id,
+ pendingTopicIds,
+ totalTopics: job.totalTopics,
+ // `transfer` vs `copy` — the client words its progress hints by it.
+ type: job.type,
+ };
+ }),
+
checkAgentsBeforeRemoval: agentGroupProcedure
.input(
z.object({
@@ -602,11 +652,29 @@ export const agentGroupRouter = router({
workspaceId: ctx.workspaceId,
});
}
- return ctx.agentGroupRepo.removeAgentsFromGroup(
- input.groupId,
- input.agentIds,
- input.deleteVirtualAgents,
- );
+ try {
+ return await ctx.agentGroupRepo.removeAgentsFromGroup(
+ input.groupId,
+ input.agentIds,
+ input.deleteVirtualAgents,
+ );
+ } catch (error) {
+ // A backfill still maps these agents' message rows — removing a member
+ // now would strand the job on a dangling `messages.agent_id`.
+ if (error instanceof Error && error.message === AGENT_TRANSFER_IN_PROGRESS) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: "A previous transfer of this group's agents is still migrating history",
+ });
+ }
+ if (error instanceof Error && error.message === AGENT_COPY_IN_PROGRESS) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'A previous copy of this agent is still duplicating its history',
+ });
+ }
+ throw error;
+ }
}),
transferGroup: agentGroupProcedureWrite
@@ -722,6 +790,16 @@ export const agentGroupRouter = router({
throw error;
}
+ // Nothing moved: the group was not in this scope, or a racing transfer
+ // took it before we got the row lock. Return before the permission writes
+ // below — they would wipe the source ACL and grant access in the target
+ // for a group this call did not transfer.
+ if (!result) return result;
+
+ // Heavy history goes through an async backfill — kick the driver now
+ // that the transfer transaction has committed.
+ if (result.transferJobId) startAgentTransferJob(ctx.serverDB, result.transferJobId);
+
if (ctx.workspaceId) {
await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).removeAll(
'agentGroup',
diff --git a/locales/ar/setting.json b/locales/ar/setting.json
index dca00fcc9a6..e2a94c2c99d 100644
--- a/locales/ar/setting.json
+++ b/locales/ar/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "خدمة النماذج الرسمية من {{name}}",
"about.title": "حول",
+ "accountDeletion.blockedByAgentMigration": "تم إيقاف الحذف مؤقتًا: لا يزال هناك وكيل يقوم بترحيل سجل المحادثات. سيتم المحاولة تلقائيًا بمجرد انتهاء الترحيل.",
+ "accountDeletion.blockedByOwnedWorkspaces": "تم إيقاف الحذف مؤقتًا: لا تزال تملك مساحة عمل تحتوي على أعضاء آخرين. قم بنقل الملكية أو حذف مساحة العمل، وسيتم المحاولة تلقائيًا.",
+ "accountDeletion.blockedRetrying": "لم يتم إكمال الحذف بعد وسيتم المحاولة تلقائيًا.",
"accountDeletion.cancelButton": "إلغاء الحذف",
"accountDeletion.cancelConfirmTitle": "هل تريد إلغاء طلب حذف الحساب؟",
"accountDeletion.cancelFailed": "فشل في إلغاء طلب الحذف",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "نعتذر عن ذلك! انضم إلينا في مجتمعنا على <0>Discord</0> وسنتابع الأمر.",
"accountDeletion.pendingDesc": "تم جدولة حذف حسابك",
"accountDeletion.pendingMessage": "سيتم حذف حسابك خلال {{hours}} ساعة",
+ "accountDeletion.processingMessage": "يتم الآن حذف حسابك...",
"accountDeletion.reasonLabel": "لماذا تغادر؟",
"accountDeletion.reasonOption.account_issue": "مشاكل الحساب (حساب مكرر / تغيير البريد الإلكتروني)",
"accountDeletion.reasonOption.bug": "واجهت خطأ معينًا",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "يجب أن تكون صورة الرمزية أصغر من 5 ميجابايت.",
"workspace.general.avatar.uploadFailed": "فشل في تحميل الصورة الرمزية",
"workspace.general.copyAgentGroups.modal.back": "رجوع",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "سجل المحادثات كبير، لذا يستمر النسخ في الخلفية. مجموعة الوكلاء جاهزة للاستخدام الآن؛ ستظهر المحادثات واحدة تلو الأخرى عند الانتهاء.",
"workspace.general.copyAgentGroups.modal.continue": "متابعة",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "مطلوب. ينسخ بيانات المجموعة، الأعضاء، أدوار الأعضاء، وملفات تعريف الوكلاء.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "تكوين مجموعة الوكلاء",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "إدارة اسم مساحة العمل، عنوان URL، الصورة الرمزية، والإعدادات الأخرى",
"workspace.general.title": "عام",
"workspace.general.transferAgentGroups.modal.back": "رجوع",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "سجل المحادثات كبير، لذا يستمر الترحيل في الخلفية. مجموعة الوكلاء جاهزة للاستخدام الآن؛ ستظهر المحادثات القديمة واحدة تلو الأخرى عند الانتهاء.",
"workspace.general.transferAgentGroups.modal.continue": "متابعة",
"workspace.general.transferAgentGroups.modal.done": "تم",
"workspace.general.transferAgentGroups.modal.failed": "فشل في نقل مجموعات الوكلاء",
diff --git a/locales/bg-BG/setting.json b/locales/bg-BG/setting.json
index 284b3fb3414..ef132fe71da 100644
--- a/locales/bg-BG/setting.json
+++ b/locales/bg-BG/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "Официална услуга за модели на {{name}}",
"about.title": "Относно",
+ "accountDeletion.blockedByAgentMigration": "Изтриването е спряно: агент все още мигрира историята на разговорите си. Ще се опита автоматично отново, след като миграцията приключи.",
+ "accountDeletion.blockedByOwnedWorkspaces": "Изтриването е спряно: все още притежавате работно пространство с други членове. Прехвърлете собствеността или изтрийте работното пространство, и то ще се опита автоматично отново.",
+ "accountDeletion.blockedRetrying": "Изтриването все още не може да бъде завършено и ще се опита автоматично отново.",
"accountDeletion.cancelButton": "Отказ от изтриване",
"accountDeletion.cancelConfirmTitle": "Да отменя ли заявката за изтриване на акаунта?",
"accountDeletion.cancelFailed": "Неуспешна отмяна на заявката за изтриване",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "Съжаляваме за това! Споделете ни в нашата <0>Discord</0> общност и ще се свържем с вас.",
"accountDeletion.pendingDesc": "Акаунтът ви е планиран за изтриване",
"accountDeletion.pendingMessage": "Акаунтът ви ще бъде изтрит след {{hours}} часа",
+ "accountDeletion.processingMessage": "Вашият акаунт се изтрива...",
"accountDeletion.reasonLabel": "Защо напускате?",
"accountDeletion.reasonOption.account_issue": "Проблеми с акаунта (дублиран акаунт / промяна на имейл)",
"accountDeletion.reasonOption.bug": "Срещнах конкретна грешка",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "Файлът на аватара трябва да бъде по-малък от 5MB.",
"workspace.general.avatar.uploadFailed": "Неуспешно качване на аватар",
"workspace.general.copyAgentGroups.modal.back": "Назад",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "Историята на разговорите е голяма, затова продължава да се копира във фонов режим. Групата агенти вече е готова за използване; разговорите се появяват един по един, докато приключат.",
"workspace.general.copyAgentGroups.modal.continue": "Продължаване",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "Задължително. Копира метаданни на групата, членове, роли на членове и профили на агенти.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "Конфигурация на група агенти",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "Управление на името, URL, аватара и други настройки на вашето работно пространство",
"workspace.general.title": "Общи",
"workspace.general.transferAgentGroups.modal.back": "Назад",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "Историята на разговорите е голяма, затова продължава да се мигрира във фонов режим. Групата агенти вече е готова за използване; по-старите разговори се появяват един по един, докато приключат.",
"workspace.general.transferAgentGroups.modal.continue": "Продължаване",
"workspace.general.transferAgentGroups.modal.done": "Готово",
"workspace.general.transferAgentGroups.modal.failed": "Неуспешно прехвърляне на групи агенти",
diff --git a/locales/de-DE/setting.json b/locales/de-DE/setting.json
index 37320de524a..3b257eefec5 100644
--- a/locales/de-DE/setting.json
+++ b/locales/de-DE/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "{{name}} Offizieller Modelldienst",
"about.title": "Über",
+ "accountDeletion.blockedByAgentMigration": "Löschung pausiert: Ein Agent migriert noch seinen Gesprächsverlauf. Es wird automatisch erneut versucht, sobald die Migration abgeschlossen ist.",
+ "accountDeletion.blockedByOwnedWorkspaces": "Löschung pausiert: Sie besitzen noch einen Arbeitsbereich mit anderen Mitgliedern. Übertragen Sie die Eigentümerschaft oder löschen Sie den Arbeitsbereich, und es wird automatisch erneut versucht.",
+ "accountDeletion.blockedRetrying": "Die Löschung konnte noch nicht abgeschlossen werden und wird automatisch erneut versucht.",
"accountDeletion.cancelButton": "Löschung abbrechen",
"accountDeletion.cancelConfirmTitle": "Löschanfrage wirklich abbrechen?",
"accountDeletion.cancelFailed": "Löschanfrage konnte nicht abgebrochen werden",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "Entschuldigung! Teilen Sie uns das in unserer <0>Discord</0>-Community mit, und wir werden uns darum kümmern.",
"accountDeletion.pendingDesc": "Ihr Konto ist zur Löschung vorgemerkt",
"accountDeletion.pendingMessage": "Ihr Konto wird in {{hours}} Stunden gelöscht",
+ "accountDeletion.processingMessage": "Ihr Konto wird gelöscht…",
"accountDeletion.reasonLabel": "Warum verlassen Sie uns?",
"accountDeletion.reasonOption.account_issue": "Kontoprobleme (doppeltes Konto / E-Mail ändern)",
"accountDeletion.reasonOption.bug": "Ich bin auf einen bestimmten Fehler gestoßen",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "Avatar-Datei muss kleiner als 5 MB sein.",
"workspace.general.avatar.uploadFailed": "Avatar-Upload fehlgeschlagen",
"workspace.general.copyAgentGroups.modal.back": "Zurück",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "Der Chatverlauf ist umfangreich, daher wird er im Hintergrund weiter kopiert. Die Agentengruppe ist jetzt einsatzbereit; Gespräche werden nacheinander angezeigt, sobald sie abgeschlossen sind.",
"workspace.general.copyAgentGroups.modal.continue": "Fortfahren",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "Erforderlich. Kopiert Gruppen-Metadaten, Mitglieder, Mitgliederrollen und Agentenprofile.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "Agenten-Gruppenkonfiguration",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "Verwalten Sie den Namen, die URL, das Avatar und andere Einstellungen Ihres Arbeitsbereichs",
"workspace.general.title": "Allgemein",
"workspace.general.transferAgentGroups.modal.back": "Zurück",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "Der Chatverlauf ist umfangreich, daher wird er im Hintergrund weiter migriert. Die Agentengruppe ist jetzt einsatzbereit; ältere Gespräche werden nacheinander angezeigt, sobald sie abgeschlossen sind.",
"workspace.general.transferAgentGroups.modal.continue": "Weiter",
"workspace.general.transferAgentGroups.modal.done": "Fertig",
"workspace.general.transferAgentGroups.modal.failed": "Agentengruppen konnten nicht übertragen werden",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 7505e34f252..7c9721b7515 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "{{name}} Official Model Service",
"about.title": "About",
+ "accountDeletion.blockedByAgentMigration": "Deletion is paused: an agent is still migrating its conversation history. It will retry automatically once the migration finishes.",
+ "accountDeletion.blockedByOwnedWorkspaces": "Deletion is paused: you still own a workspace with other members. Transfer ownership or delete the workspace, and it will retry automatically.",
+ "accountDeletion.blockedRetrying": "Deletion could not be completed yet and will retry automatically.",
"accountDeletion.cancelButton": "Cancel Deletion",
"accountDeletion.cancelConfirmTitle": "Cancel account deletion request?",
"accountDeletion.cancelFailed": "Failed to cancel deletion request",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "Sorry about that! Come tell us in our <0>Discord</0> community and we’ll follow up.",
"accountDeletion.pendingDesc": "Your account is scheduled for deletion",
"accountDeletion.pendingMessage": "Your account will be deleted in {{hours}} hours",
+ "accountDeletion.processingMessage": "Your account is being deleted…",
"accountDeletion.reasonLabel": "Why are you leaving?",
"accountDeletion.reasonOption.account_issue": "Account issues (duplicate account / changing email)",
"accountDeletion.reasonOption.bug": "I ran into a specific bug",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "Avatar file must be smaller than 5MB.",
"workspace.general.avatar.uploadFailed": "Failed to upload avatar",
"workspace.general.copyAgentGroups.modal.back": "Back",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "Chat history is large, so it keeps copying in the background. The agent group is ready to use now; conversations light up one by one as they finish.",
"workspace.general.copyAgentGroups.modal.continue": "Continue",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "Required. Copies group metadata, members, member roles, and Agent profiles.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "Agent group configuration",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "Manage your workspace name, URL, avatar and other settings",
"workspace.general.title": "General",
"workspace.general.transferAgentGroups.modal.back": "Back",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "Chat history is large, so it keeps migrating in the background. The agent group is ready to use now; older conversations light up one by one as they finish.",
"workspace.general.transferAgentGroups.modal.continue": "Continue",
"workspace.general.transferAgentGroups.modal.done": "Done",
"workspace.general.transferAgentGroups.modal.failed": "Failed to transfer agent groups",
diff --git a/locales/es-ES/setting.json b/locales/es-ES/setting.json
index 01256279c4d..220b9663f46 100644
--- a/locales/es-ES/setting.json
+++ b/locales/es-ES/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "Servicio de Modelo Oficial de {{name}}",
"about.title": "Acerca de",
+ "accountDeletion.blockedByAgentMigration": "La eliminación está en pausa: un agente aún está migrando su historial de conversaciones. Se reintentará automáticamente una vez que finalice la migración.",
+ "accountDeletion.blockedByOwnedWorkspaces": "La eliminación está en pausa: todavía eres propietario de un espacio de trabajo con otros miembros. Transfiere la propiedad o elimina el espacio de trabajo, y se reintentará automáticamente.",
+ "accountDeletion.blockedRetrying": "La eliminación no se ha podido completar aún y se reintentará automáticamente.",
"accountDeletion.cancelButton": "Cancelar eliminación",
"accountDeletion.cancelConfirmTitle": "¿Cancelar la solicitud de eliminación de cuenta?",
"accountDeletion.cancelFailed": "No se pudo cancelar la solicitud de eliminación",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "¡Lo sentimos! Ven a contárnoslo en nuestra comunidad de <0>Discord</0> y haremos un seguimiento.",
"accountDeletion.pendingDesc": "Tu cuenta está programada para ser eliminada",
"accountDeletion.pendingMessage": "Tu cuenta será eliminada en {{hours}} horas",
+ "accountDeletion.processingMessage": "Tu cuenta está siendo eliminada…",
"accountDeletion.reasonLabel": "¿Por qué te vas?",
"accountDeletion.reasonOption.account_issue": "Problemas con la cuenta (cuenta duplicada / cambio de correo electrónico)",
"accountDeletion.reasonOption.bug": "Encontré un error específico",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "El archivo del avatar debe ser menor a 5MB.",
"workspace.general.avatar.uploadFailed": "Error al cargar el avatar",
"workspace.general.copyAgentGroups.modal.back": "Atrás",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "El historial de chat es extenso, por lo que sigue copiándose en segundo plano. El grupo de agentes ya está listo para usar; las conversaciones se activan una por una a medida que se completan.",
"workspace.general.copyAgentGroups.modal.continue": "Continuar",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "Requerido. Copia los metadatos del grupo, miembros, roles de miembros y perfiles de agentes.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "Configuración del grupo de agentes",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "Gestiona el nombre, URL, avatar y otras configuraciones de tu espacio de trabajo",
"workspace.general.title": "General",
"workspace.general.transferAgentGroups.modal.back": "Atrás",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "El historial de chat es extenso, por lo que sigue migrándose en segundo plano. El grupo de agentes ya está listo para usar; las conversaciones más antiguas se activan una por una a medida que se completan.",
"workspace.general.transferAgentGroups.modal.continue": "Continuar",
"workspace.general.transferAgentGroups.modal.done": "Hecho",
"workspace.general.transferAgentGroups.modal.failed": "Error al transferir grupos de agentes",
diff --git a/locales/fa-IR/setting.json b/locales/fa-IR/setting.json
index caa9b16e01c..ee5a376f5fc 100644
--- a/locales/fa-IR/setting.json
+++ b/locales/fa-IR/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "سرویس مدل رسمی {{name}}",
"about.title": "درباره",
+ "accountDeletion.blockedByAgentMigration": "حذف متوقف شده است: یک عامل هنوز در حال انتقال تاریخچه مکالمات خود است. پس از اتمام انتقال، به‌طور خودکار دوباره تلاش خواهد کرد.",
+ "accountDeletion.blockedByOwnedWorkspaces": "حذف متوقف شده است: شما هنوز مالک یک فضای کاری با اعضای دیگر هستید. مالکیت را منتقل کنید یا فضای کاری را حذف کنید، و به‌طور خودکار دوباره تلاش خواهد کرد.",
+ "accountDeletion.blockedRetrying": "حذف هنوز نمی‌تواند تکمیل شود و به‌طور خودکار دوباره تلاش خواهد کرد.",
"accountDeletion.cancelButton": "لغو حذف",
"accountDeletion.cancelConfirmTitle": "درخواست حذف حساب لغو شود؟",
"accountDeletion.cancelFailed": "لغو درخواست حذف ناموفق بود",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "متأسفیم! لطفاً در جامعه <0>Discord</0> ما به ما اطلاع دهید و ما پیگیری خواهیم کرد.",
"accountDeletion.pendingDesc": "حساب شما در صف حذف قرار دارد",
"accountDeletion.pendingMessage": "حساب شما در {{hours}} ساعت آینده حذف خواهد شد",
+ "accountDeletion.processingMessage": "حساب شما در حال حذف شدن است...",
"accountDeletion.reasonLabel": "چرا می‌خواهید ترک کنید؟",
"accountDeletion.reasonOption.account_issue": "مشکلات حساب (حساب تکراری / تغییر ایمیل)",
"accountDeletion.reasonOption.bug": "با یک مشکل خاص مواجه شدم",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "فایل آواتار باید کمتر از ۵ مگابایت باشد.",
"workspace.general.avatar.uploadFailed": "بارگذاری آواتار ناموفق بود",
"workspace.general.copyAgentGroups.modal.back": "بازگشت",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "تاریخچه چت بزرگ است، بنابراین در پس‌زمینه به کپی کردن ادامه می‌دهد. گروه عامل اکنون آماده استفاده است؛ مکالمات یکی یکی پس از اتمام روشن می‌شوند.",
"workspace.general.copyAgentGroups.modal.continue": "ادامه",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "ضروری. کپی کردن متادیتای گروه، اعضا، نقش‌های اعضا و پروفایل‌های Agent.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "پیکربندی گروه Agent",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "نام فضای کاری، URL، آواتار و تنظیمات دیگر خود را مدیریت کنید",
"workspace.general.title": "عمومی",
"workspace.general.transferAgentGroups.modal.back": "بازگشت",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "تاریخچه چت بزرگ است، بنابراین در پس‌زمینه به انتقال ادامه می‌دهد. گروه عامل اکنون آماده استفاده است؛ مکالمات قدیمی یکی یکی پس از اتمام روشن می‌شوند.",
"workspace.general.transferAgentGroups.modal.continue": "ادامه",
"workspace.general.transferAgentGroups.modal.done": "انجام شد",
"workspace.general.transferAgentGroups.modal.failed": "انتقال گروه‌های نماینده ناموفق بود",
diff --git a/locales/fr-FR/setting.json b/locales/fr-FR/setting.json
index 9dcbbf6d6d8..59b2878f6d6 100644
--- a/locales/fr-FR/setting.json
+++ b/locales/fr-FR/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "Service de modèle officiel de {{name}}",
"about.title": "À propos",
+ "accountDeletion.blockedByAgentMigration": "La suppression est en pause : un agent migre encore son historique de conversation. Elle reprendra automatiquement une fois la migration terminée.",
+ "accountDeletion.blockedByOwnedWorkspaces": "La suppression est en pause : vous possédez encore un espace de travail avec d'autres membres. Transférez la propriété ou supprimez l'espace de travail, et elle reprendra automatiquement.",
+ "accountDeletion.blockedRetrying": "La suppression n'a pas encore pu être effectuée et reprendra automatiquement.",
"accountDeletion.cancelButton": "Annuler la suppression",
"accountDeletion.cancelConfirmTitle": "Annuler la demande de suppression du compte ?",
"accountDeletion.cancelFailed": "Échec de l'annulation de la demande de suppression",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "Désolé pour cela ! Venez nous en parler dans notre communauté <0>Discord</0> et nous ferons un suivi.",
"accountDeletion.pendingDesc": "Votre compte est en cours de suppression",
"accountDeletion.pendingMessage": "Votre compte sera supprimé dans {{hours}} heures",
+ "accountDeletion.processingMessage": "Votre compte est en cours de suppression…",
"accountDeletion.reasonLabel": "Pourquoi partez-vous ?",
"accountDeletion.reasonOption.account_issue": "Problèmes de compte (compte en double / changement d'email)",
"accountDeletion.reasonOption.bug": "J'ai rencontré un bug spécifique",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "Le fichier de l'avatar doit être inférieur à 5 Mo.",
"workspace.general.avatar.uploadFailed": "Échec du téléchargement de l'avatar",
"workspace.general.copyAgentGroups.modal.back": "Retour",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "L'historique des conversations est volumineux, il continue donc de se copier en arrière-plan. Le groupe d'agents est prêt à être utilisé maintenant ; les conversations s'affichent une par une au fur et à mesure qu'elles se terminent.",
"workspace.general.copyAgentGroups.modal.continue": "Continuer",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "Obligatoire. Copie les métadonnées du groupe, les membres, les rôles des membres et les profils des agents.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "Configuration du groupe d'agents",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "Gérez le nom, l'URL, l'avatar et d'autres paramètres de votre espace de travail",
"workspace.general.title": "Général",
"workspace.general.transferAgentGroups.modal.back": "Retour",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "L'historique des conversations est volumineux, il continue donc de migrer en arrière-plan. Le groupe d'agents est prêt à être utilisé maintenant ; les anciennes conversations s'affichent une par une au fur et à mesure qu'elles se terminent.",
"workspace.general.transferAgentGroups.modal.continue": "Continuer",
"workspace.general.transferAgentGroups.modal.done": "Terminé",
"workspace.general.transferAgentGroups.modal.failed": "Échec du transfert des groupes d'agents",
diff --git a/locales/it-IT/setting.json b/locales/it-IT/setting.json
index b7db637816d..2327d48bab0 100644
--- a/locales/it-IT/setting.json
+++ b/locales/it-IT/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "Servizio Modello Ufficiale di {{name}}",
"about.title": "Informazioni",
+ "accountDeletion.blockedByAgentMigration": "Eliminazione in pausa: un agente sta ancora migrando la cronologia delle conversazioni. Riproverà automaticamente una volta completata la migrazione.",
+ "accountDeletion.blockedByOwnedWorkspaces": "Eliminazione in pausa: possiedi ancora uno spazio di lavoro con altri membri. Trasferisci la proprietà o elimina lo spazio di lavoro, e riproverà automaticamente.",
+ "accountDeletion.blockedRetrying": "L'eliminazione non è ancora stata completata e riproverà automaticamente.",
"accountDeletion.cancelButton": "Annulla eliminazione",
"accountDeletion.cancelConfirmTitle": "Annullare la richiesta di eliminazione dell'account?",
"accountDeletion.cancelFailed": "Impossibile annullare la richiesta di eliminazione",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "Ci dispiace! Vieni a parlarcene nella nostra comunità su <0>Discord</0> e ti risponderemo.",
"accountDeletion.pendingDesc": "Il tuo account è programmato per l'eliminazione",
"accountDeletion.pendingMessage": "Il tuo account sarà eliminato tra {{hours}} ore",
+ "accountDeletion.processingMessage": "Il tuo account è in fase di eliminazione…",
"accountDeletion.reasonLabel": "Perché stai lasciando?",
"accountDeletion.reasonOption.account_issue": "Problemi con l'account (account duplicato / cambio email)",
"accountDeletion.reasonOption.bug": "Ho riscontrato un bug specifico",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "Il file dell'avatar deve essere più piccolo di 5MB.",
"workspace.general.avatar.uploadFailed": "Caricamento dell'avatar fallito",
"workspace.general.copyAgentGroups.modal.back": "Indietro",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "La cronologia delle chat è ampia, quindi continua a copiare in background. Il gruppo di agenti è ora pronto per l'uso; le conversazioni si attivano una per una man mano che vengono completate.",
"workspace.general.copyAgentGroups.modal.continue": "Continua",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "Obbligatorio. Copia i metadati del gruppo, i membri, i ruoli dei membri e i profili degli agenti.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "Configurazione del gruppo di agenti",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "Gestisci il nome del tuo workspace, URL, avatar e altre impostazioni",
"workspace.general.title": "Generale",
"workspace.general.transferAgentGroups.modal.back": "Indietro",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "La cronologia delle chat è ampia, quindi continua a migrare in background. Il gruppo di agenti è ora pronto per l'uso; le conversazioni più vecchie si attivano una per una man mano che vengono completate.",
"workspace.general.transferAgentGroups.modal.continue": "Continua",
"workspace.general.transferAgentGroups.modal.done": "Fatto",
"workspace.general.transferAgentGroups.modal.failed": "Trasferimento dei gruppi di agenti fallito",
diff --git a/locales/ja-JP/setting.json b/locales/ja-JP/setting.json
index 0849f99c0b0..d05f986c942 100644
--- a/locales/ja-JP/setting.json
+++ b/locales/ja-JP/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "{{name}} 公式モデルサービス",
"about.title": "について",
+ "accountDeletion.blockedByAgentMigration": "削除は一時停止されています: エージェントがまだ会話履歴を移行中です。移行が完了すると自動的に再試行されます。",
+ "accountDeletion.blockedByOwnedWorkspaces": "削除は一時停止されています: 他のメンバーがいるワークスペースをまだ所有しています。所有権を移譲するかワークスペースを削除すると、自動的に再試行されます。",
+ "accountDeletion.blockedRetrying": "削除はまだ完了しておらず、自動的に再試行されます。",
"accountDeletion.cancelButton": "削除をキャンセル",
"accountDeletion.cancelConfirmTitle": "アカウント削除のリクエストをキャンセルしますか?",
"accountDeletion.cancelFailed": "削除リクエストのキャンセルに失敗しました",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "申し訳ありません!<0>Discord</0>コミュニティでお知らせいただければ、対応いたします。",
"accountDeletion.pendingDesc": "アカウントは削除予定です",
"accountDeletion.pendingMessage": "アカウントは{{hours}}時間後に削除されます",
+ "accountDeletion.processingMessage": "アカウントを削除中です…",
"accountDeletion.reasonLabel": "退会の理由を教えてください。",
"accountDeletion.reasonOption.account_issue": "アカウントの問題(重複アカウント / メール変更)",
"accountDeletion.reasonOption.bug": "特定のバグに遭遇した",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "アバターファイルは5MB以下である必要があります。",
"workspace.general.avatar.uploadFailed": "アバターのアップロードに失敗しました",
"workspace.general.copyAgentGroups.modal.back": "戻る",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "チャット履歴が大きいため、バックグラウンドでコピーを続けています。エージェントグループはすぐに使用可能で、会話は完了次第順次表示されます。",
"workspace.general.copyAgentGroups.modal.continue": "続行",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "必須。グループのメタデータ、メンバー、メンバーの役割、およびエージェントプロファイルをコピーします。",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "エージェントグループ構成",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "ワークスペース名、URL、アバター、その他の設定を管理",
"workspace.general.title": "一般",
"workspace.general.transferAgentGroups.modal.back": "戻る",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "チャット履歴が大きいため、バックグラウンドで移行を続けています。エージェントグループはすぐに使用可能で、古い会話は完了次第順次表示されます。",
"workspace.general.transferAgentGroups.modal.continue": "続行",
"workspace.general.transferAgentGroups.modal.done": "完了",
"workspace.general.transferAgentGroups.modal.failed": "エージェントグループの移転に失敗しました",
diff --git a/locales/ko-KR/setting.json b/locales/ko-KR/setting.json
index 69dc05a61e9..0504f5cc47c 100644
--- a/locales/ko-KR/setting.json
+++ b/locales/ko-KR/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "{{name}} 공식 모델 서비스",
"about.title": "정보",
+ "accountDeletion.blockedByAgentMigration": "삭제가 일시 중지되었습니다: 에이전트가 여전히 대화 기록을 마이그레이션 중입니다. 마이그레이션이 완료되면 자동으로 다시 시도됩니다.",
+ "accountDeletion.blockedByOwnedWorkspaces": "삭제가 일시 중지되었습니다: 다른 멤버가 있는 워크스페이스를 아직 소유하고 있습니다. 소유권을 이전하거나 워크스페이스를 삭제하면 자동으로 다시 시도됩니다.",
+ "accountDeletion.blockedRetrying": "삭제를 아직 완료할 수 없으며 자동으로 다시 시도됩니다.",
"accountDeletion.cancelButton": "삭제 취소",
"accountDeletion.cancelConfirmTitle": "계정 삭제 요청을 취소하시겠습니까?",
"accountDeletion.cancelFailed": "삭제 요청 취소에 실패했습니다",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "불편을 드려 죄송합니다! <0>Discord</0> 커뮤니티에서 알려주시면 저희가 확인하겠습니다.",
"accountDeletion.pendingDesc": "계정이 삭제 예정 상태입니다",
"accountDeletion.pendingMessage": "계정은 {{hours}}시간 후에 삭제됩니다",
+ "accountDeletion.processingMessage": "계정이 삭제되고 있습니다…",
"accountDeletion.reasonLabel": "왜 떠나시나요?",
"accountDeletion.reasonOption.account_issue": "계정 문제 (중복 계정 / 이메일 변경)",
"accountDeletion.reasonOption.bug": "특정 버그를 발견했습니다",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "아바타 파일은 5MB보다 작아야 합니다.",
"workspace.general.avatar.uploadFailed": "아바타 업로드에 실패했습니다",
"workspace.general.copyAgentGroups.modal.back": "뒤로",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "채팅 기록이 많아 백그라운드에서 계속 복사됩니다. 에이전트 그룹은 지금 사용할 준비가 되었으며, 대화는 완료되는 대로 하나씩 표시됩니다.",
"workspace.general.copyAgentGroups.modal.continue": "계속",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "필수. 그룹 메타데이터, 멤버, 멤버 역할 및 에이전트 프로필을 복사합니다.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "에이전트 그룹 구성",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "워크스페이스 이름, URL, 아바타 및 기타 설정을 관리하세요",
"workspace.general.title": "일반",
"workspace.general.transferAgentGroups.modal.back": "뒤로",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "채팅 기록이 많아 백그라운드에서 계속 마이그레이션됩니다. 에이전트 그룹은 지금 사용할 준비가 되었으며, 이전 대화는 완료되는 대로 하나씩 표시됩니다.",
"workspace.general.transferAgentGroups.modal.continue": "계속",
"workspace.general.transferAgentGroups.modal.done": "완료",
"workspace.general.transferAgentGroups.modal.failed": "에이전트 그룹 전송에 실패했습니다",
diff --git a/locales/nl-NL/setting.json b/locales/nl-NL/setting.json
index 0b22cb5a66c..4decae3c663 100644
--- a/locales/nl-NL/setting.json
+++ b/locales/nl-NL/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "{{name}} Officiële Modeldienst",
"about.title": "Over",
+ "accountDeletion.blockedByAgentMigration": "Verwijdering is gepauzeerd: een agent migreert nog steeds zijn gespreksgeschiedenis. Het zal automatisch opnieuw proberen zodra de migratie is voltooid.",
+ "accountDeletion.blockedByOwnedWorkspaces": "Verwijdering is gepauzeerd: je bent nog steeds eigenaar van een werkruimte met andere leden. Draag het eigendom over of verwijder de werkruimte, en het zal automatisch opnieuw proberen.",
+ "accountDeletion.blockedRetrying": "Verwijdering kon nog niet worden voltooid en zal automatisch opnieuw proberen.",
"accountDeletion.cancelButton": "Verwijdering annuleren",
"accountDeletion.cancelConfirmTitle": "Verzoek tot accountverwijdering annuleren?",
"accountDeletion.cancelFailed": "Annuleren van verwijderingsverzoek mislukt",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "Onze excuses! Kom het ons vertellen in onze <0>Discord</0>-community en we zullen het opvolgen.",
"accountDeletion.pendingDesc": "Je account staat gepland voor verwijdering",
"accountDeletion.pendingMessage": "Je account wordt verwijderd over {{hours}} uur",
+ "accountDeletion.processingMessage": "Je account wordt verwijderd…",
"accountDeletion.reasonLabel": "Waarom vertrek je?",
"accountDeletion.reasonOption.account_issue": "Accountproblemen (dubbel account / e-mail wijzigen)",
"accountDeletion.reasonOption.bug": "Ik ben een specifieke bug tegengekomen",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "Avatarbestand moet kleiner zijn dan 5MB.",
"workspace.general.avatar.uploadFailed": "Uploaden van avatar mislukt",
"workspace.general.copyAgentGroups.modal.back": "Terug",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "De chatgeschiedenis is groot, dus het kopiëren gaat door op de achtergrond. De agentgroep is nu klaar voor gebruik; gesprekken worden één voor één zichtbaar zodra ze zijn voltooid.",
"workspace.general.copyAgentGroups.modal.continue": "Doorgaan",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "Vereist. Kopieert groepsmetadata, leden, ledenrollen en agentprofielen.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "Agentgroepconfiguratie",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "Beheer de naam, URL, avatar en andere instellingen van uw werkruimte",
"workspace.general.title": "Algemeen",
"workspace.general.transferAgentGroups.modal.back": "Terug",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "De chatgeschiedenis is groot, dus de migratie gaat door op de achtergrond. De agentgroep is nu klaar voor gebruik; oudere gesprekken worden één voor één zichtbaar zodra ze zijn voltooid.",
"workspace.general.transferAgentGroups.modal.continue": "Doorgaan",
"workspace.general.transferAgentGroups.modal.done": "Klaar",
"workspace.general.transferAgentGroups.modal.failed": "Agentgroepen overdragen mislukt",
diff --git a/locales/pl-PL/setting.json b/locales/pl-PL/setting.json
index 9281683b913..03bf1e37629 100644
--- a/locales/pl-PL/setting.json
+++ b/locales/pl-PL/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "Oficjalna usługa modelu {{name}}",
"about.title": "O nas",
+ "accountDeletion.blockedByAgentMigration": "Usunięcie wstrzymane: agent nadal migruje historię rozmów. Proces zostanie automatycznie wznowiony po zakończeniu migracji.",
+ "accountDeletion.blockedByOwnedWorkspaces": "Usunięcie wstrzymane: nadal jesteś właścicielem przestrzeni roboczej z innymi członkami. Przekaż własność lub usuń przestrzeń roboczą, a proces zostanie automatycznie wznowiony.",
+ "accountDeletion.blockedRetrying": "Usunięcie nie mogło zostać jeszcze zakończone i zostanie automatycznie wznowione.",
"accountDeletion.cancelButton": "Anuluj usunięcie",
"accountDeletion.cancelConfirmTitle": "Anulować prośbę o usunięcie konta?",
"accountDeletion.cancelFailed": "Nie udało się anulować prośby o usunięcie",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "Przepraszamy za to! Dołącz do naszej społeczności na <0>Discordzie</0> i zajmiemy się tym.",
"accountDeletion.pendingDesc": "Twoje konto jest zaplanowane do usunięcia",
"accountDeletion.pendingMessage": "Twoje konto zostanie usunięte za {{hours}} godzin",
+ "accountDeletion.processingMessage": "Twoje konto jest usuwane…",
"accountDeletion.reasonLabel": "Dlaczego odchodzisz?",
"accountDeletion.reasonOption.account_issue": "Problemy z kontem (duplikat konta / zmiana e-maila)",
"accountDeletion.reasonOption.bug": "Napotkałem konkretny błąd",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "Plik avatara musi być mniejszy niż 5MB.",
"workspace.general.avatar.uploadFailed": "Nie udało się przesłać avatara",
"workspace.general.copyAgentGroups.modal.back": "Wstecz",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "Historia czatu jest obszerna, więc kopiowanie odbywa się w tle. Grupa agentów jest już gotowa do użycia; rozmowy będą pojawiać się jedna po drugiej po zakończeniu.",
"workspace.general.copyAgentGroups.modal.continue": "Kontynuuj",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "Wymagane. Kopiuje metadane grup, członków, role członków i profile Agentów.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "Konfiguracja grup Agentów",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "Zarządzaj nazwą przestrzeni roboczej, URL-em, awatarem i innymi ustawieniami",
"workspace.general.title": "Ogólne",
"workspace.general.transferAgentGroups.modal.back": "Wstecz",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "Historia czatu jest obszerna, więc migracja odbywa się w tle. Grupa agentów jest już gotowa do użycia; starsze rozmowy będą pojawiać się jedna po drugiej po zakończeniu.",
"workspace.general.transferAgentGroups.modal.continue": "Kontynuuj",
"workspace.general.transferAgentGroups.modal.done": "Gotowe",
"workspace.general.transferAgentGroups.modal.failed": "Nie udało się przenieść grup agentów",
diff --git a/locales/pt-BR/setting.json b/locales/pt-BR/setting.json
index 54e3e9839c3..021a526eb8a 100644
--- a/locales/pt-BR/setting.json
+++ b/locales/pt-BR/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "Serviço Oficial de Modelos {{name}}",
"about.title": "Sobre",
+ "accountDeletion.blockedByAgentMigration": "A exclusão está pausada: um agente ainda está migrando seu histórico de conversas. Tentará novamente automaticamente assim que a migração for concluída.",
+ "accountDeletion.blockedByOwnedWorkspaces": "A exclusão está pausada: você ainda é proprietário de um espaço de trabalho com outros membros. Transfira a propriedade ou exclua o espaço de trabalho, e tentará novamente automaticamente.",
+ "accountDeletion.blockedRetrying": "A exclusão ainda não pôde ser concluída e tentará novamente automaticamente.",
"accountDeletion.cancelButton": "Cancelar Exclusão",
"accountDeletion.cancelConfirmTitle": "Cancelar solicitação de exclusão da conta?",
"accountDeletion.cancelFailed": "Falha ao cancelar a solicitação de exclusão",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "Desculpe por isso! Venha nos contar em nossa comunidade no <0>Discord</0> e nós iremos acompanhar.",
"accountDeletion.pendingDesc": "Sua conta está agendada para exclusão",
"accountDeletion.pendingMessage": "Sua conta será excluída em {{hours}} horas",
+ "accountDeletion.processingMessage": "Sua conta está sendo excluída…",
"accountDeletion.reasonLabel": "Por que você está saindo?",
"accountDeletion.reasonOption.account_issue": "Problemas com a conta (conta duplicada / alteração de e-mail)",
"accountDeletion.reasonOption.bug": "Encontrei um bug específico",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "O arquivo do avatar deve ter menos de 5MB.",
"workspace.general.avatar.uploadFailed": "Falha ao enviar o avatar",
"workspace.general.copyAgentGroups.modal.back": "Voltar",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "O histórico de conversas é grande, então continua copiando em segundo plano. O grupo de agentes está pronto para uso agora; as conversas aparecem uma a uma à medida que são concluídas.",
"workspace.general.copyAgentGroups.modal.continue": "Continuar",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "Obrigatório. Copia metadados do grupo, membros, funções dos membros e perfis de Agentes.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "Configuração do grupo de agentes",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "Gerencie o nome, URL, avatar e outras configurações do seu espaço de trabalho",
"workspace.general.title": "Geral",
"workspace.general.transferAgentGroups.modal.back": "Voltar",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "O histórico de conversas é grande, então continua migrando em segundo plano. O grupo de agentes está pronto para uso agora; as conversas mais antigas aparecem uma a uma à medida que são concluídas.",
"workspace.general.transferAgentGroups.modal.continue": "Continuar",
"workspace.general.transferAgentGroups.modal.done": "Concluído",
"workspace.general.transferAgentGroups.modal.failed": "Falha ao transferir grupos de agentes",
diff --git a/locales/ru-RU/setting.json b/locales/ru-RU/setting.json
index 923b9ff552c..523a16cf8b3 100644
--- a/locales/ru-RU/setting.json
+++ b/locales/ru-RU/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "Официальный сервис модели {{name}}",
"about.title": "О программе",
+ "accountDeletion.blockedByAgentMigration": "Удаление приостановлено: агент все еще мигрирует историю разговоров. Попытка будет выполнена автоматически после завершения миграции.",
+ "accountDeletion.blockedByOwnedWorkspaces": "Удаление приостановлено: вы все еще являетесь владельцем рабочего пространства с другими участниками. Передайте права собственности или удалите рабочее пространство, и попытка будет выполнена автоматически.",
+ "accountDeletion.blockedRetrying": "Удаление пока не может быть завершено, но попытка будет выполнена автоматически.",
"accountDeletion.cancelButton": "Отменить удаление",
"accountDeletion.cancelConfirmTitle": "Отменить запрос на удаление аккаунта?",
"accountDeletion.cancelFailed": "Не удалось отменить запрос на удаление",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "Извините за это! Расскажите нам об этом в нашем сообществе на <0>Discord</0>, и мы разберемся.",
"accountDeletion.pendingDesc": "Ваш аккаунт запланирован к удалению",
"accountDeletion.pendingMessage": "Ваш аккаунт будет удалён через {{hours}} ч.",
+ "accountDeletion.processingMessage": "Ваш аккаунт удаляется…",
"accountDeletion.reasonLabel": "Почему вы уходите?",
"accountDeletion.reasonOption.account_issue": "Проблемы с аккаунтом (дублирующийся аккаунт / изменение электронной почты)",
"accountDeletion.reasonOption.bug": "Я столкнулся с конкретной ошибкой",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "Файл аватара должен быть меньше 5 МБ.",
"workspace.general.avatar.uploadFailed": "Не удалось загрузить аватар",
"workspace.general.copyAgentGroups.modal.back": "Назад",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "История чатов большая, поэтому копирование продолжается в фоновом режиме. Группа агентов уже готова к использованию; разговоры будут появляться один за другим по мере завершения.",
"workspace.general.copyAgentGroups.modal.continue": "Продолжить",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "Обязательно. Копирует метаданные группы, участников, роли участников и профили агентов.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "Конфигурация группы агентов",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "Управляйте именем рабочей области, URL, аватаром и другими настройками",
"workspace.general.title": "Общее",
"workspace.general.transferAgentGroups.modal.back": "Назад",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "История чатов большая, поэтому миграция продолжается в фоновом режиме. Группа агентов уже готова к использованию; старые разговоры будут появляться один за другим по мере завершения.",
"workspace.general.transferAgentGroups.modal.continue": "Продолжить",
"workspace.general.transferAgentGroups.modal.done": "Готово",
"workspace.general.transferAgentGroups.modal.failed": "Не удалось перенести группы агентов",
diff --git a/locales/tr-TR/setting.json b/locales/tr-TR/setting.json
index 359d201bcf7..3755f2cc043 100644
--- a/locales/tr-TR/setting.json
+++ b/locales/tr-TR/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "{{name}} Resmi Model Hizmeti",
"about.title": "Hakkında",
+ "accountDeletion.blockedByAgentMigration": "Silme işlemi duraklatıldı: Bir temsilci hâlâ sohbet geçmişini taşıyor. Taşıma tamamlandığında otomatik olarak yeniden denenecek.",
+ "accountDeletion.blockedByOwnedWorkspaces": "Silme işlemi duraklatıldı: Hâlâ diğer üyelerle paylaşılan bir çalışma alanına sahipsiniz. Sahipliği devredin veya çalışma alanını silin, ardından otomatik olarak yeniden denenecek.",
+ "accountDeletion.blockedRetrying": "Silme işlemi henüz tamamlanamadı ve otomatik olarak yeniden denenecek.",
"accountDeletion.cancelButton": "Silme İşlemini İptal Et",
"accountDeletion.cancelConfirmTitle": "Hesap silme talebini iptal etmek istiyor musunuz?",
"accountDeletion.cancelFailed": "Silme talebi iptal edilemedi",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "Üzgünüz! <0>Discord</0> topluluğumuzda bize anlatın, biz de takip edelim.",
"accountDeletion.pendingDesc": "Hesabınız silinmek üzere planlandı",
"accountDeletion.pendingMessage": "Hesabınız {{hours}} saat içinde silinecek",
+ "accountDeletion.processingMessage": "Hesabınız siliniyor…",
"accountDeletion.reasonLabel": "Neden ayrılıyorsunuz?",
"accountDeletion.reasonOption.account_issue": "Hesap sorunları (çift hesap / e-posta değiştirme)",
"accountDeletion.reasonOption.bug": "Belirli bir hata ile karşılaştım",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "Avatar dosyası 5MB'den küçük olmalıdır.",
"workspace.general.avatar.uploadFailed": "Avatar yüklenemedi",
"workspace.general.copyAgentGroups.modal.back": "Geri",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "Sohbet geçmişi büyük olduğu için arka planda kopyalanmaya devam ediyor. Temsilci grubu artık kullanıma hazır; konuşmalar tamamlandıkça birer birer görünecek.",
"workspace.general.copyAgentGroups.modal.continue": "Devam",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "Gerekli. Grup meta verilerini, üyeleri, üye rollerini ve Ajan profillerini kopyalar.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "Ajan grubu yapılandırması",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "Çalışma alanı adınızı, URL'nizi, avatarınızı ve diğer ayarları yönetin",
"workspace.general.title": "Genel",
"workspace.general.transferAgentGroups.modal.back": "Geri",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "Sohbet geçmişi büyük olduğu için arka planda taşınmaya devam ediyor. Temsilci grubu artık kullanıma hazır; eski konuşmalar tamamlandıkça birer birer görünecek.",
"workspace.general.transferAgentGroups.modal.continue": "Devam",
"workspace.general.transferAgentGroups.modal.done": "Tamamlandı",
"workspace.general.transferAgentGroups.modal.failed": "Ajan grupları taşınamadı",
diff --git a/locales/vi-VN/setting.json b/locales/vi-VN/setting.json
index b5679d979d2..4d0911dd42a 100644
--- a/locales/vi-VN/setting.json
+++ b/locales/vi-VN/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "Dịch vụ Mô hình Chính thức của {{name}}",
"about.title": "Giới thiệu",
+ "accountDeletion.blockedByAgentMigration": "Xóa tài khoản bị tạm dừng: một tác nhân vẫn đang di chuyển lịch sử hội thoại. Hệ thống sẽ tự động thử lại sau khi quá trình di chuyển hoàn tất.",
+ "accountDeletion.blockedByOwnedWorkspaces": "Xóa tài khoản bị tạm dừng: bạn vẫn sở hữu một không gian làm việc với các thành viên khác. Hãy chuyển quyền sở hữu hoặc xóa không gian làm việc, và hệ thống sẽ tự động thử lại.",
+ "accountDeletion.blockedRetrying": "Xóa tài khoản chưa thể hoàn tất và sẽ tự động thử lại.",
"accountDeletion.cancelButton": "Hủy yêu cầu xóa",
"accountDeletion.cancelConfirmTitle": "Hủy yêu cầu xóa tài khoản?",
"accountDeletion.cancelFailed": "Không thể hủy yêu cầu xóa",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "Xin lỗi vì sự cố này! Hãy đến chia sẻ với chúng tôi trong cộng đồng <0>Discord</0> và chúng tôi sẽ theo dõi.",
"accountDeletion.pendingDesc": "Tài khoản của bạn đang chờ được xóa",
"accountDeletion.pendingMessage": "Tài khoản của bạn sẽ bị xóa sau {{hours}} giờ",
+ "accountDeletion.processingMessage": "Tài khoản của bạn đang được xóa…",
"accountDeletion.reasonLabel": "Tại sao bạn rời đi?",
"accountDeletion.reasonOption.account_issue": "Vấn đề tài khoản (tài khoản trùng lặp / thay đổi email)",
"accountDeletion.reasonOption.bug": "Tôi gặp phải một lỗi cụ thể",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "Tệp hình đại diện phải nhỏ hơn 5MB.",
"workspace.general.avatar.uploadFailed": "Không thể tải lên hình đại diện",
"workspace.general.copyAgentGroups.modal.back": "Quay lại",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "Lịch sử hội thoại lớn, vì vậy hệ thống tiếp tục sao chép trong nền. Nhóm tác nhân đã sẵn sàng sử dụng; các cuộc hội thoại sẽ lần lượt hiển thị khi hoàn tất.",
"workspace.general.copyAgentGroups.modal.continue": "Tiếp tục",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "Bắt buộc. Sao chép siêu dữ liệu nhóm, thành viên, vai trò thành viên và hồ sơ Agent.",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "Cấu hình nhóm Agent",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "Quản lý tên, URL, ảnh đại diện và các cài đặt khác của không gian làm việc của bạn",
"workspace.general.title": "Chung",
"workspace.general.transferAgentGroups.modal.back": "Quay lại",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "Lịch sử hội thoại lớn, vì vậy hệ thống tiếp tục di chuyển trong nền. Nhóm tác nhân đã sẵn sàng sử dụng; các cuộc hội thoại cũ sẽ lần lượt hiển thị khi hoàn tất.",
"workspace.general.transferAgentGroups.modal.continue": "Tiếp tục",
"workspace.general.transferAgentGroups.modal.done": "Hoàn tất",
"workspace.general.transferAgentGroups.modal.failed": "Không thể chuyển nhóm đại lý",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 3bc85cf9d75..f46b1a84aaf 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "{{name}} 官方模型服务",
"about.title": "关于",
+ "accountDeletion.blockedByAgentMigration": "删除已暂停:有助手的会话历史仍在迁移中,迁移完成后会自动重试。",
+ "accountDeletion.blockedByOwnedWorkspaces": "删除已暂停:你还拥有含其他成员的工作区,请先转让所有权或删除该工作区,之后会自动重试。",
+ "accountDeletion.blockedRetrying": "删除暂未完成,稍后会自动重试。",
"accountDeletion.cancelButton": "取消注销",
"accountDeletion.cancelConfirmTitle": "取消账号注销请求?",
"accountDeletion.cancelFailed": "取消注销请求失败",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "很抱歉给您带来困扰!欢迎加入我们的 <0>Discord</0> 社区反馈该问题,我们会跟进处理。",
"accountDeletion.pendingDesc": "您的账号已被安排删除",
"accountDeletion.pendingMessage": "您的账号将于 {{hours}} 小时后删除",
+ "accountDeletion.processingMessage": "正在删除你的账号…",
"accountDeletion.reasonLabel": "您为什么要离开?",
"accountDeletion.reasonOption.account_issue": "账号问题(重复账号 / 更换邮箱)",
"accountDeletion.reasonOption.bug": "遇到了具体的 Bug",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "头像文件必须小于 5MB。",
"workspace.general.avatar.uploadFailed": "上传头像失败",
"workspace.general.copyAgentGroups.modal.back": "返回",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "历史消息较多,正在后台继续复制。群组现在即可使用;历史会话会随复制完成逐个显示。",
"workspace.general.copyAgentGroups.modal.continue": "继续",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "必选。复制组元数据、成员、成员角色和代理配置文件。",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "代理组配置",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "管理您的工作区名称、URL、头像和其他设置",
"workspace.general.title": "通用",
"workspace.general.transferAgentGroups.modal.back": "返回",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "历史消息较多,正在后台继续迁移。群组现在即可使用;历史会话会随迁移完成逐个显示。",
"workspace.general.transferAgentGroups.modal.continue": "继续",
"workspace.general.transferAgentGroups.modal.done": "完成",
"workspace.general.transferAgentGroups.modal.failed": "转移代理组失败",
diff --git a/locales/zh-TW/setting.json b/locales/zh-TW/setting.json
index e5216059237..32c3aed1133 100644
--- a/locales/zh-TW/setting.json
+++ b/locales/zh-TW/setting.json
@@ -1,6 +1,9 @@
{
"_cloud.officialProvider": "{{name}} 官方模型服務",
"about.title": "關於",
+ "accountDeletion.blockedByAgentMigration": "刪除暫停:仍有代理正在遷移其對話記錄。遷移完成後將自動重試。",
+ "accountDeletion.blockedByOwnedWorkspaces": "刪除暫停:您仍擁有一個包含其他成員的工作空間。請轉移所有權或刪除該工作空間,完成後將自動重試。",
+ "accountDeletion.blockedRetrying": "刪除尚未完成,將自動重試。",
"accountDeletion.cancelButton": "取消刪除",
"accountDeletion.cancelConfirmTitle": "確定要取消帳號刪除申請?",
"accountDeletion.cancelFailed": "取消刪除申請失敗",
@@ -16,6 +19,7 @@
"accountDeletion.divert.bug": "很抱歉!請到我們的<0>Discord</0>社群告訴我們,我們會跟進處理。",
"accountDeletion.pendingDesc": "您的帳號已排定刪除",
"accountDeletion.pendingMessage": "您的帳號將於 {{hours}} 小時後被刪除",
+ "accountDeletion.processingMessage": "您的帳戶正在刪除中…",
"accountDeletion.reasonLabel": "您為什麼要離開?",
"accountDeletion.reasonOption.account_issue": "帳戶問題(重複帳戶 / 更改電子郵件)",
"accountDeletion.reasonOption.bug": "我遇到了一個特定的錯誤",
@@ -2193,6 +2197,7 @@
"workspace.general.avatar.tooLarge": "頭像檔案必須小於 5MB。",
"workspace.general.avatar.uploadFailed": "上傳頭像失敗",
"workspace.general.copyAgentGroups.modal.back": "返回",
+ "workspace.general.copyAgentGroups.modal.backgroundCopy": "聊天記錄量較大,因此正在背景中持續複製。代理群組現在已可使用;對話將逐一完成並顯示。",
"workspace.general.copyAgentGroups.modal.continue": "繼續",
"workspace.general.copyAgentGroups.modal.copyOptions.config.desc": "必需。複製群組元數據、成員、成員角色和代理檔案。",
"workspace.general.copyAgentGroups.modal.copyOptions.config.title": "代理群組配置",
@@ -2306,6 +2311,7 @@
"workspace.general.subtitle": "管理您的工作區名稱、URL、頭像和其他設置",
"workspace.general.title": "一般",
"workspace.general.transferAgentGroups.modal.back": "返回",
+ "workspace.general.transferAgentGroups.modal.backgroundMigration": "聊天記錄量較大,因此正在背景中持續遷移。代理群組現在已可使用;舊的對話將逐一完成並顯示。",
"workspace.general.transferAgentGroups.modal.continue": "繼續",
"workspace.general.transferAgentGroups.modal.done": "完成",
"workspace.general.transferAgentGroups.modal.failed": "轉移代理群組失敗",
diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.ts
index 325eb9cc3d9..9200c55c7f4 100644
--- a/packages/database/src/models/__tests__/agent.test.ts
+++ b/packages/database/src/models/__tests__/agent.test.ts
@@ -20,8 +20,10 @@ import {
users,
workspaces,
} from '../../schemas';
+import { agentHistoryJobAgents, agentHistoryJobs } from '../../schemas/agentHistoryJob';
import type { LobeChatDatabase } from '../../type';
import { AgentModel } from '../agent';
+import { AGENT_TRANSFER_IN_PROGRESS } from '../agentTransferJob';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -64,6 +66,10 @@ const fileList2 = [
beforeEach(async () => {
await serverDB.delete(users);
+ // Jobs deliberately carry no FK onto users, so `delete(users)` leaves them
+ // behind. On the shared server DB (`singleFork`) a stray pending job would
+ // outlive this file and trip the delete guard in the next one.
+ await serverDB.delete(agentHistoryJobs);
await serverDB.insert(users).values([{ id: userId }, { id: userId2 }]);
await serverDB.insert(knowledgeBases).values([knowledgeBase, knowledgeBase2]);
await serverDB.insert(files).values([...fileList, ...fileList2]);
@@ -71,6 +77,7 @@ beforeEach(async () => {
afterEach(async () => {
await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(agentHistoryJobs);
});
describe('AgentModel', () => {
@@ -948,6 +955,44 @@ describe('AgentModel', () => {
});
describe('delete', () => {
+ it('refuses to delete an agent a pending history job still maps', async () => {
+ // A group copy's drain writes the TARGET agent id into `messages.agent_id`.
+ // Deleting that agent leaves the queue rows behind, so the drain hits a
+ // missing-agent FK and retries forever, stranding the copy as pending.
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({ title: 'Copied Member', userId })
+ .returning();
+ // A DIFFERENT source agent, so only the target-side junction guard can
+ // catch this — the source-side guard must not be what fires.
+ const [sourceAgent] = await serverDB
+ .insert(agents)
+ .values({ title: 'Copy Source', userId })
+ .returning();
+
+ const [job] = await serverDB
+ .insert(agentHistoryJobs)
+ .values({
+ agentIds: [agent.id],
+ payload: { agents: [{ newAgentId: agent.id, sourceAgentId: sourceAgent.id }] },
+ sessionIds: [],
+ sourceUserId: userId,
+ status: 'pending',
+ targetUserId: userId,
+ totalTopics: 1,
+ type: 'copy',
+ })
+ .returning({ id: agentHistoryJobs.id });
+ await serverDB.insert(agentHistoryJobAgents).values({ agentId: agent.id, jobId: job.id });
+
+ await expect(agentModel.delete(agent.id)).rejects.toThrow(AGENT_TRANSFER_IN_PROGRESS);
+
+ const stillAlive = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+ expect(stillAlive).toBeDefined();
+ });
+
it('should delete an agent and its associated session', async () => {
// Create agent and session
const [agent] = await serverDB
diff --git a/packages/database/src/models/__tests__/agentCopyJob.test.ts b/packages/database/src/models/__tests__/agentCopyJob.test.ts
index 68875f58880..6e9a5a9f4f3 100644
--- a/packages/database/src/models/__tests__/agentCopyJob.test.ts
+++ b/packages/database/src/models/__tests__/agentCopyJob.test.ts
@@ -18,6 +18,9 @@ import type { LobeChatDatabase } from '../../type';
import { idGenerator } from '../../utils/idGenerator';
import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from '../agentCopyJob';
import { processNextAgentHistoryJobTopic } from '../agentHistoryJob';
+import { AgentTransferJobModel } from '../agentTransferJob';
+import { UserModel } from '../user';
+import { WorkspaceModel } from '../workspace';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -335,6 +338,88 @@ describe('AgentCopyJobModel', () => {
await expect(agentModel.delete(source.id)).rejects.toThrow(AGENT_COPY_IN_PROGRESS);
});
+ // LOBE-12922: copy sits on the ordinary user path, so a pending copy job
+ // must never wedge an owner's workspace/account deletion the way a pending
+ // transfer does — the cloud delete flows cancel Stripe and wipe the billing
+ // rows BEFORE they reach these guards.
+ it('does not block deleting the target workspace, and self-heals the job', async () => {
+ const source = await seedSourceAgent();
+ const { jobId, topicPairs } = await seedTargetShells(source.id);
+
+ expect(await AgentTransferJobModel.hasPendingJobTouchingWorkspace(serverDB, wsId)).toBe(false);
+ await expect(new WorkspaceModel(serverDB, userId).delete(wsId)).resolves.toBeDefined();
+
+ // the target topics cascaded away with the workspace, taking the queue
+ // rows with them, so the next drain simply finalizes the job
+ expect(await serverDB.query.agentHistoryJobTopics.findMany()).toHaveLength(0);
+ await AgentCopyJobModel.drain(serverDB, jobId);
+ const [job] = await serverDB.query.agentHistoryJobs.findMany();
+ expect(job).toMatchObject({ status: 'completed', type: 'copy' });
+
+ // source history is untouched — a copy never moved it in the first place
+ const newTopicIds = new Map(topicPairs);
+ expect(
+ await serverDB.query.messages.findMany({
+ where: and(eq(messages.agentId, source.id), isNull(messages.workspaceId)),
+ }),
+ ).toHaveLength(3);
+ expect(
+ await serverDB.query.topics.findFirst({
+ where: eq(topics.id, newTopicIds.get('acj-t1')!),
+ }),
+ ).toBeUndefined();
+ });
+
+ it('does not block deleting the owner account', async () => {
+ const source = await seedSourceAgent();
+ await seedTargetShells(source.id);
+
+ expect(await AgentTransferJobModel.hasPendingJobTouchingUser(serverDB, userId)).toBe(false);
+ await expect(UserModel.deleteUser(serverDB, userId)).resolves.toBeDefined();
+ expect(await serverDB.query.users.findFirst({ where: eq(users.id, userId) })).toBeUndefined();
+ });
+
+ // LOBE-12935: a copy drives the SAME migration UI as a transfer (progress
+ // badge, topic gray-out, open-to-prioritize) and shares the same crash-
+ // recovery net. Every query behind those must stay type-agnostic; only the
+ // owner-delete guards (LOBE-12922) and the per-type drains filter by type.
+ it('stays visible to the shared migration queries while pending', async () => {
+ const source = await seedSourceAgent();
+ const { jobId, newAgent, topicPairs } = await seedTargetShells(source.id);
+ const shellId = new Map(topicPairs).get('acj-t1')!;
+
+ // progress badge + the `type` the client words its hints by
+ const progress = await AgentTransferJobModel.findPendingJobForAgent(serverDB, newAgent.id);
+ expect(progress).toMatchObject({ id: jobId, totalTopics: 2, type: 'copy' });
+
+ // gray-out set and open-to-prioritize on a queued shell
+ expect(await AgentTransferJobModel.getPendingTopicIds(serverDB, jobId)).toHaveLength(2);
+ expect(await AgentTransferJobModel.findPendingJobForTopic(serverDB, shellId)).toEqual({
+ jobId,
+ });
+ expect(await AgentTransferJobModel.prioritizeTopic(serverDB, shellId)).toBe(true);
+
+ // crash-recovery net must re-arm copy jobs too
+ expect(await AgentTransferJobModel.listPendingJobIds(serverDB)).toContain(jobId);
+
+ // and a concurrent transfer of the copy's TARGET agent stays blocked: the
+ // drain would keep writing into the scope the transfer just moved away
+ expect(await AgentTransferJobModel.hasPendingJobForAgents(serverDB, [newAgent.id])).toBe(true);
+ });
+
+ it('is not drained by the transfer driver', async () => {
+ const source = await seedSourceAgent();
+ const { jobId } = await seedTargetShells(source.id);
+
+ // running transfer logic here would rewrite the shells' scope and delete
+ // their queue rows while copying nothing
+ expect(await AgentTransferJobModel.processNextTopic(serverDB, jobId)).toEqual({ done: true });
+
+ expect(await serverDB.query.agentHistoryJobTopics.findMany()).toHaveLength(2);
+ const [job] = await serverDB.query.agentHistoryJobs.findMany();
+ expect(job).toMatchObject({ completedTopics: 0, status: 'pending' });
+ });
+
it('routes copy jobs through the type dispatcher', async () => {
const source = await seedSourceAgent();
const { jobId, topicPairs } = await seedTargetShells(source.id);
diff --git a/packages/database/src/models/__tests__/jsonbNullTest.test.ts b/packages/database/src/models/__tests__/jsonbNullTest.test.ts
index e70840a3a78..43d39f7ec94 100644
--- a/packages/database/src/models/__tests__/jsonbNullTest.test.ts
+++ b/packages/database/src/models/__tests__/jsonbNullTest.test.ts
@@ -1,19 +1,34 @@
// @vitest-environment node
-import { readdirSync, readFileSync, statSync } from 'node:fs';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
+import { findJsonbNullTests } from './jsonbNullTestGuard';
+
/**
- * Null-testing a jsonb arrow / path expression inside a WHERE clause crashes the
- * engine backing production — `rt_fetch used out-of-bounds`, SQLSTATE XX000 —
+ * `IS [NOT] NULL` applied to an *extracted* jsonb value inside a WHERE clause
+ * crashes the query planner — SQLSTATE XX000 `rt_fetch used out-of-bounds` —
* before a single row is read.
*
- * Stock Postgres runs these predicates perfectly happily, so no test against a
- * real database will ever catch one: `getDueScheduledTopics` shipped with full
- * green model tests and its cron then crashed on every tick in production for
- * days. A source-shape guard is the only thing that can hold the line, which is
- * why this asserts on the text of the query rather than on its behavior.
+ * The culprit is `pg_search` (ParadeDB BM25), not Postgres and not the hosting
+ * provider: the crash appears the moment the scanned table carries a `bm25`
+ * index and disappears when that index is dropped. Reproduced from an empty
+ * scratch table on pg_search 0.15.26. Consequences that shape this guard:
+ *
+ * - It fires at PLAN time. `EXPLAIN` alone crashes, so an empty table crashes
+ * exactly like a full one, and no amount of test data can surface it.
+ * - Stock Postgres, PGlite and any table without a bm25 index run these
+ * predicates perfectly happily — which is why every test we have stays green
+ * while production burns. `getDueScheduledTopics` shipped fully green and its
+ * cron then crashed on every tick for days.
+ * - Today's bm25 tables are `agents`, `chat_groups`, `documents`, `files`,
+ * `knowledge_bases`, `messages`, `topics`, `user_memories*` and
+ * `user_memory_persona_documents` — but that list is one migration away from
+ * growing, and a predicate written today outlives the index list. So the rule
+ * is table-independent: never write the shape at all.
+ *
+ * A source-shape guard is the only thing that can hold this line, which is why
+ * this asserts on the text of the query rather than on its behavior.
*
* The fix is always the same — COALESCE the extracted value to a sentinel:
*
@@ -21,37 +36,22 @@ import { describe, expect, it } from 'vitest';
* (metadata ->> 'x') IS NOT NULL → COALESCE(metadata ->> 'x', '') <> ''
* (metadata ->> 'x') IS DISTINCT FROM 'y' → COALESCE(metadata ->> 'x', '') <> 'y'
*
- * Prior casualties: `getLatestSpineMessageId` (#16693),
- * `getDueScheduledTopics` (#17077).
+ * …or test key existence directly, which is also GIN-friendly:
+ * `metadata ? 'x'`, `NOT COALESCE(jsonb_exists(metadata, 'x'), false)`.
+ *
+ * Prior casualties: `getLatestSpineMessageId` (#16693), `getDueScheduledTopics`
+ * (#17077), and the `->>` predicate behind #13040.
*/
-const FORBIDDEN = /(?:->>?|#>>?)[^\n]*?\b(?:IS\s+(?:NOT\s+)?NULL|IS\s+DISTINCT\s+FROM)\b/i;
// Every directory whose queries can reach production. `models` is where the
-// two known casualties lived, but a predicate is just as lethal when it is
-// hoisted into a shared util or a repository — this guard follows the code.
+// casualties lived, but a predicate is just as lethal when it is hoisted into a
+// shared util or a repository — this guard follows the code.
const SRC_DIR = path.join(import.meta.dirname, '..', '..');
const SCANNED_DIRS = ['models', 'repositories', 'utils'].map((dir) => path.join(SRC_DIR, dir));
-const sourceFiles = (dir: string): string[] =>
- readdirSync(dir).flatMap((entry) => {
- const entryPath = path.join(dir, entry);
- if (statSync(entryPath).isDirectory())
- return entry === '__tests__' ? [] : sourceFiles(entryPath);
- return entryPath.endsWith('.ts') ? [entryPath] : [];
- });
-
describe('jsonb null tests in WHERE clauses', () => {
- it('are absent from every query source — they take the production engine down', () => {
- const offenders = SCANNED_DIRS.flatMap(sourceFiles).flatMap((file) =>
- readFileSync(file, 'utf8')
- .split('\n')
- .map((line, index) => ({ file, line: line.trim(), lineNo: index + 1 }))
- // Comments are where we explain the rule, so they get to name the shape.
- .filter(
- ({ line }) => FORBIDDEN.test(line) && !line.startsWith('*') && !line.startsWith('//'),
- )
- .map(({ file, line, lineNo }) => `${path.relative(SRC_DIR, file)}:${lineNo} ${line}`),
- );
+ it('are absent from every query source — they take the query planner down', () => {
+ const offenders = findJsonbNullTests(SCANNED_DIRS, SRC_DIR);
expect(offenders).toEqual([]);
});
diff --git a/packages/database/src/models/__tests__/jsonbNullTestGuard.test.ts b/packages/database/src/models/__tests__/jsonbNullTestGuard.test.ts
new file mode 100644
index 00000000000..2bb78492fa8
--- /dev/null
+++ b/packages/database/src/models/__tests__/jsonbNullTestGuard.test.ts
@@ -0,0 +1,137 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { findJsonbNullTestsInSource } from './jsonbNullTestGuard';
+
+const sqlOf = (source: string) => findJsonbNullTestsInSource(source).map((o) => o.sql);
+
+/**
+ * The guard's own regression suite. `connector.ts` shipped the forbidden shape
+ * past a guard that was already watching the directory it lived in — the shape
+ * was simply split across three lines through an interpolated fragment, and the
+ * guard matched line by line. These lock in that it now sees through both, and
+ * — just as importantly — that it stays quiet on the safe shapes, because a
+ * guard that cries wolf gets deleted.
+ */
+describe('findJsonbNullTestsInSource', () => {
+ describe('catches', () => {
+ it('a null test written inline', () => {
+ expect(sqlOf("const p = sql`${topics.metadata} ->> 'cronJobId' IS NULL`")).toHaveLength(1);
+ });
+
+ it('the connector.ts shape: arrow in a fragment, null test at the use site', () => {
+ // The exact regression. Neither line is forbidden on its own.
+ const source = `
+ const mountedBy = sql\`\${userConnectors.metadata} ->> 'mountedByAgentId'\`;
+ const predicate = sql\`\${mountedBy} IS NULL\`;
+ `;
+ expect(sqlOf(source)).toEqual(["${userConnectors.metadata} ->> 'mountedByAgentId' IS NULL"]);
+ });
+
+ it('a fragment spliced into an OR alongside a safe comparison', () => {
+ const source = `
+ const mountedBy = sql\`\${userConnectors.metadata} ->> 'mountedByAgentId'\`;
+ or(sql\`\${mountedBy} = \${agentId}\`, sql\`\${mountedBy} IS NULL\`);
+ `;
+ expect(sqlOf(source)).toHaveLength(1);
+ });
+
+ it('a predicate that wraps across lines', () => {
+ const source = [
+ 'const p = sql`',
+ ' ${topics.metadata}',
+ " #>> '{scheduledRun,claim,expiresAt}'",
+ ' IS NOT NULL',
+ '`;',
+ ].join('\n');
+ expect(sqlOf(source)).toHaveLength(1);
+ });
+
+ it('a null test reached through a cast and a closing paren', () => {
+ const source =
+ "const p = sql`WHERE ((${t.metadata}) -> 'progress' ->> 'total')::int IS NOT NULL`";
+ expect(sqlOf(source)).toHaveLength(1);
+ });
+
+ it('IS DISTINCT FROM, banned as a precaution', () => {
+ expect(
+ sqlOf("const p = sql`${topics.metadata} ->> 'status' IS DISTINCT FROM 'done'`"),
+ ).toHaveLength(1);
+ });
+
+ it('a fragment built from another fragment', () => {
+ const source = `
+ const raw = sql\`\${t.metadata} ->> 'k'\`;
+ const cast = sql\`(\${raw})::int\`;
+ const p = sql\`\${cast} IS NULL\`;
+ `;
+ expect(sqlOf(source)).toHaveLength(1);
+ });
+ });
+
+ describe('stays quiet on', () => {
+ it('the COALESCE rewrite that replaces it', () => {
+ expect(sqlOf("const p = sql`COALESCE(${t.metadata} ->> 'copied', '') <> 'true'`")).toEqual(
+ [],
+ );
+ });
+
+ it('a bare-column null test sharing a template with an arrow in the SELECT list', () => {
+ // `topicUsage.ts` — safe: a null test over a plain column never crashes.
+ const source =
+ 'const p = sql`SELECT usage->\'tools\' AS "toolsUsage" FROM agent_operations WHERE topic_id = ${id} AND (usage IS NOT NULL OR cost IS NOT NULL)`';
+ expect(sqlOf(source)).toEqual([]);
+ });
+
+ it('an arrow whose value is compared rather than null-tested', () => {
+ expect(sqlOf("const p = sql`${t.metadata} ->> 'mountedByAgentId' = ${agentId}`")).toEqual([]);
+ });
+
+ it('key-existence operators', () => {
+ expect(sqlOf("const p = sql`${t.metadata} ? 'cronJobId'`")).toEqual([]);
+ expect(
+ sqlOf("const p = sql`NOT COALESCE(jsonb_exists(${t.metadata}, 'signal'), false)`"),
+ ).toEqual([]);
+ });
+
+ it('an aggregate that casts an arrow result and aliases it', () => {
+ const source =
+ "const p = sql`sum((COALESCE(usage, metadata->'usage')->>'cost')::numeric) AS \"cost\" FROM messages WHERE usage IS NOT NULL`";
+ expect(sqlOf(source)).toEqual([]);
+ });
+ });
+
+ describe('suppression', () => {
+ const offending = " status: sql`WHEN ${t.metadata} ->> 'total' IS NOT NULL THEN 1 END`";
+
+ it('honors a reasoned jsonb-null-test-safe comment above the template', () => {
+ const source = [
+ ' // jsonb-null-test-safe: SET target list, not a qual',
+ offending,
+ ].join('\n');
+ expect(sqlOf(source)).toEqual([]);
+ });
+
+ it('ignores the marker when no reason follows it', () => {
+ const source = [' // jsonb-null-test-safe:', offending].join('\n');
+ expect(sqlOf(source)).toHaveLength(1);
+ });
+
+ it('does not let a marker suppress a template further down the file', () => {
+ const source = [
+ ' // jsonb-null-test-safe: applies to the next one only',
+ ' const ok = sql`1 = 1`;',
+ '',
+ '',
+ '',
+ offending,
+ ].join('\n');
+ expect(sqlOf(source)).toHaveLength(1);
+ });
+ });
+
+ it('reports the line the offending template starts on', () => {
+ const source = ['// a', '// b', "const p = sql`${t.metadata} ->> 'k' IS NULL`"].join('\n');
+ expect(findJsonbNullTestsInSource(source)[0].line).toBe(3);
+ });
+});
diff --git a/packages/database/src/models/__tests__/jsonbNullTestGuard.ts b/packages/database/src/models/__tests__/jsonbNullTestGuard.ts
new file mode 100644
index 00000000000..5f5b4e210b1
--- /dev/null
+++ b/packages/database/src/models/__tests__/jsonbNullTestGuard.ts
@@ -0,0 +1,130 @@
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import path from 'node:path';
+
+/**
+ * Source scanner behind the `jsonbNullTest` guards. Lives here rather than
+ * inside the test file because the cloud repo runs the same guard over its own
+ * query surfaces and must not drift from this one — the whole reason the shape
+ * reached `connector.ts` is that only one repo had a guard at all.
+ *
+ * See `jsonbNullTest.test.ts` for what is being forbidden and why.
+ */
+
+/**
+ * An extracted jsonb value (arrow `->` / `->>`, path `#>` / `#>>`) whose very
+ * next act is a null test. Everything the operand may legally pick up in
+ * between — closing parens, `::casts` — is consumed explicitly, so the match
+ * stays anchored to *that* expression.
+ *
+ * The tight adjacency is the point. A loose `->>[^\n]*?IS NULL` also matches
+ * templates where the arrow sits in the SELECT list and an unrelated *bare
+ * column* is null-tested in the WHERE (`topicUsage.ts` does exactly this, and
+ * is safe: a NullTest over a plain column never crashes). Guards that cry wolf
+ * get suppressed, and a suppressed guard is worth nothing.
+ *
+ * `IS DISTINCT FROM` measured safe on pg_search 0.15.26 — it is banned anyway.
+ * It is one planner-hook change away from the crashing family, the COALESCE
+ * form costs nothing, and no call site uses it today.
+ */
+const FORBIDDEN =
+ /(?:->>?|#>>?)\s*(?:'[^']*'|"[^"]*"|\$\{[^{}]*\}|\w+)(?:\s*(?:\)|::\s*\w+(?:\s*\[\s*\])?))*\s*IS\s+(?:NOT\s+NULL|NULL|DISTINCT\s+FROM)\b/i;
+
+/**
+ * Escape hatch for the shapes that are textually identical but provably safe —
+ * a null test in a SELECT list, an `ORDER BY`, or an `UPDATE … SET` target, none
+ * of which are quals. Requires a reason so the next reader can re-check it:
+ *
+ * // jsonb-null-test-safe: SET target list, not a qual — never planned as a filter
+ *
+ * The reason must be on the marker's own line: `\s*` would happily run past the
+ * newline and match the first word of the code below, suppressing on a bare
+ * marker.
+ */
+const SUPPRESSION = /jsonb-null-test-safe:[^\S\n]*\S/;
+
+/** How many lines above a template a suppression comment may sit. */
+const SUPPRESSION_REACH = 3;
+
+const sourceFiles = (dir: string): string[] => {
+ let found: string[] = [];
+ for (const entry of readdirSync(dir)) {
+ const entryPath = path.join(dir, entry);
+ if (statSync(entryPath).isDirectory()) {
+ if (entry !== '__tests__') found = found.concat(sourceFiles(entryPath));
+ } else if (entryPath.endsWith('.ts') && !entryPath.endsWith('.test.ts')) {
+ found.push(entryPath);
+ }
+ }
+ return found;
+};
+
+/**
+ * `const mountedBy = sql`…`` — the fragments a later template splices in with
+ * `${mountedBy}`. Collecting these is what makes the guard see `connector.ts`'s
+ * original shape, where the arrow lived on line 76 and the null test on 78/86:
+ * neither line was forbidden on its own, which is precisely how it shipped.
+ */
+const fragmentAliases = (source: string): Map<string, string> => {
+ const aliases = new Map<string, string>();
+ for (const match of source.matchAll(
+ /(?:const|let)\s+(\w+)\s*(?::[^=]+)?=\s*sql\s*(?:<[^>]*>\s*)?`([^`]*)`/g,
+ )) {
+ aliases.set(match[1], match[2]);
+ }
+ return aliases;
+};
+
+/**
+ * Splice fragment aliases into a template. Two passes so a fragment built from
+ * another fragment still resolves; deeper nesting is not worth chasing, and the
+ * guard stays conservative by leaving anything unresolved as-is.
+ */
+const expand = (template: string, aliases: Map<string, string>): string => {
+ let out = template;
+ for (let pass = 0; pass < 2; pass += 1) {
+ out = out.replaceAll(/\$\{(\w+)\}/g, (whole, name: string) => aliases.get(name) ?? whole);
+ }
+ return out;
+};
+
+/**
+ * The scan, over one file's text. Exported so the guard's own behavior — which
+ * is the thing that failed when `connector.ts` slipped through — can be tested
+ * against fixtures instead of only against the tree it happens to be scanning.
+ */
+export const findJsonbNullTestsInSource = (source: string): { line: number; sql: string }[] => {
+ const lines = source.split('\n');
+ const aliases = fragmentAliases(source);
+ const offenders: { line: number; sql: string }[] = [];
+
+ // Whole `sql`…`` templates, newlines and all — a per-line scan cannot see a
+ // predicate that wraps, and formatting alone should never decide whether a
+ // production-crashing shape is caught.
+ for (const match of source.matchAll(/sql\s*(?:<[^>]*>\s*)?`([^`]*)`/g)) {
+ const flattened = expand(match[1], aliases).replaceAll(/\s+/g, ' ').trim();
+ if (!FORBIDDEN.test(flattened)) continue;
+
+ const line = source.slice(0, match.index).split('\n').length;
+ const suppressionWindow = lines
+ .slice(Math.max(0, line - 1 - SUPPRESSION_REACH), line)
+ .join('\n');
+ if (SUPPRESSION.test(suppressionWindow)) continue;
+
+ offenders.push({ line, sql: flattened });
+ }
+
+ return offenders;
+};
+
+const scanFile = (file: string, relativeTo: string): string[] =>
+ findJsonbNullTestsInSource(readFileSync(file, 'utf8')).map(
+ ({ line, sql }) => `${path.relative(relativeTo, file)}:${line} ${sql}`,
+ );
+
+/**
+ * Returns one `path:line sql` entry per forbidden predicate found under `dirs`.
+ * Paths are reported relative to `relativeTo` so failures read as source
+ * locations rather than absolute machine paths.
+ */
+export const findJsonbNullTests = (dirs: string[], relativeTo: string): string[] =>
+ dirs.flatMap((dir) => sourceFiles(dir)).flatMap((file) => scanFile(file, relativeTo));
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index 98b13f7e047..ef3ea413605 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -951,6 +951,16 @@ export class AgentModel {
.where(and(eq(agents.id, agentId), this.ownership()))
.for('update');
+ // The junction records every agent an unfinished job still maps, a
+ // copy's TARGET included — and a group copy's drain writes those ids into
+ // `messages.agent_id`. Deleting one leaves the queue rows behind, so the
+ // drain hits a missing-agent FK and retries forever, stranding the copied
+ // conversations as pending. Distinct from the source guard below: a copy
+ // registers only its target here.
+ if (await AgentTransferJobModel.hasPendingJobForAgents(trx, [agentId])) {
+ throw new Error(AGENT_TRANSFER_IN_PROGRESS);
+ }
+
// A pending copy job still reads this agent's topics — deleting it would
// cascade them away and the copy would silently complete with empty
// conversations. Surface the in-progress state instead.
diff --git a/packages/database/src/models/agentCopyJob.ts b/packages/database/src/models/agentCopyJob.ts
index 9ff5ff017a9..40a356c995a 100644
--- a/packages/database/src/models/agentCopyJob.ts
+++ b/packages/database/src/models/agentCopyJob.ts
@@ -4,6 +4,7 @@ import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
import type { AgentHistoryJobTopicPayload } from '../schemas';
import {
agentHistoryJobAgents,
+ agentHistoryJobGroups,
agentHistoryJobs,
agentHistoryJobTopics,
messages,
@@ -38,18 +39,27 @@ export const getAgentCopySyncMessageThreshold = (): number => {
export interface CreateAgentCopyJobParams {
/** Source→target agent pairs duplicated by this job (job payload). */
agents: { newAgentId: string; sourceAgentId: string }[];
+ /**
+ * Set for a chat-group copy: the source group being forked and the target
+ * group its conversations are re-parented onto. Its presence switches the
+ * drain to the group remap — every member agent maps through `agents`, which
+ * for a group is a MAP, not one pair.
+ */
+ group?: { newGroupId: string; sourceGroupId: string };
source: AgentTransferTargetScope;
target: AgentTransferTargetScope;
/**
* Per-topic work units. `newTopicId` is the already-created target topic
* shell (what the queue row, status polls and gray-out UI key on);
* `sourceTopicId` is where the drain copies threads/messages from.
+ * `newAgentId` / `sourceAgentId` are the agent-copy coordinates and are
+ * omitted for a group copy (see `group`).
*/
topics: {
activityAt: Date;
- newAgentId: string;
+ newAgentId?: string;
newTopicId: string;
- sourceAgentId: string;
+ sourceAgentId?: string;
sourceTopicId: string;
}[];
}
@@ -77,8 +87,10 @@ export class AgentCopyJobModel {
.insert(agentHistoryJobs)
.values({
agentIds: params.agents.map((pair) => pair.newAgentId),
- groupIds: [],
- payload: { agents: params.agents },
+ // Like `agentIds`, the junction below records the TARGET side: the
+ // badge and gray-out belong to the copied group, not the source.
+ groupIds: params.group ? [params.group.newGroupId] : [],
+ payload: { agents: params.agents, ...(params.group ? { group: params.group } : {}) },
sessionIds: [],
sourceUserId: params.source.userId,
sourceWorkspaceId: params.source.workspaceId,
@@ -94,6 +106,11 @@ export class AgentCopyJobModel {
.insert(agentHistoryJobAgents)
.values(params.agents.map((pair) => ({ agentId: pair.newAgentId, jobId: job.id })));
}
+ if (params.group) {
+ await trx
+ .insert(agentHistoryJobGroups)
+ .values({ groupId: params.group.newGroupId, jobId: job.id });
+ }
// Chunked so a pathological agent (tens of thousands of topics) cannot
// blow the Postgres per-statement parameter cap (65535; ~5 params/row).
const TOPIC_INSERT_CHUNK = 5000;
@@ -103,8 +120,8 @@ export class AgentCopyJobModel {
activityAt: topic.activityAt,
jobId: job.id,
payload: {
- newAgentId: topic.newAgentId,
- sourceAgentId: topic.sourceAgentId,
+ ...(topic.newAgentId ? { newAgentId: topic.newAgentId } : {}),
+ ...(topic.sourceAgentId ? { sourceAgentId: topic.sourceAgentId } : {}),
sourceTopicId: topic.sourceTopicId,
},
topicId: topic.newTopicId,
@@ -144,6 +161,35 @@ export class AgentCopyJobModel {
return rows.some((row) => row.payload?.agents?.some((pair) => wanted.has(pair.sourceAgentId)));
};
+ /**
+ * Group counterpart of {@link hasPendingCopyJobForSourceAgents}: does any
+ * unfinished copy job still read conversations out of one of these groups?
+ *
+ * The member-agent guard above does not cover this. A group copy queues
+ * topics by GROUP, so a group whose roster is empty (or whose members were
+ * removed after the copy started) has no agent row to match, yet its topics
+ * are still being read.
+ */
+ static hasPendingCopyJobForSourceGroups = async (
+ db: Transaction | LobeChatDatabase,
+ sourceGroupIds: string[],
+ sourceUserId?: string,
+ ): Promise<boolean> => {
+ if (sourceGroupIds.length === 0) return false;
+ const rows = await db
+ .select({ payload: agentHistoryJobs.payload })
+ .from(agentHistoryJobs)
+ .where(
+ and(
+ eq(agentHistoryJobs.status, 'pending'),
+ eq(agentHistoryJobs.type, 'copy'),
+ sourceUserId ? eq(agentHistoryJobs.sourceUserId, sourceUserId) : undefined,
+ ),
+ );
+ const wanted = new Set(sourceGroupIds);
+ return rows.some((row) => !!row.payload?.group && wanted.has(row.payload.group.sourceGroupId));
+ };
+
/**
* Drain one unit of work: claim the next pending topic (priority first, then
* most recently active) and duplicate its threads + messages into the target
@@ -185,30 +231,47 @@ export class AgentCopyJobModel {
return { done: true };
}
- // The payload TYPE requires all three coordinates, but the column holds
+ // The payload TYPE guarantees `sourceTopicId`, but the column holds
// whatever the row happens to carry — widen to Partial and re-check.
const { newAgentId, sourceAgentId, sourceTopicId }: Partial<AgentHistoryJobTopicPayload> =
next.payload ?? {};
+ const group = job.payload?.group;
const source = { userId: job.sourceUserId, workspaceId: job.sourceWorkspaceId };
const target = { userId: job.targetUserId, workspaceId: job.targetWorkspaceId };
// A queue row without copy coordinates is unrecoverable garbage — drop it
- // instead of wedging the whole job on an infinite retry.
- if (newAgentId && sourceAgentId && sourceTopicId) {
+ // instead of wedging the whole job on an infinite retry. A group unit
+ // needs only the source topic: its agent remap is the job-level map.
+ const hasCoordinates = group
+ ? !!sourceTopicId
+ : !!(newAgentId && sourceAgentId && sourceTopicId);
+ if (hasCoordinates) {
const sourceTopicExists = await AgentCopyJobModel.sourceTopicExists(
trx,
source,
- sourceTopicId,
+ sourceTopicId!,
);
if (sourceTopicExists) {
- await AgentCopyJobModel.copyTopicContents(trx, {
- newAgentId,
- newTopicId: next.topicId,
- source,
- sourceAgentId,
- sourceTopicId,
- target,
- });
+ await (group
+ ? AgentCopyJobModel.copyGroupTopicContents(trx, {
+ agentIdPairs: (job.payload?.agents ?? []).map((pair): IdPair => [
+ pair.sourceAgentId,
+ pair.newAgentId,
+ ]),
+ newGroupId: group.newGroupId,
+ newTopicId: next.topicId,
+ source,
+ sourceTopicId: sourceTopicId!,
+ target,
+ })
+ : AgentCopyJobModel.copyTopicContents(trx, {
+ newAgentId: newAgentId!,
+ newTopicId: next.topicId,
+ source,
+ sourceAgentId: sourceAgentId!,
+ sourceTopicId: sourceTopicId!,
+ target,
+ }));
} else {
// The user deleted the conversation while the copy was queued.
// Deleting is explicit intent, so it is never blocked — but leaving
@@ -391,6 +454,101 @@ export class AgentCopyJobModel {
});
};
+ /**
+ * Group variant of {@link copyTopicContents}: duplicate one source GROUP
+ * topic's threads and messages into an existing target topic shell.
+ *
+ * The remap differs in kind, not degree. An agent copy has exactly one
+ * source→target agent, so it can inline a `case when agent_id = source`
+ * expression; a group conversation carries rows from every member, so the
+ * whole `agentIdPairs` map is joined (`_amap` / `_amap_target`) and members
+ * outside it collapse to NULL. `target_id` also has the literal `'user'`
+ * sentinel to preserve. Mirrors the synchronous
+ * `AgentGroupRepository.copyGroupConversationHistory`, scoped to one topic.
+ */
+ private static copyGroupTopicContents = async (
+ trx: Transaction,
+ unit: {
+ agentIdPairs: IdPair[];
+ newGroupId: string;
+ newTopicId: string;
+ source: AgentTransferTargetScope;
+ sourceTopicId: string;
+ target: AgentTransferTargetScope;
+ },
+ ) => {
+ const sourceCtx = {
+ userId: unit.source.userId,
+ workspaceId: unit.source.workspaceId ?? undefined,
+ };
+ const agentIdMap = new Map(unit.agentIdPairs);
+ const mapAgentId = (agentId?: null | string) =>
+ agentId ? (agentIdMap.get(agentId) ?? null) : null;
+
+ const sourceThreads = await trx.query.threads.findMany({
+ orderBy: (thread, { asc }) => [asc(thread.createdAt)],
+ where: and(buildWorkspaceWhere(sourceCtx, threads), eq(threads.topicId, unit.sourceTopicId)),
+ });
+ const threadIdMap = new Map(
+ sourceThreads.map((thread) => [thread.id, idGenerator('threads', 16)]),
+ );
+
+ // Message bodies never leave the database — only ids are fetched to build
+ // the remap tables for the in-database copy.
+ const messageIdPairs: IdPair[] = (
+ await trx.query.messages.findMany({
+ columns: { id: true },
+ where: and(
+ buildWorkspaceWhere(sourceCtx, messages),
+ eq(messages.topicId, unit.sourceTopicId),
+ ),
+ })
+ ).map(({ id }) => [id, idGenerator('messages')]);
+ const messageIdMap = new Map(messageIdPairs);
+
+ if (sourceThreads.length > 0) {
+ const { fixups: threadFixups, rows: threadRows } = splitCrossBatchSelfReferences(
+ sourceThreads.map((thread) => ({
+ ...thread,
+ agentId: mapAgentId(thread.agentId),
+ clientId: null,
+ groupId: unit.newGroupId,
+ id: threadIdMap.get(thread.id)!,
+ parentThreadId: thread.parentThreadId
+ ? (threadIdMap.get(thread.parentThreadId) ?? null)
+ : null,
+ sourceMessageId: thread.sourceMessageId
+ ? (messageIdMap.get(thread.sourceMessageId) ?? null)
+ : null,
+ topicId: unit.newTopicId,
+ userId: unit.target.userId,
+ workspaceId: unit.target.workspaceId,
+ })),
+ ['parentThreadId'],
+ );
+
+ await insertInBatches(threadRows, (batch) => trx.insert(threads).values(batch));
+
+ for (const fixup of threadFixups) {
+ await trx.update(threads).set(fixup.patch).where(eq(threads.id, fixup.id));
+ }
+ }
+
+ await copyMessagesInDatabase({
+ agentIdExpr: sql`_amap.new_id`,
+ agentIdPairs: unit.agentIdPairs,
+ executor: trx,
+ groupId: unit.newGroupId,
+ messageIdPairs,
+ childScope: (table) => buildWorkspaceWhere(sourceCtx, table),
+ targetIdExpr: sql`case when ${messages.targetId} = 'user' then ${messages.targetId} else _amap_target.new_id end`,
+ targetUserId: unit.target.userId,
+ targetWorkspaceId: unit.target.workspaceId,
+ threadIdPairs: [...threadIdMap.entries()],
+ topicIdPairs: [[unit.sourceTopicId, unit.newTopicId]],
+ });
+ };
+
/**
* Run a copy job to completion. In-process drivers call this; step-based
* drivers (workflows) call `processNextTopic` directly.
diff --git a/packages/database/src/models/agentTransferJob.ts b/packages/database/src/models/agentTransferJob.ts
index dda9cc68231..1311d06d9b0 100644
--- a/packages/database/src/models/agentTransferJob.ts
+++ b/packages/database/src/models/agentTransferJob.ts
@@ -2,6 +2,7 @@ import { and, desc, eq, inArray, isNull, or, type SQL, sql } from 'drizzle-orm';
import {
agentHistoryJobAgents,
+ agentHistoryJobGroups,
agentHistoryJobs,
agentHistoryJobTopics,
messageChunks,
@@ -135,9 +136,52 @@ export const rewriteResidualMessageScope = async (
}
};
+/**
+ * The owner-delete guards below match ONLY pending `transfer` jobs.
+ *
+ * A transfer re-homes existing rows, so between the synchronous half and the
+ * drain the message snapshot columns still point at the other side — deleting
+ * either side would cascade away history that already belongs elsewhere. That
+ * is worth blocking a delete for, and the window is minutes.
+ *
+ * A `copy` job never moves an existing row: the source stays intact and the
+ * target is a fresh duplicate, so a delete on either side can only cost a
+ * half-finished copy. Both directions also self-heal:
+ *
+ * - source gone → the per-topic drain's `sourceTopicExists` check fails and
+ * `deleteEmptyTargetTopic` drops the empty shell (same path as the user
+ * deleting the conversation mid-copy, which is likewise never blocked);
+ * - target gone → `agent_history_job_topics.topic_id` cascades with the target
+ * topics, so the queue empties and the next drain flips the job `completed`.
+ *
+ * Blocking on copy jobs is therefore pure cost: copy sits on the ordinary user
+ * path (importing a heavy agent into a workspace), so it would let any member
+ * wedge an owner's workspace/account deletion — after the caller has already
+ * cancelled Stripe and wiped the billing rows. See LOBE-12922.
+ */
+const isPendingTransfer = () =>
+ and(eq(agentHistoryJobs.status, 'pending'), eq(agentHistoryJobs.type, 'transfer'));
+
export interface CreateAgentTransferJobParams {
+ /**
+ * Agents this job covers: one junction row each, which is what the guards
+ * and the progress badge read. NOT automatically the residual linkage — see
+ * `residualAgentIds`.
+ */
agentIds: string[];
groupIds?: string[];
+ /**
+ * Agent linkage for the final topicless-residual rewrite; defaults to
+ * `agentIds`.
+ *
+ * A GROUP transfer passes `[]`. Its synchronous half rewrites residual
+ * messages by group only — a member agent's own topicless rows are not the
+ * group's to move (the group transfer does not move that agent's own topics
+ * either). Letting the drain fall back to `agentIds` would make a heavy
+ * group transfer move strictly more than a small one: exactly the fast/slow
+ * drift this framework exists to avoid.
+ */
+ residualAgentIds?: string[];
sessionIds: string[];
source: AgentTransferTargetScope;
target: AgentTransferTargetScope;
@@ -170,7 +214,9 @@ export class AgentTransferJobModel {
const [job] = await trx
.insert(agentHistoryJobs)
.values({
- agentIds: params.agentIds,
+ // The COLUMN is the residual-rewrite snapshot the drain reads back;
+ // the junction below is the coverage set. They differ for a group job.
+ agentIds: params.residualAgentIds ?? params.agentIds,
groupIds: params.groupIds ?? [],
sessionIds: params.sessionIds,
sourceUserId: params.source.userId,
@@ -186,6 +232,11 @@ export class AgentTransferJobModel {
.insert(agentHistoryJobAgents)
.values(params.agentIds.map((agentId) => ({ agentId, jobId: job.id })));
}
+ if (params.groupIds && params.groupIds.length > 0) {
+ await trx
+ .insert(agentHistoryJobGroups)
+ .values(params.groupIds.map((groupId) => ({ groupId, jobId: job.id })));
+ }
// Chunked so a pathological agent (tens of thousands of topics) cannot
// blow the Postgres per-statement parameter cap (65535; 4 params/row).
const TOPIC_INSERT_CHUNK = 5000;
@@ -201,7 +252,16 @@ export class AgentTransferJobModel {
return job.id;
};
- /** Any of the agents already covered by an unfinished job? */
+ /**
+ * Any of the agents already covered by an unfinished job?
+ *
+ * Type-agnostic on purpose. A `copy` registers its NEW agent here, and that
+ * agent is exactly the one a concurrent transfer must not move: the copy's
+ * drain keeps writing history into the scope the transfer just rewrote, so
+ * the conversation ends up split across both scopes. Exempting `copy` from
+ * the OWNER-DELETE guards (LOBE-12922) is a separate judgement — it does not
+ * extend to agent mutations.
+ */
static hasPendingJobForAgents = async (
db: Transaction | LobeChatDatabase,
agentIds: string[],
@@ -222,9 +282,39 @@ export class AgentTransferJobModel {
};
/**
- * A pending job still references this owner (as source or target). Deleting
- * the owner now would cascade away message rows whose snapshot columns have
- * not been rewritten yet.
+ * Any of the chat groups already covered by an unfinished job?
+ *
+ * Not redundant with {@link hasPendingJobForAgents}: a group's guard cannot
+ * lean on its member agents alone, because a group with an empty roster
+ * registers no agent rows and would slip through unguarded.
+ *
+ * Type-agnostic for the same reason as {@link hasPendingJobForAgents}.
+ */
+ static hasPendingJobForGroups = async (
+ db: Transaction | LobeChatDatabase,
+ groupIds: string[],
+ ): Promise<boolean> => {
+ if (groupIds.length === 0) return false;
+ const [row] = await db
+ .select({ jobId: agentHistoryJobGroups.jobId })
+ .from(agentHistoryJobGroups)
+ .innerJoin(agentHistoryJobs, eq(agentHistoryJobs.id, agentHistoryJobGroups.jobId))
+ .where(
+ and(
+ inArray(agentHistoryJobGroups.groupId, groupIds),
+ eq(agentHistoryJobs.status, 'pending'),
+ ),
+ )
+ .limit(1);
+ return !!row;
+ };
+
+ /**
+ * A pending TRANSFER job still references this owner (as source or target).
+ * Deleting the owner now would cascade away message rows whose snapshot
+ * columns have not been rewritten yet.
+ *
+ * `copy` jobs are deliberately excluded — see {@link isPendingTransfer}.
*/
static hasPendingJobTouchingUser = async (
db: Transaction | LobeChatDatabase,
@@ -235,7 +325,7 @@ export class AgentTransferJobModel {
.from(agentHistoryJobs)
.where(
and(
- eq(agentHistoryJobs.status, 'pending'),
+ isPendingTransfer(),
or(eq(agentHistoryJobs.sourceUserId, userId), eq(agentHistoryJobs.targetUserId, userId)),
),
)
@@ -243,6 +333,7 @@ export class AgentTransferJobModel {
return !!row;
};
+ /** Workspace counterpart of {@link hasPendingJobTouchingUser}. */
static hasPendingJobTouchingWorkspace = async (
db: Transaction | LobeChatDatabase,
workspaceId: string,
@@ -252,7 +343,7 @@ export class AgentTransferJobModel {
.from(agentHistoryJobs)
.where(
and(
- eq(agentHistoryJobs.status, 'pending'),
+ isPendingTransfer(),
or(
eq(agentHistoryJobs.sourceWorkspaceId, workspaceId),
eq(agentHistoryJobs.targetWorkspaceId, workspaceId),
@@ -263,6 +354,14 @@ export class AgentTransferJobModel {
return !!row;
};
+ /**
+ * Progress of the job covering this agent, for the migration badge.
+ *
+ * Deliberately NOT filtered to `type = 'transfer'` — the same reason spelled
+ * out on {@link findPendingJobForGroup}: a heavy agent COPY drives the very
+ * same badge and topic gray-out, and the returned `type` is what the client
+ * words its progress hints by.
+ */
static findPendingJobForAgent = async (
db: LobeChatDatabase,
agentId: string,
@@ -284,6 +383,36 @@ export class AgentTransferJobModel {
return row;
};
+ /**
+ * Group counterpart of {@link findPendingJobForAgent}, for the group badge.
+ *
+ * Deliberately NOT filtered to `type = 'transfer'`: a group's badge, topic
+ * gray-out and pending-topic gating must cover a heavy group COPY as well —
+ * its queue rows point at freshly created topic shells that would otherwise
+ * render as empty, writable conversations. The returned `type` is what the
+ * UI words its progress hints by.
+ */
+ static findPendingJobForGroup = async (
+ db: LobeChatDatabase,
+ groupId: string,
+ ): Promise<AgentTransferJobProgress | undefined> => {
+ const [row] = await db
+ .select({
+ completedTopics: agentHistoryJobs.completedTopics,
+ id: agentHistoryJobs.id,
+ status: agentHistoryJobs.status,
+ totalTopics: agentHistoryJobs.totalTopics,
+ type: agentHistoryJobs.type,
+ })
+ .from(agentHistoryJobGroups)
+ .innerJoin(agentHistoryJobs, eq(agentHistoryJobs.id, agentHistoryJobGroups.jobId))
+ .where(
+ and(eq(agentHistoryJobGroups.groupId, groupId), eq(agentHistoryJobs.status, 'pending')),
+ )
+ .limit(1);
+ return row;
+ };
+
/**
* Topic ids of a pending job that still await rewrite (UI gray-out set).
*
@@ -310,7 +439,12 @@ export class AgentTransferJobModel {
return rows.map((row) => row.topicId);
};
- /** Is this topic still awaiting its scope rewrite under a pending job? */
+ /**
+ * Is this topic still awaiting its rewrite under a pending job?
+ *
+ * Type-agnostic: this backs open-to-prioritize, and a copy's queued topic
+ * shell needs jumping the queue just as much as a transfer's.
+ */
static findPendingJobForTopic = async (
db: LobeChatDatabase,
topicId: string,
@@ -330,6 +464,9 @@ export class AgentTransferJobModel {
* Jump-the-queue: the user opened a topic that is still pending, so the next
* `processNextTopic` call picks it first. Returns whether a pending row was
* actually flagged (false → the topic already migrated; caller can refetch).
+ *
+ * Type-agnostic, like {@link findPendingJobForTopic} which selects the job
+ * this then kicks.
*/
static prioritizeTopic = async (db: LobeChatDatabase, topicId: string): Promise<boolean> => {
const rows = await db
@@ -376,7 +513,11 @@ export class AgentTransferJobModel {
.where(eq(agentHistoryJobs.id, jobId))
.for('update')
.limit(1);
- if (!job || job.status === 'completed') return { done: true };
+ // Mirror of `AgentCopyJobModel.processNextTopic`'s own type check: running
+ // transfer logic over a `copy` job would rewrite the scope of its target
+ // topics and drop their queue rows, reporting success against history it
+ // never duplicated (see the `type` column's schema comment).
+ if (!job || job.type !== 'transfer' || job.status === 'completed') return { done: true };
const target = { userId: job.targetUserId, workspaceId: job.targetWorkspaceId };
@@ -396,7 +537,13 @@ export class AgentTransferJobModel {
await trx
.update(agentHistoryJobs)
.set({ completedAt: new Date(), status: 'completed' })
- .where(and(eq(agentHistoryJobs.id, jobId), eq(agentHistoryJobs.status, 'pending')));
+ .where(
+ and(
+ eq(agentHistoryJobs.id, jobId),
+ eq(agentHistoryJobs.status, 'pending'),
+ eq(agentHistoryJobs.type, 'transfer'),
+ ),
+ );
return { done: true };
}
@@ -434,6 +581,9 @@ export class AgentTransferJobModel {
const rows = await db
.select({ id: agentHistoryJobs.id })
.from(agentHistoryJobs)
+ // Type-agnostic: the drivers this feeds dispatch by job type
+ // (`processNextAgentHistoryJobTopic`), so restricting it to `transfer`
+ // would strand every crashed `copy` job as permanently pending.
.where(eq(agentHistoryJobs.status, 'pending'));
return rows.map((row) => row.id);
};
diff --git a/packages/database/src/models/asyncTask.ts b/packages/database/src/models/asyncTask.ts
index 63a7ebf0bc2..3cc3b829210 100644
--- a/packages/database/src/models/asyncTask.ts
+++ b/packages/database/src/models/asyncTask.ts
@@ -102,6 +102,11 @@ export class AsyncTaskModel {
true
)
`,
+ // Verified on pg_search 0.15.26: `UPDATE … SET`, SELECT lists and ORDER
+ // BY all survive a null test over an extracted jsonb value; only quals
+ // (WHERE / JOIN ON / HAVING) crash the planner. `async_tasks` carries no
+ // bm25 index either. See the block comment above `TopicModel`.
+ // jsonb-null-test-safe: SET target list, not a qual
status: sql`
CASE
WHEN ${asyncTasks.status} = ${AsyncTaskStatus.Error} OR ${asyncTasks.error} IS NOT NULL
diff --git a/packages/database/src/models/connector.ts b/packages/database/src/models/connector.ts
index aaa26a2f80d..d8c50946f95 100644
--- a/packages/database/src/models/connector.ts
+++ b/packages/database/src/models/connector.ts
@@ -73,9 +73,13 @@ export class ConnectorModel {
* rows are candidates.
*/
private scopePredicate = (agentId?: string) => {
- const mountedBy = sql`${userConnectors.metadata} ->> 'mountedByAgentId'`;
+ // COALESCE'd to a sentinel rather than null-tested: `->> … IS NULL` in a
+ // WHERE clause is one bm25 index on `user_connectors` away from taking every
+ // caller down at plan time. See the note on `TopicModel`. `''` is a safe
+ // sentinel — a mount reference is always a real agent id, never empty.
+ const mountedBy = sql`COALESCE(${userConnectors.metadata} ->> 'mountedByAgentId', '')`;
if (!agentId) {
- return and(this.ownership(), isNull(userConnectors.agentId), sql`${mountedBy} IS NULL`);
+ return and(this.ownership(), isNull(userConnectors.agentId), sql`${mountedBy} = ''`);
}
return and(
this.ownership(),
@@ -83,7 +87,7 @@ export class ConnectorModel {
eq(userConnectors.agentId, agentId),
and(
isNull(userConnectors.agentId),
- or(sql`${mountedBy} = ${agentId}`, sql`${mountedBy} IS NULL`),
+ or(sql`${mountedBy} = ${agentId}`, sql`${mountedBy} = ''`),
),
),
);
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index 698e5e0cc47..1193f5d4a03 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -206,17 +206,31 @@ const buildTopicOrderBy = (topicActivityAt: SQL, sortBy?: TopicQuerySortBy): SQL
* ```sql
* (metadata ->> 'cronJobId') IS NULL -- 💥
* (metadata #>> '{a,b}') IS NOT NULL -- 💥
- * (metadata ->> 'status') IS DISTINCT FROM 'done' -- 💥
* ```
*
- * The engine backing production is not stock Postgres, and this query *shape*
- * crashes it outright — `rt_fetch used out-of-bounds`, SQLSTATE XX000, thrown
- * before any row is read (a table with zero matching rows crashes just the same,
- * so no test on real Postgres will ever catch it). Drizzle then reports it as a
- * bare `Failed query:`, with the real cause only in the driver's `[cause]`.
+ * The crash is `pg_search`'s (ParadeDB BM25) planner hook, and it fires on any
+ * table carrying a `bm25` index: `rt_fetch used out-of-bounds`, SQLSTATE XX000.
+ * Drizzle reports it as a bare `Failed query:`, with the real cause only in the
+ * driver's `[cause]`. Four properties make it uniquely nasty:
+ *
+ * - It fires at PLAN time. `EXPLAIN` alone crashes, so a table with zero
+ * matching rows crashes exactly like a full one.
+ * - Stock Postgres, PGlite, and any table *without* a bm25 index run these
+ * predicates happily — no test we can write will ever catch it.
+ * - It has nothing to do with jsonb. `upper(col) IS NULL` and `(id + 1) IS NULL`
+ * crash identically; the trigger is a null test over a *computed expression*
+ * in a qual. A null test over a bare column is fine.
+ * - Only quals crash — WHERE, JOIN ON, HAVING, and the WHERE of a subquery, CTE,
+ * UPDATE or DELETE. SELECT lists, ORDER BY and `UPDATE … SET` targets are safe.
+ *
+ * `topics` and `messages` carry bm25 indexes today, but so do `agents`, `files`,
+ * `documents`, `chat_groups`, `knowledge_bases` and every `user_memories*`
+ * table — and that list is one migration away from growing. A predicate written
+ * today outlives the index list, so the rule is table-independent: never write
+ * the shape.
*
* COALESCE the extracted value to a sentinel instead — same semantics, a shape
- * the engine survives:
+ * the planner survives:
*
* ```sql
* COALESCE(metadata ->> 'cronJobId', '') = '' -- "is null"
@@ -224,9 +238,14 @@ const buildTopicOrderBy = (topicActivityAt: SQL, sortBy?: TopicQuerySortBy): SQL
* COALESCE(metadata ->> 'status', '') <> 'done' -- IS DISTINCT FROM
* ```
*
- * This has now bitten twice: `getLatestSpineMessageId` (#16693) and
- * `getDueScheduledTopics` (#17077 — the scheduled-run cron crashed on every tick
- * from the day it shipped, so rate-limit continuations never once resumed).
+ * (`IS DISTINCT FROM` measured safe on pg_search 0.15.26, but the guard bans it
+ * anyway — it sits one planner-hook change from the crashing family and the
+ * COALESCE form costs nothing.)
+ *
+ * This has now bitten three times: #13040, `getLatestSpineMessageId` (#16693)
+ * and `getDueScheduledTopics` (#17077 — the scheduled-run cron crashed on every
+ * tick from the day it shipped, so rate-limit continuations never once resumed).
+ * `jsonbNullTest.test.ts` is the source-shape guard that holds the line.
*/
export class TopicModel {
private userId: string;
diff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.ts
index 06bc97656b9..6c5500e5f8a 100644
--- a/packages/database/src/models/user.ts
+++ b/packages/database/src/models/user.ts
@@ -344,10 +344,12 @@ export class UserModel {
};
static deleteUser = async (db: LobeChatDatabase, id: string) => {
- // A pending agent-transfer backfill means message rows moved to (or from)
+ // A pending agent-TRANSFER backfill means message rows moved to (or from)
// this user still carry the other side's scope snapshot; cascading the
- // delete now would destroy history the transfer already re-homed. The job
- // window is minutes — the delete can simply be retried after it drains.
+ // delete now would destroy history the transfer already re-homed. Transfer
+ // is admin-initiated and drains in minutes — the delete can simply be
+ // retried afterwards. Pending `copy` jobs do not block: they duplicate
+ // rather than move, and both sides self-heal (see `isPendingTransfer`).
if (await AgentTransferJobModel.hasPendingJobTouchingUser(db, id)) {
throw new Error(AGENT_TRANSFER_PENDING_OWNER_DELETE);
}
diff --git a/packages/database/src/models/workspace.ts b/packages/database/src/models/workspace.ts
index ca39db95d3f..33e7468e72e 100644
--- a/packages/database/src/models/workspace.ts
+++ b/packages/database/src/models/workspace.ts
@@ -97,10 +97,11 @@ export class WorkspaceModel {
};
delete = async (id: string) => {
- // See UserModel.deleteUser: while an agent-transfer backfill still points
+ // See UserModel.deleteUser: while an agent-TRANSFER backfill still points
// at this workspace (as source or target), unmigrated message snapshots
// would be cascade-deleted with it. Reject and let the caller retry after
- // the job drains.
+ // the job drains. Pending `copy` jobs do not block — see
+ // `isPendingTransfer` in agentTransferJob.ts.
if (await AgentTransferJobModel.hasPendingJobTouchingWorkspace(this.db, id)) {
throw new Error(AGENT_TRANSFER_PENDING_OWNER_DELETE);
}
diff --git a/packages/database/src/repositories/agentGroup/__tests__/groupHistoryJob.test.ts b/packages/database/src/repositories/agentGroup/__tests__/groupHistoryJob.test.ts
new file mode 100644
index 00000000000..569f3b8a4e2
--- /dev/null
+++ b/packages/database/src/repositories/agentGroup/__tests__/groupHistoryJob.test.ts
@@ -0,0 +1,407 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from '../../../models/agentCopyJob';
+import {
+ AGENT_TRANSFER_IN_PROGRESS,
+ AgentTransferJobModel,
+} from '../../../models/agentTransferJob';
+import {
+ agentHistoryJobGroups,
+ agentHistoryJobs,
+ agents,
+ chatGroups,
+ chatGroupsAgents,
+ messagePlugins,
+ messages,
+ threads,
+ topics,
+ users,
+ workspaces,
+} from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { AgentGroupRepository } from '../index';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'ghj-user';
+const wsId = 'ghj-ws';
+const groupId = 'ghj-group';
+const supervisorId = 'ghj-supervisor';
+const memberId = 'ghj-member';
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }]);
+ await serverDB
+ .insert(workspaces)
+ .values([{ id: wsId, name: 'WS', primaryOwnerId: userId, slug: 'ghj-ws' }]);
+});
+
+afterEach(async () => {
+ delete process.env.AGENT_TRANSFER_SYNC_MESSAGE_THRESHOLD;
+ delete process.env.AGENT_COPY_SYNC_MESSAGE_THRESHOLD;
+ await serverDB.delete(users);
+ // Jobs deliberately carry no FK onto users, so clean them up explicitly.
+ await serverDB.delete(agentHistoryJobs);
+});
+
+/**
+ * Personal group with a supervisor + one member, two topics, a thread, four
+ * group messages (one with a plugin child row, one addressed to the member
+ * agent, one addressed to `'user'`) and one topicless residual message.
+ */
+const seedGroupWithHistory = async () => {
+ await serverDB.insert(agents).values([
+ { id: supervisorId, title: 'Supervisor', userId, virtual: true },
+ { id: memberId, title: 'Member', userId },
+ ]);
+ await serverDB.insert(chatGroups).values([{ id: groupId, title: 'Team', userId }]);
+ await serverDB.insert(chatGroupsAgents).values([
+ { agentId: supervisorId, chatGroupId: groupId, order: -1, role: 'supervisor', userId },
+ { agentId: memberId, chatGroupId: groupId, order: 0, role: 'participant', userId },
+ ]);
+
+ await serverDB.insert(topics).values([
+ { agentId: supervisorId, groupId, id: 'ghj-t1', title: 't1', userId },
+ { agentId: supervisorId, groupId, id: 'ghj-t2', title: 't2', userId },
+ ]);
+ await serverDB.insert(threads).values([
+ {
+ agentId: memberId,
+ groupId,
+ id: 'ghj-th1',
+ title: 'thread',
+ topicId: 'ghj-t1',
+ type: 'continuation',
+ userId,
+ },
+ ]);
+ await serverDB.insert(messages).values([
+ {
+ agentId: supervisorId,
+ content: 'hi',
+ groupId,
+ id: 'ghj-m1',
+ role: 'user',
+ targetId: 'user',
+ topicId: 'ghj-t1',
+ userId,
+ },
+ {
+ agentId: memberId,
+ content: 'out',
+ groupId,
+ id: 'ghj-m2',
+ role: 'tool',
+ targetId: memberId,
+ topicId: 'ghj-t1',
+ userId,
+ },
+ // topic-only row: no agent linkage, still belongs to the group's history
+ { content: 'a', groupId, id: 'ghj-m3', role: 'assistant', topicId: 'ghj-t1', userId },
+ {
+ agentId: memberId,
+ content: 'x',
+ groupId,
+ id: 'ghj-m4',
+ role: 'user',
+ topicId: 'ghj-t2',
+ userId,
+ },
+ // residual: group-linked but topicless
+ { agentId: supervisorId, content: 'r', groupId, id: 'ghj-m5', role: 'user', userId },
+ ]);
+ await serverDB
+ .insert(messagePlugins)
+ .values([{ id: 'ghj-m2', identifier: 'test-plugin', toolCallId: 'call_1', userId }]);
+};
+
+const scopeOf = async (messageId: string) => {
+ const row = await serverDB.query.messages.findFirst({ where: eq(messages.id, messageId) });
+ return { userId: row?.userId, workspaceId: row?.workspaceId ?? null };
+};
+
+const ALL_MESSAGE_IDS = ['ghj-m1', 'ghj-m2', 'ghj-m3', 'ghj-m4', 'ghj-m5'];
+
+describe('group transfer fast path (small history)', () => {
+ it('rewrites group messages, topic-only rows and child tables inline', async () => {
+ await seedGroupWithHistory();
+
+ const result = await new AgentGroupRepository(serverDB, userId).transferToWorkspace(
+ groupId,
+ wsId,
+ userId,
+ );
+ expect(result).toEqual({ groupId, transferJobId: null });
+ expect(await serverDB.query.agentHistoryJobs.findMany()).toHaveLength(0);
+
+ for (const id of ALL_MESSAGE_IDS) {
+ expect((await scopeOf(id)).workspaceId).toBe(wsId);
+ }
+ const plugin = await serverDB.query.messagePlugins.findFirst({
+ where: eq(messagePlugins.id, 'ghj-m2'),
+ });
+ expect(plugin?.workspaceId).toBe(wsId);
+ });
+});
+
+describe('group transfer slow path (async backfill job)', () => {
+ beforeEach(() => {
+ process.env.AGENT_TRANSFER_SYNC_MESSAGE_THRESHOLD = '2';
+ });
+
+ it('records a group-keyed job, defers messages, and drains topic-by-topic', async () => {
+ await seedGroupWithHistory();
+
+ const result = await new AgentGroupRepository(serverDB, userId).transferToWorkspace(
+ groupId,
+ wsId,
+ userId,
+ );
+ expect(result!.transferJobId).not.toBeNull();
+
+ // the group and its topics moved synchronously; messages did not
+ const group = await serverDB.query.chatGroups.findFirst({ where: eq(chatGroups.id, groupId) });
+ expect(group?.workspaceId).toBe(wsId);
+ const topic = await serverDB.query.topics.findFirst({ where: eq(topics.id, 'ghj-t1') });
+ expect(topic?.workspaceId).toBe(wsId);
+ expect((await scopeOf('ghj-m1')).workspaceId).toBeNull();
+
+ // the group junction is what the badge/gray-out UI looks the job up by
+ const junction = await serverDB
+ .select()
+ .from(agentHistoryJobGroups)
+ .where(eq(agentHistoryJobGroups.groupId, groupId));
+ expect(junction).toHaveLength(1);
+
+ const job = await AgentTransferJobModel.findPendingJobForGroup(serverDB, groupId);
+ expect(job).toMatchObject({ completedTopics: 0, totalTopics: 2, type: 'transfer' });
+ expect(await AgentTransferJobModel.getPendingTopicIds(serverDB, job!.id)).toHaveLength(2);
+
+ await AgentTransferJobModel.drain(serverDB, result!.transferJobId!);
+
+ for (const id of ALL_MESSAGE_IDS) {
+ expect((await scopeOf(id)).workspaceId).toBe(wsId);
+ }
+ const plugin = await serverDB.query.messagePlugins.findFirst({
+ where: eq(messagePlugins.id, 'ghj-m2'),
+ });
+ expect(plugin?.workspaceId).toBe(wsId);
+
+ const [finished] = await serverDB.query.agentHistoryJobs.findMany();
+ expect(finished).toMatchObject({ completedTopics: 2, status: 'completed', totalTopics: 2 });
+ expect(await AgentTransferJobModel.findPendingJobForGroup(serverDB, groupId)).toBeUndefined();
+ });
+
+ it('orders the drain by pre-transfer activity, not by transfer time', async () => {
+ await seedGroupWithHistory();
+ // t1 is the most recently active conversation before the move
+ await serverDB
+ .update(topics)
+ .set({ updatedAt: new Date('2020-01-01') })
+ .where(eq(topics.id, 'ghj-t2'));
+
+ const result = await new AgentGroupRepository(serverDB, userId).transferToWorkspace(
+ groupId,
+ wsId,
+ userId,
+ );
+
+ // The ownership UPDATE stamps every topic with the same `updatedAt`; the
+ // queue must still carry the ORIGINAL activity so t1 drains first.
+ const first = await AgentTransferJobModel.processNextTopic(serverDB, result!.transferJobId!);
+ expect(first).toMatchObject({ done: false, topicId: 'ghj-t1' });
+ });
+
+ it('rejects a second transfer of the same group while the job is pending', async () => {
+ await seedGroupWithHistory();
+ const result = await new AgentGroupRepository(serverDB, userId).transferToWorkspace(
+ groupId,
+ wsId,
+ userId,
+ );
+
+ await expect(
+ new AgentGroupRepository(serverDB, userId, wsId).transferToWorkspace(groupId, null, userId),
+ ).rejects.toThrow(AGENT_TRANSFER_IN_PROGRESS);
+
+ await AgentTransferJobModel.drain(serverDB, result!.transferJobId!);
+ await expect(
+ new AgentGroupRepository(serverDB, userId, wsId).transferToWorkspace(groupId, null, userId),
+ ).resolves.toBeTruthy();
+ });
+
+ it("leaves a member agent's own topicless messages alone, exactly like the sync path", async () => {
+ await seedGroupWithHistory();
+ // A member agent that is also used on its own: a topicless message linked
+ // to the agent but NOT to the group. The synchronous branch rewrites the
+ // residual by group only, so the slow path must not move it either —
+ // otherwise a heavy group transfer moves strictly more than a small one.
+ await serverDB
+ .insert(messages)
+ .values([{ agentId: memberId, content: 'solo', id: 'ghj-solo', role: 'user', userId }]);
+
+ const result = await new AgentGroupRepository(serverDB, userId).transferToWorkspace(
+ groupId,
+ wsId,
+ userId,
+ );
+ await AgentTransferJobModel.drain(serverDB, result!.transferJobId!);
+
+ expect((await scopeOf('ghj-solo')).workspaceId).toBeNull();
+ // ...while the group's own topicless residual did move
+ expect((await scopeOf('ghj-m5')).workspaceId).toBe(wsId);
+ });
+
+ it('guards an empty-roster group, which has no member agent to match on', async () => {
+ await seedGroupWithHistory();
+ await serverDB.delete(chatGroupsAgents).where(eq(chatGroupsAgents.chatGroupId, groupId));
+
+ const result = await new AgentGroupRepository(serverDB, userId).transferToWorkspace(
+ groupId,
+ wsId,
+ userId,
+ );
+ expect(result!.transferJobId).not.toBeNull();
+
+ await expect(
+ new AgentGroupRepository(serverDB, userId, wsId).transferToWorkspace(groupId, null, userId),
+ ).rejects.toThrow(AGENT_TRANSFER_IN_PROGRESS);
+ });
+});
+
+describe('group copy fast path (small history)', () => {
+ it('duplicates topics, threads and messages inline', async () => {
+ await seedGroupWithHistory();
+
+ const copied = await new AgentGroupRepository(serverDB, userId).copyToWorkspace(
+ groupId,
+ wsId,
+ userId,
+ { includeConversationHistory: true },
+ );
+ expect(copied!.copyJobId).toBeNull();
+
+ const copiedMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.groupId, copied!.groupId));
+ // the four topic-anchored rows; the topicless residual is not copied
+ expect(copiedMessages).toHaveLength(4);
+ expect(await serverDB.query.agentHistoryJobs.findMany()).toHaveLength(0);
+ });
+});
+
+describe('group copy slow path (async copy job)', () => {
+ beforeEach(() => {
+ process.env.AGENT_COPY_SYNC_MESSAGE_THRESHOLD = '2';
+ });
+
+ it('creates empty topic shells, then fills them with the group remap applied', async () => {
+ await seedGroupWithHistory();
+
+ const copied = await new AgentGroupRepository(serverDB, userId).copyToWorkspace(
+ groupId,
+ wsId,
+ userId,
+ { includeConversationHistory: true },
+ );
+ expect(copied!.copyJobId).not.toBeNull();
+
+ // shells exist and are usable immediately; their history is still empty
+ const shells = await serverDB.select().from(topics).where(eq(topics.groupId, copied!.groupId));
+ expect(shells).toHaveLength(2);
+ expect(
+ await serverDB.select().from(messages).where(eq(messages.groupId, copied!.groupId)),
+ ).toHaveLength(0);
+
+ // the copied group carries the badge, keyed by the NEW group
+ const job = await AgentTransferJobModel.findPendingJobForGroup(serverDB, copied!.groupId);
+ expect(job).toMatchObject({ totalTopics: 2, type: 'copy' });
+
+ await AgentCopyJobModel.drain(serverDB, copied!.copyJobId!);
+
+ const copiedMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.groupId, copied!.groupId));
+ expect(copiedMessages).toHaveLength(4);
+ // every copied row landed in the target scope
+ expect(copiedMessages.every((row) => row.workspaceId === wsId)).toBe(true);
+
+ // agent remap: the source member agent maps onto its copy, `'user'`
+ // survives as the literal sentinel, and an unmapped agent becomes NULL.
+ const newAgentIds = new Set(
+ (await serverDB.select().from(agents).where(eq(agents.workspaceId, wsId))).map(
+ (row) => row.id,
+ ),
+ );
+ const copiedToolRow = copiedMessages.find((row) => row.role === 'tool')!;
+ expect(newAgentIds.has(copiedToolRow.agentId!)).toBe(true);
+ expect(copiedToolRow.agentId).not.toBe(memberId);
+ expect(newAgentIds.has(copiedToolRow.targetId!)).toBe(true);
+ expect(
+ copiedMessages.find((row) => row.role === 'user' && row.topicId === shells[0].id),
+ ).toBeDefined();
+ expect(copiedMessages.some((row) => row.targetId === 'user')).toBe(true);
+
+ // threads follow their topic onto the new group
+ const copiedThreads = await serverDB
+ .select()
+ .from(threads)
+ .where(eq(threads.groupId, copied!.groupId));
+ expect(copiedThreads).toHaveLength(1);
+
+ // the source is untouched
+ for (const id of ALL_MESSAGE_IDS) {
+ expect(await scopeOf(id)).toEqual({ userId, workspaceId: null });
+ }
+ expect(
+ await AgentTransferJobModel.findPendingJobForGroup(serverDB, copied!.groupId),
+ ).toBeUndefined();
+ });
+
+ it('rejects a second copy of the same source group while one is pending', async () => {
+ await seedGroupWithHistory();
+ const repo = new AgentGroupRepository(serverDB, userId);
+ const copied = await repo.copyToWorkspace(groupId, wsId, userId, {
+ includeConversationHistory: true,
+ });
+
+ await expect(
+ repo.copyToWorkspace(groupId, wsId, userId, { includeConversationHistory: true }),
+ ).rejects.toThrow(AGENT_COPY_IN_PROGRESS);
+
+ // ...and blocks moving the source out from under the pending copy
+ await expect(repo.transferToWorkspace(groupId, wsId, userId)).rejects.toThrow(
+ AGENT_COPY_IN_PROGRESS,
+ );
+
+ await AgentCopyJobModel.drain(serverDB, copied!.copyJobId!);
+ await expect(
+ repo.copyToWorkspace(groupId, wsId, userId, { includeConversationHistory: true }),
+ ).resolves.toBeTruthy();
+ });
+
+ it('drops a shell whose source conversation was deleted mid-copy', async () => {
+ await seedGroupWithHistory();
+ const copied = await new AgentGroupRepository(serverDB, userId).copyToWorkspace(
+ groupId,
+ wsId,
+ userId,
+ { includeConversationHistory: true },
+ );
+
+ await serverDB.delete(topics).where(eq(topics.id, 'ghj-t2'));
+ await AgentCopyJobModel.drain(serverDB, copied!.copyJobId!);
+
+ const shells = await serverDB.select().from(topics).where(eq(topics.groupId, copied!.groupId));
+ expect(shells).toHaveLength(1);
+ // progress still reaches its total instead of stalling on the missing unit
+ const [finished] = await serverDB.query.agentHistoryJobs.findMany();
+ expect(finished).toMatchObject({ completedTopics: 2, status: 'completed', totalTopics: 2 });
+ });
+});
diff --git a/packages/database/src/repositories/agentGroup/index.test.ts b/packages/database/src/repositories/agentGroup/index.test.ts
index 56b9ca0e60e..0edc18318e9 100644
--- a/packages/database/src/repositories/agentGroup/index.test.ts
+++ b/packages/database/src/repositories/agentGroup/index.test.ts
@@ -1,9 +1,10 @@
// @vitest-environment node
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { eq } from 'drizzle-orm';
-import { beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
+import { AGENT_TRANSFER_IN_PROGRESS } from '../../models/agentTransferJob';
import { ChatGroupModel } from '../../models/chatGroup';
import {
TOPIC_COMMENT_TOPIC_NOT_FOUND,
@@ -11,6 +12,7 @@ import {
TopicCommentModel,
} from '../../models/topicComment';
import { agents } from '../../schemas/agent';
+import { agentHistoryJobAgents, agentHistoryJobs } from '../../schemas/agentHistoryJob';
import { chatGroups, chatGroupsAgents } from '../../schemas/chatGroup';
import { messagePlugins, messages } from '../../schemas/message';
import { threads, topics } from '../../schemas/topic';
@@ -31,6 +33,11 @@ const isServerDB = process.env.TEST_SERVER_DB === '1';
beforeEach(async () => {
// Clean up
await serverDB.delete(users);
+ // Jobs deliberately carry no FK onto users, so `delete(users)` leaves them
+ // behind. On the shared server DB (`singleFork`) a stray pending job would
+ // outlive this file and trip the transfer/removal guards in the next one.
+ await serverDB.delete(agentHistoryJobs);
+ delete process.env.AGENT_COPY_SYNC_MESSAGE_THRESHOLD;
// Create test users
await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
@@ -39,6 +46,10 @@ beforeEach(async () => {
agentGroupRepo = new AgentGroupRepository(serverDB, userId);
});
+afterEach(async () => {
+ await serverDB.delete(agentHistoryJobs);
+});
+
describe('AgentGroupRepository', () => {
describe('findByIdWithAgents', () => {
it('should return group with its agents (including auto-created supervisor)', async () => {
@@ -914,6 +925,43 @@ describe('AgentGroupRepository', () => {
});
expect(virtualAgents).toHaveLength(0);
});
+
+ it('refuses to remove a member a pending copy job is still writing into', async () => {
+ // The copy junction records the TARGET agent. Deleting that agent now
+ // cascades the row the drain is about to reference, so its next message
+ // insert violates `messages.agent_id` and the job retries forever —
+ // leaving the copied conversations stranded as pending.
+ const [job] = await serverDB
+ .insert(agentHistoryJobs)
+ .values({
+ agentIds: ['remove-virtual'],
+ payload: { agents: [{ newAgentId: 'remove-virtual', sourceAgentId: 'keep-agent' }] },
+ sessionIds: [],
+ sourceUserId: userId,
+ status: 'pending',
+ targetUserId: userId,
+ totalTopics: 1,
+ type: 'copy',
+ })
+ .returning({ id: agentHistoryJobs.id });
+ await serverDB
+ .insert(agentHistoryJobAgents)
+ .values({ agentId: 'remove-virtual', jobId: job.id });
+
+ await expect(
+ agentGroupRepo.removeAgentsFromGroup('remove-group', ['remove-virtual']),
+ ).rejects.toThrow(AGENT_TRANSFER_IN_PROGRESS);
+
+ // Nothing was removed or deleted — the guard aborted the whole transaction.
+ const stillLinked = await serverDB.query.chatGroupsAgents.findMany({
+ where: (cga, { eq }) => eq(cga.chatGroupId, 'remove-group'),
+ });
+ expect(stillLinked).toHaveLength(3);
+ const stillAlive = await serverDB.query.agents.findFirst({
+ where: (a, { eq }) => eq(a.id, 'remove-virtual'),
+ });
+ expect(stillAlive).toBeDefined();
+ });
});
describe('duplicate', () => {
@@ -1622,6 +1670,48 @@ describe('AgentGroupRepository', () => {
expect(mention.workspaceId).toBe(targetWorkspaceId);
});
+ it('aborts when the group leaves the source scope before the lock is taken', async () => {
+ // The scope check runs outside the transaction. A racing transfer small
+ // enough to take the fast path leaves no pending job behind, so the
+ // guards cannot catch it — only re-asserting the scope inside the lock
+ // can. Simulate that window: the pre-read reports the group as in-scope,
+ // but the committed row already belongs to someone else.
+ const raceTargetWorkspaceId = 'agent-group-race-ws';
+ await serverDB.insert(workspaces).values({
+ id: raceTargetWorkspaceId,
+ name: 'Race Target Workspace',
+ primaryOwnerId: userId,
+ slug: 'agent-group-race-ws',
+ });
+ await serverDB.insert(chatGroups).values({
+ id: 'moved-group',
+ title: 'Moved Group',
+ userId: otherUserId,
+ });
+
+ const staleRead = vi
+ .spyOn(serverDB.query.chatGroups, 'findFirst')
+ .mockResolvedValueOnce({ id: 'moved-group', title: 'Moved Group', userId } as never);
+
+ try {
+ const result = await agentGroupRepo.transferToWorkspace(
+ 'moved-group',
+ raceTargetWorkspaceId,
+ userId,
+ );
+ expect(result).toBeNull();
+ } finally {
+ staleRead.mockRestore();
+ }
+
+ // Untouched: no second transfer ran off the stale state.
+ const group = await serverDB.query.chatGroups.findFirst({
+ where: (cg, { eq }) => eq(cg.id, 'moved-group'),
+ });
+ expect(group!.userId).toBe(otherUserId);
+ expect(group!.workspaceId).toBeNull();
+ });
+
it('flags teammate-authored comments as foreign transfer rows', async () => {
await serverDB.insert(chatGroups).values({
id: 'guard-group',
@@ -2008,6 +2098,13 @@ describe('AgentGroupRepository', () => {
workspaceId,
});
+ // This case exercises the SYNCHRONOUS copy's batching, so the fast/slow
+ // threshold is lifted above the seeded volume — otherwise a history this
+ // large would be deferred to a copy job and nothing would be inserted
+ // inline (the async path has its own coverage in
+ // `__tests__/groupHistoryJob.test.ts`).
+ process.env.AGENT_COPY_SYNC_MESSAGE_THRESHOLD = '100000';
+
// 2401 rows × 31 `messages` columns ≈ 74k bind parameters — above the
// 65,535 cap, so the pre-fix unbatched INSERT provably fails here.
const messageCount = 2401;
diff --git a/packages/database/src/repositories/agentGroup/index.ts b/packages/database/src/repositories/agentGroup/index.ts
index 688df60c898..af8c8e94695 100644
--- a/packages/database/src/repositories/agentGroup/index.ts
+++ b/packages/database/src/repositories/agentGroup/index.ts
@@ -1,12 +1,17 @@
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import type { AgentGroupDetail, AgentGroupMember, AgentPluginEntry } from '@lobechat/types';
import { cleanObject } from '@lobechat/utils';
-import { and, asc, eq, inArray, ne, not, sql } from 'drizzle-orm';
+import { and, asc, count, eq, inArray, ne, not, or, sql } from 'drizzle-orm';
-import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from '../../models/agentCopyJob';
+import {
+ AGENT_COPY_IN_PROGRESS,
+ AgentCopyJobModel,
+ getAgentCopySyncMessageThreshold,
+} from '../../models/agentCopyJob';
import {
AGENT_TRANSFER_IN_PROGRESS,
AgentTransferJobModel,
+ getAgentTransferSyncMessageThreshold,
rewriteMessageScopeForTopics,
rewriteResidualMessageScope,
} from '../../models/agentTransferJob';
@@ -40,6 +45,12 @@ import { idGenerator } from '../../utils/idGenerator';
import { normalizeInboxAgentMeta } from '../../utils/inboxAgent';
import { buildWorkspaceWhere } from '../../utils/workspace';
+/**
+ * Copy-with-history rejected: the source group left this scope between the
+ * ownership read and the row lock (a concurrent transfer committed).
+ */
+export const AGENT_GROUP_COPY_SOURCE_MOVED = 'AGENT_GROUP_COPY_SOURCE_MOVED';
+
interface CopyAgentGroupToWorkspaceOptions {
includeConversationHistory?: boolean;
newTitle?: string;
@@ -153,6 +164,21 @@ export class AgentGroupRepository {
workspaceId: targetWorkspaceId,
});
+ /**
+ * Duplicate a group's conversations into the freshly created target group,
+ * under the same fast/slow split as the agent copy path:
+ *
+ * - ≤ threshold — topics, threads and messages all copy inside the caller's
+ * transaction; behavior identical to the historical synchronous path.
+ * - \> threshold — only the topic SHELLS are created here; thread + message
+ * duplication becomes a `copy` history job drained one topic at a time
+ * (see `AgentCopyJobModel`). Inserting a message row maintains every
+ * message index including the multi-GB BM25 one (~5ms/row in production),
+ * so a heavy group would otherwise hold a pooled connection for minutes.
+ *
+ * Returns the job id when the slow path was taken; the caller kicks the job
+ * driver AFTER its transaction commits.
+ */
private copyGroupConversationHistory = async ({
agentIdMap,
executor,
@@ -167,7 +193,7 @@ export class AgentGroupRepository {
sourceGroupId: string;
targetUserId: string;
targetWorkspaceId: string | null;
- }) => {
+ }): Promise<{ copyJobId: string | null }> => {
const mapAgentId = (agentId?: null | string) =>
agentId ? (agentIdMap.get(agentId) ?? null) : null;
@@ -176,11 +202,51 @@ export class AgentGroupRepository {
where: and(this.topicOwnership(), eq(topics.groupId, sourceGroupId)),
});
- if (sourceTopics.length === 0) return;
+ if (sourceTopics.length === 0) return { copyJobId: null };
const sourceTopicIds = sourceTopics.map((topic) => topic.id);
const topicIdMap = new Map(sourceTopics.map((topic) => [topic.id, idGenerator('topics')]));
+ const [{ sourceMessages }] = await executor
+ .select({ sourceMessages: count() })
+ .from(messages)
+ .where(and(this.messageOwnership(), inArray(messages.topicId, sourceTopicIds)));
+
+ // Topic shells go in on both paths — they are what makes the copied group
+ // usable immediately, and what the queue rows / gray-out UI key on.
+ await insertInBatches(
+ sourceTopics.map((topic) => ({
+ ...topic,
+ ...COPIED_TOPIC_USAGE_RESET,
+ agentId: mapAgentId(topic.agentId),
+ clientId: null,
+ groupId: newGroupId,
+ id: topicIdMap.get(topic.id),
+ sessionId: null,
+ userId: targetUserId,
+ workspaceId: targetWorkspaceId,
+ })),
+ (batch) => executor.insert(topics).values(batch),
+ );
+
+ if (sourceMessages > getAgentCopySyncMessageThreshold()) {
+ const copyJobId = await AgentCopyJobModel.createJob(executor, {
+ agents: [...agentIdMap.entries()].map(([sourceAgentId, newAgentId]) => ({
+ newAgentId,
+ sourceAgentId,
+ })),
+ group: { newGroupId, sourceGroupId },
+ source: { userId: this.userId, workspaceId: this.workspaceId ?? null },
+ target: { userId: targetUserId, workspaceId: targetWorkspaceId },
+ topics: sourceTopics.map((topic) => ({
+ activityAt: topic.updatedAt ?? topic.createdAt ?? new Date(),
+ newTopicId: topicIdMap.get(topic.id)!,
+ sourceTopicId: topic.id,
+ })),
+ });
+ return { copyJobId };
+ }
+
const sourceThreads = await executor.query.threads.findMany({
orderBy: (thread, { asc }) => [asc(thread.createdAt)],
where: and(this.threadOwnership(), inArray(threads.topicId, sourceTopicIds)),
@@ -202,21 +268,6 @@ export class AgentGroupRepository {
const messageIdMap = new Map(messageIdPairs);
- await insertInBatches(
- sourceTopics.map((topic) => ({
- ...topic,
- ...COPIED_TOPIC_USAGE_RESET,
- agentId: mapAgentId(topic.agentId),
- clientId: null,
- groupId: newGroupId,
- id: topicIdMap.get(topic.id),
- sessionId: null,
- userId: targetUserId,
- workspaceId: targetWorkspaceId,
- })),
- (batch) => executor.insert(topics).values(batch),
- );
-
if (sourceThreads.length > 0) {
const { fixups: threadFixups, rows: threadRows } = splitCrossBatchSelfReferences(
sourceThreads.map((thread) => ({
@@ -261,6 +312,8 @@ export class AgentGroupRepository {
threadIdPairs: [...threadIdMap.entries()],
topicIdPairs: [...topicIdMap.entries()],
});
+
+ return { copyJobId: null };
};
/**
@@ -580,33 +633,68 @@ export class AgentGroupRepository {
const { virtualAgents } = await this.checkAgentsBeforeRemoval(groupId, agentIds);
const virtualAgentIds = virtualAgents.map((a) => a.id);
- // 2. Remove all agents from the group (batch delete from junction table).
- // Scope by the caller's ownership so a client-supplied groupId can only touch
- // the caller's own junction rows — never another user's group membership (IDOR).
- const removed = await this.db
- .delete(chatGroupsAgents)
- .where(
- and(
- eq(chatGroupsAgents.chatGroupId, groupId),
- inArray(chatGroupsAgents.agentId, agentIds),
- this.groupAgentOwnership(),
- ),
- )
- .returning({ agentId: chatGroupsAgents.agentId });
-
- // 3. Delete virtual agents if requested
- // Note: Virtual agents are standalone (no associated sessions), so we can delete them directly
- // The messages sent by these agents in the group chat will remain (orphaned agentId reference)
- if (deleteVirtualAgents && virtualAgentIds.length > 0) {
- await this.db
- .delete(agents)
- .where(and(this.agentOwnership(), inArray(agents.id, virtualAgentIds)));
- }
+ return this.db.transaction(async (trx) => {
+ // Lock-then-guard, same order as `transferToWorkspace`: take the member
+ // rows before consulting the job tables so a concurrent enqueue cannot
+ // slip its job row in after the guard reads and before the delete lands.
+ await trx
+ .select({ id: agents.id })
+ .from(agents)
+ .where(and(inArray(agents.id, agentIds), this.agentOwnership()))
+ .orderBy(asc(agents.id))
+ .for('update');
- return {
- deletedVirtualAgentIds: deleteVirtualAgents ? virtualAgentIds : [],
- removedFromGroup: removed.length,
- };
+ // An unfinished backfill maps message rows onto these agent ids. Both
+ // junctions record the TARGET side, so this catches removing an agent a
+ // pending copy is still writing into — its drain would insert
+ // `messages.agent_id` against a row this delete just cascaded away, and
+ // the FK violation would retry forever, stranding the conversations as
+ // pending. The group guard additionally covers an empty roster, which
+ // registers no agent rows at all.
+ if (
+ (await AgentTransferJobModel.hasPendingJobForAgents(trx, agentIds)) ||
+ (await AgentTransferJobModel.hasPendingJobForGroups(trx, [groupId]))
+ ) {
+ throw new Error(AGENT_TRANSFER_IN_PROGRESS);
+ }
+ // Copy jobs register only their TARGET side above; guard the source too,
+ // or deleting a virtual member would cascade away the very messages a
+ // pending copy is still reading from.
+ if (
+ (await AgentCopyJobModel.hasPendingCopyJobForSourceAgents(trx, agentIds)) ||
+ (await AgentCopyJobModel.hasPendingCopyJobForSourceGroups(trx, [groupId]))
+ ) {
+ throw new Error(AGENT_COPY_IN_PROGRESS);
+ }
+
+ // 2. Remove all agents from the group (batch delete from junction table).
+ // Scope by the caller's ownership so a client-supplied groupId can only touch
+ // the caller's own junction rows — never another user's group membership (IDOR).
+ const removed = await trx
+ .delete(chatGroupsAgents)
+ .where(
+ and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ inArray(chatGroupsAgents.agentId, agentIds),
+ this.groupAgentOwnership(),
+ ),
+ )
+ .returning({ agentId: chatGroupsAgents.agentId });
+
+ // 3. Delete virtual agents if requested
+ // Note: Virtual agents are standalone (no associated sessions), so we can delete them directly
+ // The messages sent by these agents in the group chat will remain (orphaned agentId reference)
+ if (deleteVirtualAgents && virtualAgentIds.length > 0) {
+ await trx
+ .delete(agents)
+ .where(and(this.agentOwnership(), inArray(agents.id, virtualAgentIds)));
+ }
+
+ return {
+ deletedVirtualAgentIds: deleteVirtualAgents ? virtualAgentIds : [],
+ removedFromGroup: removed.length,
+ };
+ });
}
/**
@@ -854,6 +942,23 @@ export class AgentGroupRepository {
if (!sourceGroup) return null;
return this.db.transaction(async (trx) => {
+ // Lock the group row first: it is the one serialization point every
+ // group-level operation shares, including for a group whose roster is
+ // empty (where the member-agent locks below are a no-op).
+ //
+ // The lock re-asserts the source scope rather than matching by id alone,
+ // for the same reason as the copy path below: the scope check above ran
+ // outside this transaction, and a racing transfer small enough to take
+ // the fast path leaves no pending job behind for the guards to catch —
+ // it just moves the group away. An id-only lock would let the loser wake
+ // up and transfer it a second time from stale topic state.
+ const [lockedSource] = await trx
+ .select({ id: chatGroups.id })
+ .from(chatGroups)
+ .where(and(eq(chatGroups.id, groupId), this.groupOwnership()))
+ .for('update');
+ if (!lockedSource) return null;
+
const memberRows = await trx
.select({ agentId: chatGroupsAgents.agentId })
.from(chatGroupsAgents)
@@ -872,13 +977,22 @@ export class AgentGroupRepository {
.orderBy(asc(agents.id))
.for('update');
}
- if (await AgentTransferJobModel.hasPendingJobForAgents(trx, agentIds)) {
+ // Both guards are needed: the agent one catches a member agent migrating
+ // on its own, the group one catches this group's own backfill (and is
+ // the ONLY one that fires when the roster is empty).
+ if (
+ (await AgentTransferJobModel.hasPendingJobForAgents(trx, agentIds)) ||
+ (await AgentTransferJobModel.hasPendingJobForGroups(trx, [groupId]))
+ ) {
throw new Error(AGENT_TRANSFER_IN_PROGRESS);
}
- // Copy jobs register only their TARGET agents in the junction; guard the
- // source side too, or a transfer would move the topics a pending copy is
- // still reading from.
- if (await AgentCopyJobModel.hasPendingCopyJobForSourceAgents(trx, agentIds)) {
+ // Copy jobs register only their TARGET agents/group in the junctions;
+ // guard the source side too, or a transfer would move the topics a
+ // pending copy is still reading from.
+ if (
+ (await AgentCopyJobModel.hasPendingCopyJobForSourceAgents(trx, agentIds)) ||
+ (await AgentCopyJobModel.hasPendingCopyJobForSourceGroups(trx, [groupId]))
+ ) {
throw new Error(AGENT_COPY_IN_PROGRESS);
}
@@ -947,12 +1061,17 @@ export class AgentGroupRepository {
.where(inArray(agentLabelAssignments.agentId, agentIds));
}
- await trx
- .select({ id: topics.id })
+ // `updatedAt` is read here, BEFORE the ownership update: the update below
+ // does not preserve it, so `$onUpdate` stamps every group topic with the
+ // same instant. The async backfill drains most-recently-active first, and
+ // that ordering has to come from real activity, not from transfer time.
+ const lockedTopics = await trx
+ .select({ id: topics.id, updatedAt: topics.updatedAt })
.from(topics)
.where(eq(topics.groupId, groupId))
.orderBy(asc(topics.id))
.for('update');
+ const activityAtByTopic = new Map(lockedTopics.map((topic) => [topic.id, topic.updatedAt]));
if (
options.rejectForeignTopicCommentAuthors &&
@@ -981,32 +1100,67 @@ export class AgentGroupRepository {
.where(inArray(threads.topicId, movedTopicIds));
}
- // Message scope rewrite — always inline for group transfers. Unlike
- // AgentModel.transferAgents, groups have no async-backfill UX yet (the
- // migration status endpoint, pending-topic gating, and prioritize flow
- // are all keyed to agent conversations), so a queued group topic would
- // open as an empty, writable history with no explanation. Keep group
- // transfers synchronous until group-aware gating exists; the group
- // surface is far smaller than the workspace agent-migration path the
- // async job was built for.
+ // Message scope rewrite — same fast/slow split as
+ // `AgentModel.transferAgents`: rewriting a message row maintains every
+ // message index (incl. the multi-GB BM25 index), so a heavy group's
+ // history cannot be rewritten inside this transaction. Above the
+ // threshold it becomes an async backfill job drained topic-by-topic, and
+ // the group conversation surface gates the un-migrated topics
+ // (`features/AgentTransferMigration`, keyed by `groupId`).
const targetScope = { userId: targetUserId, workspaceId: targetWorkspaceId };
- await rewriteMessageScopeForTopics(trx, movedTopicIds, targetScope);
- await rewriteResidualMessageScope(
- trx,
- { agentIds: [], groupIds: [groupId], sessionIds: [] },
- targetScope,
- );
+ const groupMessages = inArray(messages.groupId, [groupId]);
+ const [{ affectedMessages }] = await trx
+ .select({ affectedMessages: count() })
+ .from(messages)
+ .where(
+ movedTopicIds.length > 0
+ ? or(inArray(messages.topicId, movedTopicIds), groupMessages)
+ : groupMessages,
+ );
- return { groupId, transferJobId: null };
+ let transferJobId: string | null = null;
+ if (affectedMessages <= getAgentTransferSyncMessageThreshold()) {
+ await rewriteMessageScopeForTopics(trx, movedTopicIds, targetScope);
+ await rewriteResidualMessageScope(
+ trx,
+ { agentIds: [], groupIds: [groupId], sessionIds: [] },
+ targetScope,
+ );
+ } else {
+ transferJobId = await AgentTransferJobModel.createJob(trx, {
+ agentIds,
+ groupIds: [groupId],
+ // Must mirror the synchronous branch above exactly: residual by
+ // GROUP only. Member agents are covered (junction rows above) for
+ // the guards and the badge, but their own topicless messages are
+ // not part of what a group transfer moves.
+ residualAgentIds: [],
+ sessionIds: [],
+ source: { userId: this.userId, workspaceId: this.workspaceId ?? null },
+ target: targetScope,
+ topics: movedTopics.map((topic) => ({
+ activityAt: activityAtByTopic.get(topic.id) ?? topic.updatedAt,
+ id: topic.id,
+ })),
+ });
+ }
+
+ return { groupId, transferJobId };
});
}
+ /**
+ * Fork a group into another scope. With `includeConversationHistory`, a
+ * heavy group defers its thread/message duplication to a `copy` history job
+ * and returns its id — the caller must kick the job driver after the
+ * transaction commits, or the copy stalls until the resume safety net runs.
+ */
async copyToWorkspace(
groupId: string,
targetWorkspaceId: string | null,
targetUserId: string,
optionsOrNewTitle?: CopyAgentGroupToWorkspaceOptions | string,
- ): Promise<{ groupId: string; supervisorAgentId: string } | null> {
+ ): Promise<{ copyJobId: string | null; groupId: string; supervisorAgentId: string } | null> {
const options =
typeof optionsOrNewTitle === 'string'
? { newTitle: optionsOrNewTitle }
@@ -1038,6 +1192,28 @@ export class AgentGroupRepository {
targetWorkspaceId && options.targetVisibility ? options.targetVisibility : undefined;
return this.db.transaction(async (trx) => {
+ if (options.includeConversationHistory) {
+ // Lock-then-guard on the SOURCE group, mirroring the agent copy path.
+ // The lock re-asserts the source scope rather than matching by id
+ // alone: a transfer small enough to run inline leaves no pending job
+ // to catch, yet moves the group out of this scope entirely, and an
+ // id-only lock would happily queue a copy against now-stale topic ids.
+ const [lockedSource] = await trx
+ .select({ id: chatGroups.id })
+ .from(chatGroups)
+ .where(and(eq(chatGroups.id, groupId), this.groupOwnership()))
+ .for('update');
+ if (!lockedSource) throw new Error(AGENT_GROUP_COPY_SOURCE_MOVED);
+
+ // A pending transfer still owns this group's message rewrite: its
+ // topics would be copied mid-migration, and the copy's own drain would
+ // race the transfer's over the same rows.
+ if (await AgentTransferJobModel.hasPendingJobForGroups(trx, [groupId]))
+ throw new Error(AGENT_TRANSFER_IN_PROGRESS);
+ if (await AgentCopyJobModel.hasPendingCopyJobForSourceGroups(trx, [groupId], this.userId))
+ throw new Error(AGENT_COPY_IN_PROGRESS);
+ }
+
const [newGroup] = await trx
.insert(chatGroups)
.values({
@@ -1120,18 +1296,19 @@ export class AgentGroupRepository {
agentIdMap.set(sourceAgentId, newAgentId);
}
- if (options.includeConversationHistory) {
- await this.copyGroupConversationHistory({
- agentIdMap,
- executor: trx,
- newGroupId: newGroup.id,
- sourceGroupId: groupId,
- targetUserId,
- targetWorkspaceId,
- });
- }
+ const { copyJobId } = options.includeConversationHistory
+ ? await this.copyGroupConversationHistory({
+ agentIdMap,
+ executor: trx,
+ newGroupId: newGroup.id,
+ sourceGroupId: groupId,
+ targetUserId,
+ targetWorkspaceId,
+ })
+ : { copyJobId: null };
return {
+ copyJobId,
groupId: newGroup.id,
supervisorAgentId: newSupervisor.id,
};
diff --git a/packages/database/src/schemas/agentHistoryJob.ts b/packages/database/src/schemas/agentHistoryJob.ts
index 15b30a44c9e..ed00f92161f 100644
--- a/packages/database/src/schemas/agentHistoryJob.ts
+++ b/packages/database/src/schemas/agentHistoryJob.ts
@@ -32,16 +32,16 @@ export interface AgentHistoryJobPayload {
group?: { newGroupId: string; sourceGroupId: string };
}
-/**
- * `copy` queue-row payload. Required for the same reason as above: the drain
- * treats a unit missing any coordinate as unrecoverable and drops it, so a
- * row that exists at all must be complete.
- */
+/** `copy` queue-row payload. */
export interface AgentHistoryJobTopicPayload {
- /** Agent owning the target topic shell. */
- newAgentId: string;
- /** Agent the source topic belongs to. */
- sourceAgentId: string;
+ /**
+ * Agent owning the target topic shell. Agent copies always carry it; group
+ * copies leave it out — a group topic's agent remap is the job-level
+ * `agents` map, not one pair.
+ */
+ newAgentId?: string;
+ /** Agent the source topic belongs to. Absent for group copies, same reason. */
+ sourceAgentId?: string;
/** Topic to copy messages/threads from. */
sourceTopicId: string;
}
diff --git a/packages/database/src/utils/copiedTranscript.ts b/packages/database/src/utils/copiedTranscript.ts
index d79aee508c7..a1a165348c6 100644
--- a/packages/database/src/utils/copiedTranscript.ts
+++ b/packages/database/src/utils/copiedTranscript.ts
@@ -27,11 +27,11 @@ import { messages } from '../schemas';
* key, COALESCE to `''` → kept.
*
* The COALESCE is NOT cosmetic. Null-testing a jsonb arrow expression in a
- * WHERE clause (`metadata ->> 'copied' IS DISTINCT FROM 'true'`) crashes the
- * non-stock engine backing production outright — SQLSTATE XX000
- * `rt_fetch used out-of-bounds`, thrown before any row is read, so no test on
- * real Postgres can catch it. See the block comment above `TopicModel` for the
- * two incidents that established this rule.
+ * WHERE clause crashes `pg_search`'s planner hook on any table carrying a bm25
+ * index — SQLSTATE XX000 `rt_fetch used out-of-bounds`, thrown at plan time
+ * before any row is read, so no test can catch it. `messages` carries one.
+ * See the block comment above `TopicModel` for the mechanism and the incidents
+ * that established this rule.
*/
export const notCopiedTranscript = () =>
sql`coalesce(${messages.metadata} ->> 'copied', '') <> 'true'`;
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index d1ec6b4004d..7f3450d5e82 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -35,8 +35,15 @@ export default {
'You may not need to delete your account — you can change your email or link more sign-in methods in <0>Profile Settings</0>.',
'accountDeletion.divert.bug':
'Sorry about that! Come tell us in our <0>Discord</0> community and we’ll follow up.',
+ 'accountDeletion.blockedByAgentMigration':
+ 'Deletion is paused: an agent is still migrating its conversation history. It will retry automatically once the migration finishes.',
+ 'accountDeletion.blockedByOwnedWorkspaces':
+ 'Deletion is paused: you still own a workspace with other members. Transfer ownership or delete the workspace, and it will retry automatically.',
+ 'accountDeletion.blockedRetrying':
+ 'Deletion could not be completed yet and will retry automatically.',
'accountDeletion.pendingDesc': 'Your account is scheduled for deletion',
'accountDeletion.pendingMessage': 'Your account will be deleted in {{hours}} hours',
+ 'accountDeletion.processingMessage': 'Your account is being deleted…',
'accountDeletion.reasonLabel': 'Why are you leaving?',
'accountDeletion.reasonOption.account_issue':
'Account issues (duplicate account / changing email)',
@@ -2384,6 +2391,8 @@ When I am ___, I need ___
'workspace.general.copyTargetLabel': 'Copy to',
'workspace.general.transferTargetLabel': 'Move to',
'workspace.general.transferAgentGroups.modal.back': 'Back',
+ 'workspace.general.transferAgentGroups.modal.backgroundMigration':
+ 'Chat history is large, so it keeps migrating in the background. The agent group is ready to use now; older conversations light up one by one as they finish.',
'workspace.general.transferAgentGroups.modal.continue': 'Continue',
'workspace.general.transferAgentGroups.modal.done': 'Done',
'workspace.general.transferAgentGroups.modal.failed': 'Failed to transfer agent groups',
@@ -2441,6 +2450,8 @@ When I am ___, I need ___
'workspace.general.copyLobeAI.modal.title': 'Copy Agents',
'workspace.general.copyLobeAI.modal.untitledAgent': 'Untitled Agent',
'workspace.general.copyAgentGroups.modal.back': 'Back',
+ 'workspace.general.copyAgentGroups.modal.backgroundCopy':
+ 'Chat history is large, so it keeps copying in the background. The agent group is ready to use now; conversations light up one by one as they finish.',
'workspace.general.copyAgentGroups.modal.continue': 'Continue',
'workspace.general.copyAgentGroups.modal.copyOptions.config.desc':
'Required. Copies group metadata, members, member roles, and Agent profiles.',
diff --git a/src/features/AgentTransferMigration/MigrationBanner.tsx b/src/features/AgentTransferMigration/MigrationBanner.tsx
index ec4491ad14a..f992842a397 100644
--- a/src/features/AgentTransferMigration/MigrationBanner.tsx
+++ b/src/features/AgentTransferMigration/MigrationBanner.tsx
@@ -9,19 +9,18 @@ import { useTranslation } from 'react-i18next';
import { agentService } from '@/services/agent';
import { useChatStore } from '@/store/chat';
-import { useAgentTransferJob } from './useAgentTransferJob';
+import { type MigrationTarget, useAgentTransferJob } from './useAgentTransferJob';
-interface MigrationBannerProps {
- agentId: string;
+interface MigrationBannerProps extends MigrationTarget {
topicId?: string | null;
}
/**
- * Whether this topic's history is still awaiting its transfer backfill.
+ * Whether this topic's history is still awaiting its transfer/copy backfill.
* Exposed so the surrounding surface can also gate the chat input.
*/
-export const useTopicMigrationPending = (agentId?: string | null, topicId?: string | null) => {
- const { data } = useAgentTransferJob(agentId);
+export const useTopicMigrationPending = (target: MigrationTarget, topicId?: string | null) => {
+ const { data } = useAgentTransferJob(target);
return {
job: data ?? null,
topicPending: !!topicId && !!data && data.pendingTopicIds.includes(topicId),
@@ -34,59 +33,61 @@ export const useTopicMigrationPending = (agentId?: string | null, topicId?: stri
* shared job hook, and refetches messages the moment the topic flips over —
* so the usual wait is a few seconds, then the history appears in place.
*/
-export const TopicMigrationPlaceholder = memo<MigrationBannerProps>(({ agentId, topicId }) => {
- const { t } = useTranslation('chat');
- const { data, mutate } = useAgentTransferJob(agentId);
- const refreshMessages = useChatStore((s) => s.refreshMessages);
- // Tracks WHICH topic was prioritized (not just whether one was): switching
- // straight from one pending topic to another reuses this component, and the
- // new topic must jump the queue too.
- const prioritizedTopicId = useRef<string | null>(null);
-
- useEffect(() => {
- if (!topicId || prioritizedTopicId.current === topicId) return;
- prioritizedTopicId.current = topicId;
-
- void agentService
- .prioritizeTransferTopic(topicId)
- .then(({ pending }) => {
- // Already migrated between render and request — sync the job status
- // and pull the messages straight away.
- if (!pending) {
- void mutate();
- void refreshMessages();
- }
- })
- .catch(() => {
- if (prioritizedTopicId.current === topicId) prioritizedTopicId.current = null;
- });
- }, [topicId, mutate, refreshMessages]);
-
- // The placeholder unmounts when `pendingTopicIds` stops listing this topic;
- // fetch the freshly migrated history exactly once on the way out.
- useEffect(
- () => () => {
- void refreshMessages();
- },
- [refreshMessages],
- );
-
- return (
- <Flexbox align={'center'} flex={1} gap={12} justify={'center'} padding={24}>
- <Icon spin color={cssVar.colorTextDescription} icon={Loader2} size={20} />
- <Text type={'secondary'} weight={500}>
- {t(
- data?.type === 'copy'
- ? 'transferMigration.topicPendingCopy.title'
- : 'transferMigration.topicPending.title',
- )}
- </Text>
- <Text fontSize={12} style={{ maxWidth: 420, textAlign: 'center' }} type={'secondary'}>
- {t('transferMigration.topicPending.desc')}
- </Text>
- </Flexbox>
- );
-});
+export const TopicMigrationPlaceholder = memo<MigrationBannerProps>(
+ ({ agentId, groupId, topicId }) => {
+ const { t } = useTranslation('chat');
+ const { data, mutate } = useAgentTransferJob({ agentId, groupId });
+ const refreshMessages = useChatStore((s) => s.refreshMessages);
+ // Tracks WHICH topic was prioritized (not just whether one was): switching
+ // straight from one pending topic to another reuses this component, and the
+ // new topic must jump the queue too.
+ const prioritizedTopicId = useRef<string | null>(null);
+
+ useEffect(() => {
+ if (!topicId || prioritizedTopicId.current === topicId) return;
+ prioritizedTopicId.current = topicId;
+
+ void agentService
+ .prioritizeTransferTopic(topicId)
+ .then(({ pending }) => {
+ // Already migrated between render and request — sync the job status
+ // and pull the messages straight away.
+ if (!pending) {
+ void mutate();
+ void refreshMessages();
+ }
+ })
+ .catch(() => {
+ if (prioritizedTopicId.current === topicId) prioritizedTopicId.current = null;
+ });
+ }, [topicId, mutate, refreshMessages]);
+
+ // The placeholder unmounts when `pendingTopicIds` stops listing this topic;
+ // fetch the freshly migrated history exactly once on the way out.
+ useEffect(
+ () => () => {
+ void refreshMessages();
+ },
+ [refreshMessages],
+ );
+
+ return (
+ <Flexbox align={'center'} flex={1} gap={12} justify={'center'} padding={24}>
+ <Icon spin color={cssVar.colorTextDescription} icon={Loader2} size={20} />
+ <Text type={'secondary'} weight={500}>
+ {t(
+ data?.type === 'copy'
+ ? 'transferMigration.topicPendingCopy.title'
+ : 'transferMigration.topicPending.title',
+ )}
+ </Text>
+ <Text fontSize={12} style={{ maxWidth: 420, textAlign: 'center' }} type={'secondary'}>
+ {t('transferMigration.topicPending.desc')}
+ </Text>
+ </Flexbox>
+ );
+ },
+);
TopicMigrationPlaceholder.displayName = 'TopicMigrationPlaceholder';
@@ -118,9 +119,9 @@ const chipStyles = createStaticStyles(({ css }) => ({
* conversation prioritizes it) lives in the tooltip so the header stays calm.
* Renders nothing once the job completes.
*/
-export const AgentMigrationBadge = memo<{ agentId: string }>(({ agentId }) => {
+export const AgentMigrationBadge = memo<MigrationTarget>(({ agentId, groupId }) => {
const { t } = useTranslation('chat');
- const { data } = useAgentTransferJob(agentId);
+ const { data } = useAgentTransferJob({ agentId, groupId });
if (!data) return null;
diff --git a/src/features/AgentTransferMigration/TopicMigrationIndicator.tsx b/src/features/AgentTransferMigration/TopicMigrationIndicator.tsx
index 1d289a19542..475f74ff19b 100644
--- a/src/features/AgentTransferMigration/TopicMigrationIndicator.tsx
+++ b/src/features/AgentTransferMigration/TopicMigrationIndicator.tsx
@@ -6,24 +6,26 @@ import { Loader2 } from 'lucide-react';
import { memo } from 'react';
import { useTopicMigrationPending } from './MigrationBanner';
+import type { MigrationTarget } from './useAgentTransferJob';
-interface TopicMigrationIndicatorProps {
- agentId?: string;
+interface TopicMigrationIndicatorProps extends MigrationTarget {
topicId: string;
}
/**
* Tiny spinner next to a sidebar topic whose history is still migrating after
- * an agent transfer. The topic stays listed (hiding it would read as data
+ * a transfer or a copy. The topic stays listed (hiding it would read as data
* loss); opening it jumps it to the front of the backfill queue.
*/
-const TopicMigrationIndicator = memo<TopicMigrationIndicatorProps>(({ agentId, topicId }) => {
- const { topicPending } = useTopicMigrationPending(agentId, topicId);
+const TopicMigrationIndicator = memo<TopicMigrationIndicatorProps>(
+ ({ agentId, groupId, topicId }) => {
+ const { topicPending } = useTopicMigrationPending({ agentId, groupId }, topicId);
- if (!topicPending) return null;
+ if (!topicPending) return null;
- return <Icon spin color={cssVar.colorTextQuaternary} icon={Loader2} size={12} />;
-});
+ return <Icon spin color={cssVar.colorTextQuaternary} icon={Loader2} size={12} />;
+ },
+);
TopicMigrationIndicator.displayName = 'TopicMigrationIndicator';
diff --git a/src/features/AgentTransferMigration/index.ts b/src/features/AgentTransferMigration/index.ts
index 0815e78939c..c5e0da06a68 100644
--- a/src/features/AgentTransferMigration/index.ts
+++ b/src/features/AgentTransferMigration/index.ts
@@ -4,4 +4,4 @@ export {
useTopicMigrationPending,
} from './MigrationBanner';
export { default as TopicMigrationIndicator } from './TopicMigrationIndicator';
-export { useAgentTransferJob } from './useAgentTransferJob';
+export { type MigrationTarget, useAgentTransferJob } from './useAgentTransferJob';
diff --git a/src/features/AgentTransferMigration/useAgentTransferJob.ts b/src/features/AgentTransferMigration/useAgentTransferJob.ts
index 9d13c852eeb..65b1d1cf104 100644
--- a/src/features/AgentTransferMigration/useAgentTransferJob.ts
+++ b/src/features/AgentTransferMigration/useAgentTransferJob.ts
@@ -2,14 +2,29 @@ import { useEffect } from 'react';
import { useClientPollingSWR } from '@/libs/swr';
import { agentService } from '@/services/agent';
+import { chatGroupService } from '@/services/chatGroup';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
/**
- * Topics this client can currently show for the active agent: the loaded
+ * What a migration surface is keyed on. Exactly one side is set: agent
+ * conversations poll by `agentId`, group conversations by `groupId` (a group's
+ * job is registered against the group, not its member agents — an empty roster
+ * would otherwise have nothing to look up).
+ */
+export interface MigrationTarget {
+ agentId?: null | string;
+ groupId?: null | string;
+}
+
+/**
+ * Topics this client can currently show for the active agent/group: the loaded
* sidebar list plus the open topic. Sent with the status poll so the server
* only reports pending state for these instead of the job's whole queue
* (which can hold tens of thousands of topics).
+ *
+ * Group and agent surfaces share this: both drive the same chat store topic
+ * list.
*/
const getVisibleTopicIds = (): string[] => {
const state = useChatStore.getState();
@@ -31,21 +46,28 @@ export interface AgentTransferJobStatus {
}
/**
- * Poll the async history-backfill status of a transferred agent.
+ * Poll the async history-backfill status of a transferred/copied agent or
+ * chat group.
*
* One cheap indexed query per tick; polling only runs while a job is actually
* pending (`data` non-null) and stops itself once the job completes, so the
- * steady state for every normal agent is a single request per agent switch.
+ * steady state for every normal conversation is a single request per switch.
*
* Many components subscribe to the same key at once (header badge, chat
* placeholder, one indicator per sidebar topic row), so the deduping window
* sits just under the tick: each tick issues ONE request no matter how many
* rows are visible.
*/
-export const useAgentTransferJob = (agentId?: string | null) => {
+export const useAgentTransferJob = ({ agentId, groupId }: MigrationTarget) => {
const response = useClientPollingSWR<AgentTransferJobStatus | null>(
- agentId ? ['agent-transfer-job', agentId] : null,
- () => agentService.getTransferJobStatus(agentId!, getVisibleTopicIds()),
+ // `groupId` wins when both are present: on a group page the context's
+ // `agentId` is the group's supervisor, whose own job (if any) is not the
+ // one gating these conversations.
+ groupId ? ['group-transfer-job', groupId] : agentId ? ['agent-transfer-job', agentId] : null,
+ () =>
+ groupId
+ ? chatGroupService.getTransferJobStatus(groupId, getVisibleTopicIds())
+ : agentService.getTransferJobStatus(agentId!, getVisibleTopicIds()),
{
dedupingInterval: 2500,
refreshInterval: (data) => (data ? 3000 : 0),
diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
index 59e59303d21..bf48eeb3f79 100644
--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
@@ -120,7 +120,7 @@ const Conversation = memo(() => {
// could not assemble the missing context anyway. Opening it jumps it to the
// front of the backfill queue, so the wait is typically a few seconds.
const { job: migrationJob, topicPending } = useTopicMigrationPending(
- context.agentId,
+ { agentId: context.agentId },
context.topicId,
);
@@ -202,9 +202,15 @@ const Conversation = memo(() => {
<ThreadHydration />
<ChatMiniMap />
<ForwardMessageDispatcher />
- <Suspense>
- <MessageFromUrl />
- </Suspense>
+ {/* Held back while the topic is still migrating: the composer above is
+ already disabled, and letting `?message=` through would send into the
+ not-yet-migrated history this screen is waiting for. The param stays
+ in the URL, so the send fires once the backfill lands. */}
+ {!topicPending && (
+ <Suspense>
+ <MessageFromUrl />
+ </Suspense>
+ )}
</ConversationProvider>
);
});
diff --git a/src/routes/(main)/agent/features/Conversation/Header/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/index.tsx
index 16344fbc2c5..2606ce4613c 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/index.tsx
@@ -143,7 +143,7 @@ const Header = memo(() => {
// History-backfill chip in the center slot; the hook shares one SWR key with
// the rest of the migration UI, so this adds no extra polling.
- const { data: transferJob } = useAgentTransferJob(agentId);
+ const { data: transferJob } = useAgentTransferJob({ agentId });
return (
<div className={headerStyles.container}>
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx
index dddbb56b2aa..744f6227e06 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx
@@ -12,6 +12,7 @@ import DotsLoading from '@/components/DotsLoading';
import { TOPIC_STATUS_VISUALS } from '@/components/ExecutionStatus';
import RingLoadingIcon from '@/components/RingLoading';
import { isDesktop } from '@/const/version';
+import { TopicMigrationIndicator } from '@/features/AgentTransferMigration';
import { useHasDraft } from '@/features/ChatInput/draftStorage';
import NavItem from '@/features/NavPanel/components/NavItem';
import TopicCreatorAvatar, { useTopicCreator } from '@/features/TopicCreatorAvatar';
@@ -320,6 +321,10 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, stat
active={active && !threadId}
contextMenuItems={dropdownMenu}
disabled={editing}
+ // A conversation whose history is still being migrated/copied stays
+ // listed (hiding it would read as data loss) and shows a spinner;
+ // opening it jumps it to the front of the backfill queue.
+ extra={<TopicMigrationIndicator groupId={activeGroupId} topicId={id} />}
href={!editing ? href : undefined}
title={title === '...' ? <DotsLoading gap={3} size={4} /> : title}
titleColor={cssVar.colorText}
diff --git a/src/routes/(main)/group/features/Conversation/ConversationArea.tsx b/src/routes/(main)/group/features/Conversation/ConversationArea.tsx
index e0bae4e78c1..028d0aab68f 100644
--- a/src/routes/(main)/group/features/Conversation/ConversationArea.tsx
+++ b/src/routes/(main)/group/features/Conversation/ConversationArea.tsx
@@ -1,8 +1,14 @@
'use client';
import { Flexbox } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
import { memo, Suspense, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import {
+ TopicMigrationPlaceholder,
+ useTopicMigrationPending,
+} from '@/features/AgentTransferMigration';
import ChatMiniMap from '@/features/ChatMiniMap';
import { ChatList, ConversationProvider } from '@/features/Conversation';
import {
@@ -32,6 +38,7 @@ interface ConversationAreaProps {
* Uses ChatList from @/features/Conversation and MainChatInput for custom features.
*/
const Conversation = memo<ConversationAreaProps>(({ mobile = false }) => {
+ const { t } = useTranslation('chat');
const context = useGroupContext();
// Get raw dbMessages from ChatStore for this context
@@ -48,6 +55,15 @@ const Conversation = memo<ConversationAreaProps>(({ mobile = false }) => {
const actionsBarConfig = useActionsBarConfig();
+ // A topic still awaiting its transfer/copy backfill shows a placeholder
+ // instead of an empty (not-yet-migrated) history, and blocks sending — the
+ // supervisor could not assemble the missing context anyway. Opening it jumps
+ // it to the front of the queue, so the wait is typically a few seconds.
+ const { job: migrationJob, topicPending } = useTopicMigrationPending(
+ { groupId: context.groupId },
+ context.topicId,
+ );
+
return (
<ConversationProvider
actionsBar={actionsBarConfig}
@@ -68,20 +84,42 @@ const Conversation = memo<ConversationAreaProps>(({ mobile = false }) => {
position: 'relative',
}}
>
- <ChatList welcome={<WelcomeChatItem />} />
+ {topicPending ? (
+ <TopicMigrationPlaceholder groupId={context.groupId} topicId={context.topicId} />
+ ) : (
+ <ChatList welcome={<WelcomeChatItem />} />
+ )}
</Flexbox>
- <MessageForwardFooter>
- <MainChatInput />
- </MessageForwardFooter>
+ {topicPending ? (
+ <Flexbox horizontal align={'center'} justify={'center'} paddingBlock={6} paddingInline={16}>
+ <span style={{ color: cssVar.colorTextDescription, fontSize: 12, textAlign: 'center' }}>
+ {t(
+ migrationJob?.type === 'copy'
+ ? 'transferMigration.inputDisabledHintCopy'
+ : 'transferMigration.inputDisabledHint',
+ )}
+ </span>
+ </Flexbox>
+ ) : (
+ <MessageForwardFooter>
+ <MainChatInput />
+ </MessageForwardFooter>
+ )}
<ChatHydration />
<ThreadHydration />
<ForwardMessageDispatcher />
{!mobile && (
<>
<ChatMiniMap />
- <Suspense>
- <MessageFromUrl />
- </Suspense>
+ {/* Held back while the topic is still migrating: the composer above is
+ already disabled, and letting `?message=` through would send into
+ the not-yet-migrated history this screen is waiting for. The param
+ stays in the URL, so the send fires once the backfill lands. */}
+ {!topicPending && (
+ <Suspense>
+ <MessageFromUrl />
+ </Suspense>
+ )}
</>
)}
</ConversationProvider>
diff --git a/src/routes/(main)/group/features/Conversation/Header/index.tsx b/src/routes/(main)/group/features/Conversation/Header/index.tsx
index f0b4b49ce65..1ec96333e51 100644
--- a/src/routes/(main)/group/features/Conversation/Header/index.tsx
+++ b/src/routes/(main)/group/features/Conversation/Header/index.tsx
@@ -2,18 +2,32 @@
import { Flexbox } from '@lobehub/ui';
import { cssVar } from 'antd-style';
-import { memo,Suspense } from 'react';
+import { memo, Suspense } from 'react';
+import { AgentMigrationBadge } from '@/features/AgentTransferMigration';
import NavHeader from '@/features/NavHeader';
import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
+import { useAgentGroupStore } from '@/store/agentGroup';
import ShareButton from './ShareButton';
const Header = memo(() => {
+ // Same source as `useGroupContext` — the resolved group, not the route-synced
+ // chat-store global, which is transiently empty on navigation.
+ const groupId = useAgentGroupStore((s) => s.activeGroupId);
+
return (
<NavHeader
right={
- <Flexbox horizontal style={{ backgroundColor: cssVar.colorBgContainer }}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={8}
+ style={{ backgroundColor: cssVar.colorBgContainer }}
+ >
+ {/* Progress chip for a heavy group transfer/copy still filling in its
+ conversations; renders nothing once the backfill finishes. */}
+ {groupId && <AgentMigrationBadge groupId={groupId} />}
<WideScreenButton />
<Suspense>
<ShareButton />
diff --git a/src/services/chatGroup/index.ts b/src/services/chatGroup/index.ts
index f72b27cf91f..7f0a3bcbd90 100644
--- a/src/services/chatGroup/index.ts
+++ b/src/services/chatGroup/index.ts
@@ -156,13 +156,21 @@ class ChatGroupService {
groupId: string,
targetWorkspaceId: string | null,
targetVisibility?: 'private' | 'public',
- ): Promise<{ groupId: string } | null> => {
+ ): Promise<{ groupId: string; transferJobId?: string | null } | null> => {
return lambdaClient.group.transferGroup.mutate({
groupId,
targetVisibility,
targetWorkspaceId,
});
};
+
+ /**
+ * Async history-backfill progress for a transferred/copied group.
+ * `topicIds` caps the reported pending set to what the client can show.
+ */
+ getTransferJobStatus = async (groupId: string, topicIds: string[]) => {
+ return lambdaClient.group.getTransferJobStatus.query({ groupId, topicIds });
+ };
}
export const chatGroupService = new ChatGroupService();