#20022: Fix temp file leak on media download failure
size: XS
trusted-contributor
Cluster:
Media File Management Fixes
When `downloadToFile` throws (network error, size limit exceeded, SSRF block, etc.), the `.tmp` file at `tempDest` is left on disk. While `cleanOldMedia` eventually removes stale files, repeated failures can accumulate orphaned temp files.
Wrap the download-and-rename sequence in try/catch and unlink the temp file before re-throwing.
<!-- greptile_comment -->
<h3>Greptile Summary</h3>
Wraps the download-and-rename sequence in `saveMediaSource` with a try/catch to clean up the `.tmp` file when any step fails (network error, size limit, SSRF block, mime detection failure, etc.). The silent `.catch(() => {})` on `fs.unlink` correctly handles the case where the temp file was never created.
- Adds try/catch around `downloadToFile` → `detectMime` → `fs.rename` in `src/media/store.ts`
- On failure, `fs.unlink(tempDest)` removes the orphaned `.tmp` file before re-throwing
- No test coverage for the new cleanup path — consider adding a test that mocks a `downloadToFile` failure and verifies no `.tmp` file remains on disk
<h3>Confidence Score: 5/5</h3>
- This PR is safe to merge — it adds defensive cleanup logic with no change to the happy path.
- The change is minimal (wrapping existing code in try/catch with a single cleanup line), the logic is correct for all failure modes, and the silent .catch on unlink correctly handles edge cases. The happy path is unchanged. No new dependencies or architectural changes.
- No files require special attention.
<sub>Last reviewed commit: 5357841</sub>
<!-- greptile_other_comments_section -->
<!-- /greptile_comment -->
Most Similar PRs
#17630: Fix LINE media temp files accumulating in os.tmpdir
by Clawborn · 2026-02-16
79.9%
#17816: Fix media store cleanup ignoring subdirectories (e.g. inbound)
by Clawborn · 2026-02-16
73.9%
#7400: media: allow temp-dir MEDIA paths for tool outputs
by grammakov · 2026-02-02
73.1%
#16990: fix(media): strip auth headers on cross-origin redirect in download...
by AI-Reviewer-QS · 2026-02-15
71.7%
#8718: fix: sanitize download filenames to prevent path traversal (CWE-22)
by DevZenPro · 2026-02-04
71.1%
#23726: fix(resilience): destroy write streams on download errors
by kevinWangSheng · 2026-02-22
70.9%
#18811: fix(media): require file extension for ambiguous MEDIA: path detection
by aldoeliacim · 2026-02-17
70.5%
#17456: fix(test): stabilize media root guard test against tmpdir HOME overlap
by widingmarcus-cyber · 2026-02-15
70.0%
#22910: fix(browser): resolve symlinks in upload path validation
by erdinccurebal · 2026-02-21
69.6%
#22401: fix: resolve relative media paths against workspace and fix /tmp on...
by derrickburns · 2026-02-21
69.4%