fix: reflect external file changes in editor tabs (#735)
This commit is contained in:
@@ -429,6 +429,18 @@ function unsubscribe(worktreePath: string, senderId: number): void {
|
||||
// Key: `${connectionId}:${worktreePath}`, Value: unwatch function
|
||||
const remoteWatchers = new Map<string, () => void>()
|
||||
|
||||
function replaceRemoteWatcher(key: string, unwatch: () => void): void {
|
||||
const previous = remoteWatchers.get(key)
|
||||
if (previous) {
|
||||
// Why: SSH reconnect swaps in a fresh filesystem provider, but the
|
||||
// renderer keeps watching the same worktree path. Replacing the existing
|
||||
// unwatch callback here ensures a post-reconnect watch request rebinds to
|
||||
// the new provider instead of early-returning forever on stale state.
|
||||
previous()
|
||||
}
|
||||
remoteWatchers.set(key, unwatch)
|
||||
}
|
||||
|
||||
// ── Public API ───────────────────────────────────────────────────────
|
||||
|
||||
export function registerFilesystemWatcherHandlers(): void {
|
||||
@@ -441,9 +453,6 @@ export function registerFilesystemWatcherHandlers(): void {
|
||||
throw new Error(`No filesystem provider for connection "${args.connectionId}"`)
|
||||
}
|
||||
const key = `${args.connectionId}:${args.worktreePath}`
|
||||
if (remoteWatchers.has(key)) {
|
||||
return
|
||||
}
|
||||
|
||||
const unwatch = await provider.watch(args.worktreePath, (events) => {
|
||||
if (!event.sender.isDestroyed()) {
|
||||
@@ -453,7 +462,7 @@ export function registerFilesystemWatcherHandlers(): void {
|
||||
} satisfies FsChangedPayload)
|
||||
}
|
||||
})
|
||||
remoteWatchers.set(key, unwatch)
|
||||
replaceRemoteWatcher(key, unwatch)
|
||||
|
||||
event.sender.once('destroyed', () => {
|
||||
const unwatchFn = remoteWatchers.get(key)
|
||||
|
||||
@@ -27,6 +27,7 @@ import { UpdateCard } from './components/UpdateCard'
|
||||
import { ZoomOverlay } from './components/ZoomOverlay'
|
||||
import { SshPassphraseDialog } from './components/settings/SshPassphraseDialog'
|
||||
import { useGitStatusPolling } from './components/right-sidebar/useGitStatusPolling'
|
||||
import { useEditorExternalWatch } from './hooks/useEditorExternalWatch'
|
||||
import {
|
||||
setRuntimeGraphStoreStateGetter,
|
||||
setRuntimeGraphSyncEnabled
|
||||
@@ -137,6 +138,13 @@ function App(): React.JSX.Element {
|
||||
// sidebar is closed, which leaves stale "Rebasing"/"Merging" badges behind
|
||||
// until some unrelated view remount happens to refresh them.
|
||||
useGitStatusPolling()
|
||||
// Why: the editor must hear external filesystem changes regardless of
|
||||
// which right-sidebar panel is visible (Explorer unmounts when the user
|
||||
// switches to Source Control or Checks). Wiring this at App level mirrors
|
||||
// VSCode's workbench-scoped `TextFileEditorModelManager`, which reloads
|
||||
// clean models from a single always-on file-change subscription instead
|
||||
// of tying reloads to the Explorer UI lifecycle.
|
||||
useEditorExternalWatch()
|
||||
useGlobalFileDrop()
|
||||
|
||||
// Fetch initial data + hydrate GitHub cache from disk
|
||||
|
||||
@@ -371,25 +371,14 @@ function EditorPanelInner({
|
||||
if (matchingFiles.length === 0) {
|
||||
return
|
||||
}
|
||||
setFileContents((prev) => {
|
||||
const next = { ...prev }
|
||||
for (const file of matchingFiles) {
|
||||
if (file.mode === 'edit') {
|
||||
delete next[file.id]
|
||||
}
|
||||
}
|
||||
return next
|
||||
})
|
||||
setDiffContents((prev) => {
|
||||
const next = { ...prev }
|
||||
for (const file of matchingFiles) {
|
||||
if (file.mode === 'diff') {
|
||||
delete next[file.id]
|
||||
}
|
||||
}
|
||||
return next
|
||||
})
|
||||
|
||||
// Why: do NOT delete fileContents[file.id] here before the reload
|
||||
// completes. Dropping the entry renders EditorContent's "Loading..."
|
||||
// placeholder and unmounts MonacoEditor. On remount, @monaco-editor/react
|
||||
// skips its value-sync effect on the first render, and `keepCurrentModel`
|
||||
// retains the prior model — so the new content prop never reaches the
|
||||
// editor and the user sees the pre-external-edit text linger.
|
||||
// loadFileContent / loadDiffContent overwrite the entry atomically once
|
||||
// the fresh read returns, which is what Monaco's value-sync can observe.
|
||||
for (const file of matchingFiles) {
|
||||
if (file.mode === 'edit') {
|
||||
void loadFileContent(file.filePath, file.id, file.worktreeId)
|
||||
|
||||
@@ -15,7 +15,13 @@ import '@/lib/monaco-setup'
|
||||
import { computeEditorFontSize } from '@/lib/editor-font-zoom'
|
||||
|
||||
import { useContextualCopySetup } from './useContextualCopySetup'
|
||||
import { computeMonacoRevealRange } from './monaco-reveal-range'
|
||||
import { performReveal } from './monaco-reveal'
|
||||
import { syncContentOnMount, syncContentUpdate } from './monaco-content-sync'
|
||||
import {
|
||||
beginProgrammaticContentSync,
|
||||
endProgrammaticContentSync,
|
||||
shouldIgnoreMonacoContentChange
|
||||
} from './monaco-programmatic-sync'
|
||||
|
||||
type MonacoEditorProps = {
|
||||
filePath: string
|
||||
@@ -131,10 +137,46 @@ export default function MonacoEditor({
|
||||
[cancelScheduledReveal, clearTransientRevealHighlight]
|
||||
)
|
||||
|
||||
// Why: `keepCurrentModel` retains Monaco models across unmounts, and
|
||||
// @monaco-editor/react skips its value→model sync on the first render after
|
||||
// a remount. Without explicit sync, external file changes that arrived
|
||||
// while the tab was unmounted leave the retained model showing stale text.
|
||||
// contentRef lets handleMount read the current content without re-binding;
|
||||
// lastSyncedContentRef lets the update effect distinguish our own onChange
|
||||
// emissions from real prop drift.
|
||||
// Invariant: the mount path (handleMount's syncContentOnMount call) MUST
|
||||
// read `contentRef.current`, never `lastSyncedContentRef.current`. The
|
||||
// useLayoutEffect below can run before mount with `editorRef.current === null`
|
||||
// and bails without updating lastSyncedContentRef, so that ref may be stale
|
||||
// pre-mount; only contentRef is guaranteed to reflect the latest prop.
|
||||
const contentRef = useRef(content)
|
||||
contentRef.current = content
|
||||
const lastSyncedContentRef = useRef<string>(content)
|
||||
// Why: Monaco model reconciliation reuses real edit operations so retained
|
||||
// models keep sane undo behavior. Those edits are programmatic, not user
|
||||
// typing, so split panes must suppress the resulting onChange callback or a
|
||||
// freshly mounted markdown source view can mark the shared file dirty.
|
||||
const isApplyingProgrammaticContentRef = useRef(false)
|
||||
|
||||
const handleMount: OnMount = useCallback(
|
||||
(editorInstance, monaco) => {
|
||||
editorRef.current = editorInstance
|
||||
|
||||
// Why: see comment on contentRef — reconcile the retained model against
|
||||
// the current prop before any user interaction so external changes that
|
||||
// arrived while the tab was unmounted become visible immediately.
|
||||
beginProgrammaticContentSync(filePath)
|
||||
isApplyingProgrammaticContentRef.current = true
|
||||
try {
|
||||
const didSyncOnMount = syncContentOnMount(editorInstance, contentRef.current)
|
||||
if (didSyncOnMount) {
|
||||
lastSyncedContentRef.current = contentRef.current
|
||||
}
|
||||
} finally {
|
||||
isApplyingProgrammaticContentRef.current = false
|
||||
endProgrammaticContentSync(filePath)
|
||||
}
|
||||
|
||||
setupCopy(editorInstance, monaco, filePath, propsRef)
|
||||
|
||||
// Add Cmd+S save keybinding
|
||||
@@ -225,12 +267,46 @@ export default function MonacoEditor({
|
||||
const handleChange = useCallback(
|
||||
(value: string | undefined) => {
|
||||
if (value !== undefined) {
|
||||
// Why: split panes that share a retained Monaco model all receive the
|
||||
// same model change events. When one pane is reconciling prop content
|
||||
// into the shared model, sibling panes must ignore the echoed onChange
|
||||
// or they'll treat the programmatic sync as a user edit and mark the
|
||||
// shared file dirty.
|
||||
if (
|
||||
shouldIgnoreMonacoContentChange({
|
||||
filePath,
|
||||
isApplyingProgrammaticContent: isApplyingProgrammaticContentRef.current
|
||||
})
|
||||
) {
|
||||
return
|
||||
}
|
||||
lastSyncedContentRef.current = value
|
||||
onContentChange(value)
|
||||
}
|
||||
},
|
||||
[onContentChange]
|
||||
[filePath, onContentChange]
|
||||
)
|
||||
|
||||
// Why: reconcile the model whenever `content` drifts from what we last
|
||||
// synced (covers external file changes while mounted). The on-mount case
|
||||
// is handled directly in handleMount. useLayoutEffect lets the overwrite
|
||||
// land before paint so the user never sees stale text.
|
||||
useLayoutEffect(() => {
|
||||
const ed = editorRef.current
|
||||
if (!ed || lastSyncedContentRef.current === content) {
|
||||
return
|
||||
}
|
||||
beginProgrammaticContentSync(filePath)
|
||||
isApplyingProgrammaticContentRef.current = true
|
||||
try {
|
||||
syncContentUpdate(ed, content)
|
||||
lastSyncedContentRef.current = content
|
||||
} finally {
|
||||
isApplyingProgrammaticContentRef.current = false
|
||||
endProgrammaticContentSync(filePath)
|
||||
}
|
||||
}, [content, filePath])
|
||||
|
||||
// Snapshot scroll position synchronously on unmount so tab switches always
|
||||
// capture the latest value, even if the trailing throttle hasn't fired yet.
|
||||
// Why useLayoutEffect: cleanup runs before @monaco-editor/react's useEffect
|
||||
@@ -400,63 +476,3 @@ export default function MonacoEditor({
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Shared reveal logic used by both onMount and useEffect */
|
||||
function performReveal(
|
||||
ed: editor.IStandaloneCodeEditor,
|
||||
line: number,
|
||||
column: number,
|
||||
matchLength: number,
|
||||
clearTransientRevealHighlight: () => void,
|
||||
revealDecorationRef: React.RefObject<editor.IEditorDecorationsCollection | null>,
|
||||
revealHighlightTimerRef: React.RefObject<ReturnType<typeof setTimeout> | null>
|
||||
): void {
|
||||
const model = ed.getModel()
|
||||
if (!model) {
|
||||
ed.focus()
|
||||
return
|
||||
}
|
||||
|
||||
const range = computeMonacoRevealRange({
|
||||
line,
|
||||
column,
|
||||
matchLength,
|
||||
maxLine: model.getLineCount(),
|
||||
lineMaxColumn: model.getLineMaxColumn(Math.min(Math.max(1, line), model.getLineCount()))
|
||||
})
|
||||
const shouldHighlight = matchLength > 0
|
||||
|
||||
ed.setPosition({ lineNumber: range.startLineNumber, column: range.startColumn })
|
||||
if (shouldHighlight) {
|
||||
ed.setSelection(range)
|
||||
ed.revealRangeInCenter(range)
|
||||
} else {
|
||||
ed.setSelection({
|
||||
startLineNumber: range.startLineNumber,
|
||||
startColumn: range.startColumn,
|
||||
endLineNumber: range.startLineNumber,
|
||||
endColumn: range.startColumn
|
||||
})
|
||||
ed.revealPositionInCenter({ lineNumber: range.startLineNumber, column: range.startColumn })
|
||||
}
|
||||
|
||||
clearTransientRevealHighlight()
|
||||
if (shouldHighlight) {
|
||||
revealDecorationRef.current = ed.createDecorationsCollection([
|
||||
{
|
||||
range,
|
||||
options: {
|
||||
inlineClassName: 'monaco-search-result-highlight',
|
||||
stickiness: 1
|
||||
}
|
||||
}
|
||||
])
|
||||
revealHighlightTimerRef.current = setTimeout(() => {
|
||||
revealDecorationRef.current?.clear()
|
||||
revealDecorationRef.current = null
|
||||
revealHighlightTimerRef.current = null
|
||||
}, 1200)
|
||||
}
|
||||
|
||||
ed.focus()
|
||||
}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { EditorContent, useEditor } from '@tiptap/react'
|
||||
import type { Editor } from '@tiptap/react'
|
||||
import { toast } from 'sonner'
|
||||
import { RichMarkdownSlashMenu } from './RichMarkdownSlashMenu'
|
||||
import { useAppStore } from '@/store'
|
||||
import { RichMarkdownToolbar } from './RichMarkdownToolbar'
|
||||
import { extractIpcErrorMessage, getImageCopyDestination } from './rich-markdown-image-utils'
|
||||
import { encodeRawMarkdownHtmlForRichEditor } from './raw-markdown-html'
|
||||
import { useLocalImagePick } from './useLocalImagePick'
|
||||
import { createRichMarkdownExtensions } from './rich-markdown-extensions'
|
||||
import { slashCommands, syncSlashMenu } from './rich-markdown-commands'
|
||||
import type { SlashCommand, SlashMenuState } from './rich-markdown-commands'
|
||||
@@ -21,11 +20,9 @@ import { useLinkBubble } from './useLinkBubble'
|
||||
import { useEditorScrollRestore } from './useEditorScrollRestore'
|
||||
import { registerPendingEditorFlush } from './editor-pending-flush'
|
||||
import { createRichMarkdownKeyHandler } from './rich-markdown-key-handler'
|
||||
import { DOMSerializer } from '@tiptap/pm/model'
|
||||
import { TextSelection } from '@tiptap/pm/state'
|
||||
import { normalizeSoftBreaks } from './rich-markdown-normalize'
|
||||
import { autoFocusRichEditor } from './rich-markdown-auto-focus'
|
||||
import { cutVisualLine, getVisualLineRange } from './rich-markdown-visual-line'
|
||||
import { handleRichMarkdownCut } from './rich-markdown-cut-handler'
|
||||
|
||||
type RichMarkdownEditorProps = {
|
||||
fileId: string
|
||||
@@ -73,6 +70,11 @@ export default function RichMarkdownEditor({
|
||||
// which triggers onUpdate. Without this guard the editor immediately marks the
|
||||
// file dirty before the user has typed anything.
|
||||
const isInitializingRef = useRef(true)
|
||||
// Why: internal maintenance paths can dispatch transactions after mount
|
||||
// (external reloads, soft-break normalization, image-path refresh). Those
|
||||
// are not user edits, so onUpdate must ignore them or split panes can flip a
|
||||
// shared file dirty without any real content change.
|
||||
const isApplyingProgrammaticUpdateRef = useRef(false)
|
||||
const [linkBubble, setLinkBubble] = useState<LinkBubbleState | null>(null)
|
||||
const [isEditingLink, setIsEditingLink] = useState(false)
|
||||
const isEditingLinkRef = useRef(false)
|
||||
@@ -119,110 +121,8 @@ export default function RichMarkdownEditor({
|
||||
attributes: {
|
||||
class: 'rich-markdown-editor'
|
||||
},
|
||||
// Why: Electron's app menu `{ role: 'cut' }` binds Cmd/Ctrl+X at the
|
||||
// main-process level, so the keystroke never reaches handleKeyDown.
|
||||
// Instead, the menu dispatches a native cut command which fires this
|
||||
// DOM event. For empty selections we cut the current block (like VS
|
||||
// Code and Notion); for non-empty selections we defer to ProseMirror's
|
||||
// built-in clipboard serializer.
|
||||
handleDOMEvents: {
|
||||
cut: (view, event) => {
|
||||
const { selection } = view.state
|
||||
if (!selection.empty) {
|
||||
return false
|
||||
}
|
||||
|
||||
const { $from } = selection
|
||||
|
||||
// Why: a GapCursor before a top-level leaf node (e.g. horizontal rule
|
||||
// as the first child of the doc) resolves to depth 0. Attempting to cut
|
||||
// at depth 0 would call $from.before(0) on the doc node, which throws
|
||||
// RangeError("There is no position before the top-level node"). Bail
|
||||
// out and let ProseMirror's default handler deal with it.
|
||||
if ($from.depth < 1) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Walk up from the textblock to find the best node to cut. For list
|
||||
// items and task items, cut the whole item rather than just its inner
|
||||
// paragraph. Stop at table cells to avoid breaking table structure.
|
||||
let cutDepth = $from.depth
|
||||
for (let d = $from.depth - 1; d >= 1; d--) {
|
||||
const name = $from.node(d).type.name
|
||||
if (name === 'listItem' || name === 'taskItem') {
|
||||
cutDepth = d
|
||||
break
|
||||
}
|
||||
if (name === 'tableCell' || name === 'tableHeader') {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const cutNode = $from.node(cutDepth)
|
||||
const text = cutNode.textContent
|
||||
|
||||
// Why: for paragraphs that word-wrap across multiple visual lines, cut
|
||||
// only the visual line the cursor is on rather than the entire paragraph.
|
||||
// This matches the user expectation of per-line cutting (like VS Code)
|
||||
// without destroying the rest of the paragraph's content.
|
||||
if (cutNode.type.name === 'paragraph' && text) {
|
||||
const paraStart = $from.start(cutDepth)
|
||||
const paraEnd = $from.end(cutDepth)
|
||||
const lineRange = getVisualLineRange(view, selection.from, paraStart, paraEnd)
|
||||
if (lineRange) {
|
||||
return cutVisualLine(view, event, lineRange)
|
||||
}
|
||||
// Falls through to block-level cut for single-line paragraphs.
|
||||
}
|
||||
|
||||
if (!text) {
|
||||
// Still delete the empty block, matching VS Code behavior
|
||||
event.preventDefault()
|
||||
const from = $from.before(cutDepth)
|
||||
const to = $from.after(cutDepth)
|
||||
let tr = view.state.tr.delete(from, to)
|
||||
// Why: after deleting the last block the old `from` offset may exceed
|
||||
// the new document length, so we clamp and use TextSelection.near() to
|
||||
// land on the closest valid cursor position.
|
||||
const clampedPos = Math.max(0, Math.min(from, tr.doc.content.size))
|
||||
const resolvedPos = tr.doc.resolve(clampedPos)
|
||||
tr = tr.setSelection(TextSelection.near(resolvedPos))
|
||||
view.dispatch(tr)
|
||||
return true
|
||||
}
|
||||
|
||||
const clipboardEvent = event as ClipboardEvent
|
||||
// Why: if clipboardData is null (e.g. synthetic events), we must not
|
||||
// preventDefault and then delete -- that would lose content without
|
||||
// placing it on the clipboard. Fall back to browser default instead.
|
||||
if (!clipboardEvent.clipboardData) {
|
||||
return false
|
||||
}
|
||||
event.preventDefault()
|
||||
|
||||
// Why: writing both text/html and text/plain preserves inline formatting
|
||||
// (bold, italic, links) on round-trip cut-then-paste, while still giving
|
||||
// a plain-text fallback for external targets.
|
||||
const serializer = DOMSerializer.fromSchema(view.state.schema)
|
||||
const fragment = serializer.serializeFragment(cutNode.content)
|
||||
const div = document.createElement('div')
|
||||
div.appendChild(fragment)
|
||||
clipboardEvent.clipboardData.setData('text/html', div.innerHTML)
|
||||
clipboardEvent.clipboardData.setData('text/plain', text)
|
||||
|
||||
const from = $from.before(cutDepth)
|
||||
const to = $from.after(cutDepth)
|
||||
let tr = view.state.tr.delete(from, to)
|
||||
// Why: after deleting the last block the old `from` offset may exceed
|
||||
// the new document length, so we clamp and use TextSelection.near() to
|
||||
// land on the closest valid cursor position.
|
||||
const clampedPos = Math.max(0, Math.min(from, tr.doc.content.size))
|
||||
const resolvedPos = tr.doc.resolve(clampedPos)
|
||||
tr = tr.setSelection(TextSelection.near(resolvedPos))
|
||||
view.dispatch(tr)
|
||||
|
||||
return true
|
||||
}
|
||||
cut: handleRichMarkdownCut
|
||||
},
|
||||
handleKeyDown: createRichMarkdownKeyHandler({
|
||||
isMac,
|
||||
@@ -267,7 +167,10 @@ export default function RichMarkdownEditor({
|
||||
// Normalizing them into separate paragraph nodes on load ensures Cmd+X (and
|
||||
// other block-level operations) treat each line as its own block.
|
||||
normalizeSoftBreaks(nextEditor)
|
||||
lastCommittedMarkdownRef.current = nextEditor.getMarkdown()
|
||||
// Why: raw disk content is the source of truth for dirty/external-change
|
||||
// detection. getMarkdown() may round-trip soft breaks or trailing newlines
|
||||
// differently, which would otherwise force a spurious mount-time re-sync.
|
||||
lastCommittedMarkdownRef.current = content
|
||||
// Why: clear the flag *after* normalizeSoftBreaks so any onUpdate
|
||||
// triggered by the normalization transaction is still suppressed.
|
||||
isInitializingRef.current = false
|
||||
@@ -281,26 +184,19 @@ export default function RichMarkdownEditor({
|
||||
onUpdate: ({ editor: nextEditor }) => {
|
||||
syncSlashMenu(nextEditor, rootRef.current, setSlashMenu)
|
||||
|
||||
// Why: normalizeSoftBreaks in onCreate dispatches a transaction that
|
||||
// triggers this callback before the editor is ready for user interaction.
|
||||
// Treating that structural housekeeping step as a user edit would
|
||||
// immediately mark the file dirty and prompt a spurious save dialog on
|
||||
// close. Bail out until initialization is complete.
|
||||
if (isInitializingRef.current) {
|
||||
// Why: bail out during normalizeSoftBreaks's onCreate transaction so the
|
||||
// structural housekeeping doesn't mark the file dirty before the user
|
||||
// has typed anything.
|
||||
if (isInitializingRef.current || isApplyingProgrammaticUpdateRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
// Why: full markdown serialization is debounced for typing performance,
|
||||
// but close-confirmation and beforeunload checks still need to know
|
||||
// immediately that the document changed. Optimistically mark the tab
|
||||
// dirty here, then let the debounced content sync compute the exact
|
||||
// saved-vs-draft comparison a moment later.
|
||||
// Why: optimistically mark dirty for close-confirmation before the
|
||||
// debounced content sync computes the exact saved-vs-draft comparison.
|
||||
onDirtyStateHintRef.current(true)
|
||||
|
||||
// Why: getMarkdown() serializes the entire ProseMirror document tree on
|
||||
// every keystroke, which is the dominant typing-speed bottleneck for large
|
||||
// files. Debouncing it to 300ms keeps the draft store and autosave pipeline
|
||||
// fed without blocking the input path.
|
||||
// Why: getMarkdown() is the typing-speed bottleneck for large files;
|
||||
// debouncing to 300ms keeps drafts current without blocking input.
|
||||
if (serializeTimerRef.current !== null) {
|
||||
window.clearTimeout(serializeTimerRef.current)
|
||||
}
|
||||
@@ -338,13 +234,10 @@ export default function RichMarkdownEditor({
|
||||
editorRef.current = editor ?? null
|
||||
}, [editor])
|
||||
|
||||
// Why: when the component unmounts (tab switch, mode change), flush any
|
||||
// pending serialization so the autosave controller's draft store has the
|
||||
// latest content and the scroll-position cache captures the right state.
|
||||
// This must run before useEditor's cleanup destroys the editor instance,
|
||||
// so we use useLayoutEffect (synchronous cleanup) instead of useEffect.
|
||||
// React runs layout-effect cleanups before effect cleanups, guaranteeing
|
||||
// the editor is still alive when we serialize.
|
||||
// Why: use useLayoutEffect (synchronous cleanup) so the pending serialization
|
||||
// flush runs before useEditor's cleanup destroys the editor instance on tab
|
||||
// switch or mode change. React runs layout-effect cleanups before effect
|
||||
// cleanups, guaranteeing the editor is still alive when we serialize.
|
||||
React.useLayoutEffect(() => {
|
||||
return flushPendingSerialization
|
||||
}, [flushPendingSerialization])
|
||||
@@ -357,44 +250,18 @@ export default function RichMarkdownEditor({
|
||||
// nodes with the new resolved src (renderHTML reads storage at render time).
|
||||
useEffect(() => {
|
||||
if (editor) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(editor.storage as any).image.filePath = filePath
|
||||
editor.view.dispatch(editor.state.tr)
|
||||
isApplyingProgrammaticUpdateRef.current = true
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(editor.storage as any).image.filePath = filePath
|
||||
editor.view.dispatch(editor.state.tr)
|
||||
} finally {
|
||||
isApplyingProgrammaticUpdateRef.current = false
|
||||
}
|
||||
}
|
||||
}, [editor, filePath])
|
||||
|
||||
const handleLocalImagePick = useCallback(async () => {
|
||||
if (!editor) {
|
||||
return
|
||||
}
|
||||
// Why: the native file picker steals focus from the editor, which can cause
|
||||
// ProseMirror to lose track of its selection. We snapshot the cursor position
|
||||
// before the async dialog so we can insert the image exactly where the user
|
||||
// intended, not at whatever position focus() falls back to afterward.
|
||||
const insertPos = editor.state.selection.from
|
||||
try {
|
||||
const srcPath = await window.api.shell.pickImage()
|
||||
if (!srcPath) {
|
||||
return
|
||||
}
|
||||
// Why: copy the image next to the markdown file and insert a relative path
|
||||
// so the markdown stays portable and doesn't bloat with base64 data.
|
||||
const { imageName, destPath } = await getImageCopyDestination(filePath, srcPath)
|
||||
if (srcPath !== destPath) {
|
||||
await window.api.shell.copyFile({ srcPath, destPath })
|
||||
}
|
||||
// Why: insertContentAt places the image at the exact saved position
|
||||
// regardless of where focus lands after the native file dialog closes,
|
||||
// whereas setTextSelection can be overridden by ProseMirror's focus logic.
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.insertContentAt(insertPos, { type: 'image', attrs: { src: imageName } })
|
||||
.run()
|
||||
} catch (err) {
|
||||
toast.error(extractIpcErrorMessage(err, 'Failed to insert image.'))
|
||||
}
|
||||
}, [editor, filePath])
|
||||
const handleLocalImagePick = useLocalImagePick(editor, filePath)
|
||||
|
||||
useEffect(() => {
|
||||
handleLocalImagePickRef.current = handleLocalImagePick
|
||||
@@ -482,15 +349,25 @@ export default function RichMarkdownEditor({
|
||||
// Why: markdown files on disk remain the source of truth for rich mode in
|
||||
// Orca. External file changes, tab replacement, and save-after-reload must
|
||||
// overwrite the editor state so the rich view never drifts from repo text.
|
||||
editor.commands.setContent(encodeRawMarkdownHtmlForRichEditor(content), {
|
||||
contentType: 'markdown'
|
||||
})
|
||||
// Why: same soft-break normalization as onCreate — external content updates
|
||||
// may re-introduce paragraphs with embedded `\n` characters.
|
||||
normalizeSoftBreaks(editor)
|
||||
lastCommittedMarkdownRef.current = content
|
||||
isApplyingProgrammaticUpdateRef.current = true
|
||||
try {
|
||||
editor.commands.setContent(encodeRawMarkdownHtmlForRichEditor(content), {
|
||||
contentType: 'markdown',
|
||||
emitUpdate: false
|
||||
})
|
||||
// Why: same soft-break normalization as onCreate — external content updates
|
||||
// may re-introduce paragraphs with embedded `\n` characters.
|
||||
normalizeSoftBreaks(editor)
|
||||
lastCommittedMarkdownRef.current = content
|
||||
} finally {
|
||||
isApplyingProgrammaticUpdateRef.current = false
|
||||
}
|
||||
syncSlashMenu(editor, rootRef.current, setSlashMenu)
|
||||
}, [content, editor])
|
||||
// Why: fileId is part of the dep array so switching between files (where
|
||||
// content can coincidentally match what was last committed for the prior
|
||||
// file) still triggers the content-sync path and prevents cross-file
|
||||
// drift from the renderer's draft cache.
|
||||
}, [content, editor, fileId])
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -34,6 +34,20 @@ function trimEnd(s: string): string {
|
||||
return s.trimEnd()
|
||||
}
|
||||
|
||||
function shouldSyncPropIntoEditor(
|
||||
currentMarkdown: string,
|
||||
propContent: string,
|
||||
lastCommittedMarkdown: string
|
||||
): boolean {
|
||||
if (propContent === lastCommittedMarkdown) {
|
||||
return false
|
||||
}
|
||||
if (currentMarkdown === propContent) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Simulates the onCreate flow: normalizeSoftBreaks then getMarkdown().
|
||||
*/
|
||||
@@ -129,7 +143,28 @@ describe('normalizeSoftBreaks: known structural changes', () => {
|
||||
})
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 3. Actual user edits must still be detected as dirty.
|
||||
// 3. Rich editor content sync must ignore its own mount-time round-trip
|
||||
// differences, but still accept genuine external file changes.
|
||||
// -----------------------------------------------------------------------
|
||||
describe('content sync gating', () => {
|
||||
it('does not re-sync on mount when only the normalized markdown differs', () => {
|
||||
const disk = 'Line one\nLine two'
|
||||
const normalizedMarkdown = simulateOnCreate(disk)
|
||||
|
||||
expect(shouldSyncPropIntoEditor(normalizedMarkdown, disk, disk)).toBe(false)
|
||||
})
|
||||
|
||||
it('does re-sync when disk content actually changes externally', () => {
|
||||
const oldDisk = 'Line one\nLine two'
|
||||
const newDisk = 'Line one\nLine two\nLine three'
|
||||
const normalizedCurrentMarkdown = simulateOnCreate(oldDisk)
|
||||
|
||||
expect(shouldSyncPropIntoEditor(normalizedCurrentMarkdown, newDisk, oldDisk)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// 4. Actual user edits must still be detected as dirty.
|
||||
// -----------------------------------------------------------------------
|
||||
describe('real edits are detected as dirty', () => {
|
||||
it('ProseMirror transaction produces a dirty diff', () => {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { editor } from 'monaco-editor'
|
||||
|
||||
/**
|
||||
* Overwrite a Monaco model's text via pushEditOperations so the change
|
||||
* participates in the undo stack (unlike setValue, which blows it away).
|
||||
*/
|
||||
function replaceModelContent(
|
||||
editorInstance: editor.IStandaloneCodeEditor,
|
||||
model: editor.ITextModel,
|
||||
content: string,
|
||||
withUndoStops: boolean
|
||||
): void {
|
||||
if (model.getValue() === content) {
|
||||
return
|
||||
}
|
||||
const fullRange = model.getFullModelRange()
|
||||
if (withUndoStops) {
|
||||
editorInstance.pushUndoStop()
|
||||
}
|
||||
model.pushEditOperations([], [{ range: fullRange, text: content }], () => null)
|
||||
if (withUndoStops) {
|
||||
editorInstance.pushUndoStop()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile a freshly-mounted editor's retained model against the current
|
||||
* `content`. Used from handleMount.
|
||||
*
|
||||
* Why: `keepCurrentModel` retains Monaco models across unmounts so undo/redo
|
||||
* survives tab switches. But @monaco-editor/react skips its value→model sync
|
||||
* on the first render after a remount and reuses the retained model — so
|
||||
* external changes that arrived while the tab was unmounted are invisible
|
||||
* until we explicitly push them into the model here.
|
||||
*/
|
||||
export function syncContentOnMount(
|
||||
editorInstance: editor.IStandaloneCodeEditor,
|
||||
content: string
|
||||
): boolean {
|
||||
const model = editorInstance.getModel()
|
||||
if (!model) {
|
||||
return false
|
||||
}
|
||||
if (model.getValue() === content) {
|
||||
return false
|
||||
}
|
||||
// Why: no undo stop on mount — the retained model's text was already the
|
||||
// user's last-known state, and adding an undo entry here would make Cmd+Z
|
||||
// revert to the pre-remount text, which is confusing.
|
||||
replaceModelContent(editorInstance, model, content, false)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a prop-driven content change into the live model. Used from a
|
||||
* useEffect that runs whenever `content` changes.
|
||||
*
|
||||
* Why: handles the live-mount update path — external file changes that
|
||||
* arrive while the editor stays mounted. The emitted-content short-circuit
|
||||
* is done at the call site before invoking this.
|
||||
*/
|
||||
export function syncContentUpdate(
|
||||
editorInstance: editor.IStandaloneCodeEditor,
|
||||
content: string
|
||||
): void {
|
||||
const model = editorInstance.getModel()
|
||||
if (!model) {
|
||||
return
|
||||
}
|
||||
replaceModelContent(editorInstance, model, content, true)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
beginProgrammaticContentSync,
|
||||
endProgrammaticContentSync,
|
||||
resetProgrammaticContentSyncForTests,
|
||||
shouldIgnoreMonacoContentChange
|
||||
} from './monaco-programmatic-sync'
|
||||
|
||||
afterEach(() => {
|
||||
resetProgrammaticContentSyncForTests()
|
||||
})
|
||||
|
||||
describe('shouldIgnoreMonacoContentChange', () => {
|
||||
it('ignores echoed shared-model changes in the sibling split pane', () => {
|
||||
const filePath = '/repo/seed.spec.ts'
|
||||
|
||||
beginProgrammaticContentSync(filePath)
|
||||
try {
|
||||
expect(
|
||||
shouldIgnoreMonacoContentChange({
|
||||
filePath,
|
||||
isApplyingProgrammaticContent: false
|
||||
})
|
||||
).toBe(true)
|
||||
} finally {
|
||||
endProgrammaticContentSync(filePath)
|
||||
}
|
||||
})
|
||||
|
||||
it('ignores local programmatic sync even without a sibling pane', () => {
|
||||
expect(
|
||||
shouldIgnoreMonacoContentChange({
|
||||
filePath: '/repo/seed.spec.ts',
|
||||
isApplyingProgrammaticContent: true
|
||||
})
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('does not ignore a real user edit once programmatic sync is finished', () => {
|
||||
expect(
|
||||
shouldIgnoreMonacoContentChange({
|
||||
filePath: '/repo/seed.spec.ts',
|
||||
isApplyingProgrammaticContent: false
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('does not ignore a user edit that happens to match the saved prop content', () => {
|
||||
expect(
|
||||
shouldIgnoreMonacoContentChange({
|
||||
filePath: '/repo/seed.spec.ts',
|
||||
isApplyingProgrammaticContent: false
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,37 @@
|
||||
const programmaticContentSyncDepthByFilePath = new Map<string, number>()
|
||||
|
||||
export function beginProgrammaticContentSync(filePath: string): void {
|
||||
programmaticContentSyncDepthByFilePath.set(
|
||||
filePath,
|
||||
(programmaticContentSyncDepthByFilePath.get(filePath) ?? 0) + 1
|
||||
)
|
||||
}
|
||||
|
||||
export function endProgrammaticContentSync(filePath: string): void {
|
||||
const depth = programmaticContentSyncDepthByFilePath.get(filePath) ?? 0
|
||||
if (depth <= 1) {
|
||||
programmaticContentSyncDepthByFilePath.delete(filePath)
|
||||
return
|
||||
}
|
||||
programmaticContentSyncDepthByFilePath.set(filePath, depth - 1)
|
||||
}
|
||||
|
||||
export function isProgrammaticContentSyncInFlight(filePath: string): boolean {
|
||||
return (programmaticContentSyncDepthByFilePath.get(filePath) ?? 0) > 0
|
||||
}
|
||||
|
||||
export function shouldIgnoreMonacoContentChange(args: {
|
||||
filePath: string
|
||||
isApplyingProgrammaticContent: boolean
|
||||
}): boolean {
|
||||
const { filePath, isApplyingProgrammaticContent } = args
|
||||
|
||||
// Why: split panes can share one retained Monaco model by file path. If any
|
||||
// pane is currently reconciling prop content into that shared model, every
|
||||
// pane sees the echoed change event and must treat it as programmatic.
|
||||
return isApplyingProgrammaticContent || isProgrammaticContentSyncInFlight(filePath)
|
||||
}
|
||||
|
||||
export function resetProgrammaticContentSyncForTests(): void {
|
||||
programmaticContentSyncDepthByFilePath.clear()
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import type React from 'react'
|
||||
import type { editor } from 'monaco-editor'
|
||||
import { computeMonacoRevealRange } from './monaco-reveal-range'
|
||||
|
||||
/**
|
||||
* Shared reveal logic used by both onMount and useEffect paths in MonacoEditor.
|
||||
* Positions the cursor, optionally selects the match range, scrolls into center,
|
||||
* and applies a transient inline highlight decoration that clears after 1.2s.
|
||||
*/
|
||||
export function performReveal(
|
||||
ed: editor.IStandaloneCodeEditor,
|
||||
line: number,
|
||||
column: number,
|
||||
matchLength: number,
|
||||
clearTransientRevealHighlight: () => void,
|
||||
revealDecorationRef: React.RefObject<editor.IEditorDecorationsCollection | null>,
|
||||
revealHighlightTimerRef: React.RefObject<ReturnType<typeof setTimeout> | null>
|
||||
): void {
|
||||
const model = ed.getModel()
|
||||
if (!model) {
|
||||
ed.focus()
|
||||
return
|
||||
}
|
||||
|
||||
const range = computeMonacoRevealRange({
|
||||
line,
|
||||
column,
|
||||
matchLength,
|
||||
maxLine: model.getLineCount(),
|
||||
lineMaxColumn: model.getLineMaxColumn(Math.min(Math.max(1, line), model.getLineCount()))
|
||||
})
|
||||
const shouldHighlight = matchLength > 0
|
||||
|
||||
ed.setPosition({ lineNumber: range.startLineNumber, column: range.startColumn })
|
||||
if (shouldHighlight) {
|
||||
ed.setSelection(range)
|
||||
ed.revealRangeInCenter(range)
|
||||
} else {
|
||||
ed.setSelection({
|
||||
startLineNumber: range.startLineNumber,
|
||||
startColumn: range.startColumn,
|
||||
endLineNumber: range.startLineNumber,
|
||||
endColumn: range.startColumn
|
||||
})
|
||||
ed.revealPositionInCenter({ lineNumber: range.startLineNumber, column: range.startColumn })
|
||||
}
|
||||
|
||||
clearTransientRevealHighlight()
|
||||
if (shouldHighlight) {
|
||||
revealDecorationRef.current = ed.createDecorationsCollection([
|
||||
{
|
||||
range,
|
||||
options: {
|
||||
inlineClassName: 'monaco-search-result-highlight',
|
||||
stickiness: 1
|
||||
}
|
||||
}
|
||||
])
|
||||
revealHighlightTimerRef.current = setTimeout(() => {
|
||||
revealDecorationRef.current?.clear()
|
||||
revealDecorationRef.current = null
|
||||
revealHighlightTimerRef.current = null
|
||||
}, 1200)
|
||||
}
|
||||
|
||||
ed.focus()
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { DOMSerializer } from '@tiptap/pm/model'
|
||||
import { TextSelection } from '@tiptap/pm/state'
|
||||
import type { EditorView } from '@tiptap/pm/view'
|
||||
import { cutVisualLine, getVisualLineRange } from './rich-markdown-visual-line'
|
||||
|
||||
function deleteBlockAndRestoreSelection(view: EditorView, from: number, to: number): void {
|
||||
let tr = view.state.tr.delete(from, to)
|
||||
// Why: after deleting the last block the old `from` offset may exceed
|
||||
// the new document length, so we clamp and use TextSelection.near() to
|
||||
// land on the closest valid cursor position.
|
||||
const clampedPos = Math.max(0, Math.min(from, tr.doc.content.size))
|
||||
tr = tr.setSelection(TextSelection.near(tr.doc.resolve(clampedPos)))
|
||||
view.dispatch(tr)
|
||||
}
|
||||
|
||||
/**
|
||||
* Why: Electron's app menu `{ role: 'cut' }` binds Cmd/Ctrl+X at the
|
||||
* main-process level, so the keystroke never reaches handleKeyDown.
|
||||
* Instead, the menu dispatches a native cut command which fires this
|
||||
* DOM event. For empty selections we cut the current block (like VS
|
||||
* Code and Notion); for non-empty selections we defer to ProseMirror's
|
||||
* built-in clipboard serializer.
|
||||
*/
|
||||
export function handleRichMarkdownCut(view: EditorView, event: ClipboardEvent): boolean {
|
||||
const { selection } = view.state
|
||||
if (!selection.empty) {
|
||||
return false
|
||||
}
|
||||
|
||||
const { $from } = selection
|
||||
|
||||
// Why: a GapCursor before a top-level leaf node (e.g. horizontal rule
|
||||
// as the first child of the doc) resolves to depth 0. Attempting to cut
|
||||
// at depth 0 would call $from.before(0) on the doc node, which throws
|
||||
// RangeError("There is no position before the top-level node"). Bail
|
||||
// out and let ProseMirror's default handler deal with it.
|
||||
if ($from.depth < 1) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Walk up from the textblock to find the best node to cut. For list
|
||||
// items and task items, cut the whole item rather than just its inner
|
||||
// paragraph. Stop at table cells to avoid breaking table structure.
|
||||
let cutDepth = $from.depth
|
||||
for (let d = $from.depth - 1; d >= 1; d--) {
|
||||
const name = $from.node(d).type.name
|
||||
if (name === 'listItem' || name === 'taskItem') {
|
||||
cutDepth = d
|
||||
break
|
||||
}
|
||||
if (name === 'tableCell' || name === 'tableHeader') {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const cutNode = $from.node(cutDepth)
|
||||
const text = cutNode.textContent
|
||||
|
||||
// Why: for paragraphs that word-wrap across multiple visual lines, cut
|
||||
// only the visual line the cursor is on rather than the entire paragraph.
|
||||
// This matches the user expectation of per-line cutting (like VS Code)
|
||||
// without destroying the rest of the paragraph's content.
|
||||
if (cutNode.type.name === 'paragraph' && text) {
|
||||
const paraStart = $from.start(cutDepth)
|
||||
const paraEnd = $from.end(cutDepth)
|
||||
const lineRange = getVisualLineRange(view, selection.from, paraStart, paraEnd)
|
||||
if (lineRange) {
|
||||
return cutVisualLine(view, event, lineRange)
|
||||
}
|
||||
// Falls through to block-level cut for single-line paragraphs.
|
||||
}
|
||||
|
||||
if (!text) {
|
||||
// Still delete the empty block, matching VS Code behavior
|
||||
event.preventDefault()
|
||||
deleteBlockAndRestoreSelection(view, $from.before(cutDepth), $from.after(cutDepth))
|
||||
return true
|
||||
}
|
||||
|
||||
// Why: if clipboardData is null (e.g. synthetic events), we must not
|
||||
// preventDefault and then delete -- that would lose content without
|
||||
// placing it on the clipboard. Fall back to browser default instead.
|
||||
if (!event.clipboardData) {
|
||||
return false
|
||||
}
|
||||
event.preventDefault()
|
||||
|
||||
// Why: writing both text/html and text/plain preserves inline formatting
|
||||
// (bold, italic, links) on round-trip cut-then-paste, while still giving
|
||||
// a plain-text fallback for external targets.
|
||||
const serializer = DOMSerializer.fromSchema(view.state.schema)
|
||||
const fragment = serializer.serializeFragment(cutNode.content)
|
||||
const div = document.createElement('div')
|
||||
div.appendChild(fragment)
|
||||
event.clipboardData.setData('text/html', div.innerHTML)
|
||||
event.clipboardData.setData('text/plain', text)
|
||||
|
||||
deleteBlockAndRestoreSelection(view, $from.before(cutDepth), $from.after(cutDepth))
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useCallback } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import type { Editor } from '@tiptap/react'
|
||||
import { extractIpcErrorMessage, getImageCopyDestination } from './rich-markdown-image-utils'
|
||||
|
||||
export function useLocalImagePick(editor: Editor | null, filePath: string): () => Promise<void> {
|
||||
return useCallback(async () => {
|
||||
if (!editor) {
|
||||
return
|
||||
}
|
||||
// Why: the native file picker steals focus from the editor, which can cause
|
||||
// ProseMirror to lose track of its selection. We snapshot the cursor position
|
||||
// before the async dialog so we can insert the image exactly where the user
|
||||
// intended, not at whatever position focus() falls back to afterward.
|
||||
const insertPos = editor.state.selection.from
|
||||
try {
|
||||
const srcPath = await window.api.shell.pickImage()
|
||||
if (!srcPath) {
|
||||
return
|
||||
}
|
||||
// Why: copy the image next to the markdown file and insert a relative path
|
||||
// so the markdown stays portable and doesn't bloat with base64 data.
|
||||
const { imageName, destPath } = await getImageCopyDestination(filePath, srcPath)
|
||||
if (srcPath !== destPath) {
|
||||
await window.api.shell.copyFile({ srcPath, destPath })
|
||||
}
|
||||
// Why: insertContentAt places the image at the exact saved position
|
||||
// regardless of where focus lands after the native file dialog closes,
|
||||
// whereas setTextSelection can be overridden by ProseMirror's focus logic.
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.insertContentAt(insertPos, { type: 'image', attrs: { src: imageName } })
|
||||
.run()
|
||||
} catch (err) {
|
||||
toast.error(extractIpcErrorMessage(err, 'Failed to insert image.'))
|
||||
}
|
||||
}, [editor, filePath])
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getExternalFileChangeRelativePath } from './useFileExplorerWatch'
|
||||
|
||||
describe('getExternalFileChangeRelativePath', () => {
|
||||
it('returns a worktree-relative file path for external file updates', () => {
|
||||
expect(getExternalFileChangeRelativePath('/repo', '/repo/config/settings.json', false)).toBe(
|
||||
'config/settings.json'
|
||||
)
|
||||
})
|
||||
|
||||
it('ignores directory events so only file tabs reload', () => {
|
||||
expect(getExternalFileChangeRelativePath('/repo', '/repo/config', true)).toBeNull()
|
||||
})
|
||||
|
||||
it('treats isDirectory=undefined as a file so delete events still notify', () => {
|
||||
// Why: delete events from the watcher arrive with isDirectory=undefined
|
||||
// because the path no longer exists on disk (design §4.4). Gating on
|
||||
// `isDirectory !== true` ensures the editor is still notified so stale
|
||||
// tab contents get invalidated.
|
||||
expect(
|
||||
getExternalFileChangeRelativePath('/repo', '/repo/config/settings.json', undefined)
|
||||
).toBe('config/settings.json')
|
||||
})
|
||||
|
||||
it('normalizes Windows separators before deriving the relative path', () => {
|
||||
expect(
|
||||
getExternalFileChangeRelativePath('C:\\repo', 'C:\\repo\\config\\settings.json', false)
|
||||
).toBe('config/settings.json')
|
||||
})
|
||||
|
||||
it('ignores paths outside the active worktree', () => {
|
||||
expect(
|
||||
getExternalFileChangeRelativePath('/repo', '/other/config/settings.json', false)
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects sibling worktrees whose path merely shares a prefix', () => {
|
||||
// Why: string-prefix checks without a trailing separator would match
|
||||
// `/repo-other/...` as if it were inside `/repo`, leaking events across
|
||||
// worktrees.
|
||||
expect(getExternalFileChangeRelativePath('/repo', '/repo-other/file.ts', false)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when the changed path is the worktree root itself', () => {
|
||||
expect(getExternalFileChangeRelativePath('/repo', '/repo', false)).toBeNull()
|
||||
})
|
||||
|
||||
it('tolerates a trailing slash on the worktree path', () => {
|
||||
expect(getExternalFileChangeRelativePath('/repo/', '/repo/src/index.ts', false)).toBe(
|
||||
'src/index.ts'
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves nested segments in the returned relative path', () => {
|
||||
expect(getExternalFileChangeRelativePath('/repo', '/repo/a/b/c/deep.ts', false)).toBe(
|
||||
'a/b/c/deep.ts'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -3,9 +3,9 @@ import type { Dispatch, SetStateAction } from 'react'
|
||||
import type { FsChangedPayload } from '../../../../shared/types'
|
||||
import type { DirCache } from './file-explorer-types'
|
||||
import type { InlineInput } from './FileExplorerRow'
|
||||
import { normalizeRelativePath } from '@/lib/path'
|
||||
import { normalizeAbsolutePath } from './file-explorer-paths'
|
||||
import { dirname } from '@/lib/path'
|
||||
import { getConnectionId } from '@/lib/connection-context'
|
||||
import {
|
||||
purgeDirCacheSubtree,
|
||||
purgeExpandedDirsSubtree,
|
||||
@@ -25,12 +25,46 @@ type UseFileExplorerWatchParams = {
|
||||
dragSourcePath: string | null
|
||||
}
|
||||
|
||||
export function getExternalFileChangeRelativePath(
|
||||
worktreePath: string,
|
||||
absolutePath: string,
|
||||
isDirectory: boolean | undefined
|
||||
): string | null {
|
||||
if (isDirectory === true) {
|
||||
return null
|
||||
}
|
||||
|
||||
const normalizedWorktreePath = normalizeAbsolutePath(worktreePath)
|
||||
const normalizedAbsolutePath = normalizeAbsolutePath(absolutePath)
|
||||
// Why: `normalizeAbsolutePath` preserves the trailing slash for filesystem
|
||||
// roots (`/` on POSIX, `C:/` on Windows drive roots) but strips it from all
|
||||
// other paths. Blindly appending `/` would produce `//` or `C://`, so
|
||||
// external edits under a root worktree would fail the prefix check and be
|
||||
// silently dropped. Treat those roots as already-terminated prefixes.
|
||||
const isFsRoot = normalizedWorktreePath === '/' || /^[A-Za-z]:\/$/.test(normalizedWorktreePath)
|
||||
const worktreePrefix = isFsRoot ? normalizedWorktreePath : `${normalizedWorktreePath}/`
|
||||
|
||||
if (!normalizedAbsolutePath.startsWith(worktreePrefix)) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Why: EditorPanel only reloads open tabs after the renderer emits
|
||||
// `orca:editor-external-file-change` with a worktree-relative path. The
|
||||
// filesystem watcher reports absolute paths, so normalize them here before
|
||||
// the explorer refresh path returns; otherwise terminal edits refresh the
|
||||
// tree but leave the editor's cached file contents stale.
|
||||
return normalizeRelativePath(normalizedAbsolutePath.slice(worktreePrefix.length))
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes to filesystem watcher events for the active worktree and
|
||||
* reconciles File Explorer state on external changes.
|
||||
* Reconciles File Explorer state on filesystem events for the active worktree.
|
||||
*
|
||||
* Why: the renderer must explicitly tell main which worktree to watch
|
||||
* because activeWorktreeId is renderer-local Zustand state (design §4.2).
|
||||
* Why: `useEditorExternalWatch` (invoked once from App.tsx) owns the
|
||||
* `watchWorktree` / `unwatchWorktree` IPC lifecycle so editor reloads keep
|
||||
* firing even when the Explorer panel is unmounted (user switched to Source
|
||||
* Control, Checks, or Search). This hook just subscribes to the shared
|
||||
* `fs:changed` stream and filters to the active worktree for tree-cache
|
||||
* reconciliation.
|
||||
*/
|
||||
export function useFileExplorerWatch({
|
||||
worktreePath,
|
||||
@@ -75,6 +109,13 @@ export function useFileExplorerWatch({
|
||||
// Deferred events queue: events that arrive during inline input or drag
|
||||
const deferredRef = useRef<FsChangedPayload[]>([])
|
||||
|
||||
// Why: the flush effect (below) lives outside the subscribe effect that
|
||||
// owns `processPayload`, but it needs to replay deferred payloads so the
|
||||
// tree-cache reconciliation (design §6.2) converges on disk reality even
|
||||
// when events arrived during inline input or drag. A ref bridges the two
|
||||
// effects without tearing the subscription down on every render.
|
||||
const processPayloadRef = useRef<((payload: FsChangedPayload) => void) | null>(null)
|
||||
|
||||
// ── Subscribe, process events, and unsubscribe in one atomic effect ──
|
||||
// Why: merging the subscribe/unsubscribe effect and the event-processing
|
||||
// effect into a single useEffect eliminates a race where events from a
|
||||
@@ -89,9 +130,6 @@ export function useFileExplorerWatch({
|
||||
|
||||
const currentWorktreePath = worktreePath
|
||||
|
||||
const connectionId = getConnectionId(activeWorktreeId ?? null) ?? undefined
|
||||
void window.api.fs.watchWorktree({ worktreePath, connectionId })
|
||||
|
||||
function processPayload(payload: FsChangedPayload): void {
|
||||
// Why: during rapid worktree switches, in-flight batched events from
|
||||
// the old worktree can arrive after the switch. Processing them against
|
||||
@@ -171,7 +209,6 @@ export function useFileExplorerWatch({
|
||||
dirsToRefresh.add(normalizedPath)
|
||||
}
|
||||
}
|
||||
// File updates: ignored in v1
|
||||
}
|
||||
// 'rename' is deferred to v2 (design §5.3)
|
||||
}
|
||||
@@ -195,6 +232,10 @@ export function useFileExplorerWatch({
|
||||
}
|
||||
}
|
||||
|
||||
// Why: expose `processPayload` to the flush effect so it can replay
|
||||
// deferred payloads without re-subscribing the IPC listener.
|
||||
processPayloadRef.current = processPayload
|
||||
|
||||
const handleFsChanged = (payload: FsChangedPayload): void => {
|
||||
// Why: defer watcher-triggered refreshes while inline input or drag-drop
|
||||
// is active to avoid displacing the inline input row or shifting rows
|
||||
@@ -211,8 +252,8 @@ export function useFileExplorerWatch({
|
||||
|
||||
return () => {
|
||||
unsubscribeListener()
|
||||
void window.api.fs.unwatchWorktree({ worktreePath, connectionId })
|
||||
deferredRef.current = []
|
||||
processPayloadRef.current = null
|
||||
}
|
||||
}, [worktreePath, activeWorktreeId, setDirCache, setSelectedPath])
|
||||
|
||||
@@ -220,14 +261,23 @@ export function useFileExplorerWatch({
|
||||
useEffect(() => {
|
||||
if (inlineInput === null && dragSourcePath === null && deferredRef.current.length > 0) {
|
||||
const deferred = deferredRef.current.splice(0)
|
||||
// Re-process all deferred payloads now that the interaction is over.
|
||||
// We trigger a simple refresh of all visible dirs since the deferred
|
||||
// events may be stale and coalescing them is complex.
|
||||
// Why: replay every deferred payload through `processPayload` so the
|
||||
// tree cache reconciles to disk state after inline input or drag ends
|
||||
// (design §6.2). Editor-tab reloads are handled independently by
|
||||
// `useEditorExternalWatch`, which listens to the same fs:changed
|
||||
// stream at App-level and is not affected by Explorer deferral.
|
||||
if (processPayloadRef.current) {
|
||||
for (const payload of deferred) {
|
||||
processPayloadRef.current(payload)
|
||||
}
|
||||
}
|
||||
// Why: also trigger a tree refresh as a safety net. Deferred events may
|
||||
// have been coalesced by the watcher or become stale during the defer
|
||||
// window, and a full refresh guarantees the explorer state converges on
|
||||
// disk reality even if individual event replay misses a subtree.
|
||||
if (worktreePath) {
|
||||
void refreshTreeRef.current()
|
||||
}
|
||||
// Clear the deferred queue (already spliced)
|
||||
void deferred
|
||||
}
|
||||
}, [inlineInput, dragSourcePath, worktreePath])
|
||||
}
|
||||
|
||||
@@ -254,7 +254,7 @@ export default function EditorFileTab({
|
||||
/>
|
||||
) : (
|
||||
<span
|
||||
className={`truncate max-w-[130px]${file.isPreview ? ' italic' : ''}`}
|
||||
className={`truncate max-w-[130px]${file.isPreview ? ' italic' : ''}${file.externalMutation ? ' line-through' : ''}`}
|
||||
style={tabStatusColor ? { color: tabStatusColor } : undefined}
|
||||
onDoubleClick={(e) => {
|
||||
// Why: the outer tab's onDoubleClick pins preview tabs. Scope
|
||||
@@ -270,7 +270,12 @@ export default function EditorFileTab({
|
||||
{getEditorDisplayLabel(file)}
|
||||
</span>
|
||||
)}
|
||||
{tabStatus && !isRenaming && (
|
||||
{file.externalMutation && !isRenaming && (
|
||||
<span className="shrink-0 text-[10px] leading-none font-semibold tracking-wide text-muted-foreground">
|
||||
{file.externalMutation}
|
||||
</span>
|
||||
)}
|
||||
{tabStatus && !isRenaming && !file.externalMutation && (
|
||||
<span
|
||||
className="shrink-0 text-[10px] leading-none font-semibold tracking-wide"
|
||||
style={{ color: tabStatusColor }}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { getOverflowExternalReloadTargets } from './useEditorExternalWatch'
|
||||
import { useAppStore } from '@/store'
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: {
|
||||
getState: vi.fn()
|
||||
}
|
||||
}))
|
||||
|
||||
describe('getOverflowExternalReloadTargets', () => {
|
||||
const setExternalMutation = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('clears tombstones and reloads clean edit tabs on overflow', () => {
|
||||
vi.mocked(useAppStore.getState).mockReturnValue({
|
||||
openFiles: [
|
||||
{
|
||||
id: 'file-1',
|
||||
worktreeId: 'wt-1',
|
||||
worktreePath: '/repo',
|
||||
relativePath: 'notes.md',
|
||||
mode: 'edit',
|
||||
isDirty: false,
|
||||
externalMutation: 'deleted'
|
||||
},
|
||||
{
|
||||
id: 'file-2',
|
||||
worktreeId: 'wt-1',
|
||||
worktreePath: '/repo',
|
||||
relativePath: 'dirty.md',
|
||||
mode: 'edit',
|
||||
isDirty: true
|
||||
},
|
||||
{
|
||||
id: 'file-3',
|
||||
worktreeId: 'wt-1',
|
||||
worktreePath: '/repo',
|
||||
relativePath: 'staged.ts',
|
||||
mode: 'diff',
|
||||
diffSource: 'staged',
|
||||
isDirty: false
|
||||
}
|
||||
],
|
||||
setExternalMutation
|
||||
} as never)
|
||||
|
||||
expect(
|
||||
getOverflowExternalReloadTargets({
|
||||
worktreeId: 'wt-1',
|
||||
worktreePath: '/repo'
|
||||
})
|
||||
).toEqual([
|
||||
{
|
||||
worktreeId: 'wt-1',
|
||||
worktreePath: '/repo',
|
||||
relativePath: 'notes.md'
|
||||
}
|
||||
])
|
||||
expect(setExternalMutation).toHaveBeenCalledWith('file-1', null)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,353 @@
|
||||
import { useEffect, useMemo, useRef } from 'react'
|
||||
import { useAppStore } from '@/store'
|
||||
import { getConnectionId } from '@/lib/connection-context'
|
||||
import { basename } from '@/lib/path'
|
||||
import { normalizeAbsolutePath } from '@/components/right-sidebar/file-explorer-paths'
|
||||
import { getExternalFileChangeRelativePath } from '@/components/right-sidebar/useFileExplorerWatch'
|
||||
import {
|
||||
getOpenFilesForExternalFileChange,
|
||||
notifyEditorExternalFileChange
|
||||
} from '@/components/editor/editor-autosave'
|
||||
import type { FsChangedPayload } from '../../../shared/types'
|
||||
import { findWorktreeById } from '@/store/slices/worktree-helpers'
|
||||
|
||||
type WatchedTarget = {
|
||||
worktreeId: string
|
||||
worktreePath: string
|
||||
connectionId: string | undefined
|
||||
}
|
||||
|
||||
type ExternalWatchNotification = {
|
||||
worktreeId: string
|
||||
worktreePath: string
|
||||
relativePath: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes to filesystem watcher events for every worktree that currently
|
||||
* has an editor tab open, and notifies the editor to reload clean tabs when
|
||||
* their on-disk contents change.
|
||||
*
|
||||
* Why: the File Explorer panel's watcher hook is unmounted whenever the user
|
||||
* switches the right sidebar to Source Control / Checks / Search. Relying on
|
||||
* that panel to dispatch editor-reload notifications means terminal edits go
|
||||
* unnoticed while any non-Explorer sidebar tab is active. Lifting the
|
||||
* editor-reload subscription to an always-mounted hook mirrors VSCode's
|
||||
* `TextFileEditorModelManager`, which subscribes to `fileService
|
||||
* .onDidFilesChange` once at the workbench level and reloads non-dirty models
|
||||
* regardless of which UI panel is visible.
|
||||
*/
|
||||
export function useEditorExternalWatch(): void {
|
||||
const openFiles = useAppStore((s) => s.openFiles)
|
||||
const worktreesByRepo = useAppStore((s) => s.worktreesByRepo)
|
||||
const activeWorktreeId = useAppStore((s) => s.activeWorktreeId)
|
||||
|
||||
// Why: unify the target computation and the dependency key into one memo so
|
||||
// there's a single source of truth. The derived string key drives the
|
||||
// watch-diff effect; the array itself is what the effect actually iterates.
|
||||
const { targets, targetsKey } = useMemo(() => {
|
||||
const ids = new Set<string>()
|
||||
// Why: watch every worktree that has an editor tab open, so terminal edits
|
||||
// in any of those roots reach the editor. Also watch the active worktree
|
||||
// even when it has no open files — otherwise the File Explorer's tree
|
||||
// reconciliation loses its event stream the moment the last tab for that
|
||||
// worktree is closed.
|
||||
for (const f of openFiles) {
|
||||
ids.add(f.worktreeId)
|
||||
}
|
||||
if (activeWorktreeId) {
|
||||
ids.add(activeWorktreeId)
|
||||
}
|
||||
const nextTargets: WatchedTarget[] = []
|
||||
const parts: string[] = []
|
||||
for (const id of Array.from(ids).sort()) {
|
||||
const wt = findWorktreeById(worktreesByRepo, id)
|
||||
if (!wt) {
|
||||
continue
|
||||
}
|
||||
nextTargets.push({
|
||||
worktreeId: id,
|
||||
worktreePath: wt.path,
|
||||
connectionId: getConnectionId(id) ?? undefined
|
||||
})
|
||||
parts.push(`${id}::${wt.path}`)
|
||||
}
|
||||
return { targets: nextTargets, targetsKey: parts.join('|') }
|
||||
}, [openFiles, worktreesByRepo, activeWorktreeId])
|
||||
|
||||
const targetsRef = useRef<WatchedTarget[]>([])
|
||||
const latestTargetsRef = useRef<WatchedTarget[]>(targets)
|
||||
latestTargetsRef.current = targets
|
||||
|
||||
// Why: diff previous vs next targets so unchanged worktrees keep their
|
||||
// existing subscription. Tearing down every subscription on each targetsKey
|
||||
// change (e.g. opening/closing a tab in an already-watched worktree) causes
|
||||
// a watcher churn that can drop events emitted during the gap.
|
||||
useEffect(() => {
|
||||
const nextTargets = latestTargetsRef.current
|
||||
const prev = targetsRef.current
|
||||
const prevIds = new Set(prev.map((t) => t.worktreeId))
|
||||
const nextIds = new Set(nextTargets.map((t) => t.worktreeId))
|
||||
const removed = prev.filter((t) => !nextIds.has(t.worktreeId))
|
||||
const added = nextTargets.filter((t) => !prevIds.has(t.worktreeId))
|
||||
|
||||
for (const target of removed) {
|
||||
void window.api.fs.unwatchWorktree({
|
||||
worktreePath: target.worktreePath,
|
||||
connectionId: target.connectionId
|
||||
})
|
||||
}
|
||||
for (const target of added) {
|
||||
void window.api.fs.watchWorktree({
|
||||
worktreePath: target.worktreePath,
|
||||
connectionId: target.connectionId
|
||||
})
|
||||
}
|
||||
targetsRef.current = nextTargets
|
||||
// Why: this effect is intentionally differential — it does not unwatch on
|
||||
// cleanup. Final unmount unwatching lives in the separate [] effect below
|
||||
// so that re-running on targetsKey changes doesn't tear down everything.
|
||||
}, [targetsKey])
|
||||
|
||||
// Why: the fs:changed subscription and the final unmount unwatch are
|
||||
// independent of which worktrees are currently watched. Keeping them in a
|
||||
// single always-mounted effect avoids re-subscribing on every targetsKey
|
||||
// change (which would otherwise miss events fired during re-subscription).
|
||||
useEffect(() => {
|
||||
const handleFsChanged = (payload: FsChangedPayload): void => {
|
||||
const target = targetsRef.current.find(
|
||||
(t) => normalizeAbsolutePath(t.worktreePath) === normalizeAbsolutePath(payload.worktreePath)
|
||||
)
|
||||
if (!target) {
|
||||
return
|
||||
}
|
||||
|
||||
// Why: when an external process removes (or `git mv`s) a file that's
|
||||
// open in the editor, keep the tab alive and mark it as deleted/renamed
|
||||
// so the user can see the mutation and still access their in-memory
|
||||
// content. A paired create-event in the same batch signals a rename;
|
||||
// a lone delete is a hard delete. Resurrection (same path comes back
|
||||
// on disk) clears the mark further down.
|
||||
const deletedOpenEditorIds = collectDeletedOpenEditorIds(payload, target.worktreeId)
|
||||
// Why: correlate creates to deletes by basename OR parent directory to
|
||||
// avoid mislabelling unrelated create+delete pairs in a batched payload
|
||||
// as "renamed". When we can't correlate, default to 'deleted' — that's
|
||||
// the least misleading fallback (it preserves in-memory content and
|
||||
// doesn't claim a rename target that doesn't exist).
|
||||
const hasPairedCreate =
|
||||
deletedOpenEditorIds.length > 0 &&
|
||||
hasRenameCorrelatedCreate(payload, target.worktreeId, deletedOpenEditorIds)
|
||||
if (deletedOpenEditorIds.length > 0) {
|
||||
const setExternalMutation = useAppStore.getState().setExternalMutation
|
||||
const mutation = hasPairedCreate ? 'renamed' : 'deleted'
|
||||
for (const fileId of deletedOpenEditorIds) {
|
||||
setExternalMutation(fileId, mutation)
|
||||
}
|
||||
}
|
||||
|
||||
// Why: if a previously-deleted file reappears at the same path (e.g.
|
||||
// the user ran `git checkout`), clear the tombstone so the tab returns
|
||||
// to its normal state and any non-dirty content gets reloaded below.
|
||||
const createOrUpdatePaths = new Set<string>()
|
||||
for (const evt of payload.events) {
|
||||
if (evt.isDirectory === true) {
|
||||
continue
|
||||
}
|
||||
if (evt.kind === 'create' || evt.kind === 'update') {
|
||||
createOrUpdatePaths.add(normalizeAbsolutePath(evt.absolutePath))
|
||||
}
|
||||
}
|
||||
if (createOrUpdatePaths.size > 0) {
|
||||
const state = useAppStore.getState()
|
||||
for (const file of state.openFiles) {
|
||||
if (
|
||||
file.worktreeId === target.worktreeId &&
|
||||
file.mode === 'edit' &&
|
||||
file.externalMutation &&
|
||||
createOrUpdatePaths.has(normalizeAbsolutePath(file.filePath))
|
||||
) {
|
||||
state.setExternalMutation(file.id, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const changedFiles = new Set<string>()
|
||||
for (const evt of payload.events) {
|
||||
if (evt.kind === 'overflow') {
|
||||
// Why: overflow payloads omit per-path create/update info, so any
|
||||
// stale tombstone must be cleared conservatively before we decide
|
||||
// which clean tabs to reload. Otherwise a file that reappeared on
|
||||
// disk during the overrun stays struck through until some later
|
||||
// path-specific event happens to clear it.
|
||||
for (const notification of getOverflowExternalReloadTargets(target)) {
|
||||
notifyEditorExternalFileChange(notification)
|
||||
}
|
||||
// Why: `break` (not `return`) — the remaining code early-returns
|
||||
// when changedFiles is empty, so breaking out is semantically
|
||||
// equivalent and more robust to future code added after the loop.
|
||||
break
|
||||
}
|
||||
|
||||
if (evt.kind === 'update' && evt.isDirectory === true) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (evt.kind === 'delete') {
|
||||
// Why: delete events are already handled above by marking the tab
|
||||
// as tombstoned. Feeding them into the reload pipeline would fire
|
||||
// `readFile` against the ENOENT path and replace the in-memory
|
||||
// content with "Error loading file..." — losing the user's view.
|
||||
continue
|
||||
}
|
||||
|
||||
const relativePath = getExternalFileChangeRelativePath(
|
||||
target.worktreePath,
|
||||
normalizeAbsolutePath(evt.absolutePath),
|
||||
evt.isDirectory
|
||||
)
|
||||
if (relativePath) {
|
||||
changedFiles.add(relativePath)
|
||||
}
|
||||
}
|
||||
|
||||
if (changedFiles.size === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
// Why: skip notifying for any tab with unsaved edits so external writes
|
||||
// don't silently destroy the user's work. Mirrors the dirty guard in
|
||||
// `useFileExplorerHandlers`. Read `openFiles` once per payload to avoid
|
||||
// N store reads for large batched events.
|
||||
const openFilesSnapshot = useAppStore.getState().openFiles
|
||||
for (const relativePath of changedFiles) {
|
||||
const notification = {
|
||||
worktreeId: target.worktreeId,
|
||||
worktreePath: target.worktreePath,
|
||||
relativePath
|
||||
}
|
||||
const matching = getOpenFilesForExternalFileChange(openFilesSnapshot, notification)
|
||||
if (matching.length === 0) {
|
||||
continue
|
||||
}
|
||||
if (matching.some((f) => f.isDirty)) {
|
||||
continue
|
||||
}
|
||||
notifyEditorExternalFileChange(notification)
|
||||
}
|
||||
}
|
||||
|
||||
const unsubscribe = window.api.fs.onFsChanged(handleFsChanged)
|
||||
|
||||
return () => {
|
||||
unsubscribe()
|
||||
// Why: final unmount must tear down every outstanding subscription.
|
||||
// The differential watch effect above intentionally never unwatches on
|
||||
// cleanup, so this is the only place that clears them.
|
||||
for (const target of targetsRef.current) {
|
||||
void window.api.fs.unwatchWorktree({
|
||||
worktreePath: target.worktreePath,
|
||||
connectionId: target.connectionId
|
||||
})
|
||||
}
|
||||
targetsRef.current = []
|
||||
}
|
||||
}, [])
|
||||
}
|
||||
|
||||
export function getOverflowExternalReloadTargets(
|
||||
target: Pick<WatchedTarget, 'worktreeId' | 'worktreePath'>
|
||||
): ExternalWatchNotification[] {
|
||||
const state = useAppStore.getState()
|
||||
const notifications: ExternalWatchNotification[] = []
|
||||
|
||||
for (const file of state.openFiles) {
|
||||
if (file.worktreeId !== target.worktreeId || file.mode !== 'edit' || file.isDirty) {
|
||||
continue
|
||||
}
|
||||
if (file.externalMutation) {
|
||||
// Why: overflow gives no per-path resurrection signal, so fall back to
|
||||
// "assume it may exist again" and clear the tombstone before reloading.
|
||||
// If the file is still gone, EditorPanel will preserve the current in-
|
||||
// memory view by showing the read failure instead of leaving a permanent
|
||||
// stale "deleted" badge with no path to recovery.
|
||||
state.setExternalMutation(file.id, null)
|
||||
}
|
||||
notifications.push({
|
||||
worktreeId: target.worktreeId,
|
||||
worktreePath: target.worktreePath,
|
||||
relativePath: file.relativePath
|
||||
})
|
||||
}
|
||||
|
||||
return notifications
|
||||
}
|
||||
|
||||
function collectDeletedOpenEditorIds(payload: FsChangedPayload, worktreeId: string): string[] {
|
||||
const deletePaths = new Set<string>()
|
||||
for (const evt of payload.events) {
|
||||
if (evt.kind === 'delete') {
|
||||
deletePaths.add(normalizeAbsolutePath(evt.absolutePath))
|
||||
}
|
||||
}
|
||||
if (deletePaths.size === 0) {
|
||||
return []
|
||||
}
|
||||
const openFilesNow = useAppStore.getState().openFiles
|
||||
const result: string[] = []
|
||||
for (const file of openFilesNow) {
|
||||
if (file.worktreeId !== worktreeId || file.mode !== 'edit') {
|
||||
continue
|
||||
}
|
||||
if (deletePaths.has(normalizeAbsolutePath(file.filePath))) {
|
||||
result.push(file.id)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the batched payload contains at least one file-create event
|
||||
* whose basename matches a deleted open editor file.
|
||||
*
|
||||
* Why: a batched fs payload may include unrelated create+delete events. A
|
||||
* blanket `events.some(kind === 'create')` would mislabel those as renames.
|
||||
* Basename correlation catches the common `git mv` / `mv` case where the
|
||||
* filename survives the move. We intentionally do NOT correlate by parent
|
||||
* directory because editor save-as-temp patterns (`rm foo.md && touch
|
||||
* foo.md.new`) routinely put unrelated creates in the same dir as a delete,
|
||||
* which would produce false rename labels. When correlation fails the caller
|
||||
* falls back to 'deleted', which is the least misleading default.
|
||||
*/
|
||||
function hasRenameCorrelatedCreate(
|
||||
payload: FsChangedPayload,
|
||||
worktreeId: string,
|
||||
deletedOpenEditorIds: string[]
|
||||
): boolean {
|
||||
if (deletedOpenEditorIds.length === 0) {
|
||||
return false
|
||||
}
|
||||
const deletedIdSet = new Set(deletedOpenEditorIds)
|
||||
const openFilesNow = useAppStore.getState().openFiles
|
||||
const deletedBasenames = new Set<string>()
|
||||
for (const file of openFilesNow) {
|
||||
if (file.worktreeId !== worktreeId || file.mode !== 'edit') {
|
||||
continue
|
||||
}
|
||||
if (!deletedIdSet.has(file.id)) {
|
||||
continue
|
||||
}
|
||||
deletedBasenames.add(basename(normalizeAbsolutePath(file.filePath)))
|
||||
}
|
||||
if (deletedBasenames.size === 0) {
|
||||
return false
|
||||
}
|
||||
for (const evt of payload.events) {
|
||||
if (evt.kind !== 'create' || evt.isDirectory === true) {
|
||||
continue
|
||||
}
|
||||
if (deletedBasenames.has(basename(normalizeAbsolutePath(evt.absolutePath)))) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -98,6 +98,12 @@ export type OpenFile = {
|
||||
conflictReview?: ConflictReviewState
|
||||
isPreview?: boolean // preview tabs are replaced when another file is single-clicked
|
||||
isUntitled?: boolean // true for files created via "New Markdown" that haven't been renamed yet
|
||||
// Why: when an external process (e.g. `git mv`, `rm`) removes the file on
|
||||
// disk while it's open, we keep the tab around so the user can still see
|
||||
// (and potentially save) their in-memory content. The tab surfaces this as
|
||||
// a strikethrough label plus a "deleted"/"renamed" suffix. Cleared if the
|
||||
// file reappears on disk at its original path.
|
||||
externalMutation?: 'deleted' | 'renamed'
|
||||
mode: 'edit' | 'diff' | 'conflict-review'
|
||||
}
|
||||
|
||||
@@ -168,6 +174,7 @@ export type EditorSlice = {
|
||||
setActiveFile: (fileId: string) => void
|
||||
reorderFiles: (fileIds: string[]) => void
|
||||
markFileDirty: (fileId: string, dirty: boolean) => void
|
||||
setExternalMutation: (fileId: string, mutation: 'deleted' | 'renamed' | null) => void
|
||||
clearUntitled: (fileId: string) => void
|
||||
openDiff: (
|
||||
worktreeId: string,
|
||||
@@ -895,13 +902,43 @@ export const createEditorSlice: StateCreator<AppState, [], [], EditorSlice> = (s
|
||||
}),
|
||||
|
||||
markFileDirty: (fileId, dirty) =>
|
||||
set((s) => ({
|
||||
openFiles: s.openFiles.map((f) =>
|
||||
f.id === fileId
|
||||
? { ...f, isDirty: dirty, ...(dirty && f.isPreview ? { isPreview: undefined } : {}) }
|
||||
: f
|
||||
)
|
||||
})),
|
||||
set((s) => {
|
||||
// Why: typing fires this on every keystroke. Rebuilding openFiles
|
||||
// unconditionally thrashes every subscriber (EditorPanel → EditorContent
|
||||
// → MonacoEditor re-renders) and produced visible typing lag. Bail out
|
||||
// when the dirty bit is already the target value and the preview-promote
|
||||
// side effect is a no-op.
|
||||
const file = s.openFiles.find((f) => f.id === fileId)
|
||||
if (!file) {
|
||||
return s
|
||||
}
|
||||
const needsPreviewClear = dirty && file.isPreview
|
||||
if (file.isDirty === dirty && !needsPreviewClear) {
|
||||
return s
|
||||
}
|
||||
return {
|
||||
openFiles: s.openFiles.map((f) =>
|
||||
f.id === fileId
|
||||
? { ...f, isDirty: dirty, ...(needsPreviewClear ? { isPreview: undefined } : {}) }
|
||||
: f
|
||||
)
|
||||
}
|
||||
}),
|
||||
|
||||
setExternalMutation: (fileId, mutation) =>
|
||||
set((s) => {
|
||||
const file = s.openFiles.find((f) => f.id === fileId)
|
||||
if (!file) {
|
||||
return s
|
||||
}
|
||||
const next = mutation ?? undefined
|
||||
if (file.externalMutation === next) {
|
||||
return s
|
||||
}
|
||||
return {
|
||||
openFiles: s.openFiles.map((f) => (f.id === fileId ? { ...f, externalMutation: next } : f))
|
||||
}
|
||||
}),
|
||||
|
||||
clearUntitled: (fileId) =>
|
||||
set((s) => ({
|
||||
|
||||
Reference in New Issue
Block a user