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): panel final-review wave — vanish fallback, save-failure surfacing, hook guards
enesc0be67fbbd5e
diff --git a/src/renderer/components/settings/ProjectSettingsFamilies.tsx b/src/renderer/components/settings/ProjectSettingsFamilies.tsxindex 6ed9cb24b..8f46458ff 100644--- a/src/renderer/components/settings/ProjectSettingsFamilies.tsx+++ b/src/renderer/components/settings/ProjectSettingsFamilies.tsx@@ -125,9 +125,12 @@ const FAMILIES = Object.keys(FAMILY_CONFIG) as ProjectSettingsFamily[]*/function fieldEntry(family: ProjectSettingsFamily, f: FieldConfig): SettingsSearchEntry {return {+ // Deliberately NOT keyworded 'project': it discriminates nothing (every entry here is a project+ // setting) while making the query "project" match every field of every project — which mounts+ // every project's pane at once, and with it an SSH settings read per project.title: f.label,description: f.description,- keywords: [family, FAMILY_CONFIG[family].title, f.key, 'project', 'this machine', 'override']+ keywords: [family, FAMILY_CONFIG[family].title, f.key, 'this machine', 'override']}}@@ -176,6 +179,7 @@ function textareaClass(disabled?: boolean): string {function StringField({id,label,+ ariaLabel,description,note,multiline,@@ -185,6 +189,10 @@ function StringField({}: {id: stringlabel: string+ /** Accessible name, when it must differ from the visible label — a LOCAL row carries+ * "(this machine)" so it does not present the same name as its shared twin (SwitchField's+ * `ariaLabel` does the same). Omitted on a shared row, which is named by its `<label>`. */+ ariaLabel?: stringdescription?: stringnote?: stringmultiline: boolean@@ -207,6 +215,7 @@ function StringField({<textareaid={id}value={draft}+ aria-label={ariaLabel}disabled={disabled}onChange={(e) => setDraft(e.target.value)}onBlur={commit}@@ -217,6 +226,7 @@ function StringField({id={id}className="w-72"value={draft}+ aria-label={ariaLabel}disabled={disabled}onChange={(e) => setDraft(e.target.value)}onBlur={commit}@@ -234,6 +244,7 @@ function StringField({function EnvField({id,label,+ ariaLabel,description,disabled,text,@@ -242,6 +253,8 @@ function EnvField({}: {id: stringlabel: string+ /** See `StringField`'s `ariaLabel`: the local row's name carries "(this machine)". */+ ariaLabel?: stringdescription?: stringdisabled?: booleantext: string@@ -266,6 +279,7 @@ function EnvField({<textareaid={id}value={draft}+ aria-label={ariaLabel}disabled={disabled}onChange={(e) => setDraft(e.target.value)}onBlur={commit}@@ -340,6 +354,14 @@ function nextLocalIgnoreShared(return Object.keys(out).length === 0 ? undefined : (out as ProjectLocalSettings)}+/** What a refused write says. Shared and local fail for different reasons and are recoverable in+ * different ways, so they do not share one vague sentence. */+const SAVE_FAILED_NOTE: Record<'shared' | 'local', string> = {+ shared:+ 'Could not save — the shared settings file may be conflicted or unavailable; reload the project settings.',+ local: 'Could not save this override on this machine; reload the project settings.'+}+function FamilySection({projectId,family,@@ -349,8 +371,10 @@ function FamilySection({resolvedFamily,conflict,ready,+ sharedEditable,saveShared,- saveLocal+ saveLocal,+ reload}: {projectId: stringfamily: ProjectSettingsFamily@@ -365,14 +389,25 @@ function FamilySection({* network round-trip, not a render tick — a blur landing in it would write a doc built from* `{}`/`undefined`, silently deleting every other family already on disk. */ready: boolean+ /** False when this project has no file to share (see `ProjectFamilyEditors`). */+ sharedEditable: booleansaveShared: (doc: ProjectSettingsDoc) => Promise<boolean>saveLocal: (- update: ProjectLocalSettings | undefined | ((current: ProjectLocalSettings | undefined) => ProjectLocalSettings | undefined)+ update: (current: ProjectLocalSettings | undefined) => ProjectLocalSettings | undefined) => Promise<boolean>+ /** Re-reads the project's settings. Rung after a REFUSED shared write: a refusal is usually the+ * file's answer, not ours (it went conflicted, or the folder went away, between our read and our+ * write), and only a fresh read can make the pane describe the file as it now is. */+ reload: () => void}): React.JSX.Element | null {const config = FAMILY_CONFIG[family]- const sharedDisabled = conflict || !ready+ const sharedDisabled = conflict || !ready || !sharedEditableconst localDisabled = !ready+ // Which half last refused a write, or null. Set from the saver's own answer — before this, a+ // `false` was dropped on the floor and the row simply snapped back to its old value, which reads+ // as "the app ignored me". Cleared by the next save of the same half that succeeds; NOT cleared+ // by the reload a failure triggers (that would erase the message we just put up).+ const [saveFailed, setSaveFailed] = useState<'shared' | 'local' | null>(null)// Row-level search filtering. Done here rather than with `SearchableRow` wrappers because every// field renders TWICE (shared + "this machine") from the same list — filtering the list keeps// the two copies in step by construction. An entirely unmatched family drops out, heading and@@ -386,17 +421,34 @@ function FamilySection({// user interaction, but nothing stops a caller (or a test) from dispatching events on it// directly, and the merge-base hazard this guards against is a data-corruption risk, not a UX// nicety — it must hold even if the DOM attribute is bypassed.+ // Every commit path routes its saver's answer through here: a dropped `false` is a silent data+ // loss — the row reverts to the stored value with no explanation, which is indistinguishable+ // from the app ignoring the edit.+ const settle = (half: 'shared' | 'local', ok: boolean): void => {+ if (ok) {+ setSaveFailed((prev) => (prev === half ? null : prev))+ return+ }+ setSaveFailed(half)+ if (half === 'shared') reload()+ }const commitShared = (key: string, value: unknown): void => {if (sharedDisabled) return- void saveShared({ [family]: { [key]: value } } as ProjectSettingsDoc)+ void saveShared({ [family]: { [key]: value } } as ProjectSettingsDoc).then((ok) =>+ settle('shared', ok)+ )}const commitLocal = (key: string, value: unknown): void => {if (localDisabled) return- void saveLocal((current) => nextLocalField(current, family, key, value))+ void saveLocal((current) => nextLocalField(current, family, key, value)).then((ok) =>+ settle('local', ok)+ )}const commitIgnoreShared = (on: boolean): void => {if (localDisabled) return- void saveLocal((current) => nextLocalIgnoreShared(current, family, on))+ void saveLocal((current) => nextLocalIgnoreShared(current, family, on)).then((ok) =>+ settle('local', ok)+ )}const renderShared = (f: FieldConfig): React.JSX.Element => {@@ -471,6 +523,7 @@ function FamilySection({id={id}label={f.label}description={f.description}+ ariaLabel={`${f.label} (this machine)`}disabled={localDisabled}text={formatEnvLines(localFamily?.[f.key] as Record<string, string> | undefined)}overrideNote={activeNote}@@ -483,6 +536,7 @@ function FamilySection({key={f.key}id={id}label={f.label}+ ariaLabel={`${f.label} (this machine)`}description={f.description}multiline={f.kind === 'textarea' || f.kind === 'list'}note={activeNote}@@ -496,6 +550,11 @@ function FamilySection({return (<div className="space-y-3 border-t border-border pt-4"><h3 className="text-[13px] font-semibold text-text">{config.title}</h3>+ {saveFailed ? (+ <p role="status" className="text-[12px] leading-relaxed text-[color:var(--warn)]">+ {SAVE_FAILED_NOTE[saveFailed]}+ </p>+ ) : null}<div className="space-y-2.5">{fields.map(renderShared)}</div><details><summary className="cursor-pointer text-[13px] text-muted">This machine</summary>@@ -525,17 +584,30 @@ export function ProjectFamilyEditors({snapshot,resolved,conflict,+ sharedEditable,saveShared,- saveLocal+ saveLocal,+ reload}: {projectId: stringsnapshot: ProjectSettingsSnapshot | null | 'loading'resolved: ResolvedProjectSettingsconflict: boolean+ /**+ * False for a project with no folder at all — an inline canvas tab (no `cwd`, no `ssh`). There is+ * nowhere to put a `.nodeterm/settings.json`, so the store refuses every shared write+ * (`writeProjectSettings` returns false on `!e.cwd`); rendering live editors there offers a save+ * that can only ever fail. The shared rows go read-only with a sentence saying why.+ *+ * The "This machine" rows stay live: the local overlay lives in this machine's workspace index,+ * not in the project folder, so `updateLocal` genuinely succeeds for a folderless project.+ */+ sharedEditable: booleansaveShared: (doc: ProjectSettingsDoc) => Promise<boolean>saveLocal: (- update: ProjectLocalSettings | undefined | ((current: ProjectLocalSettings | undefined) => ProjectLocalSettings | undefined)+ update: (current: ProjectLocalSettings | undefined) => ProjectLocalSettings | undefined) => Promise<boolean>+ reload: () => void}): React.JSX.Element {// Loading and failed-read (`null`) both mean "no doc it is safe to merge an edit into" — see// `FamilySection`'s `ready` doc comment.@@ -544,6 +616,13 @@ export function ProjectFamilyEditors({const local: ProjectLocalSettings | undefined = snapshot && snapshot !== 'loading' ? snapshot.local : undefinedreturn (<>+ {!sharedEditable ? (+ <p className="border-t border-border pt-4 text-[13px] leading-relaxed text-muted">+ This project has no folder, so there is no shared <code>.nodeterm/settings.json</code> to+ write: the shared rows below are read-only. Overrides under “This machine”+ still apply.+ </p>+ ) : null}{FAMILIES.map((family) => (<FamilySectionkey={family}@@ -555,8 +634,10 @@ export function ProjectFamilyEditors({resolvedFamily={resolved[family] as Record<string, { source: 'local' | 'shared' } | undefined>}conflict={conflict}ready={ready}+ sharedEditable={sharedEditable}saveShared={saveShared}saveLocal={saveLocal}+ reload={reload}/>))}</>diff --git a/src/renderer/components/settings/SettingsPage.tsx b/src/renderer/components/settings/SettingsPage.tsxindex aef8ea6df..dcebdaf42 100644--- a/src/renderer/components/settings/SettingsPage.tsx+++ b/src/renderer/components/settings/SettingsPage.tsx@@ -49,14 +49,23 @@ export function SettingsPage({retargetNonce?: number}): React.JSX.Element {const hydrate = useEntitlement((s) => s.hydrate)- // Which section is shown and what is typed in the search box, plus the deep-link retarget rule.- const { active, setActive, query, setQuery } = useSettingsTarget(initialSection, retargetNonce)// ONE list feeds both the nav rows and the panes below, so a "Projects" row can never point at a// section that is not rendered (or vice versa). Memoized: `projects.filter(...)` inside a zustand// selector would return a fresh array on every store snapshot and re-render the whole page.const projects = useProjects((s) => s.projects)const openProjects = useMemo(() => projects.filter((p) => !p.closed), [projects])+ // Same list, ids only, with a stable identity — it is an effect dependency in useSettingsTarget.+ const openProjectIds = useMemo(() => openProjects.map((p) => p.id), [openProjects])++ // Which section is shown and what is typed in the search box, plus the deep-link retarget rule+ // and the fallback for a project section whose project has since been closed.+ const { active, setActive, query, setQuery } = useSettingsTarget(+ initialSection,+ retargetNonce,+ openProjectIds+ )+const extraGroups = useMemo(() => {const group = projectsSettingsGroup(openProjects.map((p) => ({ id: p.id, name: p.name, color: p.color }))diff --git a/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx b/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsxindex 53be4518a..210e3ec61 100644--- a/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx+++ b/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx@@ -1,14 +1,15 @@// @vitest-environment jsdomimport { act } from 'react'import { createRoot, type Root } from 'react-dom/client'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'import type { Project } from '@shared/types'import type { ProjectSettingsSnapshot } from '@shared/project-settings'import { useProjects } from '../../../state/projects'+import { useSettings } from '../../../state/settings'import { registerWorkspaceDirty } from '../../../state/workspaceDirty'import { SettingsSearchContext } from '../context'import { ProjectSettingsSection } from './ProjectSettingsSection'-import { useProjectSettings, type ProjectSettingsHook } from '../useProjectSettings'+import { mergeSharedDoc, useProjectSettings, type ProjectSettingsHook } from '../useProjectSettings';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true@@ -321,6 +322,101 @@ describe('ProjectSettingsSection', () => {expect(writeShared).toHaveBeenCalledWith('p1', { agents: { env: { A: '1', B: '2' } } })})+ it('surfaces a REFUSED shared write as a warn note, re-reads the file, and clears the note on the next save that lands', async () => {+ // A dropped `false` is silent data loss: the row snaps back to the stored value with no+ // explanation, which is indistinguishable from the app ignoring the edit.+ writeShared.mockResolvedValue(false)+ await mountSection()+ expect(read).toHaveBeenCalledTimes(1)+ const shell = host.querySelector<HTMLInputElement>('#project-terminal-shell-p1')!+ await typeInto(shell, '/bin/fish')+ await blur(shell)+ expect(writeShared).toHaveBeenCalledTimes(1)+ expect(host.textContent).toContain('Could not save')+ // A refusal is usually the FILE's answer (it went conflicted, or the folder went away, between+ // our read and our write), so the pane re-reads instead of describing a file it no longer knows.+ expect(read).toHaveBeenCalledTimes(2)+ writeShared.mockResolvedValue(true)+ await blur(shell)+ expect(writeShared).toHaveBeenCalledTimes(2)+ expect(host.textContent).not.toContain('Could not save')+ })++ it('surfaces a refused LOCAL write too, without re-reading (nothing about the shared file changed)', async () => {+ updateLocal.mockResolvedValue(false)+ await mountSection()+ const local = host.querySelector<HTMLInputElement>('#project-terminal-shell-local-p1')!+ await typeInto(local, '/bin/zsh')+ await blur(local)+ expect(host.textContent).toContain('Could not save this override on this machine')+ expect(read).toHaveBeenCalledTimes(1)+ })++ it('renders the shared family rows read-only for a folderless inline project, with the reason', async () => {+ // An inline canvas tab has no `cwd` and no `ssh`, so there is nowhere to put a+ // `.nodeterm/settings.json`: the store refuses every shared write for it. Editors that can only+ // ever fail must not be offered.+ await mountSection(project({ cwd: '' }))+ expect(host.textContent).toContain('no folder')+ const familyControls = [+ ...host.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>('input, textarea')+ ].filter((el) => /^project-(setup|agents|worktree|terminal)-/.test(el.id))+ const sharedRows = familyControls.filter((el) => !el.id.includes('-local-'))+ expect(sharedRows.length).toBeGreaterThan(0)+ expect(sharedRows.every((el) => el.disabled)).toBe(true)+ // Bypassing the attribute (a synthetic event) must not write either.+ const shell = host.querySelector<HTMLInputElement>('#project-terminal-shell-p1')!+ await typeInto(shell, '/bin/fish')+ await blur(shell)+ expect(writeShared).not.toHaveBeenCalled()+ // The identity rows still work: name/color/defaults live in project.json, not in the folder.+ expect(nameInput().disabled).toBe(false)+ await typeInto(nameInput(), 'Beta')+ await blur(nameInput())+ expect(useProjects.getState().getProject('p1')?.name).toBe('Beta')+ // And so does the machine-local overlay, which lives in this machine's workspace index.+ const local = host.querySelector<HTMLInputElement>('#project-terminal-shell-local-p1')!+ expect(local.disabled).toBe(false)+ await typeInto(local, '/bin/zsh')+ await blur(local)+ expect(updateLocal).toHaveBeenCalledWith('p1', { terminal: { shell: '/bin/zsh' } })+ })++ it('gives every local row an accessible name of its own, so it never duplicates its shared twin', async () => {+ await mountSection()+ expect(+ host.querySelector<HTMLInputElement>('#project-terminal-shell-local-p1')!.getAttribute('aria-label')+ ).toBe('Shell (this machine)')+ expect(+ host.querySelector<HTMLTextAreaElement>('#project-agents-env-local-p1')!.getAttribute('aria-label')+ ).toBe('Environment variables (this machine)')+ // The shared twin keeps its `<label>` as its name — the two must not read alike.+ expect(+ host.querySelector<HTMLInputElement>('#project-terminal-shell-p1')!.getAttribute('aria-label')+ ).toBeNull()+ })++ it('shows an unknown default account as itself and switches to one this machine has', async () => {+ const prior = useSettings.getState().settings+ onTestFinished(() => useSettings.setState({ settings: prior }))+ useSettings.setState({+ settings: { ...prior, claudeAccounts: [{ id: 'acc-1', label: 'Work', createdAt: 0 }] }+ })+ await mountSection(project({ defaultAccountId: 'acc-gone' }))+ const select = host.querySelector<HTMLSelectElement>('#project-account-p1')!+ // A default naming an account this machine does not have (a teammate's pick, or one since+ // removed) must READ as itself, not silently as the system account.+ expect(host.textContent).toContain('acc-gone (not on this machine)')+ expect(select.value).toBe('acc-gone')+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!+ setter.call(select, 'acc-1')+ select.dispatchEvent(new Event('change', { bubbles: true }))+ })+ expect(useProjects.getState().getProject('p1')?.defaultAccountId).toBe('acc-1')+ expect(dirty).toHaveBeenCalledTimes(1)+ })+// --- Task 5: search integration ------------------------------------------------------------const pane = (): HTMLElement | null => host.querySelector('[data-settings-section="project-p1"]')@@ -353,6 +449,20 @@ describe('ProjectSettingsSection', () => {expect(host.querySelector('#project-name-p1')).toBeNull()})+ it('does not match every family field on the non-discriminating query "project"', async () => {+ // Every field in this pane is a project setting, so "project" told the search nothing while+ // pulling in all four families of every open project. The identity rows still match — the+ // "Project name" row is titled with the word.+ // (A field whose own description genuinely says "project" — the setup scripts, the default+ // agent — still matches, and should: that is prose about the field, not a blanket keyword.)+ await mountSection(project(), { isActive: false, query: 'project' })+ expect(host.querySelector('#project-name-p1')).not.toBeNull()+ expect(host.querySelector('#project-terminal-shell-p1')).toBeNull()+ expect(host.querySelector('#project-terminal-fontFamily-p1')).toBeNull()+ expect(host.querySelector('#project-agents-launchCmd-p1')).toBeNull()+ expect(host.querySelector('#project-worktree-basePath-local-p1')).toBeNull()+ })+it('renders nothing (and reads nothing) for a query matching neither the name nor any row', async () => {await mountSection(project(), { isActive: false, query: 'zzzznomatch' })expect(host.textContent).toBe('')@@ -515,7 +625,7 @@ describe('useProjectSettings', () => {it('passes the local overlay through whole and re-reads', async () => {await mount()await act(async () => {- await hook.saveLocal({ terminal: { shell: '/bin/zsh' }, ignoreShared: { agents: true } })+ await hook.saveLocal(() => ({ terminal: { shell: '/bin/zsh' }, ignoreShared: { agents: true } }))})expect(updateLocal).toHaveBeenCalledWith('p1', {terminal: { shell: '/bin/zsh' },@@ -568,4 +678,65 @@ describe('useProjectSettings', () => {})expect(read).toHaveBeenCalledTimes(2)})++ it('refuses BOTH savers while the first read is still in flight, without writing anything', async () => {+ // Defence in depth below the editors' own `ready` gate. Every write here is a WHOLE-document+ // write; with nothing read and nothing pending, the merge base would be `{}`/`undefined`, so+ // committing would delete whatever the files already hold.+ let release: (v: ProjectSettingsSnapshot) => void = () => {}+ read.mockReturnValue(new Promise<ProjectSettingsSnapshot>((r) => (release = r)))+ root = createRoot(host)+ act(() => {+ root.render(<Probe projectId="p1" />)+ })+ expect(hook.snapshot).toBe('loading')+ let ok = true+ let okLocal = true+ await act(async () => {+ ok = await hook.saveShared({ terminal: { shell: '/bin/fish' } })+ okLocal = await hook.saveLocal(() => ({ terminal: { shell: '/bin/zsh' } }))+ })+ expect(ok).toBe(false)+ expect(okLocal).toBe(false)+ expect(writeShared).not.toHaveBeenCalled()+ expect(updateLocal).not.toHaveBeenCalled()+ await act(async () => {+ release(EMPTY_SNAPSHOT)+ })+ })++ it('refuses BOTH savers after a FAILED read, which is equally "no document to merge into"', async () => {+ read.mockRejectedValue(new Error('boom'))+ await mount()+ expect(hook.snapshot).toBeNull()+ let ok = true+ let okLocal = true+ await act(async () => {+ ok = await hook.saveShared({ terminal: { shell: '/bin/fish' } })+ okLocal = await hook.saveLocal(() => ({ terminal: { shell: '/bin/zsh' } }))+ })+ expect(ok).toBe(false)+ expect(okLocal).toBe(false)+ expect(writeShared).not.toHaveBeenCalled()+ expect(updateLocal).not.toHaveBeenCalled()+ })+})++describe('mergeSharedDoc', () => {+ it('merges field-by-field so an editor never blanks a field it does not own', () => {+ expect(+ mergeSharedDoc({ terminal: { shell: '/bin/bash', theme: 'dark' } }, { terminal: { theme: 'light' } })+ ).toEqual({ terminal: { shell: '/bin/bash', theme: 'light' } })+ })++ it('clears a WHOLE family set to undefined, and drops a family its last cleared field empties', () => {+ // The advertised family-level clear: `{ terminal: undefined }` removes the family outright,+ // while clearing its last field removes it as a side effect — an unset setting adds no bytes+ // to a file the whole team reads.+ const current = { terminal: { shell: '/bin/bash' }, setup: { waitForSetup: true } }+ expect(mergeSharedDoc(current, { terminal: undefined })).toEqual({ setup: { waitForSetup: true } })+ expect(mergeSharedDoc(current, { terminal: { shell: undefined } })).toEqual({+ setup: { waitForSetup: true }+ })+ })})diff --git a/src/renderer/components/settings/sections/ProjectSettingsSection.tsx b/src/renderer/components/settings/sections/ProjectSettingsSection.tsxindex 50a140ab1..c5f924eb9 100644--- a/src/renderer/components/settings/sections/ProjectSettingsSection.tsx+++ b/src/renderer/components/settings/sections/ProjectSettingsSection.tsx@@ -339,8 +339,12 @@ function EditableProjectSection({snapshot={snapshot}resolved={settings.resolved}conflict={conflict}+ // Only the shell knows WHERE this project lives; a folderless inline canvas tab has no+ // shared settings file and never can have one — see `sharedEditable`.+ sharedEditable={Boolean(project.cwd || project.ssh)}saveShared={settings.saveShared}saveLocal={settings.saveLocal}+ reload={settings.reload}/></SettingsSection>)diff --git a/src/renderer/components/settings/useProjectSettings.ts b/src/renderer/components/settings/useProjectSettings.tsindex d897e0077..1f423fce1 100644--- a/src/renderer/components/settings/useProjectSettings.ts+++ b/src/renderer/components/settings/useProjectSettings.ts@@ -34,18 +34,16 @@ export interface ProjectSettingsHook {saveShared(doc: ProjectSettingsDoc): Promise<boolean>/*** Commits an edit to THIS MACHINE's local overlay — a whole-document write, exactly like- * `saveShared`. Takes either the next whole document directly, or an updater over the CURRENT- * one (preferring a still-in-flight write's result over the last-read snapshot, via the same- * `pendingLocalRef` guard `saveShared` uses for the shared doc) — so two local edits inside one- * IPC round-trip do not drop the first. Prefer the updater form for anything that merges into- * the existing doc; the plain-value form stays for a caller that already holds the whole next- * document (e.g. clearing the overlay with `undefined`). Re-reads on success.+ * `saveShared`. Takes an UPDATER over the current document (preferring a still-in-flight write's+ * result over the last-read snapshot, via the same `pendingLocalRef` guard `saveShared` uses for+ * the shared doc), so two local edits inside one IPC round-trip do not drop the first. The+ * updater form is the ONLY form: a plain next-document argument cannot see the pending base, so+ * it would silently revert an edit whose re-read has not landed yet — the exact hazard+ * `pendingLocalRef` exists to close. Clearing the whole overlay is `saveLocal(() => undefined)`.+ * Re-reads on success.*/saveLocal(- update:- | ProjectLocalSettings- | undefined- | ((current: ProjectLocalSettings | undefined) => ProjectLocalSettings | undefined)+ update: (current: ProjectLocalSettings | undefined) => ProjectLocalSettings | undefined): Promise<boolean>reload(): void}@@ -60,8 +58,9 @@ function docOf(shared: ProjectSettingsFileV1 | null | undefined): ProjectSetting/*** Field-level merge of `patch` into `current`, dropping `undefined` (a cleared field) and any- * family the clearing leaves empty. Exported for the tests that pin the "an editor never blanks a- * field it does not own" rule.+ * family the clearing leaves empty. A whole family set to `undefined` is dropped outright.+ * Exported for the tests that pin the "an editor never blanks a field it does not own" rule (see+ * `mergeSharedDoc` in ProjectSettingsSection.test.tsx).*/export function mergeSharedDoc(current: ProjectSettingsDoc,@@ -138,14 +137,14 @@ export function useProjectSettings(projectId: string): ProjectSettingsHook {const saveShared = useCallback(async (doc: ProjectSettingsDoc): Promise<boolean> => {- const pending = pendingRef.current+ const pending = pendingRef.current?.projectId === projectId ? pendingRef.current : nullconst snap = snapshotRef.current- const current =- pending?.projectId === projectId- ? pending.doc- : snap && snap !== 'loading'- ? docOf(snap.shared)- : {}+ // Defence in depth under the editors' own `ready` gate: with no snapshot object AND no+ // pending write to merge into, the merge base would be `{}` — and every write here is a+ // WHOLE-document write, so committing it would delete whatever the file already holds. There+ // is nothing to merge into yet, so there is nothing safe to write: refuse.+ if (!pending && (snap === 'loading' || snap === null)) return false+ const current = pending ? pending.doc : docOf((snap as ProjectSettingsSnapshot).shared)const next = mergeSharedDoc(current, doc)const ok = await window.nodeTerminal.projectSettings.writeShared(projectId, next)if (!ok) return false@@ -160,16 +159,17 @@ export function useProjectSettings(projectId: string): ProjectSettingsHook {const saveLocal = useCallback(async (- update:- | ProjectLocalSettings- | undefined- | ((current: ProjectLocalSettings | undefined) => ProjectLocalSettings | undefined)+ update: (current: ProjectLocalSettings | undefined) => ProjectLocalSettings | undefined): Promise<boolean> => {- const pending = pendingLocalRef.current+ const pending =+ pendingLocalRef.current?.projectId === projectId ? pendingLocalRef.current : nullconst snap = snapshotRef.current- const current =- pending?.projectId === projectId ? pending.local : snap && snap !== 'loading' ? snap.local : undefined- const next = typeof update === 'function' ? update(current) : update+ // Same refusal as `saveShared`, same reason: the local overlay is a whole-document write too,+ // so an updater handed `undefined` because nothing has been READ yet (rather than because the+ // overlay is genuinely empty) would erase this machine's overrides for every other family.+ if (!pending && (snap === 'loading' || snap === null)) return false+ const current = pending ? pending.local : (snap as ProjectSettingsSnapshot).local+ const next = update(current)const ok = await window.nodeTerminal.projectSettings.updateLocal(projectId, next)if (!ok) return false// Advance the merge base NOW, not when the re-read lands: the next blur may arrive first.diff --git a/src/renderer/components/settings/useSettingsTarget.test.tsx b/src/renderer/components/settings/useSettingsTarget.test.tsxindex 32de39259..797ce764f 100644--- a/src/renderer/components/settings/useSettingsTarget.test.tsx+++ b/src/renderer/components/settings/useSettingsTarget.test.tsx@@ -89,3 +89,76 @@ describe('useSettingsTarget', () => {expect(target.query).toBe('shell')})})++/**+ * `active` outlives the dialog: Canvas keeps `settingsSection` across opens. So a project pane it+ * points at can disappear (project closed) while the selection stays — and the panel then opens on+ * a section nobody renders: no nav row, blank main area.+ */+describe('useSettingsTarget project fallback', () => {+ let root: Root+ let host: HTMLElement+ let target: SettingsTarget++ function Probe({+ initialSection,+ retargetNonce,+ openProjectIds+ }: {+ initialSection?: SettingsSectionId+ retargetNonce?: number+ openProjectIds?: string[]+ }): React.JSX.Element {+ target = useSettingsTarget(initialSection, retargetNonce, openProjectIds)+ return <div>{target.active}</div>+ }++ const render = async (props: {+ initialSection?: SettingsSectionId+ retargetNonce?: number+ openProjectIds?: string[]+ }): Promise<void> => {+ await act(async () => {+ root.render(<Probe {...props} />)+ })+ }++ beforeEach(() => {+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+ })++ afterEach(() => {+ act(() => root.unmount())+ host.remove()+ })++ it('falls back to the first section when the active project closes', async () => {+ await render({ initialSection: 'project-p1' as SettingsSectionId, retargetNonce: 1, openProjectIds: ['p1', 'p2'] })+ expect(target.active).toBe('project-p1')+ // p1 closed while the dialog was shut; the selection is still pointing at its pane.+ await render({ openProjectIds: ['p2'] })+ expect(target.active).toBe(FIRST_SECTION_ID)+ })++ it('refuses a deep link to a project that has no pane', async () => {+ await render({ initialSection: 'project-gone' as SettingsSectionId, retargetNonce: 1, openProjectIds: ['p1'] })+ expect(target.active).toBe(FIRST_SECTION_ID)+ })++ it('leaves a live project section, and every non-project section, alone', async () => {+ await render({ initialSection: 'project-p1' as SettingsSectionId, retargetNonce: 1, openProjectIds: ['p1'] })+ expect(target.active).toBe('project-p1')+ await act(async () => target.setActive('ssh'))+ await render({ openProjectIds: [] })+ expect(target.active).toBe('ssh')+ })++ it('never falls back when the caller passes no project list at all', async () => {+ // `undefined` is "I have no list", not "no projects are open": a caller whose projects have not+ // loaded yet must not bulldoze a legitimate deep link.+ await render({ initialSection: 'project-p1' as SettingsSectionId, retargetNonce: 1 })+ expect(target.active).toBe('project-p1')+ })+})diff --git a/src/renderer/components/settings/useSettingsTarget.ts b/src/renderer/components/settings/useSettingsTarget.tsindex 552a2ee42..19c847e07 100644--- a/src/renderer/components/settings/useSettingsTarget.ts+++ b/src/renderer/components/settings/useSettingsTarget.ts@@ -1,5 +1,6 @@import { useEffect, useState } from 'react'import { FIRST_SECTION_ID, type SettingsSectionId } from './nav'+import { parseProjectSectionId } from './project-settings-targets'export interface SettingsTarget {/** Section whose pane is shown when the search box is empty. */@@ -26,10 +27,23 @@ export interface SettingsTarget {* not change, so the effect would not re-run.* - Plain opens (the gear, ⌘, , the native menu) pass no section and never bump the nonce, so a* query or a section the user chose inside the dialog survives.+ * - A project section that no longer exists falls back to the first section — see `openProjectIds`.*/export function useSettingsTarget(initialSection: SettingsSectionId | undefined,- retargetNonce: number | undefined+ retargetNonce: number | undefined,+ /**+ * Ids of the projects that currently HAVE a pane (SettingsPage's open-project list). `active`+ * outlives the dialog — Canvas keeps it across opens — so a deep link to project X followed by+ * closing X would otherwise leave the panel pointing at a section nobody renders: the nav row is+ * gone and the main area is blank, with no way back but a click. Given the list, an `active` that+ * names a project not in it falls back to the first section.+ *+ * Omitted (`undefined`) means "the caller has no list", not "no projects are open": the fallback+ * is then skipped entirely, so a caller that has not loaded its projects yet cannot bulldoze a+ * legitimate deep link. SettingsPage always passes the list.+ */+ openProjectIds?: string[]): SettingsTarget {const [active, setActive] = useState<SettingsSectionId>(initialSection ?? FIRST_SECTION_ID)const [query, setQuery] = useState('')@@ -40,5 +54,13 @@ export function useSettingsTarget(setQuery('')}, [initialSection, retargetNonce])+ useEffect(() => {+ if (!openProjectIds) return+ const projectId = parseProjectSectionId(active)+ if (projectId === null) return+ if (openProjectIds.includes(projectId)) return+ setActive(FIRST_SECTION_ID)+ }, [active, openProjectIds])+return { active, setActive, query, setQuery }}