Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(project-settings): workspaceDirty persistence seam + in-flight merge base
enesa53cb87ec6d6
diff --git a/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx b/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsxindex 314eca409..314d8d49f 100644--- a/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx+++ b/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { Project } from '@shared/types'import type { ProjectSettingsSnapshot } from '@shared/project-settings'import { useProjects } from '../../../state/projects'+import { registerWorkspaceDirty } from '../../../state/workspaceDirty'import { SettingsSearchContext } from '../context'import { ProjectSettingsSection } from './ProjectSettingsSection'import { useProjectSettings, type ProjectSettingsHook } from '../useProjectSettings'@@ -31,7 +32,9 @@ describe('ProjectSettingsSection', () => {let read: ReturnType<typeof vi.fn>let writeShared: ReturnType<typeof vi.fn>let updateLocal: ReturnType<typeof vi.fn>- let save: ReturnType<typeof vi.fn>+ /** Canvas's `markDirty`, registered through the same seam the app uses. */+ let dirty: ReturnType<typeof vi.fn<() => void>>+ let unregisterDirty: () => voidconst mount = async (node: React.JSX.Element, query = ''): Promise<void> => {root = createRoot(host)@@ -71,16 +74,18 @@ describe('ProjectSettingsSection', () => {read = vi.fn(async () => EMPTY_SNAPSHOT)writeShared = vi.fn(async () => true)updateLocal = vi.fn(async () => true)- save = vi.fn(async () => undefined)+ dirty = vi.fn<() => void>()+ unregisterDirty = registerWorkspaceDirty(dirty);(window as unknown as { nodeTerminal: any }).nodeTerminal = {projectSettings: { read, writeShared, updateLocal },- workspace: { save }+ workspace: { save: vi.fn() }}})afterEach(() => {act(() => root.unmount())host.remove()+ unregisterDirty()useProjects.setState({ projects: [], activeProjectId: '' })})@@ -99,16 +104,17 @@ describe('ProjectSettingsSection', () => {expect(host.textContent).toContain('enes@box:/srv/app')})- it('renames the project on BLUR only, then saves the workspace', async () => {+ it('renames the project on BLUR only, then rings the workspace-save seam', async () => {await mountSection()await typeInto(nameInput(), 'Beta')// Still un-renamed while typing: each save is a disk write, so the commit waits for blur.expect(useProjects.getState().getProject('p1')?.name).toBe('Alpha')- expect(save).not.toHaveBeenCalled()+ expect(dirty).not.toHaveBeenCalled()await blur(nameInput())expect(useProjects.getState().getProject('p1')?.name).toBe('Beta')- expect(save).toHaveBeenCalledTimes(1)- expect(save.mock.calls[0][0].projects[0].name).toBe('Beta')+ // The seam (state/workspaceDirty) rings Canvas's markDirty, so the write inherits the canvas+ // commit and the conflict gate; a raw workspace.save from here would bypass both.+ expect(dirty).toHaveBeenCalledTimes(1)})it('ignores a blank rename instead of writing an unnamed project', async () => {@@ -116,7 +122,7 @@ describe('ProjectSettingsSection', () => {await typeInto(nameInput(), ' ')await blur(nameInput())expect(useProjects.getState().getProject('p1')?.name).toBe('Alpha')- expect(save).not.toHaveBeenCalled()+ expect(dirty).not.toHaveBeenCalled()})it('picks a color and persists it', async () => {@@ -126,7 +132,7 @@ describe('ProjectSettingsSection', () => {swatch.dispatchEvent(new MouseEvent('click', { bubbles: true }))})expect(useProjects.getState().getProject('p1')?.color).toBe('#32d74b')- expect(save).toHaveBeenCalledTimes(1)+ expect(dirty).toHaveBeenCalledTimes(1)})it('sets the default permission mode and clears it back to the global default', async () => {@@ -144,7 +150,7 @@ describe('ProjectSettingsSection', () => {select.dispatchEvent(new Event('change', { bubbles: true }))})expect(useProjects.getState().getProject('p1')?.defaultPermissionMode).toBeUndefined()- expect(save).toHaveBeenCalledTimes(2)+ expect(dirty).toHaveBeenCalledTimes(2)})it('shows the conflict banner when the shared file is git-conflicted', async () => {@@ -260,6 +266,34 @@ describe('useProjectSettings', () => {expect(read).toHaveBeenCalledTimes(2)})+ it('keeps a save that is still being re-read as the merge base for the next one', async () => {+ // Blur A saves the shell; blur B arrives BEFORE A's re-read lands. Merging into the pre-A+ // document would make B's whole-document write silently delete A's shell.+ const first: ProjectSettingsSnapshot = {+ shared: { version: 1, rev: 1, savedAt: 't', terminal: { shell: '/bin/bash' } },+ local: undefined+ }+ let gate: (v: ProjectSettingsSnapshot) => void = () => {}+ read.mockResolvedValueOnce(first).mockReturnValue(+ new Promise<ProjectSettingsSnapshot>((r) => (gate = r))+ )+ await mount()+ await act(async () => {+ await hook.saveShared({ terminal: { shell: '/bin/fish' } })+ })+ expect(hook.snapshot).toBe('loading') // the re-read is gated open+ await act(async () => {+ await hook.saveShared({ setup: { waitForSetup: true } })+ })+ expect(writeShared).toHaveBeenLastCalledWith('p1', {+ terminal: { shell: '/bin/fish' },+ setup: { waitForSetup: true }+ })+ await act(async () => {+ gate(first)+ })+ })+it('drops a field cleared to undefined, and the family with it', async () => {read.mockResolvedValue({shared: { version: 1, rev: 1, savedAt: 't', terminal: { shell: '/bin/bash' } },diff --git a/src/renderer/components/settings/sections/ProjectSettingsSection.tsx b/src/renderer/components/settings/sections/ProjectSettingsSection.tsxindex d1d41133c..aea750cce 100644--- a/src/renderer/components/settings/sections/ProjectSettingsSection.tsx+++ b/src/renderer/components/settings/sections/ProjectSettingsSection.tsx@@ -11,6 +11,7 @@ import { cn } from '@renderer/ui/cn'import { useProjects } from '../../../state/projects'import { useSettings } from '../../../state/settings'import { useSystemAccount } from '../../../state/systemAccount'+import { markWorkspaceDirty } from '../../../state/workspaceDirty'import {NODE_COLORS,accountsForProject,@@ -26,17 +27,17 @@ import { matchesQuery, type SettingsSearchEntry } from '../search'import { useProjectSettings } from '../useProjectSettings'/**- * Saves the whole workspace after an identity/defaults edit — the SAME route Canvas takes after- * `renameProject` / `setProjectColor` / `setProjectDefault*` (Canvas.tsx `persist`): the store- * setters are pure state, and nothing else pushes them to `.nodeterm/project.json`.+ * Persists an identity/defaults edit. The store setters (`renameProject`, `setProjectColor`,+ * `setProjectDefault*`) are pure state — nothing else pushes them to `.nodeterm/project.json`.*- * Canvas's `persist` first commits its live React Flow nodes into the store; this cannot (React- * Flow is Canvas-owned) and must not need to — the canvas is not being edited while the Settings- * page is up, and its own 800ms autosave has already committed anything that was. What we write is- * the store's current truth for every project, exactly like every other save.+ * `markWorkspaceDirty()` is the seam built for exactly this (state/workspaceDirty.ts; NodeLabels.tsx+ * is the precedent): it rings Canvas's own `markDirty`, so the write inherits the canvas commit,+ * the 800ms debounce, AND the conflict gate — while an external-change bar is up, autosave is+ * suspended on purpose, and calling `workspace.save` directly from here would write straight past+ * it. Debounced is right for these edits too: Canvas debounces node edits the same way.*/-async function persistWorkspace(): Promise<void> {- await window.nodeTerminal.workspace.save(useProjects.getState().toWorkspace())+function persistIdentityEdit(): void {+ markWorkspaceDirty()}function rowsFor(name: string): Record<string, SettingsSearchEntry> {@@ -159,7 +160,7 @@ function EditableProjectSection({return}useProjects.getState().renameProject(project.id, next)- void persistWorkspace()+ persistIdentityEdit()}return (@@ -234,7 +235,7 @@ function EditableProjectSection({)}onClick={() => {useProjects.getState().setProjectColor(project.id, c)- void persistWorkspace()+ persistIdentityEdit()}}/>))}@@ -260,7 +261,7 @@ function EditableProjectSection({project.id,v === '' ? undefined : (v as AgentPermissionMode))- void persistWorkspace()+ persistIdentityEdit()}}><option value="">Use global ({PERMISSION_MODE_LABELS[globalMode]})</option>@@ -287,7 +288,7 @@ function EditableProjectSection({onChange={(e) => {const v = e.target.valueuseProjects.getState().setProjectDefaultAccount(project.id, v === '' ? undefined : v)- void persistWorkspace()+ persistIdentityEdit()}}><option value="">{systemLabel}</option>diff --git a/src/renderer/components/settings/useProjectSettings.ts b/src/renderer/components/settings/useProjectSettings.tsindex 21b38df70..956a175c0 100644--- a/src/renderer/components/settings/useProjectSettings.ts+++ b/src/renderer/components/settings/useProjectSettings.ts@@ -77,24 +77,37 @@ const EMPTY_FAMILIES = (): ResolvedProjectSettings => resolveProjectSettings(undexport function useProjectSettings(projectId: string): ProjectSettingsHook {const [snapshot, setSnapshot] = useState<ProjectSettingsSnapshot | null | 'loading'>('loading')const [nonce, setNonce] = useState(0)+ /** Counts successful writes, so a read can tell whether it started before or after the last one. */+ const writeSeqRef = useRef(0)- // The merge base for `saveShared` must be the LATEST snapshot, without making the saver identity+ // The merge base for `saveShared` must be the LATEST document, without making the saver identity// change on every read (a blur handler holding last render's saver would then merge into a stale// document and silently revert a sibling field).const snapshotRef = useRef<ProjectSettingsSnapshot | null | 'loading'>(snapshot)snapshotRef.current = snapshot+ // The document we last WROTE, which outranks the snapshot until the re-read replaces it. Without+ // it, two blurs in a row (shell, then theme) both merge into the pre-first-save document — and+ // because every write is a WHOLE-document write, the second one silently drops the first. The+ // re-read is asynchronous; the user's next blur is not going to wait for it. Tagged with the+ // project id so a pane switch can never merge one project's edit into another's file.+ const pendingRef = useRef<{ projectId: string; doc: ProjectSettingsDoc } | null>(null)+useEffect(() => {let alive = truesetSnapshot('loading')- void window.nodeTerminal.projectSettings.read(projectId).then(- (s) => {- if (alive) setSnapshot(s)- },- () => {- if (alive) setSnapshot(null)- }- )+ // A read only supersedes the pending doc if no write happened while it was in flight;+ // otherwise what we just wrote is still the newer truth. Belt-and-braces: the effect's own+ // cancellation below already drops a read issued before the write in every path the test+ // harness can produce — this closes the remaining window, where the write's `reload()`+ // re-render has not been processed yet when the older read answers.+ const seqAtStart = writeSeqRef.current+ const settle = (next: ProjectSettingsSnapshot | null): void => {+ if (!alive) return+ if (writeSeqRef.current === seqAtStart) pendingRef.current = null+ setSnapshot(next)+ }+ void window.nodeTerminal.projectSettings.read(projectId).then(settle, () => settle(null))return () => {alive = false}@@ -104,14 +117,22 @@ export function useProjectSettings(projectId: string): ProjectSettingsHook {const saveShared = useCallback(async (doc: ProjectSettingsDoc): Promise<boolean> => {+ const pending = pendingRef.currentconst snap = snapshotRef.current- const current = snap && snap !== 'loading' ? docOf(snap.shared) : {}- const ok = await window.nodeTerminal.projectSettings.writeShared(- projectId,- mergeSharedDoc(current, doc)- )- if (ok) reload()- return ok+ const current =+ pending?.projectId === projectId+ ? pending.doc+ : snap && snap !== 'loading'+ ? docOf(snap.shared)+ : {}+ const next = mergeSharedDoc(current, doc)+ const ok = await window.nodeTerminal.projectSettings.writeShared(projectId, next)+ if (!ok) return false+ // Advance the merge base NOW, not when the re-read lands: the next blur may arrive first.+ writeSeqRef.current += 1+ pendingRef.current = { projectId, doc: next }+ reload()+ return true},[projectId, reload])