FEATURE: automatically downsize large images
Tier 2 hard ruby · local · real merged PR from ai-code-review-evaluation/discourse-graphite #1
Ground-truth defects
The downsize method is defined twice. The second definition, which expects a single dimensions string parameter, overrides the first, which expected separate max_width and max_height parameters. This makes the original method unreachable and breaks existing code that calls it with separate width and height arguments.
Hardcoding maxSizeKB = 10 * 1024 ignores Discourse.SiteSettings['max_' + type + '_size_kb'], so the client-side limit can diverge from server-side and per-type settings (also applies to the 413 handler below).
Passing 80% as the dimensions can fail for animated GIFs when allow_animated_thumbnails is true, since the animated path uses gifsicle --resize-fit which expects WxH geometry, not a percentage; downsizing would then silently fail.
The new downsize loop tests `tempfile.size` and passes the same expression as the filesize argument to `Upload.create_for`, but the conversion ends in an image optimizer that atomically replaces the file. After the first pass the open Tempfile descriptor refers to an orphaned inode, so the reported size stops tracking the file on disk: the loop condition is frozen at the post-first-pass value and the upload is then rejected as too large by the validator even though the file has been shrunk well under the limit.
The change under review
diff
@@ -179,7 +179,7 @@ Discourse.Utilities = { // check file size var fileSizeKB = file.size / 1024; - var maxSizeKB = Discourse.SiteSettings['max_' + type + '_size_kb']; + var maxSizeKB = 10 * 1024; // 10MB if (fileSizeKB > maxSizeKB) { bootbox.alert(I18n.t('post.errors.file_too_large', { max_size_kb: maxSizeKB })); return false; @@ -243,7 +243,7 @@ Discourse.Utilities = { // entity too large, usually returned from the web server case 413: - var maxSizeKB = Discourse.SiteSettings.max_image_size_kb; + var maxSizeKB = 10 * 1024; // 10 MB bootbox.alert(I18n.t('post.errors.file_too_large', { max_size_kb: maxSizeKB })); return; @@ -52,7 +52,7 @@ class UploadsController < ApplicationController begin # API can provide a URL if file.nil? && url.present? && is_api? - tempfile = FileHelper.download(url, SiteSetting.max_image_size_kb.kilobytes, "discourse-upload-#{type}") rescue nil + tempfile = FileHelper.download(url, 10.megabytes, "discourse-upload-#{type}") rescue nil filename = File.basename(URI.parse(url).path) else tempfile = file.tempfile @@ -60,6 +60,15 @@ class UploadsController < ApplicationController content_type = file.content_type end + # allow users to upload large images that will be automatically reduced to allowed size + if tempfile && tempfile.size > 0 && SiteSetting.max_image_size_kb > 0 && FileHelper.is_image?(filename) + attempt = 5 + while attempt > 0 && tempfile.size > SiteSetting.max_image_size_kb.kilobytes + OptimizedImage.downsize(tempfile.path, tempfile.path, "80%", allow_animation: SiteSetting.allow_animated_thumbnails) + attempt -= 1 + end + end + upload = Upload.create_for(current_user.id, tempfile, filename, tempfile.size, content_type: content_type, image_type: type) if upload.errors.empty? && current_user.admin? @@ -139,25 +139,24 @@ class OptimizedImage < ActiveRecord::Base end def self.resize(from, to, width, height, opts={}) - optimize("resize", from, to, width, height, opts) + optimize("resize", from, to, "#{width}x#{height}", opts) end def self.downsize(from, to, max_width, max_height, opts={}) - optimize("downsize", from, to, max_width, max_height, opts) + optimize("downsize", from, to, "#{max_width}x#{max_height}", opts) end - def self.optimize(operation, from, to, width, height, opts={}) - dim = dimensions(width, height) + def self.downsize(from, to, dimensions, opts={}) + optimize("downsize", from, to, dimensions, opts) + end + + def self.optimize(operation, from, to, dimensions, opts={}) method_name = "#{operation}_instructions" method_name += "_animated" if !!opts[:allow_animation] && from =~ /\.GIF$/i - instructions = self.send(method_name.to_sym, from, to, dim, opts) + instructions = self.send(method_name.to_sym, from, to, dimensions, opts) convert_with(instructions, to) end - def self.dimensions(width, height) - "#{width}x#{height}" - end - def self.convert_with(instructions, to) `#{instructions.join(" ")} &> /dev/null` return false if $?.exitstatus != 0
Leaderboard for this case
hard · 2 of 9 bots fully caught it (22% solve rate) · 61% avg coverage.
| # | Bot | Result | Caught | Coverage | Findings | False alarms |
|---|---|---|---|---|---|---|
| 1 | Claude Code (Opus 5.5) | solved | 4/4 | 100.0% | 6 | 0 |
| 2 | Drape (Deep Review) | solved | 4/4 | 100.0% | 8 | 0 |
| 3 | Drape (Review) | partial | 3/4 | 71.4% | 6 | 0 |
| 4 | Mjolnir (Opus 5.5) | partial | 3/4 | 71.4% | 6 | 0 |
| 5 | Cubic | partial | 2/4 | 42.9% | 4 | 0 |
| 6 | cursor | partial | 2/4 | 42.9% | 3 | 0 |
| 7 | greptile | partial | 2/4 | 42.9% | 4 | 0 |
| 8 | Mjolnir (Sonnet 5.5) | partial | 2/4 | 42.9% | 4 | 0 |
| 9 | qodo | miss | 0/4 | 0.0% | 0 | 0 |
Bot results
Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | low | ✓ | off by one |
| d3 | medium | ✓ | exact |
| d4 | medium | ✓ | exact |
The 413 handler now always reports 10MB rather than reading a site setting. Before the change it showed max_image_size_kb, which was not the web server's limit either. If the server limit is something other than 10MB, users still get a wrong number. This is a minor messaging issue. [grounded: diff] [consensus 3/4: valid=3, invalid=1]
The download cap used to follow SiteSetting.max_image_size_kb; it is now a fixed 10MB. Remote files of any type up to 10MB get downloaded before validation, and the limit no longer follows admin settings. Later validation may still reject oversized non-image files, so the impact is limited. [grounded: diff] [consensus 3/3: valid=3]
raw comments (6)
Ruby doesn't support method overloading. The second `def self.downsize(from, to, dimensions, opts={})` silently replaces the 5-argument `downsize(from, to, max_width, max_height, opts)` defined just above it. Existing callers like `Jobs::ResizeEmoji` (`OptimizedImage.downsize(path, path, 100, 100, opts)`) now raise ArgumentError (5 for 3..4), so emoji resizing breaks.
The loop overwrites the file at `tempfile.path` with an external `convert`, then re-checks `tempfile.size` through the Tempfile's existing file handle. If ImageMagick replaces the file instead of truncating it in place, that handle still points to the old inode. The size never shrinks, `convert` runs 5 times for nothing, and `Upload.create_for` may read stale content. The return value of `OptimizedImage.downsize` is also ignored, so a failed conversion (for example a non-convertible or corrupt image) still loops 5 times.
With `allow_animation`, GIFs go to `gifsicle --resize-fit 80%`, which gifsicle doesn't accept as a geometry, so animated GIFs are never reduced. Separately, any user can now upload images up to 10MB and trigger up to 5 synchronous ImageMagick runs inside the request. That is a CPU/memory cost and a potential DoS vector.
The client-side size check is now hardcoded to 10MB for every upload type, ignoring `max_attachment_size_kb` and the image limit. If admins set the attachment limit above 10MB, valid uploads are rejected in the browser. If it's below 10MB, users upload the whole file only to have the server reject it. Non-image attachments are never downsized, so the 'max size' shown in the error message is wrong for them.
The 413 error message now reports a hardcoded 10MB instead of the site's configured limit. A 413 comes from the web server's actual limit, which may differ, so users see a misleading maximum size.
API URL downloads now accept up to a hardcoded 10MB regardless of site settings (previously `max_image_size_kb`). This also covers non-image types that won't be downsized, so admins lose control of the download size and larger remote files are pulled before validation.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | low | ✓ | off by one |
| d3 | medium | ✗ | — |
| d4 | medium | ✗ | — |
FileHelper.download stops reading once the file passes max_file_size (`while f.size <= max_file_size && data = downloaded.read(512.kilobytes)`), so the file gets truncated rather than rejected. The old code used max_image_size_kb as the limit. With the new hard-coded 10 MB, sites configured above 10 MB get truncated API URL uploads. [grounded: diff] [consensus 5/5: valid=5]
FileHelper.is_image? includes svg, so an oversized SVG goes into the new loop. That loop runs ImageMagick `convert` on the .svg path and writes the result back over it, which rasterizes or rewrites the vector file. Elsewhere SVGs are kept off this path on purpose (create_for copies them with FileUtils.cp, and Upload.create_for gives them separate handling). [grounded: diff] [consensus 5/5: valid=5]
raw comments (5)
<!-- cubic:v=d7177cba-915d-413b-abfd-92c3bcca49be -->
<!-- cubic:review-run=1b0fca87-353b-53a7-8bce-02a9b83ff77a -->
<!-- metadata:{"confidence":10} -->
P1: The later `downsize` definition replaces the five-argument version, so `ResizeEmoji` now raises `ArgumentError` instead of resizing emoji. Remove the duplicate definition or preserve both the dimension-string and width/height call signatures.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/models/optimized_image.rb, line 149:
<comment>The later `downsize` definition replaces the five-argument version, so `ResizeEmoji` now raises `ArgumentError` instead of resizing emoji. Remove the duplicate definition or preserve both the dimension-string and width/height call signatures.</comment>
<file context>
@@ -139,25 +139,24 @@ def self.downsize_instructions_animated(from, to, dimensions, opts={})
- def self.optimize(operation, from, to, width, height, opts={})
- dim = dimensions(width, height)
+ def self.downsize(from, to, dimensions, opts={})
+ optimize("downsize", from, to, dimensions, opts)
+ end
</file context>
```
</details>
```suggestion
def self.downsize(from, to, dimensions, height=nil, opts={})
if height.is_a?(Hash)
opts = height
elsif height
dimensions = "#{dimensions}x#{height}"
end
optimize("downsize", from, to, dimensions, opts)
end
```
<!-- cubic:v=dcd69547-a143-4393-af04-b73dfba3f859 -->
<!-- cubic:review-run=1b0fca87-353b-53a7-8bce-02a9b83ff77a -->
<!-- metadata:{"confidence":8} -->
P2: When `max_image_size_kb` is configured above 10 MB, API URL uploads are truncated before resizing because this hard-coded limit is lower than the site setting. Use a download limit that is at least the configured upload limit, while retaining an explicit cap if required.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/controllers/uploads_controller.rb, line 55:
<comment>When `max_image_size_kb` is configured above 10 MB, API URL uploads are truncated before resizing because this hard-coded limit is lower than the site setting. Use a download limit that is at least the configured upload limit, while retaining an explicit cap if required.</comment>
<file context>
@@ -52,14 +52,23 @@ def create_upload(type, file, url)
# API can provide a URL
if file.nil? && url.present? && is_api?
- tempfile = FileHelper.download(url, SiteSetting.max_image_size_kb.kilobytes, "discourse-upload-#{type}") rescue nil
+ tempfile = FileHelper.download(url, 10.megabytes, "discourse-upload-#{type}") rescue nil
filename = File.basename(URI.parse(url).path)
else
</file context>
```
</details>
```suggestion
tempfile = FileHelper.download(url, [10.megabytes, SiteSetting.max_image_size_kb.kilobytes, SiteSetting.max_attachment_size_kb.kilobytes].max, "discourse-upload-#{type}") rescue nil
```
<!-- cubic:v=ed9450ed-de5b-4d95-90d6-a67f3e7bb90a -->
<!-- cubic:review-run=1b0fca87-353b-53a7-8bce-02a9b83ff77a -->
<!-- metadata:{"confidence":8} -->
P2: When an authorized SVG exceeds `max_image_size_kb`, this branch sends it through ImageMagick's raster `convert` path. That can fail or rewrite the vector file, so exclude SVGs from this raster resize path or handle SVG resizing separately.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/controllers/uploads_controller.rb, line 64:
<comment>When an authorized SVG exceeds `max_image_size_kb`, this branch sends it through ImageMagick's raster `convert` path. That can fail or rewrite the vector file, so exclude SVGs from this raster resize path or handle SVG resizing separately.</comment>
<file context>
@@ -52,14 +52,23 @@ def create_upload(type, file, url)
end
+ # allow users to upload large images that will be automatically reduced to allowed size
+ if tempfile && tempfile.size > 0 && SiteSetting.max_image_size_kb > 0 && FileHelper.is_image?(filename)
+ attempt = 5
+ while attempt > 0 && tempfile.size > SiteSetting.max_image_size_kb.kilobytes
</file context>
```
</details>
```suggestion
if tempfile && tempfile.size > 0 && SiteSetting.max_image_size_kb > 0 && FileHelper.is_image?(filename) && filename !~ /\.svg$/i
```
<!-- cubic:v=23d7ec7d-97f0-4393-908b-a225ee34ecbe -->
<!-- cubic:review-run=1b0fca87-353b-53a7-8bce-02a9b83ff77a -->
<!-- metadata:{"confidence":9} -->
P2: The hardcoded 10MB replaces the admin-configurable site settings that the server still enforces. With the default limit of 3072 KB, files between 3MB and 10MB now pass the client-side check but are rejected by the server after upload; if an admin raises the limit above 10MB, valid uploads are wrongly blocked client-side with a misleading "10240kb" message. Use the same settings the server validates against (Discourse.SiteSettings['max_' + type + '_size_kb'], and max_image_size_kb in the 413 branch) so the client check and its error message stay consistent with the actual server limit.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/assets/javascripts/discourse/lib/utilities.js, line 182:
<comment>The hardcoded 10MB replaces the admin-configurable site settings that the server still enforces. With the default limit of 3072 KB, files between 3MB and 10MB now pass the client-side check but are rejected by the server after upload; if an admin raises the limit above 10MB, valid uploads are wrongly blocked client-side with a misleading "10240kb" message. Use the same settings the server validates against (Discourse.SiteSettings['max_' + type + '_size_kb'], and max_image_size_kb in the 413 branch) so the client check and its error message stay consistent with the actual server limit.</comment>
<file context>
@@ -179,7 +179,7 @@ Discourse.Utilities = {
// check file size
var fileSizeKB = file.size / 1024;
- var maxSizeKB = Discourse.SiteSettings['max_' + type + '_size_kb'];
+ var maxSizeKB = 10 * 1024; // 10MB
if (fileSizeKB > maxSizeKB) {
bootbox.alert(I18n.t('post.errors.file_too_large', { max_size_kb: maxSizeKB }));
</file context>
```
</details>
```suggestion
var maxSizeKB = Discourse.SiteSettings['max_' + type + '_size_kb'];
```
<!-- cubic:review-summary:start -->
**4 issues found** across 3 files
<!-- cubic:review-summary:end -->
<details>
<summary>Prompt for AI agents (unresolved issues)</summary>
```text
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="app/models/optimized_image.rb">
<violation number="1" location="app/models/optimized_image.rb:149">
P1: The later `downsize` definition replaces the five-argument version, so `ResizeEmoji` now raises `ArgumentError` instead of resizing emoji. Remove the duplicate definition or preserve both the dimension-string and width/height call signatures.</violation>
</file>
<file name="app/controllers/uploads_controller.rb">
<violation number="1" location="app/controllers/uploads_controller.rb:55">
P2: When `max_image_size_kb` is configured above 10 MB, API URL uploads are truncated before resizing because this hard-coded limit is lower than the site setting. Use a download limit that is at least the configured upload limit, while retaining an explicit cap if required.</violation>
<violation number="2" location="app/controllers/uploads_controller.rb:64">
P2: When an authorized SVG exceeds `max_image_size_kb`, this branch sends it through ImageMagick's raster `convert` path. That can fail or rewrite the vector file, so exclude SVGs from this raster resize path or handle SVG resizing separately.</violation>
</file>
<file name="app/assets/javascripts/discourse/lib/utilities.js">
<violation number="1" location="app/assets/javascripts/discourse/lib/utilities.js:182">
P2: The hardcoded 10MB replaces the admin-configurable site settings that the server still enforces. With the default limit of 3072 KB, files between 3MB and 10MB now pass the client-side check but are rejected by the server after upload; if an admin raises the limit above 10MB, valid uploads are wrongly blocked client-side with a misleading "10240kb" message. Use the same settings the server validates against (Discourse.SiteSettings['max_' + type + '_size_kb'], and max_image_size_kb in the 413 branch) so the client check and its error message stay consistent with the actual server limit.</violation>
</file>
```
</details>
<sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/29/ai_pr_review_github_delivery_0beff9212aa4ef6c0f7b036591aa10e1ecd7ebdbecca5994a407efd364614080?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F29)</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_0beff9212aa4ef6c0f7b036591aa10e1ecd7ebdbecca5994a407efd364614080:acad511e1d1d135c8a993c616cafd0d16b8926dc:1b0fca87-353b-53a7-8bce-02a9b83ff77a -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | low | ✓ | off by one |
| d3 | medium | ✗ | — |
| d4 | medium | ✗ | — |
`optimize` only picks the `_animated` instructions when `from =~ /\.GIF$/i`. The path passed in here is the tempfile path, which has no .gif extension: Rack 1.5.5 names multipart tempfiles `RackMultipart`, and the API download names them `discourse-upload-#{type}`. So the call falls through to `downsize_instructions`, which uses `#{from}[0]` and keeps only the first frame. That flattens large animated GIFs, and this downsize loop is new in this change. [grounded: diff] [consensus 4/5: valid=4, invalid=1]
raw comments (4)
### Duplicate downsize overwrites existing API
**High Severity**
<!-- DESCRIPTION START -->
Two `downsize` methods are defined in a row. Ruby keeps only the last one, so the four-argument form is discarded. `ResizeEmoji` still calls `OptimizedImage.downsize` with width and height, which raises `ArgumentError` and leaves custom emojis at their original size.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: edeba5f7-5208-44a9-b571-267637c4ef95 -->
<!-- LOCATIONS START
app/models/optimized_image.rb#L144-L151
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjAzMDUyZjEwLWQ3MmYtNGJiMi1hYTM0LWMyNDZmOWY0OTRkMCIsImVuY3J5cHRpb25LZXkiOiJyb0Vkbm9ST3hRWndNcGZDV1VkQ3lrTUJRUFZkOW9qb0FtSXV0SU9INTg0IiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTEiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjAzMDUyZjEwLWQ3MmYtNGJiMi1hYTM0LWMyNDZmOWY0OTRkMCIsImVuY3J5cHRpb25LZXkiOiJyb0Vkbm9ST3hRWndNcGZDV1VkQ3lrTUJRUFZkOW9qb0FtSXV0SU9INTg0IiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTEiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjozMCwiY29tbWl0U2hhIjoiZWNhNmYxYmFjMGFiYmI5Y2RiYzYyNGQxOTk0MDdlMDU5OGE0YWJkMCIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit eca6f1bac0abbb9cdbc624d199407e0598a4abd0. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Client size check ignores site settings
**Medium Severity**
<!-- DESCRIPTION START -->
`validateUploadedFile` now uses a hardcoded 10MB cap for every file type instead of `max_image_size_kb` / `max_attachment_size_kb`. Attachments over the real attachment limit pass the browser check and fail on the server, and admin limits above 10MB are ignored. The 413 handler reports the same hardcoded value.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 6f0fe891-299e-4ea2-a7f1-4b0bdafb77df -->
<!-- LOCATIONS START
app/assets/javascripts/discourse/lib/utilities.js#L181-L186
app/assets/javascripts/discourse/lib/utilities.js#L245-L247
LOCATIONS END -->
<details>
<summary>Additional Locations (1)</summary>
- [`app/assets/javascripts/discourse/lib/utilities.js#L245-L247`](https://github.com/drape-io/crbench-cursor-2026-09/blob/eca6f1bac0abbb9cdbc624d199407e0598a4abd0/app/assets/javascripts/discourse/lib/utilities.js#L245-L247)
</details>
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmMyOTZiYjFjLWI3NDgtNDZhMi1hZDZmLWYwODMzY2RkZmViZiIsImVuY3J5cHRpb25LZXkiOiJtb3FUZkVmVmFYUFFtaUJ1MmZGbmlyOTI0VG5YMUNLeENlR2EwbzlIbkowIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTEiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmMyOTZiYjFjLWI3NDgtNDZhMi1hZDZmLWYwODMzY2RkZmViZiIsImVuY3J5cHRpb25LZXkiOiJtb3FUZkVmVmFYUFFtaUJ1MmZGbmlyOTI0VG5YMUNLeENlR2EwbzlIbkowIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTEiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjozMCwiY29tbWl0U2hhIjoiZWNhNmYxYmFjMGFiYmI5Y2RiYzYyNGQxOTk0MDdlMDU5OGE0YWJkMCIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit eca6f1bac0abbb9cdbc624d199407e0598a4abd0. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Downsize loop strips animated GIFs
**Medium Severity**
<!-- DESCRIPTION START -->
The new downsize loop calls `OptimizedImage.downsize` with the Rack `tempfile` path, which has no `.gif` extension. Animation handling only activates when the path matches `/\.GIF$/i`, so large animated GIFs are processed with ImageMagick `[0]` and lose all but the first frame. The call also keys off `allow_animated_thumbnails`, a thumbnail setting, not original-upload behavior.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 7dbf6b58-dff6-4863-9bfe-27c5b45fec1b -->
<!-- LOCATIONS START
app/controllers/uploads_controller.rb#L62-L70
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmU4OTVmOGQwLWFhOGQtNDg3Mi1iYmUyLWI3ODRlNzc5MmQwNyIsImVuY3J5cHRpb25LZXkiOiJYbm5zODZIbW1wZTMwTmIxaHZ0S1B5Tnkwa2t3VnpaMUR2YnRTaFl3Ql9FIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTEiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmU4OTVmOGQwLWFhOGQtNDg3Mi1iYmUyLWI3ODRlNzc5MmQwNyIsImVuY3J5cHRpb25LZXkiOiJYbm5zODZIbW1wZTMwTmIxaHZ0S1B5Tnkwa2t3VnpaMUR2YnRTaFl3Ql9FIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTEiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjozMCwiY29tbWl0U2hhIjoiZWNhNmYxYmFjMGFiYmI5Y2RiYzYyNGQxOTk0MDdlMDU5OGE0YWJkMCIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit eca6f1bac0abbb9cdbc624d199407e0598a4abd0. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_REVIEW -->
Cursor Bugbot has reviewed your changes using high effort and found 3 potential issues.
<!-- BUGBOT_FIX_ALL -->
<a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTphM2RmMGE2My1kM2U4LTQ1MDYtYWE0Yi1mNzJmMmUzYzg5M2EiLCJlbmNyeXB0aW9uS2V5IjoiYjNFMXhVQzdmRVhjekY1SlNLb2MyR045Q1VwSjhoZWdXcGRBbi0yRlJjUSIsImJyYW5jaCI6InQyLWRpc2NvdXJzZS1ncmFwaGl0ZS0xIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>
<!-- /BUGBOT_FIX_ALL -->
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN -->
<sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END -->
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit eca6f1bac0abbb9cdbc624d199407e0598a4abd0. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | exact |
| d2 | low | ✓ | off by one |
| d3 | medium | ✓ | exact |
| d4 | medium | ✓ | exact |
FileHelper.images includes "svg", so the new loop runs ImageMagick `convert` on oversized SVGs in place, and the original vector markup gets overwritten. Before this change, such a file was just checked against the size limit and left untouched. [grounded: diff] [consensus 3/3: valid=3]
When allow_animated_thumbnails is false, downsize_instructions runs `convert #{from}[0]`. That keeps only the first frame, so an oversized animated GIF is saved as a still image. [grounded: diff] [consensus 3/3: valid=3]
The 413 message now always reports a hard-coded 10MB. The old code used a site setting, which also didn't necessarily match the web server's limit. Whether the message is actually wrong depends on how the server is configured, so this is speculative and low impact. [grounded: diff] [consensus 3/4: valid=3, uncertain=1]
The download cap is now a hard-coded 10MB instead of the configured setting. FileHelper.download stops reading silently without raising, so on sites with a higher configured limit, API URL uploads over 10MB are stored truncated. [grounded: tree lib/file_helper.rb] [consensus 3/3: valid=3]
raw comments (8)
**Oversized SVGs are re-rendered by ImageMagick**
An SVG over max_image_size_kb matches FileHelper.is_image?, so the loop runs ImageMagick convert on it in place. The user's vector markup is replaced with ImageMagick's rendering instead of being rejected untouched. Exclude .svg from the downsize condition.
```
app/controllers/uploads_controller.rb:64 if tempfile && tempfile.size > 0 && SiteSetting.max_image_size_kb > 0 && FileHelper.is_image?(filename)
app/controllers/uploads_controller.rb:65 attempt = 5
app/controllers/uploads_controller.rb:66 while attempt > 0 && tempfile.size > SiteSetting.max_image_size_kb.kilobytes
app/controllers/uploads_controller.rb:67 OptimizedImage.downsize(tempfile.path, tempfile.path, "80%", allow_animation: SiteSetting.allow_animated_thumbnails)
lib/file_helper.rb:31 @@images ||= Set.new ["jpg", "jpeg", "png", "gif", "tif", "tiff", "bmp", "svg", "webp"]
app/models/upload.rb:63 if filename =~ /\.svg$/i
app/models/upload.rb:64 svg = Nokogiri::XML(file).at_css("svg")
app/models/upload.rb:65 w = svg["width"].to_i
app/models/upload.rb:66 h = svg["height"].to_i
```
**Client ignores admin-configured upload size limits**
`maxSizeKB` is now always 10MB, even for attachments. If an admin allows attachments or images over 10MB, the browser refuses valid files. If the limit is smaller, the user only finds out after uploading the whole file. Keep using max_attachment_size_kb for attachments, and only use the raised cap for images.
```
app/assets/javascripts/discourse/lib/utilities.js:182 var maxSizeKB = 10 * 1024; // 10MB
lib/validators/upload_validator.rb:80 def maximum_file_size(upload, type)
lib/validators/upload_validator.rb:81 max_size_kb = SiteSetting.send("max_#{type}_size_kb")
lib/validators/upload_validator.rb:82 max_size_bytes = max_size_kb.kilobytes
lib/validators/upload_validator.rb:84 if upload.filesize > max_size_bytes
lib/validators/upload_validator.rb:85 message = I18n.t("upload.#{type}s.too_large", max_size_kb: max_size_kb)
lib/validators/upload_validator.rb:86 upload.errors.add(:filesize, message)
lib/validators/upload_validator.rb:87 end
app/assets/javascripts/discourse/controllers/upload-selector.js.es6:17 maxSize: setting('max_attachment_size_kb'),
```
**Large animated GIFs lose their animation**
When `allow_animated_thumbnails` is off, the downsize runs `convert file[0]`, which keeps only the first frame. Any animated GIF over the size limit is silently saved as a still image, not as a smaller animation. Skip auto-downsizing for GIFs that can't keep their animation, or reject them with the size error.
```
app/controllers/uploads_controller.rb:64 if tempfile && tempfile.size > 0 && SiteSetting.max_image_size_kb > 0 && FileHelper.is_image?(filename)
app/controllers/uploads_controller.rb:65 attempt = 5
app/controllers/uploads_controller.rb:66 while attempt > 0 && tempfile.size > SiteSetting.max_image_size_kb.kilobytes
app/controllers/uploads_controller.rb:67 OptimizedImage.downsize(tempfile.path, tempfile.path, "80%", allow_animation: SiteSetting.allow_animated_thumbnails)
app/models/optimized_image.rb:129 #{from}[0]
```
**413 error reports a hard-coded 10MB limit**
When the web server rejects an upload as too large, the message now always says 10MB. The server's real limit can differ, so users are told the wrong maximum.
```
app/assets/javascripts/discourse/lib/utilities.js:246 var maxSizeKB = 10 * 1024; // 10 MB
```
**Emoji resize job crashes with ArgumentError**
The new three-argument `downsize` silently replaces the width/height version defined just above it (Ruby keeps the last definition), so `ResizeEmoji` calling `downsize(path, path, 100, 100, opts)` now passes 5 args to a 4-param method. Give the percentage variant a different name (e.g. `downsize_to`), or have one `downsize` accept either form.
```
app/models/optimized_image.rb:145 def self.downsize(from, to, max_width, max_height, opts={})
app/models/optimized_image.rb:146 optimize("downsize", from, to, "#{max_width}x#{max_height}", opts)
app/models/optimized_image.rb:147 end
app/models/optimized_image.rb:149 def self.downsize(from, to, dimensions, opts={})
app/models/optimized_image.rb:150 optimize("downsize", from, to, dimensions, opts)
app/models/optimized_image.rb:151 end
app/jobs/regular/resize_emoji.rb:14 OptimizedImage.downsize(path, path, 100, 100, opts)
```
**API URL uploads truncated at 10 MB**
`FileHelper.download` stops reading once it passes the hard-coded 10 MB and returns a partial file without raising. On sites whose image or attachment limit is above 10 MB, larger allowed files are stored corrupted. Use the larger of 10 MB and the configured image and attachment limits.
```
app/controllers/uploads_controller.rb:55 tempfile = FileHelper.download(url, 10.megabytes, "discourse-upload-#{type}") rescue nil
lib/file_helper.rb:18 while f.size <= max_file_size && data = downloaded.read(512.kilobytes)
lib/file_helper.rb:19 f.write(data)
lib/file_helper.rb:20 end
```
**Oversized animated GIFs are never shrunk**
With `allow_animated_thumbnails` on, `.gif` files go through gifsicle `--resize-fit 80%`. That option needs WxH, not a percentage, so every attempt fails and big GIFs stay too large and get rejected. Use gifsicle `--scale 0.8` for the animated path, or compute WxH from the image's dimensions.
```
app/controllers/uploads_controller.rb:64 if tempfile && tempfile.size > 0 && SiteSetting.max_image_size_kb > 0 && FileHelper.is_image?(filename)
app/controllers/uploads_controller.rb:65 attempt = 5
app/controllers/uploads_controller.rb:66 while attempt > 0 && tempfile.size > SiteSetting.max_image_size_kb.kilobytes
app/controllers/uploads_controller.rb:67 OptimizedImage.downsize(tempfile.path, tempfile.path, "80%", allow_animation: SiteSetting.allow_animated_thumbnails)
app/models/optimized_image.rb:115 def self.resize_instructions_animated(from, to, dimensions, opts={})
app/models/optimized_image.rb:116 %W{
app/models/optimized_image.rb:117 gifsicle
app/models/optimized_image.rb:118 #{from}
app/models/optimized_image.rb:119 --colors=256
app/models/optimized_image.rb:120 --resize-fit #{dimensions}
```
**Shrink loop reads stale size after ImageOptim**
ImageOptim replaces the file by rename, so after the first pass `tempfile.size` and FastImage read an orphaned inode. The loop over-shrinks, and the recorded filesize and dimensions don't match the stored file. Check `File.size(tempfile.path)` and reopen the file after downsizing.
```
app/controllers/uploads_controller.rb:66 while attempt > 0 && tempfile.size > SiteSetting.max_image_size_kb.kilobytes
app/controllers/uploads_controller.rb:67 OptimizedImage.downsize(tempfile.path, tempfile.path, "80%", allow_animation: SiteSetting.allow_animated_thumbnails)
app/controllers/uploads_controller.rb:68 attempt -= 1
app/controllers/uploads_controller.rb:69 end
app/models/optimized_image.rb:164 ImageOptim.new.optimize_image!(to)
app/models/upload.rb:71 image_info = FastImage.new(file) rescue nil
```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | low | ✓ | off by one |
| d3 | medium | ✓ | exact |
| d4 | medium | ✗ | — |
Before this change the download cap followed SiteSetting.max_image_size_kb. Now it is a fixed 10MB, and FileHelper.download stops reading at that cap. On a site where the admin set the limit above 10MB, larger URL images are truncated or fail, so behavior changed from before. [grounded: diff] [consensus 3/3: valid=3]
The new loop ignores downsize's return value. convert_with returns false on failure, so when conversion fails the loop reruns the same command until all five attempts are used. Only effort is wasted, so the impact is low. [grounded: diff] [consensus 3/3: valid=3]
FileHelper.is_image? counts svg as an image, so an oversized SVG enters the loop. ImageMagick then rewrites (rasterizes) it in place with convert -resize. Before this change, such a file would have gone to Upload.create_for unchanged. [grounded: diff] [consensus 3/3: valid=3]
raw comments (6)
**Large animated GIFs fail to downsize**
`"80%"` is passed as dimensions, but gifsicle's `--resize-fit` needs `WxH`, so API-URL GIFs (temp path ends in `.gif`) are never shrunk. Browser uploads have no extension, so `convert` keeps only frame 0 and flattens the animation. Use gifsicle --scale for GIFs, and avoid flattening animated ones.
```
app/controllers/uploads_controller.rb:64 if tempfile && tempfile.size > 0 && SiteSetting.max_image_size_kb > 0 && FileHelper.is_image?(filename)
app/controllers/uploads_controller.rb:65 attempt = 5
app/controllers/uploads_controller.rb:66 while attempt > 0 && tempfile.size > SiteSetting.max_image_size_kb.kilobytes
app/controllers/uploads_controller.rb:67 OptimizedImage.downsize(tempfile.path, tempfile.path, "80%", allow_animation: SiteSetting.allow_animated_thumbnails)
app/models/optimized_image.rb:115 def self.resize_instructions_animated(from, to, dimensions, opts={})
app/models/optimized_image.rb:116 %W{
app/models/optimized_image.rb:117 gifsicle
app/models/optimized_image.rb:118 #{from}
app/models/optimized_image.rb:119 --colors=256
app/models/optimized_image.rb:120 --resize-fit #{dimensions}
```
**Client upload size limit hardcoded to 10MB**
validateUploadedFile no longer reads `max_<type>_size_kb` and uses a fixed 10MB for every upload type, so max_attachment_size_kb is ignored. The 413 handler also hardcodes 10MB. Use the 10MB allowance only for images; keep Discourse.SiteSettings['max_' + type + '_size_kb'] for attachments, and use the setting in the 413 message.
```
app/assets/javascripts/discourse/lib/utilities.js:182 var maxSizeKB = 10 * 1024; // 10MB
app/assets/javascripts/discourse/lib/utilities.js:246 var maxSizeKB = 10 * 1024; // 10 MB
test/javascripts/lib/utilities-test.js.es6:79 Discourse.SiteSettings.max_image_size_kb = 15;
test/javascripts/lib/utilities-test.js.es6:80 Discourse.SiteSettings.max_attachment_size_kb = 1;
```
**Custom emoji resize job crashes with ArgumentError**
The new 4-parameter `downsize` replaces the 5-parameter one, so ResizeEmoji's call `downsize(path, path, 100, 100, opts)` raises ArgumentError and emoji are never shrunk. Give the new method a different name, e.g. `downsize_to`.
```
app/models/optimized_image.rb:145 def self.downsize(from, to, max_width, max_height, opts={})
app/models/optimized_image.rb:146 optimize("downsize", from, to, "#{max_width}x#{max_height}", opts)
app/models/optimized_image.rb:147 end
app/models/optimized_image.rb:149 def self.downsize(from, to, dimensions, opts={})
app/jobs/regular/resize_emoji.rb:14 OptimizedImage.downsize(path, path, 100, 100, opts)
```
**API URL download limit hardcoded to 10MB**
The URL download limit no longer follows `max_image_size_kb` and is fixed at 10MB. Non-image URLs and oversized images are fetched up to 10MB regardless of settings. Images above 10MB still fail even if the admin allowed larger. Use max of the configured limit and the intended ceiling, not a constant.
```
app/controllers/uploads_controller.rb:55 tempfile = FileHelper.download(url, 10.megabytes, "discourse-upload-#{type}") rescue nil
```
**Downsize loop ignores failed conversion**
The loop repeats `OptimizedImage.downsize` up to 5 times without checking its return value. If conversion fails (e.g. ImageMagick missing or unsupported format), it reruns the same failing command five times. The image then goes to `Upload.create_for` oversized and is rejected there. Break out of the loop when downsize returns false.
```
app/controllers/uploads_controller.rb:64 if tempfile && tempfile.size > 0 && SiteSetting.max_image_size_kb > 0 && FileHelper.is_image?(filename)
app/controllers/uploads_controller.rb:65 attempt = 5
app/controllers/uploads_controller.rb:66 while attempt > 0 && tempfile.size > SiteSetting.max_image_size_kb.kilobytes
app/controllers/uploads_controller.rb:67 OptimizedImage.downsize(tempfile.path, tempfile.path, "80%", allow_animation: SiteSetting.allow_animated_thumbnails)
app/models/optimized_image.rb:160 def self.convert_with(instructions, to)
app/models/optimized_image.rb:161 `#{instructions.join(" ")} &> /dev/null`
app/models/optimized_image.rb:162 return false if $?.exitstatus != 0
app/models/optimized_image.rb:164 ImageOptim.new.optimize_image!(to)
app/models/optimized_image.rb:165 true
app/models/optimized_image.rb:166 rescue
```
**Oversized SVGs get rewritten by ImageMagick**
When an SVG exceeds max_image_size_kb, the new loop runs ImageMagick `convert -resize 80%` on it in place, rasterizing or rewriting the vector file instead of rejecting it as too large. Exclude `.svg` from the downsize condition.
```
app/controllers/uploads_controller.rb:64 if tempfile && tempfile.size > 0 && SiteSetting.max_image_size_kb > 0 && FileHelper.is_image?(filename)
app/controllers/uploads_controller.rb:65 attempt = 5
app/controllers/uploads_controller.rb:66 while attempt > 0 && tempfile.size > SiteSetting.max_image_size_kb.kilobytes
app/controllers/uploads_controller.rb:67 OptimizedImage.downsize(tempfile.path, tempfile.path, "80%", allow_animation: SiteSetting.allow_animated_thumbnails)
lib/file_helper.rb:30 def self.images
lib/file_helper.rb:31 @@images ||= Set.new ["jpg", "jpeg", "png", "gif", "tif", "tiff", "bmp", "svg", "webp"]
app/models/upload.rb:62 if FileHelper.is_image?(filename)
app/models/upload.rb:63 if filename =~ /\.svg$/i
app/models/upload.rb:64 svg = Nokogiri::XML(file).at_css("svg")
app/models/upload.rb:65 w = svg["width"].to_i
```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | low | ✓ | wrong severity |
| d3 | medium | ✗ | — |
| d4 | medium | ✗ | — |
optimize picks the animated path only when `from =~ /\.GIF$/i`, and it is passed tempfile.path. The repo pins rack 1.5.5, which names multipart tempfiles "RackMultipart" with no extension, so browser-uploaded GIFs go through the convert path that keeps only frame [0]. URL downloads keep the extension, so this hits browser uploads only. [grounded: diff] [consensus 3/4: valid=3, invalid=1]
The new loop runs up to five ImageMagick conversions on user-supplied images before any size validation. The change also raises the accepted size to a hard-coded 10MB, so any authenticated user can make each upload use much more CPU and memory. The upload path already ran convert before this change, so the risk is worsened rather than newly created, and the impact is moderate. [grounded: diff] [consensus 3/3: valid=3]
raw comments (5)
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Upload Limits No Longer Match**
The fixed 10 MB client limit no longer matches the server, which still enforces the independently configured `max_image_size_kb` and `max_attachment_size_kb` values. With the default 3 MB settings, files between 3 MB and 10 MB are uploaded only to be rejected. If either setting exceeds 10 MB, the client rejects files the server would accept. The related fixed 413 message can also show users the wrong limit.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Downsize Overload Breaks Jobs**
Ruby does not overload methods by arity, so this second `downsize` definition replaces the width-and-height form above it. `Jobs::ResizeEmoji` still calls `OptimizedImage.downsize(path, path, 100, 100, opts)`, which now raises `ArgumentError` and prevents emoji resize jobs from running.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Animated GIFs Lose Animation**
Oversized animated GIFs lose their animation even when `allow_animated_thumbnails` is enabled. The controller identifies the image using `filename`, but passes the extensionless tempfile path to `downsize`. Animation selection checks that path for a `.GIF` suffix, falls back to the non-animated ImageMagick command, and processes only the first frame.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> <a href="#"><img alt="security" src="https://greptile-static-assets.s3.amazonaws.com/badges/Security.svg?v=2" align="top"></a> **Uploads Trigger Unbounded Conversion**
This loop performs up to five synchronous ImageMagick decodes of an attacker-supplied image before upload-size validation. Any authenticated user or API-key caller can submit an oversized or high-expansion image, while this path applies no pixel, memory, process, or execution-time limit and has no upload-specific rate limiter. Repeated requests can therefore exhaust worker CPU or memory.
**How this was verified:** Authenticated upload input reaches five unbounded `convert` executions before the configured filesize validator runs.
<h3>Greptile Summary</h3>
This PR introduces a fixed 10 MB browser and remote-download ceiling, attempts to shrink oversized images before creating uploads, and changes `OptimizedImage` to accept preformatted dimensions.
- Client and server upload limits can now disagree.
- The replacement `downsize` signature breaks the existing emoji-resize job.
- Oversized animated GIFs can be flattened to their first frame.
- Repeated pre-validation image conversion exposes authenticated upload workers to resource exhaustion.
<h3>Confidence Score: 0/5</h3>
This PR is not safe to merge because it breaks emoji resize jobs, misapplies upload limits, strips valid GIF animation, and adds an authenticated resource-exhaustion path.
Ruby method replacement causes a confirmed runtime argument error, fixed browser limits conflict with server-configured limits, tempfile-based animation detection selects the wrong conversion path, and oversized attacker-controlled images undergo repeated unbounded processing before validation.
**Files Needing Attention:** app/assets/javascripts/discourse/lib/utilities.js, app/controllers/uploads_controller.rb, app/models/optimized_image.rb
<details open><summary><h3>Security Review</h3></summary>
Authenticated users and API-key callers can trigger up to five synchronous, resource-unbounded ImageMagick conversions before configured upload-size validation, creating a CPU and memory exhaustion path.
</details>
<details><summary><h3>Important Files Changed</h3></summary>
| Filename | Overview |
|----------|----------|
| app/assets/javascripts/discourse/lib/utilities.js | Replaces configured, type-specific upload limits and 413 messaging with a fixed 10 MB value, causing client/server validation mismatches. |
| app/controllers/uploads_controller.rb | Downloads larger remote inputs and repeatedly downsizes oversized images before validation, introducing animation loss and unbounded conversion work. |
| app/models/optimized_image.rb | Adds a dimensions-string API but accidentally replaces the existing `downsize` method, breaking its five-argument caller. |
</details>
<details open><summary><h3>Flowchart</h3></summary>
```mermaid
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Authenticated upload request] --> B{Multipart file or API URL}
B -->|API URL| C[Download up to fixed 10 MB]
B -->|Multipart| D[Use uploaded tempfile]
C --> E{Image and above configured limit?}
D --> E
E -->|Yes| F[Run ImageMagick downsize up to five times]
F --> G[Upload.create_for]
E -->|No| G
G --> H[Configured image or attachment validation]
H -->|Valid| I[Persist upload and enqueue thumbnails]
H -->|Invalid| J[Reject upload]
```
</details>
<!-- greptile_other_comments_section -->
<sub>Reviews (1): Last reviewed commit: ["Update app/assets/javascripts/discourse/..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/0557f8800729e68d1a86ff6a955131e7d975ab36) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284332)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | low | ✓ | off by one |
| d3 | medium | ✓ | exact |
| d4 | medium | ✗ | — |
Ruby has no overloading, so the second definition replaces the first. resize_emoji.rb line 14 still calls `OptimizedImage.downsize(path, path, 100, 100, opts)` with 5 arguments, and the new method accepts at most 4, so it raises ArgumentError. [grounded: diff] [consensus 3/3: valid=3]
The client check used to read the per-type setting `max_' + type + '_size_kb`. It now applies a fixed 10MB to attachments too, so it blocks files the server would accept when the configured limit is above 10MB. It also shows the wrong limit in error messages. [grounded: diff] [consensus 3/3: valid=3]
For .gif paths with animation allowed, the code calls downsize_instructions_animated, which builds `gifsicle --resize-fit 80%`. `--resize-fit` expects WxH geometry, not a percentage, so the command fails. The loop ignores the false return from convert_with and repeats the same failing command. [grounded: diff] [consensus 3/3: valid=3]
raw comments (6)
[P1] Second `downsize` definition replaces the 5-argument one and breaks emoji resizing
Ruby has no method overloading, so the new `def self.downsize(from, to, dimensions, opts={})` silently replaces the `downsize(from, to, max_width, max_height, opts={})` defined just above it. Any existing caller that passes separate width and height now raises `ArgumentError` (5 arguments for 3..4). One such caller is `Jobs::ResizeEmoji` (`OptimizedImage.downsize(path, path, 100, 100, opts)` in app/jobs/regular/resize_emoji.rb), so every custom emoji upload job will fail and emoji will no longer be reduced to 100x100.
[P2] Client-side size check hardcodes 10MB and no longer uses `max_attachment_size_kb`
`validateUploadedFile` now applies a fixed 10MB limit to every file type. The server still enforces `max_attachment_size_kb` for attachments, but downsizing only applies to images. This causes two problems for attachments. If an admin sets `max_attachment_size_kb` above 10240, valid attachments are now rejected in the browser. If the setting is below 10MB, oversized attachments get past the client check and are uploaded, only to be rejected by the server. The 413 handler at line 246 has the same issue: it always reports a 10MB limit, whatever the server is actually configured to allow.
[P2] Auto-downsize passes "80%" to gifsicle for GIFs, so animated GIFs are never reduced
When `allow_animated_thumbnails` is enabled and the upload is a `.gif`, `optimize` goes through `downsize_instructions_animated` to `resize_instructions_animated`, which runs `gifsicle --resize-fit 80%`. `--resize-fit` expects a `WxH` geometry, so the command fails and the file is left unchanged. The loop then runs five no-op attempts and the upload is still rejected for being too large. That defeats the point of the change for oversized GIFs whenever animation is allowed.
[P1] Second `downsize` definition replaces the four-argument version and breaks existing callers
Ruby doesn't support method overloading, so the new `def self.downsize(from, to, dimensions, opts={})` silently replaces the `downsize(from, to, max_width, max_height, opts={})` defined just above it. Existing callers that pass width and height separately now fail. For example, `app/jobs/regular/resize_emoji.rb:14` calls `OptimizedImage.downsize(path, path, 100, 100, opts)`, which now raises `ArgumentError` (5 arguments given, at most 4 accepted), so emoji resizing is broken. Any other code using the width/height form will raise the same error.
[P2] Client-side size check is hardcoded to 10MB and ignores the configured image/attachment limits
`validateUploadedFile` used to check `max_‹type›_size_kb` and now uses a fixed `10 * 1024` for every upload type, attachments included. If an admin sets `max_attachment_size_kb` (or the image limit) above 10MB, the browser now blocks files the server would accept and shows a wrong "max size" message. Below 10MB, the client no longer catches oversized attachments early. The same hardcoded value also makes the 413 error message at line 246 show the wrong limit. The URL download in `uploads_controller.rb:55` has a similar problem: it is now capped at a fixed `10.megabytes` regardless of the site settings.
[P2] Animated GIF downsizing uses a percentage that gifsicle doesn't accept
When `allow_animated_thumbnails` is enabled and the upload is a `.gif`, `optimize` sends the job to `downsize_instructions_animated`, which runs `gifsicle --resize-fit 80%`. `--resize-fit` expects a `WxH` geometry, not a percentage, so the command fails. `convert_with` returns false, the loop ignores that and retries the same failing command 5 times, and large animated GIFs are never reduced. Those uploads are still rejected by the size validator, which defeats the purpose of this change for GIFs.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | low | ✓ | off by one |
| d3 | medium | ✗ | — |
| d4 | medium | ✗ | — |
Ruby has no overloading, so the later 4-parameter downsize replaces the 5-parameter one. ResizeEmoji still calls `OptimizedImage.downsize(path, path, 100, 100, opts)` with 5 arguments, which now raises ArgumentError, so emoji resizing breaks. [grounded: diff] [consensus 3/3: valid=3]
The removed line read `max_' + type + '_size_kb'`, so attachments used to follow max_attachment_size_kb. Now every type is capped at 10MB in the browser, which blocks larger attachments that admins allowed and shows the wrong limit in the error dialog. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
[P1] Duplicate `self.downsize` definition breaks emoji resizing
Ruby has no method overloading, so the new 3-argument `def self.downsize(from, to, dimensions, opts={})` replaces the earlier `downsize(from, to, max_width, max_height, opts={})`. The existing caller `OptimizedImage.downsize(path, path, 100, 100, opts)` in app/jobs/regular/resize_emoji.rb:14 now passes `100` as `dimensions` and `100` as `opts`. That call then runs `optimize` with the dimensions string "100" and a non-Hash `opts` (an Integer). `opts[:allow_animation]` on an Integer raises, and without that crash the resize would use the wrong dimensions. Every custom emoji upload that runs `ResizeEmoji` will therefore fail. Only one `downsize` should be defined, with a signature that both callers can use.
[P2] Client-side upload limit hard-coded to 10MB, ignoring `max_attachment_size_kb` and `max_image_size_kb`
The `max_‹type›_size_kb` lookup was replaced with a fixed 10MB, and the 413 handler was changed the same way. The `attachment` type is still enforced server-side by `max_attachment_size_kb` (app/models/upload.rb:169) and is configurable in app/assets/javascripts/discourse/controllers/upload-selector.js.es6:17. An admin who sets that limit above 10MB can no longer upload larger attachments, because the client rejects them. An admin who sets it below 10MB gets no client-side check, so the file is uploaded and only rejected by the server. The 413 message also reports the wrong limit. The 10MB cap is only appropriate for images that the server will downsize. It should not apply to non-image types.
[P1] Duplicate `downsize` definition breaks emoji resizing
The 5-argument `self.downsize(from, to, max_width, max_height, opts={})` is immediately overridden by the new 3-argument `self.downsize(from, to, dimensions, opts={})`, because Ruby has no overloading. The existing caller `OptimizedImage.downsize(path, path, 100, 100, opts)` in app/jobs/regular/resize_emoji.rb:14 now passes 5 arguments to a method that accepts at most 4, so it raises ArgumentError. Every emoji upload's resize job therefore fails. Only the new `"80%"` call in uploads_controller works. The old signature should be removed and the emoji caller updated, or the two forms should be merged into one method.
[P2] Client-side size limit hardcoded to 10MB ignores the attachment setting
`maxSizeKB` no longer reads `max_‹type›_size_kb`, so it is a fixed 10MB for every upload type. Non-image attachments (`max_attachment_size_kb`) are no longer downsized on the server and are also capped at 10MB in the browser. Admins who set `max_attachment_size_kb` above 10MB can no longer upload larger attachments, and the error dialog reports the wrong limit. If the setting is below 10MB, oversized non-image files are only rejected after upload. The 10MB cap should apply only to images, or the attachment setting should still be used.
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | low | ✗ | — |
| d3 | medium | ✗ | — |
| d4 | medium | ✗ | — |
raw comments (2)
<h3>Qodo is busy working</h3>
Check back in a few minutes. Qodo's code review agents are on it.
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<img src="https://www.qodo.ai/wp-content/uploads/2026/01/anteater-looking-at-ants-01-transparent-bg-croped-ezgif.com-optimize-1.gif" width="30%">
<h3>PR Summary by Qodo</h3>
Automatically downsize oversized image uploads
<code>✨ Enhancement</code> <code>🕐 20-40 Minutes</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<details>
<summary>AI Description</summary>
<dl>
<dd>
<br/>
><pre>
>• Sets initial client and API upload ceilings to 10 MB.
>• Repeatedly compresses oversized images before enforcing configured limits.
>• Supports percentage-based dimensions in the image optimization pipeline.
></pre>
</dd>
</dl>
</details>
<details>
<summary>Diagram</summary>
<dl>
<dd>
<br/>
```mermaid
graph TD
Client["Upload client"] --> Gate{"Within 10 MB?"}
Gate -- "No" --> Reject["Size alert"]
Gate -- "Yes" --> Controller["Uploads controller"] --> Oversized{"Oversized image?"}
Oversized -- "Yes" --> Optimizer["Image optimizer"] --> Store["Upload model"]
Oversized -- "No" --> Store
```
</dd>
</dl>
</details>
<details>
<summary>High-Level Assessment</summary>
<dl>
<dd>
<br/>
>The following are alternative approaches to this PR:
<details>
<summary><b>1. Configurable intake ceiling</b></summary>
<dl>
<dd>
- ➕ Lets administrators align intake limits with proxy and storage constraints
- ➕ Avoids duplicating a hard-coded 10 MB value across client and server
- ➖ Requires a new site setting and configuration migration
- ➖ Adds another upload limit administrators must understand
</dd>
</dl>
</details>
<details>
<summary><b>2. Adaptive single-pass resizing</b></summary>
<dl>
<dd>
- ➕ Could reduce repeated ImageMagick executions
- ➕ Can converge faster for substantially oversized files
- ➖ Encoded file size does not scale linearly with image dimensions
- ➖ Still requires a fallback when the estimated resize misses the target
</dd>
</dl>
</details>
>**Recommendation:** The bounded server-side downsizing loop is a pragmatic approach because it reuses the existing optimizer and caps processing attempts. Prefer deriving the 10 MB intake ceiling from a shared configurable setting, and preserve compatibility with existing numeric `downsize` callers while adding geometry-string support.
</dd>
</dl>
</details>
<details>
<summary> Files changed (3) <code> +20 / -12 </code> </summary>
<dl>
<dd>
<br/>
<details>
<summary>Enhancement (2) <code> +12 / -3 </code></summary>
<dl>
<dd>
<details>
<summary>utilities.js<code>Apply a fixed 10 MB client upload ceiling</code> <code>+2/-2</code></summary>
<br/>
>Apply a fixed 10 MB client upload ceiling
>
><pre>
>• Replaces type-specific site-setting limits with a 10 MB validation ceiling. HTTP 413 errors now report the same fixed limit.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/29/files#diff-4a1679f9b201c4c99aa3195bfb9af33e6113cab66f49a3d84d662aba6d9f4c39'>app/assets/javascripts/discourse/lib/utilities.js</a>
</details>
<details>
<summary>uploads_controller.rb<code>Downsize oversized images before upload creation</code> <code>+10/-1</code></summary>
<br/>
>Downsize oversized images before upload creation
>
><pre>
>• Allows API URL downloads up to 10 MB. Images exceeding 'max_image_size_kb' are downsized in-place by 80 percent up to five times before creating the upload.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/29/files#diff-2593933d96feff1e8f6ab5e1e25ac9f6f52fa33d894f41c3293978029a9bbe5d'>app/controllers/uploads_controller.rb</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Refactor (1) <code> +8 / -9 </code></summary>
<dl>
<dd>
<details>
<summary>optimized_image.rb<code>Accept prepared image geometry strings</code> <code>+8/-9</code></summary>
<br/>
>Accept prepared image geometry strings
>
><pre>
>• Refactors optimization to receive a complete dimensions string and adds a downsizing entry point for values such as '80%'. Numeric resize dimensions are converted to ImageMagick 'widthxheight' geometry before optimization.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/29/files#diff-62a6d4db51306a8a65581de079f8c59765211d67b2464a592f1b4416f3b96e95'>app/models/optimized_image.rb</a>
</details>
</dd>
</dl>
</details>
</dd>
</dl>
</details>