Skip to content

Conversation

@appflowy
Copy link
Contributor

@appflowy appflowy commented Dec 2, 2025

Description


Checklist

General

  • I've included relevant documentation or comments for the changes introduced.
  • I've tested the changes in multiple environments (e.g., different browsers, operating systems).

Testing

  • I've added or updated tests to validate the changes introduced for AppFlowy Web.

Feature-Specific

  • For feature additions, I've added a preview (video, screenshot, or demo) in the "Feature Preview" section.
  • I've verified that this feature integrates seamlessly with existing functionality.

Summary by Sourcery

Improve logging consistency and image handling robustness across the app.

Bug Fixes:

  • Handle cases where image fetch returns JSON instead of an image and treat them as load failures.

Enhancements:

  • Centralize console usage through the shared Log utility, including gating debug/trace output to development builds.
  • Validate and normalize fetched image blobs, inferring MIME types from URLs when necessary to ensure correct rendering.
  • Clean up excess low-level editor/WebSocket debug logging to reduce noise in production logs.

@sourcery-ai
Copy link

sourcery-ai bot commented Dec 2, 2025

Reviewer's Guide

Centralizes logging through the shared Log utility, adds image-blob validation for authenticated image fetching, and removes a few low-level debug calls from the Yjs editor integration.

Sequence diagram for authenticated image fetch with blob validation

sequenceDiagram
  actor User
  participant Browser
  participant ImageUtils as ImageUtils_checkImage
  participant Auth as Auth_getTokenParsed
  participant Storage as AppFlowyFileStorage
  participant Log

  User->>Browser: Navigate to page with image URL
  Browser->>ImageUtils: checkImage(url)
  alt isAppFlowyFileStorageUrl(url)
    ImageUtils->>Auth: getTokenParsed()
    alt token exists
      ImageUtils->>Storage: fetch(url, { Authorization: Bearer token })
      Storage-->>ImageUtils: HTTP response
      alt response.ok
        ImageUtils->>ImageUtils: response.blob()
        ImageUtils->>ImageUtils: validateImageBlob(blob, url)
        alt blob is JSON (application/json)
          ImageUtils->>Log: Log.error("Image fetch returned JSON instead of image", text)
          ImageUtils-->>Browser: { ok: false, status: 406, error: "Image fetch returned JSON instead of image" }
        else non JSON blob
          ImageUtils->>Browser: URL.createObjectURL(validatedBlob)
          Browser-->>User: Image rendered from blob URL
        end
      else !response.ok
        ImageUtils-->>Browser: { ok: false, status: response.status }
      end
    else no token
      ImageUtils-->>Browser: { ok: false, status: 401 }
    end
  else not AppFlowy file URL
    Browser->>ImageUtils: validateImageLoad(url)
    ImageUtils-->>Browser: Load result using plain URL
  end
Loading

Class diagram for updated Log utility

classDiagram
  class Log {
    - prototype
    +constructor()
    +debug(msg1, msg2, msg3, msg4, msg5)
    +trace(msg1, msg2, msg3, msg4, msg5)
    +info(msg1, msg2, msg3, msg4, msg5)
    +warn(msg1, msg2, msg3, msg4, msg5)
    +error(msg1, msg2, msg3, msg4, msg5)
  }

  note for Log "debug and trace only log to console when import.meta.env.DEV is true"
Loading

File-Level Changes

Change Details Files
Introduce shared validation for fetched image blobs and integrate it into image fetching utilities.
  • Add validateImageBlob helper to detect JSON error blobs and infer MIME type from URL for generic blobs.
  • Use validateImageBlob in checkImage to reject JSON responses and return a 406-style error object.
  • Refactor fetchImageBlob to delegate blob post-processing to validateImageBlob instead of inlined logic.
src/utils/image.ts
Replace direct console.* calls with the centralized Log utility across editor, WebSocket, and app config code.
  • Import Log from utils/log where needed and swap console.error/info/debug/warn/trace usage to Log equivalents.
  • Preserve existing log messages and contexts while routing them through the Log abstraction for consistency and configurability.
src/application/slate-yjs/command/index.ts
src/application/slate-yjs/utils/applyToSlate.ts
src/components/ws/useAppflowyWebSocket.ts
src/components/main/AppConfig.tsx
Restrict noisy debug/trace logging to development builds via the Log helper.
  • Guard Log.debug and Log.trace so they only emit in development mode using import.meta.env.DEV.
src/utils/log.ts
Remove now-unnecessary low-level debug statements from the Yjs editor plugin.
  • Delete connect/initialize console.debug traces from withYjs while keeping functional behavior intact.
  • Stop destructuring unused id parameter now that it is no longer logged.
src/application/slate-yjs/plugins/withYjs.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes - here's some feedback:

  • In checkImage, when validateImageBlob returns null you currently hardcode a 406 status; consider using the actual response.status/statusText so callers see the real HTTP result rather than a fabricated status code.
  • Log.debug/Log.trace are completely disabled outside import.meta.env.DEV; for areas like WebSocket reconnect logic and auth state sync where debug logs are often needed in production diagnostics, consider a configurable log level (e.g., via env or runtime setting) instead of hardwiring them to dev-only.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `checkImage`, when `validateImageBlob` returns null you currently hardcode a 406 status; consider using the actual `response.status`/`statusText` so callers see the real HTTP result rather than a fabricated status code.
- `Log.debug`/`Log.trace` are completely disabled outside `import.meta.env.DEV`; for areas like WebSocket reconnect logic and auth state sync where debug logs are often needed in production diagnostics, consider a configurable log level (e.g., via env or runtime setting) instead of hardwiring them to dev-only.

## Individual Comments

### Comment 1
<location> `src/utils/image.ts:63-65` </location>
<code_context>
   });
 };

+const validateImageBlob = async (blob: Blob, url?: string): Promise<Blob | null> => {
+  // Check if the response is actually JSON (e.g. error message with 200 status)
+  if (blob.type === 'application/json') {
+    try {
+      const text = await blob.text();
+
+      Log.error('Image fetch returned JSON instead of image:', text);
</code_context>

<issue_to_address>
**🚨 suggestion (security):** Consider truncating or redacting JSON error payloads before logging to avoid huge logs or leaking sensitive data.

Here the entire JSON body is logged when `blob.type === 'application/json'`. That payload could be very large and may include sensitive user data. Prefer logging a reduced version (e.g., truncated text or selected fields like status/error code) instead of the full body.

```suggestion
      const text = await blob.text();

      // Avoid logging full JSON payloads which may be large or contain sensitive data
      let safePayload: unknown = undefined;

      try {
        const parsed = JSON.parse(text);
        if (parsed && typeof parsed === 'object') {
          const obj = parsed as Record<string, unknown>;
          // Prefer logging only high‑level error metadata if present
          const { status, code, error, message } = obj;
          safePayload = {
            status,
            code,
            error,
            message,
            // Indicate that additional fields were omitted for safety
            redacted: true,
          };
        } else {
          // Non‑object JSON (e.g. string/number/array) – truncate the stringified form
          const truncated = JSON.stringify(parsed).slice(0, 500);
          safePayload = `${truncated}${truncated.length === 500 ? '…[truncated]' : ''}`;
        }
      } catch {
        // Not valid JSON – fall back to a truncated text representation
        const truncated = text.slice(0, 500);
        safePayload = `${truncated}${truncated.length === 500 ? '…[truncated]' : ''}`;
      }

      Log.error('Image fetch returned JSON instead of image', safePayload);
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@appflowy appflowy merged commit c7c9d06 into main Dec 2, 2025
11 of 12 checks passed
@appflowy appflowy deleted the console_log branch December 2, 2025 05:54
josue693 pushed a commit to josue693/AppFlowy-Web that referenced this pull request Dec 21, 2025
* chore: log json

* chore: use log
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.

2 participants