Skip to content

fix: reuse stale upload record instead of blocking re-send#7494

Merged
diegolmello merged 3 commits into
developfrom
changeable-agate
Jul 15, 2026
Merged

fix: reuse stale upload record instead of blocking re-send#7494
diegolmello merged 3 commits into
developfrom
changeable-agate

Conversation

@diegolmello

@diegolmello diegolmello commented Jul 13, 2026

Copy link
Copy Markdown
Member

Proposed changes

An upload record left behind in the local DB by a crashed or failed upload permanently blocked re-sending the same file. On the next (non–"try again") send of that file the app threw Couldn't create upload record and showed an "Upload in progress" alert, even though nothing was uploading.

Root cause: the guard in createUploadRecord treated "a record with this path exists in the DB" as "an upload is in progress". That is wrong after a crash/restart — the DB row survives, but the real in-progress signal is the in-memory uploadQueue, which is empty.

Fix: show the "Upload in progress" alert and bail only when the upload is actually active (isUploadActive). Otherwise the existing row is a stale orphan — reset its error/progress and reuse it so the send proceeds. Applied to both the V2 path (createUploadRecord) and the legacy V1 path (sendFileMessage.ts, servers < 6.10).

Issue(s)

https://rocketchat.atlassian.net/browse/NATIVE-1422

How to test or reproduce

  1. Start uploading a file, then force-kill the app mid-upload (or trigger an upload failure before the request is queued) so an uploads row is left behind.
  2. Reopen the app and send the same file again (normal send, not the "try again" button).
  3. Before: fails with Couldn't create upload record / "Upload in progress". After: the file uploads normally.
  4. Also verify a genuinely in-flight duplicate send of the same file still shows "Upload in progress".

Screenshots

Types of changes

  • Bugfix (non-breaking change which fixes an issue)
  • Improvement (non-breaking change which improves a current function)
  • New feature (non-breaking change which adds functionality)
  • Documentation update (if none of the other choices apply)

Checklist

  • I have read the CONTRIBUTING doc
  • I have signed the CLA
  • Lint and unit tests pass locally with my changes
  • I have added tests that prove my fix is effective or that my feature works (if applicable)
  • I have added necessary documentation (if applicable)
  • Any dependent changes have been merged and published in downstream modules

Further comments

Two related items intentionally left out of scope: (1) the native ObjC-interop exception that can crash the app mid-upload (a separate de-interop/symbolication track — this PR only makes the JS side resilient to the orphan it leaves), and (2) the catch branch that logs Upload cancelled and silently swallows genuine early-failure errors without rethrowing.

Summary by CodeRabbit

  • Bug Fixes

    • File uploads are now retryable when a previous upload record is stale or incomplete.
    • Duplicate attempts are blocked only when an upload is actively in progress for the same item.
    • Retrying now clears any leftover error and resets upload progress before resuming.
  • Tests

    • Added unit test coverage for active uploads, stale record reuse, forced retries, and creation of a new upload record.

@diegolmello
diegolmello temporarily deployed to approve_e2e_testing July 13, 2026 13:45 — with GitHub Actions Inactive
@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 719f5317-2220-4876-9433-4626a6e3b5ff

📥 Commits

Reviewing files that changed from the base of the PR and between 73cdb97 and 05be42a.

📒 Files selected for processing (3)
  • app/lib/methods/sendFileMessage/sendFileMessage.ts
  • app/lib/methods/sendFileMessage/utils.test.ts
  • app/lib/methods/sendFileMessage/utils.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • app/lib/methods/sendFileMessage/utils.test.ts
  • app/lib/methods/sendFileMessage/sendFileMessage.ts
  • app/lib/methods/sendFileMessage/utils.ts
📜 Recent review details
⏰ Context from checks skipped due to timeout. (1)
  • GitHub Check: ESLint and Test / run-eslint-and-test

Walkthrough

Existing upload records are checked for active uploads before blocking retries. Stale records have their error and progress reset and are reused, with tests covering active, stale, forced-retry, and new-record scenarios.

Changes

Upload retry handling

Layer / File(s) Summary
Active-upload detection and stale-record reuse
app/lib/methods/sendFileMessage/sendFileMessage.ts, app/lib/methods/sendFileMessage/utils.ts, app/lib/methods/sendFileMessage/utils.test.ts
Existing records trigger an alert only when the matching upload is active; stale records are reset and reused, with tests covering active, stale, forced-retry, and new-record paths.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested labels: type: bug

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: reusing stale upload records instead of blocking re-sends.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • NATIVE-1422: Request failed with status code 401

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
app/lib/methods/sendFileMessage/sendFileMessage.ts (1)

33-43: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the duplicated stale-record reset logic into a shared helper.

The db.write + uploadRecord.update block that resets error and progress is identical to utils.ts lines 83-88. If the reset fields or logic change, both sites must be updated in lockstep. Extract a shared helper in utils.ts and call it from both createUploadRecord and sendFileMessage.

♻️ Proposed shared helper in utils.ts
+export const resetStaleUploadRecord = async (uploadRecord: TUploadModel): Promise<void> => {
+	const db = database.active;
+	await db.write(async () => {
+		await uploadRecord.update(u => {
+			u.error = false;
+			u.progress = 0;
+		});
+	});
+};

Then in both call sites, replace the inline db.write block:

-			// Record left behind by a crashed or failed upload: reset and reuse it.
-			await db.write(async () => {
-				await uploadRecord?.update(u => {
-					u.error = false;
-					u.progress = 0;
-				});
-			});
+			// Record left behind by a crashed or failed upload: reset and reuse it.
+			await resetStaleUploadRecord(uploadRecord);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/lib/methods/sendFileMessage/sendFileMessage.ts` around lines 33 - 43,
Extract the duplicated stale-upload reset operation into a shared helper in
utils.ts, including the db.write wrapper and uploadRecord.update logic that
clears error and resets progress. Update both createUploadRecord and
sendFileMessage to call this helper instead of maintaining inline reset blocks,
preserving the existing behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/lib/methods/sendFileMessage/utils.test.ts`:
- Around line 57-65: Add an active upload entry to uploadQueue in the “reuses
the existing record when force-retry” test before calling createUploadRecord, so
isUploadActive would otherwise be true. Keep isForceTryAgain set to true and
retain the existing assertions, ensuring the test verifies that force retry
overrides the active-upload state.

---

Nitpick comments:
In `@app/lib/methods/sendFileMessage/sendFileMessage.ts`:
- Around line 33-43: Extract the duplicated stale-upload reset operation into a
shared helper in utils.ts, including the db.write wrapper and
uploadRecord.update logic that clears error and resets progress. Update both
createUploadRecord and sendFileMessage to call this helper instead of
maintaining inline reset blocks, preserving the existing behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a2b48032-4205-4ff2-b000-a38b1e711586

📥 Commits

Reviewing files that changed from the base of the PR and between 6e98b8b and 1de537f.

📒 Files selected for processing (3)
  • app/lib/methods/sendFileMessage/sendFileMessage.ts
  • app/lib/methods/sendFileMessage/utils.test.ts
  • app/lib/methods/sendFileMessage/utils.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (3)
  • GitHub Check: E2E Build Android / android-build
  • GitHub Check: E2E Build iOS / ios-build
  • GitHub Check: ESLint and Test / run-eslint-and-test
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{js,ts,jsx,tsx}: Use descriptive names for functions, variables, and classes that clearly convey their purpose
Write comments that explain the 'why' behind code decisions, not the 'what'
Keep functions small and focused on a single responsibility
Use const by default, let when reassignment is needed, and avoid var
Prefer async/await over .then() chains for handling asynchronous operations
Use explicit error handling with try/catch blocks for async operations
Avoid deeply nested code; refactor complex logic into helper functions

Files:

  • app/lib/methods/sendFileMessage/utils.ts
  • app/lib/methods/sendFileMessage/sendFileMessage.ts
  • app/lib/methods/sendFileMessage/utils.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript for type safety; add explicit type annotations to function parameters and return types
Prefer interfaces over type aliases for defining object shapes in TypeScript
Use enums for sets of related constants rather than magic strings or numbers

**/*.{ts,tsx}: Use TypeScript in strict mode, with imports resolved from the app/ baseUrl
Follow the repository's TypeScript/React Native code style enforced by Prettier: tabs, single quotes, 130-character width, no trailing commas, omit arrow-function parens when possible, and keep brackets on the same line

Files:

  • app/lib/methods/sendFileMessage/utils.ts
  • app/lib/methods/sendFileMessage/sendFileMessage.ts
  • app/lib/methods/sendFileMessage/utils.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Use the project's ESLint setup (@rocket.chat/eslint-config with React, React Native, TypeScript, and Jest plugins) for code quality and style compliance

Files:

  • app/lib/methods/sendFileMessage/utils.ts
  • app/lib/methods/sendFileMessage/sendFileMessage.ts
  • app/lib/methods/sendFileMessage/utils.test.ts
🧠 Learnings (2)
📚 Learning: 2026-04-30T17:07:51.020Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7274
File: app/lib/services/voip/MediaCallEvents.ts:0-0
Timestamp: 2026-04-30T17:07:51.020Z
Learning: In this Rocket.Chat React Native codebase, the ESLint rule `no-void: error` is enforced. When you see a promise returned from an async call that is not awaited (a “floating promise”), do not silence it with the `void somePromise()` pattern. Instead, handle the promise explicitly by attaching `.catch(...)` (or otherwise awaiting/handling the error) so unhandled-rejection risks are addressed in a way that satisfies the existing ESLint configuration.

Applied to files:

  • app/lib/methods/sendFileMessage/utils.ts
  • app/lib/methods/sendFileMessage/sendFileMessage.ts
  • app/lib/methods/sendFileMessage/utils.test.ts
📚 Learning: 2026-06-25T18:37:25.526Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7434
File: app/views/ScreenLockConfigView.test.tsx:16-22
Timestamp: 2026-06-25T18:37:25.526Z
Learning: In Rocket.Chat ReactNative tests that mock selectors for `useAppSelector`, don’t require the mocked selector input to be typed as `IApplicationState` when the fixture only includes a partial Redux state slice (e.g., only `server` and `settings`). Requiring the full `IApplicationState` type in that scenario forces unsafe `as IApplicationState` casts and undermines type-safety. For these narrowly scoped selector-mock fixtures, use a less strict type (e.g., `any`) to keep the mock focused on the slice under test.

Applied to files:

  • app/lib/methods/sendFileMessage/utils.test.ts
🔇 Additional comments (2)
app/lib/methods/sendFileMessage/utils.ts (1)

77-88: LGTM!

app/lib/methods/sendFileMessage/sendFileMessage.ts (1)

10-10: LGTM!

Comment thread app/lib/methods/sendFileMessage/utils.test.ts
@github-actions

Copy link
Copy Markdown

iOS Build Available

Rocket.Chat 4.75.0.109348

Comment thread app/lib/methods/sendFileMessage/sendFileMessage.ts Outdated
Comment thread app/lib/methods/sendFileMessage/utils.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (1)
app/lib/methods/sendFileMessage/sendFileMessage.ts (1)

31-39: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Keep the original upload path for error handling. Reassigning fileInfo.path here makes persistUploadError(fileInfo.path, rid) search by the cached path, but the upload record was created with the original path. Use a local cachedPath for the multipart body and leave fileInfo.path unchanged.

♻️ Proposed fix
-		fileInfo.path = await copyFileToCacheDirectoryIfNeeded(fileInfo.path, fileInfo.name);
+		const cachedPath = await copyFileToCacheDirectoryIfNeeded(fileInfo.path, fileInfo.name);
@@
-			uri: fileInfo.path
+			uri: cachedPath
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/lib/methods/sendFileMessage/sendFileMessage.ts` around lines 31 - 39,
Preserve the original path in fileInfo.path for persistUploadError by storing
the result of copyFileToCacheDirectoryIfNeeded in a local cachedPath variable.
Use cachedPath as the multipart formData uri while leaving fileInfo.path
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@app/lib/methods/sendFileMessage/sendFileMessage.ts`:
- Around line 31-39: Preserve the original path in fileInfo.path for
persistUploadError by storing the result of copyFileToCacheDirectoryIfNeeded in
a local cachedPath variable. Use cachedPath as the multipart formData uri while
leaving fileInfo.path unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6a87ec24-a704-4707-8b2d-7213f75af20c

📥 Commits

Reviewing files that changed from the base of the PR and between e1a66ff and 73cdb97.

📒 Files selected for processing (1)
  • app/lib/methods/sendFileMessage/sendFileMessage.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (1)
  • GitHub Check: ESLint and Test / run-eslint-and-test
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{js,ts,jsx,tsx}: Use descriptive names for functions, variables, and classes that clearly convey their purpose
Write comments that explain the 'why' behind code decisions, not the 'what'
Keep functions small and focused on a single responsibility
Use const by default, let when reassignment is needed, and avoid var
Prefer async/await over .then() chains for handling asynchronous operations
Use explicit error handling with try/catch blocks for async operations
Avoid deeply nested code; refactor complex logic into helper functions

Files:

  • app/lib/methods/sendFileMessage/sendFileMessage.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript for type safety; add explicit type annotations to function parameters and return types
Prefer interfaces over type aliases for defining object shapes in TypeScript
Use enums for sets of related constants rather than magic strings or numbers

**/*.{ts,tsx}: Use TypeScript in strict mode, with imports resolved from the app/ baseUrl
Follow the repository's TypeScript/React Native code style enforced by Prettier: tabs, single quotes, 130-character width, no trailing commas, omit arrow-function parens when possible, and keep brackets on the same line

Files:

  • app/lib/methods/sendFileMessage/sendFileMessage.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Use the project's ESLint setup (@rocket.chat/eslint-config with React, React Native, TypeScript, and Jest plugins) for code quality and style compliance

Files:

  • app/lib/methods/sendFileMessage/sendFileMessage.ts
🧠 Learnings (1)
📚 Learning: 2026-04-30T17:07:51.020Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7274
File: app/lib/services/voip/MediaCallEvents.ts:0-0
Timestamp: 2026-04-30T17:07:51.020Z
Learning: In this Rocket.Chat React Native codebase, the ESLint rule `no-void: error` is enforced. When you see a promise returned from an async call that is not awaited (a “floating promise”), do not silence it with the `void somePromise()` pattern. Instead, handle the promise explicitly by attaching `.catch(...)` (or otherwise awaiting/handling the error) so unhandled-rejection risks are addressed in a way that satisfies the existing ESLint configuration.

Applied to files:

  • app/lib/methods/sendFileMessage/sendFileMessage.ts

An upload record left in the DB by a crashed or failed upload permanently
blocked re-sending the same file, surfacing as "Couldn't create upload record".
The guard treated "record exists in DB" as "upload in progress"; the real
in-progress signal is the in-memory uploadQueue, which is empty after a crash.

Bail with the in-progress alert only when the upload is actually active
(isUploadActive); otherwise reset the stale record (error/progress) and reuse
it so the send proceeds. Applied to both the V2 and legacy V1 paths.
@diegolmello
diegolmello requested a deployment to approve_e2e_testing July 15, 2026 13:29 — with GitHub Actions Waiting
@diegolmello
diegolmello merged commit cf93469 into develop Jul 15, 2026
6 of 9 checks passed
@diegolmello
diegolmello deleted the changeable-agate branch July 15, 2026 13:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants