Repository navigation
feat(desktop): watch workspace files for external changes + save-conflict guard (#805) - #837
Conversation
…lict guard (#805) Grida Desktop treats the agent as a first-class concurrent writer, but the workbench had no awareness of changes made to workspace files outside the open editor (the agent's own writes, a `git checkout`, another editor). This implements the VSCode model end-to-end: non-dirty editors auto-reload, dirty editors defer to a save-time conflict guard, and the file tree refreshes surgically. Save-conflict guard (transport-agnostic — protects web AND desktop): - workspaces.writeFile takes an optional `expected_mtime` precondition; a stale token is rejected with 409 `modified-since` (carrying the current mtime) instead of silently clobbering an external change. Omitting it keeps last-writer-wins, so agent writes / first-time creates are unaffected. - Plumbed as a first-class optional param through fs → http route → transport → bridge contract → preload → editor client. `isWriteConflict` detects the rejection tolerantly across the contextBridge (which strips custom Error props — keys off the surviving message string). OS watcher (desktop-only, behind additive cap `native.workspace_watch`): - New main-process host on `@parcel/watcher` (the recursive per-OS backend VSCode uses), mirroring terminal-host.ts: one OS watch per workspace root, ref-counted across windows/panes, ~75ms coalesced batches, ignore globs pushed to the native backend, killed on window close / app quit. - Reached only through `guarded()` IPC; the watch root is resolved host-side from the sidecar registry (the renderer only names a workspace id, never a raw path). Subscription ids are preload-minted before the watch starts so no early event can race. See GRIDA-SEC-004. - Native-module packaging: dependencies + vite external + asar.unpack glob + pnpm allowBuilds:false (rely on prebuilds), mirroring node-pty. Renderer wiring: - WorkspaceChangesProvider holds one subscription per workspace; consumers attach via useWorkspaceChanges. The open SVG editor reloads-when-clean / defers-when-dirty; the file tree reloads the affected parent dirs. - The web daemon bridge stubs the watch methods (caps.workspace_watch:false) so the UI falls back to pull-refresh on non-Electron hosts. Tests: workspaces.fs conflict-guard (last-writer-wins, matching/stale mtime, deleted-on-disk) and desktop watcher-host (helpers, ref-count registry, GRIDA-SEC-004 guarded() anti-drift check). Closes #805
|
The latest updates on your projects. Learn more about Vercel for GitHub.
6 Skipped Deployments
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (5)
🚧 Files skipped from review as they are similar to previous changes (4)
WalkthroughAdds end-to-end workspace file watching and write conflict detection. ChangesWorkspace File Watching and Optimistic-Concurrency Writes
Sequence Diagram(s)sequenceDiagram
participant Renderer as Renderer (SVG Editor)
participant WorkspaceChangesProvider
participant Preload as preload.ts
participant IpcHandlers as IPC Handlers
participant WatcherHost as workspace-watcher-host
participant ParcelWatcher as `@parcel/watcher` (OS)
rect rgba(100, 149, 237, 0.5)
note over Renderer, ParcelWatcher: Subscribe to changes
Renderer->>WorkspaceChangesProvider: subscribeChanges(workspaceId, onChange)
WorkspaceChangesProvider->>Preload: bridge.workspaces.subscribe_changes(workspaceId, handler)
Preload->>IpcHandlers: ipcRenderer.invoke(WORKSPACE_SUBSCRIBE_CHANGES, {id, workspaceId})
IpcHandlers->>WatcherHost: subscribeWorkspaceChanges(wc, {id, root, workspaceId})
WatcherHost->>ParcelWatcher: subscribe(root, onRawEvents, {ignore})
end
rect rgba(60, 179, 113, 0.5)
note over ParcelWatcher, Renderer: Event delivery loop
ParcelWatcher-->>WatcherHost: raw events[]
WatcherHost->>WatcherHost: buffer + coalesce (timer: COALESCE_MS)
WatcherHost->>Preload: webContents.send(WORKSPACE_CHANGE, coalesced[])
Preload->>Preload: dispatch via workspaceChangeHandlers[subscription_id]
Preload->>WorkspaceChangesProvider: notify listeners
WorkspaceChangesProvider->>Renderer: onChange(events[])
alt Editor is clean
Renderer->>Renderer: reloadFromDisk() auto-reload
else Editor is dirty
Renderer->>Renderer: show SaveConflictDialog
end
end
rect rgba(255, 140, 0, 0.5)
note over Renderer, WatcherHost: Save with conflict guard
Renderer->>Preload: write_file(relPath, content, expectedMtime)
Preload->>IpcHandlers: agentClient.write_file(..., expectedMtime)
alt mtime matches
IpcHandlers-->>Renderer: 200 OK {mtimeMs}
else mtime mismatch / file missing
IpcHandlers-->>Renderer: 409 {code: modified-since, mtime}
Renderer->>Renderer: set conflict, show dialog
end
end
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 74193a782e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
editor/lib/desktop/bridge.ts (1)
838-850: ⚡ Quick winGuard the watch wrappers the same way the other additive surfaces are guarded.
subscribeChangesandunsubscribeChangescall straight through even though this capability is explicitly optional on older protocol-1 desktop binaries. If a caller misses theisWatchSupported()gate, the failure mode here is an opaqueTypeErrorfrom invoking a missing bridge method. A small in-wrapper capability check would make the unsupported-path deterministic and much easier to debug.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@editor/lib/desktop/bridge.ts` around lines 838 - 850, The functions subscribeChanges and unsubscribeChanges are making direct calls to bridge methods without verifying that watch capability is supported, which means unsupported calls will result in an opaque TypeError. Add a capability check at the beginning of both subscribeChanges and unsubscribeChanges functions using isWatchSupported() to guard access to the bridge methods, similar to how other optional capabilities are protected. If the capability is not supported, throw an appropriate error with a clear message explaining that watch functionality is not available on the current protocol version.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@desktop/src/main/workspace-watcher-host.ts`:
- Around line 256-287: The subscribeWorkspaceChanges function and related code
at lines 295-318 and 359-369 have race conditions where concurrent
subscribe/unsubscribe cycles on the same root can attach stale in-flight
subscriptions after newer cycles start, and non-first subscribers can return
success while the first start is pending, leaving dead/duplicated watchers.
Serialize per-root startup by implementing a per-root promise/lock mechanism
(e.g., a Map keyed by root) to ensure only one watch start operation executes at
a time per root, and guard all registry operations by state identity to prevent
stale in-flight subscriptions from completing after newer cycles have already
initiated or completed.
In `@editor/scaffolds/desktop/workbench/workspace-changes.tsx`:
- Around line 62-68: In the listener dispatch loop where each listener is
invoked with the events parameter, wrap the listener callback invocation in a
try-catch block to prevent a thrown error in one listener from interrupting the
fan-out to remaining listeners. This ensures that if one listener throws an
exception, the subsequent listeners in the Array.from(listenersRef.current)
iteration will still be called, allowing file-tree and editor updates to
continue for other consumers.
In `@packages/grida-ai-agent/src/workspaces/fs.ts`:
- Around line 310-331: The expected_mtime precondition check (comparing
current.mtimeMs to options.expected_mtime) is performed as a separate step
before the atomicWrite call, creating a race condition where another writer can
modify the file between validation and the actual write. Move the expected_mtime
check from its current standalone validation into the atomicWrite function call
itself, ensuring the precondition is enforced atomically under the same
exclusion as the final file replacement to prevent silent clobbering under
contention.
---
Nitpick comments:
In `@editor/lib/desktop/bridge.ts`:
- Around line 838-850: The functions subscribeChanges and unsubscribeChanges are
making direct calls to bridge methods without verifying that watch capability is
supported, which means unsupported calls will result in an opaque TypeError. Add
a capability check at the beginning of both subscribeChanges and
unsubscribeChanges functions using isWatchSupported() to guard access to the
bridge methods, similar to how other optional capabilities are protected. If the
capability is not supported, throw an appropriate error with a clear message
explaining that watch functionality is not available on the current protocol
version.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d763906b-c57b-4d8c-8640-00f83114555e
⛔ Files ignored due to path filters (1)
desktop/pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (22)
desktop/forge.config.tsdesktop/package.jsondesktop/pnpm-workspace.yamldesktop/src/bridge/contract.tsdesktop/src/main.tsdesktop/src/main/ipc-handlers.tsdesktop/src/main/workspace-watcher-host.test.tsdesktop/src/main/workspace-watcher-host.tsdesktop/src/preload.tsdesktop/vite.main.config.tseditor/lib/agent-chat/web-daemon-bridge.tseditor/lib/desktop/bridge.tseditor/scaffolds/desktop/workbench/editor-pane-svg-editor.tsxeditor/scaffolds/desktop/workbench/file-tree-pane.tsxeditor/scaffolds/desktop/workbench/workspace-changes.tsxeditor/scaffolds/desktop/workbench/workspace-workbench.tsxpackages/grida-ai-agent/src/http/routes/workspaces.tspackages/grida-ai-agent/src/http/validate.tspackages/grida-ai-agent/src/transport.tspackages/grida-ai-agent/src/workspaces.fs.test.tspackages/grida-ai-agent/src/workspaces/fs.tspackages/grida-desktop-bridge/src/index.ts
…ds; suppress watcher echo on save (#805) Two follow-ups from PR #837 review/CI: 1. GRIDA-DESKTOP-BUILD-GUARD failed on all three runners: @parcel/watcher is the first dependency to ship its native binary as per-platform prebuild PACKAGES (@parcel/watcher-<os>-<arch>) declared as optionalDependencies — like esbuild/swc. Only the current platform's prebuild installs, so the oracle (which followed optionalDependencies and required every one present) flagged the other 12 as "missing" and made the build un-shippable on every OS. Fix: a missing OPTIONAL dependency is legitimate (that is what optional means); only a missing REQUIRED dependency is a launch-crash failure. Present optionals still join the closure, so the bloat gate stays honest. Verified locally: `pnpm package` on darwin-arm64 now passes — ships exactly the 17-package closure (incl. @parcel/watcher-darwin-arm64), tolerates the 12 cross-platform prebuilds. 2. Codex review (P2): with the watcher enabled, a normal save also emits a `changed` event for the same file. By the time that coalesced batch lands the buffer is clean again, so the editor auto-reloaded — calling editor.load() and wiping selection / undo history / mode on every Cmd+S. Fix: echo suppression in reloadFromDisk — compare the freshly-read mtime against `lastMtimeRef` (the mtime we last wrote/loaded) and skip the reload when disk hasn't advanced past us. A genuine external change still reloads.
…build on every platform (#805) @electron/rebuild was compiling @parcel/watcher from source during packaging (it was not in rebuildConfig.ignoreModules). That is wasteful on mac/linux (toolchain present) and fatal on the windows runner, which has no configured Visual Studio C++ build tools -> node-gyp 'Could not find any Visual Studio installation'. @parcel/watcher ships N-API prebuilds for every platform as separate @parcel/watcher-<os>-<arch> packages, and N-API binaries load under Electron without an ABI rebuild, so it must never be compiled from source. Ignore it in rebuild on all platforms; the shipped per-platform prebuild provides the addon. Verified locally on darwin-arm64: package + oracle pass.
…e-precondition window, listener isolation, watch-cap guard (#805) - workspace-watcher-host: serialize per-root OS-watch startup. The first subscriber starts the watch; concurrent later subscribers await the same in-flight start (ensureWatchStarted) instead of returning success before the watch exists or racing a duplicate. startWatch now guards by STATE IDENTITY (not mere presence) so a teardown+restart landing mid-`subscribe()` can't stamp a stale handle onto a newer cycle (leak/duplicate); disposeWatch clears the in-flight entry so a fresh subscriber starts anew. - workspaces/fs + atomic-write: enforce the `expected_mtime` precondition as atomicWrite's new `before_commit` hook — it runs immediately before the rename, shrinking the check→replace gap from "stat → tmp-write → rename" to a single rename syscall (and drops the redundant preflight stat). Not fully atomic (rename takes no precondition) — that residual sub-syscall window is the accepted cost of mtime-based optimistic concurrency, same as VSCode's etag. The 9 fs tests (incl. stale / deleted-on-disk) still pass. - workspace-changes: isolate each listener invocation in try/catch so one throwing consumer (editor) can't suppress the batch for the others (tree). - bridge: gate subscribeChanges on isWatchSupported() (clear error instead of opaque TypeError on old protocol-1 binaries); unsubscribeChanges no-ops when unsupported (teardown paths must not throw).
Closes #805.
Grida Desktop treats the agent as a first-class concurrent writer, but the workbench had no awareness of changes made to workspace files outside the open editor — the agent's own writes, a
git checkout, another editor. Saving over an externally-modified file silently clobbered it. This implements the VSCode model end-to-end.What changed
1. Save-conflict guard — the data-loss fix (transport-agnostic: protects web and desktop)
workspaces.writeFiletakes an optionalexpected_mtimeprecondition. A stale token is rejected with 409modified-since(carrying the current on-disk mtime) instead of silently overwriting. Omitting it preserves last-writer-wins, so agent writes and first-time creates are unaffected.fs→ http route → transport → bridge contract → preload → editor client.isWriteConflict()detects the rejection tolerantly across the ElectroncontextBridge(which strips customErrorproperties — so it keys off the survivingmessagestring, withstatus/codeas belt-and-suspenders).2. OS watcher (desktop-only, behind additive cap
native.workspace_watch)@parcel/watcher(the recursive per-OS backend VSCode uses), mirroringterminal-host.ts: one OS watch per workspace root, ref-counted across windows/panes, ~75 ms coalesced batches, ignore globs (.git,node_modules, build dirs) pushed to the native backend, torn down on window close / app quit.guarded()IPC; the watch root is resolved host-side from the sidecar registry (the renderer only ever names a workspace id, never a raw path). Subscription ids are preload-minted before the watch starts so no early event can race. See GRIDA-SEC-004.node-pty:dependencies+ vite external +asar.unpackglob +pnpm allowBuilds:false(rely on per-platform prebuilds).3. Renderer wiring
WorkspaceChangesProviderholds one subscription per workspace; consumers attach viauseWorkspaceChanges. The open editor reloads-when-clean / defers-to-the-save-guard-when-dirty; the file tree reloads only the affected parent dirs.caps.workspace_watch: false), so non-Electron hosts fall back cleanly to pull-refresh.Reviewer notes
guarded(); workspace-id → root resolution is host-side; the contextBridge fanout passes structured-clone payloads only (never the Electron event object). An anti-drift test asserts theguarded()registration.@parcel/watcherdeps/external/asar.unpack/prebuild recipe is correct-by-construction (the bundle oracle auto-discovers the dynamicimport()and follows the prebuildoptionalDependencies), but a realelectron-forge packagerun on each platform is still worth confirming.Tests
workspaces.fsconflict-guard: last-writer-wins, matching/stale mtime, deleted-on-disk = conflict.workspace-watcher-host: pure helpers, ref-count registry, and the GRIDA-SEC-004guarded()anti-drift check.🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
New Features
Chores