Repository navigation
feat: open markdown files from the OS file manager - #11325
java-jaydev wants to merge 25 commits into
Conversation
Greptile SummaryThis PR adds OS-level markdown file association so Orca appears in "Open With" lists and can receive
Confidence Score: 5/5Safe to merge. The feature is well-isolated, all runtime-sensitive creation calls are pinned to the local host, and the ownership-tracking and serialization mechanisms are correctly implemented and tested. The implementation is thorough, self-consistent, and well-tested across all three platforms. The multi-sender ownership bug, remote-host routing gap, startup error isolation, and type-drift issue described in the AI review report are all addressed in the submitted diff. The one asymmetry found — filterExistingFiles applied to buffered paths but not to live-push paths — is low practical impact and is flagged for awareness. Files Needing Attention: src/main/ipc/os-file-open.ts — the live-push deliver callback skips the stat+isFile existence check that buffered paths receive.
|
| Filename | Overview |
|---|---|
| src/main/startup/os-file-open-requests.ts | New module: queue for buffering/delivering OS-opened markdown paths, with platform-specific registration (darwin open-file vs win32/linux argv + second-instance). Shape and extension validation in enqueue; stat-based existence check only on the startup drain batch. |
| src/main/ipc/os-file-open.ts | New IPC handler: takePending drains the buffered queue (with filterExistingFiles), then flips the deliver slot so later arrivals push directly to the renderer. Ownership tracking prevents a stale sender's teardown from clearing a newer owner's delivery slot. |
| src/renderer/src/lib/open-os-requested-file.ts | Core renderer logic: serializes concurrent opens via a module-level promise chain, reuses the deepest-matching local workspace or creates a folder workspace pinned to the local runtime, then opens the file tab. Error paths surface through toast. |
| src/renderer/src/lib/os-requested-file-project-group.ts | Project group resolution: path-based match (parentPath contains filePath) wins; name-based fallback (oldest local group with matching name) recovers groups created by this feature that have parentPath:null. Both legs restrict to locally-owned groups. |
| src/renderer/src/hooks/use-os-requested-file-opening.ts | Startup pull and live-push subscription; isCancelled check added at each loop iteration; errors caught and toasted per-file so startup hydration is not affected. |
| src/preload/index.ts | Adds osFileOpen bridge (takePending invoke + onOpened on/off) with satisfies PreloadApi['osFileOpen'] to catch type drift at compile time. |
| config/electron-builder.config.cjs | Adds a single fileAssociations entry for .md/.markdown with rank:Alternate, covering all three packagers without claiming the default handler. |
| src/main/ipc/register-core-handlers.ts | Threads OsFileOpenRequestQueue through as a required parameter and calls registerOsFileOpenHandlers; enforced by a new test. |
Sequence Diagram
sequenceDiagram
participant OS as OS (LaunchServices / Shell)
participant Main as Main Process
participant Queue as OsFileOpenRequestQueue
participant IPC as IPC Handler
participant Renderer as Renderer (App.tsx)
participant Logic as openOsRequestedFile
OS->>Main: open-file event (macOS) / argv (Win/Linux)
Main->>Queue: enqueue(filePath)
Note over Queue: isMarkdownFilePath check (shape + extension)
alt Renderer not yet ready
Queue->>Queue: buffer in pending[]
end
Renderer->>IPC: takePending() [after session hydration]
IPC->>Queue: setDeliver(sendFn)
IPC->>Queue: drain()
Queue-->>IPC: buffered paths[]
IPC->>IPC: filterExistingFiles(paths) [stat + isFile check]
IPC-->>Renderer: filtered paths[]
loop each pending path
Renderer->>Logic: openOsRequestedFile(filePath)
Logic->>Logic: findWorkspaceForFilePath (existing?)
alt No existing workspace
Logic->>Logic: resolveProjectGroupId
Logic->>Logic: createFolderWorkspace (local runtime)
end
Logic->>Renderer: activateAndRevealWorktree + openFile
end
Note over OS,Renderer: After renderer is live (second file open)
OS->>Main: open-file / second-instance
Main->>Queue: enqueue(filePath)
Queue->>IPC: deliver(filePath) [isMarkdownFilePath only, no stat check]
IPC->>Renderer: osFileOpen:opened event
Renderer->>Logic: openOsRequestedFile(filePath)
Reviews (3): Last reviewed commit: "docs(renderer): note why createProjectGr..." | Re-trigger Greptile
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between ff0db3b83b5cada3cf2059151fbe131aacf0874c and bc91233. 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughThe change registers Orca as an alternate Markdown handler, captures Markdown file-open requests from platform startup and subsequent launches, and delivers them through main-process IPC and the preload API. The renderer consumes pending and pushed requests, resolves or creates local project groups and folder workspaces, activates worktrees, and opens files in edit mode. Workspace, project-group, queue, IPC, renderer, configuration, localization, and concurrency behavior receives test coverage. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
config/electron-builder.config.cjs (1)
286-294: 🎯 Functional Correctness | 🔵 Trivial | 🏗️ Heavy liftMake Markdown file associations platform-specific
This common entry can fail on Windows:
nsis.perMachineis not set, and Electron-builder NSIS ignores file associations without it. On Linux,fileAssociations.extis not enough for AppImage/deb; add Linux desktop/mime registration for bothmdandmarkdownif those targets need them.Source: MCP tools
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: be69b4c4-e583-4109-ad97-67d95c5ba8f1
📥 Commits
Reviewing files that changed from the base of the PR and between e549dd3 and 6928dcb041a569e30e502d406e0d9aeea66fdc5f.
📒 Files selected for processing (27)
config/electron-builder.config.cjsconfig/scripts/electron-builder-config.test.mjssrc/main/index.tssrc/main/ipc/os-file-open.test.tssrc/main/ipc/os-file-open.tssrc/main/ipc/register-core-handlers.test.tssrc/main/ipc/register-core-handlers.tssrc/main/startup/os-file-open-requests.test.tssrc/main/startup/os-file-open-requests.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/App.tsxsrc/renderer/src/hooks/use-os-requested-file-opening-push-subscription.test.tssrc/renderer/src/hooks/use-os-requested-file-opening.test.tssrc/renderer/src/hooks/use-os-requested-file-opening.tssrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/i18n/locales/es.jsonsrc/renderer/src/i18n/locales/ja.jsonsrc/renderer/src/i18n/locales/ko.jsonsrc/renderer/src/i18n/locales/zh.jsonsrc/renderer/src/lib/open-os-requested-file.test.tssrc/renderer/src/lib/open-os-requested-file.tssrc/renderer/src/lib/os-requested-file-project-group.test.tssrc/renderer/src/lib/os-requested-file-project-group.tssrc/renderer/src/lib/os-requested-file-workspace.test.tssrc/renderer/src/lib/os-requested-file-workspace.tssrc/renderer/src/store/slices/repos.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/lib/os-requested-file-workspace-candidates.test.ts (1)
17-31: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winCover runtime ownership independently from
hostId.This fixture only sets
hostId: 'runtime:env-1'; it never setsruntimeOwnerEnvironmentId, which is also part of the production ownership model. Add a case with a local host and a remote runtime owner so regressions in runtime-owner filtering cannot pass the suite.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3879fdb5-3c4e-4c21-9d32-783702d844b8
📥 Commits
Reviewing files that changed from the base of the PR and between 6928dcb041a569e30e502d406e0d9aeea66fdc5f and ff0db3b83b5cada3cf2059151fbe131aacf0874c.
📒 Files selected for processing (5)
src/renderer/src/hooks/use-os-requested-file-opening.test.tssrc/renderer/src/hooks/use-os-requested-file-opening.tssrc/renderer/src/lib/open-os-requested-file.tssrc/renderer/src/lib/os-requested-file-workspace-candidates.test.tssrc/renderer/src/lib/os-requested-file-workspace-candidates.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/renderer/src/hooks/use-os-requested-file-opening.ts
- src/renderer/src/lib/open-os-requested-file.ts
The second-instance event handler receives (event, argv) from Electron. Update acquireSingleInstanceLock to extract argv and pass it to the callback, making it available for Task 5 (markdown queue integration). Task 3 in the open-markdown-from-finder feature.
- Replace mkdir return value assignment with upfront path computation - Add OsFileOpenApp type for purpose-built app interface - Properly type createFakeApp() to satisfy OsFileOpenApp - Mark type-only imports with type specifier
OS file-open request harvesting now subscribes to second-instance directly in registerOsFileOpenRequests instead of routing through the lock callback, so acquireSingleInstanceLock no longer needs argv. This reverts commit 18b94e1712c45e03a952f1625b999d8640f158d1.
registerOsFileOpenRequests only read argv from the first launch, so a markdown file opened while Orca was already running (Windows/Linux relay this as second-instance, not open-file) was silently dropped. Subscribe non-darwin platforms to second-instance and enqueue markdown paths from its argv alongside the existing first-launch handling.
Create the request queue and subscribe it to OS file-open sources at module load, after configureDevUserDataPath and before the single-instance-lock block, so the very first open-file event on macOS is never missed. Thread the queue through registerCoreHandlers so its IPC handlers are exposed to the renderer. The single-instance-lock callback is left untouched — second-instance argv harvesting now lives entirely in registerOsFileOpenRequests, alongside the module that already owns every other OS file-open source.
The queue is never actually absent in production, but the parameter was declared optional and guarded, so no test exercised the branch that registers its IPC handlers — a dropped call site would have compiled and passed the whole suite. Move it to a required parameter right after the defaulted mainWindowWebContentsId (before the first optional parameter, which TypeScript disallows following a required one), drop the dead guard, and cover the registration with a test.
…ection Root paths in different Unicode forms (NFD vs NFC) can have different raw lengths despite denoting the same tree. Comparing relative-path lengths instead makes the deepest-match logic immune to encoding differences, since relative paths are suffixes of the same input file path. Added tests demonstrating the fix: test 7 shows the old comparison fails on NFD vs NFC roots, and test 8 documents the empty-relative-path case.
…kdown file Group/workspace creation and lookup for an OS-handed path must never follow the currently focused runtime (e.g. an SSH session) — the OS only ever hands over a local path. createFolderWorkspace and the new createProjectGroup options both force runtimeEnvironmentId: null, and the existing-group lookup is restricted to locally-owned groups (no connectionId, no non-local executionHostId).
Pull pending OS-opened files after session hydration (worktreesByRepo/ folderWorkspaces must be populated for workspace matching) and subscribe to files opened while Orca is already running. Wiring lives in a dedicated hook since App.tsx is already over its max-lines budget. Serialize openOsRequestedFile with a module-level promise chain so two files from the same not-yet-created folder can't each create a duplicate workspace when opened concurrently.
…tion catch A failed openOsRequestedFile inside the startup pull loop propagated into App.tsx's hydration try/catch, which mistook it for a session-restore failure and disabled session persistence for the rest of the run. Catch and toast per path instead, so one bad file can't sink hydration and can't block the remaining pending files from opening.
… dropping it The push subscription fired-and-forgot openOsRequestedFile, so the same createProjectGroup rejection the startup pull could hit became an unhandled promise rejection there instead — no warning, no toast. Both entry points now route through one shared function that catches, warns, and toasts, so they can't drift apart again.
Declares a top-level fileAssociations entry so the OS offers Orca in the "Open With" list for .md/.markdown files (rank: Alternate, so it never claims the default handler), sourcing macOS CFBundleDocumentTypes, the Windows installer registry, and the Linux .desktop MimeType from one declaration.
…reating another createProjectGroup always sets parentPath: null, so the path-based lookup could never find a group this flow created itself. Every time the folder-workspace lookup missed (an orphaned group, a user-deleted workspace), a new identically-named group was added, forever. Add a name-based fallback restricted to locally-owned groups, using the same host-provenance check as the path-based lookup. When several local groups share the name, pick the oldest by createdAt.
isCancelled was only checked once before the loop started, so a cancellation arriving mid-batch (e.g. unmount during a slow createFolderWorkspace) still let every remaining pending path activate a workspace in a torn-down context. Check before each iteration instead.
…nership collectWorkspaceCandidates matched purely on path containment across every worktree and folder workspace, including remote/runtime-owned ones. A remote workspace whose path string happened to contain the local file path could be adopted for a guaranteed-local OS-opened file, then rendered with runtimeEnvironmentId: null — the same defect class already fixed for project group reuse, just on the workspace side. Filter candidates to locally-owned ones (via getExecutionHostIdForWorktree, which also covers folder-workspace ownership) before matching.
ff0db3b to
bc91233
Compare
|
Rebased onto latest Full suite is green locally against the new base (43,803 passing). One pre-existing failure, As a first-time contributor the workflows are still sitting in |
|
Superseded by #17906, which shipped this feature — thank you, and you're credited as a co-author on the merged commit. Closing this in favour of the floating-workspace design, as you yourself proposed in the issue. Flagging the overlap unprompted and saying plainly which approach was the better fit was genuinely useful — it saved a maintainer from reconstructing that comparison from scratch, and it's the reason #10173's design won without a debate. Three things from your PR made it into what shipped:
Your multi-renderer delivery finding also turned out to be the right instinct, from a different angle: review of #17906 caught that pushing to a window whose renderer hasn't attached its listener yet is dropped by Electron silently, so the queue gets consumed into a void. Fixed by making the renderer's own pull the proof its listener is live. Thanks for the thorough work and for the honest triage in the issue. |
Summary
Orca now appears in the OS "Open With" list for markdown files, and opening a
.mdthat way loads it in an editor tab — no project setup required first.Today Orca declares no document types, so a markdown file on the desktop or in
~/Downloadscannot be handed to it at all. This adds the association and the plumbing behind it:fileAssociationsentry covering macOS (CFBundleDocumentTypes), Windows (installer registry) and Linux (.desktopMimeType).rank: Alternate, so Orca joins the list without taking over anyone's default markdown editor.open-fileevent and fromargv/second-instanceon Windows and Linux, buffering them until the renderer is listening.The workspace step exists because Orca's model has no workspace-less buffer — even an untitled markdown file is written into a workspace (
createUntitledMarkdownFile), andAGENTS.mdtreats folder workspaces as a first-class peer of git worktrees. Rather than introduce a new "file with no workspace" concept, an OS-opened file gets the same kind of folder workspace that "Add Folder as Project" creates. The visible cost is one project group plus one workspace the first time you open a file from a given folder; every later file from that folder reuses them.Screenshots
Finder's "Open With" list for a
.mdfile — Orca is listed, andXcode.app (default)is still the default handler, which is whatrank: Alternateis for.The file opened in Orca — no project was registered beforehand; the
orca-open-testworkspace was created automatically from the file's parent folder.Testing
pnpm lintpnpm typecheckpnpm test— 39,573 passed / 62 skippedpnpm build(pnpm build:mac, both arm64 and x64 slices)New tests, by area:
os-file-open-requestsfilterExistingFilesagainst real fixtures (existing file, directory, missing path), per-platform registration — darwin subscribes toopen-fileonly, win32/linux read argv and subscribe tosecond-instanceos-file-openIPCos-requested-file-workspaceos-requested-file-project-groupconnectionId/ remoteexecutionHostId),parentPath: nullskipped, deterministic oldest-first tie-breakopen-os-requested-fileuse-os-requested-file-openingregister-core-handlerselectron-builder-configrank: AlternateManual verification on macOS, in two stages.
Dev build — opened
~/Downloads/orca-open-test/lf-note.mdwith no project registered: tab opened, folder workspace created, editing showed the dirty indicator,Cmd+Ssaved, closing with unsaved changes warned. A second file from the same folder reused the workspace instead of creating another. A CRLF file round-tripped byte-for-byte (0d 0apreserved, UTF-8 intact).Packaged build — after
lsregister,Orca.appappeared in the LaunchServices list for.md(14 → 16 entries) while the default handler stayed unchanged, confirmingrank: Alternatebehaves. Opening a file against a completely fresh user-data profile created the workspace from scratch. A path delivered while first-run onboarding was still in progress was buffered and opened once the renderer finished hydrating.Windows and Linux are covered by the automated tests only — see Notes.
Manual verification also caught a defect the automated suite missed. Opening a file from the same folder in a later session created a second, identically-named project group:
createProjectGroupproduces a group withparentPath: null, and the reuse lookup only matched groups whoseparentPathcontained the file — so a group this feature created could never be rediscovered, and groups accumulated. Fixed by adding a name-based fallback that carries the same host-provenance restriction as the path-based one, with the oldest group winning when several match. The fix is covered by tests verified through mutation testing.AI Review Report
Each task was implemented and then reviewed by a separate agent that read the diff against the task's requirements and ran the gates itself rather than trusting the implementer's report. Reviewers reproduced their own claims adversarially — reverting a fix and confirming the relevant test actually fails. Seven of ten tasks came back with changes required. The substantive ones:
createProjectGroupandcreateFolderWorkspacestill routed through the active runtime, so a user focused on a remote SSH environment would have had the group and workspace created on the wrong host for a guaranteed-local path — and a remote group with a coincidentally matchingparentPathcould be reused. Fixed by forcing the local host on both creation calls and restricting group reuse to locally-owned groups (reusinggetProjectGroupExecutionHostIdForRowsrather than a new comparison). This required adding an optional route-options parameter tocreateProjectGroup, mirroring the shapecreateFolderWorkspacealready had; existing call sites are unaffected and their tests still pass.App.tsx's hydrationtry, whosecatchtreats any throw as "session restore failed" — disabling session persistence and showing a permanent toast. One transient failure opening a file would have produced that false alarm. Now isolated per path, with the same reporting shared by the push subscription so the two entry points cannot drift.api-types.tsandindex.tscould diverge with a green typecheck;satisfiesnow binds them, verified by injecting drift and watching the check fail. Separately,registerCoreHandlers's new parameter had been made optional on a mistaken reading of TS1016, which left the registration path with zero test coverage — it is now required, with a test that fails if the call is dropped.Cross-platform: platform-dependent behavior sits behind injected
platformchecks that the tests drive for darwin, win32 and linux; the singlefileAssociationsentry feeds all three packagers (verified againstapp-builder-lib's macOS, NSIS and Linux code paths). No shortcuts or shortcut labels are involved. SSH/remote: covered above — OS-handed paths are always local and are now forced onto the local host at every step. Agent, integration and git-provider behavior: untouched. Performance: one extra IPC round-trip during renderer startup, and a singlestatper pending path. UI quality: no new components; failures surface through the existing toast pattern, and the three new strings went through the localization codemod with catalog parity verified.Security Audit
argv. They are treated as untrusted: absolute-path shape check, extension allow-list (.md/.markdown), and an existence +isFile()check before anything is handed to the renderer. Directories and missing paths are dropped.open -b <bundleId>was dropped, so there is no execution surface at all.osFileOpen:takePendingis renderer→main with no arguments;osFileOpen:openedis a one-way main→renderer notification. The renderer cannot inject an arbitrary path into main through either, so there is no privilege escalation path.Notes
second-instancepaths are covered by unit tests that drive all three platforms, and the singlefileAssociationsentry is what electron-builder feeds to the NSIS and Linux packagers, but I only had macOS hardware. Worth a check by someone with those platforms before merge.public.folder; this PR does not. macOS would be cheap — I confirmed from a real packaged build thatfileAssociations-generatedCFBundleDocumentTypesmerges withmac.extendInforather than replacing it — but Windows has no folder equivalent short ofDirectory\shellregistry work in the installer, and that felt like a separate topic. Happy to follow up.second-instancelistener is registered before the single-instance lock's. If the file-path listener ever threw,requestDesktopActivation()would not run — the class of symptom fix(macos): avoid scene deadlock on app reactivation #11055 guards against. The listener only runs a regex,extname, and a guardedsend, so I left it rather than adding defensive code, but the ordering is worth knowing.second-instanceargv was first plumbed through the single-instance lock callback; that turned out to collide with the source-text guard inserve-desktop-activation-wiring.test.tsleft by fix(macos): avoid scene deadlock on app reactivation #11055. Rather than weaken that guard, the OS-file-open module now subscribes tosecond-instanceitself, and the lock callback andrequestDesktopActivationare untouched. The widening was reverted so no unused signature ships.docs/preload-typecheck-hole.mdis referenced fromCONTRIBUTING.mdbut does not exist in the repo. Not touched here, just noting it.X: @lee_jinkyu71869