feat: add autosaving (#300)

This commit is contained in:
Yax Patel
2026-04-05 10:29:29 -07:00
committed by GitHub
parent 357d2c31c5
commit 0cf0bbaab4
13 changed files with 786 additions and 65 deletions
+52
View File
@@ -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)
+24 -10
View File
@@ -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 {
})}
</div>
{/* Editor panel - shown when editor tab is active */}
{activeWorktreeId && activeTabType === 'editor' && worktreeFiles.length > 0 && (
<Suspense
fallback={
<div className="flex-1 flex items-center justify-center text-muted-foreground text-sm">
Loading editor...
</div>
{/* Editor panel - keep mounted while files are open so autosave/discard
coordination and in-memory edit buffers survive tab switches. */}
{activeWorktreeId && openFiles.length > 0 && (
<div
className={
activeTabType === 'editor' && worktreeFiles.length > 0
? 'flex flex-1 min-h-0'
: 'hidden'
}
>
<EditorPanel />
</Suspense>
<Suspense
fallback={
<div className="flex-1 flex items-center justify-center text-muted-foreground text-sm">
Loading editor...
</div>
}
>
<EditorPanel />
</Suspense>
</div>
)}
{/* Save confirmation dialog */}
@@ -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<Map<string, number>>(new Map())
const autoSaveScheduledContentRef = React.useRef<Map<string, string>>(new Map())
const saveQueueRef = React.useRef<Map<string, Promise<void>>>(new Map())
const saveGenerationRef = React.useRef<Map<string, number>>(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<void> => {
const loadFileContent = useCallback(async (filePath: string, id: string): Promise<void> => {
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<void> => {
const loadDiffContent = useCallback(async (file: OpenFile | null): Promise<void> => {
if (!file) {
return
}
@@ -133,14 +169,102 @@ export default function EditorPanel(): React.JSX.Element | null {
}
}))
}
}
}, [])
const queueSave = useCallback(
(file: OpenFile, fallbackContent: string): Promise<void> => {
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<void>
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<void> => {
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<void> => {
const detail = (event as CustomEvent<EditorSaveQuiesceDetail>).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<EditorPathMutationTarget>).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])
@@ -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> = {}): 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'])
})
})
@@ -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<void> {
await new Promise<void>((resolve) => {
let claimed = false
window.dispatchEvent(
new CustomEvent<EditorSaveQuiesceDetail>(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<EditorPathMutationTarget>(ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, {
detail: target
})
)
}
@@ -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) {
@@ -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)
}
@@ -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<string | null>(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 (
<div className="space-y-8">
<section className="space-y-4">
@@ -96,6 +131,70 @@ export function GeneralPane({
<Separator />
<section className="space-y-4">
<div className="space-y-1">
<h2 className="text-sm font-semibold">Editor</h2>
<p className="text-xs text-muted-foreground">Configure how Orca persists file edits.</p>
</div>
<div className="flex items-center justify-between gap-4 px-1 py-2">
<div className="space-y-0.5">
<Label>Auto Save Files</Label>
<p className="text-xs text-muted-foreground">
Save editor and editable diff changes automatically after a short pause.
</p>
</div>
<button
role="switch"
aria-checked={settings.editorAutoSave}
onClick={() =>
updateSettings({
editorAutoSave: !settings.editorAutoSave
})
}
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent transition-colors ${
settings.editorAutoSave ? 'bg-foreground' : 'bg-muted-foreground/30'
}`}
>
<span
className={`pointer-events-none block size-3.5 rounded-full bg-background shadow-sm transition-transform ${
settings.editorAutoSave ? 'translate-x-4' : 'translate-x-0.5'
}`}
/>
</button>
</div>
<div className="flex items-center justify-between gap-4 px-1 py-2">
<div className="space-y-0.5">
<Label>Auto Save Delay</Label>
<p className="text-xs text-muted-foreground">
How long Orca waits after your last edit before saving automatically. First launch
defaults to {DEFAULT_EDITOR_AUTO_SAVE_DELAY_MS} ms.
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
<Input
type="number"
min={MIN_EDITOR_AUTO_SAVE_DELAY_MS}
max={MAX_EDITOR_AUTO_SAVE_DELAY_MS}
step={250}
value={autoSaveDelayDraft}
onChange={(e) => setAutoSaveDelayDraft(e.target.value)}
onBlur={commitAutoSaveDelay}
onKeyDown={(e) => {
if (e.key === 'Enter') {
commitAutoSaveDelay()
}
}}
className="number-input-clean w-28 text-right tabular-nums"
/>
<span className="text-xs text-muted-foreground">ms</span>
</div>
</div>
</section>
<Separator />
<CliSection currentPlatform={navigator.userAgent.includes('Mac') ? 'darwin' : 'other'} />
<Separator />
@@ -185,7 +185,7 @@ function Settings(): React.JSX.Element {
const pageHeader = showGeneralPane ? (
<div className="space-y-1">
<h1 className="text-2xl font-semibold">General</h1>
<p className="text-sm text-muted-foreground">Workspace, naming, and updates.</p>
<p className="text-sm text-muted-foreground">Workspace, editor, naming, and updates.</p>
</div>
) : showAppearancePane ? (
<div className="space-y-1">
@@ -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)
+10 -2
View File
@@ -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) {
+5
View File
@@ -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,
+2
View File
@@ -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