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.

33.2 KB
Raw Blame
import { AGENT_ARTIFACT_SOURCE_TYPES } from '@lobechat/const';
import type { DocumentAccessScope, FileAccessScope } from '@lobechat/types';
import {
  ordinaryDocumentAccessScope,
  ordinaryFileAccessScope,
  stripAgentShareDocumentProvenance,
} from '@lobechat/types';
import {
  and,
  asc,
  count,
  desc,
  eq,
  gt,
  inArray,
  isNull,
  ne,
  notExists,
  notInArray,
  or,
  sum,
} from 'drizzle-orm';

import type { DocumentItem, NewDocument } from '../schemas';
import {
  agentDocuments,
  DOCUMENT_FOLDER_TYPE,
  documentCommentMentions,
  documentComments,
  documentHistories,
  documentLikes,
  documents,
  files,
  knowledgeBaseFiles,
  messages,
  messagesFiles,
  nextDocumentUpdatedAt,
  works,
} from '../schemas';
import type { LobeChatDatabase } from '../type';
import { documentMatchesAccessScope } from '../utils/documentVisibility';
import { notFileBackedPlaceholder } from '../utils/fileBackedPlaceholder';
import {
  fileReferenceMatchesAccessScope,
  notAgentShareFileReference,
} from '../utils/fileVisibility';
import { documentOriginalCharCount } from '../utils/originalCharCount';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';

export interface QueryDocumentParams {
  /**
   * Narrow by creator: `self` keeps the caller's own documents, `others` keeps
   * documents other workspace members created (still subject to visibility).
   */
  creator?: 'others' | 'self';
  current?: number;
  /**
   * Knowledge-base ids whose documents must be dropped from the listing —
   * restricted (member No-access) libraries. Applied inside the query so
   * pagination and totals stay correct.
   */
  excludeKnowledgeBaseIds?: string[];
  fileTypes?: string[];
  /** Rows to skip; overrides `current * pageSize` for cursor-backed callers. */
  offset?: number;
  pageSize?: number;
  /** Keep only the direct children of this folder. */
  parentId?: string;
  /**
   * Row order: `updatedAt` (default) and `createdAt` list the newest first,
   * `title` lists A→Z. Ties fall back to the id so offset pages never overlap.
   */
  sortBy?: DocumentQuerySortBy;
  sourceTypes?: string[];
  /** Keep only documents that live outside every knowledge base. */
  standaloneOnly?: boolean;
}

export type DocumentQuerySortBy = 'createdAt' | 'title' | 'updatedAt';

export const DOCUMENT_TRANSFER_FOREIGN_ROWS =
  'Document subtree contains content created by other users';

export class DocumentModel {
  private userId: string;
  private db: LobeChatDatabase;
  private workspaceId?: string;
  private documentAccessScope: DocumentAccessScope;
  /**
   * Visibility of the agent that owns the calling tool execution, when this
   * model is instantiated inside a tool runtime. `'public'` tightens
   * `ownership()` so a workspace-shared agent cannot see the caller's own
   * private documents — mirrors the task side's `assertAgentVisibilityCompat`.
   * `undefined` / `'private'` / `null` leave the standard filter in place, so
   * a private agent (or a direct TRPC call from the user) still sees the
   * caller's private docs as normal.
   */
  private callerAgentVisibility?: 'private' | 'public' | null;

  constructor(
    db: LobeChatDatabase,
    userId: string,
    workspaceId?: string,
    callerAgentVisibility?: 'private' | 'public' | null,
    documentAccessScope: DocumentAccessScope = ordinaryDocumentAccessScope,
  ) {
    this.userId = userId;
    this.db = db;
    this.workspaceId = workspaceId;
    this.callerAgentVisibility = callerAgentVisibility;
    this.documentAccessScope = documentAccessScope;
  }

  private ownership = () =>
    buildWorkspaceWhere(
      {
        callerAgentVisibility: this.callerAgentVisibility,
        userId: this.userId,
        workspaceId: this.workspaceId,
      },
      documents,
    );

  private readScope = () =>
    and(
      this.ownership(),
      documentMatchesAccessScope(documents.metadata, this.documentAccessScope),
      notAgentShareFileReference(this.db, documents.fileId),
    );

  private scopeMetadata = (metadata?: Record<string, any> | null) => {
    const sanitizedMetadata = stripAgentShareDocumentProvenance(metadata);
    if (this.documentAccessScope.type !== 'agentShare') return sanitizedMetadata;

    return {
      ...sanitizedMetadata,
      agentShare: {
        shareId: this.documentAccessScope.shareId,
        topicId: this.documentAccessScope.topicId,
        visitorUserId: this.documentAccessScope.visitorUserId,
      },
    };
  };

  findOrCreateFolder = async (name: string, parentId?: string): Promise<DocumentItem> => {
    const existing = await this.db.query.documents.findFirst({
      where: and(
        this.readScope(),
        eq(documents.fileType, DOCUMENT_FOLDER_TYPE),
        eq(documents.filename, name),
        parentId ? eq(documents.parentId, parentId) : isNull(documents.parentId),
      ),
    });

    if (existing) return existing;

    return this.create({
      content: '',
      fileType: DOCUMENT_FOLDER_TYPE,
      filename: name,
      parentId,
      source: '',
      sourceType: 'api',
      title: name,
      totalCharCount: 0,
      totalLineCount: 0,
    });
  };

  create = async (params: Omit<NewDocument, 'userId'>): Promise<DocumentItem> => {
    // Workspace documents default to the schema's `'public'`: a workspace is a
    // collaborative space, so whatever a member (or an agent acting for them)
    // writes there is shared unless the caller explicitly asks for `'private'`.
    // Personal mode ignores the column.
    const result = (await this.db
      .insert(documents)
      .values(
        buildWorkspacePayload(
          { userId: this.userId, workspaceId: this.workspaceId },
          {
            ...params,
            metadata: this.scopeMetadata(params.metadata),
          },
        ),
      )
      .returning()) as DocumentItem[];

    return result[0]!;
  };

  delete = async (id: string) => {
    return this.db.delete(documents).where(and(eq(documents.id, id), this.readScope()));
  };

  deleteAll = async () => {
    return this.db.delete(documents).where(this.readScope());
  };

  query = async ({
    creator,
    current = 0,
    pageSize = 9999,
    excludeKnowledgeBaseIds,
    fileTypes,
    offset: explicitOffset,
    parentId,
    sortBy = 'updatedAt',
    sourceTypes,
    standaloneOnly,
  }: QueryDocumentParams = {}): Promise<{
    items: DocumentItem[];
    total: number;
  }> => {
    const offset = explicitOffset ?? current * pageSize;
    const conditions = [this.readScope()];

    if (parentId) conditions.push(eq(documents.parentId, parentId));
    if (fileTypes?.length) {
      conditions.push(inArray(documents.fileType, fileTypes));
    }

    if (creator === 'self') conditions.push(eq(documents.userId, this.userId));
    if (creator === 'others') conditions.push(ne(documents.userId, this.userId));

    if (standaloneOnly) {
      conditions.push(
        isNull(documents.knowledgeBaseId),
        // Parsed files taken from a library keep `knowledgeBaseId` null, so the
        // `knowledgeBaseId` check alone still lets them through. A document that
        // is backed by a file living in a library is not standalone either.
        or(
          isNull(documents.fileId),
          notInArray(
            documents.fileId,
            this.db.select({ fileId: knowledgeBaseFiles.fileId }).from(knowledgeBaseFiles),
          ),
        )!,
      );
    }

    if (excludeKnowledgeBaseIds?.length) {
      conditions.push(
        or(
          isNull(documents.knowledgeBaseId),
          notInArray(documents.knowledgeBaseId, excludeKnowledgeBaseIds),
        )!,
        // Parsed-file documents leave `knowledgeBaseId` null — their KB
        // membership lives on `fileId` → `knowledge_base_files`.
        or(
          isNull(documents.fileId),
          notInArray(
            documents.fileId,
            this.db
              .select({ fileId: knowledgeBaseFiles.fileId })
              .from(knowledgeBaseFiles)
              .where(inArray(knowledgeBaseFiles.knowledgeBaseId, excludeKnowledgeBaseIds)),
          ),
        )!,
      );
    }

    if (sourceTypes?.length) {
      conditions.push(
        inArray(
          documents.sourceType,
          sourceTypes as ('file' | 'web' | 'api' | 'topic' | 'agent' | 'agent-signal')[],
        ),
      );
    } else {
      conditions.push(notInArray(documents.sourceType, [...AGENT_ARTIFACT_SOURCE_TYPES]));
    }

    const whereCondition = and(...conditions);
    const orderBy =
      sortBy === 'title'
        ? [asc(documents.title), desc(documents.updatedAt), asc(documents.id)]
        : [
            desc(sortBy === 'createdAt' ? documents.createdAt : documents.updatedAt),
            asc(documents.id),
          ];

    // Fetch items and total count in parallel
    // Optimize: Exclude large JSONB fields (content, pages, editorData) for better performance
    const [rawItems, totalResult] = await Promise.all([
      this.db
        .select({
          accessedAt: documents.accessedAt,
          clientId: documents.clientId,
          createdAt: documents.createdAt,
          fileId: documents.fileId,
          fileType: documents.fileType,
          filename: documents.filename,
          id: documents.id,
          metadata: documents.metadata,
          parentId: documents.parentId,
          slug: documents.slug,
          source: documents.source,
          sourceType: documents.sourceType,
          title: documents.title,
          totalCharCount: documents.totalCharCount,
          totalLineCount: documents.totalLineCount,
          updatedAt: documents.updatedAt,
          userId: documents.userId,
          // Sidebar bucket selectors read `visibility` / `workspaceId` to split
          // Pages between the "Private" and "Workspace" accordions — omitting
          // them silently drops every row into the workspace bucket.
          visibility: documents.visibility,
          workspaceId: documents.workspaceId,
          // Exclude large fields: content, pages, editorData
        })
        .from(documents)
        .where(whereCondition)
        .orderBy(...orderBy)
        .limit(pageSize)
        .offset(offset),
      this.db
        .select({ count: count(documents.id) })
        .from(documents)
        .where(whereCondition),
    ]);

    // Map to DocumentItem type with excluded fields as null
    const items = rawItems.map((item) => ({
      ...item,
      content: null,
      editorData: null,
      pages: null,
    })) as DocumentItem[];

    return { items, total: totalResult[0].count };
  };

  findById = async (id: string): Promise<DocumentItem | undefined> => {
    const [document] = await this.db
      .select()
      .from(documents)
      .where(and(this.readScope(), eq(documents.id, id)))
      .limit(1);
    return document;
  };

  findByIds = async (ids: string[]): Promise<DocumentItem[]> => {
    if (ids.length === 0) return [];
    return this.db
      .select()
      .from(documents)
      .where(and(this.readScope(), inArray(documents.id, ids)));
  };

  /**
   * Whether a parsed document that prompts preview instead of inline exists for the given files or
   * for any file attached to a message in `topicId`: longer than `minChars`, or cut at parse time
   * (`metadata.originalCharCount` above the stored length). Mirrors `isOversizedFileContent` in
   * `@lobechat/prompts`, so the run gets a tool that can read those previews in windows.
   */
  hasFileDocumentsOverChars = async ({
    fileIds = [],
    minChars,
    topicId,
  }: {
    fileIds?: string[];
    minChars: number;
    topicId?: string | null;
  }): Promise<boolean> => {
    const fileConditions = [];
    if (fileIds.length > 0) fileConditions.push(inArray(documents.fileId, fileIds));
    if (topicId) {
      fileConditions.push(
        inArray(
          documents.fileId,
          this.db
            .select({ fileId: messagesFiles.fileId })
            .from(messagesFiles)
            .innerJoin(messages, eq(messages.id, messagesFiles.messageId))
            .where(eq(messages.topicId, topicId)),
        ),
      );
    }
    if (fileConditions.length === 0) return false;

    const [row] = await this.db
      .select({ id: documents.id })
      .from(documents)
      .where(
        and(
          this.ownership(),
          or(
            gt(documents.totalCharCount, minChars),
            gt(documentOriginalCharCount(), documents.totalCharCount),
          ),
          or(...fileConditions),
        ),
      )
      .limit(1);

    return !!row;
  };

  findByFileId = async (fileId: string, accessScope: FileAccessScope = ordinaryFileAccessScope) => {
    const [document] = await this.db
      .select()
      .from(documents)
      // A file can legitimately own more than one document: `parseDocument`
      // writes a page-editor copy next to the parse cache `parseFile` writes.
      // Pick the oldest one explicitly instead of leaving the choice to the
      // query plan, so repeated lookups keep returning the same content.
      // `created_at` carries no uniqueness guarantee, so `id` breaks ties.
      // An agent-document upload's empty placeholder row holds no text, so it is
      // never the file's parse result; skipping it lets `parseFile` run.
      .where(
        and(
          this.ownership(),
          eq(documents.fileId, fileId),
          notFileBackedPlaceholder(),
          fileReferenceMatchesAccessScope(this.db, documents.fileId, accessScope),
        ),
      )
      .orderBy(asc(documents.createdAt), asc(documents.id))
      .limit(1);
    return document;
  };

  findBySlug = async (slug: string): Promise<DocumentItem | undefined> => {
    const [document] = await this.db
      .select()
      .from(documents)
      .where(and(this.readScope(), eq(documents.slug, slug)))
      .limit(1);
    return document;
  };

  /**
   * Look up the user's existing document for a given `(source, sourceType)` pair.
   *
   * Crawl-style ingestion flows (`sourceType: 'web'`) use this to dedupe by URL
   * so repeated crawls of the same page update the existing row instead of
   * appending a fresh one — see .
   */
  findBySource = async (
    source: string,
    sourceType: NonNullable<NewDocument['sourceType']>,
  ): Promise<DocumentItem | undefined> => {
    const [document] = await this.db
      .select()
      .from(documents)
      .where(
        and(this.readScope(), eq(documents.source, source), eq(documents.sourceType, sourceType)),
      )
      .limit(1);
    return document;
  };

  update = async (id: string, value: Partial<DocumentItem>) => {
    // visibility is intentionally not updatable via this path. The only legal
    // transition is `private → public` via `publishToWorkspace`; strip any
    // incoming value so callers can't sneak around the one-way rule.
    const { metadata, updatedAt: _updatedAt, visibility: _ignored, ...patch } = value;

    const [row] = await this.db
      .update(documents)
      .set({
        ...patch,
        ...(metadata !== undefined && { metadata: this.scopeMetadata(metadata) }),
        updatedAt: nextDocumentUpdatedAt(),
      })
      .where(and(this.readScope(), eq(documents.id, id)))
      .returning({ updatedAt: documents.updatedAt });

    return row?.updatedAt;
  };

  /**
   * Mirror a file's placement / name onto the document row(s) backed by it
   * (`documents.file_id = fileId`). The knowledge-base tree is rendered from
   * `documents.parent_id`, so moving only the `files` row leaves the item under
   * its old folder. Counterpart of the document → file sync in
   * `DocumentService.updateDocument`.
   */
  syncFromFile = async (fileId: string, value: { name?: string; parentId?: string | null }) => {
    const patch: Partial<DocumentItem> = {};
    if (value.name !== undefined) {
      patch.title = value.name;
      patch.filename = value.name;
    }
    if (value.parentId !== undefined) patch.parentId = value.parentId;
    if (Object.keys(patch).length === 0) return [];

    return this.db
      .update(documents)
      .set({ ...patch, updatedAt: nextDocumentUpdatedAt() })
      .where(
        and(
          this.readScope(),
          eq(documents.fileId, fileId),
          // Skip documents that are an agent's own copy of the file
          // (AgentDocumentsService.importFile): they keep their collision-safe VFS filename and
          // agent-folder parent. Such a copy is created together with its agent_documents
          // binding in one transaction, so both rows share `created_at` (defaultNow() is fixed
          // per transaction). `associateDocument` binds a document that already existed, so an
          // associated knowledge-base mirror or page keeps following the file.
          notExists(
            this.db
              .select({ id: agentDocuments.id })
              .from(agentDocuments)
              .where(
                and(
                  eq(agentDocuments.documentId, documents.id),
                  eq(agentDocuments.createdAt, documents.createdAt),
                ),
              ),
          ),
        ),
      )
      .returning({ id: documents.id });
  };

  /**
   * Publish one private document into the workspace. Convenience wrapper
   * around `setVisibility(rootId, 'public')`; kept as a named method for the
   * TRPC `publishDocumentToWorkspace` procedure and existing callers.
   *
   * @returns the id of the document that was re-published.
   */
  publishToWorkspace = async (rootId: string): Promise<{ documentIds: string[] }> => {
    return this.setVisibility(rootId, 'public');
  };

  /**
   * Flip one document's `visibility`. Documents do not inherit ACL or
   * visibility from their parent: a parent may be used purely for navigation.
   */
  setVisibility = async (
    rootId: string,
    visibility: 'private' | 'public',
  ): Promise<{ documentIds: string[] }> => {
    return this.db.transaction(async (trx) => {
      const result = await (trx as LobeChatDatabase)
        .update(documents)
        .set({ visibility })
        .where(and(eq(documents.id, rootId), this.ownership(), eq(documents.userId, this.userId)))
        .returning({ fileId: documents.fileId, id: documents.id });

      if (result.length === 0) throw new Error('Document not found');

      // A page filed into a library owns a paired `files` row, stamped with the
      // library's visibility when the page was created. The library lists rows
      // through THAT column while the page opens through the document's, so
      // leaving it behind splits the two: the row keeps announcing a private
      // page's title to every member, and the page behind it refuses to open.
      // Same transaction, and scoped without `files.visibility` for the same
      // reason as `works` below — a promotion has to reach rows that are still
      // private.
      //
      // `files.userId` is required on top of the workspace scope: `fileId` is a
      // plain foreign key, and a document can point at a file somebody else
      // uploaded (parsing another member's shared file yields a caller-owned
      // document that keeps the original `fileId`). Without the owner check the
      // workspace scope alone matches every member's file, so taking such a
      // derived page private would hide the uploader's original from everyone.
      // The paired row this mirrors is always the caller's own.
      const fileId = result[0].fileId;
      if (fileId) {
        await (trx as LobeChatDatabase)
          .update(files)
          .set({ visibility })
          .where(
            and(
              eq(files.id, fileId),
              eq(files.userId, this.userId),
              buildWorkspaceWhere(
                { userId: this.userId, workspaceId: this.workspaceId },
                { userId: files.userId, workspaceId: files.workspaceId },
              ),
            ),
          );
      }

      // Mirror visibility onto existing Work projections in the same
      // transaction. Scope without works.visibility so a promotion can
      // update rows that are currently private.
      await (trx as LobeChatDatabase)
        .update(works)
        .set({ visibility })
        .where(
          and(
            eq(works.resourceType, 'document'),
            eq(works.resourceId, rootId),
            buildWorkspaceWhere(
              { userId: this.userId, workspaceId: this.workspaceId },
              { isDeleted: works.isDeleted, userId: works.userId, workspaceId: works.workspaceId },
            ),
          ),
        );

      return { documentIds: [rootId] };
    });
  };

  /**
   * Collect a document and all its descendants (folders + leaves) via BFS.
   * Honors the current ownership scope.
   */
  private collectSubtree = async (
    rootId: string,
    runner: LobeChatDatabase = this.db,
  ): Promise<DocumentItem[]> => {
    const root = await runner.query.documents.findFirst({
      where: and(this.ownership(), eq(documents.id, rootId)),
    });
    if (!root) return [];

    const collected: DocumentItem[] = [root];
    let frontier: string[] = [root.id];

    while (frontier.length > 0) {
      const children = await runner.query.documents.findMany({
        where: and(this.ownership(), inArray(documents.parentId, frontier)),
      });
      if (children.length === 0) break;
      collected.push(...children);
      frontier = children.map((c) => c.id);
    }

    return collected;
  };

  countFileUsageInSubtree = async (
    rootId: string,
    runner: LobeChatDatabase = this.db,
  ): Promise<number> => {
    const subtree = await this.collectSubtree(rootId, runner);
    if (subtree.length === 0) return 0;

    const ids = subtree.map((d) => d.id);
    const result = await runner
      .select({ totalSize: sum(files.size) })
      .from(files)
      .where(
        and(
          buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, files),
          inArray(files.parentId, ids),
        ),
      );

    return parseInt(result[0]?.totalSize ?? '0') || 0;
  };

  /**
   * Transfer a document (and its subtree) to another workspace / personal scope.
   * Files anchored to documents in the subtree are also re-homed so the
   * resource manager view stays consistent.
   */
  /**
   * Whether the subtree (documents + anchored files + comments + likes)
   * contains rows created by someone else. Transfers rehome every cascaded row, so non-owner
   * members must not move a folder that carries teammates' content. Comments
   * with a deleted author count as foreign because they do not belong to the
   * caller and may otherwise be moved or deleted by a personal-scope transfer.
   */
  subtreeHasForeignRows = async (documentId: string): Promise<boolean> => {
    const subtree = await this.collectSubtree(documentId, this.db);
    return this.hasForeignRows(subtree, this.db);
  };

  /**
   * Shared predicate behind {@link subtreeHasForeignRows} and the in-transaction
   * recheck of {@link transferTo}: the router's preflight alone is a TOCTOU —
   * a teammate's comment/like committed between the preflight and the transfer
   * transaction would otherwise be rehomed or deleted past the owner-only guard.
   */
  private hasForeignRows = async (
    subtree: { id: string; userId: string }[],
    runner: LobeChatDatabase,
  ): Promise<boolean> => {
    if (subtree.some((doc) => doc.userId !== this.userId)) return true;

    const ids = subtree.map((doc) => doc.id);
    if (ids.length === 0) return false;

    const [foreignComment] = await runner
      .select({ id: documentComments.id })
      .from(documentComments)
      .where(
        and(
          inArray(documentComments.documentId, ids),
          or(ne(documentComments.authorUserId, this.userId), isNull(documentComments.authorUserId)),
        ),
      )
      .limit(1);
    if (foreignComment) return true;

    const [foreignLike] = await runner
      .select({ id: documentLikes.id })
      .from(documentLikes)
      .where(and(inArray(documentLikes.documentId, ids), ne(documentLikes.userId, this.userId)))
      .limit(1);
    if (foreignLike) return true;

    const [foreignFile] = await runner
      .select({ id: files.id })
      .from(files)
      .where(and(inArray(files.parentId, ids), ne(files.userId, this.userId)))
      .limit(1);
    return !!foreignFile;
  };

  transferTo = async (
    documentId: string,
    targetWorkspaceId: string | null,
    targetUserId: string,
    targetVisibility?: 'private' | 'public',
    options?: {
      /**
       * Re-assert inside the transaction that the subtree carries no rows
       * created by someone else (non-owner transfers). Throws
       * {@link DOCUMENT_TRANSFER_FOREIGN_ROWS} when violated.
       */
      forbidForeignRows?: boolean;
    },
  ): Promise<{ documentIds: string[] }> => {
    return this.db.transaction(async (trx) => {
      const scopedTrx = new DocumentModel(trx as LobeChatDatabase, this.userId, this.workspaceId);
      const subtree = await scopedTrx.collectSubtree(documentId, trx as LobeChatDatabase);
      if (subtree.length === 0) throw new Error('Document not found');

      const ids = subtree.map((d) => d.id);

      // Lock every subtree document row first: concurrent comment/like writers
      // take FOR UPDATE on the document row before stamping a workspace, so
      // they either commit before this point (and are seen by the recheck
      // below) or block until this transfer commits and then re-validate.
      await (trx as LobeChatDatabase)
        .select({ id: documents.id })
        .from(documents)
        .where(inArray(documents.id, ids))
        .for('update');

      if (
        options?.forbidForeignRows &&
        (await scopedTrx.hasForeignRows(subtree, trx as LobeChatDatabase))
      ) {
        throw new Error(DOCUMENT_TRANSFER_FOREIGN_ROWS);
      }
      const ownershipUpdate = { userId: targetUserId, workspaceId: targetWorkspaceId };
      // Visibility only applies when landing in a workspace — personal scope
      // treats every row as implicitly private. Transfer still moves the
      // selected tree as one operation, while ordinary visibility changes do not cascade.
      const visibilityUpdate =
        targetWorkspaceId && targetVisibility ? { visibility: targetVisibility } : {};

      // Resolve slug conflicts in the target scope
      for (const doc of subtree) {
        if (!doc.slug) continue;
        const slug = await this.findAvailableSlug(
          trx as LobeChatDatabase,
          doc.slug,
          targetWorkspaceId,
          targetUserId,
          doc.id,
        );
        if (slug !== doc.slug) {
          await (trx as LobeChatDatabase)
            .update(documents)
            .set({ slug })
            .where(eq(documents.id, doc.id));
        }
      }

      await (trx as LobeChatDatabase)
        .update(documents)
        .set({ ...ownershipUpdate, ...visibilityUpdate })
        .where(inArray(documents.id, ids));

      if (targetWorkspaceId) {
        await (trx as LobeChatDatabase)
          .update(documentComments)
          // A scope transfer is not an author edit. Preserve updatedAt to bypass
          // the schema's Drizzle $onUpdate hook.
          .set({ updatedAt: documentComments.updatedAt, workspaceId: targetWorkspaceId })
          .where(inArray(documentComments.documentId, ids));

        await (trx as LobeChatDatabase)
          .update(documentCommentMentions)
          .set({ workspaceId: targetWorkspaceId })
          .where(
            inArray(
              documentCommentMentions.commentId,
              (trx as LobeChatDatabase)
                .select({ id: documentComments.id })
                .from(documentComments)
                .where(inArray(documentComments.documentId, ids)),
            ),
          );

        await (trx as LobeChatDatabase)
          .update(documentLikes)
          .set({ workspaceId: targetWorkspaceId })
          .where(inArray(documentLikes.documentId, ids));
      } else {
        // Comments are Workspace assets and cannot follow a document into personal scope.
        // Mention rows are removed by the comment FK cascade.
        await (trx as LobeChatDatabase)
          .delete(documentComments)
          .where(inArray(documentComments.documentId, ids));

        // Likes are Workspace reactions too; a personal document has no like surface.
        await (trx as LobeChatDatabase)
          .delete(documentLikes)
          .where(inArray(documentLikes.documentId, ids));
      }

      // Move files anchored to these documents; their visibility mirrors the
      // document subtree in workspace scope.
      await (trx as LobeChatDatabase)
        .update(files)
        .set({ ...ownershipUpdate, ...visibilityUpdate })
        .where(inArray(files.parentId, ids));

      // History reads filter on the denormalized scope. A workspace target
      // filters on `workspace_id` alone, so authors keep their attribution; a
      // personal target reads `user_id = owner`, so the new owner takes every version.
      await (trx as LobeChatDatabase)
        .update(documentHistories)
        .set(
          targetWorkspaceId
            ? { workspaceId: targetWorkspaceId }
            : { userId: targetUserId, workspaceId: null },
        )
        .where(inArray(documentHistories.documentId, ids));

      return { documentIds: ids };
    });
  };

  /**
   * Deep clone a document (and its subtree) into another workspace / personal
   * scope. Generates fresh ids and preserves the parent/child topology.
   */
  copyToWorkspace = async (
    documentId: string,
    targetWorkspaceId: string | null,
    targetUserId: string,
    targetVisibility?: 'private' | 'public',
  ): Promise<{ rootId: string }> => {
    return this.db.transaction(async (trx) => {
      const scopedTrx = new DocumentModel(trx as LobeChatDatabase, this.userId, this.workspaceId);
      const subtree = await scopedTrx.collectSubtree(documentId, trx as LobeChatDatabase);
      if (subtree.length === 0) throw new Error('Document not found');

      // Visibility only applies when landing in a workspace.
      const visibilityOverride =
        targetWorkspaceId && targetVisibility ? { visibility: targetVisibility } : {};

      // BFS clone: parents are inserted before children so we always know the
      // new parent id by the time we get to the child.
      const idMap = new Map<string, string>();
      const byId = new Map(subtree.map((d) => [d.id, d]));
      const queue: string[] = [documentId];
      const seen = new Set<string>();

      while (queue.length > 0) {
        const currentId = queue.shift()!;
        if (seen.has(currentId)) continue;
        seen.add(currentId);
        // Invariant: the queue only holds documentId (the subtree root
        // collectSubtree fetched by that id) and ids pushed from subtree rows,
        // all of which are byId keys.
        const original = byId.get(currentId)!;

        const newParentId =
          currentId === documentId ? null : (idMap.get(original.parentId!) ?? null);

        let newSlug = original.slug;
        if (newSlug) {
          newSlug = await this.findAvailableSlug(
            trx as LobeChatDatabase,
            newSlug,
            targetWorkspaceId,
            targetUserId,
          );
        }

        const inserted = (await (trx as LobeChatDatabase)
          .insert(documents)
          .values({
            accessedAt: original.accessedAt,
            clientId: null,
            content: original.content,
            editorData: original.editorData,
            fileId: null,
            fileType: original.fileType,
            filename: original.filename,
            knowledgeBaseId: null,
            metadata: { ...original.metadata, duplicatedFrom: original.id },
            pages: original.pages,
            parentId: newParentId,
            slug: newSlug,
            source: original.source,
            sourceType: original.sourceType,
            title: original.title,
            totalCharCount: original.totalCharCount,
            totalLineCount: original.totalLineCount,
            userId: targetUserId,
            workspaceId: targetWorkspaceId,
            ...visibilityOverride,
          } as NewDocument)
          .returning({ id: documents.id })) as { id: string }[];

        idMap.set(original.id, inserted[0]!.id);

        for (const c of subtree) {
          if (c.parentId === original.id) queue.push(c.id);
        }
      }

      return { rootId: idMap.get(documentId)! };
    });
  };

  /**
   * Find a slug not already taken in the target (workspaceId, userId) scope.
   * Tries `slug`, `slug-1`, …, `slug-99`. Mirrors the agent transfer behavior.
   */
  private findAvailableSlug = async (
    runner: LobeChatDatabase,
    baseSlug: string,
    targetWorkspaceId: string | null,
    targetUserId: string,
    ignoreDocumentId?: string,
  ): Promise<string> => {
    const buildWhere = (candidate: string) =>
      targetWorkspaceId
        ? and(eq(documents.slug, candidate), eq(documents.workspaceId, targetWorkspaceId))
        : and(
            eq(documents.slug, candidate),
            eq(documents.userId, targetUserId),
            isNull(documents.workspaceId),
          );

    const isFree = async (candidate: string): Promise<boolean> => {
      const existing = await runner.query.documents.findFirst({ where: buildWhere(candidate) });
      if (!existing) return true;
      return ignoreDocumentId !== undefined && existing.id === ignoreDocumentId;
    };

    if (await isFree(baseSlug)) return baseSlug;

    for (let suffix = 1; suffix < 100; suffix++) {
      const candidate = `${baseSlug}-${suffix}`;
      if (await isFree(candidate)) return candidate;
    }
    // Fallback: append timestamp to guarantee uniqueness
    return `${baseSlug}-${Date.now()}`;
  };
}