Skip to content

feat(EE): full-text search in attachments - #1502

Merged
Philipinho merged 9 commits into
mainfrom
feat/attachment-search
Sep 2, 2025
Merged

Philipinho merged 9 commits into
mainfrom
feat/attachment-search

Conversation

@Philipinho

@Philipinho Philipinho commented Aug 28, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features
    • Global Search Spotlight in the header (desktop and mobile) with Cmd/Ctrl+K shortcut.
    • Filter results by space and content type (Pages or Attachments).
    • Attachment search (Enterprise/Cloud Business), including file download from results and highlight snippets.
  • Improvements
    • Unified search experience with clearer result items and responsive design.
  • Backend
    • Automatic background indexing of uploaded PDFs and DOCX files to power attachment search; initial results may appear after indexing completes.

@coderabbitai

coderabbitai Bot commented Aug 28, 2025 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Philipinho has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 44 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 98de89a and 1dd312e.

📒 Files selected for processing (3)
  • apps/client/src/features/search/components/search-result-item.tsx (1 hunks)
  • apps/client/src/features/search/components/share-search-spotlight.tsx (2 hunks)
  • apps/server/src/database/migrations/20250901T184612-attachments-search.ts (1 hunks)

Walkthrough

Adds attachment indexing/search pipeline on server with new queue jobs, EE integration, DB migration/typing fields, and repo projections. Introduces license helper and applies it in sharing. On client, replaces search spotlight with a unified, filterable spotlight supporting page and attachment search, integrates it into layout/header, adds shortcuts, routes, and related services/types.

Changes

Cohort / File(s) Summary
Server: Attachments indexing/search pipeline
apps/server/src/core/attachment/processors/attachment.processor.ts, apps/server/src/core/attachment/services/attachment.service.ts, apps/server/src/integrations/queue/constants/queue.constants.ts, apps/server/src/database/migrations/20250901T184612-attachments-search.ts, apps/server/src/database/types/db.d.ts, apps/server/src/database/repos/attachment/attachment.repo.ts, apps/server/src/core/search/dto/search.dto.ts
Adds queue jobs ATTACHMENT_INDEX_CONTENT/ATTACHMENT_INDEXING, enqueues indexing for .pdf/.docx, dynamically resolves EE indexing service, migrates attachments with text_content/tsv, extends typings, standardizes repo field projections, and makes SearchDTO.spaceId optional.
Server: License helper and share usage
apps/server/src/common/helpers/utils.ts, apps/server/src/core/share/share.controller.ts
Adds hasLicenseOrEE helper and uses it in share controller to compute hasLicenseKey.
Server: Dependencies and submodule
apps/server/package.json, apps/server/src/ee
Adds mammoth and pdfjs-dist deps; updates EE submodule pointer.
Client: Search Spotlight overhaul
apps/client/src/features/search/components/*, apps/client/src/features/search/hooks/use-unified-search.ts, apps/client/src/features/search/queries/search-query.ts, apps/client/src/features/search/services/search-service.ts, apps/client/src/features/search/types/search.types.ts, apps/client/src/features/search/search-spotlight.tsx (removed), apps/client/src/features/share/components/share-shell.tsx
Replaces old spotlight with new component, filters (with CSS module), and result item; adds unified search hook, attachment query/service/types; gates attachment search by license; updates share-shell import; removes legacy spotlight.
Client: App integration and shortcuts
apps/client/src/components/layouts/global/app-header.tsx, apps/client/src/components/layouts/global/layout.tsx, apps/client/src/features/editor/page-editor.tsx, apps/client/src/features/editor/title-editor.tsx, apps/client/src/features/space/components/sidebar/space-sidebar.tsx, apps/client/src/lib/app-route.ts
Integrates SearchSpotlight into layout and header; adds Cmd/Ctrl+K shortcut in editors; removes sidebar spotlight; adds /search route; wires desktop/mobile search controls.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Client as Client UI
  participant Server as Server (API)
  participant Queue as Attachment Queue
  participant Proc as AttachmentProcessor
  participant EE as EE Attachment Service

  rect rgba(230,240,255,0.4)
    User->>Client: Upload/Create or Update Attachment
    Client->>Server: POST /attachments
    Server-->>Queue: Enqueue ATTACHMENT_INDEX_CONTENT {attachmentId} (if .pdf/.docx)
    Note right of Server: 2 attempts, exponential backoff 10s
  end

  rect rgba(240,255,230,0.4)
    Queue-->>Proc: process(ATTACHMENT_INDEX_CONTENT)
    Proc->>Proc: require(...) EE module
    alt EE module resolves
      Proc->>EE: indexAttachment(attachmentId)
      EE-->>Proc: OK/Fail
    else Load fails
      Proc->>Proc: Log error and return
    end
  end

  rect rgba(255,245,230,0.4)
    Queue-->>Proc: process(ATTACHMENT_INDEXING {workspaceId})
    Proc->>EE: indexAttachments(workspaceId)
    EE-->>Proc: OK/Fail
  end
Loading
sequenceDiagram
  autonumber
  actor User
  participant Header as Header/Layout
  participant Spotlight as SearchSpotlight
  participant Filters as Filters
  participant Hook as useUnifiedSearch
  participant API as Search API

  User->>Header: Click search / Cmd/Ctrl+K
  Header->>Spotlight: open()
  Spotlight->>Spotlight: set query (debounced 300ms)
  Spotlight->>Filters: onFiltersChange(space/contentType)
  Spotlight->>Hook: useUnifiedSearch({query, spaceId, contentType})
  alt contentType=attachment AND license present
    Hook->>API: POST /search-attachments
  else
    Hook->>API: POST /search
  end
  API-->>Hook: results
  Hook-->>Spotlight: results
  Spotlight-->>User: Render list (pages/attachments)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I thump the keys with whiskered glee,
New queues now hum—indexing spree!
A spotlight blooms for search at night,
Pages, files—both come to light.
With licenses checked and datasets grown,
I burrow through text, well-known.
Hop hop—ship it, carrots shown! 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/attachment-search

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Philipinho Philipinho added the EE Enterprise edition label Aug 28, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/server/src/core/attachment/services/attachment.service.ts (2)

122-126: Propagate error and clean up the uploaded file on failure.

Currently only logs; the file stays orphaned and the caller may get a null attachment without an error.

     } catch (err) {
-      // delete uploaded file on error
-      this.logger.error(err);
+      // delete uploaded file on error
+      this.logger.error('File upload error:', err);
+      await this.deleteRedundantFile(filePath);
+      throw new BadRequestException('Failed to upload file');
     }

68-74: Use ORs here; current AND allows mismatched fields to slip through.

Throw if any of pageId, fileExt, or workspaceId doesn’t match.

-      if (
-        existingAttachment.pageId !== pageId &&
-        existingAttachment.fileExt !== preparedFile.fileExtension &&
-        existingAttachment.workspaceId !== workspaceId
-      ) {
+      if (
+        existingAttachment.pageId !== pageId ||
+        existingAttachment.fileExt !== preparedFile.fileExtension ||
+        existingAttachment.workspaceId !== workspaceId
+      ) {
         throw new BadRequestException('File attachment does not match');
       }
🧹 Nitpick comments (8)
apps/server/package.json (2)

69-79: EE-only feature: consider relocating to optional/EE deps to keep CE installs lean.

If indexing is EE-scoped, move mammoth/pdfjs-dist out of the CE server’s hard deps to avoid bloating CE containers and CI. Options:

  • Make them optionalDependencies here and load conditionally when EE is enabled.
  • Or declare them in the EE package (preferred if the EE module owns the implementation) and peerDependencies-gate from the EE module.

Within this file (removals in current hunk):

-    "mammoth": "^1.10.0",
-    ...
-    "pdfjs-dist": "^5.4.54",

Outside the current hunk (add near the root of package.json):

"optionalDependencies": {
  "mammoth": "^1.10.0",
  "pdfjs-dist": "^5.4.54"
}

Also consider declaring engines to reflect runtime expectations (Node 18+ recommended for these libs and Nest 11):

"engines": {
  "node": ">=18"
}

69-79: Dependencies verified; implement PDF/DOCX indexing guardrails

[email protected] requires Node ≥20.16.0 || ≥22.3.0—our Node v24.3.0 satisfies this. Licenses are Apache-2.0 (pdfjs-dist) and BSD-2-Clause (mammoth); unpacked sizes are ~35 MB and ~2 MB, respectively—use lazy dynamic imports to mitigate cold-start bloat.

Enforce:

  • Max file size/pages and wall-clock CPU timeouts to prevent zip-bombs.
  • Low BullMQ concurrency for CPU/memory-heavy parsing.
  • Legacy pdfjs-dist build with workers disabled in Node:
const { getDocument, GlobalWorkerOptions } = await import('pdfjs-dist/legacy/build/pdf.mjs');
GlobalWorkerOptions.workerSrc = null;
const loadingTask = getDocument({ data: pdfBuffer, disableFontFace: true });
apps/server/src/ee (1)

1-1: Ensure CI fetches submodules.

If not already, configure the CI checkout to pull submodules to avoid build/runtime surprises.

Example for GitHub Actions:

- uses: actions/checkout@v4
  with:
    submodules: recursive
    fetch-depth: 0
apps/server/src/integrations/queue/constants/queue.constants.ts (1)

12-12: Normalize job string to kebab-case (consistency with existing values).

Existing job strings use kebab-case; this one uses an underscore. Align for consistency and easier ops/metrics filtering.

-  ATTACHMENT_INDEX_CONTENT = 'attachment_index_content',
+  ATTACHMENT_INDEX_CONTENT = 'attachment-index-content',
apps/server/src/database/migrations/20250827T184612-attachments-search.ts (1)

7-7: Keep tsv in sync automatically (generated column or trigger).

Optional but recommended: derive tsv from text_content to prevent drift when only one column is updated.

Option A (preferred, Postgres 12+):

ALTER TABLE attachments
  DROP COLUMN tsv,
  ADD COLUMN tsv tsvector GENERATED ALWAYS AS (to_tsvector('simple', coalesce(text_content, ''))) STORED;

Option B (trigger):

CREATE OR REPLACE FUNCTION attachments_tsv_sync() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  NEW.tsv := to_tsvector('simple', coalesce(NEW.text_content, ''));
  RETURN NEW;
END$$;

DROP TRIGGER IF EXISTS attachments_tsv_update ON attachments;
CREATE TRIGGER attachments_tsv_update
BEFORE INSERT OR UPDATE OF text_content ON attachments
FOR EACH ROW EXECUTE FUNCTION attachments_tsv_sync();
apps/server/src/database/repos/attachment/attachment.repo.ts (1)

15-30: Include textContent and tsv in baseFields (keeps Attachment shape consistent, helps indexer).

Prevents silent omission of newly introduced fields when selecting/returning.

   private baseFields: Array<keyof Attachment> = [
     'id',
     'fileName',
     'filePath',
     'fileSize',
     'fileExt',
     'mimeType',
     'type',
     'creatorId',
     'pageId',
     'spaceId',
     'workspaceId',
     'createdAt',
     'updatedAt',
     'deletedAt',
+    'textContent',
+    'tsv',
   ];
apps/server/src/core/attachment/processors/attachment.processor.ts (2)

11-14: Make ModuleRef immutable in the constructor.
Marking DI properties readonly is consistent and prevents accidental reassignment.

-    private readonly attachmentService: AttachmentService,
-    private moduleRef: ModuleRef,
+    private readonly attachmentService: AttachmentService,
+    private readonly moduleRef: ModuleRef,

33-36: Optional: prefer dynamic import for future ESM compatibility.
If/when the server moves to ESM, require will fail. import() keeps tree-shaking/CE builds intact and works in CJS too.

-        try {
-          // eslint-disable-next-line @typescript-eslint/no-require-imports
-          eeIndexing = require('./../../../ee/attachment-indexing/attachment-indexing.service');
-        } catch (err) {
+        try {
+          eeIndexing = await import('../../../ee/attachment-indexing/attachment-indexing.service');
+        } catch (err) {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 08135a2 and 294009e.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • apps/server/package.json (2 hunks)
  • apps/server/src/core/attachment/processors/attachment.processor.ts (2 hunks)
  • apps/server/src/core/attachment/services/attachment.service.ts (3 hunks)
  • apps/server/src/database/migrations/20250827T184612-attachments-search.ts (1 hunks)
  • apps/server/src/database/repos/attachment/attachment.repo.ts (6 hunks)
  • apps/server/src/database/types/db.d.ts (1 hunks)
  • apps/server/src/ee (1 hunks)
  • apps/server/src/integrations/queue/constants/queue.constants.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/server/src/core/attachment/processors/attachment.processor.ts (1)
apps/server/src/integrations/queue/processors/backlinks.processor.ts (1)
  • Processor (11-135)
🔇 Additional comments (7)
apps/server/src/ee (2)

1-1: LGTM on pinning to an immutable commit.

No further concerns on this file; the pointer is precise and reproducible.


1-1: Verify EE submodule bump and AttachmentIndexingService export

The submodule at apps/server/src/ee failed to clone (remote not found), so please manually ensure:

  • The EE submodule’s remote URL and pinned commit (d8a37faf0f312b91778caa6756108bf43df4ebb8) are correct.
  • The EE code exports AttachmentIndexingService (e.g. via export class AttachmentIndexingService or named/default export) and the server’s import paths match.
  • The server code compiles successfully against the updated EE APIs.
apps/server/src/database/types/db.d.ts (1)

42-43: LGTM: Types align with migration.

textContent and tsv are correctly added as nullable fields on Attachments.

apps/server/src/core/attachment/services/attachment.service.ts (2)

25-27: LGTM: Queue wiring imports added.


39-40: LGTM: BullMQ queue injected for attachment indexing.

apps/server/src/core/attachment/processors/attachment.processor.ts (2)

6-6: LGTM: DI hook import is correct.
No issues with importing ModuleRef.


31-50: Add guards for missing EE provider and validate job payload

  • Check that attachmentIndexingService (result of moduleRef.get) is defined before calling indexAttachment, and bail with a clear error if it’s missing.
  • Ensure job.data?.attachmentId is present and skip the job with an error log when it’s not.
  • Verify that the EE module actually registers AttachmentIndexingService in its providers so moduleRef.get can succeed.

- search filters
- attachments search ui
- and more

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (37)
apps/server/src/common/helpers/utils.ts (1)

91-98: Add tests for gating edge cases.

Please add unit tests for: licenseKey set/empty/whitespace, isCloud true/false, plan "business"/"Business"/undefined.

I can generate a small Jest spec for utils.hasLicenseOrEE if helpful.

apps/server/src/core/share/share.controller.ts (2)

181-185: Mirror dual field in tree endpoint for consistency.

Apply:

       return {
         ...(await this.shareService.getShareTree(dto.shareId, workspace.id)),
-        hasLicenseKey: hasLicenseOrEE({
+        hasEEAccess: hasLicenseOrEE({
+          licenseKey: workspace.licenseKey,
+          isCloud: this.environmentService.isCloud(),
+          plan: workspace.plan,
+        }),
+        // kept for backward compatibility; deprecate later
+        hasLicenseKey: hasLicenseOrEE({
           licenseKey: workspace.licenseKey,
           isCloud: this.environmentService.isCloud(),
           plan: workspace.plan,
         }),
       };

69-74: Add hasEEAccess while retaining hasLicenseKey for backward compatibility
Client code across apps/client (e.g. shared‐page.tsx:58, share‐shell.tsx:167, workspace types, search hooks, settings sidebar, etc.) relies on hasLicenseKey. Introduce hasEEAccess and keep hasLicenseKey as an alias to avoid breaking changes.

       return {
         ...(await this.shareService.getSharedPage(dto, workspace.id)),
-        hasLicenseKey: hasLicenseOrEE({
+        hasEEAccess: hasLicenseOrEE({
           licenseKey: workspace.licenseKey,
           isCloud: this.environmentService.isCloud(),
           plan: workspace.plan,
         }),
+        // kept for backward compatibility; deprecate later
+        hasLicenseKey: hasLicenseOrEE({
+          licenseKey: workspace.licenseKey,
+          isCloud: this.environmentService.isCloud(),
+          plan: workspace.plan,
+        }),
       };

apps/server/src/core/share/share.controller.ts lines 69–74

apps/client/src/features/editor/page-editor.tsx (1)

225-228: Prevent default and stop propagation for mod+K

Avoid any editor/browser side-effects and keep behavior consistent with mod+S.

Apply:

-            if ((event.ctrlKey || event.metaKey) && event.code === 'KeyK') {
-              searchSpotlight.open();
-              return true;
-            }
+            if ((event.ctrlKey || event.metaKey) && event.code === 'KeyK') {
+              event.preventDefault();
+              event.stopPropagation();
+              searchSpotlight.open();
+              return true;
+            }
apps/client/src/features/share/components/share-shell.tsx (1)

184-185: Render ShareSearchSpotlight only when shareId exists

Saves mounting work when the page isn’t a share context.

-      <ShareSearchSpotlight shareId={shareId} />
+      {shareId && <ShareSearchSpotlight shareId={shareId} />}
apps/server/src/core/search/dto/search.dto.ts (1)

26-33: Parse limit/offset as numbers (and optionally bound them)

Without class-transformer @type, validated values may remain strings depending on global pipe config.

-import {
-  IsBoolean,
-  IsNotEmpty,
-  IsNumber,
-  IsOptional,
-  IsString,
-} from 'class-validator';
+import { IsBoolean, IsNotEmpty, IsNumber, IsOptional, IsString } from 'class-validator';
+import { Type } from 'class-transformer';
@@
   @IsOptional()
+  @Type(() => Number)
   @IsNumber()
   limit?: number;
@@
   @IsOptional()
+  @Type(() => Number)
   @IsNumber()
   offset?: number;

Optionally add bounds:

-  @IsNumber()
+  @IsNumber()
+  @Min(1)
+  @Max(100)
   limit?: number;
apps/client/src/features/editor/title-editor.tsx (2)

90-103: Also prevent default/stop propagation for mod+K

Mirror mod+S handling to avoid bubbling and ensure consistent UX.

           if ((event.ctrlKey || event.metaKey) && event.code === "KeyK") {
-            searchSpotlight.open();
+            event.preventDefault();
+            event.stopPropagation();
+            searchSpotlight.open();
             return true;
           }

206-214: Optional: unify hotkeys via getHotkeyHandler

Keeps key handling consistent and centralized.

-      onKeyDown={(event) => {
-        // First handle the search hotkey
-        getHotkeyHandler([["mod+F", openSearchDialog]])(event);
-
-        // Then handle other key events
-        handleTitleKeyDown(event);
-      }}
+      onKeyDown={getHotkeyHandler([
+        ["mod+F", openSearchDialog],
+      ])}

Note: keep editorProps.handleDOMEvents for mod+S/mod+K.

apps/client/src/features/search/components/search-spotlight-filters.module.css (2)

1-7: Add WebKit scrollbar styling for consistent UX across browsers

scrollbar-width only affects Firefox. Add WebKit scrollbar rules to keep visuals consistent.

 .filtersContainer {
   display: flex;
   gap: 8px;
   overflow-x: auto;
   padding: 8px 0;
   scrollbar-width: thin;
 }
+
+/* WebKit scrollbar for Chrome/Edge/Safari */
+.filtersContainer::-webkit-scrollbar {
+  height: 6px;
+}
+.filtersContainer::-webkit-scrollbar-thumb {
+  background-color: var(--mantine-color-gray-3);
+  border-radius: 4px;
+}
+.filtersContainer:hover::-webkit-scrollbar-thumb {
+  background-color: var(--mantine-color-gray-4);
+}

15-18: Confirm CSS Nesting support (nested &:hover in .css module)

This uses native CSS Nesting. Verify our build/browsers target supports it; otherwise, expand the selector to a top-level .filterButton:hover rule to avoid being dropped by older processors.

Optional non-nested fallback:

 .filterButton {
   white-space: nowrap;
   flex-shrink: 0;
   font-size: 13px;
   height: 32px;
   padding: 0 12px;
   color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-gray-6));
-  &:hover {
-    color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-gray-6));
-  }
+}
+
+.filterButton:hover {
+  color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-gray-6));
 }
apps/client/src/features/search/queries/search-query.ts (1)

47-55: Stabilize queryKey and enable request cancellation to avoid duplicate fetches on fast typing

  • Using the whole params object in the key risks cache misses if identity changes.
  • Wire React Query’s signal into Axios to cancel in-flight searches on input changes.
 export function useAttachmentSearchQuery(
   params: IPageSearchParams,
 ): UseQueryResult<IAttachmentSearch[], Error> {
   return useQuery({
-    queryKey: ["attachment-search", params],
-    queryFn: () => searchAttachments(params),
+    queryKey: [
+      "attachment-search",
+      params.query,
+      params.spaceId ?? null,
+      params.shareId ?? null,
+    ],
+    queryFn: ({ signal }) => searchAttachments(params, { signal }),
     enabled: !!params.query,
+    keepPreviousData: true,
   });
 }

Follow-up: update searchAttachments signature as in the service diff (next comment).

Ensure other search hooks aren’t relying on object identity for keys; aligning them reduces unnecessary refetches.

apps/client/src/features/search/services/search-service.ts (1)

31-36: Add AbortSignal support for cancellable searches

Pass through React Query’s abort signal to Axios to prevent race conditions and wasted work during fast typing.

-export async function searchAttachments(
-  params: IPageSearchParams,
-): Promise<IAttachmentSearch[]> {
-  const req = await api.post<IAttachmentSearch[]>("/search-attachments", params);
+export async function searchAttachments(
+  params: IPageSearchParams,
+  opts?: { signal?: AbortSignal },
+): Promise<IAttachmentSearch[]> {
+  const req = await api.post<IAttachmentSearch[]>(
+    "/search-attachments",
+    params,
+    { signal: opts?.signal },
+  );
   return req.data;
 }
apps/client/src/components/layouts/global/app-header.tsx (1)

22-24: Remove unused import

shareSearchSpotlight is imported but not used.

-import {
-  searchSpotlight,
-  shareSearchSpotlight,
-} from "@/features/search/constants.ts";
+import { searchSpotlight } from "@/features/search/constants.ts";
apps/client/src/components/layouts/global/layout.tsx (2)

11-13: Confirm hook expects slug, not id; tighten param typing

You pass spaceSlug into useGetSpaceBySlugQuery. Ensure that hook truly accepts a slug (and not an id) and that its queryFn calls the slug-based API. Also consider typing the route params to make intent explicit.

-  const { spaceSlug } = useParams();
+  const { spaceSlug } = useParams<{ spaceSlug?: string }>();

7-7: Minor: remove unused React import (new JSX runtime)

With modern tooling, explicit React import is unnecessary in .tsx files unless used directly.

-import React from "react";
apps/server/src/integrations/queue/constants/queue.constants.ts (1)

12-13: Clarify job intent with brief doc comments or more specific names.

ATTACHMENT_INDEX_CONTENT vs ATTACHMENT_INDEXING are easy to confuse. Consider short JSDoc (single-attachment vs workspace backfill) or rename to ATTACHMENT_INDEX_ONE and ATTACHMENT_INDEX_WORKSPACE for self-documenting intent.

apps/client/src/features/search/types/search.types.ts (1)

41-61: Reuse existing types to prevent drift and improve IntelliSense.

Instead of redefining nested shapes, pick from ISpace/IPage as you did for IPageSearch.

 export interface IAttachmentSearch {
   id: string;
   fileName: string;
   pageId: string;
   creatorId: string;
   createdAt: Date;
   updatedAt: Date;
   rank: string;
   highlight: string;
-  space: {
-    id: string;
-    name: string;
-    slug: string;
-    icon: string;
-  };
-  page: {
-    id: string;
-    title: string;
-    slugId: string;
-  };
+  space: Pick<ISpace, "id" | "name" | "slug" | "icon">;
+  page: Pick<IPage, "id" | "title" | "slugId">;
 }
apps/server/src/core/attachment/services/attachment.service.ts (2)

107-122: Make extension check robust and dedupe jobs with a deterministic jobId.

Null-guard fileExt, avoid repeated jobs for the same attachment, and keep the queue tidy.

-      // Only index PDFs and DOCX files
-      if (['.pdf', '.docx'].includes(attachment.fileExt.toLowerCase())) {
-        await this.attachmentQueue.add(
-          QueueJob.ATTACHMENT_INDEX_CONTENT,
-          {
-            attachmentId: attachmentId,
-          },
-          {
-            attempts: 2,
-            backoff: {
-              type: 'exponential',
-              delay: 10000,
-            },
-          },
-        );
-      }
+      // Only index PDFs and DOCX files
+      const INDEXABLE_EXTENSIONS = new Set<string>(['.pdf', '.docx']);
+      const ext = (attachment.fileExt || '').toLowerCase();
+      if (INDEXABLE_EXTENSIONS.has(ext)) {
+        await this.attachmentQueue.add(
+          QueueJob.ATTACHMENT_INDEX_CONTENT,
+          { attachmentId },
+          {
+            jobId: `attachment:index-content:${attachmentId}`,
+            attempts: 2,
+            backoff: { type: 'exponential', delay: 10_000 },
+            removeOnComplete: 500,
+            removeOnFail: 1000,
+          },
+        );
+      }

123-127: Update misleading comment or handle deletion on failure.

The catch says “delete uploaded file on error,” but only logs. Either adjust the comment or perform deletion where appropriate.

-    } catch (err) {
-      // delete uploaded file on error
-      this.logger.error(err);
-    }
+    } catch (err) {
+      // indexing enqueue failed; keep the uploaded file
+      this.logger.error('Attachment indexing enqueue failed', err);
+    }
apps/server/src/core/attachment/processors/attachment.processor.ts (2)

11-16: Make ModuleRef dependency readonly.

Minor nit: mark moduleRef readonly for consistency with other ctor deps.

-  constructor(
-    private readonly attachmentService: AttachmentService,
-    private moduleRef: ModuleRef,
-  ) {
+  constructor(
+    private readonly attachmentService: AttachmentService,
+    private readonly moduleRef: ModuleRef,
+  ) {

31-57: Guard against missing EE service and avoid re-requiring per job.

If ModuleRef can’t resolve the service, current code will throw on method access. Also, requiring on every job adds overhead.

-        const attachmentEeService = this.moduleRef.get(
+        const attachmentEeService = this.moduleRef.get(
           AttachmentEeModule.AttachmentEeService,
           { strict: false },
         );
 
-        if (job.name === QueueJob.ATTACHMENT_INDEX_CONTENT) {
+        if (!attachmentEeService) {
+          this.logger.error('AttachmentEeService not registered in ModuleRef');
+          return;
+        }
+
+        if (job.name === QueueJob.ATTACHMENT_INDEX_CONTENT) {
           await attachmentEeService.indexAttachment(job.data.attachmentId);
         } else if (job.name === QueueJob.ATTACHMENT_INDEXING) {
           await attachmentEeService.indexAttachments(
             job.data.workspaceId,
           );
         }

Additionally, consider caching the resolved service:

// at class scope
private eeService?: any;

// helper
private getEeService(): any | undefined {
  if (this.eeService) return this.eeService;
  // eslint-disable-next-line @typescript-eslint/no-require-imports
  const mod = require('./../../../ee/attachments-ee/attachment-ee.service');
  this.eeService = this.moduleRef.get(mod.AttachmentEeService, { strict: false });
  return this.eeService;
}

Then replace the require+get block with const attachmentEeService = this.getEeService();.

apps/client/src/features/search/components/search-spotlight.tsx (4)

3-3: Import useCallback to stabilize handlers.

We’ll use it below for handleFiltersChange.

-import React, { useState, useMemo } from "react";
+import React, { useState, useMemo, useCallback } from "react";

28-33: Type search params to avoid “any” and catch mismatches at compile time.

-  const searchParams = useMemo(() => {
-    const params: any = {
+  const searchParams = useMemo(() => {
+    const params: UseUnifiedSearchParams = {
       query: debouncedSearchQuery,
       contentType: filters.contentType || "page", // Only used for frontend routing
     };

Note: add the import:

import type { UseUnifiedSearchParams } from "../hooks/use-unified-search.ts";

57-59: Stabilize handler to reduce child re-renders.

-  const handleFiltersChange = (newFilters: any) => {
-    setFilters(newFilters);
-  };
+  const handleFiltersChange = useCallback((newFilters: any) => {
+    setFilters(newFilters);
+  }, []);

95-99: Optional: show a loading state.

Consider a lightweight loader while isLoading is true to improve UX.

apps/client/src/features/search/components/search-result-item.tsx (3)

33-41: Avoid // @ts-ignore by narrowing slug types.

Current ignore hides real typing gaps. Prefer optional chaining and a helper that accepts optional space slug.

If possible, change buildPageUrl signature to accept optional spaceName. Locally, at least narrow values:

-        //@ts-ignore
-        to={buildPageUrl(
-          attachmentResult.space.slug,
+        to={buildPageUrl(
+          attachmentResult.space?.slug as any,
           attachmentResult.page.slugId,
           attachmentResult.page.title,
         )}

Longer-term: make buildPageUrl(spaceName?: string, ...).


63-71: Improve a11y: add aria-label and tooltip i18n.

ActionIcon lacks accessible name and is not localized.

-          <ActionIcon
+          <ActionIcon
             variant="subtle"
             color="gray"
             onClick={handleDownload}
-            title="Download attachment"
+            title="Download attachment"
+            aria-label="Download attachment"
           >

77-86: Same ts-ignore concern for page link.

Prefer typed narrowing over suppression.

-        //@ts-ignore
-        to={buildPageUrl(
-          pageResult.space.slug,
+        to={buildPageUrl(
+          pageResult.space?.slug as any,
           pageResult.slugId,
           pageResult.title,
         )}

Longer-term: make buildPageUrl(spaceName?: string, ...).

apps/client/src/features/search/hooks/use-unified-search.ts (3)

26-31: Stabilize query key; avoid object identity churn.

Using the whole params object can cause unnecessary refetches.

-    queryKey: ["unified-search", searchType, params],
+    queryKey: [
+      "unified-search",
+      searchType,
+      params.query,
+      params.spaceId ?? null,
+      params.shareId ?? null,
+    ],

38-39: Don’t query on whitespace-only strings.

Trim to prevent accidental fetches.

-    enabled: !!params.query,
+    enabled: !!params.query?.trim(),

17-25: Expose effective search type to consumers to prevent UI/data mismatch.

When license is missing, search falls back to pages but UI may still expect attachments. Return the effective type.

Option:

-export function useUnifiedSearch(
+export function useUnifiedSearch(
   params: UseUnifiedSearchParams,
-): UseQueryResult<UnifiedSearchResult[], Error> {
+): UseQueryResult<UnifiedSearchResult[], Error> & { searchType: "page" | "attachment" } {
   const { hasLicenseKey } = useLicense();
   const isAttachmentSearch =
     params.contentType === "attachment" && hasLicenseKey;
   const searchType = isAttachmentSearch ? "attachment" : "page";
 
-  return useQuery({
+  const query = useQuery({
     ...
   });
+  return Object.assign(query, { searchType });
}

Ensure callers use the returned searchType to render the right item component.

apps/client/src/features/search/components/search-spotlight-filters.tsx (6)

27-30: Type the filters callback to a concrete shape.

Avoid any; improves DX and catches mistakes.

-interface SearchSpotlightFiltersProps {
-  onFiltersChange?: (filters: any) => void;
+interface FiltersState {
+  spaceId: string | null;
+  contentType: "page" | "attachment" | null;
+}
+interface SearchSpotlightFiltersProps {
+  onFiltersChange?: (filters: FiltersState) => void;
   spaceId?: string;
 }

68-75: Notify on filter changes via deps; current effect runs only once.

If parent passes a new spaceId later, or contentType is changed programmatically, it won’t propagate.

-  useEffect(() => {
-    if (onFiltersChange) {
-      onFiltersChange({
-        spaceId: selectedSpaceId,
-        contentType,
-      });
-    }
-  }, []);
+  useEffect(() => {
+    onFiltersChange?.({ spaceId: selectedSpaceId, contentType });
+  }, [selectedSpaceId, contentType, onFiltersChange]);

Also add:

+  useEffect(() => {
+    setSelectedSpaceId(spaceId || null);
+  }, [spaceId]);

77-84: Localize visible strings; t() is imported but unused.

Hardcoded labels (“Pages”, “Attachments”) block i18n.

Example:

-  const contentTypeOptions = [
-    { value: "page", label: "Pages" },
+  const contentTypeOptions = [
+    { value: "page", label: t("search.filters.pages", "Pages") },
     {
-      value: "attachment",
-      label: "Attachments",
+      value: "attachment",
+      label: t("search.filters.attachments", "Attachments"),
       disabled: !hasLicenseKey,
     },
   ];

Apply similar to “Space:”, “All spaces”, “Find a space”, “Type”, “Enterprise”, etc.


86-95: Deduplicate handlers; use handleFilterChange for space too.

Single path reduces divergence.

-  const handleSpaceSelect = (spaceId: string | null) => {
-    setSelectedSpaceId(spaceId);
-    if (onFiltersChange) {
-      onFiltersChange({
-        spaceId: spaceId,
-        contentType,
-      });
-    }
-  };
+  const handleSpaceSelect = (spaceId: string | null) =>
+    handleFilterChange("spaceId", spaceId);

219-221: Minor: compute label once to avoid find on every render.

-            {contentType
-              ? `Type: ${contentTypeOptions.find((opt) => opt.value === contentType)?.label || contentType}`
-              : "Type"}
+            {`${
+              t("search.filters.typePrefix", "Type:")
+            } ${
+              (contentTypeOptions.find((o) => o.value === contentType)?.label ??
+                t("search.filters.type", "Type"))
+            }`}

120-137: Add aria-labels to filter buttons for accessibility.

-          <Button
+          <Button
             variant="subtle"
             color="gray"
             size="sm"
+            aria-label="Select space filter"
             rightSection={<IconChevronDown size={14} />}
             leftSection={<IconBuilding size={16} />}
             className={classes.filterButton}
             fw={500}
           >

And similarly for the Type button: aria-label="Select content type filter".

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 294009e and 24db249.

📒 Files selected for processing (23)
  • apps/client/src/components/layouts/global/app-header.tsx (2 hunks)
  • apps/client/src/components/layouts/global/layout.tsx (1 hunks)
  • apps/client/src/features/editor/page-editor.tsx (2 hunks)
  • apps/client/src/features/editor/title-editor.tsx (3 hunks)
  • apps/client/src/features/search/components/search-result-item.tsx (1 hunks)
  • apps/client/src/features/search/components/search-spotlight-filters.module.css (1 hunks)
  • apps/client/src/features/search/components/search-spotlight-filters.tsx (1 hunks)
  • apps/client/src/features/search/components/search-spotlight.tsx (1 hunks)
  • apps/client/src/features/search/hooks/use-unified-search.ts (1 hunks)
  • apps/client/src/features/search/queries/search-query.ts (2 hunks)
  • apps/client/src/features/search/search-spotlight.tsx (0 hunks)
  • apps/client/src/features/search/services/search-service.ts (2 hunks)
  • apps/client/src/features/search/types/search.types.ts (1 hunks)
  • apps/client/src/features/share/components/share-shell.tsx (1 hunks)
  • apps/client/src/features/space/components/sidebar/space-sidebar.tsx (0 hunks)
  • apps/client/src/lib/app-route.ts (1 hunks)
  • apps/server/src/common/helpers/utils.ts (1 hunks)
  • apps/server/src/core/attachment/processors/attachment.processor.ts (2 hunks)
  • apps/server/src/core/attachment/services/attachment.service.ts (4 hunks)
  • apps/server/src/core/search/dto/search.dto.ts (1 hunks)
  • apps/server/src/core/share/share.controller.ts (3 hunks)
  • apps/server/src/ee (1 hunks)
  • apps/server/src/integrations/queue/constants/queue.constants.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • apps/client/src/features/search/search-spotlight.tsx
  • apps/client/src/features/space/components/sidebar/space-sidebar.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/server/src/ee
🧰 Additional context used
🧬 Code graph analysis (11)
apps/client/src/features/search/queries/search-query.ts (2)
apps/client/src/features/search/types/search.types.ts (2)
  • IPageSearchParams (35-39)
  • IAttachmentSearch (41-61)
apps/client/src/features/search/services/search-service.ts (1)
  • searchAttachments (31-36)
apps/server/src/core/share/share.controller.ts (1)
apps/server/src/common/helpers/utils.ts (1)
  • hasLicenseOrEE (91-98)
apps/client/src/components/layouts/global/layout.tsx (2)
apps/client/src/features/space/queries/space-query.ts (1)
  • useGetSpaceBySlugQuery (98-107)
apps/client/src/features/search/components/search-spotlight.tsx (1)
  • SearchSpotlight (15-104)
apps/server/src/common/helpers/utils.ts (2)
apps/client/src/lib/config.ts (1)
  • isCloud (40-42)
apps/server/src/integrations/environment/environment.service.ts (1)
  • isCloud (164-169)
apps/client/src/features/search/services/search-service.ts (1)
apps/client/src/features/search/types/search.types.ts (2)
  • IPageSearchParams (35-39)
  • IAttachmentSearch (41-61)
apps/client/src/features/search/hooks/use-unified-search.ts (3)
apps/client/src/features/search/types/search.types.ts (3)
  • IPageSearch (6-18)
  • IAttachmentSearch (41-61)
  • IPageSearchParams (35-39)
apps/client/src/ee/hooks/use-license.tsx (1)
  • useLicense (4-7)
apps/client/src/features/search/services/search-service.ts (2)
  • searchAttachments (31-36)
  • searchPage (10-15)
apps/client/src/components/layouts/global/app-header.tsx (1)
apps/client/src/features/search/components/search-control.tsx (2)
  • SearchControl (19-35)
  • SearchMobileControl (41-56)
apps/client/src/features/search/components/search-result-item.tsx (3)
apps/client/src/features/search/types/search.types.ts (2)
  • IPageSearch (6-18)
  • IAttachmentSearch (41-61)
apps/client/src/features/page/page.utils.ts (1)
  • buildPageUrl (14-23)
apps/client/src/lib/utils.tsx (1)
  • getPageIcon (87-95)
apps/client/src/features/search/components/search-spotlight.tsx (6)
apps/client/src/ee/hooks/use-license.tsx (1)
  • useLicense (4-7)
apps/client/src/features/search/hooks/use-unified-search.ts (1)
  • useUnifiedSearch (17-40)
apps/client/src/features/search/components/search-result-item.tsx (1)
  • SearchResultItem (17-111)
apps/client/src/features/search/constants.ts (1)
  • searchSpotlightStore (3-3)
apps/client/src/features/search/components/search-spotlight-filters.tsx (1)
  • SearchSpotlightFilters (32-252)
apps/client/src/features/search/search-spotlight.tsx (1)
  • SearchSpotlight (16-83)
apps/client/src/features/search/components/search-spotlight-filters.tsx (2)
apps/client/src/ee/hooks/use-license.tsx (1)
  • useLicense (4-7)
apps/client/src/features/space/queries/space-query.ts (1)
  • useGetSpacesQuery (34-43)
apps/server/src/core/attachment/processors/attachment.processor.ts (1)
apps/server/src/integrations/queue/processors/backlinks.processor.ts (1)
  • Processor (11-135)
🪛 ast-grep (0.38.6)
apps/client/src/features/search/components/search-result-item.tsx

[warning] 57-57: Usage of dangerouslySetInnerHTML detected. This bypasses React's built-in XSS protection. Always sanitize HTML content using libraries like DOMPurify before injecting it into the DOM to prevent XSS attacks.
Context: dangerouslySetInnerHTML
Note: [CWE-79] Improper Neutralization of Input During Web Page Generation [REFERENCES]
- https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
- https://cwe.mitre.org/data/definitions/79.html

(react-unsafe-html-injection)


[warning] 102-102: Usage of dangerouslySetInnerHTML detected. This bypasses React's built-in XSS protection. Always sanitize HTML content using libraries like DOMPurify before injecting it into the DOM to prevent XSS attacks.
Context: dangerouslySetInnerHTML
Note: [CWE-79] Improper Neutralization of Input During Web Page Generation [REFERENCES]
- https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
- https://cwe.mitre.org/data/definitions/79.html

(react-unsafe-html-injection)

🪛 Biome (2.1.2)
apps/client/src/features/search/components/search-result-item.tsx

[error] 58-58: Avoid passing content using the dangerouslySetInnerHTML prop.

Setting content using code can expose users to cross-site scripting (XSS) attacks

(lint/security/noDangerouslySetInnerHtml)


[error] 103-103: Avoid passing content using the dangerouslySetInnerHTML prop.

Setting content using code can expose users to cross-site scripting (XSS) attacks

(lint/security/noDangerouslySetInnerHtml)

🔇 Additional comments (11)
apps/server/src/core/share/share.controller.ts (1)

34-34: No action needed: hasLicenseOrEE is properly exported via the common/helpers barrel.

apps/client/src/lib/app-route.ts (1)

4-4: LGTM: new SEARCH route constant

Route key and path look consistent with the existing convention.

apps/client/src/features/editor/page-editor.tsx (1)

52-52: LGTM: import for searchSpotlight

Import aligns with the new global search entrypoint.

apps/client/src/features/share/components/share-shell.tsx (1)

37-37: LGTM: updated ShareSearchSpotlight import path

Matches the new components location.

apps/server/src/core/search/dto/search.dto.ts (1)

14-16: No action needed: optional spaceId is correctly scoped
The search controller checks user permissions when spaceId is provided, and the search service defaults to restricting results to the caller’s accessible spaces when spaceId is omitted.

apps/client/src/features/editor/title-editor.tsx (1)

29-29: LGTM: searchSpotlight import

Matches the shared search trigger used elsewhere.

apps/client/src/features/search/services/search-service.ts (1)

3-8: Validate date field types returned from the API

IAttachmentSearch.createdAt/updatedAt are typed as Date, but Axios will return strings unless the client transforms responses. Confirm api normalizes these to Date; otherwise, change the interface to string or parse here.

Also applies to: 31-36

apps/client/src/components/layouts/global/app-header.tsx (1)

90-97: Nice: unified search trigger wired for desktop and mobile

Clean separation with responsive Groups and a shared searchSpotlight.open handler looks good.

apps/client/src/components/layouts/global/layout.tsx (1)

20-20: LGTM: Spotlight rendered once at layout root with optional space scope

Passing space?.id is safe and keeps Spotlight globally available.

apps/client/src/features/search/types/search.types.ts (1)

46-49: Confirm runtime wire type (Date vs string).

If the API returns ISO strings for createdAt/updatedAt, typing as Date can mislead consumers. Either keep as string or ensure deserialization on fetch.

apps/server/src/core/attachment/services/attachment.service.ts (1)

107-122: Do we need to support .doc as well?

Earlier iterations mentioned .doc; current code indexes only .pdf/.docx. If .doc isn’t supported by the EE parser, this is fine—just confirming intent.

Comment on lines +91 to +98
export function hasLicenseOrEE(opts: {
licenseKey: string;
plan: string;
isCloud: boolean;
}): boolean {
const { licenseKey, plan, isCloud } = opts;
return Boolean(licenseKey) || (isCloud && plan === 'business');
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden license/plan check: tolerate nullish inputs and normalize plan case.

Workspace.licenseKey/plan may be null/undefined or have different casing (e.g., "Business"). Current strict check risks false negatives for paying cloud customers.

Apply:

-export function hasLicenseOrEE(opts: {
-  licenseKey: string;
-  plan: string;
-  isCloud: boolean;
-}): boolean {
-  const { licenseKey, plan, isCloud } = opts;
-  return Boolean(licenseKey) || (isCloud && plan === 'business');
-}
+export function hasLicenseOrEE(opts: {
+  licenseKey?: string | null;
+  plan?: string | null;
+  isCloud: boolean;
+}): boolean {
+  const { licenseKey, plan, isCloud } = opts;
+  const planId = plan?.toLowerCase();
+  return Boolean(licenseKey?.trim()) || (isCloud && planId === 'business');
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function hasLicenseOrEE(opts: {
licenseKey: string;
plan: string;
isCloud: boolean;
}): boolean {
const { licenseKey, plan, isCloud } = opts;
return Boolean(licenseKey) || (isCloud && plan === 'business');
}
export function hasLicenseOrEE(opts: {
licenseKey?: string | null;
plan?: string | null;
isCloud: boolean;
}): boolean {
const { licenseKey, plan, isCloud } = opts;
const planId = plan?.toLowerCase();
return Boolean(licenseKey?.trim()) || (isCloud && planId === 'business');
}
🤖 Prompt for AI Agents
In apps/server/src/common/helpers/utils.ts around lines 91–98, the current
hasLicenseOrEE check can false-negative when licenseKey or plan are
null/undefined or when plan uses different casing; update the function to
tolerate nullish inputs and normalize values: treat licenseKey as present only
if it's a non-empty string after trimming (guard against undefined/null), coerce
isCloud to a boolean, and normalize plan with toLowerCase().trim() before
comparing to 'business'; then return true if the normalized licenseKey exists OR
(isCloud truthy AND normalized plan === 'business').

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (4)
apps/client/src/features/search/components/search-result-item.tsx (4)

24-29: Encode URL and use noopener/noreferrer for safer downloads.

Prevents broken URLs and window.opener hijack.

Apply:

-      const downloadUrl = `/api/files/${attachmentResult.id}/${attachmentResult.fileName}`;
-      window.open(downloadUrl, "_blank");
+      const downloadUrl = `/api/files/${encodeURIComponent(attachmentResult.id)}/${encodeURIComponent(attachmentResult.fileName)}`;
+      const win = window.open(downloadUrl, "_blank", "noopener,noreferrer");
+      if (win) win.opener = null;

53-59: XSS: sanitize attachment highlight before injecting HTML.

Current use of dangerouslySetInnerHTML is unsafe.

Apply:

-            {attachmentResult?.highlight && (
-              <Text
-                opacity={0.6}
-                size="xs"
-                dangerouslySetInnerHTML={{ __html: attachmentResult.highlight }}
-              />
-            )}
+            {attachmentResult?.highlight && (
+              <Text opacity={0.6} size="xs">
+                <span
+                  dangerouslySetInnerHTML={{
+                    __html: DOMPurify.sanitize(attachmentResult.highlight, {
+                      ALLOWED_TAGS: ["mark", "em", "strong"],
+                      ALLOWED_ATTR: [],
+                    }),
+                  }}
+                />
+              </Text>
+            )}

98-104: XSS: sanitize page highlight before injecting HTML.

Mirror the attachment fix.

Apply:

-            {pageResult?.highlight && (
-              <Text
-                opacity={0.6}
-                size="xs"
-                dangerouslySetInnerHTML={{ __html: pageResult.highlight }}
-              />
-            )}
+            {pageResult?.highlight && (
+              <Text opacity={0.6} size="xs">
+                <span
+                  dangerouslySetInnerHTML={{
+                    __html: DOMPurify.sanitize(pageResult.highlight, {
+                      ALLOWED_TAGS: ["mark", "em", "strong"],
+                      ALLOWED_ATTR: [],
+                    }),
+                  }}
+                />
+              </Text>
+            )}

1-9: Add DOMPurify import for sanitizing highlights.

Required for the fixes below.

Apply:

 import React from "react";
+import DOMPurify from "dompurify";
🧹 Nitpick comments (3)
apps/client/src/features/search/components/search-result-item.tsx (3)

62-69: Add accessible name to the download button.

Improves a11y.

Apply:

-          <ActionIcon
+          <ActionIcon
             variant="subtle"
             color="gray"
             onClick={handleDownload}
             title="Download attachment"
+            aria-label="Download attachment"
           >

34-39: Avoid // @ts-ignore by widening buildPageUrl input.

Let buildPageUrl accept an optional space slug to match Partial. Removes the need to ignore TS.

Apply in apps/client/src/features/page/page.utils.ts:

-export const buildPageUrl = (
-  spaceName: string,
+export const buildPageUrl = (
+  spaceName: string | undefined,
   pageSlugId: string,
   pageTitle?: string,
 ): string => {
-  if (spaceName === undefined) {
+  if (spaceName === undefined) {
     return `/p/${buildPageSlug(pageSlugId, pageTitle)}`;
   }
   return `/s/${spaceName}/p/${buildPageSlug(pageSlugId, pageTitle)}`;
 };

Then remove both //@ts-ignore usages here.

Also applies to: 79-83


10-20: Prefer discriminated props over boolean + casts.

Reduces type assertions and runtime mismatch risk.

Example:

type SearchResultItemProps =
  | { result: IAttachmentSearch; isAttachmentResult: true; showSpace?: boolean }
  | { result: IPageSearch; isAttachmentResult: false; showSpace?: boolean };

Then branch on isAttachmentResult without casts.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5ac095c and de48f0d.

📒 Files selected for processing (1)
  • apps/client/src/features/search/components/search-result-item.tsx (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/client/src/features/search/components/search-result-item.tsx (3)
apps/client/src/features/search/types/search.types.ts (2)
  • IPageSearch (6-18)
  • IAttachmentSearch (41-61)
apps/client/src/features/page/page.utils.ts (1)
  • buildPageUrl (14-23)
apps/client/src/lib/utils.tsx (1)
  • getPageIcon (87-95)
🪛 Biome (2.1.2)
apps/client/src/features/search/components/search-result-item.tsx

[error] 57-57: Avoid passing content using the dangerouslySetInnerHTML prop.

Setting content using code can expose users to cross-site scripting (XSS) attacks

(lint/security/noDangerouslySetInnerHtml)


[error] 102-102: Avoid passing content using the dangerouslySetInnerHTML prop.

Setting content using code can expose users to cross-site scripting (XSS) attacks

(lint/security/noDangerouslySetInnerHtml)

🪛 ast-grep (0.38.6)
apps/client/src/features/search/components/search-result-item.tsx

[warning] 56-56: Usage of dangerouslySetInnerHTML detected. This bypasses React's built-in XSS protection. Always sanitize HTML content using libraries like DOMPurify before injecting it into the DOM to prevent XSS attacks.
Context: dangerouslySetInnerHTML
Note: [CWE-79] Improper Neutralization of Input During Web Page Generation [REFERENCES]
- https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
- https://cwe.mitre.org/data/definitions/79.html

(react-unsafe-html-injection)


[warning] 101-101: Usage of dangerouslySetInnerHTML detected. This bypasses React's built-in XSS protection. Always sanitize HTML content using libraries like DOMPurify before injecting it into the DOM to prevent XSS attacks.
Context: dangerouslySetInnerHTML
Note: [CWE-79] Improper Neutralization of Input During Web Page Generation [REFERENCES]
- https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
- https://cwe.mitre.org/data/definitions/79.html

(react-unsafe-html-injection)

🔇 Additional comments (1)
apps/client/src/features/search/components/search-result-item.tsx (1)

8-8: Import source fixed—good.

Using types from the types module avoids accidental circular deps.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (5)
apps/server/package.json (1)

70-70: DOCX parsing: enforce size/time limits and cap extracted text length

Mammoth will unzip and parse untrusted .docx; add guardrails to avoid CPU/ZIP-bomb spikes and huge DB rows.

Suggested checks:

  • Reject files > X MB (consistent with existing upload limits).
  • Timebox parsing and abort on >N paragraphs/chars; truncate text_content to a sane cap (e.g., 1–2 MB) before persisting.
  • Sanitize/control memory when unzipping.

I can draft a helper that enforces these caps in the attachment indexing job if useful.

apps/server/src/database/migrations/20250901T184612-attachments-search.ts (4)

1-1: Tighten typing: use generated DB type instead of any

Prefer the generated DB type from Kysely codegen to catch drift at compile time.

-import { type Kysely, sql } from 'kysely';
+import { type Kysely, sql } from 'kysely';
+import type { DB } from '../../database/types/db'; // adjust relative path if needed
-export async function up(db: Kysely<any>): Promise<void> {
+export async function up(db: Kysely<DB>): Promise<void> {
 ...
-export async function down(db: Kysely<any>): Promise<void> {
+export async function down(db: Kysely<DB>): Promise<void> {

3-9: Optional: make tsv a generated column instead of using a trigger

Reduces trigger overhead and centralizes logic in schema; use if you don’t need per-row custom configs.

-    .addColumn('tsv', sql`tsvector`, (col) => col)
+    // For Postgres ≥ 12, a stored generated column works well:
+    // ALTER TABLE ... ADD COLUMN tsv tsvector GENERATED ALWAYS AS (to_tsvector('pg_catalog.english', coalesce(text_content, ''))) STORED
+    // Kysely raw SQL:
+    .execute();
+  await sql`ALTER TABLE attachments
+            ADD COLUMN IF NOT EXISTS tsv tsvector
+            GENERATED ALWAYS AS (to_tsvector('pg_catalog.english', coalesce(text_content, ''))) STORED`.execute(db);
+  await sql`CREATE INDEX IF NOT EXISTS attachments_tsv_gin_idx
+            ON attachments USING GIN (tsv)`.execute(db);
+  return;

If you apply this, omit the trigger comment above.


3-9: Nit: column name clarity

Consider search_vector instead of tsv for readability.


3-9: Cap stored text size to protect row bloat

Large PDFs/DOCX can inflate text_content; consider truncating to a max length before persisting (e.g., first 1–2 MB).

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between de48f0d and 98de89a.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • apps/client/src/features/editor/page-editor.tsx (2 hunks)
  • apps/client/src/features/share/components/share-shell.tsx (1 hunks)
  • apps/server/package.json (2 hunks)
  • apps/server/src/database/migrations/20250901T184612-attachments-search.ts (1 hunks)
  • apps/server/src/database/types/db.d.ts (1 hunks)
  • apps/server/src/ee (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • apps/client/src/features/share/components/share-shell.tsx
  • apps/server/src/ee
  • apps/client/src/features/editor/page-editor.tsx
  • apps/server/src/database/types/db.d.ts
🔇 Additional comments (1)
apps/server/package.json (1)

80-80: No server-side imports of pdfjs-dist; safe to keep as CommonJS
Verified no import or require('pdfjs-dist') in apps/server, tsconfig uses module: "commonjs", and there’s no Jest ESM config—no adjustments needed.

@Philipinho
Philipinho merged commit f12866c into main Sep 2, 2025
github-actions Bot added a commit to antiagingrecord/docmost that referenced this pull request Oct 9, 2025
4231ba9 Merge commit '042836cb6d7cc1f71af3ce44c7957f8abbbf8f25' into feat/aar_edition
042836c sync
4f1f0ba fix
3164b69 feat: api keys management (EE) (docmost#1665)
16c1e86 fix comment space
c9b1cad sync
bf8cf62 feat: Typesense search driver (EE) (docmost#1664)
5a2e16a Merge commit '31350303760163384113bf49d07127e886f94907' into feat/aar_edition
3bc710d Adds CLAUDE.md documentation
16914f1 Block search for non-indexed shares
ca75e29 Set default page mode to Read
3135030 fix editor converter (docmost#1647)
3fae41a fix: editor performance improvements (docmost#1648)
b50e256 sync
1f3b0c7 cloud fix
3c4cab0 v0.23.2
4de25a8 invalidate queries on space deletion
cf5bbb1 fix import html processing
ac17521 sync
9ac180f fix: enhance page import (docmost#1570)
46669fe (cloud) disable page sharing in trial mode
fe6ecdf fix: update combobox props in SpaceSelect component (docmost#1564)
04ae1d7 Allow lastColumnResizable in table
1280f96 feat: implement space and workspace icons (docmost#1558)
61d1cf8 fix: reset file inputs after import
f413720 - sync - reinstantiate S3 client to fix file upload errors during import - delete import zip file after use
8e16ad9 v0.23.1
7ada3cb fix: page import task (docmost#1551)
47c5417 sync
dc06502 sync
091e790 fix attachment search in cloud
ae24ea2 v0.23.0
9df6061 lock file
31053e2 update mermaid
eb8e850 use debug
c99bfb8 make print better
26ea04e sync
6cc58c5 sync
7d2ff34 UI fixes
b08d37f fix
d43ee77 remove debug log
5d91eb4 feat: queue imported attachments for indexing
3e9f6b1 Remove version from docker-compose.yml [deprecated] (docmost#1011)
db55de9 feat: progressive web app (docmost#614)
1919eba New Crowdin updates (docmost#1522)
7951b2e New Crowdin updates (docmost#1509)
73b78f6 more translations
cf7534d fix version display
adec36d fix: adjust margins - use default browser highlight background
f9e1080 sync
00e499b Fixing extra page bug on print (docmost#1478)
5ee6e46 checkbox aligned to text (docmost#1486)
1f797c3 fix: confluence drawio import (docmost#1518)
f12866c feat(EE): full-text search in attachments (docmost#1502)
dcbb65d feat(EE): LDAP integration (docmost#1515)
5968764 feat: emoji callout icon (docmost#1323)
242fb6b fix: set mermaid theme based on computed color scheme (docmost#1438)
74cd890 feat(EE): implement SSO group sync for SAML and OIDC (docmost#1452)
509622a ignore type error
937386e fix: hide table handles in readonly mode
60a373f fix: readonly editor table responsiveness
73ee6ee feat: subpages (child pages) list node (docmost#1462)
7d1e5bc feat: table row/column drag and drop (docmost#1467)
aa58e27 fix: exclude deleted pages (docmost#1494)
08135a2 sync
d92a942 sync
5012a68 sync
5a33777 feat: debug mode env variable (docmost#1450)
3b85f4b fix: enforce C collation for page position ordering to ensure consistent behavior in Postgres 17+ (docmost#1446)
cb2a039 fix: invalidate trashed page from tree state
95b7be6 fix: hide trash from can view permission (docmost#1445)
b0c5572 fix nested taskList in markdown export (docmost#1443)
dddfd48 feat: add attachments support for single page exports (docmost#1440)
aa6eec7 fix: exclude trashed pages from position generation
97a7701 fix local storage copy function (docmost#1442)
b97eb85 sync

git-subtree-dir: vendor/app
git-subtree-split: 4231ba9
@Philipinho
Philipinho deleted the feat/attachment-search branch December 14, 2025 19:07
nulluserid pushed a commit to N2con-Inc/docmost that referenced this pull request Dec 17, 2025
* feat(EE): fulltext search in attachments

* feat: global search
- search filters
- attachments search ui
- and more

* fix import

* fix import

* rename migration

* add GIN index

* fix table name

* sanitize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

EE Enterprise edition

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant