Skip to content

Renaming: v2.0 rewrite — fix batch failures, security vulnerability, add undo history - #25499

Closed
TurboCoder13 wants to merge 27 commits into
raycast:mainfrom
TurboCoder13:improve-renaming-extension
Closed

TurboCoder13 wants to merge 27 commits into
raycast:mainfrom
TurboCoder13:improve-renaming-extension

Conversation

@TurboCoder13

@TurboCoder13 TurboCoder13 commented Feb 16, 2026 •

Copy link
Copy Markdown
Contributor

🤖 Disclosure

This rewrite was developed with AI assistance (Claude Code, Codex and CodeRabbitAI), with my guidance on architecture, requirements, and testing. All code was reviewed and validated by me, including manual testing in Raycast.

Description

This PR is a complete rewrite of the Renaming extension, motivated by critical bugs and a security vulnerability in the original AppleScript-based approach.

Why the rewrite

1. Batch failures
The original implementation spawned a separate osascript process for each file rename via spawnSync(). In practice, this became unreliable — I noticed timeouts and partial completion starting around ~90 files, where some files were renamed while others were silently skipped, with no indication of which succeeded or failed and no way to undo. Switching to native fs.rename() eliminates the problem entirely.

2. Shell injection vulnerability
Filenames were interpolated directly into osascript commands with only " → \" escaping:

const escapedFilePath = file.replaceAll('"', '\\"');
await runAppleScript(`
  tell application "Finder"
    set theItem to POSIX file "${escapedFilePath}" as alias
    set name of theItem to "${escapedNewName}"
  end tell
`);

This is insufficient — filenames containing other shell metacharacters could inject arbitrary AppleScript commands. A targeted security fix was merged upstream (ad9f7d6), but this rewrite eliminates the entire attack surface by using Node.js fs.rename() directly.

3. No error recovery
The original had a single try/catch around the entire rename loop. A failure mid-batch left files in an inconsistent state with no per-file error tracking, no conflict detection, and no undo capability.

What changed

  • AppleScript → Node.js fs.rename() — eliminates process spawning overhead and shell injection entirely
  • Undo/History system — all operations tracked in LocalStorage, reversible with ⌘Z
  • Per-file error handling — each file renamed independently with individual success/failure tracking
  • Conflict detection — warns before creating duplicate filenames; refuses to overwrite
  • Results view — after each operation, shows exactly what succeeded, what failed, and why
  • Case transformation — 8 styles (UPPERCASE, lowercase, Title Case, camelCase, PascalCase, snake_case, kebab-case, Sentence case)
  • Regex support — find/replace with regex, including ReDoS safety validation
  • Presets — save and reuse rename configurations
  • Folder renaming — dedicated rename and replace sub-commands for folders
  • Clipboard rename — rename files from clipboard contents
  • AI Smart Rename — generate descriptive names from file metadata (Raycast Pro)
  • Test suite — 26 test files with 85% coverage via Vitest
  • Modular architecture — composable hooks, focused components, extracted utilities

Note on command structure

The original extension exposed 2 top-level commands (Rename File(s) and Replace File(s) Characters). This rewrite consolidates into a single hub command with 8 sub-commands accessible via a menu. Both original commands are preserved and enhanced within the hub. See my follow-up comment for more context on this decision.

Screencast

Screenshots in metadata/ folder.

Checklist

  • I read the extension guidelines
  • I read the documentation about publishing
  • I ran npm run build and tested the distribution build in Raycast
  • I checked that files in the assets folder are used by the extension
  • I checked that assets used in the README are outside the metadata folder

Add vitest test framework, update TypeScript to ES2023 with
noImplicitOverride, and add validate/typecheck/test scripts.
Define FileInfo, RenameOperation, NamingTemplate and other core types. Add enums for CaseStyle, SelectionMode, SortField, FileCategory, etc.
Structured logging with module-scoped loggers, custom error hierarchy
(FileNotFoundError, PermissionError, ConflictError, etc.), centralized
constants, filename validation, and regex safety checks.
Batch rename with conflict detection, file type categorization,
case transformation (8 styles), clipboard parsing, OS capability
detection, progress tracking, selection summary, and thumbnail
generation via Quick Look.
Template parser with variable resolution ({original}, {counter},
{date}, {exif.*}, {file.*}, {spotlight.*}), format specifiers,
transliteration, sorting, and built-in template defaults.
Extract image EXIF data (camera, dimensions, GPS, exposure settings), Spotlight metadata (audio, video, document properties), and file stats (size, dates) for use in template variables.
Type-specific AI prompts for images, videos, audio, documents, and
code files. Includes prompt builder, suggested name cleaning, and
metadata-aware context generation for Raycast AI.
Undo/redo history with LocalStorage persistence (last 10 operations),
and preset system for saving/loading rename configurations including
template presets.
Hooks for file selection (Finder integration), rename form logic,
AI suggestions, file metadata loading, and thumbnail caching.
All hooks include structured logging for error diagnostics.
Reusable components for file metadata detail, file selection form, rename form view, results view, template builder/preview, history detail view, and undo action panel.
Replace monolithic index.tsx with focused command modules: rename,
replace, clipboard-rename, ai-suggest, history, and presets. Remove
legacy replace.tsx and utils.tsx.
26 test files covering core library modules: file operations, template
system, metadata extraction, clipboard parsing, case transforms,
validation, history, presets, and more. Includes Raycast API/utils
mocks and test fixtures. 85% coverage thresholds configured.
Update README with v2.0 features, fix CHANGELOG to Keep a Changelog format, add LIMITATIONS.md, and update extension screenshots for the Raycast Store.
@raycastbot raycastbot added extension fix / improvement Label for PRs with extension's fix improvements extension: renaming Issues related to the renaming extension labels Feb 16, 2026
@TurboCoder13

TurboCoder13 commented Feb 16, 2026 •

Copy link
Copy Markdown
Contributor Author

A note on the single-command hub pattern

The original extension had 2 top-level commands. This rewrite adds significantly more functionality — the full set is now 8 sub-commands:

  1. Rename File(s)
  2. Rename Folder(s)
  3. Replace in File Names
  4. Replace in Folder Names
  5. Rename from Clipboard
  6. AI Smart Rename
  7. Rename History
  8. Presets

I chose to consolidate these into a single "Renaming" hub command rather than exposing all 8 as separate top-level commands, for two reasons:

  1. Clutter — 8 commands in the Raycast palette for a single extension feels excessive, especially since several are variations of the same operation (files vs folders)
  2. Discoverability — a hub makes the full feature set visible in one place, rather than requiring users to know each command exists

The trade-off is that users lose the ability to search/hotkey individual sub-commands directly, and the original Replace File(s) Characters command is no longer a top-level entry (though its functionality is fully preserved and enhanced as "Replace in File Names" within the hub).

I'd appreciate your guidance on the right approach here. Some options:

  • Current: Single hub command (cleanest palette, all features discoverable)
  • Hybrid: Expose the most-used commands as top-level (e.g., Rename File(s), Replace in File Names, Rename History) and keep the rest in the hub
  • Full separation: Expose all 8 as individual commands

Happy to adjust based on what you think works best for users and the Store! 🙇

@raycastbot

raycastbot commented Feb 16, 2026 •

Copy link
Copy Markdown
Collaborator

Thank you for your contribution! 🎉

🔔 @theodaguier @ridemountainpig you might want to have a look.

You can use this guide to learn how to check out the Pull Request locally in order to test it.

📋 Quick checkout commands
BRANCH="improve-renaming-extension"
FORK_URL="https://github.com/TurboCoder13/extensions.git"
EXTENSION_NAME="renaming"
REPO_NAME="extensions"

git clone -n --depth=1 --filter=tree:0 -b $BRANCH $FORK_URL
cd $REPO_NAME
git sparse-checkout set --no-cone "extensions/$EXTENSION_NAME"
git checkout
cd "extensions/$EXTENSION_NAME"
npm install && npm run dev

We're currently experiencing a high volume of incoming requests. As a result, the initial review may take up to 10-15 business days.

@greptile-apps

greptile-apps Bot commented Feb 16, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This is a substantial v2.0 rewrite of the Renaming extension, replacing the AppleScript-based approach with native Node.js fs.rename(), adding undo history, per-file error handling, conflict detection, regex support, case transformation, presets, and AI-assisted renaming. Previous review concerns (shell injection in thumbnails, EXIF for non-images, stale regex state, duplicate kMDItemAuthors, double-dot filenames) are all addressed.

  • Undo broken for case-change renames: undoLastRename() and undoToPoint() in history.ts call fileExists(op.oldPath) without accounting for macOS's case-insensitive filesystem. After renaming photo.jpg → PHOTO.JPG, the undo guard sees photo.jpg as already existing (it resolves to the same inode as PHOTO.JPG) and aborts with "photo.jpg already exists" — making every case-transformation operation un-undoable. The fix is to skip the guard when op.oldPath.toLowerCase() === op.newPath.toLowerCase().

Confidence Score: 4/5

Safe to merge after fixing the case-insensitive undo guard in history.ts; all other previously flagged issues are resolved.

One P1 defect remains: the undo system silently fails for every case-transformation rename on macOS due to the case-insensitive filesystem not being accounted for in the fileExists guard. Since case transformation is a headline feature of this rewrite, leaving it un-undoable is a present, reproducible bug. All prior review findings are addressed.

extensions/renaming/src/lib/history.ts — both undoLastRename (line 88) and undoToPoint (line 168) need the case-insensitive guard fix.

Important Files Changed

Filename Overview
extensions/renaming/src/lib/history.ts Undo/history system: contains a P1 bug where fileExists(op.oldPath) falsely blocks undo of case-change renames on macOS case-insensitive FS, in both undoLastRename and undoToPoint.
extensions/renaming/src/lib/files.ts Core rename engine: well-implemented with path traversal checks, case-insensitive conflict detection, two-phase temp-rename for within-batch conflicts, and depth-sorted directory handling.
extensions/renaming/src/commands/replace.tsx Find-and-replace command: synchronous regex validation before execution avoids stale-state issues from prior review; conflict detection and per-file error handling present.
extensions/renaming/src/lib/thumbnails.ts Thumbnail generation via Quick Look: uses execFile (arg array) to eliminate shell injection; fs/promises rename replaces the previous mv shell invocation.
extensions/renaming/src/lib/validation.ts Filename validation: covers empty names, / and null characters, reserved names, UTF-8 byte length, and dot-only names; clean implementation.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/renaming/src/lib/history.ts
Line: 88-91

Comment:
**Undo blocked for case-change renames on macOS**

`fileExists(op.oldPath)` uses `fs.access()`, which on macOS's case-insensitive APFS/HFS+ filesystem treats `photo.jpg` and `PHOTO.JPG` as the same path. After renaming `photo.jpg` → `PHOTO.JPG`, undoing hits this guard: `fileExists("photo.jpg")` returns `true` (because `PHOTO.JPG` is the same inode), so the undo aborts with "photo.jpg already exists" — even though the file you're trying to restore IS that file.

Since case transformation (lowercase → UPPERCASE, etc.) is a primary feature of this rewrite, every case-change batch will be un-undoable.

The `files.ts` module already has the helper needed here. Skip the guard when `oldPath` and `newPath` are the same on the current filesystem:

```ts
// Check if original path is free
// Skip when oldPath and newPath are the same file (case-only rename on case-insensitive FS)
const isCaseOnlyRename = op.oldPath.toLowerCase() === op.newPath.toLowerCase();
if (!isCaseOnlyRename && (await fileExists(op.oldPath))) {
  errors.push(`${basename(op.oldPath)} already exists`);
  failedOps.push(op);
  continue;
}
```

The same pattern applies in `undoToPoint()` at line 168.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: extensions/renaming/src/lib/history.ts
Line: 168-171

Comment:
**Same case-insensitive undo bug in `undoToPoint`**

Same issue as line 88: `fileExists(op.oldPath)` incorrectly returns `true` for case-change renames on macOS, blocking `undoToPoint` from reverting any case-transformation operation. Apply the same `isCaseOnlyRename` guard here.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (4): Last reviewed commit: "fix: address CodeRabbit review findings ..." | Re-trigger Greptile

@greptile-apps greptile-apps 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.

115 files reviewed, 5 comments

Edit Code Review Agent Settings | Greptile

@TurboCoder13
TurboCoder13 marked this pull request as draft February 16, 2026 10:58
…and wasteful EXIF reads

- Fix double-dot filenames in ai-suggest, clipboard, and template commands
  where `.${file.extension}` produced `name..jpg` since extname() already
  includes the leading dot
- Fix inline sample FileInfo using `extension: "jpg"` instead of `".jpg"`
- Replace shell `mv` command in thumbnails.ts with fs.rename() to eliminate
  shell injection via filenames containing single quotes
- Gate EXIF metadata extraction to image files only, avoiding reading entire
  non-image files into memory
Address division-by-zero in shutter speed, array bounds in EXIF,
DateTimeOriginal regex validation, negative bytes guard, units overflow
clamping, Promise.allSettled for resilient extraction, and artist/author
space-preserving parsing in Spotlight metadata.
Normalize toTitleCase to lowercase remainder, fix duration :60 bug in
audio/video prompts, reorder detectFormatType to check time before date,
handle negative numbers in formatNumber, guard formatSize against
negative/non-finite bytes, and accept 0 as valid random length.
Use UTF-8 byte length for filename validation, add backslash to invalid
chars, fix RFC 4180 CSV parsing, sanitize thumbnail size parameter,
re-sanitize after space replacement in transliterate, escape regex
special chars in template parser, use path.dirname for directory
extraction, add platform-aware path handling, and guard null extension.
Wrap undo/delete/save operations in try/catch across commands and
components, add error state in useSelectedFiles, fix isLoading on null
paths, correct fallback group size, remove unused historyDescription
field, fix pluralization, add truncation indicator for directory groups,
accept 0 as counter start, fix duplicate keyboard shortcuts, and
preserve history on complete undo failure.
Update Preserve Name Mode terminology in README, clarify undo history
and regex limitation descriptions, and remove vitest/globals from
tsconfig types (already set in vitest.config.ts).
Use path.extname for hidden file extension extraction in template
preview, make thumbnail test assertions explicit instead of conditional,
and always use extname with fallback in isPreviewableImage.
@TurboCoder13

Copy link
Copy Markdown
Contributor Author

@greptile can you do a fresh review please?

@greptile-apps greptile-apps 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.

116 files reviewed, 2 comments

Edit Code Review Agent Settings | Greptile

kMDItemAuthors was read twice — once for artist (line 178) and again
for author (line 206), making both fields always identical. Author now
reads from kMDItemCreator first, falling back to kMDItemAuthors.
Re-validate the pattern inside the submit handler instead of relying
on stale useEffect-based regexError state, preventing silent failures
when the user types quickly and submits before state updates.
@TurboCoder13

Copy link
Copy Markdown
Contributor Author

File Breakdown

Category Count Description
Implementation 66 Source code (commands, components, hooks, lib, types)
Tests 31 26 test files + 5 helpers (mocks, fixtures, setup)
Images 10 1 extension icon + 9 screenshots
Config 8 package.json, tsconfig, eslint, vitest, prettier, gitignore, raycast-env.d.ts, package-lock
Docs 3 README, CHANGELOG, LIMITATIONS
Total 118

Distribution

Implementation ██████████████████████████████████████  55.9%
Tests          ██████████████████                      26.3%
Images         ██████                                   8.5%
Config         █████                                    6.8%
Docs           ██                                       2.5%

- Return fallback string for empty input in buildAutoSummary
- Use consistent "exif." prefix in getRequiredDateSource
- Skip directories in groupFilesByExtension
- Pad with "unnamed" instead of empty string in parseBatchAIResponse
- Clear stale UI state after successful undo in useRenameOperations
- Add error handling to handleClearHistory and loadHistory in history command
- Always reload history after undoToPoint for partial undo handling
- Use SortDirection.DESC enum instead of string literal in template builder
- Remove inconsistent readonly from ExtensionGroupConfig.extension
- Include file mtime in thumbnail cache key for staleness detection
- Guard safeSize against NaN with Number.isFinite fallback
- Update tests to match new behavior
@TurboCoder13
TurboCoder13 force-pushed the improve-renaming-extension branch from dc13666 to 29a4d5e Compare February 16, 2026 19:16
@TurboCoder13
TurboCoder13 marked this pull request as ready for review February 16, 2026 19:19
@TurboCoder13

Copy link
Copy Markdown
Contributor Author

@greptileai can you please do full review?

@pernielsentikaer

Copy link
Copy Markdown
Contributor

Thanks for the update @TurboCoder13

@theodaguier do you want to check this?

@pernielsentikaer

Copy link
Copy Markdown
Contributor

Giving @theodaguier a few days to review 🙂

@pernielsentikaer
pernielsentikaer marked this pull request as draft February 23, 2026 12:16
@raycastbot

Copy link
Copy Markdown
Collaborator

This pull request has been automatically marked as stale because it did not have any recent activity.

It will be closed if no further activity occurs in the next 7 days to keep our backlog clean 😊

@raycastbot raycastbot added the status: stalled Stalled due inactivity label Mar 9, 2026
@raycastbot

Copy link
Copy Markdown
Collaborator

This pull request has been automatically closed due to inactivity.

Feel free to comment in the thread when you're ready to continue working on it 🙂

You can also catch us in Slack if you want to discuss this.

@raycastbot raycastbot closed this Mar 16, 2026
@TurboCoder13

Copy link
Copy Markdown
Contributor Author

Hey @pernielsentikaer 👋

I just got back from vacation, so I unfortunately didn't get to look at this before it went stale and got closed 😅

May I re-open the PR or perhaps do something else for these changes? 🤞

@pernielsentikaer

Copy link
Copy Markdown
Contributor

Hey @TurboCoder13, thanks for putting so much work into this — the security fix (AppleScript → fs.rename) and the overall improvements are great.

A few things we'd need before we can merge this:

  • It would be better to keep the existing commands since users lose their hotkeys, aliases, and ranking. The current Rename File(s) and Replace File(s) Characters commands need to stay as top-level entries. You can add new commands alongside them, but the existing ones need to keep their current names and entry points. You might still be able to add the HUB command as a new one which gathers them.

  • Consider splitting this PR up. This is a huge PR (118 files) which makes it really hard to review properly. Ideally I'd love to see the core security fix (AppleScript → fs.rename) as one PR, and then the new features (AI rename, presets, clipboard rename, folder rename, history) as follow-up PRs. That way we can get the important fix in without the risk of landing everything at once.

  • Trim the dependencies if possible. safe-regex and exifreader make sense, but transliteration and mime-types feel like they could be avoided — transliteration is only used for one case transform and mime-types could be replaced with file extension checks.

The foundation is solid and the direction is good — just need to make it more incremental so we can land it safely.

Happy to help if you have questions!

@pernielsentikaer pernielsentikaer self-assigned this Mar 24, 2026
@TurboCoder13

Copy link
Copy Markdown
Contributor Author

@pernielsentikaer thanks so much! I appreciate the response and I will make work of your advice 🙂

Comment on lines +88 to +91
if (await fileExists(op.oldPath)) {
errors.push(`${basename(op.oldPath)} already exists`);
failedOps.push(op);
continue;

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.

P1 Undo blocked for case-change renames on macOS

fileExists(op.oldPath) uses fs.access(), which on macOS's case-insensitive APFS/HFS+ filesystem treats photo.jpg and PHOTO.JPG as the same path. After renaming photo.jpg → PHOTO.JPG, undoing hits this guard: fileExists("photo.jpg") returns true (because PHOTO.JPG is the same inode), so the undo aborts with "photo.jpg already exists" — even though the file you're trying to restore IS that file.

Since case transformation (lowercase → UPPERCASE, etc.) is a primary feature of this rewrite, every case-change batch will be un-undoable.

The files.ts module already has the helper needed here. Skip the guard when oldPath and newPath are the same on the current filesystem:

// Check if original path is free
// Skip when oldPath and newPath are the same file (case-only rename on case-insensitive FS)
const isCaseOnlyRename = op.oldPath.toLowerCase() === op.newPath.toLowerCase();
if (!isCaseOnlyRename && (await fileExists(op.oldPath))) {
  errors.push(`${basename(op.oldPath)} already exists`);
  failedOps.push(op);
  continue;
}

The same pattern applies in undoToPoint() at line 168.

Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/renaming/src/lib/history.ts
Line: 88-91

Comment:
**Undo blocked for case-change renames on macOS**

`fileExists(op.oldPath)` uses `fs.access()`, which on macOS's case-insensitive APFS/HFS+ filesystem treats `photo.jpg` and `PHOTO.JPG` as the same path. After renaming `photo.jpg` → `PHOTO.JPG`, undoing hits this guard: `fileExists("photo.jpg")` returns `true` (because `PHOTO.JPG` is the same inode), so the undo aborts with "photo.jpg already exists" — even though the file you're trying to restore IS that file.

Since case transformation (lowercase → UPPERCASE, etc.) is a primary feature of this rewrite, every case-change batch will be un-undoable.

The `files.ts` module already has the helper needed here. Skip the guard when `oldPath` and `newPath` are the same on the current filesystem:

```ts
// Check if original path is free
// Skip when oldPath and newPath are the same file (case-only rename on case-insensitive FS)
const isCaseOnlyRename = op.oldPath.toLowerCase() === op.newPath.toLowerCase();
if (!isCaseOnlyRename && (await fileExists(op.oldPath))) {
  errors.push(`${basename(op.oldPath)} already exists`);
  failedOps.push(op);
  continue;
}
```

The same pattern applies in `undoToPoint()` at line 168.

How can I resolve this? If you propose a fix, please make it concise.

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

Labels

extension fix / improvement Label for PRs with extension's fix improvements extension: renaming Issues related to the renaming extension OP is contributor The OP of the PR is a contributor of the extension platform: macOS status: stalled Stalled due inactivity

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants