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.

38.0 KB
Raw Blame
import { randomUUID } from 'node:crypto';

import {
  CUSTOM_DOCUMENT_FILE_TYPE,
  CUSTOM_FOLDER_FILE_TYPE,
  HTML_DOCUMENT_FILE_TYPE,
} from '@lobechat/const';
import { type LobeChatDatabase } from '@lobechat/database';
import { type DocumentItem } from '@lobechat/database/schemas';
import { documents, files } from '@lobechat/database/schemas';
import type { DocumentAccessScope, DocumentWriteSource, FileAccessScope } from '@lobechat/types';
import {
  ordinaryDocumentAccessScope,
  ordinaryFileAccessScope,
  stripAgentShareDocumentProvenance,
} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { and, eq, sql } from 'drizzle-orm';
import isEqual from 'fast-deep-equal';

import { MAX_FILE_PARSE_SIZE } from '@/const/file';
import { DocumentModel, type QueryDocumentParams } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { buildWorkspaceWhere } from '@/database/utils/workspace';
import { isValidEditorData } from '@/libs/editor/isValidEditorData';
import { normalizeEditorDataDiffNodes } from '@/libs/editor/normalizeDiffNodes';
import { diffAddedMentionUserIds } from '@/server/utils/documentMentions';
import { type LobeDocument } from '@/types/document';

import { EditLockService } from '../editLock';
import { FileService } from '../file';
import { parseFileInWorker } from '../fileParse';
import { normalizeParseFileError } from '../fileParse/normalizeError';
import { dropPageRooms } from '../pageCollab/notify';
import { publishResourceEvent } from '../resourceEvents';
import { countEditorDataText } from './editorData';
import { DocumentHistoryService } from './history';
import type {
  CompareDocumentHistoryItemsParams,
  CompareDocumentHistoryItemsResult,
  DocumentHistoryAccessOptions,
  DocumentHistorySaveSource,
  DocumentLockResult,
  GetDocumentHistoryItemParams,
  ListDocumentHistoryParams,
  ListDocumentHistoryResult,
  SaveDocumentHistoryResult,
  UpdateDocumentParams,
  UpdateDocumentResult,
} from './types';
import { assertDocumentWriteWithinLimit } from './writeLimit';

const log = debug('lobe-chat:service:document');

export class DocumentService {
  userId: string;
  private fileModel: FileModel;
  private documentModel: DocumentModel;
  private documentHistoryServiceInstance?: DocumentHistoryService;
  private fileServiceInstance?: FileService;
  private knowledgeBaseModel: KnowledgeBaseModel;
  private editLockService: EditLockService;
  private db: LobeChatDatabase;
  private callerAgentVisibility?: 'private' | 'public' | null;
  private documentAccessScope: DocumentAccessScope;

  private workspaceId?: string;

  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;
    this.fileModel = new FileModel(db, userId, workspaceId);
    this.knowledgeBaseModel = new KnowledgeBaseModel(db, userId, workspaceId);
    this.documentModel = new DocumentModel(
      db,
      userId,
      workspaceId,
      callerAgentVisibility,
      documentAccessScope,
    );
    this.editLockService = new EditLockService(userId);
  }

  private get fileService() {
    this.fileServiceInstance ??= new FileService(this.db, this.userId, this.workspaceId);

    return this.fileServiceInstance;
  }

  private get documentHistoryService() {
    this.documentHistoryServiceInstance ??= new DocumentHistoryService(
      this.db,
      this.userId,
      this.workspaceId,
    );

    return this.documentHistoryServiceInstance;
  }

  /**
   * Whether a document participates in collaborative edit locking. Only
   * workspace documents other members can actually open need the lock:
   * a `visibility: 'private'` row is creator-only (buildWorkspaceWhere hides it
   * from everyone else), so locking it can only ever conflict the creator with
   * themselves — e.g. a stale lease left behind by a publish → unpublish flip
   * turning every autosave into a CONFLICT loop. NULL visibility is treated as
   * public, mirroring buildWorkspaceWhere.
   */
  private isCollaborativeDocument(
    doc: Pick<DocumentItem, 'visibility' | 'workspaceId'> | null | undefined,
  ): boolean {
    return Boolean(this.workspaceId && doc?.workspaceId && doc.visibility !== 'private');
  }

  async assertCanWriteBody(id: string, lockOwnerId?: string) {
    const document = await this.documentModel.findById(id);
    if (!this.isCollaborativeDocument(document)) return;
    if (await this.editLockService.canWrite('document', id, lockOwnerId)) return;
    throw new TRPCError({
      cause: { data: { code: 'DocumentLocked' } },
      code: 'CONFLICT',
      message: 'Document is being edited by another user',
    });
  }

  private async deleteFileRecordAndStorage(fileId: string) {
    const file = await this.fileModel.delete(fileId);
    if (!file?.url || file.url.startsWith('internal://')) return;

    await this.fileService.deleteFile(file.url);
  }

  /**
   * Create a document
   */
  async createDocument(params: {
    content?: string;
    editorData?: Record<string, any>;
    fileType?: string;
    knowledgeBaseId?: string;
    metadata?: Record<string, any>;
    parentId?: string;
    rawData?: string;
    slug?: string;
    title: string;
    visibility?: 'private' | 'public';
    /** Who asked for the write; `system` skips the per-document character limit. Defaults to `user`. */
    writeSource?: DocumentWriteSource;
  }): Promise<DocumentItem> {
    const {
      content,
      editorData,
      title,
      fileType = CUSTOM_DOCUMENT_FILE_TYPE,
      metadata,
      slug,
      visibility,
    } = params;
    // Refuse before any row (including the KB mirror file) is written.
    await assertDocumentWriteWithinLimit({
      charCount: Math.max(content?.length ?? 0, countEditorDataText(editorData)),
      source: params.writeSource,
      userId: this.userId,
      workspaceId: this.workspaceId,
    });

    // Agent tool calls often fill optional ids with "" — that means "unset".
    // Passed through, it reaches the `parent_id` / `knowledge_base_id` FKs and
    // fails the insert with an opaque `Failed query` error.
    const knowledgeBaseId = params.knowledgeBaseId?.trim() || undefined;
    const parentId = params.parentId?.trim() || undefined;
    const sanitizedMetadata = stripAgentShareDocumentProvenance(metadata);

    // Calculate character and line counts
    const totalCharCount = content?.length || 0;
    const totalLineCount = content?.split('\n').length || 0;

    // Resolve visibility upfront so the KB mirror file uses the same policy
    // as the document. A library-root document inherits the KB visibility;
    // parent documents remain navigation-only and do not pass visibility or
    // ACL to children. Without a library or an explicit value it stays
    // undefined, so the row takes the schema default (`'public'` — workspace
    // documents are shared unless asked otherwise). Personal mode ignores the
    // column but still checks the library exists, so a wrong id fails as
    // NOT_FOUND instead of a foreign-key violation.
    let resolvedVisibility: 'private' | 'public' | undefined = visibility;
    if (knowledgeBaseId) {
      const knowledgeBase = await this.knowledgeBaseModel.findById(
        knowledgeBaseId,
        this.callerAgentVisibility,
      );
      if (!knowledgeBase) {
        throw new TRPCError({
          code: 'NOT_FOUND',
          message: `Knowledge base not found: ${knowledgeBaseId}`,
        });
      }
      if (this.workspaceId) resolvedVisibility = knowledgeBase.visibility;
    }

    let fileId: string | null = null;

    // If creating in a knowledge base, create a corresponding file record
    // BUT skip for folders - folders should only exist in the documents table
    if (knowledgeBaseId && fileType !== CUSTOM_FOLDER_FILE_TYPE) {
      const file = await this.fileModel.create(
        {
          fileType,
          knowledgeBaseId,
          metadata: sanitizedMetadata,
          name: title,
          parentId,
          size: totalCharCount,
          url: `internal://document/placeholder`, // Placeholder URL
          ...(resolvedVisibility ? { visibility: resolvedVisibility } : {}),
        },
        false, // Do not insert to global files
      );
      fileId = file.id;
    }

    // Store knowledgeBaseId in metadata for folders (which don't have fileId)
    const finalMetadata =
      knowledgeBaseId && fileType === CUSTOM_FOLDER_FILE_TYPE
        ? { ...sanitizedMetadata, knowledgeBaseId }
        : sanitizedMetadata;

    const document = await this.documentModel.create({
      content,
      editorData,
      fileId,
      fileType,
      filename: title,
      knowledgeBaseId, // Set knowledge_base_id column for all document types
      metadata: finalMetadata,
      pages: undefined,
      parentId,
      slug,
      source: 'document',
      sourceType: 'api',
      title,
      totalCharCount,
      totalLineCount,
      ...(resolvedVisibility ? { visibility: resolvedVisibility } : {}),
    });

    return document;
  }

  /**
   * Publish one private document to the workspace. Thin wrapper around
   * `DocumentModel.publishToWorkspace`, with a side-effect notification so any
   * other workspace member with the page open (referencing chip, etc.) sees
   * the new visibility on the next refresh.
   */
  async publishToWorkspace(documentId: string): Promise<{ documentIds: string[] }> {
    return this.setVisibility(documentId, 'public');
  }

  /**
   * Flip one document's `visibility`. Thin wrapper around
   * `DocumentModel.setVisibility`, plus a side-effect notification so any
   * other workspace member with the page open (referencing chip, editor
   * placeholder, etc.) sees the new visibility on the next refresh — same
   * pattern as `publishToWorkspace`.
   */
  async setVisibility(
    documentId: string,
    visibility: 'private' | 'public',
  ): Promise<{ documentIds: string[] }> {
    const result = await this.documentModel.setVisibility(documentId, visibility);

    if (this.workspaceId) {
      void publishResourceEvent(
        { id: documentId, type: 'document' },
        { actorId: this.userId, type: 'doc.updated' },
      );
    }

    return result;
  }

  /**
   * Create multiple documents in batch (optimized for folder creation)
   * Returns array of created documents with same order as input
   */
  async createDocuments(
    documents: Array<{
      content?: string;
      editorData?: Record<string, any>;
      fileType?: string;
      knowledgeBaseId?: string;
      metadata?: Record<string, any>;
      parentId?: string;
      slug?: string;
      title: string;
      visibility?: 'private' | 'public';
      writeSource?: DocumentWriteSource;
    }>,
  ): Promise<DocumentItem[]> {
    // Create all documents in parallel for better performance
    const results = await Promise.all(documents.map((params) => this.createDocument(params)));

    return results;
  }

  /**
   * Query documents with pagination
   */
  async queryDocuments(params?: QueryDocumentParams) {
    return this.documentModel.query(params);
  }

  /**
   * Get document by ID
   */
  async getDocumentById(id: string) {
    return this.documentModel.findById(id);
  }

  /**
   * Acquire (or refresh) the collaborative edit lock for a workspace document.
   *
   * Doubles as the heartbeat: an active editor calls this on an interval to keep
   * the lease alive, and a locked-out member calls it to take the lock over once
   * it frees up. Locking only applies in workspace context — personal documents
   * always report as unlocked.
   */
  async acquireDocumentLock(id: string): Promise<DocumentLockResult> {
    return this.acquireDocumentLockWithOwner(id, this.userId);
  }

  async acquireDocumentLockWithOwner(id: string, ownerId: string): Promise<DocumentLockResult> {
    if (!this.workspaceId)
      return { expiresAt: null, holderId: null, lockedByOther: false, ownerId: null };

    // Creator-only (private-visibility) documents never take a lease — see
    // isCollaborativeDocument. Refusing here keeps a stale client from minting
    // a lock the write guards would then trip over.
    const doc = await this.documentModel.findById(id);
    if (!this.isCollaborativeDocument(doc))
      return { expiresAt: null, holderId: null, lockedByOther: false, ownerId: null };

    const prevHolder = await this.editLockService.getActiveLock('document', id);
    const result = await this.editLockService.acquire('document', id, ownerId);

    // Broadcast only on a holder edge (first claim / takeover). This method also
    // serves the periodic heartbeat, so a steady-state refresh (same holder)
    // must not emit an event.
    if (
      (result.holderId ?? null) !== (prevHolder?.userId ?? null) ||
      (result.ownerId ?? null) !== (prevHolder?.ownerId ?? null)
    ) {
      void publishResourceEvent(
        { id, type: 'document' },
        {
          actorId: this.userId,
          data: {
            expiresAt: result.expiresAt?.toISOString() ?? null,
            holderId: result.holderId,
            ownerId: result.ownerId,
          },
          type: 'lock.changed',
        },
      );
    }

    return result;
  }

  /**
   * Read-only peek of the current edit lock (does not acquire). Lets a client
   * render a workspace page read-only on open when another member holds it.
   */
  async getDocumentLock(id: string, ownerId?: string): Promise<DocumentLockResult> {
    if (!this.workspaceId)
      return { expiresAt: null, holderId: null, lockedByOther: false, ownerId: null };
    // Private-visibility documents always read as unlocked (no lease can be
    // taken on them), so a viewer of a just-unpublished page is never stranded
    // read-only behind a leftover lease.
    const doc = await this.documentModel.findById(id);
    if (!this.isCollaborativeDocument(doc))
      return { expiresAt: null, holderId: null, lockedByOther: false, ownerId: null };
    const holder = await this.editLockService.getActiveLock('document', id);
    const lockedByOther = holder
      ? holder.ownerId
        ? holder.ownerId !== ownerId
        : holder.userId !== this.userId
      : false;
    return {
      expiresAt: holder?.expiresAt ?? null,
      holderId: holder?.userId ?? null,
      lockedByOther,
      ownerId: holder?.ownerId ?? null,
    };
  }

  /**
   * Release the edit lock if the current user holds it. No-op in personal mode.
   */
  async releaseDocumentLock(id: string): Promise<void> {
    return this.releaseDocumentLockWithOwner(id, this.userId);
  }

  async releaseDocumentLockWithOwner(id: string, ownerId: string): Promise<void> {
    if (!this.workspaceId) return;
    // Only broadcast "unlocked" when we actually released our own lock — if the
    // lease had expired and another member took over, the lock is still held and
    // a bogus holderId:null would wrongly flip their viewers to editable.
    const released = await this.editLockService.release('document', id, ownerId);
    if (!released) return;
    void publishResourceEvent(
      { id, type: 'document' },
      {
        actorId: this.userId,
        data: { expiresAt: null, holderId: null, ownerId: null },
        type: 'lock.changed',
      },
    );
  }

  /**
   * Run a server-initiated read-modify-write (e.g. a Page Agent tool) under the
   * collaborative edit lock. Acquiring the lock up front — rather than only
   * checking it at persist time like {@link updateDocument} — serializes agent
   * writes against other workspace members and rejects when someone else is
   * actively editing, so an agent can no longer silently clobber a human's
   * in-progress edits or another concurrent agent write.
   *
   * No-op in personal mode (no workspace → no collaboration → no lock). When
   * Redis is down the underlying lock degrades to "unlocked" (fail-open), so
   * this never blocks a write.
   */
  async runWithDocumentLock<T>(id: string, fn: (lockOwnerId?: string) => Promise<T>): Promise<T> {
    if (!this.workspaceId) {
      // Diagnostic: distinguishes "no-op because workspaceId is
      // missing at runtime" from "lock actually evaluated".
      log('runWithDocumentLock skip: no workspaceId (id=%s userId=%s)', id, this.userId);
      return fn();
    }

    // Creator-only (private-visibility) documents have no collaborators to
    // serialize against — run without a lease, same as personal mode.
    const targetDoc = await this.documentModel.findById(id);
    if (!this.isCollaborativeDocument(targetDoc)) {
      log('runWithDocumentLock skip: non-collaborative doc (id=%s userId=%s)', id, this.userId);
      return fn();
    }

    // If this user's live editor already holds the lease, ride along on the
    // same ownerId so the acquire below is a pure heartbeat. Stealing the lock
    // with a fresh `server:UUID` would silently rewrite the lease's ownerId,
    // demote the user's saves through the owner-scoped write guard, and on the
    // finally release leave a window where another member could grab the free
    // lock. When we're truly claiming a lock, mint a server-scoped owner id
    // we can identify in release.
    const holderBefore = await this.editLockService.getActiveLock('document', id);
    const heldBeforeByUser = holderBefore?.userId === this.userId;
    const ownerId =
      heldBeforeByUser && holderBefore?.ownerId ? holderBefore.ownerId : `server:${randomUUID()}`;

    const lock = await this.acquireDocumentLockWithOwner(id, ownerId);
    // Diagnostic: surfaces workspaceId/holder/acquire for debugging lock issues.
    log(
      'runWithDocumentLock: id=%s userId=%s ws=%s holderBefore=%s acquired=%o',
      id,
      this.userId,
      this.workspaceId,
      holderBefore?.userId,
      lock,
    );
    if (lock.lockedByOther) {
      throw new TRPCError({
        cause: { data: { code: 'DocumentLocked' } },
        code: 'CONFLICT',
        message: 'Document is being edited by another user',
      });
    }

    try {
      return await fn(ownerId);
    } finally {
      // Only release a lease we freshly claimed. When the same user already
      // held it, leave their session alive — releasing would briefly flip
      // their editor to read-only and let another member grab the lock in
      // the gap before the next client heartbeat.
      if (!heldBeforeByUser) await this.releaseDocumentLockWithOwner(id, ownerId);
    }
  }

  async listDocumentHistory(
    params: ListDocumentHistoryParams,
    options?: DocumentHistoryAccessOptions,
  ): Promise<ListDocumentHistoryResult> {
    return this.documentHistoryService.listDocumentHistory(params, options);
  }

  async getDocumentHistoryItem(
    params: GetDocumentHistoryItemParams,
    options?: DocumentHistoryAccessOptions,
  ) {
    return this.documentHistoryService.getDocumentHistoryItem(params, options);
  }

  async compareDocumentHistoryItems(
    params: CompareDocumentHistoryItemsParams,
    options?: DocumentHistoryAccessOptions,
  ): Promise<CompareDocumentHistoryItemsResult> {
    return this.documentHistoryService.compareDocumentHistoryItems(params, options);
  }

  /**
   * Save a document history snapshot explicitly.
   */
  async saveDocumentHistory(
    documentId: string,
    editorData: Record<string, any>,
    saveSource: DocumentHistorySaveSource,
    lockOwnerId?: string,
  ): Promise<SaveDocumentHistoryResult> {
    const currentDocument = await this.documentModel.findById(documentId);
    if (!currentDocument) {
      throw new Error(`Document not found: ${documentId}`);
    }

    // Same collaborative edit-lock guard as updateDocument: don't record a
    // history snapshot for a workspace document another member is editing, so a
    // locked-out actor (e.g. a Copilot mutation that will itself be rejected)
    // can't pollute the version timeline. The lock holder forwards its
    // `lockOwnerId` so it can still snapshot its own page (e.g. the pre-mutation
    // snapshot a Copilot edit takes) without being blocked by its own lease.
    if (this.isCollaborativeDocument(currentDocument)) {
      const canWrite = await this.editLockService.canWrite('document', documentId, lockOwnerId);
      if (!canWrite) {
        throw new TRPCError({
          cause: { data: { code: 'DocumentLocked' } },
          code: 'CONFLICT',
          message: 'Document is being edited by another user',
        });
      }
    }

    const normalizedEditorData = normalizeEditorDataDiffNodes(editorData);
    const savedAt = new Date();
    const history = await this.documentHistoryService.createHistory({
      documentId,
      editorData: normalizedEditorData,
      saveSource,
      savedAt,
    });

    return { historyId: history.id, savedAt };
  }

  /**
   * Best-effort snapshot of the current document editor state before an automated mutation.
   */
  async trySaveCurrentDocumentHistory(
    documentId: string,
    saveSource: DocumentHistorySaveSource,
    editorDataOverride?: Record<string, any>,
  ): Promise<SaveDocumentHistoryResult | undefined> {
    try {
      const currentDocument = await this.documentModel.findById(documentId);
      const editorData = editorDataOverride ?? currentDocument?.editorData;
      if (!isValidEditorData(editorData)) return undefined;

      const normalizedEditorData = normalizeEditorDataDiffNodes(editorData);
      const savedAt = new Date();
      const history = await this.documentHistoryService.createHistory({
        documentId,
        editorData: normalizedEditorData,
        saveSource,
        savedAt,
      });

      return { historyId: history.id, savedAt };
    } catch (error) {
      console.error('[DocumentService] Failed to save current document history:', error);
      return undefined;
    }
  }

  /**
   * Delete document (recursively deletes children if it's a folder)
   */
  async deleteDocument(id: string, options?: { restrictToCreator?: boolean }) {
    const document = await this.documentModel.findById(id);
    if (!document) return;
    // Descendants created by other members are skipped, not deleted — their
    // parentId FK is `set null`, so they get promoted to root instead of being
    // destroyed by a non-owner's folder delete.
    if (options?.restrictToCreator && document.userId !== this.userId) return;

    // If it's a folder, recursively delete all children first
    if (document.fileType === CUSTOM_FOLDER_FILE_TYPE) {
      const children = await this.db.query.documents.findMany({
        where: and(
          eq(documents.parentId, id),
          buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, documents),
        ),
      });

      // Recursively delete all children
      for (const child of children) {
        await this.deleteDocument(child.id, options);
      }

      // Also delete all files in this folder
      const childFiles = await this.db.query.files.findMany({
        where: and(
          eq(files.parentId, id),
          buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, files),
        ),
      });

      for (const file of childFiles) {
        if (options?.restrictToCreator && file.userId !== this.userId) continue;
        await this.deleteFileRecordAndStorage(file.id);
      }
    }

    // Delete the associated file record if it exists
    if (document.fileId) {
      await this.deleteFileRecordAndStorage(document.fileId);
    }

    // Finally delete the document itself
    const deleted = await this.documentModel.delete(id);
    if (document.workspaceId) dropPageRooms([id]);
    return deleted;
  }

  /**
   * Delete multiple documents in batch
   */
  async deleteDocuments(ids: string[], options?: { restrictToCreator?: boolean }) {
    let targetIds = ids;

    // Workspace bulk deletes from non-owner members only target rows they
    // created; the restriction also applies to each folder's recursive cascade.
    if (options?.restrictToCreator) {
      const rows = await this.documentModel.findByIds(ids);
      targetIds = rows.filter((row) => row.userId === this.userId).map((row) => row.id);
    }

    // Delete each document (which handles recursive deletion for folders)
    await Promise.all(targetIds.map((id) => this.deleteDocument(id, options)));
  }

  /**
   * Update document
   */
  async updateDocument(id: string, params: UpdateDocumentParams): Promise<UpdateDocumentResult> {
    let changed = false;
    const result = await this.db.transaction(async (tx) => {
      const transactionDb = tx as unknown as LobeChatDatabase;
      const documentModel = new DocumentModel(
        transactionDb,
        this.userId,
        this.workspaceId,
        this.callerAgentVisibility,
        this.documentAccessScope,
      );
      const fileModel = new FileModel(transactionDb, this.userId, this.workspaceId);
      const documentHistoryService = new DocumentHistoryService(
        transactionDb,
        this.userId,
        this.workspaceId,
      );

      const currentDocument = await documentModel.findById(id);
      if (!currentDocument) {
        throw new Error(`Document not found: ${id}`);
      }

      // Optimistic-concurrency predicate for the client's CONFLICT recovery:
      // the retry asserts the exact version it verified. Re-read the row with
      // FOR UPDATE so the check-and-write is atomic inside this transaction —
      // an interleaved save from another session either commits first (and
      // fails this predicate) or blocks until we commit.
      if (params.expectedUpdatedAt !== undefined) {
        const [row] = await transactionDb
          .select({ updatedAt: documents.updatedAt })
          .from(documents)
          .where(eq(documents.id, id))
          .for('update');
        if (!row?.updatedAt || row.updatedAt.getTime() !== params.expectedUpdatedAt.getTime()) {
          throw new TRPCError({
            cause: { data: { code: 'DocumentVersionMismatch' } },
            code: 'CONFLICT',
            message: 'Document has been updated by another session',
          });
        }
      }

      // An HTML document's body is its content alone: rich-text editorData sent
      // with it (or with the write that makes it HTML) is never persisted, and
      // any the page carried before is cleared. Left behind, that pre-HTML JSON
      // is what the editor would load and save if the page turned rich-text again.
      const isHtmlDocument =
        (params.fileType ?? currentDocument.fileType) === HTML_DOCUMENT_FILE_TYPE;
      const editorDataParam = isHtmlDocument ? undefined : params.editorData;

      // Accepted-view projections used only for historyAppended comparison and
      // for the "before" snapshot written into history. The persisted editorData
      // keeps any pending diff nodes — they're only normalized when the user
      // explicitly accepts/rejects via DiffAllToolbar.
      const currentEditorDataAccepted = normalizeEditorDataDiffNodes(
        (currentDocument.editorData ?? {}) as Record<string, any>,
      );
      const nextEditorDataAccepted =
        editorDataParam === undefined ? undefined : normalizeEditorDataDiffNodes(editorDataParam);
      const historyAppended =
        nextEditorDataAccepted !== undefined &&
        !isEqual(nextEditorDataAccepted, currentEditorDataAccepted);
      // Mentions are diffed on the accepted view so a chip inside a pending
      // AI diff block only pings once the suggestion is accepted.
      const addedMentionUserIds = historyAppended
        ? diffAddedMentionUserIds(currentEditorDataAccepted, nextEditorDataAccepted)
        : [];

      // Collaborative edit lock guard: reject writes to a workspace document that
      // another member is actively editing, so concurrent edits can't clobber
      // each other. Only the rich-text BODY is locked — metadata-only saves
      // (title/emoji) pass through, since the autosave always re-sends the
      // unchanged body. The lease auto-expires in Redis; when Redis is down this
      // returns null (fail-open) so the lock can't block saving.
      // Switching a page into or out of HTML replaces the body other members see
      // (and clears its editorData), so it is a body change even with no content.
      const htmlTypeChanged =
        isHtmlDocument !== (currentDocument.fileType === HTML_DOCUMENT_FILE_TYPE);
      const contentChanged =
        historyAppended ||
        htmlTypeChanged ||
        (params.content !== undefined && params.content !== currentDocument.content);
      if (
        contentChanged &&
        params.origin !== 'room-projection' &&
        this.isCollaborativeDocument(currentDocument)
      ) {
        const canWrite = await this.editLockService.canWrite('document', id, params.lockOwnerId);
        if (!canWrite) {
          throw new TRPCError({
            cause: { data: { code: 'DocumentLocked' } },
            code: 'CONFLICT',
            message: 'Document is being edited by another user',
          });
        }
      }

      const updates: Record<string, unknown> = {};

      // Checked before anything is persisted. Room projections are checked too:
      // the room accepts browser edits without measuring them, so the
      // projection is the only place a collaborative page's length is enforced.
      // `restoreFromHistoryId` is not an exemption: the client
      // sends it with a body the server does not match against the version, so
      // only server-side restores opt out via `writeSource`. Editor data is
      // measured too because it can arrive without `content`.
      if (params.content !== undefined || editorDataParam !== undefined) {
        await assertDocumentWriteWithinLimit({
          charCount: Math.max(params.content?.length ?? 0, countEditorDataText(editorDataParam)),
          previousCharCount: Math.max(
            currentDocument.content?.length ?? 0,
            countEditorDataText(currentDocument.editorData),
          ),
          source: params.writeSource,
          userId: this.userId,
          workspaceId: this.workspaceId,
        });
      }

      if (params.content !== undefined) {
        updates.content = params.content;
        updates.totalCharCount = params.content.length;
        updates.totalLineCount = params.content.split('\n').length;
      }

      if (editorDataParam !== undefined) {
        updates.editorData = editorDataParam;
      } else if (isHtmlDocument && currentDocument.editorData != null) {
        updates.editorData = null;
      }

      if (params.fileType !== undefined) {
        updates.fileType = params.fileType;
      }

      if (params.title !== undefined) {
        updates.title = params.title;
        updates.filename = params.title;
      }

      if (params.metadata !== undefined) {
        updates.metadata = params.metadata;
      }

      if (params.parentId !== undefined) {
        updates.parentId = params.parentId;
      }

      // The lock lease is refreshed by the client heartbeat (acquireDocumentLock),
      // so a save does not need to touch it.

      const rowUpdated = Object.keys(updates).length > 0 || historyAppended;
      let updatedAt = currentDocument.updatedAt;
      if (rowUpdated) {
        const committedVersion = await documentModel.update(id, updates as Partial<DocumentItem>);
        if (!committedVersion) throw new Error(`Document not found: ${id}`);
        updatedAt = committedVersion;
      }

      const savedAt = historyAppended ? updatedAt : undefined;
      if (historyAppended) {
        await documentHistoryService.createHistory({
          ...params.history,
          breakAutosaveWindow: params.breakAutosaveWindow,
          documentId: id,
          editorData: currentEditorDataAccepted,
          saveSource: params.saveSource ?? 'autosave',
          savedAt: updatedAt,
        });
      }

      if ((params.title !== undefined || params.parentId !== undefined) && currentDocument.fileId) {
        const fileUpdates: Record<string, string | null> = {};
        if (params.title !== undefined) fileUpdates.name = params.title;
        if (params.parentId !== undefined) fileUpdates.parentId = params.parentId;
        await fileModel.update(currentDocument.fileId, fileUpdates);
      }

      changed = rowUpdated;

      return {
        ...(addedMentionUserIds.length > 0 ? { addedMentionUserIds } : {}),
        historyAppended,
        id,
        savedAt,
        updatedAt,
      };
    });

    // Notify other workspace members that the document changed so their open
    // editor refreshes immediately (best-effort; the heartbeat is the fallback).
    if (this.workspaceId && changed) {
      void publishResourceEvent(
        { id, type: 'document' },
        { actorId: this.userId, type: 'doc.updated' },
      );
    }

    return result;
  }

  /**
   * Parse file and create a document for page editor (without page tags)
   */
  async parseDocument(fileId: string): Promise<LobeDocument> {
    const { filePath, file, cleanup } = await this.fileService.downloadFileToLocal(
      fileId,
      undefined,
      { maxBytes: MAX_FILE_PARSE_SIZE },
    );

    const logPrefix = `[${file.name}]`;
    log(`${logPrefix} Starting to parse file as document, path: ${filePath}`);

    try {
      // Strips the <page> wrappers and applies the stored-content cap inside the worker thread.
      const fileDocument = await parseFileInWorker(filePath, { fileId, mode: 'document' });

      log(`${logPrefix} File parsed successfully %O`, {
        fileType: fileDocument.fileType,
        size: fileDocument.content.length,
      });

      // Extract title from metadata or use file name (remove extension)
      const title =
        fileDocument.metadata?.title ||
        file.name.replace(/\.(pdf|docx?|md|markdown)$/i, '') ||
        'Untitled';

      const cleanContent = fileDocument.content;

      const document = await this.documentModel.create({
        content: cleanContent,
        fileId,
        fileType: CUSTOM_DOCUMENT_FILE_TYPE,
        filename: title,
        metadata: fileDocument.metadata,
        parentId: file.parentId,
        source: file.url,
        sourceType: 'file',
        title,
        totalCharCount: cleanContent.length,
        totalLineCount: cleanContent.split('\n').length,
      });

      return document as LobeDocument;
    } catch (error) {
      const parseError = normalizeParseFileError(error);
      console.error(`${logPrefix} File parsing failed:`, parseError);
      throw parseError;
    } finally {
      await cleanup();
    }
  }

  /**
   * Parse file content.
   *
   * Idempotent: returns the document already stored for the file, and serializes
   * the cache write per file so two concurrent calls cannot both insert one.
   *
   * The database handle must not be an open transaction — the advisory lock is
   * transaction scoped, so a nested call would hold it until the outer
   * transaction commits instead of releasing it after the insert.
   */
  async parseFile(
    fileId: string,
    accessScope: FileAccessScope = ordinaryFileAccessScope,
  ): Promise<LobeDocument> {
    // Idempotent: return existing document if already parsed
    const existingDoc = await this.documentModel.findByFileId(fileId, accessScope);
    if (existingDoc) return existingDoc as LobeDocument;

    const { filePath, file, cleanup } = await this.fileService.downloadFileToLocal(
      fileId,
      accessScope,
      { maxBytes: MAX_FILE_PARSE_SIZE },
    );

    const logPrefix = `[${file.name}]`;
    log(`${logPrefix} Starting to parse file, path: ${filePath}`);

    try {
      // Parsed and capped on a worker thread: a heavy file must not hold this one.
      const fileDocument = await parseFileInWorker(filePath, { fileId, mode: 'file' });

      log(`${logPrefix} File parsed successfully %O`, {
        fileType: fileDocument.fileType,
        size: fileDocument.content.length,
      });

      // Extract title from metadata or use file name (remove extension)
      const title =
        fileDocument.metadata?.title ||
        file.name.replace(/\.(pdf|docx?|md|markdown)$/i, '') ||
        'Untitled';

      const document = await this.db.transaction(async (tx) => {
        // The existence check above ran before the download and the parse, so
        // another request can have published its own row for this file in the
        // meantime. Serialize the write per file so two concurrent `parseFile`
        // calls cannot both insert one. `hashtext` returns int4 while
        // `pg_advisory_xact_lock` takes bigint, so cast. Under the default READ
        // COMMITTED isolation the re-check below takes a fresh snapshot once the
        // lock is granted, so it sees whatever the holder committed. The parse
        // itself stays outside the transaction: it downloads and reads the whole
        // file, and holding a connection that long would turn every large upload
        // into pool pressure.
        await tx.execute(
          sql`SELECT pg_advisory_xact_lock(hashtext(${`parseFile:${fileId}`})::bigint)`,
        );

        const transactionDb = tx as unknown as LobeChatDatabase;
        const transactionDocumentModel = new DocumentModel(
          transactionDb,
          this.userId,
          this.workspaceId,
          this.callerAgentVisibility,
          this.documentAccessScope,
        );

        // Whoever inserted first wins; discard this parse rather than adding a
        // second document for the same file.
        const raced = await transactionDocumentModel.findByFileId(fileId, accessScope);
        if (raced) return raced;

        return transactionDocumentModel.create({
          content: fileDocument.content,
          fileId,
          fileType: CUSTOM_DOCUMENT_FILE_TYPE, // Use custom/document for all parsed files
          filename: title,
          metadata: fileDocument.metadata,
          pages: fileDocument.pages,
          parentId: file.parentId,
          source: file.url,
          sourceType: 'file',
          title,
          totalCharCount: fileDocument.totalCharCount,
          totalLineCount: fileDocument.totalLineCount,
        });
      });

      return document as LobeDocument;
    } catch (error) {
      const parseError = normalizeParseFileError(error);
      console.error(`${logPrefix} File parsing failed:`, parseError);
      throw parseError;
    } finally {
      await cleanup();
    }
  }
}