Skip to content

feat(desktop): watch workspace files — refresh open editor + file tree on external change, with save-conflict guard (VSCode model) #805

Closed

Description

@softmarshmallow

Summary

Grida Desktop does not react to external file changes. When a workspace file is modified on disk outside the app:

  1. An open editor doesn't refresh. The SVG editor reads the file once into React state and never re-reads — stale content stays on screen.
  2. The file tree doesn't refresh. Directory listings are pull-based and only re-fetch on a manual refresh or an in-app write; files created/deleted/renamed externally are invisible.
  3. (Hidden, worse) A save silently clobbers the external change — data loss. The load mtime is discarded and the save carries no precondition, so writing back overwrites whatever changed on disk in the meantime — with no conflict detection.

This issue captures the symptoms, the current gaps, and the VSCode mental model (researched below) as the reference design, then maps it onto Grida's seams. Description + design proposal for later pickup, not a fix.

Why this matters more here than in VSCode: the agent is a first-class concurrent writer. "External change" in Grida includes "the agent just edited the file you have open." So refresh + conflict handling isn't an edge case — it's a core part of the human↔agent loop.

Current state (grounded)

  • No OS file watcher exists. A deferred-work breadcrumb confirms it: packages/grida-ai-agent/src/http/routes/files.ts:61 — "External-file-change watcher deferred. SSE plumbing requires chokidar." (files/io.ts:26 echoes it.) The only watch in-tree is AgentFs.watch (packages/grida-ai-agent/src/fs/index.ts), which fires on the agent's own virtual-fs writes — not a real OS watch on the workspace root.
  • Open editor loads once, never revalidates. editor/scaffolds/desktop/workbench/editor-pane-svg-editor.tsx calls workspaces.read_file → { content, mtime }, stores content in React state, and discards mtime. No re-fetch on focus, no subscription.
  • Dirty tracking exists but is disconnected from disk. Surface tracks contentVersion vs savedVersion → dirty, and surfaces it (tab dot, window.set_document_edited). But it never compares the load mtime to disk, so it cannot know a conflict exists.
  • File tree is pull-based. file-tree-pane.tsx + file-tree-source.ts lazily call workspaces.readdir per expanded folder, cache in knownDirectories, and refresh only via (a) a manual button or (b) a refreshKey bump after an in-app save / agent stream-end (bumpTreeRefresh). No external-change channel.
  • write_file has no precondition. Signature is write_file(workspaceId, relPath, content) → { mtime } — it cannot reject a stale overwrite.
  • No file-change event channel on the bridge. Existing file surface: files.read/write, workspaces.readdir/read_file/read_file_bytes/write_file/trash_entry. The push precedent is sessions.subscribe_status (callback handle + unsubscribe_status).

Reference: the VSCode mental model

A 4-layer pipeline, one invariant. (Anchors in ~/Documents/GitHub/vscode/src.)

@parcel/watcher  →  watcher service (coalesce ~75ms / throttle ~200ms)  →  FileService.onDidFilesChange (FileChangesEvent)
                                                                                  │
                                          ┌───────────────────────────────────────┼───────────────────────────────┐
                                          ▼                                       ▼                               ▼
                              TextFileEditorModelManager              TextFileEditorModel                 ExplorerService
                              (non-dirty → auto-reload)               (dirty → keep edits, orphan)        (surgical, 500ms-debounced)
  1. One library, two modes. @parcel/watcher (native per-OS backend: fs-events / inotify / windows) for recursive subtree watches; a node fs.watch watcher for non-recursive. excludes (node_modules, .git) pushed down to the native layer. (vs/platform/files/node/watcher/parcel/parcelWatcher.ts)
  2. Coalesce + throttle at the source so higher layers never see raw spam (ADD+DELETE cancel, DELETE→ADD becomes UPDATE). (vs/platform/files/common/watcher.ts)
  3. Normalize into one queryable event — FileChangesEvent with contains()/affects() and a correlationId to distinguish my watch from global. (vs/platform/files/common/files.ts, fileService.ts)
  4. Three independent consumers subscribe to the same event and each filter for what they care about.
  5. Non-dirty open editor → auto-reload (bounded queue, depth 2). (textFileEditorModelManager.ts)
  6. Dirty open editor → NEVER reload. Keep the user's edits; only track orphan (deleted-on-disk) state. The conflict is deferred to save time. (textFileEditorModel.ts)
  7. Staleness is detected on WRITE via captured mtime + etag. etag = mtime + size (cheap, no checksum) with a byte-equality escape hatch to suppress false positives. FileService.validateWriteFile throws FILE_MODIFIED_SINCE if disk advanced. (fileService.ts:499-535)
  8. Conflict = a state + a UI, not data loss. Model enters CONFLICT, stays dirty; TextFileSaveErrorHandler offers Compare / Overwrite / Revert. (.../editors/textFileSaveErrorHandler.ts)
  9. Explorer applies surgical, debounced (500ms) tree updates, suppressed during inline rename; raw-FS path is a coarse fallback to in-app operation events. (explorerService.ts)
  10. Invariant: an external change never silently discards user edits. Every rule above exists to enforce this.

Mapping onto Grida's seams

VSCode layer Grida landing
Watcher (@parcel/watcher) A new OS watcher on workspace.root. Placement decision (see below): agent sidecar (matches the deferred SSE/chokidar note) or Electron main (like the proposed terminal host).
Normalized FileChangesEvent A WorkspaceChangeEvent DTO { kind: added|changed|deleted, relPath }, coalesced/throttled at the source.
onDidFilesChange subscription New workspaces.subscribe_changes(workspaceId, onEvent) on the bridge — follow sessions.subscribe_status exactly (handle + unsubscribe_changes).
Model manager (non-dirty auto-reload) editor-pane-svg-editor.tsx: on a change event for the open relPath, if !dirty → re-read & re-init the editor from disk.
Model (dirty → defer; save-time guard) Retain load mtime/etag; extend write_file to take an expected mtime/etag precondition and return a MODIFIED_SINCE error; on save reject stale → enter conflict state.
Explorer surgical refresh file-tree-pane.tsx: on a change event, surgically invalidate+load the affected parent (already supported via reloadParent); debounce bursts.

Open design decisions (for the planning pass)

  1. Watcher placement: agent sidecar (SSE) vs. Electron main (IPC). The deferred note lives in the sidecar's files route and the workspace registry lives there too — but the desktop terminal proposal puts native processes in main. Pick one; the sidecar already owns workspace identity/cwd, so SSE-from-sidecar is the lower-friction match.
  2. Watcher library. VSCode moved off chokidar to @parcel/watcher (native per-OS, recursive, mature exclude handling). The deferred note guessed chokidar; re-evaluate @parcel/watcher as the better default. Either way it's a native module → same packaging recipe as node-pty / sandbox-runtime (dependencies + asar.unpack + postPackage oracle).
  3. etag definition. Adopt VSCode's mtime + size etag (cheap) + a byte-equality escape hatch, vs. a content hash. Recommend matching VSCode.
  4. Conflict UX for VISUAL editors. VSCode's "Compare" is a text diff. Grida's SVG editor is a structured/visual editor — a 3-way text diff is awkward. Decide the resolution surface: Keep mine / Reload from disk / Overwrite anyway (no diff), or a visual before/after. The mtime/etag save-guard itself is editor-agnostic and should ship regardless of the resolution UI.
  5. Agent-origin echo. When the agent writes via NodeFsBackend, the OS watcher will fire for the agent's own writes. Decide whether to (a) treat agent writes like any external change (simple, uniform — agent edits a file you have open → you get a refresh/conflict), or (b) carry an origin/correlation id to suppress self-echo. VSCode uses correlation ids; the agent's AgentFs.watch deliberately does not track origin today (fs/index.ts:262).
  6. Watch scope & excludes. Recursive on workspace.root with node_modules/.git/build-output excludes pushed to the native layer; cap/throttle under change storms (VSCode: 75ms coalesce, 200ms throttle, 30k buffer cap).
  7. Multi-window / multi-subscriber. Ref-count one OS watch per workspace across N renderer subscribers (VSCode does this via request hashing).

Affected files

Concern File
Watcher impl + event source packages/grida-ai-agent/src/files/io.ts, packages/grida-ai-agent/src/http/routes/files.ts / routes/workspaces.ts (or a new Electron-main host)
write_file precondition (etag/mtime) packages/grida-ai-agent/src/files/**, workspaces route, and the bridge write_file signature
Bridge change-subscription packages/grida-desktop-bridge/src/index.ts, desktop/src/preload.ts, editor/lib/desktop/bridge.ts
Open-editor reload + conflict editor/scaffolds/desktop/workbench/editor-pane-svg-editor.tsx (capture mtime, subscribe, reload-if-clean, conflict-if-dirty)
File tree surgical refresh editor/scaffolds/desktop/workbench/file-tree-pane.tsx, file-tree-source.ts
Native packaging desktop/package.json, desktop/forge.config.ts, desktop/scripts/verify-packaged-bundle.mjs

Proposed minimal scope (v1)

  1. OS watcher on workspace.root (placement + library per decisions 1–2) emitting coalesced WorkspaceChangeEvents.
  2. workspaces.subscribe_changes bridge channel (mirror sessions.subscribe_status).
  3. File tree: surgical, debounced auto-refresh on events.
  4. Open editor: retain mtime/etag; auto-reload when clean.
  5. Save-conflict guard: write_file precondition + reject stale → conflict state (Keep mine / Reload / Overwrite). This is the data-loss fix and is the highest-value piece.
  6. Defer: visual 3-way diff, rename detection, watch tuning for huge trees.

References

  • Deferred breadcrumb: packages/grida-ai-agent/src/http/routes/files.ts:61, files/io.ts:26
  • Editor load/dirty: editor/scaffolds/desktop/workbench/editor-pane-svg-editor.tsx
  • File tree: editor/scaffolds/desktop/workbench/file-tree-pane.tsx, file-tree-source.ts
  • Bridge + push precedent: packages/grida-desktop-bridge/src/index.ts (sessions.subscribe_status)
  • VSCode model anchors: vs/platform/files/{node/watcher/parcel/parcelWatcher.ts, common/watcher.ts, common/files.ts, common/fileService.ts}; vs/workbench/services/textfile/common/{textFileEditorModel.ts, textFileEditorModelManager.ts}; vs/workbench/contrib/files/browser/{explorerService.ts, editors/textFileSaveErrorHandler.ts}

Metadata

Metadata

Assignees

No one assigned

    Labels

    desktopenhancementinvestigate

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions