Skip to content

Conversation

arkylin
Copy link

@arkylin arkylin commented Aug 10, 2025

Memory shortage issue when uploading multiple images.

    E  [OPLUS]FATAL EXCEPTION: DefaultDispatcher-worker-14
                                                                                                    Process: app.affine.pro, PID: 2551
                                                                                                    java.lang.OutOfMemoryError: Failed to allocate a 9437200 byte allocation with 3143328 free bytes and 3069KB until OOM, target footprint 268435456, growth limit 268435456
                                                                                                    	at java.util.Arrays.copyOf(Arrays.java:3585)
                                                                                                    	at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:177)
                                                                                                    	at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:753)
                                                                                                    	at java.lang.StringBuilder.append(StringBuilder.java:257)
                                                                                                    	at org.json.JSONStringer.string(JSONStringer.java:354)
                                                                                                    	at org.json.JSONStringer.value(JSONStringer.java:261)
                                                                                                    	at org.json.JSONObject.writeTo(JSONObject.java:734)
                                                                                                    	at org.json.JSONStringer.value(JSONStringer.java:246)
                                                                                                    	at org.json.JSONObject.writeTo(JSONObject.java:734)
                                                                                                    	at org.json.JSONObject.toString(JSONObject.java:702)
                                                                                                    	at com.getcapacitor.PluginResult.toString(PluginResult.java:67)
                                                                                                    	at com.getcapacitor.MessageHandler.sendResponseMessage(MessageHandler.java:126)
                                                                                                    	at com.getcapacitor.PluginCall.resolve(PluginCall.java:55)
                                                                                                    	at app.affine.pro.plugin.NbStorePlugin$getBlob$1.invokeSuspend(NbStorePlugin.kt:248)
                                                                                                    	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
                                                                                                    	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:100)
                                                                                                    	at kotlinx.coroutines.internal.LimitedDispatcher$Worker.run(LimitedDispatcher.kt:124)
                                                                                                    	at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:89)
                                                                                                    	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:586)
                                                                                                    	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:820)
                                                                                                    	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:717)
                                                                                                    	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:704)
                                                                                                    	Suppressed: kotlinx.coroutines.internal.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@b97be2a, Dispatchers.IO]

packages\frontend\apps\android\App\app\src\main\java\app\affine\pro\plugin\NbStorePlugin.kt

    @PluginMethod
    fun getBlob(call: PluginCall) {
        launch(Dispatchers.IO) {
            try {
                val id = call.getStringEnsure("id")
                val key = call.getStringEnsure("key")
                val blob = docStoragePool.getBlob(universalId = id, key = key)
                blob?.let {
                    call.resolve(
                        JSObject()
                            .put("key", it.key)
                            .put("data", it.data)
                            .put("mime", it.mime)
                            .put("size", it.size)
                            .put("createdAt", it.createdAt)
                    )
                } ?: call.resolve()
            } catch (e: Exception) {
                call.reject("Failed to get blob: ${e.message}", null, e)
            }
        }
    }

Summary by CodeRabbit

  • Chores
    • Updated app configuration to request a larger memory allocation on Android devices.

Memory shortage issue when uploading multiple images.
@CLAassistant
Copy link

CLAassistant commented Aug 10, 2025

CLA assistant check
All committers have signed the CLA.

Copy link
Contributor

coderabbitai bot commented Aug 10, 2025

Walkthrough

The AndroidManifest.xml file was updated to include the android:largeHeap="true" attribute in the <application> tag, enabling the application to request a larger memory heap from the Android system.

Changes

Cohort / File(s) Change Summary
AndroidManifest largeHeap Attribute
packages/frontend/apps/android/App/app/src/main/AndroidManifest.xml
Added android:largeHeap="true" to the <application> tag to request a larger heap size.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

Poem

A nibble here, a nibble there,
More memory for apps to share!
The heap grows large, with space anew,
For bunnies and apps, more things to do.
With one small tag, the change is done—
Hopping forward, memory won! 🐇✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@arkylin arkylin changed the title fix(android): Memory shortage: Update AndroidManifest.xml fix(android): Memory shortage when uploading multiple images: Update AndroidManifest.xml Aug 10, 2025
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bc1bd59 and 2837793.

📒 Files selected for processing (1)
  • packages/frontend/apps/android/App/app/src/main/AndroidManifest.xml (1 hunks)

android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:largeHeap="true"
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Adding android:largeHeap="true" is a band-aid; fix the blob-loading OOM at the source.

largeHeap is not guaranteed and can mask underlying inefficiencies. Given the OOM arises when returning image/blob data via JSON, prioritize:

  • Avoid base64/JSON for large binaries; return a file URI via FileProvider or a persisted content URI instead, and stream on the JS side.
  • If decoding images, downsample aggressively (inSampleSize, inPreferredConfig RGB_565), and stream with ContentResolver rather than loading whole arrays in memory.
  • If you must pass bytes, chunk/stream and avoid one-shot arrays.

I recommend keeping this attribute only as a temporary mitigation while landing a plugin refactor.

Refactor sketch (Kotlin) for the plugin to return a URI instead of base64:

// Inside NbStorePlugin.getBlob(...)
val file = File(context.cacheDir, "${blob.key}.bin")
file.outputStream().use { it.write(blob.data) }
// Return a content URI via FileProvider declared in your manifest
val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
JSObject().apply {
  put("key", blob.key)
  put("uri", uri.toString())
  put("mimeType", blob.mimeType)
  put("size", blob.size)
  put("createdAt", blob.createdAt)
}.also { call.resolve(it) }
// On JS side, fetch via the URI/stream instead of reading a base64 field

Optional: log available heap to validate any effect of largeHeap and guide downsampling:

// In Application.onCreate
val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
Log.i("MemClass", "memoryClass=${am.memoryClass}, largeMemoryClass=${am.largeMemoryClass}")

To locate the risky code paths now and confirm base64/JSON usage, run:


🏁 Script executed:

#!/bin/bash
# Find NbStorePlugin.getBlob and base64/JSON payload construction
rg -n --glob '!**/node_modules/**' $'class NbStorePlugin|fun getBlob\\(|Base64|encodeToString\\(|JSONObject\\(|put\\(\\s*"data"' -A 3 -B 3

Length of output: 32804


🏁 Script executed:

#!/bin/bash
rg -n 'getBlob' -A 3 -B 3 packages/frontend/apps/android/src/plugins/nbstore/index.ts

Length of output: 606


Refactor native blob handling instead of relying on largeHeap

Adding android:largeHeap="true" in AndroidManifest only masks the OOM when returning large base64 blobs via the Capacitor plugin. To eliminate the root cause, update your NbStorePlugin.getBlob implementation to stream files instead of inlining giant Base64 strings:

• In packages/frontend/apps/android/App/app/src/main/java/app/affine/pro/plugin/NbStorePlugin.kt (lines ~241–254), you currently do:

JSObject().apply {
  put("key", it.key)
  put("data", it.data)           // full Base64 payload
  put("mime", it.mime)
  put("size", it.size)
  put("createdAt", it.createdAt)
}

• Replace with a FileProvider-backed URI:

val file = File(context.cacheDir, "${blob.key}.bin")
file.outputStream().use { it.write(blob.data) }
val uri = FileProvider.getUriForFile(
  context,
  "${context.packageName}.fileprovider",
  file
)
JSObject().apply {
  put("key", blob.key)
  put("uri", uri.toString())    // stream on JS side
  put("mimeType", blob.mimeType)
  put("size", blob.size)
  put("createdAt", blob.createdAt)
}.also { call.resolve(it) }

• On the JS side, fetch via the URI and process streams instead of decoding one-shot Base64.

• For image blobs, also downsample aggressively with BitmapFactory.Options (e.g. inSampleSize, inPreferredConfig=RGB_565) and load via ContentResolver.openInputStream.

Optional heap logging to guide tuning:

val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
Log.i("MemClass", "memoryClass=${am.memoryClass}, largeMemoryClass=${am.largeMemoryClass}")

To verify all Base64 paths in the Android plugin implementation:

rg -n 'NbStorePlugin.kt' -e 'put("data"' -A3 -B3
🤖 Prompt for AI Agents
In packages/frontend/apps/android/App/app/src/main/AndroidManifest.xml at line
18, remove the android:largeHeap="true" attribute as it only masks out-of-memory
issues caused by large Base64 blobs. Instead, update the NbStorePlugin.getBlob
method in
packages/frontend/apps/android/App/app/src/main/java/app/affine/pro/plugin/NbStorePlugin.kt
(around lines 241–254) to write the blob data to a file in the cache directory,
obtain a FileProvider URI for that file, and return this URI in the JSObject
instead of the full Base64 string. On the JavaScript side, modify the code to
fetch and process the blob data via the URI stream rather than decoding Base64
in one shot. For image blobs, implement downsampling using BitmapFactory.Options
and load images through ContentResolver.openInputStream to reduce memory usage.
Optionally, add heap logging to monitor memory class for tuning purposes.

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

Labels

None yet

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

2 participants