Skip to content

chore: trim useless files for client#14488

Merged
darkskygit merged 3 commits intocanaryfrom
darksky/trim-useless-files
Feb 22, 2026
Merged

chore: trim useless files for client#14488
darkskygit merged 3 commits intocanaryfrom
darksky/trim-useless-files

Conversation

@darkskygit
Copy link
Member

@darkskygit darkskygit commented Feb 21, 2026

PR Dependency Tree

This tree was auto-generated by Charcoal

Summary by CodeRabbit

  • Chores
    • Improved Electron build to trim unused locale files on macOS, Windows, and Linux while always preserving English fallbacks; added post-build cleanup and stricter packaging ignore rules to exclude tests, examples, scripts, docs, README, and build metadata.
  • Style
    • Reformatted a TypeScript type annotation for consistency.

@darkskygit darkskygit requested a review from a team as a code owner February 21, 2026 18:28
@github-actions github-actions bot added app:electron Related to electron app app:core labels Feb 21, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 21, 2026

📝 Walkthrough

Walkthrough

Adds Electron build-time locale trimming (removes unneeded .lproj and .pak locale files) integrated into the Forge afterCopy hook; also reformats a TypeScript union type for brevity.

Changes

Cohort / File(s) Summary
Electron Locale Optimization
packages/frontend/apps/electron/forge.config.mjs
Adds locale retention logic and mappings; imports fs/promises; implements getElectronLocalesKeep, getElectronPakLocalesKeep, trimElectronFrameworkLocales (macOS .lproj) and trimElectronPakLocales (Windows/Linux .pak); extends packager ignore rules and adds afterCopy hook to run trimming.
Type Annotation Formatting
packages/frontend/core/src/blocksuite/ai/components/ai-tools/code-artifact.ts
Reformats CodeArtifactToolResult.result union type from a multi-line to a single-line declaration; no runtime or behavioral changes.

Sequence Diagram(s)

sequenceDiagram
    participant Forge as Electron Forge Packager
    participant Hook as afterCopy Hook
    participant TrimmerFW as trimElectronFrameworkLocales
    participant TrimmerPAK as trimElectronPakLocales
    participant FS as File System

    Forge->>Hook: invoke afterCopy(filesPath, platform)
    alt platform is darwin or mas
        Hook->>TrimmerFW: pass frameworkPath & keep list
        TrimmerFW->>FS: read framework resources directories
        TrimmerFW->>FS: remove non-kept `.lproj` directories
        TrimmerFW-->>Hook: done
    else platform is win or linux
        Hook->>TrimmerPAK: pass localesPath & keep list
        TrimmerPAK->>FS: read locales directory
        TrimmerPAK->>FS: remove non-kept `.pak` files
        TrimmerPAK-->>Hook: done
    end
    Hook-->>Forge: post-copy cleanup complete
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 I munched through folders, soft and small,

Kept English safe, the fallback for all,
Pak and lproj, trimmed just right,
Lighter builds — I hop with delight! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'chore: trim useless files for client' accurately reflects the main change: adding locale retention/trimming logic to the Electron build configuration to remove unnecessary locale files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch darksky/trim-useless-files

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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/frontend/apps/electron/forge.config.mjs (1)

55-74: Env-var locale names are not case-normalised — mismatches silently skip deletion on Linux.

raw.split(',').map(s => s.trim()) preserves the caller's casing. For the macOS path, the case-insensitive filesystem hides the problem. For Linux .pak trimming, 'zh_cn' converts to 'zh-cn' (not 'zh-CN'), so pakKeep.has('zh-cn') won't match Chromium's actual zh-CN.pak, and that file will be skipped silently.

✨ Suggested improvement
 const keep = new Set(
   raw
     .split(',')
     .map(s => s.trim())
     .filter(Boolean)
 );
+// Normalise locale names that users may supply in wrong case.
+// The DEFAULT set uses the canonical Chromium casing (e.g. 'zh_CN', 'en_GB').
+// We can't do a full case-fold because locale codes are case-significant
+// (upper-case region suffix is the convention), so at minimum warn:
+if (process.env.NODE_ENV !== 'production') {
+  for (const l of keep) {
+    if (l !== l.replace(/[a-z]{2}$/, s => s.toUpperCase())) {
+      console.warn(`[forge] ELECTRON_LOCALES_KEEP: "${l}" may need a capitalised region suffix (e.g. zh_CN)`);
+    }
+  }
+}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/frontend/apps/electron/forge.config.mjs` around lines 55 - 74, The
getElectronLocalesKeep function builds the keep Set from ELECTRON_LOCALES_KEEP
but preserves caller casing, causing mismatches (e.g., 'zh_cn' vs 'zh-CN');
update the mapping in getElectronLocalesKeep to normalize each entry before
adding to the Set by applying .toLowerCase() and normalizing separators (e.g.,
replace '_' with '-') so comparisons against Chromium .pak names succeed, and
ensure the forced fallbacks ('en', 'en_US', 'en_GB') are added in the same
normalized form; leave DEFAULT_ELECTRON_LOCALES_KEEP and the null/"all" handling
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/frontend/apps/electron/forge.config.mjs`:
- Around line 29-53: DEFAULT_ELECTRON_LOCALES_KEEP omits 'en_US' while
getElectronLocalesKeep force-adds 'en_US' when an env-var override is present;
update DEFAULT_ELECTRON_LOCALES_KEEP to include 'en_US' so default (no env-var)
builds behave consistently and won't remove an en_US.lproj if Electron ever
ships it, ensuring both the constant and getElectronLocalesKeep logic align.

---

Nitpick comments:
In `@packages/frontend/apps/electron/forge.config.mjs`:
- Around line 55-74: The getElectronLocalesKeep function builds the keep Set
from ELECTRON_LOCALES_KEEP but preserves caller casing, causing mismatches
(e.g., 'zh_cn' vs 'zh-CN'); update the mapping in getElectronLocalesKeep to
normalize each entry before adding to the Set by applying .toLowerCase() and
normalizing separators (e.g., replace '_' with '-') so comparisons against
Chromium .pak names succeed, and ensure the forced fallbacks ('en', 'en_US',
'en_GB') are added in the same normalized form; leave
DEFAULT_ELECTRON_LOCALES_KEEP and the null/"all" handling unchanged.

@codecov
Copy link

codecov bot commented Feb 21, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 56.93%. Comparing base (3d01766) to head (b438e04).
⚠️ Report is 1 commits behind head on canary.

Additional details and impacted files
@@            Coverage Diff             @@
##           canary   #14488      +/-   ##
==========================================
- Coverage   57.41%   56.93%   -0.48%     
==========================================
  Files        2860     2860              
  Lines      154542   154542              
  Branches    23351    23222     -129     
==========================================
- Hits        88724    87988     -736     
- Misses      62901    63629     +728     
- Partials     2917     2925       +8     
Flag Coverage Δ
server-test 74.96% <ø> (-0.96%) ⬇️
unittest 33.93% <ø> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/frontend/apps/electron/forge.config.mjs (1)

345-354: Consider anchoring (or documenting) the broad directory-name ignore patterns.

Electron Packager's ignore patterns are matched against the absolute path of every file/directory being copied — including paths inside node_modules. The three unanchored patterns:

/\/src($|\/)/
/\/test($|\/)/
/\/scripts($|\/)/

will silently exclude any src/, test/, or scripts/ subdirectory found anywhere under node_modules, not just those at the project root. This is harmless for the vast majority of npm packages, but if any production dependency ever ships runtime assets under one of those directory names it would be stripped without warning.

Anchoring them to the project root (^ prefix) would make the intent explicit and avoid the ambiguity:

♻️ Suggested anchoring
-      /\/src($|\/)/,
-      /\/test($|\/)/,
-      /\/scripts($|\/)/,
+      /^\/src($|\/)/,
+      /^\/test($|\/)/,
+      /^\/scripts($|\/)/,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/frontend/apps/electron/forge.config.mjs` around lines 345 - 354, The
ignore array in forge.config.mjs currently uses unanchored patterns
(/\/src($|\/)/, /\/test($|\/)/, /\/scripts($|\/)/) which will match those
directory names anywhere in absolute paths (including node_modules); update the
ignore entries in the ignore: [...] block to anchor them to the project root
(prefix with ^) so they only match root-level directories, or alternatively add
a clear comment above the ignore array documenting that these patterns are
intentionally global and may strip matching dirs inside node_modules; target the
ignore array and the specific regex entries to make this change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/frontend/apps/electron/forge.config.mjs`:
- Around line 345-354: The ignore array in forge.config.mjs currently uses
unanchored patterns (/\/src($|\/)/, /\/test($|\/)/, /\/scripts($|\/)/) which
will match those directory names anywhere in absolute paths (including
node_modules); update the ignore entries in the ignore: [...] block to anchor
them to the project root (prefix with ^) so they only match root-level
directories, or alternatively add a clear comment above the ignore array
documenting that these patterns are intentionally global and may strip matching
dirs inside node_modules; target the ignore array and the specific regex entries
to make this change.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/frontend/apps/electron/forge.config.mjs (1)

114-119: Silent catch swallows non-ENOENT errors with no build signal.

Both readdir catch blocks return unconditionally, meaning a permission error or unexpected FS issue silently disables locale trimming and the build succeeds with the full locale set included. Adding a warning would surface these cases.

♻️ Proposed improvement for both catch blocks
-  } catch {
-    return;
-  }
+  } catch (err) {
+    if (err?.code !== 'ENOENT') {
+      console.warn('[locale-trim] readdir failed, skipping trim:', err);
+    }
+    return;
+  }

Also applies to: 146-151

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/frontend/apps/electron/forge.config.mjs` around lines 114 - 119, The
try/catch around the readdir calls (when reading frameworkResourcesDir and the
other locale directory) currently swallows all errors by returning silently;
update both catch blocks to capture the thrown error (e.g., catch (err)) and log
a warning that includes the error details and context (which directory failed)
instead of unconditionally returning, and only return early when the error is
ENOENT; reference the readdir calls and the entries variable and include the
directory name (frameworkResourcesDir / the other locale dir) in the log so
permission or unexpected FS errors are visible during build.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/frontend/apps/electron/forge.config.mjs`:
- Around line 114-119: The try/catch around the readdir calls (when reading
frameworkResourcesDir and the other locale directory) currently swallows all
errors by returning silently; update both catch blocks to capture the thrown
error (e.g., catch (err)) and log a warning that includes the error details and
context (which directory failed) instead of unconditionally returning, and only
return early when the error is ENOENT; reference the readdir calls and the
entries variable and include the directory name (frameworkResourcesDir / the
other locale dir) in the log so permission or unexpected FS errors are visible
during build.

@darkskygit darkskygit merged commit ad988db into canary Feb 22, 2026
101 of 102 checks passed
@darkskygit darkskygit deleted the darksky/trim-useless-files branch February 22, 2026 09:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app:core app:electron Related to electron app

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

1 participant