From 0cf0bbaab49214098e75d25d749f2bbd7c5afabe Mon Sep 17 00:00:00 2001 From: Yax Patel <74978532+ypatel2022@users.noreply.github.com> Date: Sun, 5 Apr 2026 13:29:29 -0400 Subject: [PATCH] feat: add autosaving (#300) --- src/main/persistence.test.ts | 52 +++ src/renderer/src/components/Terminal.tsx | 34 +- .../src/components/editor/EditorPanel.tsx | 349 +++++++++++++++--- .../components/editor/editor-autosave.test.ts | 164 ++++++++ .../src/components/editor/editor-autosave.ts | 95 +++++ .../right-sidebar/SourceControl.tsx | 21 +- .../right-sidebar/useFileDeletion.ts | 10 +- .../src/components/settings/GeneralPane.tsx | 99 +++++ .../src/components/settings/Settings.tsx | 2 +- .../terminal/useTerminalSaveDialog.ts | 6 +- src/renderer/src/lib/terminal-links.ts | 12 +- src/shared/constants.ts | 5 + src/shared/types.ts | 2 + 13 files changed, 786 insertions(+), 65 deletions(-) create mode 100644 src/renderer/src/components/editor/editor-autosave.test.ts create mode 100644 src/renderer/src/components/editor/editor-autosave.ts diff --git a/src/main/persistence.test.ts b/src/main/persistence.test.ts index b6c9b220d..1983dc642 100644 --- a/src/main/persistence.test.ts +++ b/src/main/persistence.test.ts @@ -1,3 +1,6 @@ +/* eslint-disable max-lines -- Why: this persistence suite keeps defaulting, +migration, mutation, and flush behavior in one file so schema changes are +reviewed against the full storage contract instead of being scattered. */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { writeFileSync, readFileSync, rmSync, mkdtempSync, mkdirSync } from 'fs' import { join } from 'path' @@ -67,6 +70,8 @@ describe('Store', () => { const settings = store.getSettings() expect(settings.branchPrefix).toBe('git-username') expect(settings.theme).toBe('system') + expect(settings.editorAutoSave).toBe(false) + expect(settings.editorAutoSaveDelayMs).toBe(1000) expect(settings.terminalFontSize).toBe(14) expect(settings.terminalFontWeight).toBe(500) expect(settings.rightSidebarOpenByDefault).toBe(true) @@ -133,11 +138,43 @@ describe('Store', () => { // settings should preserve the overridden value expect(store.getSettings().theme).toBe('dark') // new fields get defaults when missing from persisted data + expect(store.getSettings().editorAutoSave).toBe(false) + expect(store.getSettings().editorAutoSaveDelayMs).toBe(1000) expect(store.getSettings().rightSidebarOpenByDefault).toBe(true) // repos should be loaded expect(store.getRepos()).toHaveLength(1) }) + it('preserves editorAutoSaveDelayMs when set in persisted data', async () => { + writeDataFile({ + schemaVersion: 1, + repos: [], + worktreeMeta: {}, + settings: { editorAutoSaveDelayMs: 2500 }, + ui: {}, + githubCache: { pr: {}, issue: {} }, + workspaceSession: {} + }) + + const store = await createStore() + expect(store.getSettings().editorAutoSaveDelayMs).toBe(2500) + }) + + it('preserves editorAutoSave when set to true in persisted data', async () => { + writeDataFile({ + schemaVersion: 1, + repos: [], + worktreeMeta: {}, + settings: { editorAutoSave: true }, + ui: {}, + githubCache: { pr: {}, issue: {} }, + workspaceSession: {} + }) + + const store = await createStore() + expect(store.getSettings().editorAutoSave).toBe(true) + }) + it('preserves rightSidebarOpenByDefault when set to true in persisted data', async () => { writeDataFile({ schemaVersion: 1, @@ -238,16 +275,31 @@ describe('Store', () => { const updated = store.updateSettings({ theme: 'dark', + editorAutoSave: true, + editorAutoSaveDelayMs: 1500, terminalFontSize: 16, terminalFontWeight: 600 }) expect(updated.theme).toBe('dark') + expect(updated.editorAutoSave).toBe(true) + expect(updated.editorAutoSaveDelayMs).toBe(1500) expect(updated.terminalFontSize).toBe(16) expect(updated.terminalFontWeight).toBe(600) // Other fields preserved expect(updated.branchPrefix).toBe('git-username') }) + it('updateSettings toggles editorAutoSave', async () => { + const store = await createStore() + expect(store.getSettings().editorAutoSave).toBe(false) + + store.updateSettings({ editorAutoSave: true }) + expect(store.getSettings().editorAutoSave).toBe(true) + + store.updateSettings({ editorAutoSave: false }) + expect(store.getSettings().editorAutoSave).toBe(false) + }) + it('updateSettings toggles rightSidebarOpenByDefault', async () => { const store = await createStore() expect(store.getSettings().rightSidebarOpenByDefault).toBe(true) diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index 82d1ae2f3..7b9377f24 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -12,6 +12,7 @@ import { import { Button } from '@/components/ui/button' import TabBar from './tab-bar/TabBar' import TerminalPane from './terminal-pane/TerminalPane' +import { requestEditorSaveQuiesce } from './editor/editor-autosave' const EditorPanel = lazy(() => import('./editor/EditorPanel')) @@ -86,10 +87,14 @@ export default function Terminal(): React.JSX.Element | null { setSaveDialogFileId(null) }, [saveDialogFileId]) - const handleSaveDialogDiscard = useCallback(() => { + const handleSaveDialogDiscard = useCallback(async () => { if (!saveDialogFileId) { return } + // Why: autosave runs on a background timer. Wait for any pending/in-flight + // write to settle before honoring "Don't Save", otherwise the file can be + // written after the user explicitly chose to discard their edits. + await requestEditorSaveQuiesce({ fileId: saveDialogFileId }) markFileDirty(saveDialogFileId, false) closeFile(saveDialogFileId) setSaveDialogFileId(null) @@ -403,17 +408,26 @@ export default function Terminal(): React.JSX.Element | null { })} - {/* Editor panel - shown when editor tab is active */} - {activeWorktreeId && activeTabType === 'editor' && worktreeFiles.length > 0 && ( - - Loading editor... - + {/* Editor panel - keep mounted while files are open so autosave/discard + coordination and in-memory edit buffers survive tab switches. */} + {activeWorktreeId && openFiles.length > 0 && ( +
0 + ? 'flex flex-1 min-h-0' + : 'hidden' } > - - + + Loading editor... +
+ } + > + +
+ )} {/* Save confirmation dialog */} diff --git a/src/renderer/src/components/editor/EditorPanel.tsx b/src/renderer/src/components/editor/EditorPanel.tsx index 3913c9e45..9c0f2e799 100644 --- a/src/renderer/src/components/editor/EditorPanel.tsx +++ b/src/renderer/src/components/editor/EditorPanel.tsx @@ -1,13 +1,26 @@ +/* eslint-disable max-lines -- Why: EditorPanel owns the editor tab save/load +lifecycle end-to-end, including autosave coordination with external mutations. +Keeping that state machine co-located avoids subtle regressions from splitting +the tightly-coupled effects, refs, and event handlers across multiple modules. */ import React, { useCallback, useEffect, useState, Suspense } from 'react' import { Columns2, FileText, Rows2 } from 'lucide-react' import { useAppStore } from '@/store' import { detectLanguage } from '@/lib/language-detect' import { getEditorHeaderCopyState, getEditorHeaderOpenFileState } from './editor-header' import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip' -import type { MarkdownViewMode } from '@/store/slices/editor' +import type { MarkdownViewMode, OpenFile } from '@/store/slices/editor' import MarkdownViewToggle from './MarkdownViewToggle' import { EditorContent } from './EditorContent' import type { GitDiffResult } from '../../../../shared/types' +import { + canAutoSaveOpenFile, + getOpenFilesForExternalFileChange, + normalizeAutoSaveDelayMs, + ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, + ORCA_EDITOR_QUIESCE_FILE_SAVES_EVENT, + type EditorPathMutationTarget, + type EditorSaveQuiesceDetail +} from './editor-autosave' type FileContent = { content: string @@ -28,6 +41,7 @@ export default function EditorPanel(): React.JSX.Element | null { const markdownViewMode = useAppStore((s) => s.markdownViewMode) const setMarkdownViewMode = useAppStore((s) => s.setMarkdownViewMode) const openFile = useAppStore((s) => s.openFile) + const settings = useAppStore((s) => s.settings) const activeFile = openFiles.find((f) => f.id === activeFileId) ?? null @@ -38,6 +52,28 @@ export default function EditorPanel(): React.JSX.Element | null { null ) const [sideBySide, setSideBySide] = useState(true) + const autoSaveTimersRef = React.useRef>(new Map()) + const autoSaveScheduledContentRef = React.useRef>(new Map()) + const saveQueueRef = React.useRef>>(new Map()) + const saveGenerationRef = React.useRef>(new Map()) + const openFilesRef = React.useRef(openFiles) + const editBuffersRef = React.useRef(editBuffers) + const autoSaveDelayMs = normalizeAutoSaveDelayMs(settings?.editorAutoSaveDelayMs) + openFilesRef.current = openFiles + editBuffersRef.current = editBuffers + + const clearAutoSaveTimer = useCallback((fileId: string): void => { + const timerId = autoSaveTimersRef.current.get(fileId) + if (timerId !== undefined) { + window.clearTimeout(timerId) + autoSaveTimersRef.current.delete(fileId) + } + autoSaveScheduledContentRef.current.delete(fileId) + }, []) + + const bumpSaveGeneration = useCallback((fileId: string): void => { + saveGenerationRef.current.set(fileId, (saveGenerationRef.current.get(fileId) ?? 0) + 1) + }, []) // Load file content when active file changes useEffect(() => { @@ -76,7 +112,7 @@ export default function EditorPanel(): React.JSX.Element | null { return () => window.clearTimeout(timeout) }, [copiedPathToast]) - const loadFileContent = async (filePath: string, id: string): Promise => { + const loadFileContent = useCallback(async (filePath: string, id: string): Promise => { try { const result = (await window.api.fs.readFile({ filePath })) as FileContent setFileContents((prev) => ({ ...prev, [id]: result })) @@ -86,9 +122,9 @@ export default function EditorPanel(): React.JSX.Element | null { [id]: { content: `Error loading file: ${err}`, isBinary: false } })) } - } + }, []) - const loadDiffContent = async (file: typeof activeFile): Promise => { + const loadDiffContent = useCallback(async (file: OpenFile | null): Promise => { if (!file) { return } @@ -133,14 +169,102 @@ export default function EditorPanel(): React.JSX.Element | null { } })) } - } + }, []) + + const queueSave = useCallback( + (file: OpenFile, fallbackContent: string): Promise => { + clearAutoSaveTimer(file.id) + const saveGeneration = saveGenerationRef.current.get(file.id) ?? 0 + + const previousSave = saveQueueRef.current.get(file.id) ?? Promise.resolve() + const queuedSave = previousSave + .catch(() => undefined) + .then(async () => { + if ((saveGenerationRef.current.get(file.id) ?? 0) !== saveGeneration) { + return + } + if (!openFilesRef.current.some((openFile) => openFile.id === file.id)) { + return + } + + const liveFile = openFilesRef.current.find((openFile) => openFile.id === file.id) ?? file + const contentToSave = editBuffersRef.current[file.id] ?? fallbackContent + + try { + await window.api.fs.writeFile({ filePath: liveFile.filePath, content: contentToSave }) + if ((saveGenerationRef.current.get(file.id) ?? 0) !== saveGeneration) { + return + } + + if (liveFile.mode === 'edit') { + setFileContents((prev) => ({ + ...prev, + [file.id]: { content: contentToSave, isBinary: false } + })) + } else { + setDiffContents((prev) => { + const existing = prev[file.id] + if (!existing || existing.kind !== 'text') { + return prev + } + return { + ...prev, + [file.id]: { ...existing, modifiedContent: contentToSave } + } + }) + } + + const currentBuffer = editBuffersRef.current[file.id] + const stillDirty = currentBuffer !== undefined && currentBuffer !== contentToSave + + markFileDirty(file.id, stillDirty) + setEditBuffers((prev) => { + const bufferedContent = prev[file.id] + if (bufferedContent === undefined || bufferedContent === contentToSave) { + const next = { ...prev } + delete next[file.id] + editBuffersRef.current = next + return next + } + editBuffersRef.current = prev + return prev + }) + } catch (err) { + console.error('Save failed:', err) + throw err + } + }) + + let trackedSave: Promise + trackedSave = queuedSave.finally(() => { + if (saveQueueRef.current.get(file.id) === trackedSave) { + saveQueueRef.current.delete(file.id) + } + }) + saveQueueRef.current.set(file.id, trackedSave) + return trackedSave + }, + [clearAutoSaveTimer, markFileDirty] + ) + + const quiesceFileSave = useCallback( + async (fileId: string): Promise => { + const pendingSave = saveQueueRef.current.get(fileId) + clearAutoSaveTimer(fileId) + bumpSaveGeneration(fileId) + await pendingSave?.catch(() => undefined) + }, + [bumpSaveGeneration, clearAutoSaveTimer] + ) const handleContentChange = useCallback( (content: string) => { if (!activeFile) { return } - setEditBuffers((prev) => ({ ...prev, [activeFile.id]: content })) + const nextBuffers = { ...editBuffersRef.current, [activeFile.id]: content } + editBuffersRef.current = nextBuffers + setEditBuffers(nextBuffers) if (activeFile.mode === 'edit') { // Compare against saved content to determine dirty state const saved = fileContents[activeFile.id]?.content ?? '' @@ -151,8 +275,19 @@ export default function EditorPanel(): React.JSX.Element | null { const original = dc?.kind === 'text' ? dc.modifiedContent : '' markFileDirty(activeFile.id, content !== original) } + + if (!settings?.editorAutoSave) { + clearAutoSaveTimer(activeFile.id) + } }, - [activeFile, markFileDirty, fileContents, diffContents] + [ + activeFile, + clearAutoSaveTimer, + diffContents, + fileContents, + markFileDirty, + settings?.editorAutoSave + ] ) const handleSave = useCallback( @@ -161,37 +296,10 @@ export default function EditorPanel(): React.JSX.Element | null { return } try { - await window.api.fs.writeFile({ filePath: activeFile.filePath, content }) - markFileDirty(activeFile.id, false) - if (activeFile.mode === 'edit') { - setFileContents((prev) => ({ - ...prev, - [activeFile.id]: { content, isBinary: false } - })) - } else { - // Update the diff's modified content baseline so dirty tracking stays correct - setDiffContents((prev) => { - const existing = prev[activeFile.id] - if (!existing || existing.kind !== 'text') { - return prev - } - return { - ...prev, - [activeFile.id]: { ...existing, modifiedContent: content } - } - }) - } - // Clear the edit buffer since it now matches saved state - setEditBuffers((prev) => { - const next = { ...prev } - delete next[activeFile.id] - return next - }) - } catch (err) { - console.error('Save failed:', err) - } + await queueSave(activeFile, content) + } catch {} }, - [activeFile, markFileDirty] + [activeFile, queueSave] ) // Handle save-and-close events from the save confirmation dialog @@ -202,17 +310,11 @@ export default function EditorPanel(): React.JSX.Element | null { if (!file) { return } - const buffer = editBuffers[fileId] + const buffer = editBuffersRef.current[fileId] if (buffer !== undefined) { try { - await window.api.fs.writeFile({ filePath: file.filePath, content: buffer }) - markFileDirty(fileId, false) - setFileContents((prev) => ({ - ...prev, - [fileId]: { content: buffer, isBinary: false } - })) - } catch (err) { - console.error('Save failed:', err) + await queueSave(file, buffer) + } catch { return // Don't close if save fails } } @@ -220,7 +322,159 @@ export default function EditorPanel(): React.JSX.Element | null { } window.addEventListener('orca:save-and-close', handler as EventListener) return () => window.removeEventListener('orca:save-and-close', handler as EventListener) - }, [editBuffers, markFileDirty]) + }, [queueSave]) + + useEffect(() => { + const handler = async (event: Event): Promise => { + const detail = (event as CustomEvent).detail + if (!detail) { + return + } + detail.claim() + + const matchingFiles = + 'fileId' in detail + ? openFilesRef.current.filter((file) => file.id === detail.fileId) + : getOpenFilesForExternalFileChange(openFilesRef.current, detail) + + await Promise.all(matchingFiles.map((file) => quiesceFileSave(file.id))) + detail.resolve() + } + + window.addEventListener(ORCA_EDITOR_QUIESCE_FILE_SAVES_EVENT, handler as EventListener) + return () => + window.removeEventListener(ORCA_EDITOR_QUIESCE_FILE_SAVES_EVENT, handler as EventListener) + }, [quiesceFileSave]) + + useEffect(() => { + const handler = (event: Event): void => { + const detail = (event as CustomEvent).detail + if (!detail) { + return + } + + const matchingFiles = getOpenFilesForExternalFileChange(openFilesRef.current, detail) + if (matchingFiles.length === 0) { + return + } + + const matchingIds = new Set(matchingFiles.map((file) => file.id)) + + for (const file of matchingFiles) { + clearAutoSaveTimer(file.id) + bumpSaveGeneration(file.id) + markFileDirty(file.id, false) + } + + setEditBuffers((prev) => { + const next = { ...prev } + for (const fileId of matchingIds) { + delete next[fileId] + } + editBuffersRef.current = next + return next + }) + + 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 + }) + + for (const file of matchingFiles) { + if (file.mode === 'edit') { + void loadFileContent(file.filePath, file.id) + } else if ( + file.mode === 'diff' && + file.diffSource !== 'combined-uncommitted' && + file.diffSource !== 'combined-branch' + ) { + void loadDiffContent(file) + } + } + } + + window.addEventListener(ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, handler as EventListener) + return () => + window.removeEventListener(ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, handler as EventListener) + }, [bumpSaveGeneration, clearAutoSaveTimer, loadDiffContent, loadFileContent, markFileDirty]) + + useEffect(() => { + const openFilesById = new Map(openFiles.map((file) => [file.id, file])) + + for (const fileId of Array.from(autoSaveTimersRef.current.keys())) { + const file = openFilesById.get(fileId) + const buffer = editBuffers[fileId] + const shouldKeepTimer = + settings?.editorAutoSave && + file && + file.isDirty && + canAutoSaveOpenFile(file) && + buffer !== undefined + if (!shouldKeepTimer) { + clearAutoSaveTimer(fileId) + } + } + + if (!settings?.editorAutoSave) { + return + } + + for (const file of openFiles) { + const buffer = editBuffers[file.id] + if (!file.isDirty || buffer === undefined || !canAutoSaveOpenFile(file)) { + clearAutoSaveTimer(file.id) + continue + } + + if ( + autoSaveTimersRef.current.has(file.id) && + autoSaveScheduledContentRef.current.get(file.id) === buffer + ) { + continue + } + + clearAutoSaveTimer(file.id) + autoSaveScheduledContentRef.current.set(file.id, buffer) + const timerId = window.setTimeout(() => { + autoSaveTimersRef.current.delete(file.id) + autoSaveScheduledContentRef.current.delete(file.id) + void queueSave(file, buffer) + }, autoSaveDelayMs) + autoSaveTimersRef.current.set(file.id, timerId) + } + }, [ + autoSaveDelayMs, + clearAutoSaveTimer, + editBuffers, + openFiles, + queueSave, + settings?.editorAutoSave + ]) + + useEffect( + () => () => { + for (const timerId of autoSaveTimersRef.current.values()) { + window.clearTimeout(timerId) + } + autoSaveTimersRef.current.clear() + autoSaveScheduledContentRef.current.clear() + }, + [] + ) // Clean up content caches when files are closed useEffect(() => { @@ -250,6 +504,7 @@ export default function EditorPanel(): React.JSX.Element | null { next[k] = v } } + editBuffersRef.current = next return next }) }, [openFiles]) diff --git a/src/renderer/src/components/editor/editor-autosave.test.ts b/src/renderer/src/components/editor/editor-autosave.test.ts new file mode 100644 index 000000000..95b106470 --- /dev/null +++ b/src/renderer/src/components/editor/editor-autosave.test.ts @@ -0,0 +1,164 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { OpenFile } from '@/store/slices/editor' +import { + canAutoSaveOpenFile, + getOpenFilesForExternalFileChange, + normalizeAutoSaveDelayMs, + ORCA_EDITOR_QUIESCE_FILE_SAVES_EVENT, + requestEditorSaveQuiesce +} from './editor-autosave' + +type WindowEventStub = Pick< + Window, + 'addEventListener' | 'removeEventListener' | 'dispatchEvent' | 'setTimeout' | 'clearTimeout' +> + +function makeOpenFile(overrides: Partial = {}): OpenFile { + return { + id: '/repo/file.ts', + filePath: '/repo/file.ts', + relativePath: 'file.ts', + worktreeId: 'wt-1', + language: 'typescript', + isDirty: false, + mode: 'edit', + ...overrides + } +} + +beforeEach(() => { + const eventTarget = new EventTarget() + vi.stubGlobal('window', { + addEventListener: eventTarget.addEventListener.bind(eventTarget), + removeEventListener: eventTarget.removeEventListener.bind(eventTarget), + dispatchEvent: eventTarget.dispatchEvent.bind(eventTarget), + setTimeout: globalThis.setTimeout.bind(globalThis), + clearTimeout: globalThis.clearTimeout.bind(globalThis) + } satisfies WindowEventStub) +}) + +afterEach(() => { + vi.unstubAllGlobals() +}) + +describe('canAutoSaveOpenFile', () => { + it('allows normal edit tabs and unstaged single-file diffs', () => { + expect(canAutoSaveOpenFile(makeOpenFile())).toBe(true) + expect( + canAutoSaveOpenFile( + makeOpenFile({ + id: 'wt-1::diff::unstaged::file.ts', + mode: 'diff', + diffSource: 'unstaged' + }) + ) + ).toBe(true) + }) + + it('rejects staged, combined, and conflict-review tabs', () => { + expect( + canAutoSaveOpenFile( + makeOpenFile({ + id: 'wt-1::diff::staged::file.ts', + mode: 'diff', + diffSource: 'staged' + }) + ) + ).toBe(false) + expect( + canAutoSaveOpenFile( + makeOpenFile({ + id: 'wt-1::all-diffs::uncommitted', + filePath: '/repo', + relativePath: 'All Changes', + mode: 'diff', + diffSource: 'combined-uncommitted' + }) + ) + ).toBe(false) + expect( + canAutoSaveOpenFile( + makeOpenFile({ + id: 'wt-1::conflicts', + filePath: '/repo', + relativePath: 'Conflicts', + mode: 'conflict-review' + }) + ) + ).toBe(false) + }) +}) + +describe('normalizeAutoSaveDelayMs', () => { + it('defaults and clamps invalid values', () => { + expect(normalizeAutoSaveDelayMs(undefined)).toBe(1000) + expect(normalizeAutoSaveDelayMs(Number.NaN)).toBe(1000) + expect(normalizeAutoSaveDelayMs('750')).toBe(750) + expect(normalizeAutoSaveDelayMs('oops')).toBe(1000) + expect(normalizeAutoSaveDelayMs(10)).toBe(250) + expect(normalizeAutoSaveDelayMs(25_000)).toBe(10_000) + }) +}) + +describe('requestEditorSaveQuiesce', () => { + it('resolves immediately when no editor listener claims the request', async () => { + await expect(requestEditorSaveQuiesce({ fileId: 'file-1' })).resolves.toBeUndefined() + }) + + it('waits for a claiming listener to finish quiescing', async () => { + let resolved = false + const handler = (event: Event): void => { + const detail = (event as CustomEvent).detail as { + claim: () => void + resolve: () => void + } + detail.claim() + window.setTimeout(() => detail.resolve(), 0) + } + + window.addEventListener(ORCA_EDITOR_QUIESCE_FILE_SAVES_EVENT, handler as EventListener) + try { + const promise = requestEditorSaveQuiesce({ fileId: 'file-1' }).then(() => { + resolved = true + }) + + expect(resolved).toBe(false) + await promise + expect(resolved).toBe(true) + } finally { + window.removeEventListener(ORCA_EDITOR_QUIESCE_FILE_SAVES_EVENT, handler as EventListener) + } + }) +}) + +describe('getOpenFilesForExternalFileChange', () => { + it('matches edit tabs and unstaged diff tabs for the same worktree file', () => { + const matchingEdit = makeOpenFile() + const matchingUnstagedDiff = makeOpenFile({ + id: 'wt-1::diff::unstaged::file.ts', + mode: 'diff', + diffSource: 'unstaged' + }) + const stagedDiff = makeOpenFile({ + id: 'wt-1::diff::staged::file.ts', + mode: 'diff', + diffSource: 'staged' + }) + const otherWorktree = makeOpenFile({ + id: '/other/file.ts', + filePath: '/other/file.ts', + worktreeId: 'wt-2' + }) + + expect( + getOpenFilesForExternalFileChange( + [matchingEdit, matchingUnstagedDiff, stagedDiff, otherWorktree], + { + worktreeId: 'wt-1', + worktreePath: '/repo', + relativePath: 'file.ts' + } + ).map((file) => file.id) + ).toEqual(['/repo/file.ts', 'wt-1::diff::unstaged::file.ts']) + }) +}) diff --git a/src/renderer/src/components/editor/editor-autosave.ts b/src/renderer/src/components/editor/editor-autosave.ts new file mode 100644 index 000000000..e59ccf3ad --- /dev/null +++ b/src/renderer/src/components/editor/editor-autosave.ts @@ -0,0 +1,95 @@ +import { joinPath } from '@/lib/path' +import type { OpenFile } from '@/store/slices/editor' +import { + DEFAULT_EDITOR_AUTO_SAVE_DELAY_MS, + MAX_EDITOR_AUTO_SAVE_DELAY_MS, + MIN_EDITOR_AUTO_SAVE_DELAY_MS +} from '../../../../shared/constants' +import { clampNumber } from '@/lib/terminal-theme' + +export const ORCA_EDITOR_QUIESCE_FILE_SAVES_EVENT = 'orca:editor-quiesce-file-saves' +export const ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT = 'orca:editor-external-file-change' + +export type EditorPathMutationTarget = { + worktreeId: string + worktreePath: string + relativePath: string +} + +export type EditorSaveQuiesceTarget = { fileId: string } | EditorPathMutationTarget + +export type EditorSaveQuiesceDetail = EditorSaveQuiesceTarget & { + claim: () => void + resolve: () => void +} + +export function canAutoSaveOpenFile(file: OpenFile): boolean { + // Why: single-file editors and one-file unstaged diffs have an unambiguous + // write target. Combined diff and conflict-review tabs can represent multiple + // paths, so autosave must stay out of those surfaces until they have their + // own save coordination instead of guessing which file should be written. + return file.mode === 'edit' || (file.mode === 'diff' && file.diffSource === 'unstaged') +} + +export function normalizeAutoSaveDelayMs(value: unknown): number { + // Why: settings are persisted locally and can be missing or hand-edited. + // Clamp the delay at the write site so autosave never degenerates into an + // effectively immediate save loop or an unexpectedly huge wait. + const numericValue = + typeof value === 'string' ? Number(value) : typeof value === 'number' ? value : null + const normalizedValue = + numericValue !== null && Number.isFinite(numericValue) + ? numericValue + : DEFAULT_EDITOR_AUTO_SAVE_DELAY_MS + return clampNumber(normalizedValue, MIN_EDITOR_AUTO_SAVE_DELAY_MS, MAX_EDITOR_AUTO_SAVE_DELAY_MS) +} + +export function getOpenFilesForExternalFileChange( + openFiles: OpenFile[], + target: EditorPathMutationTarget +): OpenFile[] { + const absolutePath = joinPath(target.worktreePath, target.relativePath) + return openFiles.filter((file) => { + if (file.worktreeId !== target.worktreeId) { + return false + } + if (file.mode === 'edit') { + return file.filePath === absolutePath + } + if (file.mode === 'diff') { + return file.diffSource === 'unstaged' && file.relativePath === target.relativePath + } + return false + }) +} + +export async function requestEditorSaveQuiesce(target: EditorSaveQuiesceTarget): Promise { + await new Promise((resolve) => { + let claimed = false + window.dispatchEvent( + new CustomEvent(ORCA_EDITOR_QUIESCE_FILE_SAVES_EVENT, { + detail: { + ...target, + claim: () => { + claimed = true + }, + resolve + } + }) + ) + // Why: discard/delete flows also run when no editor tab is mounted. Let + // those external mutations proceed immediately instead of hanging forever + // waiting on a quiesce listener that does not exist in that UI state. + if (!claimed) { + resolve() + } + }) +} + +export function notifyEditorExternalFileChange(target: EditorPathMutationTarget): void { + window.dispatchEvent( + new CustomEvent(ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, { + detail: target + }) + ) +} diff --git a/src/renderer/src/components/right-sidebar/SourceControl.tsx b/src/renderer/src/components/right-sidebar/SourceControl.tsx index 296129229..9c4d3fe7d 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.tsx @@ -38,6 +38,10 @@ import { DialogTitle } from '@/components/ui/dialog' import { BaseRefPicker } from '@/components/settings/BaseRefPicker' +import { + notifyEditorExternalFileChange, + requestEditorSaveQuiesce +} from '@/components/editor/editor-autosave' import { PullRequestIcon } from './checks-helpers' import type { GitBranchChangeEntry, @@ -379,16 +383,29 @@ export default function SourceControl(): React.JSX.Element { const handleDiscard = useCallback( async (filePath: string) => { - if (!worktreePath) { + if (!worktreePath || !activeWorktreeId) { return } try { + // Why: git discard replaces the working tree version of this file. Any + // pending editor autosave must be quiesced first so it cannot recreate + // the discarded edits after git restores the file. + await requestEditorSaveQuiesce({ + worktreeId: activeWorktreeId, + worktreePath, + relativePath: filePath + }) await window.api.git.discard({ worktreePath, filePath }) + notifyEditorExternalFileChange({ + worktreeId: activeWorktreeId, + worktreePath, + relativePath: filePath + }) } catch { // git operation failed silently } }, - [worktreePath] + [activeWorktreeId, worktreePath] ) if (!activeWorktree || !activeRepo || !worktreePath) { diff --git a/src/renderer/src/components/right-sidebar/useFileDeletion.ts b/src/renderer/src/components/right-sidebar/useFileDeletion.ts index 2c3e26379..d06c0d441 100644 --- a/src/renderer/src/components/right-sidebar/useFileDeletion.ts +++ b/src/renderer/src/components/right-sidebar/useFileDeletion.ts @@ -4,6 +4,7 @@ import { toast } from 'sonner' import { useAppStore } from '@/store' import { isPathEqualOrDescendant } from './file-explorer-paths' import type { PendingDelete, TreeNode } from './file-explorer-types' +import { requestEditorSaveQuiesce } from '@/components/editor/editor-autosave' type UseFileDeletionParams = { activeWorktreeId: string | null @@ -79,11 +80,16 @@ export function useFileDeletion({ setIsDeleting(true) try { - await window.api.fs.deletePath({ targetPath: node.path }) - const filesToClose = openFiles.filter((file) => isPathEqualOrDescendant(file.filePath, node.path) ) + // Why: moving a file to Trash/Recycle Bin is another external mutation of + // the file path. Let any in-flight autosave finish first so the delete + // action cannot be undone by a trailing write that recreates the file. + await Promise.all(filesToClose.map((file) => requestEditorSaveQuiesce({ fileId: file.id }))) + + await window.api.fs.deletePath({ targetPath: node.path }) + for (const file of filesToClose) { closeFile(file.id) } diff --git a/src/renderer/src/components/settings/GeneralPane.tsx b/src/renderer/src/components/settings/GeneralPane.tsx index 954af39f6..7cba63e71 100644 --- a/src/renderer/src/components/settings/GeneralPane.tsx +++ b/src/renderer/src/components/settings/GeneralPane.tsx @@ -7,6 +7,12 @@ import { Separator } from '../ui/separator' import { Download, FolderOpen, Loader2, RefreshCw } from 'lucide-react' import { useAppStore } from '../../store' import { CliSection } from './CliSection' +import { + DEFAULT_EDITOR_AUTO_SAVE_DELAY_MS, + MAX_EDITOR_AUTO_SAVE_DELAY_MS, + MIN_EDITOR_AUTO_SAVE_DELAY_MS +} from '../../../../shared/constants' +import { clampNumber } from '@/lib/terminal-theme' type GeneralPaneProps = { settings: GlobalSettings @@ -21,11 +27,18 @@ export function GeneralPane({ }: GeneralPaneProps): React.JSX.Element { const updateStatus = useAppStore((s) => s.updateStatus) const [appVersion, setAppVersion] = useState(null) + const [autoSaveDelayDraft, setAutoSaveDelayDraft] = useState( + String(settings.editorAutoSaveDelayMs) + ) useEffect(() => { window.api.updater.getVersion().then(setAppVersion) }, []) + useEffect(() => { + setAutoSaveDelayDraft(String(settings.editorAutoSaveDelayMs)) + }, [settings.editorAutoSaveDelayMs]) + const handleBrowseWorkspace = async () => { const path = await window.api.repos.pickFolder() if (path) { @@ -33,6 +46,28 @@ export function GeneralPane({ } } + const commitAutoSaveDelay = (): void => { + const trimmed = autoSaveDelayDraft.trim() + if (trimmed === '') { + setAutoSaveDelayDraft(String(settings.editorAutoSaveDelayMs)) + return + } + + const value = Number(trimmed) + if (!Number.isFinite(value)) { + setAutoSaveDelayDraft(String(settings.editorAutoSaveDelayMs)) + return + } + + const next = clampNumber( + Math.round(value), + MIN_EDITOR_AUTO_SAVE_DELAY_MS, + MAX_EDITOR_AUTO_SAVE_DELAY_MS + ) + updateSettings({ editorAutoSaveDelayMs: next }) + setAutoSaveDelayDraft(String(next)) + } + return (
@@ -96,6 +131,70 @@ export function GeneralPane({ +
+
+

Editor

+

Configure how Orca persists file edits.

+
+ +
+
+ +

+ Save editor and editable diff changes automatically after a short pause. +

+
+ +
+ +
+
+ +

+ How long Orca waits after your last edit before saving automatically. First launch + defaults to {DEFAULT_EDITOR_AUTO_SAVE_DELAY_MS} ms. +

+
+
+ setAutoSaveDelayDraft(e.target.value)} + onBlur={commitAutoSaveDelay} + onKeyDown={(e) => { + if (e.key === 'Enter') { + commitAutoSaveDelay() + } + }} + className="number-input-clean w-28 text-right tabular-nums" + /> + ms +
+
+
+ + + diff --git a/src/renderer/src/components/settings/Settings.tsx b/src/renderer/src/components/settings/Settings.tsx index 80680746c..48624d065 100644 --- a/src/renderer/src/components/settings/Settings.tsx +++ b/src/renderer/src/components/settings/Settings.tsx @@ -185,7 +185,7 @@ function Settings(): React.JSX.Element { const pageHeader = showGeneralPane ? (

General

-

Workspace, naming, and updates.

+

Workspace, editor, naming, and updates.

) : showAppearancePane ? (
diff --git a/src/renderer/src/components/terminal/useTerminalSaveDialog.ts b/src/renderer/src/components/terminal/useTerminalSaveDialog.ts index 6fcdc2185..a55bb0b69 100644 --- a/src/renderer/src/components/terminal/useTerminalSaveDialog.ts +++ b/src/renderer/src/components/terminal/useTerminalSaveDialog.ts @@ -1,5 +1,6 @@ import { useCallback, useState } from 'react' import type { OpenFile } from '@/store/slices/editor' +import { requestEditorSaveQuiesce } from '@/components/editor/editor-autosave' type UseTerminalSaveDialogParams = { openFiles: OpenFile[] @@ -50,11 +51,14 @@ export function useTerminalSaveDialog({ setSaveDialogFileId(null) }, [saveDialogFileId]) - const handleSaveDialogDiscard = useCallback(() => { + const handleSaveDialogDiscard = useCallback(async () => { if (!saveDialogFileId) { return } + // Why: "Don't Save" must win over any pending autosave write for the same + // tab, even if the editor is currently waiting on a background debounce. + await requestEditorSaveQuiesce({ fileId: saveDialogFileId }) markFileDirty(saveDialogFileId, false) closeFile(saveDialogFileId) setSaveDialogFileId(null) diff --git a/src/renderer/src/lib/terminal-links.ts b/src/renderer/src/lib/terminal-links.ts index 8e6ed7135..1e1ca0f73 100644 --- a/src/renderer/src/lib/terminal-links.ts +++ b/src/renderer/src/lib/terminal-links.ts @@ -220,7 +220,11 @@ export function resolveTerminalFileLink( export function isPathInsideWorktree(filePath: string, worktreePath: string): boolean { const normalizedFile = normalizeAbsolutePath(filePath) const normalizedWorktree = normalizeAbsolutePath(worktreePath) - if (!normalizedFile || !normalizedWorktree || normalizedFile.rootKind !== normalizedWorktree.rootKind) { + if ( + !normalizedFile || + !normalizedWorktree || + normalizedFile.rootKind !== normalizedWorktree.rootKind + ) { return false } if (normalizedFile.comparisonKey === normalizedWorktree.comparisonKey) { @@ -232,7 +236,11 @@ export function isPathInsideWorktree(filePath: string, worktreePath: string): bo export function toWorktreeRelativePath(filePath: string, worktreePath: string): string | null { const normalizedFile = normalizeAbsolutePath(filePath) const normalizedWorktree = normalizeAbsolutePath(worktreePath) - if (!normalizedFile || !normalizedWorktree || normalizedFile.rootKind !== normalizedWorktree.rootKind) { + if ( + !normalizedFile || + !normalizedWorktree || + normalizedFile.rootKind !== normalizedWorktree.rootKind + ) { return null } if (normalizedFile.comparisonKey === normalizedWorktree.comparisonKey) { diff --git a/src/shared/constants.ts b/src/shared/constants.ts index fcfd8d6b3..29244e4e4 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -9,6 +9,9 @@ import type { import { DEFAULT_TERMINAL_FONT_WEIGHT } from './terminal-fonts' export const SCHEMA_VERSION = 1 +export const DEFAULT_EDITOR_AUTO_SAVE_DELAY_MS = 1000 +export const MIN_EDITOR_AUTO_SAVE_DELAY_MS = 250 +export const MAX_EDITOR_AUTO_SAVE_DELAY_MS = 10_000 export const DEFAULT_WORKTREE_CARD_PROPERTIES: WorktreeCardProperty[] = [ 'status', @@ -37,6 +40,8 @@ export function getDefaultSettings(homedir: string): GlobalSettings { branchPrefix: 'git-username', branchPrefixCustom: '', theme: 'system', + editorAutoSave: false, + editorAutoSaveDelayMs: DEFAULT_EDITOR_AUTO_SAVE_DELAY_MS, terminalFontSize: 14, terminalFontFamily: 'SF Mono', terminalFontWeight: DEFAULT_TERMINAL_FONT_WEIGHT, diff --git a/src/shared/types.ts b/src/shared/types.ts index cca936859..5e01d70b0 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -205,6 +205,8 @@ export type GlobalSettings = { branchPrefix: 'git-username' | 'custom' | 'none' branchPrefixCustom: string theme: 'system' | 'dark' | 'light' + editorAutoSave: boolean + editorAutoSaveDelayMs: number terminalFontSize: number terminalFontFamily: string terminalFontWeight: number