Skip to content

feat: implement space and workspace icons - #1558

Merged
Philipinho merged 5 commits into
mainfrom
feat/enhance-avatar-icons
Sep 15, 2025
Merged

Philipinho merged 5 commits into
mainfrom
feat/enhance-avatar-icons

Conversation

@Philipinho

@Philipinho Philipinho commented Sep 14, 2025 •

Copy link
Copy Markdown
Member
  • Create reusable AvatarUploader component supporting avatars, space icons, and workspace icons
  • Add Sharp package for server-side image resizing and optimization
  • Create reusable AvatarUploader component supporting avatars, space icons, and workspace icons
  • Support removing icons

Summary by CodeRabbit

  • New Features

    • Upload/remove avatars, space and workspace icons with success/error notifications and loading states.
    • Centralized avatar uploader used across account, space, workspace, listings, and switcher.
    • New UI strings for image actions and status messages.
  • Improvements

    • Max upload size increased to 10MB.
    • Uploaded images are optimized/resized for faster loading.
    • Filenames with special characters are sanitized.
    • Space Settings: details pane now scrolls; members list is read-only when you lack manage permissions.

- Create reusable AvatarUploader component supporting avatars, space icons, and workspace icons
- Add Sharp package for server-side image resizing and optimization
- Create reusable AvatarUploader component supporting avatars, space icons, and workspace icons
- Support removing icons
@coderabbitai

coderabbitai Bot commented Sep 14, 2025 •

Copy link
Copy Markdown

Walkthrough

Adds type-aware icon/avatar support across client and server: new AvatarUploader and WorkspaceIcon UI, CustomAvatar/type-aware getAvatarUrl, attachment client APIs and types, server image processing with sharp, new remove-icon endpoint/DTO, icon enum renames, MAX_AVATAR_SIZE → 10MB, and removal of legacy DTO/type locations.

Changes

Cohort / File(s) Summary
i18n strings
apps/client/public/locales/en-US/translation.json
Added six image-related UI strings: Icon, Upload image, Remove image, Failed to remove image, Image exceeds 10MB limit., Image removed successfully.
New Avatar uploader component
apps/client/src/components/common/avatar-uploader.tsx
New AvatarUploader component: hidden file input, accepts PNG/JPEG/JPG, client-side 10MB validation, upload/remove handlers, notifications, i18n and props for current image, styling, callbacks, loading/disabled states.
Custom avatar & config URL
apps/client/src/components/ui/custom-avatar.tsx, apps/client/src/lib/config.ts
CustomAvatar gains type?: AvatarIconType (and mt?), now calls getAvatarUrl(avatarUrl, type); getAvatarUrl signature updated to accept type and build /attachments/img/${type}/ and applies encodeURI.
Attachments client: types & services
apps/client/src/features/attachments/types/attachment.types.ts, .../services/attachment-service.ts, .../services/index.ts
Added IAttachment interface, AvatarIconType and AttachmentType enums; new client APIs: uploadIcon, uploadUserAvatar, uploadSpaceIcon, uploadWorkspaceIcon, and removeAvatar, removeSpaceIcon, removeWorkspaceIcon; index re-exports them.
Client type realignment
apps/client/src/lib/types.ts, apps/client/src/features/editor/.../drawio-view.tsx, .../excalidraw-view.tsx, apps/client/src/features/page/services/page-service.ts
Removed IAttachment from lib/types.ts; updated imports to consume IAttachment from new attachments types; adjusted type-only import paths.
Account / Workspace / Space UI integration
apps/client/src/features/user/components/account-avatar.tsx, apps/client/src/features/workspace/components/settings/components/workspace-icon.tsx, apps/client/src/pages/settings/workspace/workspace-settings.tsx
AccountAvatar and new WorkspaceIcon use AvatarUploader; workspace settings render WorkspaceIcon; upload/remove flows wired to attachments client APIs and workspace atom.
Space UI: avatars and props
apps/client/src/features/space/components/space-details.tsx, .../settings-modal.tsx, .../sidebar/space-select.tsx, .../sidebar/switch-space.tsx, .../space-grid.tsx, .../space-list.tsx, .../spaces-page/all-spaces-list.tsx, .../sidebar/space-sidebar.tsx
Replaced Mantine Avatar with CustomAvatar (type SPACE_ICON) across space UIs; added AvatarUploader in SpaceDetails; added/propagated props (readOnly, value, width, opened, clearable, spaceIcon); layout tweaks (ScrollArea, responsive rows).
Space types change
apps/client/src/features/space/types/space.types.ts
ISpace.icon: string → ISpace.logo?: string (renamed, now optional). Removed includeAttachments? from IExportSpaceParams.
Top menu / styling tweaks
apps/client/src/components/layouts/global/top-menu.tsx, apps/client/src/features/space/components/space-grid.module.css, apps/client/src/features/editor/styles/core.css
Workspace avatar now uses AvatarIconType.WORKSPACE_ICON; small CSS tweak to dark background shade; hr border color switched to theme-aware mixins.
Server: deps & filename utils
apps/server/package.json, apps/server/src/common/helpers/utils.ts
Added sharp dependency, pinned sanitize-filename-ts; sanitizeFileName now also replaces # with _.
Server attachment constants
apps/server/src/core/attachment/attachment.constants.ts
Renamed enum members: WorkspaceLogo→WorkspaceIcon, SpaceLogo→SpaceIcon; MAX_AVATAR_SIZE increased from '5MB' to '10MB'.
Server DTOs & controller changes
apps/server/src/core/attachment/dto/attachment.dto.ts, removed: .../avatar-upload.dto.ts, .../get-file.dto.ts, .../upload-file.dto.ts, apps/server/src/core/attachment/attachment.controller.ts
Added RemoveIconDto DTO; removed legacy DTOs AvatarUploadDto, GetFileDto, UploadFileDto; added POST /attachments/remove-icon endpoint that validates type and spaceId and performs type-specific removals with permission checks.
Server attachment utils & service
apps/server/src/core/attachment/attachment.utils.ts, apps/server/src/core/attachment/services/attachment.service.ts
PreparedFile now includes file metadata; added compressAndResizeIcon(buffer) using sharp; folder mapping updated for Icon variants; uploadImage now compresses/resizes icon buffers and uses Icon enums; added service methods removeUserAvatar, removeSpaceIcon, removeWorkspaceIcon (with NotFound handling).
Misc: removed client helpers
apps/client/src/features/user/services/user-service.ts, apps/client/src/features/workspace/services/workspace-service.ts
Removed legacy client upload helpers: uploadAvatar and uploadLogo — replaced by attachments service methods.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant UI as AvatarUploader (Client)
  participant ClientSvc as Attachments Client Service
  participant Controller as /attachments API
  participant Service as AttachmentService (Server)
  participant Store as Storage/DB

  rect rgb(240,248,255)
    User->>UI: select image
    UI->>ClientSvc: uploadUserAvatar / uploadSpaceIcon / uploadWorkspaceIcon (multipart/form-data)
    ClientSvc->>Controller: POST /attachments/upload-image
    Controller->>Service: uploadImage(type, file, ...)
    Service->>Service: compressAndResizeIcon(buffer) [sharp]
    Service->>Store: save processed file, create DB record
    Store-->>Service: ok
    Service-->>Controller: Attachment metadata
    Controller-->>ClientSvc: 200 with Attachment
    ClientSvc-->>UI: success
    UI-->>User: show success notification
  end

  rect rgb(245,255,240)
    User->>UI: click Remove image
    UI->>ClientSvc: removeAvatar / removeSpaceIcon / removeWorkspaceIcon
    ClientSvc->>Controller: POST /attachments/remove-icon { type, spaceId? }
    Controller->>Service: removeIcon(dto, user, workspace)
    Service->>Store: delete file, clear DB field
    Store-->>Service: ok
    Service-->>Controller: ok
    Controller-->>ClientSvc: ok
    ClientSvc-->>UI: success
    UI-->>User: show removal notification
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I nibble pixels tidy, trim each little dot,
Icons hop in neatly, saved in just one spot.
Sharp sharpens every edge, I stash them out of sight,
Uploads and removals — a rabbit's gentle byte.
Hooray for shiny avatars, hopping into light. 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "feat: implement space and workspace icons" is concise and accurately captures the main change set: adding icon support for spaces and workspaces (new AvatarUploader UI, attachment types/services, server-side image processing with sharp, and remove-icon endpoints). It is specific enough for a reviewer or teammate scanning history to understand the primary intent without listing files or extraneous detail.
✨ 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/enhance-avatar-icons

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 29201f5 and 620645e.

📒 Files selected for processing (2)
  • apps/client/public/locales/en-US/translation.json (1 hunks)
  • apps/client/src/components/common/avatar-uploader.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/client/public/locales/en-US/translation.json
  • apps/client/src/components/common/avatar-uploader.tsx

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@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: 18

Caution

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

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

69-75: Mismatch check uses &&; should be || to prevent cross‑entity overwrite.

As written, it throws only when all three fields mismatch. Any single mismatch should abort.

-      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');
       }

82-85: Update flow writes new filePath but doesn’t update DB; also leaks extra files.

For updates you should overwrite the existing storage path (or update DB fields). Currently, a new fileName/path is written while only updatedAt is changed.

-    const filePath = `${getAttachmentFolderPath(AttachmentType.File, workspaceId)}/${attachmentId}/${preparedFile.fileName}`;
+    let filePath: string;
-    if (opts?.attachmentId) {
-      const existingAttachment = await this.attachmentRepo.findById(
+    let existingAttachment = null;
+    if (opts?.attachmentId) {
+      existingAttachment = await this.attachmentRepo.findById(
         opts.attachmentId,
       );
@@
-      attachmentId = opts.attachmentId;
-      isUpdate = true;
+      attachmentId = opts.attachmentId;
+      isUpdate = true;
     } else {
       attachmentId = uuid7();
     }
@@
-    await this.uploadToDrive(filePath, preparedFile.buffer);
+    if (isUpdate) {
+      // overwrite existing file
+      filePath = existingAttachment.filePath;
+      await this.uploadToDrive(filePath, preparedFile.buffer);
+    } else {
+      filePath = `${getAttachmentFolderPath(AttachmentType.File, workspaceId)}/${attachmentId}/${preparedFile.fileName}`;
+      await this.uploadToDrive(filePath, preparedFile.buffer);
+    }

Also applies to: 88-107


124-127: On error, uploaded file isn’t deleted (contradicts the comment).

This leaves orphaned blobs on storage when DB ops fail.

-    } catch (err) {
-      // delete uploaded file on error
-      this.logger.error(err);
-    }
+    } catch (err) {
+      // delete uploaded file on error
+      this.logger.error(err);
+      try {
+        if (filePath) await this.deleteRedundantFile(filePath);
+      } catch (_) {
+        // already logged inside deleteRedundantFile
+      }
+      throw new BadRequestException('Failed to upload file');
+    }
apps/client/src/features/page/services/page-service.ts (2)

169-176: Bug: uploadFile returns Axios response instead of data

This breaks callers expecting IAttachment.

-  return req as unknown as IAttachment;
+  return req.data;

148-154: Type the import-zip request

Strengthen typing on the response.

-  const req = await api.post<any>("/pages/import-zip", formData, {
+  const req = await api.post<IFileTask>("/pages/import-zip", formData, {
apps/client/src/features/space/components/sidebar/switch-space.tsx (1)

39-41: Fix controlled Popover state handling (toggle inverts next state).

Using onChange={toggle} will invert the boolean passed by Mantine and can cause flicker or stuck state when opening/closing. Set state based on the provided value.

-      opened={opened}
-      onChange={toggle}
+      opened={opened}
+      onChange={(nextOpened) => (nextOpened ? open() : close())}
apps/client/src/components/ui/custom-avatar.tsx (1)

6-17: Allow null/undefined avatar and default the type.

Call sites pass possibly null URLs. Also default type to AVATAR so most usages don't need to set it explicitly.

 interface CustomAvatarProps {
-  avatarUrl: string;
+  avatarUrl?: string | null;
   name: string;
@@
-  type?: AvatarIconType;
+  type?: AvatarIconType;
   mt?: string | number;
 }

Additionally, consider updating getAvatarUrl to accept string | null | undefined (see note below).

🧹 Nitpick comments (20)
apps/server/src/core/attachment/services/attachment.service.ts (1)

238-245: Tighten type on upload buffer.

Use Buffer instead of any for fileBuffer.

-  async uploadToDrive(filePath: string, fileBuffer: any) {
+  async uploadToDrive(filePath: string, fileBuffer: Buffer) {
apps/client/src/features/attachments/types/attachment.types.ts (1)

18-29: Optional: consider literal unions over enums to reduce runtime weight.
If your toolchain allows, string literal unions (with a const map if you need namespacing) avoid emitted enum objects.

Example (non-breaking if you also export a const for namespacing):

export type AvatarIconType = "avatar" | "space-icon" | "workspace-icon";
export const AvatarIcon = {
  AVATAR: "avatar",
  SPACE_ICON: "space-icon",
  WORKSPACE_ICON: "workspace-icon",
} as const;

export type AttachmentType =
  | "avatar"
  | "workspace-icon"
  | "space-icon"
  | "file";
export const Attachment = {
  AVATAR: "avatar",
  WORKSPACE_ICON: "workspace-icon",
  SPACE_ICON: "space-icon",
  FILE: "file",
} as const;
apps/client/src/features/editor/components/excalidraw/excalidraw-view.tsx (1)

18-18: Type-only import to avoid unnecessary runtime import.
Switch to import type for IAttachment.

-import { IAttachment } from "@/features/attachments/types/attachment.types";
+import type { IAttachment } from "@/features/attachments/types/attachment.types";
apps/client/src/features/editor/components/drawio/drawio-view.tsx (1)

20-20: Type-only import to avoid runtime cost.
Same adjustment here.

-import { IAttachment } from "@/features/attachments/types/attachment.types";
+import type { IAttachment } from "@/features/attachments/types/attachment.types";
apps/client/src/features/space/components/space-list.tsx (2)

17-17: Fix state type: allow null initial value

Initialize with a nullable type to match the null default.

-  const [selectedSpaceId, setSelectedSpaceId] = useState<string>(null);
+  const [selectedSpaceId, setSelectedSpaceId] = useState<string | null>(null);

36-41: Use stable keys for list items

Avoid index keys; use the space id for React reconciliation.

-                key={index}
+                key={space.id}
apps/client/src/features/page/services/page-service.ts (2)

11-13: Unify imports to prevent duplicate module identities

Mixing with/without “.ts” can cause type duplication under some resolvers.

-import { QueryParams } from "@/lib/types";
-import { IPagination } from "@/lib/types.ts";
+import { QueryParams, IPagination } from "@/lib/types";

143-147: Avoid appending undefined to FormData

Only append source when provided to prevent the literal "undefined" value.

-  formData.append("source", source);
+  if (source) {
+    formData.append("source", source);
+  }
apps/client/src/features/space/components/settings-modal.tsx (2)

76-91: Add ScrollArea to members tab to avoid body overflow

General tab scrolls internally; mirror for members list for consistency and to prevent modal body overflow on long lists.

-                <Tabs.Panel value="members">
+                <Tabs.Panel value="members">
                   <Group my="md" justify="flex-end">
                     {spaceAbility.can(
                       SpaceCaslAction.Manage,
                       SpaceCaslSubject.Member,
                     ) && <AddSpaceMembersModal spaceId={space?.id} />}
                   </Group>
-
-                  <SpaceMembersList
-                    spaceId={space?.id}
-                    readOnly={spaceAbility.cannot(
-                      SpaceCaslAction.Manage,
-                      SpaceCaslSubject.Member,
-                    )}
-                  />
+                  <ScrollArea h={550} scrollbarSize={4} pr={8}>
+                    <SpaceMembersList
+                      spaceId={space?.id}
+                      readOnly={spaceAbility.cannot(
+                        SpaceCaslAction.Manage,
+                        SpaceCaslSubject.Member,
+                      )}
+                    />
+                  </ScrollArea>
                 </Tabs.Panel>

33-41: Modal sizing consistency

mah={400} with inner container height rem(600) can fight each other. Consider letting the body define height (via ScrollArea) and drop mah or the fixed 600 container.

Also applies to: 53-54

apps/client/src/features/space/components/space-grid.tsx (1)

20-21: Guard optional chaining on items

Avoid possible undefined access when data is present but items is not.

-  const cards = data?.items.slice(0, 9).map((space, index) => (
+  const cards = data?.items?.slice(0, 9).map((space, index) => (
apps/client/src/features/space/components/spaces-page/all-spaces-list.tsx (1)

27-34: Type spaces prop to the shape used here

Avoid any[]. Define a lightweight interface for safety and editor help.

-interface AllSpacesListProps {
-  spaces: any[];
+interface SpaceListItem {
+  id: string;
+  slug: string;
+  name: string;
+  description?: string | null;
+  logo?: string | null;
+  memberCount: number;
+}
+
+interface AllSpacesListProps {
+  spaces: SpaceListItem[];

Also applies to: 36-44

apps/client/src/features/space/components/sidebar/switch-space.tsx (1)

66-69: Guard against undefined selection from SpaceSelect.

space can be undefined (e.g., clearing or no match). Current code will throw on space.slug.

-          onChange={(space) => handleSelect(space.slug)}
+          onChange={(space) => space?.slug && handleSelect(space.slug)}
apps/client/src/components/ui/custom-avatar.tsx (1)

19-24: Fix ref typing to match Mantine Avatar and set a safe default for type.

Ref is currently HTMLInputElement, which is incorrect for Avatar (and breaks when component="button"). Also add a default for type.

-export const CustomAvatar = React.forwardRef<
-  HTMLInputElement,
-  CustomAvatarProps
->(({ avatarUrl, name, type, ...props }: CustomAvatarProps, ref) => {
-  const avatarLink = getAvatarUrl(avatarUrl, type);
+export const CustomAvatar = React.forwardRef<
+  React.ElementRef<typeof Avatar>,
+  CustomAvatarProps
+>(({ avatarUrl, name, type = AvatarIconType.AVATAR, ...props }: CustomAvatarProps, ref) => {
+  const avatarLink = getAvatarUrl(avatarUrl as any, type);

Outside this file (supporting change): update getAvatarUrl signature to accept nullable values.

// apps/client/src/lib/config.ts
export function getAvatarUrl(
  avatarUrl?: string | null,
  type: string = "avatar",
) {
  if (!avatarUrl) return null;
  if (avatarUrl.startsWith("http")) return avatarUrl;
  return getBackendUrl() + `/attachments/img/${type}/` + avatarUrl;
}
apps/client/src/features/space/components/sidebar/space-select.tsx (3)

86-89: Handle cleared/unknown slug safely and align types.

slug can be null and find can return undefined. Prevent passing undefined to onChange.

-      onChange={(slug) =>
-        onChange(spaces.items?.find((item) => item.slug === slug))
-      }
+      onChange={(slug) => {
+        const selected = spaces?.items?.find((item) => item.slug === slug);
+        if (selected) onChange(selected);
+      }}

Optionally, update SpaceSelectProps to onChange: (value: ISpace) => void or (value?: ISpace) => void and adapt call sites accordingly.


54-72: Effect dependencies may be stale when value changes.

You filter out the currently selected value but don’t re-run when it changes.

-  }, [spaces]);
+  }, [spaces, value]);

52-53: Type the data state.

Avoid any to catch shape errors early.

-  const [data, setData] = useState([]);
+  const [data, setData] = useState<Array<{ label: string; value: string; icon?: string | null }>>([]);
apps/client/src/components/common/avatar-uploader.tsx (2)

91-97: Fix accept attribute (image/jpg isn’t a valid MIME).

Use extensions (simpler, widely supported) and optionally add modern formats if the backend allows.

-        accept="image/png,image/jpeg,image/jpg"
+        accept=".png,.jpg,.jpeg"

If sharp/Web API supports them, consider:

  • .webp and .avif

99-107: Disable interactions and add a11y affordances while loading.

Prevent menu open during isLoading and expose state to AT.

-      <Menu shadow="md" width={200} withArrow disabled={disabled}>
+      <Menu shadow="md" width={200} withArrow disabled={disabled || isLoading}>
         <Menu.Target>
           <CustomAvatar
             component="button"
             size={size}
             avatarUrl={currentImageUrl}
+            aria-label={t("Upload or remove image")}
+            aria-busy={isLoading}
+            disabled={disabled || isLoading}
             name={fallbackName}
             style={{ cursor: disabled ? "default" : "pointer" }}
           />
apps/client/src/features/attachments/services/attachment-service.ts (1)

7-18: Optional: support abort signals for UX.

Allow callers to cancel in-flight uploads when dialogs close.

-export function uploadIcon(
+export function uploadIcon(
   file: File,
   type: AvatarIconType,
-  spaceId?: string,
+  spaceId?: string,
+  signal?: AbortSignal,
 ): Promise<IAttachment> {
...
-  return api.post<IAttachment>("/attachments/upload-image", formData);
+  return api.post<IAttachment>("/attachments/upload-image", formData, { signal });
}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f413720 and dae30fb.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (34)
  • apps/client/public/locales/en-US/translation.json (1 hunks)
  • apps/client/src/components/common/avatar-uploader.tsx (1 hunks)
  • apps/client/src/components/ui/custom-avatar.tsx (2 hunks)
  • apps/client/src/features/attachments/services/attachment-service.ts (1 hunks)
  • apps/client/src/features/attachments/services/index.ts (1 hunks)
  • apps/client/src/features/attachments/types/attachment.types.ts (1 hunks)
  • apps/client/src/features/editor/components/drawio/drawio-view.tsx (1 hunks)
  • apps/client/src/features/editor/components/excalidraw/excalidraw-view.tsx (1 hunks)
  • apps/client/src/features/page/services/page-service.ts (1 hunks)
  • apps/client/src/features/space/components/settings-modal.tsx (3 hunks)
  • apps/client/src/features/space/components/sidebar/space-select.tsx (3 hunks)
  • apps/client/src/features/space/components/sidebar/space-sidebar.tsx (1 hunks)
  • apps/client/src/features/space/components/sidebar/switch-space.tsx (3 hunks)
  • apps/client/src/features/space/components/space-details.tsx (2 hunks)
  • apps/client/src/features/space/components/space-grid.module.css (1 hunks)
  • apps/client/src/features/space/components/space-grid.tsx (4 hunks)
  • apps/client/src/features/space/components/space-list.tsx (2 hunks)
  • apps/client/src/features/space/components/spaces-page/all-spaces-list.tsx (3 hunks)
  • apps/client/src/features/space/services/space-service.ts (0 hunks)
  • apps/client/src/features/space/types/space.types.ts (2 hunks)
  • apps/client/src/features/user/components/account-avatar.tsx (1 hunks)
  • apps/client/src/features/user/services/user-service.ts (0 hunks)
  • apps/client/src/lib/config.ts (1 hunks)
  • apps/client/src/lib/types.ts (0 hunks)
  • apps/server/package.json (1 hunks)
  • apps/server/src/common/helpers/utils.ts (1 hunks)
  • apps/server/src/core/attachment/attachment.constants.ts (1 hunks)
  • apps/server/src/core/attachment/attachment.controller.ts (5 hunks)
  • apps/server/src/core/attachment/attachment.utils.ts (4 hunks)
  • apps/server/src/core/attachment/dto/attachment.dto.ts (1 hunks)
  • apps/server/src/core/attachment/dto/avatar-upload.dto.ts (0 hunks)
  • apps/server/src/core/attachment/dto/get-file.dto.ts (0 hunks)
  • apps/server/src/core/attachment/dto/upload-file.dto.ts (0 hunks)
  • apps/server/src/core/attachment/services/attachment.service.ts (6 hunks)
💤 Files with no reviewable changes (6)
  • apps/client/src/lib/types.ts
  • apps/client/src/features/user/services/user-service.ts
  • apps/client/src/features/space/services/space-service.ts
  • apps/server/src/core/attachment/dto/avatar-upload.dto.ts
  • apps/server/src/core/attachment/dto/upload-file.dto.ts
  • apps/server/src/core/attachment/dto/get-file.dto.ts
🧰 Additional context used
🧬 Code graph analysis (15)
apps/client/src/features/space/components/space-list.tsx (1)
apps/client/src/components/ui/custom-avatar.tsx (1)
  • CustomAvatar (19-35)
apps/client/src/features/space/components/sidebar/space-sidebar.tsx (1)
apps/client/src/features/space/components/sidebar/switch-space.tsx (1)
  • SwitchSpace (18-75)
apps/client/src/features/space/components/spaces-page/all-spaces-list.tsx (1)
apps/client/src/components/ui/custom-avatar.tsx (1)
  • CustomAvatar (19-35)
apps/client/src/components/common/avatar-uploader.tsx (2)
apps/client/src/components/ui/custom-avatar.tsx (1)
  • CustomAvatar (19-35)
apps/client/src/lib/config.ts (1)
  • getAvatarUrl (44-49)
apps/client/src/features/user/components/account-avatar.tsx (3)
apps/client/src/features/user/atoms/current-user-atom.ts (2)
  • userAtom (11-25)
  • currentUserAtom (6-9)
apps/client/src/features/attachments/services/attachment-service.ts (2)
  • uploadUserAvatar (26-28)
  • removeAvatar (54-56)
apps/client/src/components/common/avatar-uploader.tsx (1)
  • AvatarUploader (21-133)
apps/client/src/features/space/components/space-grid.tsx (1)
apps/client/src/components/ui/custom-avatar.tsx (1)
  • CustomAvatar (19-35)
apps/server/src/core/attachment/attachment.utils.ts (1)
apps/server/src/common/helpers/utils.ts (1)
  • sanitizeFileName (74-79)
apps/client/src/features/attachments/services/attachment-service.ts (3)
apps/client/src/features/attachments/types/attachment.types.ts (1)
  • IAttachment (1-16)
apps/server/src/core/attachment/attachment.controller.ts (1)
  • removeIcon (385-435)
apps/server/src/core/attachment/services/attachment.service.ts (2)
  • removeSpaceIcon (411-424)
  • removeWorkspaceIcon (426-433)
apps/client/src/components/ui/custom-avatar.tsx (1)
apps/client/src/lib/config.ts (1)
  • getAvatarUrl (44-49)
apps/client/src/features/space/components/sidebar/space-select.tsx (1)
apps/client/src/components/ui/custom-avatar.tsx (1)
  • CustomAvatar (19-35)
apps/server/src/core/attachment/attachment.controller.ts (4)
apps/server/src/core/attachment/dto/attachment.dto.ts (1)
  • RemoveIconDto (4-12)
apps/server/src/common/decorators/auth-user.decorator.ts (1)
  • AuthUser (7-16)
apps/server/src/common/decorators/auth-workspace.decorator.ts (1)
  • AuthWorkspace (7-18)
apps/server/src/core/attachment/attachment.utils.ts (1)
  • validAttachmentTypes (71-71)
apps/client/src/features/space/components/settings-modal.tsx (2)
apps/client/src/features/space/components/space-details.tsx (1)
  • SpaceDetails (26-131)
apps/client/src/features/space/components/add-space-members-modal.tsx (1)
  • AddSpaceMembersModal (13-74)
apps/client/src/features/space/components/sidebar/switch-space.tsx (1)
apps/client/src/components/ui/custom-avatar.tsx (1)
  • CustomAvatar (19-35)
apps/server/src/core/attachment/services/attachment.service.ts (3)
apps/server/src/core/attachment/attachment.utils.ts (5)
  • PreparedFile (8-14)
  • prepareFile (16-42)
  • validateFileType (44-51)
  • compressAndResizeIcon (73-99)
  • getAttachmentFolderPath (53-69)
apps/server/src/core/attachment/attachment.constants.ts (1)
  • validImageExtensions (8-8)
apps/server/src/database/types/entity.types.ts (2)
  • User (37-37)
  • Workspace (25-25)
apps/client/src/features/space/components/space-details.tsx (5)
apps/client/src/features/space/queries/space-query.ts (1)
  • useSpaceQuery (45-62)
apps/client/src/features/attachments/services/attachment-service.ts (2)
  • uploadSpaceIcon (30-35)
  • removeSpaceIcon (58-60)
apps/client/src/main.tsx (1)
  • queryClient (23-32)
apps/client/src/components/common/avatar-uploader.tsx (1)
  • AvatarUploader (21-133)
apps/client/src/components/ui/responsive-settings-row.tsx (3)
  • ResponsiveSettingsRow (8-23)
  • ResponsiveSettingsContent (29-35)
  • ResponsiveSettingsControl (41-47)
🔇 Additional comments (25)
apps/server/src/core/attachment/attachment.constants.ts (1)

9-9: Avatar size raised to 10MB: align client and infra limits

Ensure client-side validation, reverse proxy (e.g., Nginx), Fastify multipart limits, and any S3/LB limits are ≥ 10MB to avoid 413 mismatches.

apps/server/src/core/attachment/attachment.controller.ts (4)

3-3: Import Body: LGTM


55-55: Import RemoveIconDto: LGTM


307-317: Workspace icon permission check: LGTM

Correct Manage/Settings check for workspace-level icon uploads.


319-330: Space icon permission check: LGTM

Correct Manage/Settings check and required spaceId.

apps/server/package.json (1)

87-88: Add sharp: verify runtime/build compatibility and document it

  • Found: /Dockerfile uses node:22-alpine (musl). pnpm-lock.yaml contains prebuilt sharp/libvips artifacts for linuxmusl and linux (x64 & arm64) for [email protected] and lockfile engines require Node ^18.17.0 || ^20.3.0 || >=21.0.0 — node:22 satisfies this.
  • Action: Add a short note in apps/server/README or a Dockerfile comment that sharp ships native binaries and that CI/deploy images must match musl/glibc and target archs (or install libvips/build deps) to avoid build-time/runtime failures.
  • Pinning: apps/server/package.json (lines ~86–88) pins "sanitize-filename-ts" to 1.0.2 while most deps use caret; "sharp" is pinned to 0.34.3. Either make pinning consistent or document intentional exact pins for native-binary reproducibility.
apps/server/src/core/attachment/attachment.utils.ts (2)

27-31: Filename sanitization LGTM.

Using sanitizeFileName and capping at 255 chars is sound.


60-63: New folder paths for WorkspaceIcon/SpaceIcon look correct.

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

132-141: Signature changes (WorkspaceIcon/SpaceIcon) look good.

Input types align with new enums.


170-183: Avatar/space/workspace DB updates LGTM.

Old file cleanup and DB updates are consistent with the new types.

Also applies to: 183-195, 195-208


398-409: New removal helpers read well and are idempotent.

Good use of non‑HTTP guard and centralized deletion.

Also applies to: 411-424, 426-433


1-34: Sanity check — adjust sharp import & compressAndResizeIcon call sites.

import * as sharp exists only in apps/server/src/core/attachment/attachment.utils.ts; compressAndResizeIcon is defined there and only called from apps/server/src/core/attachment/services/attachment.service.ts — update those two locations if you changed the function signature; no other usages found.

apps/client/src/features/space/components/space-grid.module.css (1)

10-10: LGTM: dark-mode background token tweak is fine.
No functional risk; improves contrast slightly.

apps/client/public/locales/en-US/translation.json (1)

530-536: LGTM: added image-upload/remove strings.
Keys and casing are consistent with existing patterns.

apps/client/src/lib/config.ts (1)

44-49: No action required — callsites pass the typed type arg.
Found usages at apps/client/src/components/ui/custom-avatar.tsx:23 and apps/client/src/components/common/avatar-uploader.tsx:104 — both call getAvatarUrl(..., type); no string-literal second args detected.

apps/client/src/features/space/components/sidebar/space-sidebar.tsx (1)

77-81: Approve — space.logo correctly passed into SwitchSpace; no change required.
SwitchSpace defines spaceIcon?: string and forwards it to CustomAvatar (avatarUrl); space-sidebar passes space?.logo. See apps/client/src/features/space/components/sidebar/switch-space.tsx and apps/client/src/features/space/components/sidebar/space-sidebar.tsx.

apps/client/src/features/space/components/space-list.tsx (1)

44-50: Avatar wiring: verify type → URL mapping and ref type in CustomAvatar

  • Confirm getAvatarUrl handles AvatarIconType.SPACE_ICON and returns the expected URL for space.logo.
  • In CustomAvatar, ensure forwardRef target type matches Mantine Avatar’s element (likely HTMLDivElement), not HTMLInputElement.

Would you like a quick PR to adjust forwardRef typing if needed?

apps/client/src/features/space/components/settings-modal.tsx (1)

64-73: Good: read-only gates derived from CASL ability

Passing readOnly based on Manage/Settings is correct and keeps UI consistent with permissions.

apps/client/src/features/space/components/space-grid.tsx (1)

32-40: LGTM: CustomAvatar migration

Passing avatarUrl and AvatarIconType.SPACE_ICON aligns with the new URL scheme.

apps/client/src/features/space/components/spaces-page/all-spaces-list.tsx (1)

91-98: LGTM: Consistent CustomAvatar usage

Props match the new avatar pipeline; alt text via name is preserved.

apps/client/src/features/space/components/space-details.tsx (1)

71-85: LGTM: Icon uploader wiring is clean and resilient.

Handlers set loading, refetch, and invalidate caches; UI is disabled under readOnly. Good integration.

apps/client/src/components/common/avatar-uploader.tsx (2)

34-41: Early return logic OK.

Guarding disabled and empty file first keeps the flow clean. LGTM.


5-7: Verify import style consistency (with/without extensions)

apps/client/src/components/common/avatar-uploader.tsx (lines 5–7) imports with explicit .ts/.tsx extensions. Mixing extensioned and extensionless '@/...' imports can break Vite/TS path resolution. Automated sandbox search failed (rg: "unrecognized file type: tsx"); run locally to enumerate occurrences and normalize imports or adjust tsconfig/vite.

Suggested local check:
rg -n "@/[^'" ]+.(ts|tsx)" -S

apps/client/src/features/attachments/services/index.ts (1)

1-9: Approve — barrel export and .ts extension are consistent with project style.
Other barrels use the .ts suffix (e.g. apps/client/src/ee/mfa/index.ts:19); no changes needed.

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

26-39: AvatarIconType matches server AttachmentType — no action required.

Client enum values ('avatar', 'space-icon', 'workspace-icon') match AttachmentType in apps/server/src/core/attachment/attachment.constants.ts; no change needed.

@docmost docmost deleted a comment from coderabbitai Bot Sep 14, 2025
- add upload loader
- add white background to transparent image
- other fixes and enhancements

@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

♻️ Duplicate comments (7)
apps/server/src/core/attachment/attachment.controller.ts (1)

383-431: Missing validation for AttachmentType.File and incorrect HTTP status code

The endpoint accepts AttachmentType.File through DTO validation but doesn't handle it, resulting in an implicit 200 OK with no action. Additionally, successful deletions should return 204 No Content instead of 200 OK.

Apply this fix to reject invalid types and use proper status codes:

   @UseGuards(JwtAuthGuard)
-  @HttpCode(HttpStatus.OK)
+  @HttpCode(HttpStatus.NO_CONTENT)
   @Post('attachments/remove-icon')
   async removeIcon(
     @Body() dto: RemoveIconDto,
     @AuthUser() user: User,
     @AuthWorkspace() workspace: Workspace,
   ) {
     const { type, spaceId } = dto;

+    // Reject file type for icon removal endpoint
+    if (type === AttachmentType.File) {
+      throw new BadRequestException('Invalid attachment type for icon removal');
+    }

     // remove current user avatar
     if (type === AttachmentType.Avatar) {
       await this.attachmentService.removeUserAvatar(user);
       return;
     }

     // remove space icon
     if (type === AttachmentType.SpaceIcon) {
       if (!spaceId) {
         throw new BadRequestException(
           'spaceId is required to change space icons',
         );
       }

       const spaceAbility = await this.spaceAbility.createForUser(user, spaceId);
       if (
         spaceAbility.cannot(SpaceCaslAction.Manage, SpaceCaslSubject.Settings)
       ) {
         throw new ForbiddenException();
       }

       await this.attachmentService.removeSpaceIcon(spaceId, workspace.id);
       return;
     }

     // remove workspace icon
     if (type === AttachmentType.WorkspaceIcon) {
       const ability = this.workspaceAbility.createForUser(user, workspace);
       if (
         ability.cannot(
           WorkspaceCaslAction.Manage,
           WorkspaceCaslSubject.Settings,
         )
       ) {
         throw new ForbiddenException();
       }
       await this.attachmentService.removeWorkspaceIcon(workspace);
       return;
     }
   }
apps/client/src/components/common/avatar-uploader.tsx (1)

64-71: Improve error handling with proper type guards

The error object is untyped, which could lead to runtime errors when accessing nested properties.

-    } catch (error) {
-      const errorMessage =
-        error?.response?.data?.message || t("Failed to upload image");
+    } catch (error: unknown) {
+      let errorMessage = t("Failed to upload image");
+      if (error && typeof error === 'object' && 'response' in error) {
+        const axiosError = error as any;
+        if (axiosError.response?.data?.message) {
+          errorMessage = axiosError.response.data.message;
+        }
+      }
       notifications.show({
         message: errorMessage,
         color: "red",
       });
     }

Apply the same pattern to the remove handler:

-    } catch (error) {
-      const errorMessage =
-        error?.response?.data?.message || t("Failed to remove image");
+    } catch (error: unknown) {
+      let errorMessage = t("Failed to remove image");
+      if (error && typeof error === 'object' && 'response' in error) {
+        const axiosError = error as any;
+        if (axiosError.response?.data?.message) {
+          errorMessage = axiosError.response.data.message;
+        }
+      }
       notifications.show({
         message: errorMessage,
         color: "red",
       });
     }

Also applies to: 95-102

apps/server/src/core/attachment/attachment.utils.ts (4)

5-5: Fix Sharp import to avoid runtime errors

Sharp uses a default export. The current namespace import will cause "sharp is not a function" runtime errors.

-import * as sharp from 'sharp';
+import sharp from 'sharp';

72-110: Add EXIF orientation handling

Images with EXIF orientation data may appear rotated incorrectly. Sharp can automatically handle this with the rotate() method.

 export async function compressAndResizeIcon(buffer: Buffer): Promise<Buffer> {
   try {
-    let sharpInstance = sharp(buffer);
+    let sharpInstance = sharp(buffer).rotate(); // Auto-orient based on EXIF
     const metadata = await sharpInstance.metadata();

81-81: Add null checks for metadata dimensions

The metadata width/height could be undefined for corrupted images, potentially causing runtime errors.

     // Only resize if image is larger than target dimensions
-    if (metadata.width > targetWidth || metadata.height > targetHeight) {
+    if ((metadata.width && metadata.width > targetWidth) || 
+        (metadata.height && metadata.height > targetHeight)) {
       sharpInstance = sharpInstance.resize(targetWidth, targetHeight, {

89-106: PNG transparency is lost due to flatten operation

The flatten operation with a white background removes transparency from PNG images, which defeats the purpose of maintaining the PNG format. Users may want to preserve transparent backgrounds for logos and icons.

     // Handle based on original format
     if (metadata.format === 'png') {
       return await sharpInstance
-        .flatten({ background: { r: 255, g: 255, b: 255 } })
         .png({
           quality: 85,
           compressionLevel: 6,
         })
         .toBuffer();
     } else {
       return await sharpInstance
         .flatten({ background: { r: 255, g: 255, b: 255 } })
         .jpeg({
           quality: 85,
           progressive: true,
           mozjpeg: true,
         })
         .toBuffer();
     }
apps/server/src/core/attachment/services/attachment.service.ts (1)

145-148: Don't hard‑force JPEG; use the processing result to preserve transparency when needed.

The code unconditionally forces JPEG format which destroys transparency in PNG images. This contradicts the compressAndResizeIcon function which preserves PNG format for images with transparency.

Looking at the compressAndResizeIcon function in the relevant code snippets, it returns a Buffer but should ideally return format information to avoid forcing JPEG. The processing function already handles PNG vs JPEG appropriately based on the original format.

-    const processedBuffer = await compressAndResizeIcon(preparedFile.buffer);
-    preparedFile.buffer = processedBuffer;
-    preparedFile.fileSize = processedBuffer.length;
+    const processedBuffer = await compressAndResizeIcon(preparedFile.buffer);
+    preparedFile.buffer = processedBuffer;
+    preparedFile.fileSize = processedBuffer.length;
+    // Remove the hardcoded JPEG extension override

Let me verify the actual return type of compressAndResizeIcon:

#!/bin/bash
# Description: Check the return type of compressAndResizeIcon function
ast-grep --pattern 'export async function compressAndResizeIcon($_): $_ {
  $$$
}'
🧹 Nitpick comments (4)
apps/client/src/pages/settings/workspace/workspace-settings.tsx (1)

3-3: Simplify import path by removing file extension

Remove the .tsx extension from the import path for consistency with other imports and TypeScript module resolution conventions.

-import WorkspaceIcon from "@/features/workspace/components/settings/components/workspace-icon.tsx";
+import WorkspaceIcon from "@/features/workspace/components/settings/components/workspace-icon";
apps/client/src/features/workspace/components/settings/components/workspace-icon.tsx (2)

11-11: Import path inconsistency

The import statement uses a mix of import conventions. Some imports include .tsx extension while most TypeScript projects rely on module resolution without extensions.

-import { workspaceAtom } from "@/features/user/atoms/current-user-atom.ts";
+import { workspaceAtom } from "@/features/user/atoms/current-user-atom";

20-32: Consider handling race conditions in upload handler

Multiple rapid clicks could trigger concurrent uploads. Consider disabling the uploader while an upload is in progress (which you already do via isLoading), but also consider aborting any pending requests if a new upload starts.

apps/client/src/components/common/avatar-uploader.tsx (1)

83-84: Remove console.error in production code

Console statements should be avoided in production code. Consider using a proper logging service or removing this entirely since the error case is unlikely.

-    } else {
-      console.error("File input ref is null!");
     }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dae30fb and edaeb24.

📒 Files selected for processing (13)
  • apps/client/public/locales/en-US/translation.json (1 hunks)
  • apps/client/src/components/common/avatar-uploader.tsx (1 hunks)
  • apps/client/src/components/layouts/global/top-menu.tsx (3 hunks)
  • apps/client/src/features/attachments/services/attachment-service.ts (1 hunks)
  • apps/client/src/features/space/components/space-details.tsx (2 hunks)
  • apps/client/src/features/user/components/account-avatar.tsx (1 hunks)
  • apps/client/src/features/workspace/components/settings/components/workspace-icon.tsx (1 hunks)
  • apps/client/src/lib/config.ts (2 hunks)
  • apps/client/src/pages/settings/workspace/workspace-settings.tsx (2 hunks)
  • apps/server/src/core/attachment/attachment.controller.ts (5 hunks)
  • apps/server/src/core/attachment/attachment.utils.ts (4 hunks)
  • apps/server/src/core/attachment/dto/attachment.dto.ts (1 hunks)
  • apps/server/src/core/attachment/services/attachment.service.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • apps/server/src/core/attachment/dto/attachment.dto.ts
  • apps/client/src/lib/config.ts
  • apps/client/src/features/user/components/account-avatar.tsx
  • apps/client/public/locales/en-US/translation.json
  • apps/client/src/features/attachments/services/attachment-service.ts
  • apps/client/src/features/space/components/space-details.tsx
🧰 Additional context used
🧬 Code graph analysis (6)
apps/client/src/pages/settings/workspace/workspace-settings.tsx (1)
apps/client/src/features/workspace/components/settings/components/workspace-icon.tsx (1)
  • WorkspaceIcon (14-67)
apps/client/src/features/workspace/components/settings/components/workspace-icon.tsx (4)
apps/client/src/features/user/atoms/current-user-atom.ts (1)
  • workspaceAtom (27-41)
apps/client/src/hooks/use-user-role.tsx (1)
  • useUserRole (5-17)
apps/client/src/features/attachments/services/attachment-service.ts (2)
  • uploadWorkspaceIcon (37-39)
  • removeWorkspaceIcon (62-64)
apps/client/src/components/common/avatar-uploader.tsx (1)
  • AvatarUploader (22-171)
apps/server/src/core/attachment/attachment.controller.ts (3)
apps/server/src/core/attachment/dto/attachment.dto.ts (1)
  • RemoveIconDto (4-17)
apps/server/src/common/decorators/auth-user.decorator.ts (1)
  • AuthUser (7-16)
apps/server/src/common/decorators/auth-workspace.decorator.ts (1)
  • AuthWorkspace (7-18)
apps/server/src/core/attachment/attachment.utils.ts (1)
apps/server/src/common/helpers/utils.ts (1)
  • sanitizeFileName (74-79)
apps/server/src/core/attachment/services/attachment.service.ts (3)
apps/server/src/core/attachment/attachment.utils.ts (5)
  • PreparedFile (7-13)
  • prepareFile (15-41)
  • validateFileType (43-50)
  • compressAndResizeIcon (72-110)
  • getAttachmentFolderPath (52-68)
apps/server/src/core/attachment/attachment.constants.ts (1)
  • validImageExtensions (8-8)
apps/server/src/database/types/entity.types.ts (2)
  • User (37-37)
  • Workspace (25-25)
apps/client/src/components/common/avatar-uploader.tsx (1)
apps/client/src/components/ui/custom-avatar.tsx (1)
  • CustomAvatar (19-35)
🔇 Additional comments (9)
apps/client/src/components/layouts/global/top-menu.tsx (2)

5-5: Mantine import tweak is fine.

Importing UnstyledButton here is consistent and non-breaking.


53-53: Type-aware workspace avatar — verified: workspace.logo unchanged; CustomAvatar falls back to initials.

  • No rename detected: server attachment service still references workspace.logo.
  • CustomAvatar forwards name to Avatar (src from getAvatarUrl) so initials/placeholder fallback is present.
apps/client/src/pages/settings/workspace/workspace-settings.tsx (1)

18-18: LGTM! Clean integration of workspace icon component

The WorkspaceIcon component is well-placed after the settings title and before the workspace name form, maintaining a logical flow in the settings page.

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

10-10: LGTM - Added necessary imports for icon processing and new removal functionality.

The imports are correctly added for compressAndResizeIcon and the entity types (User, Workspace) needed for the new removal methods.

Also applies to: 20-20


136-137: LGTM - Updated type union to use new icon naming.

The function signature correctly updates from WorkspaceLogo/SpaceLogo to WorkspaceIcon/SpaceIcon, maintaining consistency with the renamed attachment types.


181-181: LGTM - Updated conditional checks for new icon types.

The conditionals are correctly updated from WorkspaceLogo to WorkspaceIcon and SpaceLogo to SpaceIcon, maintaining the same logic flow.

Also applies to: 193-193


396-407: LGTM - Clean implementation of user avatar removal.

The method properly handles both file deletion and database cleanup, with appropriate HTTP URL filtering to avoid attempting to delete external avatars.


409-422: LGTM - Well-structured space icon removal with proper error handling.

The method includes proper validation with NotFoundException for missing spaces and follows the same pattern as other removal methods for file cleanup.


424-431: LGTM - Consistent workspace icon removal implementation.

The method follows the established pattern for icon removal with proper HTTP URL filtering and cleanup of both storage and database references.

@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

Caution

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

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

193-206: Save SpaceIcon attachments with spaceId (prevents orphaned records on space delete).

The icon file is linked to the space in repos, but the attachment is saved without spaceId. Add it so handleDeleteSpaceAttachments can clean up.

Apply this diff (call site above):

-        attachment = await this.saveAttachment({
+        attachment = await this.saveAttachment({
           preparedFile,
           filePath,
           type,
           userId,
           workspaceId,
           trx,
-        });
+          spaceId: type === AttachmentType.SpaceIcon ? spaceId : undefined,
+        });

124-128: Orphaned upload on error: delete the blob if DB ops fail.

The comment says “delete uploaded file on error,” but the code only logs. This leaks storage.

Apply this diff:

-    } catch (err) {
-      // delete uploaded file on error
-      this.logger.error(err);
-    }
+    } catch (err) {
+      // delete uploaded file on error
+      await this.deleteRedundantFile(filePath);
+      this.logger.error(err);
+      throw err;
+    }

69-75: Update-guard uses AND; should be OR to detect any mismatch.

As written, all three fields must differ to reject, allowing partial mismatches through.

Apply this diff:

-      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');
       }

82-85: Updating files: overwrite existing path and persist new metadata.

On update you compute a new path from a new fileName but don’t update the DB, producing a stale pointer and an orphaned blob. Reuse the existing path (overwrite) and update size/mime/ext in DB.

Apply this diff:

-    const filePath = `${getAttachmentFolderPath(AttachmentType.File, workspaceId)}/${attachmentId}/${preparedFile.fileName}`;
+    // Keep the same path when updating to avoid breaking references
+    const filePath = isUpdate
+      ? (await this.attachmentRepo.findById(attachmentId)).filePath
+      : `${getAttachmentFolderPath(AttachmentType.File, workspaceId)}/${attachmentId}/${preparedFile.fileName}`;
@@
-        attachment = await this.attachmentRepo.updateAttachment(
-          {
-            updatedAt: new Date(),
-          },
-          attachmentId,
-        );
+        attachment = await this.attachmentRepo.updateAttachment(
+          {
+            updatedAt: new Date(),
+            fileSize: preparedFile.fileSize,
+            mimeType: preparedFile.mimeType,
+            fileExt: preparedFile.fileExtension,
+          },
+          attachmentId
+        );

Optional (keep names consistent when overwriting):

-    const preparedFile: PreparedFile = await prepareFile(filePromise);
+    const preparedFile: PreparedFile = await prepareFile(filePromise);
+    if (isUpdate) {
+      const prev = await this.attachmentRepo.findById(attachmentId);
+      preparedFile.fileName = prev.fileName; // preserve path
+    }

Also applies to: 89-95

♻️ Duplicate comments (2)
apps/server/src/core/attachment/services/attachment.service.ts (1)

145-149: Align processed image metadata with buffer (avoid stale ext/mime).

You update only the buffer/size after processing. If Sharp emits a different container or you later change processing (e.g., transcode), DB/file name/mime can drift. Prefer returning ext/mime from the processor and assigning all three.

Apply this diff here:

-    const processedBuffer = await compressAndResizeIcon(preparedFile.buffer, type);
-    preparedFile.buffer = processedBuffer;
-    preparedFile.fileSize = processedBuffer.length;
-    preparedFile.fileName = uuid4() + preparedFile.fileExtension;
+    const processed = await compressAndResizeIcon(preparedFile.buffer, type);
+    preparedFile.buffer = processed.buffer;
+    preparedFile.fileSize = processed.buffer.length;
+    preparedFile.fileExtension = processed.fileExtension;
+    preparedFile.mimeType = processed.mimeType;
+    preparedFile.fileName = uuid4() + processed.fileExtension;

And update the processor (in attachment.utils.ts) accordingly:

 export async function compressAndResizeIcon(
   buffer: Buffer,
   attachmentType?: AttachmentType,
-): Promise<Buffer> {
+): Promise<{ buffer: Buffer; fileExtension: string; mimeType: string }> {
@@
-      return await sharpInstance
-        .png({
-          quality: 85,
-          compressionLevel: 6,
-        })
-        .toBuffer();
+      const out = await sharpInstance.png({ quality: 85, compressionLevel: 6 }).toBuffer();
+      return { buffer: out, fileExtension: '.png', mimeType: 'image/png' };
@@
-      return await sharpInstance
-        .jpeg({
-          quality: 85,
-          progressive: true,
-          mozjpeg: true,
-        })
-        .toBuffer();
+      const out = await sharpInstance.jpeg({ quality: 85, progressive: true, mozjpeg: true }).toBuffer();
+      return { buffer: out, fileExtension: '.jpg', mimeType: 'image/jpeg' };
apps/client/src/features/space/components/space-details.tsx (1)

15-15: Use useQueryClient instead of importing a singleton.

Avoid coupling to a global client; get it from context for testability and correctness.

Apply this diff:

 import { AvatarIconType } from "@/features/attachments/types/attachment.types.ts";
-import { queryClient } from "@/main.tsx";
+import { useQueryClient } from "@tanstack/react-query";
@@
 export default function SpaceDetails({ spaceId, readOnly }: SpaceDetailsProps) {
   const { t } = useTranslation();
   const { data: space, isLoading, refetch } = useSpaceQuery(spaceId);
   const [exportOpened, { open: openExportModal, close: closeExportModal }] =
     useDisclosure(false);
   const [isIconUploading, setIsIconUploading] = useState(false);
+  const queryClient = useQueryClient();

Also applies to: 1-5, 26-33

🧹 Nitpick comments (3)
apps/client/src/features/space/components/space-details.tsx (3)

38-41: Prefer keyed invalidation over predicate.

Directly target the “spaces” queries; simpler and a bit faster.

Apply this diff:

-      await queryClient.invalidateQueries({
-        predicate: (item) => ["spaces"].includes(item.queryKey[0] as string),
-      });
+      await queryClient.invalidateQueries({ queryKey: ["spaces"] });

And similarly for the remove handler.

Also applies to: 53-55


41-45: Don’t silently swallow errors.

At least log for diagnostics; UI toasts are handled by AvatarUploader.

Apply this diff:

-    } catch (err) {
-      // skip
+    } catch (err) {
+      console.error("Space icon upload failed:", err);
     } finally {
       setIsIconUploading(false);
     }

And:

-    } catch (err) {
-      // skip
+    } catch (err) {
+      console.error("Space icon removal failed:", err);
     } finally {
       setIsIconUploading(false);
     }

Also applies to: 56-60


76-86: Confirm size prop type for CustomAvatar.

You pass size="60px". If CustomAvatar expects a number (Mantine Avatar often accepts number), switch to size={60}. Otherwise ignore.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between edaeb24 and 29201f5.

📒 Files selected for processing (7)
  • apps/client/public/locales/en-US/translation.json (1 hunks)
  • apps/client/src/features/editor/styles/core.css (1 hunks)
  • apps/client/src/features/space/components/space-details.tsx (2 hunks)
  • apps/client/src/features/workspace/components/settings/components/workspace-icon.tsx (1 hunks)
  • apps/client/src/features/workspace/services/workspace-service.ts (0 hunks)
  • apps/server/src/core/attachment/attachment.utils.ts (4 hunks)
  • apps/server/src/core/attachment/services/attachment.service.ts (6 hunks)
💤 Files with no reviewable changes (1)
  • apps/client/src/features/workspace/services/workspace-service.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/server/src/core/attachment/attachment.utils.ts
  • apps/client/src/features/workspace/components/settings/components/workspace-icon.tsx
🧰 Additional context used
🧬 Code graph analysis (2)
apps/server/src/core/attachment/services/attachment.service.ts (3)
apps/server/src/core/attachment/attachment.utils.ts (5)
  • PreparedFile (7-13)
  • prepareFile (15-41)
  • validateFileType (43-50)
  • compressAndResizeIcon (72-118)
  • getAttachmentFolderPath (52-68)
apps/server/src/core/attachment/attachment.constants.ts (1)
  • validImageExtensions (8-8)
apps/server/src/database/types/entity.types.ts (2)
  • User (37-37)
  • Workspace (25-25)
apps/client/src/features/space/components/space-details.tsx (5)
apps/client/src/features/space/queries/space-query.ts (1)
  • useSpaceQuery (45-62)
apps/client/src/features/attachments/services/attachment-service.ts (2)
  • uploadSpaceIcon (30-35)
  • removeSpaceIcon (58-60)
apps/client/src/main.tsx (1)
  • queryClient (23-32)
apps/client/src/components/common/avatar-uploader.tsx (1)
  • AvatarUploader (22-171)
apps/client/src/components/ui/responsive-settings-row.tsx (3)
  • ResponsiveSettingsRow (8-23)
  • ResponsiveSettingsContent (29-35)
  • ResponsiveSettingsControl (41-47)
🪛 Biome (2.1.2)
apps/client/src/features/editor/styles/core.css

[error] 101-101: Duplicate properties can lead to unexpected behavior and may override previous declarations unintentionally.

border-top is already defined here.

Remove or rename the duplicate property to ensure consistent styling.

(lint/suspicious/noDuplicateProperties)


[error] 101-101: Duplicate properties can lead to unexpected behavior and may override previous declarations unintentionally.

border-top is already defined here.

Remove or rename the duplicate property to ensure consistent styling.

(lint/suspicious/noDuplicateProperties)


[error] 101-101: Duplicate properties can lead to unexpected behavior and may override previous declarations unintentionally.

border-top is already defined here.

Remove or rename the duplicate property to ensure consistent styling.

(lint/suspicious/noDuplicateProperties)

🔇 Additional comments (6)
apps/server/src/core/attachment/services/attachment.service.ts (5)

136-138: Type additions for WorkspaceIcon/SpaceIcon look good.

Union and downstream cases align with utils/path mappings.


181-193: WorkspaceIcon branch: LGTM.

Correctly updates DB, captures old filename for cleanup, and uses type-specific folder path.


395-406: removeUserAvatar: LGTM.

Correctly guards http URLs, deletes storage+DB via helper, and nulls the field.


408-421: removeSpaceIcon: LGTM.

Good NotFound handling and cleanup flow.


423-430: removeWorkspaceIcon: LGTM.

Consistent with SpaceIcon removal; path construction is correct.

apps/client/src/features/space/components/space-details.tsx (1)

31-31: Good UX: loading disables interactions and shows an overlay.

The isIconUploading gating and loader overlay are solid.

Also applies to: 84-85

@Philipinho
Philipinho merged commit 1280f96 into main Sep 15, 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/enhance-avatar-icons branch December 14, 2025 19:06
nulluserid pushed a commit to N2con-Inc/docmost that referenced this pull request Dec 17, 2025
* feat: implement space and workspace icons
- Create reusable AvatarUploader component supporting avatars, space icons, and workspace icons
- Add Sharp package for server-side image resizing and optimization
- Create reusable AvatarUploader component supporting avatars, space icons, and workspace icons
- Support removing icons

* add workspace logo support
- add upload loader
- add white background to transparent image
- other fixes and enhancements

* dark mode

* fixes

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant